From cb19660fbe5f527331d0558ae0f2c116c100018f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:24:51 +0200 Subject: [PATCH] Build Horizon Rust parity foundations and differential validation Add version-bound core, world data, geometry, generation and feature implementations with native client/server comparison tools and scoped evidence reports. Apply Horizon project branding. Workspace tests, Clippy and 147 Python tests passed. Full 51-family survival and expanded provider comparisons are still running; complete gameplay parity and a playable Rust client remain unfinished. Private game artifacts and the isolated simple-block placement work are excluded. --- .github/workflows/ci.yml | 249 +++- .gitignore | 2 +- Cargo.lock | 169 +++ Cargo.toml | 2 +- README.md | 67 +- .../rust-anchor-2026-10-06/scoped-parity.json | 118 ++ .../scoped-parity.json | 153 +++ .../scoped-parity.json | 131 ++ .../scoped-parity.json | 149 ++ .../scoped-parity.json | 158 +++ .../scoped-parity.json | 136 ++ .../scoped-parity.json | 148 ++ .../scoped-parity.json | 126 ++ .../scoped-parity.json | 131 ++ .../scoped-parity.json | 176 +++ .../scoped-parity.json | 127 ++ .../scoped-parity.json | 172 +++ .../scoped-parity.json | 192 +++ .../scoped-parity.json | 169 +++ .../scoped-parity.json | 146 ++ .../scoped-parity.json | 141 ++ .../scoped-parity.json | 134 ++ .../scoped-parity.json | 146 ++ .../scoped-parity.json | 161 +++ .../scoped-parity.json | 75 + .../rust-core-2026-10-04/scoped-parity.json | 44 + .../rust-core-2026-10-05/scoped-parity.json | 69 + .../scoped-parity.json | 161 +++ .../scoped-parity.json | 178 +++ .../scoped-parity.json | 159 +++ .../scoped-parity.json | 182 +++ .../scoped-parity.json | 164 +++ .../scoped-parity.json | 167 +++ .../scoped-parity.json | 181 +++ .../scoped-parity.json | 159 +++ .../scoped-parity.json | 160 +++ .../scoped-parity.json | 169 +++ .../scoped-parity.json | 156 +++ .../scoped-parity.json | 157 +++ .../boundary-parity.json | 373 +++++ .../scoped-parity.json | 87 ++ .../rust-fluid-2026-10-06/scoped-parity.json | 168 +++ .../scoped-parity.json | 73 + .../scoped-parity.json | 110 ++ .../scoped-parity.json | 152 +++ .../scoped-parity.json | 126 ++ .../scoped-parity.json | 145 ++ .../scoped-parity.json | 134 ++ .../scoped-parity.json | 149 ++ .../scoped-parity.json | 180 +++ .../scoped-parity.json | 118 ++ .../rust-noise-2026-10-05/scoped-parity.json | 71 + .../scoped-parity.json | 177 +++ .../scoped-parity.json | 153 +++ .../scoped-parity.json | 161 +++ .../scoped-parity.json | 163 +++ .../scoped-parity.json | 161 +++ .../scoped-parity.json | 213 +++ .../scoped-parity.json | 115 ++ .../scoped-parity.json | 123 ++ .../rust-ticks-2026-10-05/scoped-parity.json | 87 ++ .../scoped-parity.json | 151 ++ .../rust-world-2026-10-05/scoped-parity.json | 77 ++ .../scoped-parity.json | 307 +++++ .../scoped-parity.json | 627 +++++++++ .../scoped-parity.json | 162 +++ crates/horizon-core/Cargo.toml | 31 + .../examples/biome_zoom_fixture.rs | 46 + crates/horizon-core/src/bin/density_parity.rs | 1103 +++++++++++++++ .../horizon-core/src/bin/float_log_parity.rs | 55 + .../horizon-core/src/bin/geometry_parity.rs | 564 ++++++++ crates/horizon-core/src/bin/noise_parity.rs | 423 ++++++ crates/horizon-core/src/bin/parity.rs | 321 +++++ crates/horizon-core/src/bin/tick_parity.rs | 246 ++++ crates/horizon-core/src/biome.rs | 74 + crates/horizon-core/src/biome/seed_hash.rs | 66 + crates/horizon-core/src/carving.rs | 164 +++ crates/horizon-core/src/carving/ellipsoid.rs | 124 ++ crates/horizon-core/src/density/arithmetic.rs | 248 ++++ crates/horizon-core/src/density/beardifier.rs | 214 +++ crates/horizon-core/src/density/cache.rs | 128 ++ .../horizon-core/src/density/end_islands.rs | 79 ++ .../src/density/graph/compiler.rs | 498 +++++++ crates/horizon-core/src/density/graph/mod.rs | 712 ++++++++++ .../horizon-core/src/density/graph/seeded.rs | 97 ++ .../horizon-core/src/density/graph/tests.rs | 552 ++++++++ .../horizon-core/src/density/interpolation.rs | 207 +++ crates/horizon-core/src/density/interval.rs | 412 ++++++ crates/horizon-core/src/density/mod.rs | 391 ++++++ crates/horizon-core/src/density/power.rs | 72 + crates/horizon-core/src/density/rounding.rs | 98 ++ crates/horizon-core/src/density/selection.rs | 228 ++++ crates/horizon-core/src/density/slice.rs | 85 ++ crates/horizon-core/src/density/spline.rs | 344 +++++ crates/horizon-core/src/density/surface.rs | 99 ++ .../horizon-core/src/density/terrain_noise.rs | 220 +++ crates/horizon-core/src/density/tests.rs | 757 ++++++++++ .../horizon-core/src/density/world_fields.rs | 151 ++ crates/horizon-core/src/geometry/mod.rs | 656 +++++++++ crates/horizon-core/src/geometry/movement.rs | 208 +++ crates/horizon-core/src/geometry/shape.rs | 551 ++++++++ .../horizon-core/src/geometry/shape/create.rs | 147 ++ .../horizon-core/src/geometry/shape/face.rs | 123 ++ .../horizon-core/src/geometry/shape/join.rs | 363 +++++ crates/horizon-core/src/geometry/sweep.rs | 224 +++ crates/horizon-core/src/geometry/traversal.rs | 155 +++ crates/horizon-core/src/geometry/trig.rs | 38 + crates/horizon-core/src/lib.rs | 17 + crates/horizon-core/src/noise/mod.rs | 289 ++++ crates/horizon-core/src/noise/normal.rs | 387 ++++++ crates/horizon-core/src/noise/perlin.rs | 273 ++++ crates/horizon-core/src/noise/simplex.rs | 121 ++ crates/horizon-core/src/noise/stack.rs | 233 ++++ crates/horizon-core/src/noise/volume.rs | 94 ++ crates/horizon-core/src/position.rs | 184 +++ crates/horizon-core/src/position/iter.rs | 159 +++ crates/horizon-core/src/random.rs | 263 ++++ crates/horizon-core/src/random/hash.rs | 157 +++ crates/horizon-core/src/random/positional.rs | 79 ++ crates/horizon-core/src/random/worldgen.rs | 190 +++ crates/horizon-core/src/storage.rs | 172 +++ crates/horizon-core/src/ticks/heap.rs | 101 ++ crates/horizon-core/src/ticks/index.rs | 159 +++ crates/horizon-core/src/ticks/mod.rs | 638 +++++++++ crates/horizon-core/tests/carving_bounds.rs | 58 + .../tests/density_world_fields.rs | 202 +++ crates/horizon-world/Cargo.toml | 22 + .../horizon-world/examples/anchor_fixture.rs | 71 + .../examples/basic_feature_fixture.rs | 175 +++ .../examples/biome_chunk_fixture.rs | 62 + .../examples/biome_generation_fixture.rs | 106 ++ .../examples/biome_placement_fixture.rs | 175 +++ .../examples/biome_source_codec_fixture.rs | 79 ++ .../examples/biome_source_fixture.rs | 79 ++ .../examples/biome_temperature_fixture.rs | 119 ++ .../examples/block_properties_fixture.rs | 142 ++ .../examples/block_state_codec_fixture.rs | 70 + .../examples/block_support_fixture.rs | 69 + .../examples/block_survival_fixture.rs | 279 ++++ .../examples/bulk_section_fixture.rs | 209 +++ .../examples/canyon_carver_fixture.rs | 99 ++ .../examples/carving_geometry_fixture.rs | 119 ++ .../examples/carving_mask_fixture.rs | 76 ++ .../examples/cave_carver_fixture.rs | 99 ++ .../examples/chunk_stage_fixture.rs | 212 +++ .../examples/collision_fixture.rs | 199 +++ .../examples/decoration_fixture.rs | 211 +++ .../examples/decoration_region_fixture.rs | 304 +++++ .../examples/dynamic_support_fixture.rs | 252 ++++ .../examples/entity_obstruction_fixture.rs | 115 ++ .../examples/face_support_fixture.rs | 147 ++ .../examples/feature_catalog_fixture.rs | 276 ++++ .../examples/feature_graph_fixture.rs | 180 +++ .../examples/feature_placement_fixture.rs | 91 ++ .../examples/feature_region_fixture.rs | 294 ++++ .../examples/feature_sort_fixture.rs | 50 + .../examples/fill_layer_fixture.rs | 195 +++ .../horizon-world/examples/fluid_fixture.rs | 121 ++ .../examples/height_provider_fixture.rs | 50 + .../examples/heightmap_fixture.rs | 253 ++++ .../examples/material_condition_fixture.rs | 735 ++++++++++ .../examples/material_extension_fixture.rs | 208 +++ .../examples/material_stage_fixture.rs | 838 ++++++++++++ .../examples/material_surface_fixture.rs | 137 ++ .../examples/piston_shape_fixture.rs | 190 +++ .../examples/placement_fixture.rs | 84 ++ .../examples/replace_block_fixture.rs | 204 +++ .../examples/rule_test_fixture.rs | 95 ++ .../examples/scattered_ore_fixture.rs | 228 ++++ .../examples/state_provider_fixture.rs | 540 ++++++++ .../examples/structure_density_fixture.rs | 97 ++ .../examples/support/decoration_storage.rs | 101 ++ .../examples/support/placement_queries.rs | 149 ++ .../horizon-world/examples/terrain_fixture.rs | 303 ++++ crates/horizon-world/examples/tick_fixture.rs | 71 + .../examples/value_provider_fixture.rs | 68 + .../horizon-world/examples/world_fixture.rs | 154 +++ .../examples/worldgen_random_fixture.rs | 134 ++ .../horizon-world/src/bin/worldgen_parity.rs | 915 +++++++++++++ crates/horizon-world/src/block_collision.rs | 112 ++ crates/horizon-world/src/block_properties.rs | 171 +++ crates/horizon-world/src/block_support.rs | 221 +++ crates/horizon-world/src/block_survival.rs | 1215 +++++++++++++++++ crates/horizon-world/src/chunk.rs | 556 ++++++++ crates/horizon-world/src/collision.rs | 190 +++ crates/horizon-world/src/compression.rs | 227 +++ crates/horizon-world/src/dynamic_support.rs | 251 ++++ .../horizon-world/src/entity_obstruction.rs | 89 ++ crates/horizon-world/src/fluid.rs | 252 ++++ crates/horizon-world/src/heightmap.rs | 249 ++++ crates/horizon-world/src/lib.rs | 22 + crates/horizon-world/src/main.rs | 197 +++ crates/horizon-world/src/nbt.rs | 606 ++++++++ crates/horizon-world/src/piston_shape.rs | 196 +++ crates/horizon-world/src/region.rs | 376 +++++ crates/horizon-world/src/registry.rs | 106 ++ crates/horizon-world/src/registry/json.rs | 135 ++ crates/horizon-world/src/tick_data.rs | 81 ++ crates/horizon-world/src/worldgen.rs | 258 ++++ crates/horizon-world/src/worldgen/anchor.rs | 102 ++ crates/horizon-world/src/worldgen/aquifer.rs | 100 ++ .../src/worldgen/aquifer/config.rs | 127 ++ .../src/worldgen/aquifer/noise_based.rs | 578 ++++++++ crates/horizon-world/src/worldgen/biome.rs | 153 +++ .../horizon-world/src/worldgen/biome_chunk.rs | 178 +++ .../src/worldgen/biome_predicate.rs | 81 ++ .../src/worldgen/biome_source.rs | 92 ++ .../src/worldgen/biome_source/codec.rs | 262 ++++ .../src/worldgen/biome_source/runtime.rs | 170 +++ .../src/worldgen/biome_temperature.rs | 193 +++ .../src/worldgen/block_feature.rs | 333 +++++ .../src/worldgen/block_predicate.rs | 360 +++++ .../src/worldgen/bulk_section.rs | 113 ++ crates/horizon-world/src/worldgen/carver.rs | 296 ++++ .../src/worldgen/carver/canyon.rs | 161 +++ .../src/worldgen/carver/generation.rs | 167 +++ crates/horizon-world/src/worldgen/carving.rs | 122 ++ crates/horizon-world/src/worldgen/climate.rs | 118 ++ .../src/worldgen/climate/codec.rs | 59 + .../src/worldgen/climate/index.rs | 325 +++++ .../horizon-world/src/worldgen/decoration.rs | 141 ++ crates/horizon-world/src/worldgen/density.rs | 578 ++++++++ crates/horizon-world/src/worldgen/feature.rs | 162 +++ .../src/worldgen/feature_catalog.rs | 266 ++++ .../src/worldgen/feature_graph.rs | 441 ++++++ .../src/worldgen/feature_region.rs | 231 ++++ .../src/worldgen/feature_sort.rs | 116 ++ .../src/worldgen/fluid_predicate.rs | 92 ++ .../src/worldgen/height_provider.rs | 149 ++ .../src/worldgen/material_condition.rs | 611 +++++++++ .../src/worldgen/material_condition/codec.rs | 474 +++++++ .../worldgen/material_condition/density.rs | 147 ++ .../worldgen/material_condition/library.rs | 359 +++++ .../src/worldgen/material_condition/noise.rs | 112 ++ .../src/worldgen/material_condition/rule.rs | 222 +++ .../src/worldgen/material_extensions.rs | 229 ++++ .../src/worldgen/material_stage.rs | 351 +++++ .../src/worldgen/material_surface.rs | 142 ++ .../horizon-world/src/worldgen/ore_feature.rs | 101 ++ .../horizon-world/src/worldgen/placement.rs | 505 +++++++ .../src/worldgen/placement/chain.rs | 270 ++++ .../src/worldgen/placement/context.rs | 117 ++ .../src/worldgen/placement/layer.rs | 68 + crates/horizon-world/src/worldgen/router.rs | 168 +++ .../horizon-world/src/worldgen/rule_test.rs | 133 ++ crates/horizon-world/src/worldgen/settings.rs | 45 + .../src/worldgen/state_provider.rs | 601 ++++++++ .../src/worldgen/state_provider/catalog.rs | 55 + .../src/worldgen/state_provider/noise.rs | 231 ++++ .../src/worldgen/state_provider/properties.rs | 178 +++ crates/horizon-world/src/worldgen/tags.rs | 369 +++++ crates/horizon-world/src/worldgen/terrain.rs | 479 +++++++ .../src/worldgen/value_provider.rs | 215 +++ crates/horizon-world/src/worldgen/weighted.rs | 105 ++ crates/horizon-world/tests/biome_data.rs | 91 ++ .../tests/biome_predicate_bounds.rs | 39 + crates/horizon-world/tests/biome_region.rs | 40 + .../tests/block_predicate_bounds.rs | 92 ++ .../horizon-world/tests/carver_generation.rs | 89 ++ crates/horizon-world/tests/carving_stage.rs | 172 +++ crates/horizon-world/tests/collision_data.rs | 157 +++ .../horizon-world/tests/decoration_bounds.rs | 35 + crates/horizon-world/tests/feature_catalog.rs | 62 + .../tests/feature_graph_bounds.rs | 89 ++ .../horizon-world/tests/feature_placement.rs | 41 + crates/horizon-world/tests/feature_region.rs | 148 ++ .../tests/feature_sort_bounds.rs | 34 + crates/horizon-world/tests/material_stage.rs | 295 ++++ .../horizon-world/tests/placement_bounds.rs | 58 + .../horizon-world/tests/placement_queries.rs | 45 + .../horizon-world/tests/rule_test_bounds.rs | 69 + .../tests/state_provider_bounds.rs | 81 ++ crates/horizon-world/tests/tick_data.rs | 117 ++ .../horizon-world/tests/weighted_provider.rs | 53 + crates/horizon-world/tests/world_io.rs | 199 +++ docs/biome-lookup.md | 133 ++ docs/biome-temperatures.md | 33 + docs/block-state-codecs.md | 25 + docs/carving.md | 126 ++ docs/collision-geometry.md | 283 ++++ docs/compact-headers.md | 2 +- docs/debounce-queue.md | 2 +- docs/density-functions.md | 502 +++++++ docs/dispatch-retry.md | 2 +- docs/feature-placement.md | 543 ++++++++ docs/heightmaps.md | 57 + docs/mac-first-test.md | 2 +- docs/material-conditions.md | 88 ++ docs/material-rule-libraries.md | 36 + docs/material-surfaces.md | 125 ++ docs/noise-generation.md | 96 ++ docs/optimization-plan.md | 7 + docs/playable-validation.md | 4 +- docs/process-memory.md | 2 +- docs/rust-parity.md | 381 ++++++ docs/scheduled-ticks.md | 136 ++ docs/shader-world-smoke.md | 2 +- docs/structure-density.md | 43 + docs/terrain-filling.md | 88 ++ docs/value-providers.md | 63 + docs/vertical-anchors.md | 22 + docs/worker-pacing.md | 2 +- docs/world-data.md | 147 ++ docs/world-generation.md | 192 +++ .../main/java/dev/horizonlab/HorizonLab.java | 2 +- .../dev/horizonlab/budget/DebounceWait.java | 0 .../dev/horizonlab/budget/DispatchRetry.java | 0 .../dev/horizonlab/budget/TerrainBudget.java | 0 .../horizonlab/budget/TerrainReadWait.java | 0 .../horizonlab/budget/WakeableIdleWait.java | 0 .../dev/horizonlab/budget/WorkerPacer.java | 0 .../client/DistantTerrainBudget.java | 2 +- .../client/DistantTerrainSettings.java | 0 .../dev/horizonlab/client/HorizonClient.java | 0 .../dev/horizonlab/client/ShaderSettings.java | 0 .../geometry/RelativeTerrainPosition.java | 0 .../metrics/ProcessMemoryMonitor.java | 0 .../dev/horizonlab/metrics/Recording.java | 0 .../java/dev/horizonlab/metrics/Reports.java | 0 .../horizonlab/metrics/ResidentMemory.java | 0 .../dev/horizonlab/metrics/SampleStats.java | 0 .../dev/horizonlab/metrics/ServerContext.java | 0 .../horizonlab/metrics/SoftwareContext.java | 0 .../dev/horizonlab/metrics/TickState.java | 0 .../mixin/CullingEmptyWhitelistMixin.java | 0 .../mixin/CullingRayScratchMixin.java | 0 .../horizonlab/mixin/DhDebounceWaitMixin.java | 0 .../mixin/DhPriorityDispatchMixin.java | 0 .../horizonlab/mixin/DhQuadReuseMixin.java | 0 .../mixin/DhRelativePositionMixin.java | 0 .../mixin/DhTerrainReadWaitMixin.java | 0 .../horizonlab/mixin/DhTickDedupMixin.java | 0 .../horizonlab/mixin/DhWorkerPacingMixin.java | 0 .../java/dev/horizonlab/mixin/FrameMixin.java | 0 .../horizonlab/mixin/HorizonMixinPlugin.java | 0 .../dev/horizonlab/mixin/ServerTickMixin.java | 0 .../assets/horizonlab/lang/en_us.json | 0 .../src/main/resources/fabric.mod.json | 2 +- .../src/main/resources/horizonlab.mixins.json | 0 .../budget/DebounceQueueBenchmark.java | 0 .../horizonlab/budget/DebounceWaitTest.java | 0 .../horizonlab/budget/DispatchRetryTest.java | 0 .../horizonlab/budget/IdleQueueBenchmark.java | 0 .../horizonlab/budget/TerrainBudgetTest.java | 0 .../budget/WakeableIdleWaitTest.java | 0 .../horizonlab/budget/WorkerPacerTest.java | 0 .../budget/WorkerPacingBenchmark.java | 0 .../client/DistantTerrainBudgetTest.java | 0 .../client/DistantTerrainSettingsTest.java | 0 .../dispatch/CullingEmptyIntegration.java | 0 .../dispatch/CullingRayIntegration.java | 0 .../dispatch/DispatchIntegration.java | 0 .../dispatch/PositionIntegration.java | 0 .../dispatch/QuadReuseIntegration.java | 0 .../dispatch/QuadSizeIntegration.java | 0 .../dispatch/TerrainReadIntegration.java | 0 .../dispatch/TickDedupIntegration.java | 0 .../dispatch/fixture/CullingRayAccess.java | 0 .../fixture/GraphicsBackendTraceMixin.java | 0 .../geometry/RelativeTerrainPositionTest.java | 0 .../metrics/ClientGraphicsIntegration.java | 0 .../dev/horizonlab/metrics/MetricsTest.java | 0 .../metrics/ObjectHeaderBenchmark.java | 0 .../horizonlab/metrics/ObjectSizeAgent.java | 0 .../metrics/ResidentMemoryTest.java | 0 .../metrics/ServerGraphicsIntegration.java | 0 .../metrics/TickStateIntegration.java | 0 .../parity/VanillaAnchorOracle.java | 57 + .../parity/VanillaBasicFeatureOracle.java | 78 ++ .../parity/VanillaBiomeChunkOracle.java | 45 + .../horizonlab/parity/VanillaBiomeExport.java | 32 + .../parity/VanillaBiomeGenerationOracle.java | 69 + .../parity/VanillaBiomePlacementOracle.java | 80 ++ .../parity/VanillaBiomeSourceCodecOracle.java | 47 + .../parity/VanillaBiomeSourceOracle.java | 39 + .../parity/VanillaBiomeTemperatureOracle.java | 69 + .../parity/VanillaBiomeZoomOracle.java | 36 + .../parity/VanillaBlockPropertiesOracle.java | 56 + .../parity/VanillaBlockStateCodecOracle.java | 46 + .../parity/VanillaBlockSupportOracle.java | 37 + .../parity/VanillaBlockSurvivalOracle.java | 91 ++ .../parity/VanillaBulkSectionOracle.java | 88 ++ .../parity/VanillaCanyonCarverOracle.java | 40 + .../parity/VanillaCarvingGeometryOracle.java | 43 + .../parity/VanillaCarvingMaskOracle.java | 51 + .../parity/VanillaCaveCarverOracle.java | 40 + .../parity/VanillaChunkStageOracle.java | 56 + .../parity/VanillaCollisionOracle.java | 153 +++ .../horizonlab/parity/VanillaCoreOracle.java | 161 +++ .../parity/VanillaDecorationOracle.java | 102 ++ .../parity/VanillaDecorationRegionOracle.java | 125 ++ .../parity/VanillaDensityOracle.java | 471 +++++++ .../parity/VanillaDynamicSupportOracle.java | 55 + .../VanillaEntityObstructionOracle.java | 58 + .../parity/VanillaFaceSupportOracle.java | 56 + .../parity/VanillaFeatureCatalogOracle.java | 123 ++ .../parity/VanillaFeatureGraphOracle.java | 79 ++ .../parity/VanillaFeaturePlacementOracle.java | 53 + .../parity/VanillaFeatureRegionOracle.java | 97 ++ .../parity/VanillaFeatureSortOracle.java | 45 + .../parity/VanillaFillLayerOracle.java | 76 ++ .../parity/VanillaFloatLogOracle.java | 32 + .../horizonlab/parity/VanillaFluidOracle.java | 45 + .../parity/VanillaGeometryOracle.java | 218 +++ .../parity/VanillaHeightProviderOracle.java | 32 + .../parity/VanillaHeightmapOracle.java | 145 ++ .../VanillaMaterialConditionOracle.java | 251 ++++ .../VanillaMaterialExtensionOracle.java | 67 + .../parity/VanillaMaterialStageOracle.java | 181 +++ .../parity/VanillaMaterialSurfaceOracle.java | 75 + .../horizonlab/parity/VanillaNoiseOracle.java | 149 ++ .../parity/VanillaPistonShapeOracle.java | 41 + .../parity/VanillaPlacementOracle.java | 101 ++ .../parity/VanillaReplaceBlockOracle.java | 74 + .../parity/VanillaRuleTestOracle.java | 37 + .../parity/VanillaScatteredOreOracle.java | 78 ++ .../parity/VanillaStateProviderOracle.java | 147 ++ .../parity/VanillaStructureDensityOracle.java | 38 + .../horizonlab/parity/VanillaTagExport.java | 12 + .../parity/VanillaTerrainOracle.java | 110 ++ .../parity/VanillaTickDataOracle.java | 90 ++ .../horizonlab/parity/VanillaTickOracle.java | 109 ++ .../parity/VanillaValueProviderOracle.java | 39 + .../horizonlab/parity/VanillaWorldOracle.java | 217 +++ .../parity/VanillaWorldgenOracle.java | 387 ++++++ .../parity/VanillaWorldgenRandomOracle.java | 50 + packs/START-HERE.txt | 4 +- tests/test_anchor_parity.py | 22 + tests/test_basic_feature_parity.py | 25 + tests/test_biome_chunk_parity.py | 23 + tests/test_biome_generation_parity.py | 27 + tests/test_biome_placement_parity.py | 20 + tests/test_biome_source_codec_parity.py | 23 + tests/test_biome_source_parity.py | 23 + tests/test_biome_temperature_parity.py | 33 + tests/test_biome_zoom_parity.py | 20 + tests/test_block_properties_parity.py | 19 + tests/test_block_state_codec_parity.py | 19 + tests/test_block_survival_parity.py | 72 + tests/test_bulk_section_parity.py | 22 + tests/test_canyon_carver_parity.py | 20 + tests/test_carving_geometry_parity.py | 22 + tests/test_carving_mask_parity.py | 20 + tests/test_cave_carver_parity.py | 21 + tests/test_chunk_stage_parity.py | 22 + tests/test_decoration_parity.py | 22 + tests/test_decoration_region_parity.py | 22 + tests/test_density_parity.py | 254 ++++ tests/test_dynamic_support_parity.py | 31 + tests/test_entity_obstruction_parity.py | 19 + tests/test_face_support_parity.py | 20 + tests/test_feature_catalog_parity.py | 24 + tests/test_feature_graph_parity.py | 22 + tests/test_feature_placement_parity.py | 21 + tests/test_feature_region_parity.py | 21 + tests/test_feature_sort_parity.py | 18 + tests/test_fill_layer_parity.py | 20 + tests/test_float_log_parity.py | 37 + tests/test_fluid_parity.py | 17 + tests/test_geometry_parity.py | 41 + tests/test_height_provider_parity.py | 23 + tests/test_heightmap_parity.py | 39 + tests/test_lab.py | 3 +- tests/test_material_condition_parity.py | 112 ++ tests/test_material_extension_parity.py | 19 + tests/test_material_rule_library_parity.py | 24 + tests/test_material_stage_parity.py | 95 ++ tests/test_material_surface_parity.py | 21 + tests/test_noise_parity.py | 43 + tests/test_packs.py | 26 +- tests/test_piston_shape_parity.py | 19 + tests/test_placement_parity.py | 27 + tests/test_replace_block_parity.py | 20 + tests/test_rule_test_parity.py | 19 + tests/test_rust_parity.py | 72 + tests/test_scattered_ore_parity.py | 21 + tests/test_state_provider_parity.py | 32 + tests/test_structure_density_parity.py | 27 + tests/test_terrain_parity.py | 37 + tests/test_tick_parity.py | 32 + tests/test_value_provider_parity.py | 23 + tests/test_worldgen_parity.py | 150 ++ tests/test_worldgen_random_parity.py | 20 + tools/Compare-Benchmarks.html | 4 +- tools/build_mod.py | 6 +- tools/build_pack.py | 8 +- tools/build_release.py | 2 +- tools/check_public_tree.py | 4 +- tools/lab.py | 2 +- tools/runtime.py | 4 +- tools/server.py | 2 +- tools/test_anchor_parity.py | 76 ++ tools/test_basic_feature_parity.py | 95 ++ tools/test_biome_chunk_parity.py | 66 + tools/test_biome_generation_parity.py | 88 ++ tools/test_biome_placement_parity.py | 70 + tools/test_biome_source_codec_parity.py | 120 ++ tools/test_biome_source_parity.py | 68 + tools/test_biome_temperature_parity.py | 105 ++ tools/test_biome_zoom_parity.py | 81 ++ tools/test_block_properties_parity.py | 73 + tools/test_block_state_codec_parity.py | 76 ++ tools/test_block_support_parity.py | 51 + tools/test_block_survival_parity.py | 267 ++++ tools/test_bulk_section_parity.py | 93 ++ tools/test_canyon_carver_parity.py | 89 ++ tools/test_carving_geometry_parity.py | 96 ++ tools/test_carving_mask_parity.py | 89 ++ tools/test_cave_carver_parity.py | 84 ++ tools/test_chunk_stage_parity.py | 96 ++ tools/test_client_graphics.py | 2 +- tools/test_collision_parity.py | 78 ++ tools/test_culling_empty.py | 2 +- tools/test_culling_rays.py | 2 +- tools/test_decoration_parity.py | 92 ++ tools/test_decoration_region_parity.py | 97 ++ tools/test_density_parity.py | 1100 +++++++++++++++ tools/test_dispatch.py | 2 +- tools/test_dynamic_support_parity.py | 98 ++ tools/test_entity_obstruction_parity.py | 77 ++ tools/test_face_support_parity.py | 77 ++ tools/test_feature_catalog_parity.py | 123 ++ tools/test_feature_graph_parity.py | 104 ++ tools/test_feature_placement_parity.py | 111 ++ tools/test_feature_region_parity.py | 93 ++ tools/test_feature_sort_parity.py | 81 ++ tools/test_fill_layer_parity.py | 85 ++ tools/test_float_log_parity.py | 100 ++ tools/test_fluid_parity.py | 62 + tools/test_geometry_parity.py | 313 +++++ tools/test_height_provider_parity.py | 97 ++ tools/test_heightmap_parity.py | 122 ++ tools/test_material_condition_parity.py | 316 +++++ tools/test_material_extension_parity.py | 80 ++ tools/test_material_rule_library_parity.py | 93 ++ tools/test_material_stage_parity.py | 146 ++ tools/test_material_surface_parity.py | 75 + tools/test_noise_parity.py | 209 +++ tools/test_piston_shape_parity.py | 79 ++ tools/test_placement_parity.py | 132 ++ tools/test_quad_reuse.py | 2 +- tools/test_quad_sizes.py | 2 +- tools/test_replace_block_parity.py | 93 ++ tools/test_rule_test_parity.py | 89 ++ tools/test_rust_parity.py | 185 +++ tools/test_scattered_ore_parity.py | 94 ++ tools/test_server_graphics.py | 2 +- tools/test_state_provider_parity.py | 400 ++++++ tools/test_structure_density_parity.py | 91 ++ tools/test_terrain_parity.py | 121 ++ tools/test_terrain_position.py | 2 +- tools/test_terrain_read.py | 2 +- tools/test_tick_dedup.py | 2 +- tools/test_tick_parity.py | 194 +++ tools/test_value_provider_parity.py | 98 ++ tools/test_world_parity.py | 112 ++ tools/test_worldgen_parity.py | 394 ++++++ tools/test_worldgen_random_parity.py | 70 + 558 files changed, 73754 insertions(+), 58 deletions(-) create mode 100644 benchmarks/rust-anchor-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-basic-feature-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-biome-chunk-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-biome-generation-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-biome-placement-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-biome-source-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-biome-source-codec-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-biome-temperature-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-biome-zoom-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-block-properties-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-block-state-codec-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-block-support-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-block-survival-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-bulk-section-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-canyon-carver-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-carving-geometry-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-carving-mask-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-cave-carver-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-chunk-stage-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-collision-2026-10-05/scoped-parity.json create mode 100644 benchmarks/rust-core-2026-10-04/scoped-parity.json create mode 100644 benchmarks/rust-core-2026-10-05/scoped-parity.json create mode 100644 benchmarks/rust-decoration-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-decoration-region-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-density-2026-10-05/scoped-parity.json create mode 100644 benchmarks/rust-dynamic-support-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-entity-obstruction-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-face-support-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-feature-catalog-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-feature-graph-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-feature-placement-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-feature-region-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-feature-sort-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-fill-layer-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-float-log-2026-10-05/boundary-parity.json create mode 100644 benchmarks/rust-float-log-2026-10-05/scoped-parity.json create mode 100644 benchmarks/rust-fluid-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-geometry-2026-10-05/scoped-parity.json create mode 100644 benchmarks/rust-geometry-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-height-provider-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-heightmap-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-material-condition-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-material-extension-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-material-rule-library-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-material-stage-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-material-surface-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-noise-2026-10-05/scoped-parity.json create mode 100644 benchmarks/rust-piston-shape-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-placement-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-replace-block-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-rule-test-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-scattered-ore-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-state-provider-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-structure-density-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-terrain-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-ticks-2026-10-05/scoped-parity.json create mode 100644 benchmarks/rust-value-provider-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-world-2026-10-05/scoped-parity.json create mode 100644 benchmarks/rust-worldgen-2026-10-05/scoped-parity.json create mode 100644 benchmarks/rust-worldgen-2026-10-06/scoped-parity.json create mode 100644 benchmarks/rust-worldgen-random-2026-10-06/scoped-parity.json create mode 100644 crates/horizon-core/Cargo.toml create mode 100644 crates/horizon-core/examples/biome_zoom_fixture.rs create mode 100644 crates/horizon-core/src/bin/density_parity.rs create mode 100644 crates/horizon-core/src/bin/float_log_parity.rs create mode 100644 crates/horizon-core/src/bin/geometry_parity.rs create mode 100644 crates/horizon-core/src/bin/noise_parity.rs create mode 100644 crates/horizon-core/src/bin/parity.rs create mode 100644 crates/horizon-core/src/bin/tick_parity.rs create mode 100644 crates/horizon-core/src/biome.rs create mode 100644 crates/horizon-core/src/biome/seed_hash.rs create mode 100644 crates/horizon-core/src/carving.rs create mode 100644 crates/horizon-core/src/carving/ellipsoid.rs create mode 100644 crates/horizon-core/src/density/arithmetic.rs create mode 100644 crates/horizon-core/src/density/beardifier.rs create mode 100644 crates/horizon-core/src/density/cache.rs create mode 100644 crates/horizon-core/src/density/end_islands.rs create mode 100644 crates/horizon-core/src/density/graph/compiler.rs create mode 100644 crates/horizon-core/src/density/graph/mod.rs create mode 100644 crates/horizon-core/src/density/graph/seeded.rs create mode 100644 crates/horizon-core/src/density/graph/tests.rs create mode 100644 crates/horizon-core/src/density/interpolation.rs create mode 100644 crates/horizon-core/src/density/interval.rs create mode 100644 crates/horizon-core/src/density/mod.rs create mode 100644 crates/horizon-core/src/density/power.rs create mode 100644 crates/horizon-core/src/density/rounding.rs create mode 100644 crates/horizon-core/src/density/selection.rs create mode 100644 crates/horizon-core/src/density/slice.rs create mode 100644 crates/horizon-core/src/density/spline.rs create mode 100644 crates/horizon-core/src/density/surface.rs create mode 100644 crates/horizon-core/src/density/terrain_noise.rs create mode 100644 crates/horizon-core/src/density/tests.rs create mode 100644 crates/horizon-core/src/density/world_fields.rs create mode 100644 crates/horizon-core/src/geometry/mod.rs create mode 100644 crates/horizon-core/src/geometry/movement.rs create mode 100644 crates/horizon-core/src/geometry/shape.rs create mode 100644 crates/horizon-core/src/geometry/shape/create.rs create mode 100644 crates/horizon-core/src/geometry/shape/face.rs create mode 100644 crates/horizon-core/src/geometry/shape/join.rs create mode 100644 crates/horizon-core/src/geometry/sweep.rs create mode 100644 crates/horizon-core/src/geometry/traversal.rs create mode 100644 crates/horizon-core/src/geometry/trig.rs create mode 100644 crates/horizon-core/src/lib.rs create mode 100644 crates/horizon-core/src/noise/mod.rs create mode 100644 crates/horizon-core/src/noise/normal.rs create mode 100644 crates/horizon-core/src/noise/perlin.rs create mode 100644 crates/horizon-core/src/noise/simplex.rs create mode 100644 crates/horizon-core/src/noise/stack.rs create mode 100644 crates/horizon-core/src/noise/volume.rs create mode 100644 crates/horizon-core/src/position.rs create mode 100644 crates/horizon-core/src/position/iter.rs create mode 100644 crates/horizon-core/src/random.rs create mode 100644 crates/horizon-core/src/random/hash.rs create mode 100644 crates/horizon-core/src/random/positional.rs create mode 100644 crates/horizon-core/src/random/worldgen.rs create mode 100644 crates/horizon-core/src/storage.rs create mode 100644 crates/horizon-core/src/ticks/heap.rs create mode 100644 crates/horizon-core/src/ticks/index.rs create mode 100644 crates/horizon-core/src/ticks/mod.rs create mode 100644 crates/horizon-core/tests/carving_bounds.rs create mode 100644 crates/horizon-core/tests/density_world_fields.rs create mode 100644 crates/horizon-world/Cargo.toml create mode 100644 crates/horizon-world/examples/anchor_fixture.rs create mode 100644 crates/horizon-world/examples/basic_feature_fixture.rs create mode 100644 crates/horizon-world/examples/biome_chunk_fixture.rs create mode 100644 crates/horizon-world/examples/biome_generation_fixture.rs create mode 100644 crates/horizon-world/examples/biome_placement_fixture.rs create mode 100644 crates/horizon-world/examples/biome_source_codec_fixture.rs create mode 100644 crates/horizon-world/examples/biome_source_fixture.rs create mode 100644 crates/horizon-world/examples/biome_temperature_fixture.rs create mode 100644 crates/horizon-world/examples/block_properties_fixture.rs create mode 100644 crates/horizon-world/examples/block_state_codec_fixture.rs create mode 100644 crates/horizon-world/examples/block_support_fixture.rs create mode 100644 crates/horizon-world/examples/block_survival_fixture.rs create mode 100644 crates/horizon-world/examples/bulk_section_fixture.rs create mode 100644 crates/horizon-world/examples/canyon_carver_fixture.rs create mode 100644 crates/horizon-world/examples/carving_geometry_fixture.rs create mode 100644 crates/horizon-world/examples/carving_mask_fixture.rs create mode 100644 crates/horizon-world/examples/cave_carver_fixture.rs create mode 100644 crates/horizon-world/examples/chunk_stage_fixture.rs create mode 100644 crates/horizon-world/examples/collision_fixture.rs create mode 100644 crates/horizon-world/examples/decoration_fixture.rs create mode 100644 crates/horizon-world/examples/decoration_region_fixture.rs create mode 100644 crates/horizon-world/examples/dynamic_support_fixture.rs create mode 100644 crates/horizon-world/examples/entity_obstruction_fixture.rs create mode 100644 crates/horizon-world/examples/face_support_fixture.rs create mode 100644 crates/horizon-world/examples/feature_catalog_fixture.rs create mode 100644 crates/horizon-world/examples/feature_graph_fixture.rs create mode 100644 crates/horizon-world/examples/feature_placement_fixture.rs create mode 100644 crates/horizon-world/examples/feature_region_fixture.rs create mode 100644 crates/horizon-world/examples/feature_sort_fixture.rs create mode 100644 crates/horizon-world/examples/fill_layer_fixture.rs create mode 100644 crates/horizon-world/examples/fluid_fixture.rs create mode 100644 crates/horizon-world/examples/height_provider_fixture.rs create mode 100644 crates/horizon-world/examples/heightmap_fixture.rs create mode 100644 crates/horizon-world/examples/material_condition_fixture.rs create mode 100644 crates/horizon-world/examples/material_extension_fixture.rs create mode 100644 crates/horizon-world/examples/material_stage_fixture.rs create mode 100644 crates/horizon-world/examples/material_surface_fixture.rs create mode 100644 crates/horizon-world/examples/piston_shape_fixture.rs create mode 100644 crates/horizon-world/examples/placement_fixture.rs create mode 100644 crates/horizon-world/examples/replace_block_fixture.rs create mode 100644 crates/horizon-world/examples/rule_test_fixture.rs create mode 100644 crates/horizon-world/examples/scattered_ore_fixture.rs create mode 100644 crates/horizon-world/examples/state_provider_fixture.rs create mode 100644 crates/horizon-world/examples/structure_density_fixture.rs create mode 100644 crates/horizon-world/examples/support/decoration_storage.rs create mode 100644 crates/horizon-world/examples/support/placement_queries.rs create mode 100644 crates/horizon-world/examples/terrain_fixture.rs create mode 100644 crates/horizon-world/examples/tick_fixture.rs create mode 100644 crates/horizon-world/examples/value_provider_fixture.rs create mode 100644 crates/horizon-world/examples/world_fixture.rs create mode 100644 crates/horizon-world/examples/worldgen_random_fixture.rs create mode 100644 crates/horizon-world/src/bin/worldgen_parity.rs create mode 100644 crates/horizon-world/src/block_collision.rs create mode 100644 crates/horizon-world/src/block_properties.rs create mode 100644 crates/horizon-world/src/block_support.rs create mode 100644 crates/horizon-world/src/block_survival.rs create mode 100644 crates/horizon-world/src/chunk.rs create mode 100644 crates/horizon-world/src/collision.rs create mode 100644 crates/horizon-world/src/compression.rs create mode 100644 crates/horizon-world/src/dynamic_support.rs create mode 100644 crates/horizon-world/src/entity_obstruction.rs create mode 100644 crates/horizon-world/src/fluid.rs create mode 100644 crates/horizon-world/src/heightmap.rs create mode 100644 crates/horizon-world/src/lib.rs create mode 100644 crates/horizon-world/src/main.rs create mode 100644 crates/horizon-world/src/nbt.rs create mode 100644 crates/horizon-world/src/piston_shape.rs create mode 100644 crates/horizon-world/src/region.rs create mode 100644 crates/horizon-world/src/registry.rs create mode 100644 crates/horizon-world/src/registry/json.rs create mode 100644 crates/horizon-world/src/tick_data.rs create mode 100644 crates/horizon-world/src/worldgen.rs create mode 100644 crates/horizon-world/src/worldgen/anchor.rs create mode 100644 crates/horizon-world/src/worldgen/aquifer.rs create mode 100644 crates/horizon-world/src/worldgen/aquifer/config.rs create mode 100644 crates/horizon-world/src/worldgen/aquifer/noise_based.rs create mode 100644 crates/horizon-world/src/worldgen/biome.rs create mode 100644 crates/horizon-world/src/worldgen/biome_chunk.rs create mode 100644 crates/horizon-world/src/worldgen/biome_predicate.rs create mode 100644 crates/horizon-world/src/worldgen/biome_source.rs create mode 100644 crates/horizon-world/src/worldgen/biome_source/codec.rs create mode 100644 crates/horizon-world/src/worldgen/biome_source/runtime.rs create mode 100644 crates/horizon-world/src/worldgen/biome_temperature.rs create mode 100644 crates/horizon-world/src/worldgen/block_feature.rs create mode 100644 crates/horizon-world/src/worldgen/block_predicate.rs create mode 100644 crates/horizon-world/src/worldgen/bulk_section.rs create mode 100644 crates/horizon-world/src/worldgen/carver.rs create mode 100644 crates/horizon-world/src/worldgen/carver/canyon.rs create mode 100644 crates/horizon-world/src/worldgen/carver/generation.rs create mode 100644 crates/horizon-world/src/worldgen/carving.rs create mode 100644 crates/horizon-world/src/worldgen/climate.rs create mode 100644 crates/horizon-world/src/worldgen/climate/codec.rs create mode 100644 crates/horizon-world/src/worldgen/climate/index.rs create mode 100644 crates/horizon-world/src/worldgen/decoration.rs create mode 100644 crates/horizon-world/src/worldgen/density.rs create mode 100644 crates/horizon-world/src/worldgen/feature.rs create mode 100644 crates/horizon-world/src/worldgen/feature_catalog.rs create mode 100644 crates/horizon-world/src/worldgen/feature_graph.rs create mode 100644 crates/horizon-world/src/worldgen/feature_region.rs create mode 100644 crates/horizon-world/src/worldgen/feature_sort.rs create mode 100644 crates/horizon-world/src/worldgen/fluid_predicate.rs create mode 100644 crates/horizon-world/src/worldgen/height_provider.rs create mode 100644 crates/horizon-world/src/worldgen/material_condition.rs create mode 100644 crates/horizon-world/src/worldgen/material_condition/codec.rs create mode 100644 crates/horizon-world/src/worldgen/material_condition/density.rs create mode 100644 crates/horizon-world/src/worldgen/material_condition/library.rs create mode 100644 crates/horizon-world/src/worldgen/material_condition/noise.rs create mode 100644 crates/horizon-world/src/worldgen/material_condition/rule.rs create mode 100644 crates/horizon-world/src/worldgen/material_extensions.rs create mode 100644 crates/horizon-world/src/worldgen/material_stage.rs create mode 100644 crates/horizon-world/src/worldgen/material_surface.rs create mode 100644 crates/horizon-world/src/worldgen/ore_feature.rs create mode 100644 crates/horizon-world/src/worldgen/placement.rs create mode 100644 crates/horizon-world/src/worldgen/placement/chain.rs create mode 100644 crates/horizon-world/src/worldgen/placement/context.rs create mode 100644 crates/horizon-world/src/worldgen/placement/layer.rs create mode 100644 crates/horizon-world/src/worldgen/router.rs create mode 100644 crates/horizon-world/src/worldgen/rule_test.rs create mode 100644 crates/horizon-world/src/worldgen/settings.rs create mode 100644 crates/horizon-world/src/worldgen/state_provider.rs create mode 100644 crates/horizon-world/src/worldgen/state_provider/catalog.rs create mode 100644 crates/horizon-world/src/worldgen/state_provider/noise.rs create mode 100644 crates/horizon-world/src/worldgen/state_provider/properties.rs create mode 100644 crates/horizon-world/src/worldgen/tags.rs create mode 100644 crates/horizon-world/src/worldgen/terrain.rs create mode 100644 crates/horizon-world/src/worldgen/value_provider.rs create mode 100644 crates/horizon-world/src/worldgen/weighted.rs create mode 100644 crates/horizon-world/tests/biome_data.rs create mode 100644 crates/horizon-world/tests/biome_predicate_bounds.rs create mode 100644 crates/horizon-world/tests/biome_region.rs create mode 100644 crates/horizon-world/tests/block_predicate_bounds.rs create mode 100644 crates/horizon-world/tests/carver_generation.rs create mode 100644 crates/horizon-world/tests/carving_stage.rs create mode 100644 crates/horizon-world/tests/collision_data.rs create mode 100644 crates/horizon-world/tests/decoration_bounds.rs create mode 100644 crates/horizon-world/tests/feature_catalog.rs create mode 100644 crates/horizon-world/tests/feature_graph_bounds.rs create mode 100644 crates/horizon-world/tests/feature_placement.rs create mode 100644 crates/horizon-world/tests/feature_region.rs create mode 100644 crates/horizon-world/tests/feature_sort_bounds.rs create mode 100644 crates/horizon-world/tests/material_stage.rs create mode 100644 crates/horizon-world/tests/placement_bounds.rs create mode 100644 crates/horizon-world/tests/placement_queries.rs create mode 100644 crates/horizon-world/tests/rule_test_bounds.rs create mode 100644 crates/horizon-world/tests/state_provider_bounds.rs create mode 100644 crates/horizon-world/tests/tick_data.rs create mode 100644 crates/horizon-world/tests/weighted_provider.rs create mode 100644 crates/horizon-world/tests/world_io.rs create mode 100644 docs/biome-lookup.md create mode 100644 docs/biome-temperatures.md create mode 100644 docs/block-state-codecs.md create mode 100644 docs/carving.md create mode 100644 docs/collision-geometry.md create mode 100644 docs/density-functions.md create mode 100644 docs/feature-placement.md create mode 100644 docs/heightmaps.md create mode 100644 docs/material-conditions.md create mode 100644 docs/material-rule-libraries.md create mode 100644 docs/material-surfaces.md create mode 100644 docs/noise-generation.md create mode 100644 docs/rust-parity.md create mode 100644 docs/scheduled-ticks.md create mode 100644 docs/structure-density.md create mode 100644 docs/terrain-filling.md create mode 100644 docs/value-providers.md create mode 100644 docs/vertical-anchors.md create mode 100644 docs/world-data.md create mode 100644 docs/world-generation.md rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/HorizonLab.java (97%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/budget/DebounceWait.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/budget/DispatchRetry.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/budget/TerrainBudget.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/budget/TerrainReadWait.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/budget/WakeableIdleWait.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/budget/WorkerPacer.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/client/DistantTerrainBudget.java (97%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/client/DistantTerrainSettings.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/client/HorizonClient.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/client/ShaderSettings.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/geometry/RelativeTerrainPosition.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/metrics/ProcessMemoryMonitor.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/metrics/Recording.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/metrics/Reports.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/metrics/ResidentMemory.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/metrics/SampleStats.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/metrics/ServerContext.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/metrics/SoftwareContext.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/metrics/TickState.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/mixin/CullingEmptyWhitelistMixin.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/mixin/CullingRayScratchMixin.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/mixin/DhDebounceWaitMixin.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/mixin/DhPriorityDispatchMixin.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/mixin/DhQuadReuseMixin.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/mixin/DhRelativePositionMixin.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/mixin/DhTerrainReadWaitMixin.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/mixin/DhTickDedupMixin.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/mixin/DhWorkerPacingMixin.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/mixin/FrameMixin.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/mixin/HorizonMixinPlugin.java (100%) rename mods/{horizon-lab => horizon}/src/main/java/dev/horizonlab/mixin/ServerTickMixin.java (100%) rename mods/{horizon-lab => horizon}/src/main/resources/assets/horizonlab/lang/en_us.json (100%) rename mods/{horizon-lab => horizon}/src/main/resources/fabric.mod.json (95%) rename mods/{horizon-lab => horizon}/src/main/resources/horizonlab.mixins.json (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/budget/DebounceQueueBenchmark.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/budget/DebounceWaitTest.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/budget/DispatchRetryTest.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/budget/IdleQueueBenchmark.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/budget/TerrainBudgetTest.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/budget/WakeableIdleWaitTest.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/budget/WorkerPacerTest.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/budget/WorkerPacingBenchmark.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/client/DistantTerrainBudgetTest.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/client/DistantTerrainSettingsTest.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/dispatch/CullingEmptyIntegration.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/dispatch/CullingRayIntegration.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/dispatch/DispatchIntegration.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/dispatch/PositionIntegration.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/dispatch/QuadReuseIntegration.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/dispatch/QuadSizeIntegration.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/dispatch/TerrainReadIntegration.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/dispatch/TickDedupIntegration.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/dispatch/fixture/CullingRayAccess.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/dispatch/fixture/GraphicsBackendTraceMixin.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/geometry/RelativeTerrainPositionTest.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/metrics/ClientGraphicsIntegration.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/metrics/MetricsTest.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/metrics/ObjectHeaderBenchmark.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/metrics/ObjectSizeAgent.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/metrics/ResidentMemoryTest.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/metrics/ServerGraphicsIntegration.java (100%) rename mods/{horizon-lab => horizon}/src/test/java/dev/horizonlab/metrics/TickStateIntegration.java (100%) create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBasicFeatureOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeChunkOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeExport.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeGenerationOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomePlacementOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceCodecOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeZoomOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPropertiesOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSupportOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSurvivalOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBulkSectionOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCanyonCarverOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingGeometryOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingMaskOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCaveCarverOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkStageOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCoreOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationRegionOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDensityOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDynamicSupportOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityObstructionOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFaceSupportOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureCatalogOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureGraphOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeaturePlacementOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureRegionOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureSortOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFillLayerOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFloatLogOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGeometryOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightProviderOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialConditionOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialExtensionOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialStageOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialSurfaceOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNoiseOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonShapeOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaReplaceBlockOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRuleTestOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaScatteredOreOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStateProviderOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureDensityOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTagExport.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTerrainOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTickDataOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTickOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaValueProviderOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenRandomOracle.java create mode 100644 tests/test_anchor_parity.py create mode 100644 tests/test_basic_feature_parity.py create mode 100644 tests/test_biome_chunk_parity.py create mode 100644 tests/test_biome_generation_parity.py create mode 100644 tests/test_biome_placement_parity.py create mode 100644 tests/test_biome_source_codec_parity.py create mode 100644 tests/test_biome_source_parity.py create mode 100644 tests/test_biome_temperature_parity.py create mode 100644 tests/test_biome_zoom_parity.py create mode 100644 tests/test_block_properties_parity.py create mode 100644 tests/test_block_state_codec_parity.py create mode 100644 tests/test_block_survival_parity.py create mode 100644 tests/test_bulk_section_parity.py create mode 100644 tests/test_canyon_carver_parity.py create mode 100644 tests/test_carving_geometry_parity.py create mode 100644 tests/test_carving_mask_parity.py create mode 100644 tests/test_cave_carver_parity.py create mode 100644 tests/test_chunk_stage_parity.py create mode 100644 tests/test_decoration_parity.py create mode 100644 tests/test_decoration_region_parity.py create mode 100644 tests/test_density_parity.py create mode 100644 tests/test_dynamic_support_parity.py create mode 100644 tests/test_entity_obstruction_parity.py create mode 100644 tests/test_face_support_parity.py create mode 100644 tests/test_feature_catalog_parity.py create mode 100644 tests/test_feature_graph_parity.py create mode 100644 tests/test_feature_placement_parity.py create mode 100644 tests/test_feature_region_parity.py create mode 100644 tests/test_feature_sort_parity.py create mode 100644 tests/test_fill_layer_parity.py create mode 100644 tests/test_float_log_parity.py create mode 100644 tests/test_fluid_parity.py create mode 100644 tests/test_geometry_parity.py create mode 100644 tests/test_height_provider_parity.py create mode 100644 tests/test_heightmap_parity.py create mode 100644 tests/test_material_condition_parity.py create mode 100644 tests/test_material_extension_parity.py create mode 100644 tests/test_material_rule_library_parity.py create mode 100644 tests/test_material_stage_parity.py create mode 100644 tests/test_material_surface_parity.py create mode 100644 tests/test_noise_parity.py create mode 100644 tests/test_piston_shape_parity.py create mode 100644 tests/test_placement_parity.py create mode 100644 tests/test_replace_block_parity.py create mode 100644 tests/test_rule_test_parity.py create mode 100644 tests/test_rust_parity.py create mode 100644 tests/test_scattered_ore_parity.py create mode 100644 tests/test_state_provider_parity.py create mode 100644 tests/test_structure_density_parity.py create mode 100644 tests/test_terrain_parity.py create mode 100644 tests/test_tick_parity.py create mode 100644 tests/test_value_provider_parity.py create mode 100644 tests/test_worldgen_parity.py create mode 100644 tests/test_worldgen_random_parity.py create mode 100644 tools/test_anchor_parity.py create mode 100644 tools/test_basic_feature_parity.py create mode 100644 tools/test_biome_chunk_parity.py create mode 100644 tools/test_biome_generation_parity.py create mode 100644 tools/test_biome_placement_parity.py create mode 100644 tools/test_biome_source_codec_parity.py create mode 100644 tools/test_biome_source_parity.py create mode 100644 tools/test_biome_temperature_parity.py create mode 100644 tools/test_biome_zoom_parity.py create mode 100644 tools/test_block_properties_parity.py create mode 100644 tools/test_block_state_codec_parity.py create mode 100644 tools/test_block_support_parity.py create mode 100644 tools/test_block_survival_parity.py create mode 100644 tools/test_bulk_section_parity.py create mode 100644 tools/test_canyon_carver_parity.py create mode 100644 tools/test_carving_geometry_parity.py create mode 100644 tools/test_carving_mask_parity.py create mode 100644 tools/test_cave_carver_parity.py create mode 100644 tools/test_chunk_stage_parity.py create mode 100644 tools/test_collision_parity.py create mode 100644 tools/test_decoration_parity.py create mode 100644 tools/test_decoration_region_parity.py create mode 100644 tools/test_density_parity.py create mode 100644 tools/test_dynamic_support_parity.py create mode 100644 tools/test_entity_obstruction_parity.py create mode 100644 tools/test_face_support_parity.py create mode 100644 tools/test_feature_catalog_parity.py create mode 100644 tools/test_feature_graph_parity.py create mode 100644 tools/test_feature_placement_parity.py create mode 100644 tools/test_feature_region_parity.py create mode 100644 tools/test_feature_sort_parity.py create mode 100644 tools/test_fill_layer_parity.py create mode 100644 tools/test_float_log_parity.py create mode 100644 tools/test_fluid_parity.py create mode 100644 tools/test_geometry_parity.py create mode 100644 tools/test_height_provider_parity.py create mode 100644 tools/test_heightmap_parity.py create mode 100644 tools/test_material_condition_parity.py create mode 100644 tools/test_material_extension_parity.py create mode 100644 tools/test_material_rule_library_parity.py create mode 100644 tools/test_material_stage_parity.py create mode 100644 tools/test_material_surface_parity.py create mode 100644 tools/test_noise_parity.py create mode 100644 tools/test_piston_shape_parity.py create mode 100644 tools/test_placement_parity.py create mode 100644 tools/test_replace_block_parity.py create mode 100644 tools/test_rule_test_parity.py create mode 100644 tools/test_rust_parity.py create mode 100644 tools/test_scattered_ore_parity.py create mode 100644 tools/test_state_provider_parity.py create mode 100644 tools/test_structure_density_parity.py create mode 100644 tools/test_terrain_parity.py create mode 100644 tools/test_tick_parity.py create mode 100644 tools/test_value_provider_parity.py create mode 100644 tools/test_world_parity.py create mode 100644 tools/test_worldgen_parity.py create mode 100644 tools/test_worldgen_random_parity.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7df85d008..975936753 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,25 +7,262 @@ permissions: contents: read jobs: verify: - runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-26, windows-latest] + runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 with: fetch-depth: 0 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' - name: Keep game artifacts out of Git run: | - python3 tools/check_public_tree.py - python3 tools/check_public_tree.py --history + python tools/check_public_tree.py + python tools/check_public_tree.py --history - name: Test offline research tooling - run: python3 -m unittest discover -s tests -v + run: python -m unittest discover -s tests -v - name: Install Rust toolchain run: rustup toolchain install stable --profile minimal --component rustfmt --component clippy - name: Check formatting and lint run: | cargo +stable fmt --all -- --check cargo +stable clippy --workspace --all-targets -- -D warnings - - name: Test voxel kernel correctness + - name: Test Rust core and voxel kernel correctness run: cargo +stable test --workspace + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '25' + - name: Compare Rust foundations with pinned vanilla client and server bytecode + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_rust_parity.py --prepare + - name: Check Rust world-data interoperability with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_world_parity.py + - name: Compare scheduled ticks and saved tick data with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_tick_parity.py + - name: Compare simulation geometry and cached block collision shapes + env: + RUSTUP_TOOLCHAIN: stable + run: | + python tools/test_geometry_parity.py + python tools/test_collision_parity.py + - name: Compare noise samplers and density kernels with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_noise_parity.py + - name: Compare compiled density samplers with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_density_parity.py + - name: Compare world-generation JSON codecs with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_worldgen_parity.py + - name: Compare heightmap predicates and chunk mutations with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_heightmap_parity.py + - name: Compare pre-light chunk status transitions and block writes + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_chunk_stage_parity.py + - name: Compare feature placement into resident neighboring chunks + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_feature_region_parity.py + - name: Compare nested feature selectors and sequences + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_feature_graph_parity.py + - name: Compare named feature holders and placed-feature tags + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_feature_catalog_parity.py + - name: Compare configured fill-layer block placement + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_fill_layer_parity.py + - name: Compare replacement-rule codecs and evaluation + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_rule_test_parity.py + - name: Compare ordered single-block replacement features + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_replace_block_parity.py + - name: Compare scattered ore placement and air-exposure checks + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_scattered_ore_parity.py + - name: Compare resident bulk-section access and raw writes + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_bulk_section_parity.py + - name: Compare biome feature ordering and cycle detection + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_feature_sort_parity.py + - name: Compare world-generation random wrappers and seeding + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_worldgen_random_parity.py + - name: Compare biome filtering and top-level feature context + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_biome_placement_parity.py + - name: Compare biome decoration feature scheduling and seeding + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_decoration_parity.py + - name: Compare decoration against resident biome and terrain sections + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_decoration_region_parity.py + - name: Compare block-state provider choices and rotation + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_state_provider_parity.py + - name: Compare contained fluids and height queries with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_fluid_parity.py + - name: Compare entity obstruction with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_entity_obstruction_parity.py + - name: Compare block solidity and replaceability with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_block_properties_parity.py + - name: Compare face slicing and block support with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_face_support_parity.py + - name: Compare cached block support with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_block_support_parity.py + - name: Compare dynamic block support with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_dynamic_support_parity.py + - name: Compare moving-piston collision and interpolation with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_piston_shape_parity.py + - name: Compare supported block survival rules with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_block_survival_parity.py + - name: Compare noise-stage chunk filling with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_terrain_parity.py + - name: Compare structure terrain-adaptation density with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_structure_density_parity.py + - name: Compare seeded material bands and surface queries with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_material_surface_parity.py + - name: Compare material condition codecs and rule evaluation with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_material_condition_parity.py + - name: Compare biome temperatures and cache behavior with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_biome_temperature_parity.py + - name: Compare badlands and frozen-ocean extensions with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_material_extension_parity.py + - name: Compare bundled material-rule libraries with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_material_rule_library_parity.py + - name: Compare fixed, checkerboard and End biome sources with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_biome_source_parity.py + - name: Compare seeded cave paths and failure state with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_cave_carver_parity.py + - name: Compare seeded canyon paths and width factors with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_canyon_carver_parity.py + - name: Compare initial block-writing feature algorithms with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_basic_feature_parity.py + - name: Compare feature placement chains with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_feature_placement_parity.py + - name: Compare feature placement primitives with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_placement_parity.py + - name: Compare anchored height providers with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_height_provider_parity.py + - name: Compare scalar value providers with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_value_provider_parity.py + - name: Compare cave and canyon geometric primitives with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_carving_geometry_parity.py + - name: Compare carving-mask traversal and callback mutations with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_carving_mask_parity.py + - name: Compare registry-bound biome-source codecs with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_biome_source_codec_parity.py + - name: Compare all four biome-source kinds in chunk generation with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_biome_generation_parity.py + - name: Compare chunk biome filling and failure state with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_biome_chunk_parity.py + - name: Compare biome zoom and seed obfuscation with pinned vanilla + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_biome_zoom_parity.py + - name: Compare surface-stage chunks with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_material_stage_parity.py + - name: Compare block-state JSON codecs with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_block_state_codec_parity.py + - name: Compare vertical anchors with pinned vanilla client and server + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_anchor_parity.py + - name: Compare float logarithms at domain and rounding boundaries + env: + RUSTUP_TOOLCHAIN: stable + run: python tools/test_float_log_parity.py portable-mod: strategy: fail-fast: false @@ -122,7 +359,7 @@ jobs: name: horizon-${{ matrix.os }} path: | dist/*.mrpack - dist/horizon-lab-*.jar + dist/horizon-*.jar dist/worker-pacing-benchmark.txt dist/debounce-queue-benchmark.txt dist/idle-queue-benchmark.txt diff --git a/.gitignore b/.gitignore index d50bc8051..e47691442 100644 --- a/.gitignore +++ b/.gitignore @@ -14,4 +14,4 @@ /run/ /logs/ /dist/ -/mods/horizon-lab/build/ +/mods/horizon/build/ diff --git a/Cargo.lock b/Cargo.lock index c676f4e42..09592a28b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,175 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "horizon-core" +version = "0.1.0" + +[[package]] +name = "horizon-world" +version = "0.1.0" +dependencies = [ + "flate2", + "horizon-core", + "lz4_flex", + "serde_json", + "xxhash-rust", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "lz4_flex" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + [[package]] name = "voxel-kernels" version = "0.1.0" + +[[package]] +name = "xxhash-rust" +version = "0.8.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index 26510443b..5cc45265c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/voxel-kernels"] +members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels"] resolver = "2" [workspace.package] diff --git a/README.md b/README.md index 809990868..bfc5d4022 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ -# Minecraft Optimization Lab / Horizon Lab +# Horizon -Client-first performance research for Minecraft Java **26.3**, preserving vanilla gameplay rules. Any language or renderer may be used when measured gains justify it. Not affiliated with Mojang or Microsoft. +Horizon is a Rust rewrite effort targeting one-to-one vanilla gameplay parity with Minecraft Java **26.3**, alongside client performance research. The Rust implementation has core primitives and world-data storage verified against pinned vanilla classes. It does not yet run a playable game. Existing playable downloads use Java performance packs. Not affiliated with Mojang or Microsoft. **First playable release:** pinned Java performance packs, distant terrain, an original frame/tick recorder, and Mac/client/server starter downloads. The M2 Pro/16 GB Mac is the first testing target. A Rust rewrite or custom renderer has not been completed; no M2 FPS improvement has been measured yet. ## Play on your Mac -Download **horizon-mac-starter-0.21.0.zip** from [Releases](https://github.com/ludovic111/minecraft-optimization-lab/releases), extract it and open `Mac-Start.command`. It verifies and installs official universal Prism Launcher in `~/Applications` if needed, then opens the balanced pack import. Sign into Microsoft **inside Prism yourself**. This project needs no credentials. +Download **horizon-mac-starter-0.21.0.zip** from [Releases](https://github.com/ludovic111/Horizon/releases), extract it and open `Mac-Start.command`. It verifies and installs official universal Prism Launcher in `~/Applications` if needed, then opens the balanced pack import. Sign into Microsoft **inside Prism yourself**. This project needs no credentials. Use native **Java 25 ARM64**, maximum heap **6144 MiB**, minimum **512 MiB** on your 16 GB M2 Pro. Prism can download Java automatically. Start at 1280×800 or 1920×1200; full Retina resolution is a larger GPU workload. [START-HERE.txt](packs/START-HERE.txt) has details. The same `.mrpack` files import into Prism on Windows and Linux. @@ -180,8 +180,8 @@ this launcher correction is not a measured graphics performance improvement. Game JARs, decompiled Java, libraries, inventories, worlds and logs live **inside this checkout** under gitignored **`.local/`**. No game code is in Git history or release downloads. Fresh clones regenerate the inspection workspace from official downloads; Microsoft credentials are not needed for this step. ```sh -git clone https://github.com/ludovic111/minecraft-optimization-lab.git -cd minecraft-optimization-lab +git clone https://github.com/ludovic111/Horizon.git +cd Horizon git config core.hooksPath .githooks python3 tools/lab.py prepare python3 tools/lab.py decompile @@ -194,6 +194,58 @@ Class-file SourceFile metadata covers inner classes, which often share a source ## Original Rust research +The dependency-free `horizon-core` crate starts the Rust simulation foundation: +integer block/chunk/section positions, legacy and xoroshiro seeded random streams and positional factories, +padded palette-index storage, scheduled block/fluid tick queues, and double-precision +bounding-box and voxel-grid collision geometry. Noise samplers, octave stacks and +bulk density kernels provide the next world-generation foundation. Compiled +density samplers add gradients, shifted and blended terrain noise, distance +metrics and arithmetic evaluation. +Differential runners compare selected +operations with the checksum-pinned vanilla client and server bytecode. +[Implemented scope, validation, and remaining rewrite work](docs/rust-parity.md). + +```sh +python3 tools/test_rust_parity.py --prepare +python3 tools/test_world_parity.py +python3 tools/test_tick_parity.py +python3 tools/test_geometry_parity.py +python3 tools/test_collision_parity.py +python3 tools/test_noise_parity.py +python3 tools/test_density_parity.py +``` + +The core corpus checks 1,634,520 output lines per reference JAR, including +signed boundaries, RNG rejection/state consumption and raw storage words. +Passing it does not establish full gameplay parity or an FPS improvement. +The separate [noise suite](docs/noise-generation.md) checks 26.3 Perlin/simplex, +derivatives, density-volume accumulation, stack composition, normal-noise +normalization and modern/legacy initialization against both reference JARs. +The [density suite](docs/density-functions.md) checks compiled scalar and bulk +evaluation, including nested samplers, their different arithmetic paths, and +selected interval operations used for graph range analysis. + +`horizon-world` adds NBT, four region compression codecs, `.mca`/`.mcc` +reading and export, saved palettes, a version-checked block-state registry, +and packed resident block sections. The world-data suite checks Rust output +with the actual vanilla NBT, region and block-state decoders on both JARs. +It covers all 35,723 exported state IDs and a 100,000-edit section trace. +[World-data commands and validation limits](docs/world-data.md). + +Scheduled ticks now support vanilla ordering, duplicate suppression, save/reload, +chunk eligibility and callback mutations. The tick suite compares 97,776 output +lines per reference JAR and checks saved block/fluid lists through vanilla codecs +and region files. [Scheduler behavior and remaining integration](docs/scheduled-ticks.md). + +Voxel shapes preserve vanilla collision tolerances, greedy box ordering, ray faces, +inside hits, and cube-versus-array cell lookup. A cached collision registry connects +imported shapes to resident block sections while checking exact state identities. +Movement helpers resolve supplied colliders and step-up candidates, including +landing adjustment and the second collider query. Movement-path block visits +preserve vanilla ordering, step indices and packed-position deduplication. +Uncached states require block behavior; the entity-context overload also needs +separate implementation. [Geometry and collision scope](docs/collision-geometry.md). + ```sh cargo test --workspace cargo run --release --bin voxel-bench -- 100 > .local/voxel-benchmark.csv @@ -201,6 +253,11 @@ cargo run --release --bin voxel-bench -- 100 > .local/voxel-benchmark.csv The dependency-free occupancy experiment compares scalar and bitset exposed-face counting for synthetic 16³ sections. It has no real mesh, material/AO/light work, neighboring-section context, JNI bridge or game integration. Speedups are kernel-only, not Minecraft FPS. [Research plan](docs/optimization-plan.md) describes profiling, improved Java baselines, native integration and behavior checks before expanding scope. +Public branding and new mod downloads use **Horizon**. The existing Fabric mod +ID and `dev.horizonlab` namespace remain stable for installed instances and +measurement compatibility. The installer backs up both old `horizon-lab-*.jar` +and new `horizon-*.jar` versions before installing an update. + ## Validation and ownership ```sh diff --git a/benchmarks/rust-anchor-2026-10-06/scoped-parity.json b/benchmarks/rust-anchor-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..344423502 --- /dev/null +++ b/benchmarks/rust-anchor-2026-10-06/scoped-parity.json @@ -0,0 +1,118 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 192, + "codec_inputs": 74112, + "runtime_anchors": 107328, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java": "226628d98b89aadbdd374936575d033945e7064a900dbb050c662204dbc7e119", + "tools/test_anchor_parity.py": "6f394f5cc236fc6ca96bfa526b09ac3009fd90b1db997ff1aed059b51170437a", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry.rs": "f46065659e60eb5e84ad69b9f3b5e94dc87ee19de16408817e26f23d16b6c7e7", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "134cf93b53a40fb1ed0e0170c90316c80e270773b2968c63dc3f9cef2c941bff", + "crates/horizon-world/src/worldgen.rs": "e1e815997cfef573c36d7814582fe28086456488be3d87708dbfd94740cf04fd", + "crates/horizon-world/examples/anchor_fixture.rs": "ff824b3b85d09881217c8bdb5219d602099cad21b6efdd180e6c8e3149337b31" + }, + "fixtures_sha256": { + ".local/rust-anchor-parity/inputs.txt": "cc495eb8aca212c1768c882a309052cf4612664570a208082d08ea83f7e8ee60" + }, + "rust_output_sha256": "e48ad3177f302e687ece755cc8933f76ca610ac1e9cba00c0e919431f75cd19b", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "e48ad3177f302e687ece755cc8933f76ca610ac1e9cba00c0e919431f75cd19b", + "matched_output_lines": 181632 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "e48ad3177f302e687ece755cc8933f76ca610ac1e9cba00c0e919431f75cd19b", + "matched_output_lines": 181632 + } + ], + "scope": "Actual VerticalAnchor.CODEC parsing and encoding, all four anchor kinds, constant helpers, runtime integer overflow and unrestricted constructor values. WorldGenerationContext.of uses a LevelAccessor proxy with verified method calls; the generator constructor uses a native NoiseBasedChunkGenerator with supplied minimum, height and sea level. Strict JSON transport covers range limits, numeric truncation/wrapping, null/wrong field types, duplicate fields and nested exclusive alternatives. Level access outside the three queried values, JSON syntax diagnostics and complete material conditions remain pending." +} diff --git a/benchmarks/rust-basic-feature-2026-10-06/scoped-parity.json b/benchmarks/rust-basic-feature-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..e1f455b12 --- /dev/null +++ b/benchmarks/rust-basic-feature-2026-10-06/scoped-parity.json @@ -0,0 +1,153 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 3608, + "basic_features": 3, + "block_states": 5, + "composed_fixtures": 1584, + "requested_placements": 7208, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBasicFeatureOracle.java": "5a0de14f47f344f3d1b7eda7e1204156545358f6b5770b72120f805a85773938", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java": "ac727111418c4263d302a9fea4050bd4e050cf4d94674bb0b532ea4b36557eb7", + "tools/test_basic_feature_parity.py": "19e8b87b83ba5f8698e648a6946b6998f83dee29ffa0627836177baf53a49844", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/placement/chain.rs": "76832dd4f76b44edfcc8bd52d8115f6e30684bfaea0e0b959ba060f07cc3483d", + "crates/horizon-world/src/worldgen/placement/context.rs": "cb57bbdadc2b933528278a0ec13b545e453021765ee59fa3b638fb79199dd110", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "bed9b24771fde57b4845b721f539f558af59d804b8a1ecdbb41f4614c8a6b5a0", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "42823918deec5e149dc729a95bfe54aa32d91604098d5eb8452da0162d557d22", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "1ae40b843721d0f1e1c849b984e0a065aacda6e1384e21fc599cda261f996945", + "crates/horizon-world/src/worldgen.rs": "3fd53d507b2749a9fe5461c77a516fd673de40eb6b51f0b625cd637ade4dcfb5", + "crates/horizon-world/examples/basic_feature_fixture.rs": "40636fe2de41279f1a5633b3150e86d73b7f76dd7f447ecba2d39186abaa2957" + }, + "fixtures_sha256": { + ".local/rust-basic-feature-parity/inputs.txt": "e8b48d25591a8902972fdf8ac9bdaa7f16c0890b3f2076f1161f2c2b87bd5a20", + ".local/rust-basic-feature-parity/facts-client.json": "6c8d9aeb824f4150293f5d6a580d3347d866589b3eeee185a2c18479f5c64b0a", + ".local/rust-basic-feature-parity/facts-server.json": "6c8d9aeb824f4150293f5d6a580d3347d866589b3eeee185a2c18479f5c64b0a" + }, + "rust_output_sha256": "1e7df8d3ee5bfa2f750b94c95b03f426b50608e1a37991ebc3bc3c5c656ee811", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "1e7df8d3ee5bfa2f750b94c95b03f426b50608e1a37991ebc3bc3c5c656ee811", + "matched_output_lines": 1820614 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "1e7df8d3ee5bfa2f750b94c95b03f426b50608e1a37991ebc3bc3c5c656ee811", + "matched_output_lines": 1820614 + } + ], + "scope": "Actual Feature.DIRECT_CODEC and native void-start-platform, End-island and End-platform feature algorithms. A mutable WorldGenLevel proxy logs ordered block reads, writes, update flags, rejected writes, thrown failures and accumulated stored states after repeated placements. Native LevelWriter.setBlockAndUpdate executes through its actual default method. Required default block-state IDs are independently exported and checked across both authenticated JARs. Direct calls and native FeaturePlacer modifier chains share the mutable world and random stream, including reused placer buffers after failures. Both random modes, multiple seeds, nearby/far chunks and extreme wrapped coordinates are compared, with nextLong values after every placement and at fixture end. The End-platform feature invokes its ordinary generation path without block destruction/drops. Actual chunk mutation, neighbor updates, lighting, entity/block drops, full feature registry behavior and complete generated worlds remain outside this comparison." +} diff --git a/benchmarks/rust-biome-chunk-2026-10-06/scoped-parity.json b/benchmarks/rust-biome-chunk-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..8add1e527 --- /dev/null +++ b/benchmarks/rust-biome-chunk-2026-10-06/scoped-parity.json @@ -0,0 +1,131 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 20, + "fills": 160, + "block_queries": 21120, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeChunkOracle.java": "5d1a7f967d2b35af4e0ff4783278d40077df61383c1d6dbf27b7ed52974bdae8", + "tools/test_biome_chunk_parity.py": "f469958617099939c6ae9e6f149e8d6458e75ad9ea5da3710572c5f6017718d2", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "055caaeaa507f45dd6df4c219da874831c88db05f7cfa15c8a11cbfd98ae4332", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "04ac9130138ea4ce67fc43f7701f5036972984724ffcd49bfe857d0693361d87", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "4ab2681a45108e5d2ea6fb761ea1cb7fa40b72833fa6190d2efe34ce29845c21", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "42823918deec5e149dc729a95bfe54aa32d91604098d5eb8452da0162d557d22", + "crates/horizon-world/src/worldgen.rs": "c2cfc116613456f98901732c24fedaba6532e58b3342833674b88b2e17f9f13c", + "crates/horizon-world/examples/biome_chunk_fixture.rs": "b16fdee8abcaac7d714ae71efb0c327deb2bb85a2e9a2419829441cc59e1bd02" + }, + "fixtures_sha256": { + ".local/rust-biome-chunk-parity/inputs.txt": "b2be08e1b743547c1e2880c01a3473c42cc10191d1de32eb2cad2e364c463094" + }, + "rust_output_sha256": "00ae2e07b4ccaa18f6ce6f35258833801e9f4f9335089fbb0bf7f7661988bca6", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "00ae2e07b4ccaa18f6ce6f35258833801e9f4f9335089fbb0bf7f7661988bca6", + "matched_output_lines": 478340 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "00ae2e07b4ccaa18f6ce6f35258833801e9f4f9335089fbb0bf7f7661988bca6", + "matched_output_lines": 478340 + } + ], + "scope": "Actual ChunkAccess.fillBiomesFromNoise, LevelChunkSection.fillBiomesFromNoise and chunk/section biome reads using synthetic registered holder identities. Ordered resolver queries, section contents and clamped/wrapped chunk lookups are compared after repeated fills and failures at section boundaries. Covers full supported aligned vertical bounds, generation bounds cutting through sections, negative/extreme chunk coordinates and 1..512 possible biome identities. Completed earlier sections survive failure while the failing section retains its previous values. This compares stored biome values, not native in-memory palette layout, wire encoding, biome-source generation, blending, retrogen or complete generated worlds." +} diff --git a/benchmarks/rust-biome-generation-2026-10-06/scoped-parity.json b/benchmarks/rust-biome-generation-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..895d7196b --- /dev/null +++ b/benchmarks/rust-biome-generation-2026-10-06/scoped-parity.json @@ -0,0 +1,149 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 252, + "fills": 322, + "biome_values": 341504, + "block_queries": 35910, + "preset_entries": { + "minecraft:nether": 5, + "minecraft:overworld": 7594 + }, + "source_fixtures": { + "multi": 84, + "fixed": 56, + "checkerboard": 56, + "end": 56 + }, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeGenerationOracle.java": "7285f7d0e358cae2857e0704bcc5fcdb73deb895653b16490eb44323c2789f7d", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeExport.java": "f9a773713cf21b69bfa10018b76f27b953bda140ede9934f43d3aa3091101cf5", + "tools/test_biome_generation_parity.py": "919af38c6c5903cb692b33d39d20c0d6cc6daf8351694f7683f7ab20cf322d93", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "055caaeaa507f45dd6df4c219da874831c88db05f7cfa15c8a11cbfd98ae4332", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "04ac9130138ea4ce67fc43f7701f5036972984724ffcd49bfe857d0693361d87", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "4ab2681a45108e5d2ea6fb761ea1cb7fa40b72833fa6190d2efe34ce29845c21", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "42823918deec5e149dc729a95bfe54aa32d91604098d5eb8452da0162d557d22", + "crates/horizon-world/src/worldgen.rs": "3ea3386996321113027dcf51d918d29d363ac1944b7c146a7f1383d17a50967b", + "crates/horizon-world/examples/biome_generation_fixture.rs": "161b985f41123dc97451f4fe0060070276466ca9aa652141aa82e62284442c7e" + }, + "fixtures_sha256": { + ".local/rust-biome-generation-parity/inputs.txt": "10cf6ac3eaeaacafecf786eaa902d5c0b8700dcad9f045d4b6032ba78b4e30f9", + ".local/rust-biome-generation-parity/registries.json": "c6868228cc1002755dab31d947e953cc4be785a1b6ae82697755817a238b7de9", + ".local/rust-biome-generation-parity/presets-client.json": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9", + ".local/rust-biome-generation-parity/presets-server.json": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9" + }, + "rust_output_sha256": "b84a1734641fbec028768da94208f583546f564eb45939c75da13efe85f3f0b9", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "b84a1734641fbec028768da94208f583546f564eb45939c75da13efe85f3f0b9", + "matched_output_lines": 383072 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "b84a1734641fbec028768da94208f583546f564eb45939c75da13efe85f3f0b9", + "matched_output_lines": 383072 + } + ], + "scope": "Actual ChunkGenerator.doCreateBiomes through NoiseBasedChunkGenerator with empty Blender and no retrogen. Both bundled Overworld/Nether multi-noise preset tables are independently exported from authenticated JARs; Rust imports quantized tables and compiles climate routers itself. All seven bundled routers, both random modes, multiple seeds and distant positive/negative chunks are tested. Complete section biome values and subsequent BiomeManager block lookups are compared, including repeated generation with fresh density contexts and persistent previous-leaf search state, and generation bounds excluding top/bottom sections. Holders are identity placeholders; no biome properties are evaluated. Fixed, checkerboard and End source fixtures also run actual chunk generation through every bundled router, including real seeded End erosion, the central-island shortcut, distant coordinates and wrapped checkerboard shifts. Preset builders, complete biome-source codecs, blending, retrogen, terrain-stage linkage and complete generated worlds remain pending." +} diff --git a/benchmarks/rust-biome-placement-2026-10-06/scoped-parity.json b/benchmarks/rust-biome-placement-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..0f1630313 --- /dev/null +++ b/benchmarks/rust-biome-placement-2026-10-06/scoped-parity.json @@ -0,0 +1,158 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 9152, + "random_modes": 2, + "requested_placements": 27456, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomePlacementOracle.java": "e8fd44142ad1448a32758036705ce2be41b0ecbf411c4562f2caed2eea9b50b9", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java": "12b1c46cc397755ef6827da777faef3e71c008cafa48403669c03ca2bdc3c7cb", + "tools/test_biome_placement_parity.py": "bac6b4857b1d4e84b23e6736398f5fce5ea1a4297b05d77235d9d242a2219b80", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "c215156f2ecf7faf214b3d89e0829b65d54f4ff6d134d778ec941f18a606a327", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "2297b194514925688dba25016a69d5ba5eb8b869bdfff28f2e611a6742ac5954", + "crates/horizon-world/src/worldgen/feature_region.rs": "4a95a30c0987d97e671f84380e13ddea070ad81f996baa65b2a06c4d892971c7", + "crates/horizon-world/src/worldgen/feature_sort.rs": "0b9d1e1c15d8449125d39e400776b8f28eec7b7cbd047660a94f8cb90160adfe", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "9bce6b17b60fec575d810713d9fb2714780aadbbc973db969c07cf4455201847", + "crates/horizon-world/src/worldgen/placement/context.rs": "f8fa467d3b931d0f98d3572fbc80c659d452a7fc5755d5c98123dc477c2b541c", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "c39c0b5f761fd573ff2f2a1d9d42901305995cc88f5c4ca3a49aaa4ef5dd933b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "55c4317bd9c782378de7c2a7d58be5aa08febc5b8f2f4b86379a39e0ba500b3c", + "crates/horizon-world/examples/biome_placement_fixture.rs": "93b4668e04daf52aed34def93aeed9af4f5bf55a8e1c60b616428aadd454648c" + }, + "fixtures_sha256": { + ".local/rust-biome-placement-parity/inputs.txt": "f823d452b40ad5c4448e5c6b6e59d7f1b0db8f40f8fdb4c36b2bc23cc99ffd09" + }, + "rust_output_sha256": "84aceee3d6197790495a2b877b04c037340258cf3d36bc440af78f82be15010b", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "84aceee3d6197790495a2b877b04c037340258cf3d36bc440af78f82be15010b", + "matched_output_lines": 121423 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "84aceee3d6197790495a2b877b04c037340258cf3d36bc440af78f82be15010b", + "matched_output_lines": 121423 + } + ], + "scope": "Actual BiomeFilter.modify and FeaturePlacer.place/placeWithBiomeCheck with native biome generation settings. Missing top features fail before biome lookup. Direct, absent, structurally equal and different placed-feature membership, query order, callback random draws/results/errors, dirty buffers across repeats and nested plain placers are compared. Direct and WorldgenRandom-wrapped legacy/xoroshiro streams execute modifier chains. Rust delegates biome resolution and generation-settings membership to the caller while isolating each placer invocation context. Full biome sampling/registry equality, complete decoration, crash-report text and gameplay remain pending." +} diff --git a/benchmarks/rust-biome-source-2026-10-06/scoped-parity.json b/benchmarks/rust-biome-source-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..47138c9a6 --- /dev/null +++ b/benchmarks/rust-biome-source-2026-10-06/scoped-parity.json @@ -0,0 +1,136 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 457, + "queries": 1147984, + "sources": { + "fixed": 1, + "checkerboard": 375, + "end": 81 + }, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceOracle.java": "8a3807e4bcb871ad3cd5eb281c803df55daf1ffb654a91d0cdb7b927643b2601", + "tools/test_biome_source_parity.py": "38a1bd39ab15d87538316541424e09a91a621f539c2202543d9c859297c0b8e4", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "055caaeaa507f45dd6df4c219da874831c88db05f7cfa15c8a11cbfd98ae4332", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source.rs": "bd1efc819d45df54a99744a90918e5e98c76759e92e7436c11933b1ce6e96c53", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "04ac9130138ea4ce67fc43f7701f5036972984724ffcd49bfe857d0693361d87", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "4ab2681a45108e5d2ea6fb761ea1cb7fa40b72833fa6190d2efe34ce29845c21", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "42823918deec5e149dc729a95bfe54aa32d91604098d5eb8452da0162d557d22", + "crates/horizon-world/src/worldgen.rs": "3ea3386996321113027dcf51d918d29d363ac1944b7c146a7f1383d17a50967b", + "crates/horizon-world/examples/biome_source_fixture.rs": "dd485dba7cef8fd924b7a8ba4357766fb874d144120c16ad3f8f6c41a863c074" + }, + "fixtures_sha256": { + ".local/rust-biome-source-parity/inputs.txt": "165d02b6bcac5cb70e7129368b4c5b2220c5cdcaba2314d94f86b687886beffa" + }, + "rust_output_sha256": "a57198fab8b45fe8db011b7153ffdc6781d6c0862c95eb9b8c0ebc6318be526d", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "a57198fab8b45fe8db011b7153ffdc6781d6c0862c95eb9b8c0ebc6318be526d", + "matched_output_lines": 1306096 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "a57198fab8b45fe8db011b7153ffdc6781d6c0862c95eb9b8c0ebc6318be526d", + "matched_output_lines": 1306096 + } + ], + "scope": "Actual FixedBiomeSource, CheckerboardColumnBiomeSource and TheEndBiomeSource runtime queries using synthetic holder identities. Fixed results, checkerboard empty/duplicate/large lists, all codec-valid scales plus unrestricted runtime scales, Java masked shifts and wrapping sums are compared. End central-circle shortcuts, erosion sampler coordinates, exact threshold boundaries, nonfinite float samples, sampler failures and integer coordinate wrapping are compared through actual Climate.Sampler bindings. End density inputs in this suite are supplied constants; real seeded End density, biome-source codecs, registry/preset loading, possible-biome metadata and generated-world integration remain separate work." +} diff --git a/benchmarks/rust-biome-source-codec-2026-10-06/scoped-parity.json b/benchmarks/rust-biome-source-codec-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..b2998f65d --- /dev/null +++ b/benchmarks/rust-biome-source-codec-2026-10-06/scoped-parity.json @@ -0,0 +1,148 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 40481, + "query_positions": 7, + "climate_grid_cases": 40001, + "biomes": 67, + "biome_tags": 86, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceCodecOracle.java": "a6f231ee68fe0aa94159c63d55f589b86c668b9f2052e215f832e10763a818e2", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeExport.java": "f9a773713cf21b69bfa10018b76f27b953bda140ede9934f43d3aa3091101cf5", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialConditionOracle.java": "04a87405fd2a1c79baf4eb3a8895aa66dc96b8f6baffb9b486ef207f8b91b5ee", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java": "226628d98b89aadbdd374936575d033945e7064a900dbb050c662204dbc7e119", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java": "243bbc525c6aec24674e7f172c5fb4f7b50f9a679d8b9dfba40ea278219a2d28", + "tools/test_biome_temperature_parity.py": "68f84d02e7802349e491b8cb66e18d9b08c9e72ab2306b663667259e852cc2b1", + "tools/test_material_condition_parity.py": "01c82e1a768d9131f8f7e6d59d01ddb06272074469dbdcd8547f44f0a8fa152d", + "tools/test_biome_source_codec_parity.py": "e7d19478429b0c6c550f45d804d4771194b2f5cecb094ebd21007a3afdbe8ca2", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "055caaeaa507f45dd6df4c219da874831c88db05f7cfa15c8a11cbfd98ae4332", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "04ac9130138ea4ce67fc43f7701f5036972984724ffcd49bfe857d0693361d87", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "4ab2681a45108e5d2ea6fb761ea1cb7fa40b72833fa6190d2efe34ce29845c21", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "42823918deec5e149dc729a95bfe54aa32d91604098d5eb8452da0162d557d22", + "crates/horizon-world/src/worldgen.rs": "3ea3386996321113027dcf51d918d29d363ac1944b7c146a7f1383d17a50967b", + "crates/horizon-world/examples/biome_source_codec_fixture.rs": "654094b2846692c34233ee2016fd3a4f9a44df0281e5bb2552ed6c35ffb17bc1" + }, + "fixtures_sha256": { + ".local/rust-biome-source-codec-parity/inputs.txt": "c9e3cbc7af471f04bbd4d8cc79a2399e2f61c00f2d2ebcc9343a254798095fbb", + ".local/rust-biome-source-codec-parity/presets-client.json": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9", + ".local/rust-biome-source-codec-parity/presets-server.json": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9", + ".local/rust-biome-source-codec-parity/positions.json": "35e94adf55d9bc0326133967abf93d50b896c39489f77f81d2bfa4f278364430", + ".local/rust-biome-source-codec-parity/biomes.json": "9b26dc3b662627dc3bbbf8da209f287882ce79ff4daf8f454b994ddc7510df99", + ".local/rust-biome-source-codec-parity/biome_tags.json": "4006b76c24f616cb457a6fdad816db9b27f4528fe6daaed5747f1f79cf6225cf", + ".local/rust-biome-source-codec-parity/presets.json": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9" + }, + "rust_output_sha256": "568792acae9f5b0df02bb5cf7cd6b4f7edb017a0223236c57c6fef4b0dfbb1a8", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "568792acae9f5b0df02bb5cf7cd6b4f7edb017a0223236c57c6fef4b0dfbb1a8", + "matched_output_lines": 363121 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "568792acae9f5b0df02bb5cf7cd6b4f7edb017a0223236c57c6fef4b0dfbb1a8", + "matched_output_lines": 363121 + } + ], + "scope": "Actual BiomeSource.CODEC parsing and encoding for fixed, checkerboard, End and multi-noise sources bound to pinned biome/tag registries and preset holders. Named biome holders, direct/tag holder sets, canonical identifiers, scale defaults/bounds/numeric narrowing, inline climate parameter lists, named/inline preset holders, inline-list preference/fallback, malformed fields and duplicate keys are compared. Canonical serialized JSON is compared as sorted structures with numeric double-bit values; possible-biome sets are sorted and compared, followed by source queries against zero climate/erosion. Rust imports independently authenticated preset tables. Full inline biome definitions, live registry ownership/reloads and complete source/world generation remain outside this scoped codec comparison." +} diff --git a/benchmarks/rust-biome-temperature-2026-10-06/scoped-parity.json b/benchmarks/rust-biome-temperature-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..1306b9bd0 --- /dev/null +++ b/benchmarks/rust-biome-temperature-2026-10-06/scoped-parity.json @@ -0,0 +1,126 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 387, + "biome_resources": 67, + "codec_inputs": 183, + "operations": 53790, + "thread_isolation_fixtures": 12, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java": "243bbc525c6aec24674e7f172c5fb4f7b50f9a679d8b9dfba40ea278219a2d28", + "tools/test_biome_temperature_parity.py": "68f84d02e7802349e491b8cb66e18d9b08c9e72ab2306b663667259e852cc2b1", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry.rs": "f46065659e60eb5e84ad69b9f3b5e94dc87ee19de16408817e26f23d16b6c7e7", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "3094bb2c4abe911720a7143953f43fda3db97dcb80405b4a62f35204a06920dc", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "a6d613eed1876d7c6ef4a491ffbda36d673f27a62a9db3c4d50006ed9fc0e0b8", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "8cb30bcf221def3b2ea14aa5bd9c719aa9655432149a177180f716ba218457b8", + "crates/horizon-world/src/worldgen/material_condition.rs": "e577927593cdbc7b8aa01b7e8d641df0374f36cc8b5b4cc1eb797f526fa8e636", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "134cf93b53a40fb1ed0e0170c90316c80e270773b2968c63dc3f9cef2c941bff", + "crates/horizon-world/src/worldgen.rs": "e5123e2249017e2cef7067cd7ddd85316a075c418bf9d1b452db601eea3483a0", + "crates/horizon-world/examples/biome_temperature_fixture.rs": "192fb207c28c2a040c6264d2c3573bd71d389ce04f66408eed47b9bfa6aa6df0" + }, + "fixtures_sha256": { + ".local/rust-biome-temperature-parity/inputs.txt": "f882dff81e4b3be8b37e2a5130198a6bd0eb437ebd903f68b15899bd1509e681", + ".local/rust-biome-temperature-parity/biomes.json": "9b26dc3b662627dc3bbbf8da209f287882ce79ff4daf8f454b994ddc7510df99" + }, + "rust_output_sha256": "2c40a4156ce3edd9dbbecc80aeea0cd1606fd462e79abb377d778c02a973d38e", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "2c40a4156ce3edd9dbbecc80aeea0cd1606fd462e79abb377d778c02a973d38e", + "matched_output_lines": 836659 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "2c40a4156ce3edd9dbbecc80aeea0cd1606fd462e79abb377d778c02a973d38e", + "matched_output_lines": 836659 + } + ], + "scope": "Actual Biome temperature methods, warm/cold/iceberg-melt predicates and precipitation selection, with both temperature modifiers and arbitrary base float bits. Native private climate/biome constructors provide explicit temperature inputs; unrelated biome fields are null and never queried. Fixed seeded simplex/stack sources, float/double conversion and arithmetic order, height adjustment and sea-level overflow, packed-position aliases, repeated queries with changed sea levels, cache capacity/order/content, NaN recomputation and eviction, and actual native thread-local isolation versus independently owned Rust workers. ClimateSettings map-codec parsing additionally covers all independently authenticated bundled biome definitions, direct float conversion, nonfinite overflow, modifier defaults/null handling, field types, duplicates and missing fields. Full biome data codecs, climate encoding, complete weather placement/freezing, material condition integration and automatic migration of shared biome instances between threads remain outside this scope." +} diff --git a/benchmarks/rust-biome-zoom-2026-10-06/scoped-parity.json b/benchmarks/rust-biome-zoom-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..4f607d3ae --- /dev/null +++ b/benchmarks/rust-biome-zoom-2026-10-06/scoped-parity.json @@ -0,0 +1,131 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 256933, + "seed_hashes": 4104, + "block_queries": 169408, + "position_queries": 83421, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeZoomOracle.java": "89962784c285822d11ff72cbff0c22d41a3a27993793a61e35869c50a72ed614", + "tools/test_biome_zoom_parity.py": "0b5f02ed01306a2acb0143da1019562a8413602afa05fef16bdc485e0e6ae716", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "055caaeaa507f45dd6df4c219da874831c88db05f7cfa15c8a11cbfd98ae4332", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "04ac9130138ea4ce67fc43f7701f5036972984724ffcd49bfe857d0693361d87", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "4ab2681a45108e5d2ea6fb761ea1cb7fa40b72833fa6190d2efe34ce29845c21", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "42823918deec5e149dc729a95bfe54aa32d91604098d5eb8452da0162d557d22", + "crates/horizon-world/src/worldgen.rs": "cffb5e72b59222dad13e57fa74ed4f553570a61a8773f27b5199444111ced2e0", + "crates/horizon-core/examples/biome_zoom_fixture.rs": "8bdb7a4f15ac94cd4807ea1e1211c53f0ea050fda5ddfea65b2dc345e13b2e27" + }, + "fixtures_sha256": { + ".local/rust-biome-zoom-parity/inputs.txt": "61abb5e562325847d5c7f7849dac79aa9392b9ae2dab9f42dab6485dd89c5ea7" + }, + "rust_output_sha256": "7b5d1c89f31ce1a803bafe9a675677d035cbce49ecede300d6beab7240501c95", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "7b5d1c89f31ce1a803bafe9a675677d035cbce49ecede300d6beab7240501c95", + "matched_output_lines": 256933 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "7b5d1c89f31ce1a803bafe9a675677d035cbce49ecede300d6beab7240501c95", + "matched_output_lines": 256933 + } + ], + "scope": "Actual BiomeManager seed obfuscation, block-position eight-corner jitter selection, direct block/double-to-quart queries, and source replacement preserving the zoom seed. Captured resolver coordinates are compared, including dense local grids, signed coordinate overflow, negative boundaries, distant blocks, long-seed boundaries, random seeds/positions, double infinities/NaNs/subnormals and saturating conversion. SHA-256 seed transforms are also compared against Python hashlib independently. Biome storage/source generation, blending, chunk integration and gameplay remain separate work." +} diff --git a/benchmarks/rust-block-properties-2026-10-06/scoped-parity.json b/benchmarks/rust-block-properties-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..0382cf402 --- /dev/null +++ b/benchmarks/rust-block-properties-2026-10-06/scoped-parity.json @@ -0,0 +1,176 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "registry_states": 35723, + "fixtures": 18096, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPropertiesOracle.java": "99a396b9b983f6ca9149133251f3ece9aaf76d3d16dafa1f322378212a19490c", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java": "60ff9ef7c1d5e23c080f9aec95ab2e7d3b7c5b5bcd67b9efa9518776c400629a", + "tools/test_block_properties_parity.py": "083d09fe190a783b2939068b7ad01e98938d9277f9583c5273bb2453e870d713", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/face.rs": "f243bce81384040a95ce7984b02b5699206c596c537b2713097e86005b4d3a5c", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "e8d88a763de1525f77a30b99591641e8a8b80946263acbde035a9bcc356df960", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/block_collision.rs": "cec2af81d212d5eed7a2196e4cf0be2daf4cecf53248f78cc68f2190e4d83f9a", + "crates/horizon-world/src/block_properties.rs": "b3caf26bd3afc9d10cdcca3f7e794c30abf5ba09afa1fe80ba8f44713acdb274", + "crates/horizon-world/src/block_support.rs": "ade4fbd47284b450dabdd682dc86138b2ac05a0fd379525d7110648908245476", + "crates/horizon-world/src/block_survival.rs": "2c882aeb095c27a8edfda1e934ac829102e4be136d53fd83110132150b7293b1", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "05313e0c1f3089524fe029f9aac3e439cd47f1c9584c8c7e154c9adcfa88c335", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/dynamic_support.rs": "e799b31e5120cfdb04e0b342f2097d610ed98ef8c4be031620ee00368d82df59", + "crates/horizon-world/src/entity_obstruction.rs": "a4b28a19bf83b23611c59d94535c488db37e4aee24b22c973c545910894a809f", + "crates/horizon-world/src/fluid.rs": "8a2834a9347ee2c2db7cf1c86a064907ec06e9ac16ba9cc3936e315fc4ad49ca", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "09f697d8d4e709acacc8e9f7c35c5fd307bab6ab0df4a1339fe760afc655cdab", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/piston_shape.rs": "399c2337103b8e7e0eb5667227c5aa14f9549d6a467b7be7da3d0717f0263500", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "3fe316b875aa32683759c337dc71f624910faf0812a2d6d83b8098d6d0bac7a0", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "d6389c8d1adf900eb8f0e6c8833feafe43dc92d74e5c7ffa6f3950975529d624", + "crates/horizon-world/src/worldgen/biome_predicate.rs": "bfc581bc40077cc74ffda43e990a55fe997adc04c7130f98e039c3305ca79aac", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "82a424d3b20837dc401005f5fe038616659eb17b5bbd78d0c8c29f8bdeb1104a", + "crates/horizon-world/src/worldgen/block_predicate.rs": "074c692367e3f2191a1bb28d87b23402430a843c246bd30a4ea838ee3500280e", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/decoration.rs": "75a79b20b21e133816e729f16e758be6165d0db18a64bfbd5fd3618325a2adf3", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "fe61a5e43179a7588737a71782ea246811fe2c8721e74793e1ac018c8eb93c34", + "crates/horizon-world/src/worldgen/feature_region.rs": "2c78e5f1bdb08307f8d982f231f1abbc3306cd54348d9023b86ee6ed3516fd33", + "crates/horizon-world/src/worldgen/feature_sort.rs": "3488a093dfe1321aaa29d8a30cfb115d8e666a81bf195514e87b170de626835c", + "crates/horizon-world/src/worldgen/fluid_predicate.rs": "e682d13a21f90605215b79f5d254bf2e524d35e89eab2e3b46384709af80b847", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "9218399b4d3757f7bbc550d7729a7201f32a1c83a7030865e0c12aab8a80d116", + "crates/horizon-world/src/worldgen/placement/context.rs": "cd1d2fe305ad4e205e7e01b32128ff895fa8aacc76fa11f200ad6c7c9fba1f49", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "b0397e5818fae84358546193a95f84bcb0b5bffafce909e6fcb3386179ee8023", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/state_provider/catalog.rs": "fa0616353f07460975ab323357ab280b7f35e7bfe2de6edc08d304316766ed26", + "crates/horizon-world/src/worldgen/state_provider/noise.rs": "7ee369c2a032e5620cb9bdf9ee7adad1f70870fb0a27efb7b7c514d92f83491f", + "crates/horizon-world/src/worldgen/state_provider/properties.rs": "9909139aaca1dc4f743957257fadaa9d423d21fa401fa9abc050505f79365139", + "crates/horizon-world/src/worldgen/state_provider.rs": "9cc353d474184f4db880c4305137ec6e35a564a983f602c76af39349ecb58541", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "3358b563db8cb0bc8a9cfbbe2b8b3e70941cd2d37a0b519fbb6545f8d0dcbb69", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "821981c893fc84312351503f2be0c06c681d8bc768dade14576697cf047a9f8f", + "crates/horizon-world/examples/block_properties_fixture.rs": "c5438e5397136631e29858e08eb5c09ad2c82647e20bf1913d7ce9160df530a4" + }, + "fixtures_sha256": { + ".local/rust-block-properties-parity/inputs.txt": "b4d336ea8fc168df652a71651bb48e41e5f23fc22bb451b6969c8021140cfe53", + ".local/rust-block-properties-parity/block-registry.nbt": "5042073c80753f9548cb8fdb5b1000f0e5a1220127a0cc3c6a75737e180bf9bb", + ".local/rust-block-properties-parity/cached-collision.nbt": "f3a5c6a5b2d51dad6c52e486e2b9989e79fd55db1a9bda6196db399550b04078", + ".local/rust-block-properties-parity/block-properties.nbt": "1aba22092f70d16b8092014c058ddc210e4aaa77bac32f6ec62e4d0e91d92a99" + }, + "rust_output_sha256": "235f4a96d29c0753c31b8f142a22383031458be5606f12539b34e6c72217deb6", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "235f4a96d29c0753c31b8f142a22383031458be5606f12539b34e6c72217deb6", + "matched_output_lines": 143361 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "235f4a96d29c0753c31b8f142a22383031458be5606f12539b34e6c72217deb6", + "matched_output_lines": 143361 + } + ], + "scope": "All pinned block-definition force-solid, replaceability, liquid and occlusion flags and raw occlusion geometry are imported privately; Rust computes legacy solidity from cached collision shapes and solid rendering from occlusion geometry. Actual native BlockState isSolid, liquid, canOcclude, isSolidRender and no-context canBeReplaced are compared for every state, together with raw cached bounds and synthetic force-flag/cache/shape threshold combinations using the private native solidity calculator and native full-shape test. Item/fluid replacement, block support, survival, dynamic collision and full gameplay remain pending." +} diff --git a/benchmarks/rust-block-state-codec-2026-10-06/scoped-parity.json b/benchmarks/rust-block-state-codec-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..2c5e1f897 --- /dev/null +++ b/benchmarks/rust-block-state-codec-2026-10-06/scoped-parity.json @@ -0,0 +1,127 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "block_states": 35723, + "blocks": 1286, + "integer_properties": 146, + "codec_inputs": 185538, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java": "5c217a8cb72094020082bd4846ed675a6399b9fa371be95a221bd92d227b2e09", + "tools/test_block_state_codec_parity.py": "51b8174d92fbf2326362141eb66e3c1d4c302bffc3914ce9405b1eb66d8856bb", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "92638c9461715244f9fb9aa4c1830e97f0708cd4195ab0b3ce6bcac19d969f63", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "eba4d1fff21be6748ba93fd917b990dc0928673848ff5251fa9f41c3b42a93d9", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "b8afa733ba6289920d8563dea480bcc7efba04f53a3948d514d2a72ed4177348", + "crates/horizon-world/src/worldgen/material_condition.rs": "dca4498ce95e952334f80b67e6518e1a6ad83b3c7100de532d5a38ea63f75b9e", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "134cf93b53a40fb1ed0e0170c90316c80e270773b2968c63dc3f9cef2c941bff", + "crates/horizon-world/src/worldgen.rs": "a5abb8b8b186c90b12eaa1552c0304c952cf40e4cb0f60d2665b34202154893d", + "crates/horizon-world/examples/block_state_codec_fixture.rs": "c053e44f17b3641bf5c45ed05c2fd0c88c3ac2a20cdf385737502d5a865e7a2b" + }, + "fixtures_sha256": { + ".local/rust-block-state-codec-parity/inputs.txt": "3266a7d8ac5b6afbbcb786f6bd85ba98d876eab589e0d4ed4af9d2212235af5e", + ".local/rust-block-state-codec-parity/facts-client.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b", + ".local/rust-block-state-codec-parity/facts-server.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b" + }, + "rust_output_sha256": "fb4b7c50dcfb93170898f0c378aa3893a6ff8a211c1b8a25725dd898cb45ce5b", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "fb4b7c50dcfb93170898f0c378aa3893a6ff8a211c1b8a25725dd898cb45ce5b", + "matched_output_lines": 221261 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "fb4b7c50dcfb93170898f0c378aa3893a6ff8a211c1b8a25725dd898cb45ce5b", + "matched_output_lines": 221261 + } + ], + "scope": "Actual BlockState.CODEC and FULL_CODEC, every pinned runtime block state, compact/default versus full encoding, canonical object keys, namespaces, property omission/invalid fallback, unknown fields, malformed property containers, Java integer-property parsing including signs/leading zeroes/BMP decimal digits and overflow, invalid identifiers/types, duplicate fields. Registry identities, defaults and integer property kinds are imported from both authenticated JARs and must agree. This ports codec behavior over that metadata, not block gameplay. Native warning text, arbitrary malformed JSON/unpaired surrogate text, registry lifecycle/ownership and full material-rule codecs remain pending." +} diff --git a/benchmarks/rust-block-support-2026-10-06/scoped-parity.json b/benchmarks/rust-block-support-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..9d1e28341 --- /dev/null +++ b/benchmarks/rust-block-support-2026-10-06/scoped-parity.json @@ -0,0 +1,172 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "registry_states": 35723, + "cached_states": 35524, + "uncached_states": 199, + "support_queries": 639432, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSupportOracle.java": "7ffafa1a5769872b32652d2f29ed94a9a514a18d7dabc96f46d8776e27cc8fdb", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java": "02acfbae94aee306c5a4e1db7c86c68f7d6156ddd3dd477dc9e9d06e5ca98118", + "tools/test_block_support_parity.py": "48bc64c5a75e1b0a8821412e0318401aacc711700c6032c49effd56a7e2d444e", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/face.rs": "f243bce81384040a95ce7984b02b5699206c596c537b2713097e86005b4d3a5c", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "e8d88a763de1525f77a30b99591641e8a8b80946263acbde035a9bcc356df960", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/block_properties.rs": "e74b368012d4d440dcdbd4d9bcaf80495220b90557f0e0c733b0aa21ad03c53c", + "crates/horizon-world/src/block_support.rs": "1c8676c3e85743bc8f64ba30bea52842703e4acce312da8389a5761d0cd112e3", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "05313e0c1f3089524fe029f9aac3e439cd47f1c9584c8c7e154c9adcfa88c335", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/entity_obstruction.rs": "a4b28a19bf83b23611c59d94535c488db37e4aee24b22c973c545910894a809f", + "crates/horizon-world/src/fluid.rs": "8a2834a9347ee2c2db7cf1c86a064907ec06e9ac16ba9cc3936e315fc4ad49ca", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "9f1c2f81745412ccdac0ddf7b5edd33077059e14d498ff8e6b6b385b0a8c9f6a", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "3fe316b875aa32683759c337dc71f624910faf0812a2d6d83b8098d6d0bac7a0", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "d6389c8d1adf900eb8f0e6c8833feafe43dc92d74e5c7ffa6f3950975529d624", + "crates/horizon-world/src/worldgen/biome_predicate.rs": "bfc581bc40077cc74ffda43e990a55fe997adc04c7130f98e039c3305ca79aac", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "7c8f628601a6d835d913c034b0d421a8f83bee6c569033448aac99123ed84a2c", + "crates/horizon-world/src/worldgen/block_predicate.rs": "b5c02b44e759a121d8b4a977e2c52874ab2eaf3aa787a15bae7f5c7eaa2ce503", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/decoration.rs": "75a79b20b21e133816e729f16e758be6165d0db18a64bfbd5fd3618325a2adf3", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "fe61a5e43179a7588737a71782ea246811fe2c8721e74793e1ac018c8eb93c34", + "crates/horizon-world/src/worldgen/feature_region.rs": "2c78e5f1bdb08307f8d982f231f1abbc3306cd54348d9023b86ee6ed3516fd33", + "crates/horizon-world/src/worldgen/feature_sort.rs": "3488a093dfe1321aaa29d8a30cfb115d8e666a81bf195514e87b170de626835c", + "crates/horizon-world/src/worldgen/fluid_predicate.rs": "e682d13a21f90605215b79f5d254bf2e524d35e89eab2e3b46384709af80b847", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "2f9849fcd492d0b987a15857607004a95380deff4217c48cbbf02a27339b3aa3", + "crates/horizon-world/src/worldgen/placement/context.rs": "bc0ad613ba599b825bdc3e746b6618e5d427d01e0729287269d452e4c7018143", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "b0397e5818fae84358546193a95f84bcb0b5bffafce909e6fcb3386179ee8023", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/state_provider/catalog.rs": "fa0616353f07460975ab323357ab280b7f35e7bfe2de6edc08d304316766ed26", + "crates/horizon-world/src/worldgen/state_provider/noise.rs": "7ee369c2a032e5620cb9bdf9ee7adad1f70870fb0a27efb7b7c514d92f83491f", + "crates/horizon-world/src/worldgen/state_provider/properties.rs": "9909139aaca1dc4f743957257fadaa9d423d21fa401fa9abc050505f79365139", + "crates/horizon-world/src/worldgen/state_provider.rs": "647f253a7d14d724086b4d146f26295e0da825df86f4adbd6a0e367d5198f3d5", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "3358b563db8cb0bc8a9cfbbe2b8b3e70941cd2d37a0b519fbb6545f8d0dcbb69", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "821981c893fc84312351503f2be0c06c681d8bc768dade14576697cf047a9f8f", + "crates/horizon-world/examples/block_support_fixture.rs": "a459611c5f0ba22d7f9d3b964ff877dbfa513e5db1cf6e9f5114a73e746fa8ce" + }, + "fixtures_sha256": { + ".local/rust-block-support-parity/block-registry.nbt": "5042073c80753f9548cb8fdb5b1000f0e5a1220127a0cc3c6a75737e180bf9bb", + ".local/rust-block-support-parity/cached-support.nbt": "b6fdc9471b0b61e904206d3f099f4dc235aad6d723536c210be0cb7c3560d82c" + }, + "rust_output_sha256": "6489ad4b567eefca4a3b1c1253b80f19b039a6cec8c5fa56e1d82c569be4d9f8", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "6489ad4b567eefca4a3b1c1253b80f19b039a6cec8c5fa56e1d82c569be4d9f8", + "matched_output_lines": 248867 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "6489ad4b567eefca4a3b1c1253b80f19b039a6cec8c5fa56e1d82c569be4d9f8", + "matched_output_lines": 248867 + } + ], + "scope": "All 35,524 cached block-state support shapes are imported privately and Rust derives FULL/CENTER/RIGID face-support masks. These are compared with actual BlockState.isFaceSturdy cache results across all six directions; all 199 uncached states remain explicitly unsupported. Registry/DataVersion/kind validation, shared shape identities, exact face geometry and full-state queries are covered. Dynamic support selection, block survival and full gameplay remain pending." +} diff --git a/benchmarks/rust-block-survival-2026-10-06/scoped-parity.json b/benchmarks/rust-block-survival-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..c7fe41a50 --- /dev/null +++ b/benchmarks/rust-block-survival-2026-10-06/scoped-parity.json @@ -0,0 +1,192 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "supported_blocks": 1274, + "supported_states": 34758, + "survival_rules": 54, + "survival_rule_kinds": 42, + "fluid_tag_files": 10, + "fixtures": 4501019, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSurvivalOracle.java": "dcbaacd909f0ae33d20957e21306dc1e060f428ea5bff2bd2f3833ce8f131b6f", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPropertiesOracle.java": "82e5cadbcdcba5b4577c56c5a033262b066ccc4cc4a14c7c48ce46c4c6247a03", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSupportOracle.java": "04350901a2d708fb8fa672de61d058f73f332d2e90df1b93a67781862f89c1ad", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java": "5c217a8cb72094020082bd4846ed675a6399b9fa371be95a221bd92d227b2e09", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java": "02acfbae94aee306c5a4e1db7c86c68f7d6156ddd3dd477dc9e9d06e5ca98118", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java": "145c943637ed177cc4ef8a85f2484da8afd164868e84a8463882feec1653a860", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_block_survival_parity.py": "5ebed710b5674e535a6cbb616878824efe89c53bca53e114c3d2ec9e7da619c1", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/face.rs": "f243bce81384040a95ce7984b02b5699206c596c537b2713097e86005b4d3a5c", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "e8d88a763de1525f77a30b99591641e8a8b80946263acbde035a9bcc356df960", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/block_properties.rs": "e74b368012d4d440dcdbd4d9bcaf80495220b90557f0e0c733b0aa21ad03c53c", + "crates/horizon-world/src/block_support.rs": "ade4fbd47284b450dabdd682dc86138b2ac05a0fd379525d7110648908245476", + "crates/horizon-world/src/block_survival.rs": "b0fccfd7b44976b3cf27316da1ce0b202d5aa6a5574e821c36e79952d23026a2", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "05313e0c1f3089524fe029f9aac3e439cd47f1c9584c8c7e154c9adcfa88c335", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/dynamic_support.rs": "1bf4ad95fcdf7f2df4e33dde38e08959d9b76a6260838c13e97c2bb59e006294", + "crates/horizon-world/src/entity_obstruction.rs": "a4b28a19bf83b23611c59d94535c488db37e4aee24b22c973c545910894a809f", + "crates/horizon-world/src/fluid.rs": "8a2834a9347ee2c2db7cf1c86a064907ec06e9ac16ba9cc3936e315fc4ad49ca", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "69cdc611b7a7e20a7da705fcc25de6b97cdb64cf63f954be49d0a11f9a820465", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/piston_shape.rs": "399c2337103b8e7e0eb5667227c5aa14f9549d6a467b7be7da3d0717f0263500", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "3fe316b875aa32683759c337dc71f624910faf0812a2d6d83b8098d6d0bac7a0", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "d6389c8d1adf900eb8f0e6c8833feafe43dc92d74e5c7ffa6f3950975529d624", + "crates/horizon-world/src/worldgen/biome_predicate.rs": "bfc581bc40077cc74ffda43e990a55fe997adc04c7130f98e039c3305ca79aac", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "6be7c0161cecf1362c196e91ecbeb166e16c8da3731d988ce8f2308f06209265", + "crates/horizon-world/src/worldgen/block_predicate.rs": "074c692367e3f2191a1bb28d87b23402430a843c246bd30a4ea838ee3500280e", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/decoration.rs": "75a79b20b21e133816e729f16e758be6165d0db18a64bfbd5fd3618325a2adf3", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "fe61a5e43179a7588737a71782ea246811fe2c8721e74793e1ac018c8eb93c34", + "crates/horizon-world/src/worldgen/feature_region.rs": "2c78e5f1bdb08307f8d982f231f1abbc3306cd54348d9023b86ee6ed3516fd33", + "crates/horizon-world/src/worldgen/feature_sort.rs": "3488a093dfe1321aaa29d8a30cfb115d8e666a81bf195514e87b170de626835c", + "crates/horizon-world/src/worldgen/fluid_predicate.rs": "e682d13a21f90605215b79f5d254bf2e524d35e89eab2e3b46384709af80b847", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "9218399b4d3757f7bbc550d7729a7201f32a1c83a7030865e0c12aab8a80d116", + "crates/horizon-world/src/worldgen/placement/context.rs": "cd1d2fe305ad4e205e7e01b32128ff895fa8aacc76fa11f200ad6c7c9fba1f49", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "b0397e5818fae84358546193a95f84bcb0b5bffafce909e6fcb3386179ee8023", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/state_provider/catalog.rs": "fa0616353f07460975ab323357ab280b7f35e7bfe2de6edc08d304316766ed26", + "crates/horizon-world/src/worldgen/state_provider/noise.rs": "7ee369c2a032e5620cb9bdf9ee7adad1f70870fb0a27efb7b7c514d92f83491f", + "crates/horizon-world/src/worldgen/state_provider/properties.rs": "9909139aaca1dc4f743957257fadaa9d423d21fa401fa9abc050505f79365139", + "crates/horizon-world/src/worldgen/state_provider.rs": "89cb0410899608545aa1ba3b1b4c1babf533fb25efd341feab1c87661f44f7b9", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "3358b563db8cb0bc8a9cfbbe2b8b3e70941cd2d37a0b519fbb6545f8d0dcbb69", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "821981c893fc84312351503f2be0c06c681d8bc768dade14576697cf047a9f8f", + "crates/horizon-world/examples/block_survival_fixture.rs": "a3b53925164b72be53d0d8137c1ee5bb07276cd64be8b20f4cd6dbe2ec4377bd" + }, + "fixtures_sha256": { + ".local/rust-block-survival-parity/inputs.txt": "bed87f9edbe95e9b0c019e1a544bac7c563a10beda8a2a5283b26b0b39e53161", + ".local/rust-block-survival-parity/fluid-tags.json": "f1e5eb6d22ea7effbb118a2282709cfdeef1bfae4516b775a55ad7a4df29d7d0", + ".local/rust-block-survival-parity/survival-placement-classes.json": "7fdbf48ab18c87098bbe1b6176cb81f4842b6c5d9a4d6bbaf7037ff61cb1848c", + ".local/rust-block-survival-parity/survival-support-tags.json": "15d88d5bb5ad10d65124d5abb2cc055d251b06d129bca7be06f55b43dc13f6fd", + ".local/rust-block-survival-parity/facts.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b", + ".local/rust-block-survival-parity/survival-classes.json": "361832008eea0aa9151d367a125a19c6353d99a0b88b27dd0682f55b7954553e", + ".local/rust-block-survival-parity/survival-rules.json": "4360a5430f28eea27c40491352a0400ca29247a5f5e870895a665be08c298716", + ".local/rust-block-survival-parity/tags.json": "36975358262568f32bf84778d63d9989a36e7394ed4796d70a34809a8f4a64f0", + ".local/rust-block-survival-parity/block-registry.nbt": "5042073c80753f9548cb8fdb5b1000f0e5a1220127a0cc3c6a75737e180bf9bb", + ".local/rust-block-survival-parity/cached-collision.nbt": "f3a5c6a5b2d51dad6c52e486e2b9989e79fd55db1a9bda6196db399550b04078", + ".local/rust-block-survival-parity/block-properties.nbt": "699a994c5c0c9f7ee58e35b9c23c4503a5936efe84133643113232f825ae2216", + ".local/rust-block-survival-parity/cached-support.nbt": "b6fdc9471b0b61e904206d3f099f4dc235aad6d723536c210be0cb7c3560d82c" + }, + "rust_output_sha256": "1bd97e34be67e70f536602c085d8fddb294f7b983589a1db2ed129ec8fae8e10", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "1bd97e34be67e70f536602c085d8fddb294f7b983589a1db2ed129ec8fae8e10", + "matched_output_lines": 14574905 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "1bd97e34be67e70f536602c085d8fddb294f7b983589a1db2ed129ec8fae8e10", + "matched_output_lines": 14574905 + } + ], + "scope": "Initial block survival rules are assigned from privately inspected native definition classes and executed in Rust against solid/air/tag tests and unified support geometry. Actual native canSurvive evaluates every supported candidate state, each neighbor state against behavior representatives, changing repeated reads, world-coordinate wrapping, absent/closed/open shulker snapshots, brightness thresholds, independent fluid state sequences and block/entity/light/fluid query failures. Unsupported survival families, full block placement/update behavior and full gameplay remain pending." +} diff --git a/benchmarks/rust-bulk-section-2026-10-06/scoped-parity.json b/benchmarks/rust-bulk-section-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..a0278a0df --- /dev/null +++ b/benchmarks/rust-bulk-section-2026-10-06/scoped-parity.json @@ -0,0 +1,169 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "block_states": 35723, + "block_tag_files": 300, + "fixtures": 8, + "resident_chunks_per_fixture": 4, + "operations": { + "has": 56, + "get": 72022, + "set": 71966, + "world": 71966, + "height": 32, + "reset": 8 + }, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBulkSectionOracle.java": "aa235a47cfa64e4daf3c38901f80534957e4418e4cba1b726deaedd83ce5289f", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java": "145c943637ed177cc4ef8a85f2484da8afd164868e84a8463882feec1653a860", + "tools/test_bulk_section_parity.py": "f3e1415ec54a42e04406f278375eec0a0d7b4dff7e4e550e630a3b4453b90f55", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "c215156f2ecf7faf214b3d89e0829b65d54f4ff6d134d778ec941f18a606a327", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "2297b194514925688dba25016a69d5ba5eb8b869bdfff28f2e611a6742ac5954", + "crates/horizon-world/src/worldgen/feature_region.rs": "4a95a30c0987d97e671f84380e13ddea070ad81f996baa65b2a06c4d892971c7", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "1b976aa4dd2516468196d0af3451e3fdd037493a14d269f54ebdd7254055e05e", + "crates/horizon-world/src/worldgen/placement/context.rs": "b36dfd9297896e62770f2085cf934fc08ebd4c030ecc7ae17d864e819a113201", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "68ecf36954fea5705436d486e9be93836933fd56779022afeb881a0399d6a674", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "828ef13e9d498037598d2ea86e3b46fa2713a35818ddac1d883b04ecceefd5ce", + "crates/horizon-world/examples/bulk_section_fixture.rs": "543dcae1cda92b0a14fd00c853f55c1af516240def6bdcd2612539b0ed955157" + }, + "fixtures_sha256": { + ".local/rust-bulk-section-parity/inputs.txt": "44b1c8c133d9c868bbdbe5fd577c01e6a5e1fa6382731211dcb35919975eff60", + ".local/rust-bulk-section-parity/tags.json": "36975358262568f32bf84778d63d9989a36e7394ed4796d70a34809a8f4a64f0", + ".local/rust-bulk-section-parity/facts-client.json": "1d24883ee807b0b71473f0bbf8ed548ddaf712148caeb3fcc7aa13ab973a97b0", + ".local/rust-bulk-section-parity/facts-server.json": "1d24883ee807b0b71473f0bbf8ed548ddaf712148caeb3fcc7aa13ab973a97b0" + }, + "rust_output_sha256": "2628afc7a43f0eda9513298cb5a05dd1e0a225e7ae4e643b2dec03f21beb068f", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "2628afc7a43f0eda9513298cb5a05dd1e0a225e7ae4e643b2dec03f21beb068f", + "matched_output_lines": 959640 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "2628afc7a43f0eda9513298cb5a05dd1e0a225e7ae4e643b2dec03f21beb068f", + "matched_output_lines": 959640 + } + ], + "scope": "Actual BulkSectionAccess over resident ProtoChunks: raw reads/writes, all-air chunk-read collapse, outside-height AIR, absent sections, missing neighbors, packed-key caching and aliasing, cache reset and complete final raw sections/heightmap words. Every pinned block state is inserted and read with both preprimed and lazy heightmaps. Rust holds an exclusive region borrow instead of Java section acquire/release locks. Concurrent ownership, ordinary ore geometry, region side effects and complete gameplay remain pending." +} diff --git a/benchmarks/rust-canyon-carver-2026-10-06/scoped-parity.json b/benchmarks/rust-canyon-carver-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..c548896a0 --- /dev/null +++ b/benchmarks/rust-canyon-carver-2026-10-06/scoped-parity.json @@ -0,0 +1,146 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 508, + "carve_attempts": 924, + "bundled_canyon_definitions": 1, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCanyonCarverOracle.java": "d8456c8f79a1d9094ddfd2b83a73c2e6593c5bb2eeca69227326b1cb47c817b7", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java": "226628d98b89aadbdd374936575d033945e7064a900dbb050c662204dbc7e119", + "tools/test_canyon_carver_parity.py": "0a69288d2acb4f7b467ce7104bf6f11a432db71e214c61282c5987ffa8243204", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/placement.rs": "54131e84ee04b6605d13584c1fbfd5f8c19e746455577febf6aaeebe5a51c2b1", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "42823918deec5e149dc729a95bfe54aa32d91604098d5eb8452da0162d557d22", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "1ae40b843721d0f1e1c849b984e0a065aacda6e1384e21fc599cda261f996945", + "crates/horizon-world/src/worldgen.rs": "810bac2405b8370d2851df54eca5dcbb7a762492eafaedfce333670707408da5", + "crates/horizon-world/examples/canyon_carver_fixture.rs": "351a20f891b7f87251341336089138200facc660bbe924ac378f25829b4bba2d" + }, + "fixtures_sha256": { + ".local/rust-canyon-carver-parity/inputs.txt": "4b8d8d6d7d309ee3f5b7537848eca0279673d364aca55caaff3072e7288b8bd1", + ".local/rust-canyon-carver-parity/carvers.json": "cff93e18a087786ad09d04c329293a0d7f4c4944cabecb4d618cee2dbc519096" + }, + "rust_output_sha256": "b02ebaf90c2638965b1b890b75ec5b953b5ede9790250a42bb5886eb85035351", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "b02ebaf90c2638965b1b890b75ec5b953b5ede9790250a42bb5886eb85035351", + "matched_output_lines": 1094517 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "b02ebaf90c2638965b1b890b75ec5b953b5ede9790250a42bb5886eb85035351", + "matched_output_lines": 1094517 + } + ], + "scope": "Actual WorldCarver.DIRECT_CODEC, CanyonWorldCarver.isStartChunk and CanyonWorldCarver.carve using the independently authenticated bundled canyon definition. Compares ordered output cells including duplicates, partial output failures, resulting mask intervals and subsequent random longs across repeated invocations. Covers both outer random modes, local legacy streams, height-dependent width factors, horizontal/vertical radius variation, four generation heights, negative/distant/extreme coordinates and adjacent/far origin chunks. Custom shapes exercise width smoothness, path length, degenerate radii and failure branches; malformed selected codec fields are tested. Gaussian/weighted provider codecs, neighbor-carver seeding/biome selection, blending and complete worlds remain outside this scope. Rust bounds paths to 4096 steps, height to 4064 and total candidates to 2^24 per invocation." +} diff --git a/benchmarks/rust-carving-geometry-2026-10-06/scoped-parity.json b/benchmarks/rust-carving-geometry-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..b579052ea --- /dev/null +++ b/benchmarks/rust-carving-geometry-2026-10-06/scoped-parity.json @@ -0,0 +1,141 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 15, + "ellipsoids": 690, + "reach_queries": 5536, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingGeometryOracle.java": "558ac2108421822d7def914969e99ff10a44ca9ff63932e747f5d0a1d8946ef2", + "tools/test_carving_geometry_parity.py": "5c6548495da71606ab5e47d12acf8633c6713e79662193d48a1fc7f030bee208", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/carver.rs": "0a75ec71570f80f8800c349c3b612e0d0bc35b6009d1b66a0ae1056be1eb8e3a", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/height_provider.rs": "c9a148cdbd392b4ae998e466120c0870eb121736366a160347e1a697bdad914f", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "42823918deec5e149dc729a95bfe54aa32d91604098d5eb8452da0162d557d22", + "crates/horizon-world/src/worldgen/value_provider.rs": "7083e7a494894e080c252e7fb485651eb9f54e72043122e4f2b5bee5749e6184", + "crates/horizon-world/src/worldgen.rs": "58527080379e82d834763d661ebf51fb8f9a83f6d530c85ddf26bf0ea2d53f7d", + "crates/horizon-world/examples/carving_geometry_fixture.rs": "acf2c1b2c0c55726a6adbe185adb81505e163100e11ef739d8dcec60bda9f25b" + }, + "fixtures_sha256": { + ".local/rust-carving-geometry-parity/inputs.txt": "a3ccf40f7eec666483d901d3de637ba37badb306652f43fc60159fdaa8a702b2", + ".local/rust-carving-geometry-parity/reach.txt": "fb9945ca459d53d1c07c39b53d3a98628f65a3caa90954255c66e0d010aa9647" + }, + "rust_output_sha256": "4b40510463e96accae26cfd7cbf617b15b8fc6a53d704040674ea444a25dae6a", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "4b40510463e96accae26cfd7cbf617b15b8fc6a53d704040674ea444a25dae6a", + "matched_output_lines": 106699 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "4b40510463e96accae26cfd7cbf617b15b8fc6a53d704040674ea444a25dae6a", + "matched_output_lines": 106699 + } + ], + "scope": "Actual WorldCarver.carveEllipsoid and canReach methods. Compares ordered normalized-coordinate skip queries, output cells, partial output on callback failure and resulting mask column runs; canReach includes Java float thickness arithmetic and signed step overflow. Corpus covers negative/extreme/distant chunk coordinates, output-height clipping, small/large/zero/negative radii, boundaries and IEEE NaNs/infinities/subnormals. NaN trace values are canonicalized. This validates shared geometric primitives, not randomized cave/canyon paths, codecs, provider sampling, biome carver selection or complete worlds." +} diff --git a/benchmarks/rust-carving-mask-2026-10-06/scoped-parity.json b/benchmarks/rust-carving-mask-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..cc7b8b436 --- /dev/null +++ b/benchmarks/rust-carving-mask-2026-10-06/scoped-parity.json @@ -0,0 +1,134 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 28, + "operations": 6988, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingMaskOracle.java": "7d6d395e9e8659cb00e6ec7c24f9f0e7f59477198533137f9428eabfb592c7e6", + "tools/test_carving_mask_parity.py": "1f0b8f800ee42a84c69cb3c23a83e1463eb4941f9a996499d0eb665c3ffdc779", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving.rs": "f6042ae85ec6dda6803ff353de035bf00c499f383b6933994a424e0dfe196b93", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "04ac9130138ea4ce67fc43f7701f5036972984724ffcd49bfe857d0693361d87", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "4ab2681a45108e5d2ea6fb761ea1cb7fa40b72833fa6190d2efe34ce29845c21", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "42823918deec5e149dc729a95bfe54aa32d91604098d5eb8452da0162d557d22", + "crates/horizon-world/src/worldgen.rs": "3ea3386996321113027dcf51d918d29d363ac1944b7c146a7f1383d17a50967b", + "crates/horizon-world/examples/carving_mask_fixture.rs": "0e3069cf0b4cabae8b4016e034727465e123cce2fd389acf448bc053106677d0" + }, + "fixtures_sha256": { + ".local/rust-carving-mask-parity/inputs.txt": "07a5dceb375ea41d9d2acd80b5d6951bf16f7829c3c656a785f486d373e6a4cc" + }, + "rust_output_sha256": "854a0f1074132dacec5989aa92fcf38258c84cbc800aabc6d7e580256bf06175", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "854a0f1074132dacec5989aa92fcf38258c84cbc800aabc6d7e580256bf06175", + "matched_output_lines": 45742 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "854a0f1074132dacec5989aa92fcf38258c84cbc800aabc6d7e580256bf06175", + "matched_output_lines": 45742 + } + ], + "scope": "Actual CarvingMask construction, carve, isEmpty and visit methods. Compares packed vertical-run traversal, splitting across columns, dense/sparse masks, duplicate writes, word boundaries, coordinate overflow and positive aliases, negative index failures, callback additions during traversal and mutations retained after visitor failures. Rust bounds height to 1..4064 and positive index growth to 2^24 bits; corpus indices remain below 2^20. This validates masks, not cave/canyon generation, mask application, aquifers, blending or complete terrain generation." +} diff --git a/benchmarks/rust-cave-carver-2026-10-06/scoped-parity.json b/benchmarks/rust-cave-carver-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..27f95ecc1 --- /dev/null +++ b/benchmarks/rust-cave-carver-2026-10-06/scoped-parity.json @@ -0,0 +1,146 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 415, + "carve_attempts": 739, + "bundled_cave_definitions": 3, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCaveCarverOracle.java": "28e029f0d535f8529291124337855c2d7c1b123ec77b7728938e5afeb9be4c3b", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java": "226628d98b89aadbdd374936575d033945e7064a900dbb050c662204dbc7e119", + "tools/test_cave_carver_parity.py": "11ec1ceb25fb0d8ec193d619c8bcc744b2c5a9105c2d3ac769a802f59a5b63d7", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/placement.rs": "54131e84ee04b6605d13584c1fbfd5f8c19e746455577febf6aaeebe5a51c2b1", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "42823918deec5e149dc729a95bfe54aa32d91604098d5eb8452da0162d557d22", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "1ae40b843721d0f1e1c849b984e0a065aacda6e1384e21fc599cda261f996945", + "crates/horizon-world/src/worldgen.rs": "810bac2405b8370d2851df54eca5dcbb7a762492eafaedfce333670707408da5", + "crates/horizon-world/examples/cave_carver_fixture.rs": "2aae82674be65a4fc0e13975b2f4185b66fd73a553784d2fa5be3875c3d65c91" + }, + "fixtures_sha256": { + ".local/rust-cave-carver-parity/inputs.txt": "44cc4a5532fe65dcc38d70f708b8f72dcac4df1b04cafc131c5ffecc5a8588bd", + ".local/rust-cave-carver-parity/carvers.json": "cff93e18a087786ad09d04c329293a0d7f4c4944cabecb4d618cee2dbc519096" + }, + "rust_output_sha256": "bed22be613f5b1d8caa0d75546afb4e6cee33222d8d9b51004acff70e1a03d7d", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "bed22be613f5b1d8caa0d75546afb4e6cee33222d8d9b51004acff70e1a03d7d", + "matched_output_lines": 882005 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "bed22be613f5b1d8caa0d75546afb4e6cee33222d8d9b51004acff70e1a03d7d", + "matched_output_lines": 882005 + } + ], + "scope": "Actual WorldCarver.DIRECT_CODEC, CaveWorldCarver.isStartChunk and CaveWorldCarver.carve using all three independently authenticated bundled cave definitions. Compares ordered output cells including duplicates, partial output failures, resulting mask intervals and subsequent random longs across repeated invocations. Covers both outer random modes, local legacy tunnel streams, rooms, branching, thickness bias, floor thresholds, negative/distant/extreme target coordinates and adjacent/far origin chunks. Explicit custom distributions force path and failure branches; malformed selected codec fields are tested. Gaussian/weighted provider codecs, canyon paths, neighbor-carver seeding/biome selection, blending and complete generated worlds remain outside this scope. Rust bounds count to 4096 and total candidates to 2^24 per invocation." +} diff --git a/benchmarks/rust-chunk-stage-2026-10-06/scoped-parity.json b/benchmarks/rust-chunk-stage-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..66324076a --- /dev/null +++ b/benchmarks/rust-chunk-stage-2026-10-06/scoped-parity.json @@ -0,0 +1,161 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "block_states": 35723, + "block_tag_files": 300, + "fixtures": 32, + "operation_counts": { + "stage": 392, + "set": 151562, + "get": 80086, + "query": 151922, + "dump": 32, + "prime": 120 + }, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkStageOracle.java": "dea4639bd8b0196b0044d30a046d9971200f1fcc32c29b5d2202a996f7dc0161", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java": "145c943637ed177cc4ef8a85f2484da8afd164868e84a8463882feec1653a860", + "tools/test_chunk_stage_parity.py": "655f1fd5e79bddad3a1d2a1b7b51bb61d6e7fce6aece086c32bc0cbacac5acc3", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/placement/chain.rs": "76832dd4f76b44edfcc8bd52d8115f6e30684bfaea0e0b959ba060f07cc3483d", + "crates/horizon-world/src/worldgen/placement/context.rs": "b36dfd9297896e62770f2085cf934fc08ebd4c030ecc7ae17d864e819a113201", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "f9d264985d0ce6a7eb91a4f559661efbecc5a3fe097ce559f6acbcf0132c8c87", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "fa7ef419e62e67c8ff226f45ced1f7cc4e6f1cc583684476cced17be49b8ab46", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "1ae40b843721d0f1e1c849b984e0a065aacda6e1384e21fc599cda261f996945", + "crates/horizon-world/src/worldgen.rs": "edc1d675acc52d264486a3c8c56e93a21ebf2c6a73da912f35b8fa2a7233cdde", + "crates/horizon-world/examples/chunk_stage_fixture.rs": "ea09c70cf987fc5d332ed993de11a553f30a70d40852f22b80b26c555ffcab06" + }, + "fixtures_sha256": { + ".local/rust-chunk-stage-parity/inputs.txt": "401e093fd21a566637a9ee3d28afec5c2f0be6b538eda69ec0a7d184af545c5c", + ".local/rust-chunk-stage-parity/tags.json": "36975358262568f32bf84778d63d9989a36e7394ed4796d70a34809a8f4a64f0", + ".local/rust-chunk-stage-parity/facts-client.json": "1d24883ee807b0b71473f0bbf8ed548ddaf712148caeb3fcc7aa13ab973a97b0", + ".local/rust-chunk-stage-parity/facts-server.json": "1d24883ee807b0b71473f0bbf8ed548ddaf712148caeb3fcc7aa13ab973a97b0" + }, + "rust_output_sha256": "95dbf7a1cade1004b7055dc131e45af8f3cecc1ffe2f194ad816a831bc2d9975", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "95dbf7a1cade1004b7055dc131e45af8f3cecc1ffe2f194ad816a831bc2d9975", + "matched_output_lines": 8090090 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "95dbf7a1cade1004b7055dc131e45af8f3cecc1ffe2f194ad816a831bc2d9975", + "matched_output_lines": 8090090 + } + ], + "scope": "Actual ProtoChunk.setBlockState, direct section reads, heightmap presence/packed data and pre-light persisted-status assignments for empty, structure starts, structure references, biomes, terrain and features. Every pinned block state is inserted/removed under both heightmap groups. Forward/backward status assignments, untouched stale maps, missing-map priming, explicit priming, empty-section AIR writes, cave/void-air collapse, outside-height writes and wrapped X/Z coordinates are compared. Facts are independently exported from both authenticated JARs; block tags are resolved in Rust. This covers stage-dependent mutation and map selection, not the scheduler, persisted metadata, retro-generation, block entities, lighting, whole region behavior or a complete generated world." +} diff --git a/benchmarks/rust-collision-2026-10-05/scoped-parity.json b/benchmarks/rust-collision-2026-10-05/scoped-parity.json new file mode 100644 index 000000000..a0ccf862a --- /dev/null +++ b/benchmarks/rust-collision-2026-10-05/scoped-parity.json @@ -0,0 +1,75 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "inputs_sha256": "ec4d8458f10935a5e68dd27e69af493bd38463eb0a59747741cc7a5bd49957c7", + "rust_output_sha256": "2bc52fdaef3bc6b404642565139555ddb9568d4d669d7c2cb15a21d475f0b796", + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java": "02acfbae94aee306c5a4e1db7c86c68f7d6156ddd3dd477dc9e9d06e5ca98118", + "tools/test_collision_parity.py": "2ca10b21bf94146ef62cb79ce2e38b753d1565c4f34da7c9f6a887805253d853", + "tools/test_rust_parity.py": "500652427164c7e067a5eb69310ec81f843d5fe37a7c9d88edd2b1ca6606020a", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "faae2edce8b573fd32fcb4bd1f898be7d700a5b38479439f5bec96df764688fd", + "crates/horizon-core/Cargo.toml": "09243cac4d45e8b4aaed3a6169bf3ee0e1272fdff4298c43c80d5fff0116d01c", + "crates/horizon-world/Cargo.toml": "e3250c38fb21b149b5ccaf3c90b5c87ff15b2902f5204b7159207ef7fbf229f2", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/parity.rs": "7b455f2181862e1430e7387633c146877c2d317c2ea682c1e6fa64345dbc5885", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "acaa0a51a759e1a08d417538e567847a66b8c9ae6a7434872e1621ed210364b1", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random.rs": "2f304dfb580a6bc1b5c51b048a2fa2a57f73c5f28f5eb2447f925bf138513389", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/lib.rs": "521ed8987f9fc21e9df75206795414871611e5b6acbf3906c26f44a4c6e6115e", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry.rs": "f46065659e60eb5e84ad69b9f3b5e94dc87ee19de16408817e26f23d16b6c7e7", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/examples/collision_fixture.rs": "ee754b5b42e0a51fe0a305b3f4bb56522ff3fffae564180aab8087b1b9e44afc" + }, + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "2bc52fdaef3bc6b404642565139555ddb9568d4d669d7c2cb15a21d475f0b796", + "matched_output_lines": 1097456, + "registry_states": 35723, + "cached_states": 35524, + "uncached_states": 199, + "unique_shapes": 6093, + "unique_grids": 330, + "queries": 213144 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "2bc52fdaef3bc6b404642565139555ddb9568d4d669d7c2cb15a21d475f0b796", + "matched_output_lines": 1097456, + "registry_states": 35723, + "cached_states": 35524, + "uncached_states": 199, + "unique_shapes": 6093, + "unique_grids": 330, + "queries": 213144 + } + ], + "scope": "Pinned no-context cached collision branch only. Registry identity validation, resident section lookup, grids, discrete extrema including empty shapes, greedy boxes, bounds, translated collide, ray hits, closest points and moved cell lookup. Uncached states and entity-context behavior remain unsupported." +} diff --git a/benchmarks/rust-core-2026-10-04/scoped-parity.json b/benchmarks/rust-core-2026-10-04/scoped-parity.json new file mode 100644 index 000000000..94680d453 --- /dev/null +++ b/benchmarks/rust-core-2026-10-04/scoped-parity.json @@ -0,0 +1,44 @@ +{ + "schema": 1, + "minecraft": "26.3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "commands": { + "position": 12375, + "legacy": 23, + "xoroshiro": 23, + "xoroshiro_state": 5, + "storage": 274 + }, + "inputs_sha256": "dbdebadd4b14ec57d198d22f15e196e0cc9a6b88bac6691db702348a769459c1", + "rust_output_sha256": "7801e3274307aab1852d96d996d7f29b1ca1567750d231c5f74c9e3263f84f87", + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCoreOracle.java": "649b8353fcc3c45a3baf8e2d78dc76cfedfd96de36030b0dddfb2305829cd844", + "tools/test_rust_parity.py": "d2d06842abb80d9c718a5bf0e71ab0c098ad4c519b8ef35711e30cf58af140d7", + "crates/horizon-core/src/bin/parity.rs": "7b455f2181862e1430e7387633c146877c2d317c2ea682c1e6fa64345dbc5885", + "crates/horizon-core/src/lib.rs": "deb2e339f78c9f5bd55a1c8a8428f3e37fae93a02268f9a2fc782dc3e27c2869", + "crates/horizon-core/src/position.rs": "8c2a54e912f8c31a774682b3377ca5f2138910350fbf605e760b24e2cbcacfba", + "crates/horizon-core/src/random.rs": "2f304dfb580a6bc1b5c51b048a2fa2a57f73c5f28f5eb2447f925bf138513389", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/Cargo.toml": "1928b71e389c24c506804f0d8e3104976da6feb27d9bfdbb3b55fb7af0c62664", + "Cargo.toml": "9ca59fba126895de9e58952eb5e9421bee0ffdfb5f6d2fcb03d7726e394e7c3f", + "Cargo.lock": "f2b104dbb3f64512b6c72e8d8732b7adda849212689e8c816f9a6abf564f4660" + }, + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "7801e3274307aab1852d96d996d7f29b1ca1567750d231c5f74c9e3263f84f87", + "matched_output_lines": 1017920 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "7801e3274307aab1852d96d996d7f29b1ca1567750d231c5f74c9e3263f84f87", + "matched_output_lines": 1017920 + } + ], + "scope": "Selected integer position, seeded RNG and packed-storage operations only. No gameplay, rendering or performance claim." +} diff --git a/benchmarks/rust-core-2026-10-05/scoped-parity.json b/benchmarks/rust-core-2026-10-05/scoped-parity.json new file mode 100644 index 000000000..67cc61e06 --- /dev/null +++ b/benchmarks/rust-core-2026-10-05/scoped-parity.json @@ -0,0 +1,69 @@ +{ + "schema": 1, + "minecraft": "26.3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "commands": { + "position": 12375, + "legacy": 23, + "xoroshiro": 23, + "xoroshiro_state": 5, + "storage": 274, + "factory": 4400, + "helpers": 5000 + }, + "inputs_sha256": "fa3dce6416a2d2a6e4af89b29715bab9575bb99b18be9c188f777af415383c03", + "rust_output_sha256": "799ae9305fe380b8bc63fc280d9f0222e62d093bfdb8d286305e7414448bb0e7", + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCoreOracle.java": "69d9d3ff45e56122136d6a6f6b8fde0972985c4ced1a052fcb9c44a9df6b3c14", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "86e7a87439acf5458be3c9b6ed5dfc3705170f39483ec0f1c2b723b4f5e3ff28", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "f00ebba7484168ae0064fa993ace9afafb323c3222ab80cfee3792bd98562e8d", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-core/Cargo.toml": "f9aff52d34439ed6511b026beee5cbd9918f34cc0a67e90e441df12c905a6dc0", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "faae2edce8b573fd32fcb4bd1f898be7d700a5b38479439f5bec96df764688fd" + }, + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "799ae9305fe380b8bc63fc280d9f0222e62d093bfdb8d286305e7414448bb0e7", + "matched_output_lines": 1634520 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "799ae9305fe380b8bc63fc280d9f0222e62d093bfdb8d286305e7414448bb0e7", + "matched_output_lines": 1634520 + } + ], + "scope": "Selected integer positions, seeded RNG operations including inclusive/exclusive integer intervals and float/double triangular draws, positional factories, UTF-16 Java string hashing, MD5-derived seeds and packed-storage operations. Floating-point helper NaNs canonicalized; finite results and signed zeros compared by bits. No gameplay, rendering or performance claim." +} diff --git a/benchmarks/rust-decoration-2026-10-06/scoped-parity.json b/benchmarks/rust-decoration-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..649dad3b8 --- /dev/null +++ b/benchmarks/rust-decoration-2026-10-06/scoped-parity.json @@ -0,0 +1,161 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 2188, + "biomes": 67, + "requested_decorations": 4376, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationOracle.java": "ddec65c7fbc798fb40eca1e4b0301c201d8ae90e771e989fdbc8915553973543", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java": "12b1c46cc397755ef6827da777faef3e71c008cafa48403669c03ca2bdc3c7cb", + "tools/test_decoration_parity.py": "6309a586685b3795610b04659b721b8a94e120841d4509112494a81c08733f07", + "tools/test_feature_sort_parity.py": "ba745b738c3181c432c77c939126ed8f41fa7bc0430c1900d909f2ed50e5fdd6", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "c215156f2ecf7faf214b3d89e0829b65d54f4ff6d134d778ec941f18a606a327", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/decoration.rs": "8e29ca35bf432232b47087b162a513e18a5b0ac470461b73ca8444bef7cd9960", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "2297b194514925688dba25016a69d5ba5eb8b869bdfff28f2e611a6742ac5954", + "crates/horizon-world/src/worldgen/feature_region.rs": "4a95a30c0987d97e671f84380e13ddea070ad81f996baa65b2a06c4d892971c7", + "crates/horizon-world/src/worldgen/feature_sort.rs": "3488a093dfe1321aaa29d8a30cfb115d8e666a81bf195514e87b170de626835c", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "9bce6b17b60fec575d810713d9fb2714780aadbbc973db969c07cf4455201847", + "crates/horizon-world/src/worldgen/placement/context.rs": "f8fa467d3b931d0f98d3572fbc80c659d452a7fc5755d5c98123dc477c2b541c", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "c39c0b5f761fd573ff2f2a1d9d42901305995cc88f5c4ca3a49aaa4ef5dd933b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "d69e6a02e628df1238a253c99b7ee6d1597b8fcd6703795525e0f77fdf1cf47b", + "crates/horizon-world/examples/decoration_fixture.rs": "d195a9edbe2b82694fba45ada3a619340506d441d4063aedf8111c1ccfde6df7" + }, + "fixtures_sha256": { + ".local/rust-decoration-parity/inputs.txt": "3ead79dc3276a770c3c2a70fe080e355ca9e45af763f927cd82e9eb5475fbad0", + ".local/rust-decoration-parity/biome-features.json": "cc3846a9d2eae7e45ba9fd69f07e37a715ce5cb946c9cdbe8a86a471c8a8a975" + }, + "rust_output_sha256": "7c34f5bf7b39df3d175c5a4e2da4917ce538ed5fa125a88c4b44a43805a964de", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "7c34f5bf7b39df3d175c5a4e2da4917ce538ed5fa125a88c4b44a43805a964de", + "matched_output_lines": 337398 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "7c34f5bf7b39df3d175c5a4e2da4917ce538ed5fa125a88c4b44a43805a964de", + "matched_output_lines": 337398 + } + ], + "scope": "Actual ChunkGenerator.applyBiomeDecoration with structure generation disabled, native ProtoChunk biome palettes, native FeatureSorter and WorldgenRandom, and traced feature sinks. Nine-chunk query order, possible-biome intersection, sorted global feature indices, decoration/feature seeds, biome-check placement, repeated calls, ignored false results, progress markers and partial failures are compared. All 67 bundled biome feature lists participate with synthetic payloads. Rust owns immutable generation settings and delegates resident palette transport and feature callbacks. Structure decoration, complete registry/world region integration, all feature algorithms, crash-report formatting and full gameplay remain pending." +} diff --git a/benchmarks/rust-decoration-region-2026-10-06/scoped-parity.json b/benchmarks/rust-decoration-region-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..c6915af64 --- /dev/null +++ b/benchmarks/rust-decoration-region-2026-10-06/scoped-parity.json @@ -0,0 +1,178 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "block_states": 35723, + "block_tag_files": 300, + "fixtures": 240, + "biome_zoom": true, + "resident_chunks_per_fixture": 9, + "requested_decorations": 480, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationRegionOracle.java": "9c67be65ec6b7c86850fce4277a930fba9b613e416cd749b33989b75d34ee971", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java": "145c943637ed177cc4ef8a85f2484da8afd164868e84a8463882feec1653a860", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java": "12b1c46cc397755ef6827da777faef3e71c008cafa48403669c03ca2bdc3c7cb", + "tools/test_decoration_region_parity.py": "d85b316b4fca4f71239b8e6edf7fad4be4e7be972b108450d62ec96bea8a3196", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_feature_region_parity.py": "fceba45d5aa9bb2c137350f1df70f4ba64ea65c4179a50920e713a2669bf4e28", + "tools/test_decoration_parity.py": "6309a586685b3795610b04659b721b8a94e120841d4509112494a81c08733f07", + "tools/test_feature_sort_parity.py": "ba745b738c3181c432c77c939126ed8f41fa7bc0430c1900d909f2ed50e5fdd6", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/fluid.rs": "8a2834a9347ee2c2db7cf1c86a064907ec06e9ac16ba9cc3936e315fc4ad49ca", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5e93b751c43417dc0a5eac05f4389c8097959e1df3b307e499a7b3e4403c6584", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "3fe316b875aa32683759c337dc71f624910faf0812a2d6d83b8098d6d0bac7a0", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "d6389c8d1adf900eb8f0e6c8833feafe43dc92d74e5c7ffa6f3950975529d624", + "crates/horizon-world/src/worldgen/biome_predicate.rs": "bfc581bc40077cc74ffda43e990a55fe997adc04c7130f98e039c3305ca79aac", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "d8b2d3f19f49a0a60c913596f5a8f5fcb5be2e8633c9910e4e583e5d85916bde", + "crates/horizon-world/src/worldgen/block_predicate.rs": "95997ad124f4ee85abf02c8a1058cf9fb5e6d0289f4ef6721e532ae39c886640", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/decoration.rs": "75a79b20b21e133816e729f16e758be6165d0db18a64bfbd5fd3618325a2adf3", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "fe61a5e43179a7588737a71782ea246811fe2c8721e74793e1ac018c8eb93c34", + "crates/horizon-world/src/worldgen/feature_region.rs": "2c78e5f1bdb08307f8d982f231f1abbc3306cd54348d9023b86ee6ed3516fd33", + "crates/horizon-world/src/worldgen/feature_sort.rs": "3488a093dfe1321aaa29d8a30cfb115d8e666a81bf195514e87b170de626835c", + "crates/horizon-world/src/worldgen/fluid_predicate.rs": "e682d13a21f90605215b79f5d254bf2e524d35e89eab2e3b46384709af80b847", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "4b5a908d6572ba166b82e232927ad884f0d6cf1ca997c8a4c89f41fd15370041", + "crates/horizon-world/src/worldgen/placement/context.rs": "6d450931cdeab1427253a19baa5184c1b70cfaecb1ee3f60d5400f083b96e682", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "b0397e5818fae84358546193a95f84bcb0b5bffafce909e6fcb3386179ee8023", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/state_provider/catalog.rs": "fa0616353f07460975ab323357ab280b7f35e7bfe2de6edc08d304316766ed26", + "crates/horizon-world/src/worldgen/state_provider/noise.rs": "7ee369c2a032e5620cb9bdf9ee7adad1f70870fb0a27efb7b7c514d92f83491f", + "crates/horizon-world/src/worldgen/state_provider/properties.rs": "9909139aaca1dc4f743957257fadaa9d423d21fa401fa9abc050505f79365139", + "crates/horizon-world/src/worldgen/state_provider.rs": "64a9ecb17f3567d5928de9959702a8f45e75b36a3227342ef392a8f840d18d18", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "3358b563db8cb0bc8a9cfbbe2b8b3e70941cd2d37a0b519fbb6545f8d0dcbb69", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "821981c893fc84312351503f2be0c06c681d8bc768dade14576697cf047a9f8f", + "crates/horizon-world/examples/decoration_region_fixture.rs": "f22941c968628c13326890abb627223092ded53565db234be0867b56bc126749", + "crates/horizon-world/examples/support/decoration_storage.rs": "feb724e80bbcc1f66b671881ce58875f9bb419434dbd83b90475488e6e0bda99" + }, + "fixtures_sha256": { + ".local/rust-decoration-region-parity/inputs.txt": "cd00683424d45ef1edbd39dc5be3001554e182b3b9fca220f4feb18fef339cbf", + ".local/rust-decoration-region-parity/tags.json": "36975358262568f32bf84778d63d9989a36e7394ed4796d70a34809a8f4a64f0", + ".local/rust-decoration-region-parity/facts-client.json": "1d24883ee807b0b71473f0bbf8ed548ddaf712148caeb3fcc7aa13ab973a97b0", + ".local/rust-decoration-region-parity/facts-server.json": "1d24883ee807b0b71473f0bbf8ed548ddaf712148caeb3fcc7aa13ab973a97b0" + }, + "rust_output_sha256": "5065d7e427a570e65b844e13d2a98f2127b62d87ab501cd68b9b5ea47b41638b", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "5065d7e427a570e65b844e13d2a98f2127b62d87ab501cd68b9b5ea47b41638b", + "matched_output_lines": 36173951 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "5065d7e427a570e65b844e13d2a98f2127b62d87ab501cd68b9b5ea47b41638b", + "matched_output_lines": 36173951 + } + ], + "scope": "Actual ChunkGenerator.applyBiomeDecoration with structures disabled executes three native basic features, configured fill-layer sequences, replacements and scattered ore into nine ProtoChunks. Biome palettes, native BiomeManager zoom, possible-biome selection, FeatureSorter order, WorldgenRandom seeding, biome filters, registry-bound matching-biome predicates, ordered volume predicates and graph composition share resident terrain. Both pre-light heightmap groups, mixed/uniform biome neighborhoods, count/square/heightmap/layered chains, repeated decoration, rejected writes and partial failures are compared. Ordered writes, current-feature markers, complete final raw sections and all heightmap presence/data are checked. Rust uses resident BiomeRegion and TerrainRegion with caller-owned biome membership/write effects. Actual WorldGenRegion write-zone policy, POIs, block entities, postprocessing, lighting, structures, remaining feature algorithms, complete noise-to-decoration lifecycle and gameplay remain pending." +} diff --git a/benchmarks/rust-density-2026-10-05/scoped-parity.json b/benchmarks/rust-density-2026-10-05/scoped-parity.json new file mode 100644 index 000000000..98ad5e490 --- /dev/null +++ b/benchmarks/rust-density-2026-10-05/scoped-parity.json @@ -0,0 +1,159 @@ +{ + "schema": 1, + "minecraft": "26.3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "commands": { + "constant": 336, + "query": 931724, + "volume": 225642, + "gradient": 2041, + "noise": 272, + "shift": 1200, + "unary": 3168, + "binary": 2408, + "choice": 1250, + "lerp": 1216, + "interval": 1000, + "bounds": 41176, + "offset": 816, + "blended": 192, + "distance": 320, + "metric": 12000, + "blendfail": 10, + "blendfbm": 256, + "counted": 3120, + "cache": 532, + "context": 34805, + "counts": 532632, + "lookup": 10000, + "slice": 384, + "interpolate": 384, + "surface": 384, + "spconstant": 78, + "spsampler": 330, + "spfail": 4, + "sppoints": 768, + "sprange": 13536, + "greset": 368, + "gconst": 3414, + "ggradient": 672, + "gbind": 768, + "gcache": 2870, + "gsame": 1808, + "gslice": 272, + "gunary": 832, + "gbinary": 960, + "gclamp": 384, + "gchoice": 128, + "glerp": 128, + "ginterp": 368, + "gsurface": 256, + "ginfo": 17906, + "gtry": 3900, + "gcompile": 18282, + "gdistance": 128, + "ginterval": 1024, + "gsconstant": 1120, + "gspline": 2160, + "gspoints": 1456, + "gseed": 70, + "gregister": 326, + "gready": 70, + "ginstance": 640, + "goffset": 262, + "gnoise": 838, + "gblended": 64, + "gend": 128, + "round": 1576, + "ground": 880, + "power": 1456, + "gpow": 1552, + "wfield": 96, + "blenddensity": 96, + "wcontext": 20416, + "gwfield": 96, + "gblenddensity": 176, + "gref": 288, + "gnamed": 224, + "glookup": 64 + }, + "inputs_sha256": "3bb59de57994936c7347c504b212900f9ec7c3c3eff1f0e49c051b46d23bed97", + "rust_output_sha256": "e1fcf55d697acd4d0f6470079416c5cae2cbc75d524f8f7aee50b5555f2c330d", + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDensityOracle.java": "0be907c58f2bb35f924b1c42919397cdfc0c38f7be500e26c5d462f46aaf1f08", + "tools/test_density_parity.py": "ab052eb065a0ae0c0469e95335b952153adbb01f46b5d12ad075fc1a5a8ec0d0", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "69f89566a78456c29caaa39dacedfe711ca59e49b78f64e68b0414fb6a73d8fc", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-core/tests/density_world_fields.rs": "e193e45080817ef92547828a8d106482a376b9f788e39d4d3831f44e9d693148", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "faae2edce8b573fd32fcb4bd1f898be7d700a5b38479439f5bec96df764688fd" + }, + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "e1fcf55d697acd4d0f6470079416c5cae2cbc75d524f8f7aee50b5555f2c330d", + "matched_output_lines": 15524627 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "e1fcf55d697acd4d0f6470079416c5cae2cbc75d524f8f7aee50b5555f2c330d", + "matched_output_lines": 15524627 + } + ], + "scope": "Compiled constant, clamped/repeated/mirrored gradient, unshifted and XZ/XYZ shifted noise, all eleven vanilla unary operators and constant-operand specializations, binary arithmetic/min/max, power with constant base/exponent samplers, floor/nearest/ceil/truncate rounding to integer or sampled multiples, range choice and linear interpolation with constant-branch/endpoint specializations; multi-threshold and single-threshold selection; shift/shift-A/shift-B offset samplers; old blended terrain noise definition ranges, ordered smeared FBM construction, scalar/bulk composition and failure RNG state; distance metrics and distance-to-point samplers with wrapped differences; cached and uncached density contexts, nested cache nodes, scalar/volume hits, packed-coordinate key collisions, NaN misses and zero-initialized failure buffers, exact lattice lookup; X/Y/Z and combined XZ slices, reduced-volume bulk evaluation, unchanged-volume delegation, nested and cached children; positive-cell grid interpolation with aligned delegation, eight-corner scalar sampling, repeated-addition bulk columns and dense-then-strided selection; raw and Y=0-sliced surface-height search with scalar density probes, bulk upper bounds, strict positive crossing, saturating floor conversion and wrapped cell alignment, early lower-bound return and single-layer validation; nested cubic splines with endpoint extrapolation, binary interval selection, compact coordinate IDs, lazy scalar/volume coordinate caches, repeated NaN scalar misses and partial output failures, constant-NaN compile rejection and conservative spline range propagation; interval construction, hulls, arithmetic/min/max, reciprocal, abs/square/sign, powers and logarithms, clamp, monotonic endpoint mapping, finite/infinite interpolation, predicates, equality and Java hashes; scalar and strided bulk paths, signed/wrapped integer coordinates, nested child bulk evaluation, unary/leaf buffer tails, exact-volume multi-input buffers, scalar short circuits, NaN/signed-zero differences between scalar and bulk min/max, arithmetic failures and partial writes. Finite outputs and signed zeros compared by bits; NaNs canonicalized. Initial integrated density graph compiler for constants, gradients, all eleven unary and six binary operations, power, rounding, clamp, range choice, lerp, interval selection, distance-to-point, slices, caches, interpolation, surface search, nested cubic splines, registered normal and shifted noise, offset noise, old blended noise and outer End island density: structural interning, range/axis metadata, constant and disjoint-range specialization, uniform-axis slicing, cache-ID allocation/deduplication, memoized roots and failed preparation state are compared with vanilla. Seeded normal-noise lookup, modern/legacy positional factories, named instance reuse, dedicated Nether legacy branches and old blended terrain seed selection are checked against vanilla RandomState's actual compile context. Power samplers retain base/exponent evaluation order, literal-base precedence, sqrt/identity/square/cube exponent specialization, negative-exponent reciprocal composition for sqrt/identity/square/cube and the direct signed-exponent fallback, f64 constant operands, buffer tails and partial writes. Power ranges check exact and interval exponents, signed-zero bases, negative bases with integer exponent bounds, infinite exponents and NaI hulls. Log and square-root graphs check partially invalid domains, range clipping, cache preparation, scalar/bulk composition and trusted bound metadata. Rounding checks positive-infinity ties, int saturation, signed zeros, NaNs, infinite and zero multiples, literal-one specialization, dynamic-multiple child order, declared range propagation, cache preparation and partial input writes on multiple failure. End islands use the dedicated legacy world-seed stream, 17,292 discarded draws, simplex island threshold, truncated negative coordinates, wrapped integer edges, vertical bulk columns and nested/cache/spline/interpolation graphs. Context-bound alpha, offset and structure-density samplers compare fallback/custom fallback, missing/bound fields, declared metadata independent of bindings, same-context delegation, scalar/bulk child calls, failure writes, constant tails, cache namespaces, uniform-axis slicing and nested spline/arithmetic/interpolation graphs. Blend-density wrappers compare absent and actual EMPTY vanilla Blender contexts, input-first evaluation and input metadata propagation; nonempty old-world Blender math remains pending. Direct and registered density holders compare structural value versus holder identity, named lookup, raw delegation and metadata, one-level reference inlining before cache detection, nested holder rewrite replacement, constant specialization, cache allocation/deduplication and memoized roots. Remaining graph definitions, remaining range integration, codecs, world-dependent samplers and terrain integration remain pending; no complete terrain, gameplay, rendering or performance claim." +} diff --git a/benchmarks/rust-dynamic-support-2026-10-06/scoped-parity.json b/benchmarks/rust-dynamic-support-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..2b1faf4b7 --- /dev/null +++ b/benchmarks/rust-dynamic-support-2026-10-06/scoped-parity.json @@ -0,0 +1,182 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "uncached_states": 199, + "collision_fixtures": 60161, + "shulker_progress_fixtures": 13014, + "active_piston_fixtures": 9216, + "fixtures": 107308, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDynamicSupportOracle.java": "d608e197b5b48d3a3ed522e72427610343dede1146e24bf5d17c6f046b480b57", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFaceSupportOracle.java": "9ce939a435842867786fed648951bbe77f6ab843f6df09af15f3deb1948c4877", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java": "5c217a8cb72094020082bd4846ed675a6399b9fa371be95a221bd92d227b2e09", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java": "02acfbae94aee306c5a4e1db7c86c68f7d6156ddd3dd477dc9e9d06e5ca98118", + "tools/test_dynamic_support_parity.py": "6652e6284f7da62787a5fc03332950dba0b2c4b81348d22421617b658d3d7ce1", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/face.rs": "f243bce81384040a95ce7984b02b5699206c596c537b2713097e86005b4d3a5c", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "e8d88a763de1525f77a30b99591641e8a8b80946263acbde035a9bcc356df960", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/block_collision.rs": "cec2af81d212d5eed7a2196e4cf0be2daf4cecf53248f78cc68f2190e4d83f9a", + "crates/horizon-world/src/block_properties.rs": "e74b368012d4d440dcdbd4d9bcaf80495220b90557f0e0c733b0aa21ad03c53c", + "crates/horizon-world/src/block_support.rs": "ade4fbd47284b450dabdd682dc86138b2ac05a0fd379525d7110648908245476", + "crates/horizon-world/src/block_survival.rs": "cf97e26f839a393687922e4b74ecbe140a048ee6eeab98b4d19818e6dc3bea3e", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "05313e0c1f3089524fe029f9aac3e439cd47f1c9584c8c7e154c9adcfa88c335", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/dynamic_support.rs": "e799b31e5120cfdb04e0b342f2097d610ed98ef8c4be031620ee00368d82df59", + "crates/horizon-world/src/entity_obstruction.rs": "a4b28a19bf83b23611c59d94535c488db37e4aee24b22c973c545910894a809f", + "crates/horizon-world/src/fluid.rs": "8a2834a9347ee2c2db7cf1c86a064907ec06e9ac16ba9cc3936e315fc4ad49ca", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "09f697d8d4e709acacc8e9f7c35c5fd307bab6ab0df4a1339fe760afc655cdab", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/piston_shape.rs": "399c2337103b8e7e0eb5667227c5aa14f9549d6a467b7be7da3d0717f0263500", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "3fe316b875aa32683759c337dc71f624910faf0812a2d6d83b8098d6d0bac7a0", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "d6389c8d1adf900eb8f0e6c8833feafe43dc92d74e5c7ffa6f3950975529d624", + "crates/horizon-world/src/worldgen/biome_predicate.rs": "bfc581bc40077cc74ffda43e990a55fe997adc04c7130f98e039c3305ca79aac", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "6be7c0161cecf1362c196e91ecbeb166e16c8da3731d988ce8f2308f06209265", + "crates/horizon-world/src/worldgen/block_predicate.rs": "074c692367e3f2191a1bb28d87b23402430a843c246bd30a4ea838ee3500280e", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/decoration.rs": "75a79b20b21e133816e729f16e758be6165d0db18a64bfbd5fd3618325a2adf3", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "fe61a5e43179a7588737a71782ea246811fe2c8721e74793e1ac018c8eb93c34", + "crates/horizon-world/src/worldgen/feature_region.rs": "2c78e5f1bdb08307f8d982f231f1abbc3306cd54348d9023b86ee6ed3516fd33", + "crates/horizon-world/src/worldgen/feature_sort.rs": "3488a093dfe1321aaa29d8a30cfb115d8e666a81bf195514e87b170de626835c", + "crates/horizon-world/src/worldgen/fluid_predicate.rs": "e682d13a21f90605215b79f5d254bf2e524d35e89eab2e3b46384709af80b847", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "9218399b4d3757f7bbc550d7729a7201f32a1c83a7030865e0c12aab8a80d116", + "crates/horizon-world/src/worldgen/placement/context.rs": "cd1d2fe305ad4e205e7e01b32128ff895fa8aacc76fa11f200ad6c7c9fba1f49", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "b0397e5818fae84358546193a95f84bcb0b5bffafce909e6fcb3386179ee8023", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/state_provider/catalog.rs": "fa0616353f07460975ab323357ab280b7f35e7bfe2de6edc08d304316766ed26", + "crates/horizon-world/src/worldgen/state_provider/noise.rs": "7ee369c2a032e5620cb9bdf9ee7adad1f70870fb0a27efb7b7c514d92f83491f", + "crates/horizon-world/src/worldgen/state_provider/properties.rs": "9909139aaca1dc4f743957257fadaa9d423d21fa401fa9abc050505f79365139", + "crates/horizon-world/src/worldgen/state_provider.rs": "89cb0410899608545aa1ba3b1b4c1babf533fb25efd341feab1c87661f44f7b9", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "3358b563db8cb0bc8a9cfbbe2b8b3e70941cd2d37a0b519fbb6545f8d0dcbb69", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "821981c893fc84312351503f2be0c06c681d8bc768dade14576697cf047a9f8f", + "crates/horizon-world/examples/dynamic_support_fixture.rs": "5ab94e91a419b43d5644f13f7d7e39b3bc60b95f625ae78b43d50543b84997a7" + }, + "fixtures_sha256": { + ".local/rust-dynamic-support-parity/inputs.txt": "2d24447d3bbcd56ab60a6d485fcae13f6e723d57090280a9597ac073763903fe", + ".local/rust-dynamic-support-parity/facts.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b", + ".local/rust-dynamic-support-parity/uncached-states.json": "0e4a57a4ac3e1cde7463b2245d2d76f776d572628eb3ad4a0bbc11184ef7afc3", + ".local/rust-dynamic-support-parity/block-registry.nbt": "5042073c80753f9548cb8fdb5b1000f0e5a1220127a0cc3c6a75737e180bf9bb", + ".local/rust-dynamic-support-parity/cached-collision.nbt": "f3a5c6a5b2d51dad6c52e486e2b9989e79fd55db1a9bda6196db399550b04078" + }, + "rust_output_sha256": "9eee435b8d88db41ae17ff424f122f63e6cda51bdab5f6069160d781b6a038a7", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "9eee435b8d88db41ae17ff424f122f63e6cda51bdab5f6069160d781b6a038a7", + "matched_output_lines": 4867780 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "9eee435b8d88db41ae17ff424f122f63e6cda51bdab5f6069160d781b6a038a7", + "matched_output_lines": 4867780 + } + ], + "scope": "Actual native support-shape and no-entity-context collision selection, block offsets and all support directions/types for the 199 uncached states. Bamboo, speleothem thickness/direction, scaffolding, powder snow and shulker support are compared over coordinate boundaries and privately allocated block-entity snapshots, including animation state, absent/wrong entity types and failures. Collision checks additionally cover exact shulker bounds and shape representation over progress interpolation boundaries and deterministic finite progress pairs. Moving-piston selection also delegates to actual native entity collision generation for active snapshots; Rust composes the independently tested piston algorithm with registry collision shapes across extension/retraction, source heads, progress boundaries, noclip directions and world-query failures. Entity lifecycle, ticking/pushing and full gameplay remain pending." +} diff --git a/benchmarks/rust-entity-obstruction-2026-10-06/scoped-parity.json b/benchmarks/rust-entity-obstruction-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..64dcf886b --- /dev/null +++ b/benchmarks/rust-entity-obstruction-2026-10-06/scoped-parity.json @@ -0,0 +1,164 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 5254, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityObstructionOracle.java": "90fbb4438ac9dbfb0705138ece57bc418ca97e73bddb2fbdfc10609b2aefc42f", + "tools/test_entity_obstruction_parity.py": "769d478003e91902e103503a128f88e7be595462213b78dd1c1ef8b76d96a105", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/entity_obstruction.rs": "a4b28a19bf83b23611c59d94535c488db37e4aee24b22c973c545910894a809f", + "crates/horizon-world/src/fluid.rs": "8a2834a9347ee2c2db7cf1c86a064907ec06e9ac16ba9cc3936e315fc4ad49ca", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "2cfc358d87afa4b6e45247ef799114d33c2e0930f7aa7b2106cd4756ca007f5e", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "3fe316b875aa32683759c337dc71f624910faf0812a2d6d83b8098d6d0bac7a0", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "d6389c8d1adf900eb8f0e6c8833feafe43dc92d74e5c7ffa6f3950975529d624", + "crates/horizon-world/src/worldgen/biome_predicate.rs": "bfc581bc40077cc74ffda43e990a55fe997adc04c7130f98e039c3305ca79aac", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "d8b2d3f19f49a0a60c913596f5a8f5fcb5be2e8633c9910e4e583e5d85916bde", + "crates/horizon-world/src/worldgen/block_predicate.rs": "4f8e0782db36423b4968dfc35633ff5ae4394b3eb6b97fd94c18b8df92a61929", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/decoration.rs": "75a79b20b21e133816e729f16e758be6165d0db18a64bfbd5fd3618325a2adf3", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "fe61a5e43179a7588737a71782ea246811fe2c8721e74793e1ac018c8eb93c34", + "crates/horizon-world/src/worldgen/feature_region.rs": "2c78e5f1bdb08307f8d982f231f1abbc3306cd54348d9023b86ee6ed3516fd33", + "crates/horizon-world/src/worldgen/feature_sort.rs": "3488a093dfe1321aaa29d8a30cfb115d8e666a81bf195514e87b170de626835c", + "crates/horizon-world/src/worldgen/fluid_predicate.rs": "e682d13a21f90605215b79f5d254bf2e524d35e89eab2e3b46384709af80b847", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "2f9849fcd492d0b987a15857607004a95380deff4217c48cbbf02a27339b3aa3", + "crates/horizon-world/src/worldgen/placement/context.rs": "bc0ad613ba599b825bdc3e746b6618e5d427d01e0729287269d452e4c7018143", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "b0397e5818fae84358546193a95f84bcb0b5bffafce909e6fcb3386179ee8023", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/state_provider/catalog.rs": "fa0616353f07460975ab323357ab280b7f35e7bfe2de6edc08d304316766ed26", + "crates/horizon-world/src/worldgen/state_provider/noise.rs": "7ee369c2a032e5620cb9bdf9ee7adad1f70870fb0a27efb7b7c514d92f83491f", + "crates/horizon-world/src/worldgen/state_provider/properties.rs": "9909139aaca1dc4f743957257fadaa9d423d21fa401fa9abc050505f79365139", + "crates/horizon-world/src/worldgen/state_provider.rs": "64a9ecb17f3567d5928de9959702a8f45e75b36a3227342ef392a8f840d18d18", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "3358b563db8cb0bc8a9cfbbe2b8b3e70941cd2d37a0b519fbb6545f8d0dcbb69", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "821981c893fc84312351503f2be0c06c681d8bc768dade14576697cf047a9f8f", + "crates/horizon-world/examples/entity_obstruction_fixture.rs": "1fdb7c690d59fbc8431bb846121f2935c79b69eafc2afbe4250668c0a984302f" + }, + "fixtures_sha256": { + ".local/rust-entity-obstruction-parity/inputs.txt": "dc4094ffbb54a57a36df53927c6b07fbd46338b11c5ce356b4a10544d848afeb" + }, + "rust_output_sha256": "e7f66070f9980b005a79012c408cd32ba0df4bcdee8b7409e4225e48de2f6eb1", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "e7f66070f9980b005a79012c408cd32ba0df4bcdee8b7409e4225e48de2f6eb1", + "matched_output_lines": 15121 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "e7f66070f9980b005a79012c408cd32ba0df4bcdee8b7409e4225e48de2f6eb1", + "matched_output_lines": 15121 + } + ], + "scope": "Actual EntityGetter.isUnobstructed, its default non-spectator query, Entity removal/root-vehicle methods and voxel intersection execute over privately allocated entity snapshots. Empty shapes, excluded identities, spectators, removed/non-building entities, same-root vehicle exclusions, ordered broad-phase queries and selected candidates, thin boxes, boundary contacts, composite shapes and query failures are compared. Entity construction, lifecycle, spatial indexing, vehicle maintenance and full gameplay remain pending." +} diff --git a/benchmarks/rust-face-support-2026-10-06/scoped-parity.json b/benchmarks/rust-face-support-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..5fc447943 --- /dev/null +++ b/benchmarks/rust-face-support-2026-10-06/scoped-parity.json @@ -0,0 +1,167 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 1615, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFaceSupportOracle.java": "9ce939a435842867786fed648951bbe77f6ab843f6df09af15f3deb1948c4877", + "tools/test_face_support_parity.py": "a8d09fd0f2e7d9e5bf651dd86e4fe08ff025c596e0c5e15bea42ec8aadcf1fd9", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/face.rs": "f243bce81384040a95ce7984b02b5699206c596c537b2713097e86005b4d3a5c", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "e8d88a763de1525f77a30b99591641e8a8b80946263acbde035a9bcc356df960", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/block_properties.rs": "e74b368012d4d440dcdbd4d9bcaf80495220b90557f0e0c733b0aa21ad03c53c", + "crates/horizon-world/src/block_support.rs": "1c8676c3e85743bc8f64ba30bea52842703e4acce312da8389a5761d0cd112e3", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "05313e0c1f3089524fe029f9aac3e439cd47f1c9584c8c7e154c9adcfa88c335", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/entity_obstruction.rs": "a4b28a19bf83b23611c59d94535c488db37e4aee24b22c973c545910894a809f", + "crates/horizon-world/src/fluid.rs": "8a2834a9347ee2c2db7cf1c86a064907ec06e9ac16ba9cc3936e315fc4ad49ca", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "9f1c2f81745412ccdac0ddf7b5edd33077059e14d498ff8e6b6b385b0a8c9f6a", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "3fe316b875aa32683759c337dc71f624910faf0812a2d6d83b8098d6d0bac7a0", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "d6389c8d1adf900eb8f0e6c8833feafe43dc92d74e5c7ffa6f3950975529d624", + "crates/horizon-world/src/worldgen/biome_predicate.rs": "bfc581bc40077cc74ffda43e990a55fe997adc04c7130f98e039c3305ca79aac", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "7c8f628601a6d835d913c034b0d421a8f83bee6c569033448aac99123ed84a2c", + "crates/horizon-world/src/worldgen/block_predicate.rs": "b5c02b44e759a121d8b4a977e2c52874ab2eaf3aa787a15bae7f5c7eaa2ce503", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/decoration.rs": "75a79b20b21e133816e729f16e758be6165d0db18a64bfbd5fd3618325a2adf3", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "fe61a5e43179a7588737a71782ea246811fe2c8721e74793e1ac018c8eb93c34", + "crates/horizon-world/src/worldgen/feature_region.rs": "2c78e5f1bdb08307f8d982f231f1abbc3306cd54348d9023b86ee6ed3516fd33", + "crates/horizon-world/src/worldgen/feature_sort.rs": "3488a093dfe1321aaa29d8a30cfb115d8e666a81bf195514e87b170de626835c", + "crates/horizon-world/src/worldgen/fluid_predicate.rs": "e682d13a21f90605215b79f5d254bf2e524d35e89eab2e3b46384709af80b847", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "2f9849fcd492d0b987a15857607004a95380deff4217c48cbbf02a27339b3aa3", + "crates/horizon-world/src/worldgen/placement/context.rs": "bc0ad613ba599b825bdc3e746b6618e5d427d01e0729287269d452e4c7018143", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "b0397e5818fae84358546193a95f84bcb0b5bffafce909e6fcb3386179ee8023", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/state_provider/catalog.rs": "fa0616353f07460975ab323357ab280b7f35e7bfe2de6edc08d304316766ed26", + "crates/horizon-world/src/worldgen/state_provider/noise.rs": "7ee369c2a032e5620cb9bdf9ee7adad1f70870fb0a27efb7b7c514d92f83491f", + "crates/horizon-world/src/worldgen/state_provider/properties.rs": "9909139aaca1dc4f743957257fadaa9d423d21fa401fa9abc050505f79365139", + "crates/horizon-world/src/worldgen/state_provider.rs": "647f253a7d14d724086b4d146f26295e0da825df86f4adbd6a0e367d5198f3d5", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "3358b563db8cb0bc8a9cfbbe2b8b3e70941cd2d37a0b519fbb6545f8d0dcbb69", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "821981c893fc84312351503f2be0c06c681d8bc768dade14576697cf047a9f8f", + "crates/horizon-world/examples/face_support_fixture.rs": "25c2a1505ff3ff323228390d0b059985927bed82173a3ff1a9985ad382e7a563" + }, + "fixtures_sha256": { + ".local/rust-face-support-parity/inputs.txt": "317b3e7d2b9df64adb1ec4e034f7c6951eb6363b627e890794589220a17021d1" + }, + "rust_output_sha256": "7d4af4acb31cf95e8f512fda8a623d047fa4651b3845354cac36f6d7cd2c3a4a", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "7d4af4acb31cf95e8f512fda8a623d047fa4651b3845354cac36f6d7cd2c3a4a", + "matched_output_lines": 595686 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "7d4af4acb31cf95e8f512fda8a623d047fa4651b3845354cac36f6d7cd2c3a4a", + "matched_output_lines": 595686 + } + ], + "scope": "Actual VoxelShape.getFaceShape and nested face slicing, shape identity/cache reuse, exact coordinate metadata, extrema, bounds and decomposition, plus FULL/CENTER/RIGID SupportType algorithms over caller-supplied support shapes. Sparse grids, phantom slice bounds, cube/array lookup, epsilon boundaries and translations are included. Per-block support-shape selection, world/entity context, survival and full gameplay remain pending." +} diff --git a/benchmarks/rust-feature-catalog-2026-10-06/scoped-parity.json b/benchmarks/rust-feature-catalog-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..f7dc0483a --- /dev/null +++ b/benchmarks/rust-feature-catalog-2026-10-06/scoped-parity.json @@ -0,0 +1,181 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 6408, + "worldgen_random_modes": [ + false, + true + ], + "basic_features": 3, + "composition_features": 6, + "definitions": 89, + "block_states": 35723, + "configured_block_features": 3, + "named_features": 9, + "named_placed_features": 14, + "tag_files": 5, + "requested_placements": 12816, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureCatalogOracle.java": "28adc261de263896b32dc7e196bc0091060677b73823d2babbe829a35f1f9f0d", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java": "12b1c46cc397755ef6827da777faef3e71c008cafa48403669c03ca2bdc3c7cb", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java": "5c217a8cb72094020082bd4846ed675a6399b9fa371be95a221bd92d227b2e09", + "tools/test_feature_catalog_parity.py": "2f85e37a24361bd64b0abf8620cb0e3c3b80bf2f69bc9aa1de957e39cb96c547", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/fluid.rs": "8a2834a9347ee2c2db7cf1c86a064907ec06e9ac16ba9cc3936e315fc4ad49ca", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "06aa7b44e1229b3cf50abcf3827f2cacd7ae54321865873bdba0f371cb458b3f", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "d6389c8d1adf900eb8f0e6c8833feafe43dc92d74e5c7ffa6f3950975529d624", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "f8c2ef2de1cfe9a8689a7375d4bf0cc00431484e06f6d4b2b95aabac8fdfffb0", + "crates/horizon-world/src/worldgen/block_predicate.rs": "8513e9d96c8626594b5ee078bf20ccf3de90fc9f9d7123780d1cab5eefb6b5c2", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/decoration.rs": "297524aefeb4567c5f5c0c1678013e44002eb91ca16ee63b51ffacf93f31a095", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "fe61a5e43179a7588737a71782ea246811fe2c8721e74793e1ac018c8eb93c34", + "crates/horizon-world/src/worldgen/feature_region.rs": "2c78e5f1bdb08307f8d982f231f1abbc3306cd54348d9023b86ee6ed3516fd33", + "crates/horizon-world/src/worldgen/feature_sort.rs": "3488a093dfe1321aaa29d8a30cfb115d8e666a81bf195514e87b170de626835c", + "crates/horizon-world/src/worldgen/fluid_predicate.rs": "e682d13a21f90605215b79f5d254bf2e524d35e89eab2e3b46384709af80b847", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "08ee8697f589e96b69653b395238eecd144d51cfec30017214275f9b338d82af", + "crates/horizon-world/src/worldgen/placement/context.rs": "c916b30177e283e8eedfa342dc5282b42c898a2873668b44f59c83501ff866bd", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "b0397e5818fae84358546193a95f84bcb0b5bffafce909e6fcb3386179ee8023", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/state_provider/catalog.rs": "fa0616353f07460975ab323357ab280b7f35e7bfe2de6edc08d304316766ed26", + "crates/horizon-world/src/worldgen/state_provider/noise.rs": "7ee369c2a032e5620cb9bdf9ee7adad1f70870fb0a27efb7b7c514d92f83491f", + "crates/horizon-world/src/worldgen/state_provider/properties.rs": "9909139aaca1dc4f743957257fadaa9d423d21fa401fa9abc050505f79365139", + "crates/horizon-world/src/worldgen/state_provider.rs": "d1097d91b43e30cec38b09365d3ed58f15522b829feb584e255718447e4c68b4", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "3358b563db8cb0bc8a9cfbbe2b8b3e70941cd2d37a0b519fbb6545f8d0dcbb69", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "b08f074f54f451c24795d5dda68968165b84b8d762d244f0444a8d62de61820e", + "crates/horizon-world/examples/feature_catalog_fixture.rs": "fe03581cad3593d7fae403251ec2a1cde0fc87f958cd42a70ec5f3d0c6840715" + }, + "fixtures_sha256": { + ".local/rust-feature-catalog-parity/inputs.txt": "b0ee5e1737bd138c7997086cb20c2324cc63a70a5966aad1372c40264a62d32e", + ".local/rust-feature-catalog-parity/catalog.json": "5dc542269399635bbe3f82deb0916bba9052c62ec9328306f3e70c24f26a4443", + ".local/rust-feature-catalog-parity/facts-client.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b", + ".local/rust-feature-catalog-parity/facts-server.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b" + }, + "rust_output_sha256": "4f6cb77afc2bb55c744e1b3c1b726eeba7655e500ff0df3913e6dc7ce6228f4e", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "4f6cb77afc2bb55c744e1b3c1b726eeba7655e500ff0df3913e6dc7ce6228f4e", + "matched_output_lines": 1734390 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "4f6cb77afc2bb55c744e1b3c1b726eeba7655e500ff0df3913e6dc7ce6228f4e", + "matched_output_lines": 1734390 + } + ], + "scope": "Actual Feature.CODEC and PlacedFeature.CODEC bind named and inline holders through RegistryOps and registered feature/placed-feature snapshots. Native TagLoader resolves ordered nested, duplicate, empty, optional-missing and required-missing placed-feature tags. Root holders, named children, tag lists, mixed inline/named lists, namespace shorthand, unknown names and unselected malformed children are compared. Registry-bound fill-layer, single-block replacement and scattered-ore states execute through named roots, nested tags and composed placement. Registry-bound matching-block/fluid predicates also execute through filters, ordered volumes, environment scans and composed named features against the mutable world, including a flowing-water fill followed by repeated fluid-filtered replacement. Actual feature algorithms, nested placement, ordered world mutations, rejected writes, partial failures and direct and WorldgenRandom-wrapped legacy/xoroshiro streams execute through the same mutable world transport. Rust expands requested immutable resource roots with bounded dependency/node traversal; unused resources, cyclic references, registry reload/lifecycle, encoding, all feature algorithms and complete world generation remain outside this comparison." +} diff --git a/benchmarks/rust-feature-graph-2026-10-06/scoped-parity.json b/benchmarks/rust-feature-graph-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..529fd53d9 --- /dev/null +++ b/benchmarks/rust-feature-graph-2026-10-06/scoped-parity.json @@ -0,0 +1,159 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 3885, + "basic_features": 3, + "composition_features": 6, + "definitions": 105, + "block_states": 5, + "composed_fixtures": 105, + "requested_placements": 7770, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureGraphOracle.java": "27d25432c07f6d9af7b3d5de5f7ea231ae59b9e3439fa83195e9fa05f95ce8ea", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java": "12b1c46cc397755ef6827da777faef3e71c008cafa48403669c03ca2bdc3c7cb", + "tools/test_feature_graph_parity.py": "d12fcefa11c1b6971819157528326fd8f80b28d4c5329c9f13dd567e0e11ee9c", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "4b445c59c37738ce7dd1cb52234b8743fef68642f6ea9fbb41032e4101617dfb", + "crates/horizon-world/src/worldgen/feature_graph.rs": "36a0017782b6d1d4f4fe419698467646cec447838e8b86f96cfc2ed40b632a4f", + "crates/horizon-world/src/worldgen/feature_region.rs": "4a95a30c0987d97e671f84380e13ddea070ad81f996baa65b2a06c4d892971c7", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/placement/chain.rs": "1b976aa4dd2516468196d0af3451e3fdd037493a14d269f54ebdd7254055e05e", + "crates/horizon-world/src/worldgen/placement/context.rs": "b36dfd9297896e62770f2085cf934fc08ebd4c030ecc7ae17d864e819a113201", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "68ecf36954fea5705436d486e9be93836933fd56779022afeb881a0399d6a674", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "c40017f3449b57558921e1c968b4998f9d32d9d16054ef1741a0d8edc4478489", + "crates/horizon-world/examples/feature_graph_fixture.rs": "5999d3902d8980dd46cfe172ab026adba012e33237b0184f7995318c60c6c499" + }, + "fixtures_sha256": { + ".local/rust-feature-graph-parity/inputs.txt": "10a2c498d0b8ca151715c93de61eaf8b04e5b83a882c117eb26627ff5ca183b4", + ".local/rust-feature-graph-parity/facts-client.json": "6c8d9aeb824f4150293f5d6a580d3347d866589b3eeee185a2c18479f5c64b0a", + ".local/rust-feature-graph-parity/facts-server.json": "6c8d9aeb824f4150293f5d6a580d3347d866589b3eeee185a2c18479f5c64b0a" + }, + "rust_output_sha256": "a0e074e6ae8f81d383c33deafce607285c27f461ac970734983018054bee5127", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "a0e074e6ae8f81d383c33deafce607285c27f461ac970734983018054bee5127", + "matched_output_lines": 737779 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "a0e074e6ae8f81d383c33deafce607285c27f461ac970734983018054bee5127", + "matched_output_lines": 737779 + } + ], + "scope": "Actual Feature.DIRECT_CODEC and native no-op, sequence, random-boolean-selector, simple-random-selector and chance-based random-selector and weighted-random-selector features compose three native block-writing features through inline PlacedFeature holders and actual nested FeaturePlacer calls. Ordered writes, reads, flags, accumulated states, boolean results, rejected writes, partial failures, shared randomness and top-level modifier chains are compared. Sequence short-circuiting, selector return propagation and empty/all-zero weighted choices without random draws are included. Named registry holders/tags, encoders, full feature registries and complete generated worlds remain pending. Rust bounds decode depth/nodes/lists, nested execution depth and feature/placed-feature visits; nested modifier-chain execution shares the feature work budget." +} diff --git a/benchmarks/rust-feature-placement-2026-10-06/scoped-parity.json b/benchmarks/rust-feature-placement-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..b0c66f7ae --- /dev/null +++ b/benchmarks/rust-feature-placement-2026-10-06/scoped-parity.json @@ -0,0 +1,160 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 5544, + "modifier_chains": 80, + "requested_placements": 22176, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeaturePlacementOracle.java": "537f5926111131960e2fdf3e5a0c2f21b46fda629286831f9d9528fe1390afe0", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java": "12b1c46cc397755ef6827da777faef3e71c008cafa48403669c03ca2bdc3c7cb", + "tools/test_feature_placement_parity.py": "6b158d8f63296660ecb362310ffd9f1cdadebfe213352bc9acb147ff5c129345", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "c215156f2ecf7faf214b3d89e0829b65d54f4ff6d134d778ec941f18a606a327", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "2297b194514925688dba25016a69d5ba5eb8b869bdfff28f2e611a6742ac5954", + "crates/horizon-world/src/worldgen/feature_region.rs": "4a95a30c0987d97e671f84380e13ddea070ad81f996baa65b2a06c4d892971c7", + "crates/horizon-world/src/worldgen/feature_sort.rs": "0b9d1e1c15d8449125d39e400776b8f28eec7b7cbd047660a94f8cb90160adfe", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "9bce6b17b60fec575d810713d9fb2714780aadbbc973db969c07cf4455201847", + "crates/horizon-world/src/worldgen/placement/context.rs": "f8fa467d3b931d0f98d3572fbc80c659d452a7fc5755d5c98123dc477c2b541c", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "c39c0b5f761fd573ff2f2a1d9d42901305995cc88f5c4ca3a49aaa4ef5dd933b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "55c4317bd9c782378de7c2a7d58be5aa08febc5b8f2f4b86379a39e0ba500b3c", + "crates/horizon-world/examples/feature_placement_fixture.rs": "0c46c49a53cb962ef86c2af81842a969e9fbc5266f84f7710870af0b781d48e2", + "crates/horizon-world/examples/support/placement_queries.rs": "623b98c33245cb584d666a06bd5a3ddf7f19bf77e0ea9dc67be9a242086c063c" + }, + "fixtures_sha256": { + ".local/rust-feature-placement-parity/inputs.txt": "193b18bbac342a2dbcd70a3bc1c88a694ac042ae30fd76f8015d87a6d57d7f34" + }, + "rust_output_sha256": "52ccd98ab6617d3b21694d1033851a1782d2eee5595f027113bd6d635b0e9190", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "52ccd98ab6617d3b21694d1033851a1782d2eee5595f027113bd6d635b0e9190", + "matched_output_lines": 548461 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "52ccd98ab6617d3b21694d1033851a1782d2eee5595f027113bd6d635b0e9190", + "matched_output_lines": 548461 + } + ], + "scope": "Actual native FeaturePlacer executing decoded placement-modifier chains with a synthetic Feature sink. Empty chains, repeated modifiers, nested random choices, count expansion, filtering, fixed positions, offsets, anchored heights heightmap filters and layered scans are compared. Sink callbacks emit positions, optionally consume the shared random stream, return true/false/mixed results or fail after partial placement. The same native placer is reused across calls, including after errors, exposing retained pending and modified-position buffers. Both random modes, repeated calls, ordinary and overflowing generation contexts and subsequent nextLong values are compared. Predicate filtering and vertical environment scans compare bounds-query order, short-circuiting and failures. Traced heightmap queries include synthetic extreme heights, distinct world/generation minima and injected failures. Configured feature algorithms, block queries, biome checks, registry lifecycle, nested feature placement, Gaussian providers, encoding and complete world generation remain pending. Rust bounds chain length to 1024 and pending/output work to 2^20." +} diff --git a/benchmarks/rust-feature-region-2026-10-06/scoped-parity.json b/benchmarks/rust-feature-region-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..dbb26ff03 --- /dev/null +++ b/benchmarks/rust-feature-region-2026-10-06/scoped-parity.json @@ -0,0 +1,169 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "block_states": 35723, + "block_tag_files": 300, + "fixtures": 192, + "worldgen_random_modes": [ + false, + true + ], + "resident_chunks_per_fixture": 9, + "requested_placements": 2304, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureRegionOracle.java": "5a4cabc6e5c79a0af42b4b840d4fb48e206d146c336af89b919fd47e922bda20", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java": "145c943637ed177cc4ef8a85f2484da8afd164868e84a8463882feec1653a860", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java": "12b1c46cc397755ef6827da777faef3e71c008cafa48403669c03ca2bdc3c7cb", + "tools/test_feature_region_parity.py": "fceba45d5aa9bb2c137350f1df70f4ba64ea65c4179a50920e713a2669bf4e28", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "c215156f2ecf7faf214b3d89e0829b65d54f4ff6d134d778ec941f18a606a327", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "2297b194514925688dba25016a69d5ba5eb8b869bdfff28f2e611a6742ac5954", + "crates/horizon-world/src/worldgen/feature_region.rs": "4a95a30c0987d97e671f84380e13ddea070ad81f996baa65b2a06c4d892971c7", + "crates/horizon-world/src/worldgen/feature_sort.rs": "0b9d1e1c15d8449125d39e400776b8f28eec7b7cbd047660a94f8cb90160adfe", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "1b976aa4dd2516468196d0af3451e3fdd037493a14d269f54ebdd7254055e05e", + "crates/horizon-world/src/worldgen/placement/context.rs": "b36dfd9297896e62770f2085cf934fc08ebd4c030ecc7ae17d864e819a113201", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "68ecf36954fea5705436d486e9be93836933fd56779022afeb881a0399d6a674", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "55c4317bd9c782378de7c2a7d58be5aa08febc5b8f2f4b86379a39e0ba500b3c", + "crates/horizon-world/examples/feature_region_fixture.rs": "7f915c3795e16bc8e2b156c6b3a5d4f2b24f786fdd2ee64eb5159adef7170255" + }, + "fixtures_sha256": { + ".local/rust-feature-region-parity/inputs.txt": "c6ac6ff43c8da61a74dec0e7e72b80da5d2abed0c5a2277f921247cf8dcb04db", + ".local/rust-feature-region-parity/tags.json": "36975358262568f32bf84778d63d9989a36e7394ed4796d70a34809a8f4a64f0", + ".local/rust-feature-region-parity/facts-client.json": "1d24883ee807b0b71473f0bbf8ed548ddaf712148caeb3fcc7aa13ab973a97b0", + ".local/rust-feature-region-parity/facts-server.json": "1d24883ee807b0b71473f0bbf8ed548ddaf712148caeb3fcc7aa13ab973a97b0" + }, + "rust_output_sha256": "93b8b0b9900d2cab972f4d50d4ba9a580db725a20dbc2ebb7fee723af414fc31", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "93b8b0b9900d2cab972f4d50d4ba9a580db725a20dbc2ebb7fee723af414fc31", + "matched_output_lines": 28922634 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "93b8b0b9900d2cab972f4d50d4ba9a580db725a20dbc2ebb7fee723af414fc31", + "matched_output_lines": 28922634 + } + ], + "scope": "Native FeaturePlacer and three basic block-writing features, a composed sequence of four configured fill layers, single-block replacements and scattered ore share a world proxy backed by nine actual ProtoChunks. Configured water, horizontal logs, air, out-of-height fills and ore/replacement rules test graph-to-region binding. Initial two-layer stone/dirt terrain, both pre-light heightmap groups, count/square/heightmap/layered modifier chains, repeated placements, direct and WorldgenRandom-wrapped random streams, missing-neighbor errors, rejected writes and injected partial failures are compared. Final complete raw sections, heightmap presence and packed words are compared alongside ordered feature writes, update flags, explicit height queries and subsequent random draws. Rust uses resident registry-backed chunks, lazy heightmap priming and a caller-supplied write callback; imported air/fluid facts and bundled block tags bind independently across authenticated JARs. The proxy supplies storage mutation only. Actual WorldGenRegion construction, write-zone policy, POIs, block entities, postprocessing effects, lighting, complete feature registries and complete world generation remain outside this comparison." +} diff --git a/benchmarks/rust-feature-sort-2026-10-06/scoped-parity.json b/benchmarks/rust-feature-sort-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..9ace2a9c1 --- /dev/null +++ b/benchmarks/rust-feature-sort-2026-10-06/scoped-parity.json @@ -0,0 +1,156 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 3871, + "biomes": 67, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureSortOracle.java": "cbb527d2a204197bf344597487164e6948f9894641971899e8d023d0b3603abe", + "tools/test_feature_sort_parity.py": "ba745b738c3181c432c77c939126ed8f41fa7bc0430c1900d909f2ed50e5fdd6", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "c215156f2ecf7faf214b3d89e0829b65d54f4ff6d134d778ec941f18a606a327", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "2297b194514925688dba25016a69d5ba5eb8b869bdfff28f2e611a6742ac5954", + "crates/horizon-world/src/worldgen/feature_region.rs": "4a95a30c0987d97e671f84380e13ddea070ad81f996baa65b2a06c4d892971c7", + "crates/horizon-world/src/worldgen/feature_sort.rs": "0b9d1e1c15d8449125d39e400776b8f28eec7b7cbd047660a94f8cb90160adfe", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "1b976aa4dd2516468196d0af3451e3fdd037493a14d269f54ebdd7254055e05e", + "crates/horizon-world/src/worldgen/placement/context.rs": "b36dfd9297896e62770f2085cf934fc08ebd4c030ecc7ae17d864e819a113201", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "68ecf36954fea5705436d486e9be93836933fd56779022afeb881a0399d6a674", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "55c4317bd9c782378de7c2a7d58be5aa08febc5b8f2f4b86379a39e0ba500b3c", + "crates/horizon-world/examples/feature_sort_fixture.rs": "36dc9257be8b823a8dfb632934c56a5bdb733911d470fa8015506b1febc4225c" + }, + "fixtures_sha256": { + ".local/rust-feature-sort-parity/inputs.txt": "ab3aa064287cc2d3c39f1caf3c3f497270e6b91a7af6581cf0e19a01aeb2b720", + ".local/rust-feature-sort-parity/biome-features.json": "cc3846a9d2eae7e45ba9fd69f07e37a715ce5cb946c9cdbe8a86a471c8a8a975" + }, + "rust_output_sha256": "a20952d4dac7add773c676543ec414dfb0bd498737a293a3c18341951e7ddea8", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "a20952d4dac7add773c676543ec414dfb0bd498737a293a3c18341951e7ddea8", + "matched_output_lines": 411751 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "a20952d4dac7add773c676543ec414dfb0bd498737a293a3c18341951e7ddea8", + "matched_output_lines": 411751 + } + ], + "scope": "Actual FeatureSorter.buildFeaturesPerStep with structurally equal but identity-distinct placed-feature payloads. Ordered per-biome step lists, repeated references, cycles, cross-step reuse, disconnected nodes, empty steps and identity index lookups are compared. Every bundled biome feature list and deterministic shuffled/subset combinations bind named references to stable object identities without executing unported feature algorithms. Rust uses bounded iterative DFS. Cycle diagnostic minimization/text, full registry ownership, decoration seeding and feature execution remain pending." +} diff --git a/benchmarks/rust-fill-layer-2026-10-06/scoped-parity.json b/benchmarks/rust-fill-layer-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..8488d5e86 --- /dev/null +++ b/benchmarks/rust-fill-layer-2026-10-06/scoped-parity.json @@ -0,0 +1,157 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 39541, + "block_states": 35723, + "integer_properties": 146, + "requested_placements": 7636, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFillLayerOracle.java": "17730a2248b4b4c808ef6455a09eb80aaad6cf5d7f6b089f8f617993965da7ea", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java": "5c217a8cb72094020082bd4846ed675a6399b9fa371be95a221bd92d227b2e09", + "tools/test_fill_layer_parity.py": "4b534276e6d9feb291d1ba965e596efcbef1be97c186dc6cb3bcdc376a57a7b8", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "22f571a0e4a0ca4e97413b34edabfb1dec9eaccbb8efcefd3ae140b5cee10200", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "80f55c85f5e719aa2df293e6f3afa576ee0783eb0aeccd088e4a4866fa426d7c", + "crates/horizon-world/src/worldgen/feature_region.rs": "4a95a30c0987d97e671f84380e13ddea070ad81f996baa65b2a06c4d892971c7", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/placement/chain.rs": "1b976aa4dd2516468196d0af3451e3fdd037493a14d269f54ebdd7254055e05e", + "crates/horizon-world/src/worldgen/placement/context.rs": "b36dfd9297896e62770f2085cf934fc08ebd4c030ecc7ae17d864e819a113201", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "68ecf36954fea5705436d486e9be93836933fd56779022afeb881a0399d6a674", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "bbb07d92a4ba00513c68e437309a7cb80cd0dd676e6e71aa816168e5676dd96d", + "crates/horizon-world/examples/fill_layer_fixture.rs": "af96e1b2659ea5882a0bc5826c5374baf7cf062463846b481d3682d70cfc673b" + }, + "fixtures_sha256": { + ".local/rust-fill-layer-parity/facts-client.json": "5c785e645fd0bfb583e48c30eaf8bbffc185ee5515b158a8cd32a8bc3c508ba6", + ".local/rust-fill-layer-parity/facts-server.json": "5c785e645fd0bfb583e48c30eaf8bbffc185ee5515b158a8cd32a8bc3c508ba6", + ".local/rust-fill-layer-parity/inputs.txt": "afcceccc92af42fa419325a44bf4d0264c345ada72390c168cf53bbd99cb1a64" + }, + "rust_output_sha256": "75cc33fedb778e95c292c3fd9a6c6b1ef5c567b4b904b970f43e9a28fb5e205f", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "75cc33fedb778e95c292c3fd9a6c6b1ef5c567b4b904b970f43e9a28fb5e205f", + "matched_output_lines": 1305274 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "75cc33fedb778e95c292c3fd9a6c6b1ef5c567b4b904b970f43e9a28fb5e205f", + "matched_output_lines": 1305274 + } + ], + "scope": "Actual Feature.DIRECT_CODEC decoding of fill-layer features binds every pinned block state through BlockState.CODEC; selected compact/full states exercise integer properties and invalid-property defaults. Native FillLayerFeature.place traces each world-minimum query, ordered X/Z block reads and conditional writes, flags, rejected writes, thrown minimum/read/write failures and accumulated stored states after repeated calls. Air-state identity and height-limit metadata are independently exported from both authenticated JARs and checked. Extreme wrapping coordinates and world minima, both random modes and untouched subsequent random state are compared. Full world effects, region integration of fill-layer features, other configured block features and complete generated worlds remain pending." +} diff --git a/benchmarks/rust-float-log-2026-10-05/boundary-parity.json b/benchmarks/rust-float-log-2026-10-05/boundary-parity.json new file mode 100644 index 000000000..3cca81044 --- /dev/null +++ b/benchmarks/rust-float-log-2026-10-05/boundary-parity.json @@ -0,0 +1,373 @@ +{ + "schema": 1, + "minecraft": "26.3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "exhaustive": false, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFloatLogOracle.java": "1794510183faa07892761e93094301b69665d4b6a5300ef7117b5482832165f2", + "tools/test_float_log_parity.py": "1ba733163133ea6232a9021fcee5b38255887d62ebab8d1b42e4ccad259b21f3", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "crates/horizon-core/src/bin/density_parity.rs": "ca79feb1ff690557a54dcb3a504967453dd0190ac65d7322512c778048127c5e", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "e42a19893a8d75f8f62b564bd9e527131d87fb469c808422fb8d3b14eb9edac0", + "crates/horizon-core/src/density/cache.rs": "3ccc1268dca96259890279e9f91cb7a099c74b12e6ca2973880d4fa246f7a619", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ede1da60dec40f6df846e44a663bff03c21631c21f2b6e25a58c358115f122a1", + "crates/horizon-core/src/density/graph/mod.rs": "47f1716a8b5fffc1012b9e4654e223b0ff818f00f6a059818ab3dfe8c37e3056", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "3034eccba649851d7a95e276a48472efd70cdf747b54526b565fb0feb88ce43a", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "3e56cc0f6b51c6faa4bd8d9fc259bf01a0c3bf647f36be8be7640971cfe3b334", + "crates/horizon-core/src/density/power.rs": "b18a5b0d524de52a3d1e6028adcddd183424be2913f24d3f098ff56c5e1c6942", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "faae2edce8b573fd32fcb4bd1f898be7d700a5b38479439f5bec96df764688fd" + }, + "comparisons": [ + { + "start_bits": 0, + "count": 65536, + "rust_output_sha256": "1e684e3e6b93407fb3f37762a4de01f8706c047cf5294cf9d2a1ac173fc02075", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "1e684e3e6b93407fb3f37762a4de01f8706c047cf5294cf9d2a1ac173fc02075", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "1e684e3e6b93407fb3f37762a4de01f8706c047cf5294cf9d2a1ac173fc02075", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 8388608, + "count": 65536, + "rust_output_sha256": "4200cba9cf0053911e1d672fabbee94f5267d5b7aa109fbe57ddc5a4f7b70393", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "4200cba9cf0053911e1d672fabbee94f5267d5b7aa109fbe57ddc5a4f7b70393", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "4200cba9cf0053911e1d672fabbee94f5267d5b7aa109fbe57ddc5a4f7b70393", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 1056899072, + "count": 65536, + "rust_output_sha256": "cae10428767d3e776f5183caba1780897d2e1831913c05ae6dd8d843a6e25a76", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "cae10428767d3e776f5183caba1780897d2e1831913c05ae6dd8d843a6e25a76", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "cae10428767d3e776f5183caba1780897d2e1831913c05ae6dd8d843a6e25a76", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 1065287680, + "count": 65536, + "rust_output_sha256": "59024062288c0bc65906a38484eff0fb73aaba11cb8110aaebc6dde8891ed10c", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "59024062288c0bc65906a38484eff0fb73aaba11cb8110aaebc6dde8891ed10c", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "59024062288c0bc65906a38484eff0fb73aaba11cb8110aaebc6dde8891ed10c", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 1065353216, + "count": 65536, + "rust_output_sha256": "01849695d0e9a30ccd132270cb79ecaaf1065411d66b323a36f1b87f5d0e4596", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "01849695d0e9a30ccd132270cb79ecaaf1065411d66b323a36f1b87f5d0e4596", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "01849695d0e9a30ccd132270cb79ecaaf1065411d66b323a36f1b87f5d0e4596", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 1073741824, + "count": 65536, + "rust_output_sha256": "0df001f091df446399cccd24b0fa1e4114894c263d5cdc707b8c4a2ded269936", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "0df001f091df446399cccd24b0fa1e4114894c263d5cdc707b8c4a2ded269936", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "0df001f091df446399cccd24b0fa1e4114894c263d5cdc707b8c4a2ded269936", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 2139029504, + "count": 65536, + "rust_output_sha256": "c39faee80d047d450472ae5eb25f2811e4010b5aad1ccad80ff4d8f7638bd3d5", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "c39faee80d047d450472ae5eb25f2811e4010b5aad1ccad80ff4d8f7638bd3d5", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "c39faee80d047d450472ae5eb25f2811e4010b5aad1ccad80ff4d8f7638bd3d5", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 2139095040, + "count": 65536, + "rust_output_sha256": "1c60d380d4dc55a05bed3452e32f4d5c813c9beb4459ba890338c27f0b047345", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "1c60d380d4dc55a05bed3452e32f4d5c813c9beb4459ba890338c27f0b047345", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "1c60d380d4dc55a05bed3452e32f4d5c813c9beb4459ba890338c27f0b047345", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 2147418112, + "count": 65536, + "rust_output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 2147483648, + "count": 65536, + "rust_output_sha256": "b365699b17956be9409c58c88b48da5f7edf7e4783fcca72efa00b0dae84455f", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "b365699b17956be9409c58c88b48da5f7edf7e4783fcca72efa00b0dae84455f", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "b365699b17956be9409c58c88b48da5f7edf7e4783fcca72efa00b0dae84455f", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 2155872256, + "count": 65536, + "rust_output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 3212771328, + "count": 65536, + "rust_output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 3212836864, + "count": 65536, + "rust_output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 4286513152, + "count": 65536, + "rust_output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 4286578688, + "count": 65536, + "rust_output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "matched_float_values": 65536 + } + ] + }, + { + "start_bits": 4294901760, + "count": 65536, + "rust_output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "matched_float_values": 65536 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "f3b37b44be6c4c25b1d85b2bce7844c67cc9f3e5a3270d4a53101d99049b966e", + "matched_float_values": 65536 + } + ] + } + ], + "scope": "Compiled scalar UnaryFunction.LogSampler compared by float result bits across the recorded input bit ranges, including signed zeros, subnormals, finite values, infinities and NaNs. NaN results are canonicalized as Float.floatToIntBits. Exhaustive mode checks all 2^32 float input bit patterns against both checksum-pinned JARs on this machine's JDK. Bulk composition, range propagation, compiler rewriting and other operations belong to the separate density suite. This does not establish double-precision Math.log parity, other-platform math parity, complete terrain, gameplay or performance." +} diff --git a/benchmarks/rust-float-log-2026-10-05/scoped-parity.json b/benchmarks/rust-float-log-2026-10-05/scoped-parity.json new file mode 100644 index 000000000..df0091792 --- /dev/null +++ b/benchmarks/rust-float-log-2026-10-05/scoped-parity.json @@ -0,0 +1,87 @@ +{ + "schema": 1, + "minecraft": "26.3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "exhaustive": true, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFloatLogOracle.java": "1794510183faa07892761e93094301b69665d4b6a5300ef7117b5482832165f2", + "tools/test_float_log_parity.py": "c7f9aa59351309cba8a1e8c118e304c58dee0ddd31dcd98d3f0d41a86b5d77a9", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "crates/horizon-core/src/bin/density_parity.rs": "9a1b2d7033682f23e413d1e8764365052c673a05306ee254a4f6f5d6c5a728f6", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "e23a963bfbc75ba7c3e7bdefd0e300907dcc4f8c8336826c27ddf479d320f075", + "crates/horizon-core/src/density/cache.rs": "3ccc1268dca96259890279e9f91cb7a099c74b12e6ca2973880d4fa246f7a619", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "89993bf84b2bb5ca8d28b8c1c944db87078a43890a904a8d2bd1989e6cd3864f", + "crates/horizon-core/src/density/graph/mod.rs": "7a05a8b2b99fa41b69fd85d38228b8c0cc95b11761039643abb9af5f6a0d07d7", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "91da8b08b1567640e82daab5440fb767c74ff14e63bcc555cbd2e6b4f5ff3cd6", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "e5cd03f4c1b15caf5d6680f2a6d6271f324af9d9f6cad7068ddf942509b3fe62", + "crates/horizon-core/src/density/mod.rs": "6a3eec3feb37bdeb574b9070036c207544f2375a41ef25ab93315cccaba6ebc2", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "faae2edce8b573fd32fcb4bd1f898be7d700a5b38479439f5bec96df764688fd" + }, + "comparisons": [ + { + "start_bits": 0, + "count": 4294967296, + "rust_output_sha256": "3a67757c8e4e4c70d597613ea11b7ace2ea45d8f02effaa23e70233e4ee327d7", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "3a67757c8e4e4c70d597613ea11b7ace2ea45d8f02effaa23e70233e4ee327d7", + "matched_float_values": 4294967296 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "3a67757c8e4e4c70d597613ea11b7ace2ea45d8f02effaa23e70233e4ee327d7", + "matched_float_values": 4294967296 + } + ] + } + ], + "scope": "Compiled scalar UnaryFunction.LogSampler compared by float result bits across the recorded input bit ranges, including signed zeros, subnormals, finite values, infinities and NaNs. NaN results are canonicalized as Float.floatToIntBits. Exhaustive mode checks all 2^32 float input bit patterns against both checksum-pinned JARs on this machine's JDK. Bulk composition, range propagation, compiler rewriting and other operations belong to the separate density suite. This does not establish double-precision Math.log parity, other-platform math parity, complete terrain, gameplay or performance." +} diff --git a/benchmarks/rust-fluid-2026-10-06/scoped-parity.json b/benchmarks/rust-fluid-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..d19807d8a --- /dev/null +++ b/benchmarks/rust-fluid-2026-10-06/scoped-parity.json @@ -0,0 +1,168 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "block_states": 35723, + "fluid_kinds": 5, + "fixtures": 40344, + "requested_height_queries": 80688, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidOracle.java": "616e256245f1a95069745b7cde26ade08ae16dadd7e9224fa54abf16cef9fee9", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java": "5c217a8cb72094020082bd4846ed675a6399b9fa371be95a221bd92d227b2e09", + "tools/test_fluid_parity.py": "3728655b2e524a01bfaac137dd9351bf3f4e7b4053037ec72049e6f549d38ba2", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/fluid.rs": "8a2834a9347ee2c2db7cf1c86a064907ec06e9ac16ba9cc3936e315fc4ad49ca", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "06aa7b44e1229b3cf50abcf3827f2cacd7ae54321865873bdba0f371cb458b3f", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "d6389c8d1adf900eb8f0e6c8833feafe43dc92d74e5c7ffa6f3950975529d624", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "f8c2ef2de1cfe9a8689a7375d4bf0cc00431484e06f6d4b2b95aabac8fdfffb0", + "crates/horizon-world/src/worldgen/block_predicate.rs": "8513e9d96c8626594b5ee078bf20ccf3de90fc9f9d7123780d1cab5eefb6b5c2", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/decoration.rs": "297524aefeb4567c5f5c0c1678013e44002eb91ca16ee63b51ffacf93f31a095", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "fe61a5e43179a7588737a71782ea246811fe2c8721e74793e1ac018c8eb93c34", + "crates/horizon-world/src/worldgen/feature_region.rs": "2c78e5f1bdb08307f8d982f231f1abbc3306cd54348d9023b86ee6ed3516fd33", + "crates/horizon-world/src/worldgen/feature_sort.rs": "3488a093dfe1321aaa29d8a30cfb115d8e666a81bf195514e87b170de626835c", + "crates/horizon-world/src/worldgen/fluid_predicate.rs": "e682d13a21f90605215b79f5d254bf2e524d35e89eab2e3b46384709af80b847", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "08ee8697f589e96b69653b395238eecd144d51cfec30017214275f9b338d82af", + "crates/horizon-world/src/worldgen/placement/context.rs": "c916b30177e283e8eedfa342dc5282b42c898a2873668b44f59c83501ff866bd", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "b0397e5818fae84358546193a95f84bcb0b5bffafce909e6fcb3386179ee8023", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/state_provider/catalog.rs": "fa0616353f07460975ab323357ab280b7f35e7bfe2de6edc08d304316766ed26", + "crates/horizon-world/src/worldgen/state_provider/noise.rs": "7ee369c2a032e5620cb9bdf9ee7adad1f70870fb0a27efb7b7c514d92f83491f", + "crates/horizon-world/src/worldgen/state_provider/properties.rs": "9909139aaca1dc4f743957257fadaa9d423d21fa401fa9abc050505f79365139", + "crates/horizon-world/src/worldgen/state_provider.rs": "d1097d91b43e30cec38b09365d3ed58f15522b829feb584e255718447e4c68b4", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "3358b563db8cb0bc8a9cfbbe2b8b3e70941cd2d37a0b519fbb6545f8d0dcbb69", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "b08f074f54f451c24795d5dda68968165b84b8d762d244f0444a8d62de61820e", + "crates/horizon-world/examples/fluid_fixture.rs": "4603e462ce92f60426bb6025cd42b08410d0d4e81293e08861636a5664dfe0b1" + }, + "fixtures_sha256": { + ".local/rust-fluid-parity/inputs.txt": "532b6e5965ce43b01989e7ee11c104d6bb498e52bcad0a79b14c5865068d287d", + ".local/rust-fluid-parity/facts-client.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b", + ".local/rust-fluid-parity/facts-server.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b" + }, + "rust_output_sha256": "b25ed573e8c2177c68a5f48ff62665144cf687aee3b948e8de696ab43e16fad1", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "b25ed573e8c2177c68a5f48ff62665144cf687aee3b948e8de696ab43e16fad1", + "matched_output_lines": 239190 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "b25ed573e8c2177c68a5f48ff62665144cf687aee3b948e8de696ab43e16fad1", + "matched_output_lines": 239190 + } + ], + "scope": "Native fluid identity, amount, falling/source/full flags, own-height bits and legacy block conversion for every pinned block state; all fluid-family identity pairs. Surface and camera height query order, above-fluid family checks, source-only downward-face support checks, coordinate wrapping and injected query failures are compared. The fixture supplies stone/air support states; general block support shapes, fluid spreading/ticks, entities and rendering remain outside this comparison." +} diff --git a/benchmarks/rust-geometry-2026-10-05/scoped-parity.json b/benchmarks/rust-geometry-2026-10-05/scoped-parity.json new file mode 100644 index 000000000..9efcea4a4 --- /dev/null +++ b/benchmarks/rust-geometry-2026-10-05/scoped-parity.json @@ -0,0 +1,73 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "commands": { + "traverse": 8448, + "trig-table": 1, + "rotation": 16000, + "vec": 7256, + "box": 7006, + "block-box": 100, + "grid": 201, + "query": 52500, + "many": 2500, + "motion": 12000, + "join": 5652, + "make-box": 600, + "optimize": 500, + "join-optimized": 500, + "step-motion": 17680, + "block-iterate": 2400, + "box-iterate": 2400, + "sweep": 9022, + "floor-height": 12000 + }, + "inputs_sha256": "95abe82bf9f328e8b51aafb84a3e97954073f743b963a3d2fa4892cc120f49f1", + "rust_output_sha256": "ebb938b5288e05a291b6e1039f286aa7565821f8de46afb1d853d8112c079dd5", + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGeometryOracle.java": "48c233ec1a5684cbd5a9edb5d7972aa4647465045ef298dce14a91de45cc4809", + "tools/test_geometry_parity.py": "38ce169dc520535c217a01705510b71ef3ee81128376640e849f47bc999ef64d", + "tools/test_rust_parity.py": "500652427164c7e067a5eb69310ec81f843d5fe37a7c9d88edd2b1ca6606020a", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "faae2edce8b573fd32fcb4bd1f898be7d700a5b38479439f5bec96df764688fd", + "crates/horizon-core/Cargo.toml": "09243cac4d45e8b4aaed3a6169bf3ee0e1272fdff4298c43c80d5fff0116d01c", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/parity.rs": "7b455f2181862e1430e7387633c146877c2d317c2ea682c1e6fa64345dbc5885", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "acaa0a51a759e1a08d417538e567847a66b8c9ae6a7434872e1621ed210364b1", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random.rs": "2f304dfb580a6bc1b5c51b048a2fa2a57f73c5f28f5eb2447f925bf138513389", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e" + }, + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "ebb938b5288e05a291b6e1039f286aa7565821f8de46afb1d853d8112c079dd5", + "matched_output_lines": 1320187 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "ebb938b5288e05a291b6e1039f286aa7565821f8de46afb1d853d8112c079dd5", + "matched_output_lines": 1320187 + } + ], + "scope": "Selected Vec3/AABB operations, sine table entries, quantized trig, rotations and look directions; finite block-ray traversal; bounded inclusive/directional block iteration and finite swept-block visits with step indices; immutable cube/array voxel-grid bounds, column minima/maxima, greedy boxes, collide, ray hits, closest points and cell lookup; lazy floor-height selection; box quantization, optimized/unoptimized Boolean joins, alias identity and joinIsNotEmpty; Entity.collideWithShapes, candidate step heights and Entity.collide step-up decisions/query bounds with caller-controlled block/entity/border shape lists. No live entities, actual world shape selection, grounding/velocity side effects, fluids or block behavior." +} diff --git a/benchmarks/rust-geometry-2026-10-06/scoped-parity.json b/benchmarks/rust-geometry-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..1dbed368b --- /dev/null +++ b/benchmarks/rust-geometry-2026-10-06/scoped-parity.json @@ -0,0 +1,110 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "commands": { + "traverse": 8448, + "trig-table": 1, + "rotation": 16000, + "vec": 7256, + "box": 7006, + "block-box": 100, + "grid": 201, + "query": 52500, + "many": 2500, + "motion": 12000, + "join": 5652, + "make-box": 600, + "optimize": 500, + "join-optimized": 500, + "step-motion": 17680, + "block-iterate": 2400, + "box-iterate": 2400, + "sweep": 9022, + "floor-height": 12000 + }, + "inputs_sha256": "95abe82bf9f328e8b51aafb84a3e97954073f743b963a3d2fa4892cc120f49f1", + "rust_output_sha256": "ebb938b5288e05a291b6e1039f286aa7565821f8de46afb1d853d8112c079dd5", + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGeometryOracle.java": "48c233ec1a5684cbd5a9edb5d7972aa4647465045ef298dce14a91de45cc4809", + "tools/test_geometry_parity.py": "38ce169dc520535c217a01705510b71ef3ee81128376640e849f47bc999ef64d", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/face.rs": "f243bce81384040a95ce7984b02b5699206c596c537b2713097e86005b4d3a5c", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "e8d88a763de1525f77a30b99591641e8a8b80946263acbde035a9bcc356df960", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e" + }, + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "ebb938b5288e05a291b6e1039f286aa7565821f8de46afb1d853d8112c079dd5", + "matched_output_lines": 1320187 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "ebb938b5288e05a291b6e1039f286aa7565821f8de46afb1d853d8112c079dd5", + "matched_output_lines": 1320187 + } + ], + "scope": "Selected Vec3/AABB operations, sine table entries, quantized trig, rotations and look directions; finite block-ray traversal; bounded inclusive/directional block iteration and finite swept-block visits with step indices; immutable cube/array voxel-grid bounds, column minima/maxima, greedy boxes, collide, ray hits, closest points and cell lookup; lazy floor-height selection; box quantization, optimized/unoptimized Boolean joins, alias identity and joinIsNotEmpty; Entity.collideWithShapes, candidate step heights and Entity.collide step-up decisions/query bounds with caller-controlled block/entity/border shape lists. No live entities, actual world shape selection, grounding/velocity side effects, fluids or block behavior." +} diff --git a/benchmarks/rust-height-provider-2026-10-06/scoped-parity.json b/benchmarks/rust-height-provider-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..5419d587f --- /dev/null +++ b/benchmarks/rust-height-provider-2026-10-06/scoped-parity.json @@ -0,0 +1,152 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 9030, + "definitions": 301, + "samples_per_valid_fixture": 32, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightProviderOracle.java": "fa366ca1ed396353f8ec4a79c553f23aa9d0fc9bc85275427552e98cd27a777e", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java": "226628d98b89aadbdd374936575d033945e7064a900dbb050c662204dbc7e119", + "tools/test_height_provider_parity.py": "06685252f1e2ffbe6988759655f96b95f5895353dd43b774db9908bc59365fe2", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_graph.rs": "5dfb83b9f97eb24b386e3514aaac957b314461b32d59e1fdb6dcac7ca0a32e1b", + "crates/horizon-world/src/worldgen/feature_region.rs": "4a95a30c0987d97e671f84380e13ddea070ad81f996baa65b2a06c4d892971c7", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/placement/chain.rs": "1b976aa4dd2516468196d0af3451e3fdd037493a14d269f54ebdd7254055e05e", + "crates/horizon-world/src/worldgen/placement/context.rs": "b36dfd9297896e62770f2085cf934fc08ebd4c030ecc7ae17d864e819a113201", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "68ecf36954fea5705436d486e9be93836933fd56779022afeb881a0399d6a674", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "f18a6c0e66cadec431d2e3154ad70d96b3be623e675f939d4419858f2cce92ab", + "crates/horizon-world/examples/height_provider_fixture.rs": "d8a314edf7c3c90483f86aaa3786f41192c957480a751353fbbf6e9dbc8cad3f" + }, + "fixtures_sha256": { + ".local/rust-height-provider-parity/inputs.txt": "03bcc47709132ca5afe9b4fd1b6c9b1ba2bd238270ddfed90fd284f39817e143" + }, + "rust_output_sha256": "bb3677402722cf44c4d4572e8b0a915774e15a2d04928171ea69b194603c44fb", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "bb3677402722cf44c4d4572e8b0a915774e15a2d04928171ea69b194603c44fb", + "matched_output_lines": 507660 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "bb3677402722cf44c4d4572e8b0a915774e15a2d04928171ea69b194603c44fb", + "matched_output_lines": 507660 + } + ], + "scope": "Actual HeightProvider.CODEC decoding and sampled heights with interleaved nextLong values, using actual WorldGenerationContext and all four vertical-anchor kinds. Covers constant, uniform, biased-to-bottom, very-biased-to-bottom trapezoid and weighted-list providers, both random modes, empty/equal ranges, inner/plateau defaults and bounds, numeric narrowing, relative coordinate overflow, malformed fields and anchor-versus-dispatch preference. Warning logs are excluded. Weighted lists include zero weights, singleton draws, nested providers, 63/64/65 weight totals, maximum/overflow totals and malformed entries; native constructor rejections count as decode errors. Encoding, cave/canyon paths and complete generation remain outside this scope." +} diff --git a/benchmarks/rust-heightmap-2026-10-06/scoped-parity.json b/benchmarks/rust-heightmap-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..83cda8c9d --- /dev/null +++ b/benchmarks/rust-heightmap-2026-10-06/scoped-parity.json @@ -0,0 +1,126 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "block_states": 35723, + "block_tag_files": 300, + "fixtures": 100, + "operation_counts": { + "set": 86806, + "query": 54306, + "dump": 474, + "prime": 516, + "raw": 378, + "update": 42 + }, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java": "145c943637ed177cc4ef8a85f2484da8afd164868e84a8463882feec1653a860", + "tools/test_heightmap_parity.py": "d8c0e68d51fa102c518030c816ce9f41d05c7d6d65e2d484b2e57c253b407510", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/test_worldgen_parity.py": "3574ac73f81e3a6606ac9d3c16fa2c50b57a37b89be52e7d5448e7045c41a9ee", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "69f89566a78456c29caaa39dacedfe711ca59e49b78f64e68b0414fb6a73d8fc", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry.rs": "f46065659e60eb5e84ad69b9f3b5e94dc87ee19de16408817e26f23d16b6c7e7", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "134cf93b53a40fb1ed0e0170c90316c80e270773b2968c63dc3f9cef2c941bff", + "crates/horizon-world/src/worldgen.rs": "b89dd4a9de02caf6bce457304a105ffbc0f0f220f8647c095852a45a1bf292bb", + "crates/horizon-world/examples/heightmap_fixture.rs": "eddd4c15620eebfc5bd919d3b19b0b2fd69d6fd31a19d8c512121aa297efa848" + }, + "fixtures_sha256": { + ".local/rust-heightmap-parity/inputs.txt": "bf53719ac137e1ebbf7b874bd887e3208516e9938372c00d8f3d2c969297ec22", + ".local/rust-heightmap-parity/tags.json": "36975358262568f32bf84778d63d9989a36e7394ed4796d70a34809a8f4a64f0", + ".local/rust-heightmap-parity/facts-client.json": "1d24883ee807b0b71473f0bbf8ed548ddaf712148caeb3fcc7aa13ab973a97b0", + ".local/rust-heightmap-parity/facts-server.json": "1d24883ee807b0b71473f0bbf8ed548ddaf712148caeb3fcc7aa13ab973a97b0" + }, + "rust_output_sha256": "1268526add13ad33c0db95dc70df1e37fb12d35d5c95ce82fbb2bcef2d830a9d", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "1268526add13ad33c0db95dc70df1e37fb12d35d5c95ce82fbb2bcef2d830a9d", + "matched_output_lines": 1671668 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "1268526add13ad33c0db95dc70df1e37fb12d35d5c95ce82fbb2bcef2d830a9d", + "matched_output_lines": 1671668 + } + ], + "scope": "Six heightmap types, client/persistence flags and predicates for every pinned block state. Air/fluid facts are imported independently from both authenticated JARs and required to agree; block-tag membership is resolved in Rust from bundled resources. State behavioral methods are not ported by that import. Actual vanilla ProtoChunk and Heightmap APIs compare insertion/removal, downward rescans, repeated priming, empty-column retention, raw packed words including padding/unused slots, invalid-length fallback, wrapped column indexing, height queries, errors and selected exact block-read traces. Positive aligned vertical ranges are bounded to the NoiseSettings codec domain; arbitrary height accessors, chunk lifecycle integration, complete terrain/gameplay and rendering remain pending." +} diff --git a/benchmarks/rust-material-condition-2026-10-06/scoped-parity.json b/benchmarks/rust-material-condition-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..9843a46c6 --- /dev/null +++ b/benchmarks/rust-material-condition-2026-10-06/scoped-parity.json @@ -0,0 +1,145 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 245, + "initial_conditions": 11288, + "context_operations": 217969, + "noise_resources": 64, + "condition_resources": 8, + "biome_resources": 67, + "biome_tag_resources": 86, + "biome_fixtures": 23, + "preliminary_fixtures": 61, + "ore_fixtures": 57, + "noise_fixtures": 24, + "initial_rules": 6271, + "codec_inputs": 8609, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialConditionOracle.java": "04a87405fd2a1c79baf4eb3a8895aa66dc96b8f6baffb9b486ef207f8b91b5ee", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java": "226628d98b89aadbdd374936575d033945e7064a900dbb050c662204dbc7e119", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java": "243bbc525c6aec24674e7f172c5fb4f7b50f9a679d8b9dfba40ea278219a2d28", + "tools/test_biome_temperature_parity.py": "68f84d02e7802349e491b8cb66e18d9b08c9e72ab2306b663667259e852cc2b1", + "tools/test_material_condition_parity.py": "01c82e1a768d9131f8f7e6d59d01ddb06272074469dbdcd8547f44f0a8fa152d", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "39e1a8807f9ae975ff5a4c92effe619050049a386549a94c0d1ddaebf66f24af", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "04ac9130138ea4ce67fc43f7701f5036972984724ffcd49bfe857d0693361d87", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "4ab2681a45108e5d2ea6fb761ea1cb7fa40b72833fa6190d2efe34ce29845c21", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "99926c7b867b752966084cdf2b20530dde8069703f4b3709bf623fefad425102", + "crates/horizon-world/src/worldgen.rs": "cffb5e72b59222dad13e57fa74ed4f553570a61a8773f27b5199444111ced2e0", + "crates/horizon-world/examples/material_condition_fixture.rs": "a9b6c0adf7308eebfa746baa84696ec6df75e6a0d93c5742958fb9a58e090000" + }, + "fixtures_sha256": { + ".local/rust-material-condition-parity/inputs.txt": "56215086f8ae7d82df35e05235d67da42749bd4f8b629bb55d9c408e6aab70ef", + ".local/rust-material-condition-parity/noises.json": "310b240c9b70586bb704ca44a915766a8d41d6a073183324c37184fcb317a992", + ".local/rust-material-condition-parity/conditions.json": "a417b8cd9e41ad6b45ea9ac8d587d70c0a50f0b0c4aa7d4812fce1a6c6016ba8", + ".local/rust-material-condition-parity/biomes.json": "9b26dc3b662627dc3bbbf8da209f287882ce79ff4daf8f454b994ddc7510df99", + ".local/rust-material-condition-parity/biome_tags.json": "f7ed4da9e7755712a1116b2fd64e749639f085d8698b5def3ecabae5ece87095" + }, + "rust_output_sha256": "02c3bcbfae34fe6f7eed98add6ef550a3dae15734eda587d269d622661c68633", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "02c3bcbfae34fe6f7eed98add6ef550a3dae15734eda587d269d622661c68633", + "matched_output_lines": 5627426 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "02c3bcbfae34fe6f7eed98add6ef550a3dae15734eda587d269d622661c68633", + "matched_output_lines": 5627426 + } + ], + "scope": "Actual runtime constructors and compiled evaluators for hole, steep, Y, water, stone-depth, vertical-gradient, noise-threshold, biome-membership, temperature and negated conditions, with actual MaterialRuleContext updates and secondary-noise caching. Both world random algorithms and named positional gradient factories, boundary/overflow arithmetic, floor/ceiling selection, reversed/equal gradient bounds, late compilation and repeated/changed context evaluations. Context surfaceDepth is injected after native updateXZ and the secondary sampler is a traced constant-noise override; these supplied inputs isolate condition behavior, with full MaterialSystem surface inputs checked separately. Direct and holder condition codecs cover all eight bundled definitions, canonical encoding, forward and nested references, default namespaces, numeric wrapping/truncation, required fields, invalid types and nested anchor alternatives. Cycles and bounded resource limits are typed Rust errors, not compared to native stack overflow. Actual BlockRule, SequenceRule, ConditionRule and BandlandsRule compilation/application additionally cover ordered short circuiting, nested and empty/singleton sequences, independent context versus application coordinates, late compilation and seeded band results/failures. Noise-threshold conditions additionally cover shared/separate XZ and XYZ cached suppliers, all bundled named noise resources under both random modes, traced changing source inputs, repeated coordinates/updates, late binding, float promotion, NaN/infinite thresholds and values. Encoded JSON numbers are compared as canonical double bits, including nonfinite Gson output tokens. Biome membership and temperature conditions additionally cover all bundled biome climate settings, possible-biome constant folding (including empty sets), context biome caching and XZ/Y invalidation, shared temperature caches across contexts, null biome results, query failures and lazy-condition retry behavior. Named biome-tag holders additionally cover every bundled biome tag, native TagLoader resolution/binding versus Rust TagDefinitions, encoded tag identity, namespace aliases, empty/duplicate/nested/optional entries, membership and possible-biome folding, predicate errors and conditional-rule application. Preliminary-surface conditions additionally cover lazy unit-spaced XZ plane sampling versus scalar fallback, traced sample order, ignored source-volume strides/Y extent, column minimum caching, block-height changes, partial density failures and retained buffers, same-column failure retries, floor/nonfinite conversions and wrapping arithmetic. Provider error occurrence is compared, not exception class or message. Preliminary planes are bounded to 1,048,576 samples in Rust. Ore-vein rules additionally cover eager density/richness volumes, lazy gap sampling, exact strided lattice hits and scalar misses, shared context versus independent application/random coordinates, both positional random modes, ordered draws and short circuiting, mutable/NaN/infinite sources, raw-ore chances, failed compilation and provider retries. Rust requires precompiled density roots for the same world context; live registry/tag reloads, rule codecs, registry-owner validation, arbitrary provider failures and full surface-stage application remain pending." +} diff --git a/benchmarks/rust-material-extension-2026-10-06/scoped-parity.json b/benchmarks/rust-material-extension-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..96b409158 --- /dev/null +++ b/benchmarks/rust-material-extension-2026-10-06/scoped-parity.json @@ -0,0 +1,134 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 410, + "extension_calls": 3920, + "biome_resources": 67, + "noise_resources": 64, + "constant_noise_fixtures": 142, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialExtensionOracle.java": "4ad5ad2836095f06394d84c9b86ca5866b6180dd6ed9f81bc038754051537184", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java": "243bbc525c6aec24674e7f172c5fb4f7b50f9a679d8b9dfba40ea278219a2d28", + "tools/test_material_extension_parity.py": "b4e03657bfcec04e1844f1c738d6dd28181b97686b8f07dbe32ba4b541e30364", + "tools/test_biome_temperature_parity.py": "68f84d02e7802349e491b8cb66e18d9b08c9e72ab2306b663667259e852cc2b1", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "39e1a8807f9ae975ff5a4c92effe619050049a386549a94c0d1ddaebf66f24af", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "04ac9130138ea4ce67fc43f7701f5036972984724ffcd49bfe857d0693361d87", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "4ab2681a45108e5d2ea6fb761ea1cb7fa40b72833fa6190d2efe34ce29845c21", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "99926c7b867b752966084cdf2b20530dde8069703f4b3709bf623fefad425102", + "crates/horizon-world/src/worldgen.rs": "cffb5e72b59222dad13e57fa74ed4f553570a61a8773f27b5199444111ced2e0", + "crates/horizon-world/examples/material_extension_fixture.rs": "3eae986504abfc5087b9f93d570aa26a3a0b4ad7dfc354c53cf887d7a2ad31a4" + }, + "fixtures_sha256": { + ".local/rust-material-extension-parity/inputs.txt": "9b688fb99c7ff971b5824749f9b6fef0cc647b8543efb7a0b1e52e24eba798be", + ".local/rust-material-extension-parity/noises.json": "310b240c9b70586bb704ca44a915766a8d41d6a073183324c37184fcb317a992", + ".local/rust-material-extension-parity/biomes.json": "9b26dc3b662627dc3bbbf8da209f287882ce79ff4daf8f454b994ddc7510df99" + }, + "rust_output_sha256": "8cdb9fb92fe6b66759941ece3ba56d6653c1bcebf1b6744ab3b74c7ad7bed9c5", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "8cdb9fb92fe6b66759941ece3ba56d6653c1bcebf1b6744ab3b74c7ad7bed9c5", + "matched_output_lines": 233100 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "8cdb9fb92fe6b66759941ece3ba56d6653c1bcebf1b6744ab3b74c7ad7bed9c5", + "matched_output_lines": 233100 + } + ], + "scope": "Actual private MaterialSystem erodedBadlandsExtension and frozenOceanExtension methods, with ordered noise-coordinate/block-read/block-write traces and complete resulting columns. Both positional random modes, actual seeded bundled noises, all biome climate settings, same-block identity across state properties, air variants, flowing water, waterlogged nonwater blocks, snow/ice thresholds, repeated calls and height clipping by supplied column providers. Constant overrides cover thresholds, signed zero, NaN/infinity, sea-level integer extremes and bounded provider read failures. Native exception class/message and full chunk/heightmap/postprocessing integration are not compared here. Rust caps extension loops to 1,048,576 iterations; oversized synthetic scans hit the fixture provider limit in both implementations. Full surface-stage and playable parity remain pending." +} diff --git a/benchmarks/rust-material-rule-library-2026-10-06/scoped-parity.json b/benchmarks/rust-material-rule-library-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..4f0d1c51a --- /dev/null +++ b/benchmarks/rust-material-rule-library-2026-10-06/scoped-parity.json @@ -0,0 +1,149 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "resources": { + "noises": 64, + "densities": 55, + "rules": 42, + "conditions": 8, + "biomes": 67, + "biome_tags": 86 + }, + "fixtures": 12, + "codec_inputs": 142, + "rule_applications": 665712, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialConditionOracle.java": "04a87405fd2a1c79baf4eb3a8895aa66dc96b8f6baffb9b486ef207f8b91b5ee", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java": "226628d98b89aadbdd374936575d033945e7064a900dbb050c662204dbc7e119", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java": "243bbc525c6aec24674e7f172c5fb4f7b50f9a679d8b9dfba40ea278219a2d28", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java": "5c217a8cb72094020082bd4846ed675a6399b9fa371be95a221bd92d227b2e09", + "tools/test_material_rule_library_parity.py": "21bf17b6bebd7dab2927be075f9098b773a56365462cf910d69160995a7b6939", + "tools/test_material_condition_parity.py": "01c82e1a768d9131f8f7e6d59d01ddb06272074469dbdcd8547f44f0a8fa152d", + "tools/test_biome_temperature_parity.py": "68f84d02e7802349e491b8cb66e18d9b08c9e72ab2306b663667259e852cc2b1", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "39e1a8807f9ae975ff5a4c92effe619050049a386549a94c0d1ddaebf66f24af", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "04ac9130138ea4ce67fc43f7701f5036972984724ffcd49bfe857d0693361d87", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "4ab2681a45108e5d2ea6fb761ea1cb7fa40b72833fa6190d2efe34ce29845c21", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "99926c7b867b752966084cdf2b20530dde8069703f4b3709bf623fefad425102", + "crates/horizon-world/src/worldgen.rs": "cffb5e72b59222dad13e57fa74ed4f553570a61a8773f27b5199444111ced2e0", + "crates/horizon-world/examples/material_condition_fixture.rs": "a9b6c0adf7308eebfa746baa84696ec6df75e6a0d93c5742958fb9a58e090000" + }, + "fixtures_sha256": { + ".local/rust-material-rule-library-parity/inputs.txt": "194b14c212a1fb423cb689141d2f38b79654c9f665616094ca0f6a70e2220633", + ".local/rust-material-rule-library-parity/facts-client.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b", + ".local/rust-material-rule-library-parity/facts-server.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b", + ".local/rust-material-rule-library-parity/noises.json": "310b240c9b70586bb704ca44a915766a8d41d6a073183324c37184fcb317a992", + ".local/rust-material-rule-library-parity/densities.json": "28fe94e1b7cf3a06edfa2337319c03b5374c15bf18235570ee76e9c498c2f450", + ".local/rust-material-rule-library-parity/rules.json": "d5410ec3af96cf17a672a2f4c0a27b4e10ac4e4c75d63c52f6de406b64acbe57", + ".local/rust-material-rule-library-parity/conditions.json": "54a470a4513fb34a23e0fe66b0a5129a468dbd0002f5b2839437a9861a6005b9", + ".local/rust-material-rule-library-parity/biomes.json": "9b26dc3b662627dc3bbbf8da209f287882ce79ff4daf8f454b994ddc7510df99", + ".local/rust-material-rule-library-parity/biome_tags.json": "4006b76c24f616cb457a6fdad816db9b27f4528fe6daaed5747f1f79cf6225cf" + }, + "rust_output_sha256": "8f4055c8b6b4ca1a01c1451808a76a79ea5453cc5bfca21d879810a3322ca10d", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "8f4055c8b6b4ca1a01c1451808a76a79ea5453cc5bfca21d879810a3322ca10d", + "matched_output_lines": 678174 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "8f4055c8b6b4ca1a01c1451808a76a79ea5453cc5bfca21d879810a3322ca10d", + "matched_output_lines": 678174 + } + ], + "scope": "All bundled material-rule definitions loaded against authenticated condition, biome/tag, block-state, noise and density registries, then compiled/evaluated for both world random modes. Forward/nested rule holders, all five rule kinds, malformed/omitted fields and property fallback, actual seeded density/richness/gap sources, strided chunk-volume caching, scalar fallback and independent context/application positions are covered. Surface depth and secondary noise remain supplied context inputs; preliminary density is zero for isolation. All bundled biome climates are used, with unrestricted or complete possible-biome sets. Rust library definitions are immutable and atomically loaded, with typed cycle/resource-bound errors. Rule/density encoding, live reload/registry owner validation, complete surface-stage chunks and gameplay remain pending." +} diff --git a/benchmarks/rust-material-stage-2026-10-06/scoped-parity.json b/benchmarks/rust-material-stage-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..eb6e129f8 --- /dev/null +++ b/benchmarks/rust-material-stage-2026-10-06/scoped-parity.json @@ -0,0 +1,180 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "resources": { + "noises": 64, + "densities": 55, + "rules": 42, + "settings": 7, + "carvers": 4, + "conditions": 8, + "biomes": 67, + "biome_tags": 86, + "block_tags": 300 + }, + "fixtures": 79, + "generated_carving_passes": 42, + "carving_passes": 158, + "top_material_queries": 7584, + "surface_builds": 106, + "terrain_builds": 42, + "biome_chunks": 378, + "biome_values": 400896, + "block_values": 21757952, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialStageOracle.java": "2eda078914d39c40ff995e465a0be02dc413d9de8fd9272b9658a4d1587762b5", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialConditionOracle.java": "04a87405fd2a1c79baf4eb3a8895aa66dc96b8f6baffb9b486ef207f8b91b5ee", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java": "226628d98b89aadbdd374936575d033945e7064a900dbb050c662204dbc7e119", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java": "243bbc525c6aec24674e7f172c5fb4f7b50f9a679d8b9dfba40ea278219a2d28", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java": "145c943637ed177cc4ef8a85f2484da8afd164868e84a8463882feec1653a860", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeExport.java": "f9a773713cf21b69bfa10018b76f27b953bda140ede9934f43d3aa3091101cf5", + "tools/test_material_stage_parity.py": "002cc17628a05b94ce4d40e1e5c29240d1a87ea8fc29281794e0a2e42be7add2", + "tools/test_material_condition_parity.py": "01c82e1a768d9131f8f7e6d59d01ddb06272074469dbdcd8547f44f0a8fa152d", + "tools/test_biome_temperature_parity.py": "68f84d02e7802349e491b8cb66e18d9b08c9e72ab2306b663667259e852cc2b1", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "476f1542d335eb02fb627b7480d708f4aa6b7f9929f4dbc2c646e15b063cf083", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "ecf8fd3be57fa773033bac4a303a951f8c12dcd5cbb4d5432a21534525a69546", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "db91c00342842cab4f001b1428692d12dce7fa43b0704a7c0bb6f4f26ad8e2d9", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/height_provider.rs": "c9a148cdbd392b4ae998e466120c0870eb121736366a160347e1a697bdad914f", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "42823918deec5e149dc729a95bfe54aa32d91604098d5eb8452da0162d557d22", + "crates/horizon-world/src/worldgen/value_provider.rs": "7083e7a494894e080c252e7fb485651eb9f54e72043122e4f2b5bee5749e6184", + "crates/horizon-world/src/worldgen.rs": "58527080379e82d834763d661ebf51fb8f9a83f6d530c85ddf26bf0ea2d53f7d", + "crates/horizon-world/examples/material_stage_fixture.rs": "58f2b8cbcc537c43c4596a9d0ef937ae4e23612a49a7865ab5546bc346726d96" + }, + "fixtures_sha256": { + ".local/rust-material-stage-parity/inputs.txt": "7b0e92acc72ccf74f8f89a0feb2c5d42a65cf479ce86ed4338c2fe01d2e2cb83", + ".local/rust-material-stage-parity/presets-client.json": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9", + ".local/rust-material-stage-parity/presets-server.json": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9", + ".local/rust-material-stage-parity/facts-client.json": "e4b5e33240a44a6c86a5ec0a3793c22b507e8aea31ea85ed6d6c9d3069384e7f", + ".local/rust-material-stage-parity/facts-server.json": "e4b5e33240a44a6c86a5ec0a3793c22b507e8aea31ea85ed6d6c9d3069384e7f", + ".local/rust-material-stage-parity/noises.json": "310b240c9b70586bb704ca44a915766a8d41d6a073183324c37184fcb317a992", + ".local/rust-material-stage-parity/densities.json": "28fe94e1b7cf3a06edfa2337319c03b5374c15bf18235570ee76e9c498c2f450", + ".local/rust-material-stage-parity/rules.json": "b47af5bc7a19f2f3796326b310af49d677432ac87c6c9f4dc9c9cc4664fd5afb", + ".local/rust-material-stage-parity/settings.json": "dcc7d892420fb3faadab36c935ef0d2d8709a038a8fb944c00e354f417b3b586", + ".local/rust-material-stage-parity/carvers.json": "b09cf69ff328cad7836da8cd9565d0fb7ecf8bc35aebf17815f40f32a6a0ca4e", + ".local/rust-material-stage-parity/conditions.json": "54a470a4513fb34a23e0fe66b0a5129a468dbd0002f5b2839437a9861a6005b9", + ".local/rust-material-stage-parity/biomes.json": "9b26dc3b662627dc3bbbf8da209f287882ce79ff4daf8f454b994ddc7510df99", + ".local/rust-material-stage-parity/biome_tags.json": "4006b76c24f616cb457a6fdad816db9b27f4528fe6daaed5747f1f79cf6225cf", + ".local/rust-material-stage-parity/block_tags.json": "36975358262568f32bf84778d63d9989a36e7394ed4796d70a34809a8f4a64f0", + ".local/rust-material-stage-parity/presets.json": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9" + }, + "rust_output_sha256": "6cf2554dae38af3e828ce4f04934b5f08b1db0c034c5e95f4087e3a17ef2ae3d", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "6cf2554dae38af3e828ce4f04934b5f08b1db0c034c5e95f4087e3a17ef2ae3d", + "matched_output_lines": 6733382 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "6cf2554dae38af3e828ce4f04934b5f08b1db0c034c5e95f4087e3a17ef2ae3d", + "matched_output_lines": 6733382 + } + ], + "scope": "Actual MaterialSystem.buildSurface and topMaterial against ProtoChunk before lighting, with complete raw sections, WG heightmap words, ordered fluid-postprocessing offsets and biome-lookup traces. All bundled rule registries, both seeded random modes, real surface/band/extension noises, real or supplied preliminary density, ore densities, empty/populated chunks, synthetic vertical spans/cavities/nondefault solids, clipped generation writes, lazy/primed maps and repeated surface builds sharing density contexts. Synthetic prefilled fixtures use a supplied deterministic block-position biome resolver; generated terrain fixtures first generate a 3x3 biome neighborhood through actual ChunkGenerator.doCreateBiomes, using pinned multi-noise preset tables or the End biome source. Complete stored biome values and subsequent BiomeManager block/quart lookup traces are compared. Both runtimes load the biome-source JSON against their biome/preset registries before generation. Rust imports independently authenticated preset tables; preset builders remain outside this comparison. Block air/fluid identities are imported from both authenticated JARs and motion predicates use resolved block tags. Each fixture applies an explicit carving mask twice through actual NoiseBasedChunkGenerator.applyCarvingMask after surface and top-material queries. The native aquifer is wrapped only to trace ordered computeSubstance/results/fluid-scheduling queries. Filtered and unfiltered passes, uncarvable tags, grass/mycelium/dirt restoration, repeated writes and disjoint runs are compared, followed by full chunk/heightmap/postprocessing dumps. Generated fixtures additionally invoke actual generateCarvers with biome carver settings selected from a 17x17 origin neighborhood, ordinal world seeds, native start checks and cave/canyon paths. The same source is reused after biome filling, preserving prior search state; a traced wrapper exposes uncached quart lookup order. Terrain/aquifer/postprocessing state is compared after procedural carving before explicit mask stress. Native carver settings retain actual carver holder lists while placed features are empty, as features are not evaluated in this stage. Each completed fixture also queries topMaterial at column edges and interior positions, above/below vertical bounds and around sea level, in dry and submerged contexts; these bind fresh one-cell material contexts without possible-biome restrictions. Empty blending only. Generated terrain fixtures also invoke actual NoiseBasedChunkGenerator.doFill before the surface stage, sharing a NoiseChunk and comparing full chunk state before and after surface builds for all bundled terrain routers and aquifers. Biome/feature/structure stages, nonempty blending, lighting and complete generated worlds/gameplay remain pending." +} diff --git a/benchmarks/rust-material-surface-2026-10-06/scoped-parity.json b/benchmarks/rust-material-surface-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..13c1637ed --- /dev/null +++ b/benchmarks/rust-material-surface-2026-10-06/scoped-parity.json @@ -0,0 +1,118 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 277, + "surface_queries": 5263, + "noise_resources": 64, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialSurfaceOracle.java": "37ecc58f73344830bc743075d813411ace42032e23b6c4572a1d2e5206d30fc3", + "tools/test_material_surface_parity.py": "8fcc300339e33017c4475adce5ae1d0fb79ae7eae95f70015fda58f8d383c1a2", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry.rs": "f46065659e60eb5e84ad69b9f3b5e94dc87ee19de16408817e26f23d16b6c7e7", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "134cf93b53a40fb1ed0e0170c90316c80e270773b2968c63dc3f9cef2c941bff", + "crates/horizon-world/src/worldgen.rs": "3460256893108079ecebed39d496b0d1ad17feb5193455ad8c51f441dfd19b2f", + "crates/horizon-world/examples/material_surface_fixture.rs": "5283d0c1cabfc0585e259525bba09a1acf30a749cfa7d8735bac415f3505305f" + }, + "fixtures_sha256": { + ".local/rust-material-surface-parity/inputs.txt": "2f070e7a9cc33fd7c5fba9a76dfedde9514aca66e36c7599b46b5a2d2e2ab0eb", + ".local/rust-material-surface-parity/noises.json": "310b240c9b70586bb704ca44a915766a8d41d6a073183324c37184fcb317a992" + }, + "rust_output_sha256": "f36a2c1972b0cce429fd2ef23a4dae9f91b134ca161f085c27da03b2ff74e0f3", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "f36a2c1972b0cce429fd2ef23a4dae9f91b134ca161f085c27da03b2ff74e0f3", + "matched_output_lines": 122988 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "f36a2c1972b0cce429fd2ef23a4dae9f91b134ca161f085c27da03b2ff74e0f3", + "matched_output_lines": 122988 + } + ], + "scope": "Actual MaterialSystem.generateBands and constructor-generated terracotta bands, protected getBand/getSurfaceDepth/getSurfaceSecondary methods. Both random streams, direct and world-root-derived clay_bands child streams, preconsumed inputs, complete 192-state band arrays and subsequent RNG draws. Surface lookups use independently authenticated bundled noise definitions, world-root positional random factories and optional constant-noise overrides for rounding/cast edges, nonfinite float values and signed integer overflow/remainder. Raw float-to-double secondary bits use canonical NaNs. Registry adapter identity binding, full material rule evaluation, eroded badlands/frozen ocean extensions and surface-stage chunk integration remain pending." +} diff --git a/benchmarks/rust-noise-2026-10-05/scoped-parity.json b/benchmarks/rust-noise-2026-10-05/scoped-parity.json new file mode 100644 index 000000000..bd9a46e65 --- /dev/null +++ b/benchmarks/rust-noise-2026-10-05/scoped-parity.json @@ -0,0 +1,71 @@ +{ + "schema": 1, + "minecraft": "26.3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "commands": { + "wrap": 12026, + "create": 384, + "query": 234497, + "local": 38400, + "volume": 14208, + "stack": 723, + "normal": 3600 + }, + "inputs_sha256": "358956a9ee89ce2db357f6ad9b8b3c1fba68008d044af4758f3ae73e1249ad6d", + "rust_output_sha256": "21a1c084822f9ea6e97421e4280727fae1b9c01c1b04e1f44e552ccb84b6e92b", + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNoiseOracle.java": "ac087a06452fbbe2823875cd771d7c06be313f3320aa0efa6e16c64c399c562e", + "tools/test_noise_parity.py": "3f2bcccc2fb8ff42f7d9d9b4c8f8df992195779144113309de8f411780fce595", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "86e7a87439acf5458be3c9b6ed5dfc3705170f39483ec0f1c2b723b4f5e3ff28", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "f00ebba7484168ae0064fa993ace9afafb323c3222ab80cfee3792bd98562e8d", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-core/Cargo.toml": "f9aff52d34439ed6511b026beee5cbd9918f34cc0a67e90e441df12c905a6dc0", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "faae2edce8b573fd32fcb4bd1f898be7d700a5b38479439f5bec96df764688fd" + }, + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "21a1c084822f9ea6e97421e4280727fae1b9c01c1b04e1f44e552ccb84b6e92b", + "matched_output_lines": 1443539 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "21a1c084822f9ea6e97421e4280727fae1b9c01c1b04e1f44e552ccb84b6e92b", + "matched_output_lines": 1443539 + } + ], + "scope": "26.3 gradient offsets, permutation tables, constructor RNG consumption, ranges, coordinate wrap, Perlin 2D/3D and derivative accumulation, simplex 2D/3D with both offset modes, smeared Perlin 2D/3D and inherited unsmeared derivatives; bounded strided density volumes, wrapped block coordinates, flat indices, cached and scalar bulk accumulation with preserved buffer tails; nested and flattened noise stacks; normal-noise octave construction, enabled/disabled/legacy normalization, parity factory, modern positional seeding, legacy Nether biome initialization, failure draw state, scalar and bulk sampling. Finite outputs and signed zeros compared by bits; NaNs canonicalized. No serialized noise definitions, density-function graphs, generated terrain, gameplay, rendering or performance claim." +} diff --git a/benchmarks/rust-piston-shape-2026-10-06/scoped-parity.json b/benchmarks/rust-piston-shape-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..d13eb0942 --- /dev/null +++ b/benchmarks/rust-piston-shape-2026-10-06/scoped-parity.json @@ -0,0 +1,177 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "block_states": 35723, + "kinematic_cases": 10000, + "fixtures": 102315, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonShapeOracle.java": "f8ce2b8d50a2ca8dfd131968cf79437af6ec686a827fdc0841dcd528418f43de", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFaceSupportOracle.java": "9ce939a435842867786fed648951bbe77f6ab843f6df09af15f3deb1948c4877", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java": "5c217a8cb72094020082bd4846ed675a6399b9fa371be95a221bd92d227b2e09", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java": "02acfbae94aee306c5a4e1db7c86c68f7d6156ddd3dd477dc9e9d06e5ca98118", + "tools/test_piston_shape_parity.py": "e1bed92b9f9fbdbcd42eba540bdb06c64cd2ddbb9e522943b96cf1764b87860e", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/face.rs": "f243bce81384040a95ce7984b02b5699206c596c537b2713097e86005b4d3a5c", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "e8d88a763de1525f77a30b99591641e8a8b80946263acbde035a9bcc356df960", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/block_properties.rs": "e74b368012d4d440dcdbd4d9bcaf80495220b90557f0e0c733b0aa21ad03c53c", + "crates/horizon-world/src/block_support.rs": "ade4fbd47284b450dabdd682dc86138b2ac05a0fd379525d7110648908245476", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "05313e0c1f3089524fe029f9aac3e439cd47f1c9584c8c7e154c9adcfa88c335", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/dynamic_support.rs": "1bf4ad95fcdf7f2df4e33dde38e08959d9b76a6260838c13e97c2bb59e006294", + "crates/horizon-world/src/entity_obstruction.rs": "a4b28a19bf83b23611c59d94535c488db37e4aee24b22c973c545910894a809f", + "crates/horizon-world/src/fluid.rs": "8a2834a9347ee2c2db7cf1c86a064907ec06e9ac16ba9cc3936e315fc4ad49ca", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "d347020c29ea795b6f9554828a84274d27820bdaf6257ce3b2d265c5c9051ecc", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/piston_shape.rs": "399c2337103b8e7e0eb5667227c5aa14f9549d6a467b7be7da3d0717f0263500", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "3fe316b875aa32683759c337dc71f624910faf0812a2d6d83b8098d6d0bac7a0", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "d6389c8d1adf900eb8f0e6c8833feafe43dc92d74e5c7ffa6f3950975529d624", + "crates/horizon-world/src/worldgen/biome_predicate.rs": "bfc581bc40077cc74ffda43e990a55fe997adc04c7130f98e039c3305ca79aac", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "7c8f628601a6d835d913c034b0d421a8f83bee6c569033448aac99123ed84a2c", + "crates/horizon-world/src/worldgen/block_predicate.rs": "535c9840de71704f0338b5d77c63084aceb5239644f9ebb6f2993b95acfec042", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/decoration.rs": "75a79b20b21e133816e729f16e758be6165d0db18a64bfbd5fd3618325a2adf3", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "fe61a5e43179a7588737a71782ea246811fe2c8721e74793e1ac018c8eb93c34", + "crates/horizon-world/src/worldgen/feature_region.rs": "2c78e5f1bdb08307f8d982f231f1abbc3306cd54348d9023b86ee6ed3516fd33", + "crates/horizon-world/src/worldgen/feature_sort.rs": "3488a093dfe1321aaa29d8a30cfb115d8e666a81bf195514e87b170de626835c", + "crates/horizon-world/src/worldgen/fluid_predicate.rs": "e682d13a21f90605215b79f5d254bf2e524d35e89eab2e3b46384709af80b847", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "09d79c5acf7332e18a9049aed1a05c38a2bccbc6c2f20bbac560f2e58c35c6f5", + "crates/horizon-world/src/worldgen/placement/context.rs": "d801e1831200ddd9161ea960aa0009c9f5b8227d2113027abf88ad48ca259eed", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "b0397e5818fae84358546193a95f84bcb0b5bffafce909e6fcb3386179ee8023", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/state_provider/catalog.rs": "fa0616353f07460975ab323357ab280b7f35e7bfe2de6edc08d304316766ed26", + "crates/horizon-world/src/worldgen/state_provider/noise.rs": "7ee369c2a032e5620cb9bdf9ee7adad1f70870fb0a27efb7b7c514d92f83491f", + "crates/horizon-world/src/worldgen/state_provider/properties.rs": "9909139aaca1dc4f743957257fadaa9d423d21fa401fa9abc050505f79365139", + "crates/horizon-world/src/worldgen/state_provider.rs": "647f253a7d14d724086b4d146f26295e0da825df86f4adbd6a0e367d5198f3d5", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "3358b563db8cb0bc8a9cfbbe2b8b3e70941cd2d37a0b519fbb6545f8d0dcbb69", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "821981c893fc84312351503f2be0c06c681d8bc768dade14576697cf047a9f8f", + "crates/horizon-world/examples/piston_shape_fixture.rs": "d3c6ae35bfd1183fcfe5360b0c175bd008c29b0db001bad122dbc2fc3169dab3" + }, + "fixtures_sha256": { + ".local/rust-piston-shape-parity/inputs.txt": "cc974edd3f7053e7b29d9f34695a3dde8bd5fdffdd034e3972f80dc56b4452ec", + ".local/rust-piston-shape-parity/facts.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b", + ".local/rust-piston-shape-parity/block-registry.nbt": "5042073c80753f9548cb8fdb5b1000f0e5a1220127a0cc3c6a75737e180bf9bb", + ".local/rust-piston-shape-parity/cached-collision.nbt": "f3a5c6a5b2d51dad6c52e486e2b9989e79fd55db1a9bda6196db399550b04078" + }, + "rust_output_sha256": "c86088bc353d6bb31da1aa6b9918c689bccc67da07129fcb38de21a639fb5ca7", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "c86088bc353d6bb31da1aa6b9918c689bccc67da07129fcb38de21a639fb5ca7", + "matched_output_lines": 1096811 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "c86088bc353d6bb31da1aa6b9918c689bccc67da07129fcb38de21a639fb5ca7", + "matched_output_lines": 1096811 + } + ], + "scope": "Actual moving-piston entity collision shape, interpolation/offset float bits, movement direction and collision-related block-state selection. Every registered moved state is sampled, piston-base/source/extension/head thresholds and all noclip directions are crossed, and dynamic block-entity query failures are compared. Cached collision geometry is imported privately; uncached moved blocks use Rust support selection only in the tested empty-collision-context, absent-block-entity world. Piston ticking, entity pushes, live block entities, networking and full gameplay remain pending." +} diff --git a/benchmarks/rust-placement-2026-10-06/scoped-parity.json b/benchmarks/rust-placement-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..69df2a846 --- /dev/null +++ b/benchmarks/rust-placement-2026-10-06/scoped-parity.json @@ -0,0 +1,153 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 21840, + "modifier_kinds": 17, + "predicate_kinds": 5, + "definitions": 520, + "requested_modifications": 70080, + "requested_counts": 17280, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java": "12b1c46cc397755ef6827da777faef3e71c008cafa48403669c03ca2bdc3c7cb", + "tools/test_placement_parity.py": "eeb3759f09561e00c9ec436bef84d2c14358a1e839e06b1214580f6fe043fc5d", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/placement/chain.rs": "76832dd4f76b44edfcc8bd52d8115f6e30684bfaea0e0b959ba060f07cc3483d", + "crates/horizon-world/src/worldgen/placement/context.rs": "b36dfd9297896e62770f2085cf934fc08ebd4c030ecc7ae17d864e819a113201", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "f9d264985d0ce6a7eb91a4f559661efbecc5a3fe097ce559f6acbcf0132c8c87", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "42823918deec5e149dc729a95bfe54aa32d91604098d5eb8452da0162d557d22", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "1ae40b843721d0f1e1c849b984e0a065aacda6e1384e21fc599cda261f996945", + "crates/horizon-world/src/worldgen.rs": "edc1d675acc52d264486a3c8c56e93a21ebf2c6a73da912f35b8fa2a7233cdde", + "crates/horizon-world/examples/placement_fixture.rs": "ad7ba1c87b033f26967e8a3b773bc656e03f41cbbf9e45f2a3687fd0b11c3deb", + "crates/horizon-world/examples/support/placement_queries.rs": "623b98c33245cb584d666a06bd5a3ddf7f19bf77e0ea9dc67be9a242086c063c" + }, + "fixtures_sha256": { + ".local/rust-placement-parity/inputs.txt": "7809f8d0b891cc84e12f317504b67493e2998a1f528517ec918bd49de810b6e5" + }, + "rust_output_sha256": "a9ebcecfb5ada440004a86c2a65de67968d648bdf5126dbdafa92ecf7b575d5a", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "a9ebcecfb5ada440004a86c2a65de67968d648bdf5126dbdafa92ecf7b575d5a", + "matched_output_lines": 1268600 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "a9ebcecfb5ada440004a86c2a65de67968d648bdf5126dbdafa92ecf7b575d5a", + "matched_output_lines": 1268600 + } + ], + "scope": "Actual PlacementModifier.CODEC parsing and modify callbacks for count, in-square, offset, height-range, rarity, random-chance, fixed-position randomly-selected, heightmap, surface-relative-threshold and surface-water-depth modifiers, plus native noise-based and noise-threshold repeating counts and cuboid placement with edge/interior controls and count-on-every-layer scans, predicate filters and environment scans. Logical and inside-world-bounds predicates preserve short-circuiting and offset wrapping; traced world-bound queries expose scan termination, final target tests and failures. Layer scanning uses traced synthetic block strata containing air variants, water/lava, ordinary ground, bubble columns and bedrock; callbacks and injected height/block failures preserve query order and random consumption. Both random modes, repeated calls, zero counts, inclusive provider bounds, nested random choices, anchored and overflowing coordinates, same-chunk fixed filtering, duplicates, malformed fields and failing consumers. Consumer callbacks optionally draw from the shared random stream; subsequent nextLong values verify exact consumption. Contexts use an actual PlacementContext with a traced WorldGenLevel proxy and native noise generator. Heightmap queries use traced synthetic world responses, ordinary/extreme heights and injected query failures; world minimum and generation minimum can differ. Noise count-only calls include extreme ratios, factors, offsets and thresholds without expanding huge position lists. Additional block predicates, biome filtering, configured features, provider encoders, Gaussian providers and complete world generation remain pending." +} diff --git a/benchmarks/rust-replace-block-2026-10-06/scoped-parity.json b/benchmarks/rust-replace-block-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..e803da170 --- /dev/null +++ b/benchmarks/rust-replace-block-2026-10-06/scoped-parity.json @@ -0,0 +1,161 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 14840, + "block_states": 35723, + "integer_properties": 146, + "requested_placements": 44520, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaReplaceBlockOracle.java": "12de4d544e91d7e470fe225389ea8901a9590b89e9a16a1fb3bfc762584cd847", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java": "5c217a8cb72094020082bd4846ed675a6399b9fa371be95a221bd92d227b2e09", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java": "145c943637ed177cc4ef8a85f2484da8afd164868e84a8463882feec1653a860", + "tools/test_replace_block_parity.py": "7c670b047595bf2753a5e362f1c360d58944e2610e8598e4cea22d1ad2c7738b", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "23b2a335505bebfa512f2fee699cf0bf69f65b59ddf22add616fc5a3fcf5432c", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "2297b194514925688dba25016a69d5ba5eb8b869bdfff28f2e611a6742ac5954", + "crates/horizon-world/src/worldgen/feature_region.rs": "4a95a30c0987d97e671f84380e13ddea070ad81f996baa65b2a06c4d892971c7", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "1b976aa4dd2516468196d0af3451e3fdd037493a14d269f54ebdd7254055e05e", + "crates/horizon-world/src/worldgen/placement/context.rs": "b36dfd9297896e62770f2085cf934fc08ebd4c030ecc7ae17d864e819a113201", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "68ecf36954fea5705436d486e9be93836933fd56779022afeb881a0399d6a674", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "3ffc2db40a9c2d0ecc2d8de68f9d853c2d11320709139a203d4b3f5f9023fb0a", + "crates/horizon-world/examples/replace_block_fixture.rs": "15a088eb29f4efbe9ec1f872cea0f108cea080424d984516db6f3858217319f6" + }, + "fixtures_sha256": { + ".local/rust-replace-block-parity/tags.json": "36975358262568f32bf84778d63d9989a36e7394ed4796d70a34809a8f4a64f0", + ".local/rust-replace-block-parity/facts-client.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b", + ".local/rust-replace-block-parity/facts-server.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b", + ".local/rust-replace-block-parity/inputs.txt": "cc29f71f4afaa654bcea09f182cfcd3d04bbc64acc5e965e3082e8bfb1e5e132" + }, + "rust_output_sha256": "86fe7a04e08d0f2690843a8dab63cfb27be2fc491e1eb3c7fa053a1d2c05904d", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "86fe7a04e08d0f2690843a8dab63cfb27be2fc491e1eb3c7fa053a1d2c05904d", + "matched_output_lines": 303678 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "86fe7a04e08d0f2690843a8dab63cfb27be2fc491e1eb3c7fa053a1d2c05904d", + "matched_output_lines": 303678 + } + ], + "scope": "Actual replace_single_block feature codecs and native ReplaceBlockFeature.place. Ordered target rules re-read the origin state, short-circuit on the first match, preserve random draw order and write flags, ignore rejected writes, retain partial mutations and stop on injected read/write failures. Bound block/tag/state/height/random/logical targets and malformed unselected entries are compared across both random modes and repeated calls. Full region side effects, structure processors, ore clusters and complete gameplay remain pending." +} diff --git a/benchmarks/rust-rule-test-2026-10-06/scoped-parity.json b/benchmarks/rust-rule-test-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..686e1c15a --- /dev/null +++ b/benchmarks/rust-rule-test-2026-10-06/scoped-parity.json @@ -0,0 +1,163 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "block_states": 35723, + "blocks": 1286, + "integer_properties": 146, + "codec_inputs": 75920, + "rule_types": 10, + "block_tag_files": 300, + "requested_tests": 1866052, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRuleTestOracle.java": "881ca5018ee48b5853f98aa1232462523a9bf6b3b5818e27a5a2a4a809a8bca2", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java": "5c217a8cb72094020082bd4846ed675a6399b9fa371be95a221bd92d227b2e09", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java": "145c943637ed177cc4ef8a85f2484da8afd164868e84a8463882feec1653a860", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rule_test_parity.py": "ac7d41cda769b1538dd6bcfb8b5b21215b869220b35defb07725d0eb58f8c1ae", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "2f5e4f01628dd783c3c21203be533db585caacfe3eb26037fc5cd05e574d8273", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "5df2e58e2070b3a9e205b3cb7f52936fad16b5bcf538c2c2861a9d94d5ea90c1", + "crates/horizon-world/src/worldgen/feature_region.rs": "4a95a30c0987d97e671f84380e13ddea070ad81f996baa65b2a06c4d892971c7", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/placement/chain.rs": "1b976aa4dd2516468196d0af3451e3fdd037493a14d269f54ebdd7254055e05e", + "crates/horizon-world/src/worldgen/placement/context.rs": "b36dfd9297896e62770f2085cf934fc08ebd4c030ecc7ae17d864e819a113201", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "68ecf36954fea5705436d486e9be93836933fd56779022afeb881a0399d6a674", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "8494d32cbc0bf0b8f4b50c7e83e123f66d12490181844f14f633921dd7e20676", + "crates/horizon-world/examples/rule_test_fixture.rs": "91aa337a4d2b44b37003716658bbcd739479f23714471a2f2af73fb23cb58310" + }, + "fixtures_sha256": { + ".local/rust-rule-test-parity/inputs.txt": "4c101191c2f0feb5f4c9597dc90eba62246af06ab60ece43ff9535e88973da6d", + ".local/rust-rule-test-parity/tags.json": "36975358262568f32bf84778d63d9989a36e7394ed4796d70a34809a8f4a64f0", + ".local/rust-rule-test-parity/facts-client.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b", + ".local/rust-rule-test-parity/facts-server.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b" + }, + "rust_output_sha256": "22050d0a64e4406d86231a0d905d978a294734e1a5adc9501b819ebd3f3fa5e3", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "22050d0a64e4406d86231a0d905d978a294734e1a5adc9501b819ebd3f3fa5e3", + "matched_output_lines": 1890716 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "22050d0a64e4406d86231a0d905d978a294734e1a5adc9501b819ebd3f3fa5e3", + "matched_output_lines": 1890716 + } + ], + "scope": "Actual RuleTest.CODEC and all ten registered replacement-rule types. Every block and block-state identity, all bundled block tags, absent tags, inclusive and reversed height ranges, unrestricted random probabilities, logical short-circuit evaluation, malformed inputs, both random modes and subsequent draws are compared. Registry metadata and tag resources independently agree across authenticated JARs. Bound tags are immutable snapshots. Replacement feature mutations, structure processors, reload ownership and complete gameplay remain outside this standalone comparison." +} diff --git a/benchmarks/rust-scattered-ore-2026-10-06/scoped-parity.json b/benchmarks/rust-scattered-ore-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..e5abaaeb2 --- /dev/null +++ b/benchmarks/rust-scattered-ore-2026-10-06/scoped-parity.json @@ -0,0 +1,161 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 11544, + "block_states": 35723, + "integer_properties": 146, + "requested_placements": 23088, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaScatteredOreOracle.java": "3c635f6a2c169688db210710eebb269a91fad6432fc84485a41f1059f9a6e895", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java": "5c217a8cb72094020082bd4846ed675a6399b9fa371be95a221bd92d227b2e09", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java": "145c943637ed177cc4ef8a85f2484da8afd164868e84a8463882feec1653a860", + "tools/test_scattered_ore_parity.py": "7834042bcba27f5f538a063e173d49b73f7b1a174fda2086c3e4955a4ea9daed", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "23b2a335505bebfa512f2fee699cf0bf69f65b59ddf22add616fc5a3fcf5432c", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "2297b194514925688dba25016a69d5ba5eb8b869bdfff28f2e611a6742ac5954", + "crates/horizon-world/src/worldgen/feature_region.rs": "4a95a30c0987d97e671f84380e13ddea070ad81f996baa65b2a06c4d892971c7", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "1b976aa4dd2516468196d0af3451e3fdd037493a14d269f54ebdd7254055e05e", + "crates/horizon-world/src/worldgen/placement/context.rs": "b36dfd9297896e62770f2085cf934fc08ebd4c030ecc7ae17d864e819a113201", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "68ecf36954fea5705436d486e9be93836933fd56779022afeb881a0399d6a674", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "3ffc2db40a9c2d0ecc2d8de68f9d853c2d11320709139a203d4b3f5f9023fb0a", + "crates/horizon-world/examples/scattered_ore_fixture.rs": "1f5d77e1ce57230a1ca80870fd139fad8405a74e36b18bc781e2cdd61ec3eddf" + }, + "fixtures_sha256": { + ".local/rust-scattered-ore-parity/tags.json": "36975358262568f32bf84778d63d9989a36e7394ed4796d70a34809a8f4a64f0", + ".local/rust-scattered-ore-parity/facts-client.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b", + ".local/rust-scattered-ore-parity/facts-server.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b", + ".local/rust-scattered-ore-parity/inputs.txt": "16b9b7dc315f01f8a86a063323f261e91047096131e46df9fbf721eccdaa8c0f" + }, + "rust_output_sha256": "2f63fa6cb1317368053a1983f0cac8914c8f3139bee1ddb1d3e376b8c9913c29", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "2f63fa6cb1317368053a1983f0cac8914c8f3139bee1ddb1d3e376b8c9913c29", + "matched_output_lines": 758484 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "2f63fa6cb1317368053a1983f0cac8914c8f3139bee1ddb1d3e376b8c9913c29", + "matched_output_lines": 758484 + } + ], + "scope": "Actual scattered_ore feature codec and native ScatteredOreFeature.place. Attempt counts, six float draws per offset, Java rounding, wrapped coordinates, state capture per attempt, ordered target predicates, conditional air-exposure draws, directional neighbor reads, early air detection and mutation flags/results/errors are compared. Both random modes, size/discard boundaries, empty targets, repeated calls, solid/mixed/directional-air worlds and partial failures are included. Complete ore veins, region side effects, chunk decoration and gameplay remain pending." +} diff --git a/benchmarks/rust-state-provider-2026-10-06/scoped-parity.json b/benchmarks/rust-state-provider-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..44f186dd5 --- /dev/null +++ b/benchmarks/rust-state-provider-2026-10-06/scoped-parity.json @@ -0,0 +1,213 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "block_states": 35723, + "blocks": 1286, + "integer_properties": 146, + "codec_inputs": 299507, + "provider_types": 10, + "named_providers": 22, + "rule_predicate_types": 16, + "survival_supported_blocks": 1138, + "survival_supported_states": 31171, + "support_cached_states": 35524, + "support_dynamic_states": 199, + "biomes": 67, + "biome_tag_files": 88, + "fluid_tag_files": 11, + "bundled_provider_definitions": 8, + "block_tag_files": 302, + "requested_samples": 39270062, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStateProviderOracle.java": "33ca3001656490ad4eb66e1e61ded306de4e448210eb7aca6299a068780761a0", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java": "5c217a8cb72094020082bd4846ed675a6399b9fa371be95a221bd92d227b2e09", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java": "145c943637ed177cc4ef8a85f2484da8afd164868e84a8463882feec1653a860", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialConditionOracle.java": "04a87405fd2a1c79baf4eb3a8895aa66dc96b8f6baffb9b486ef207f8b91b5ee", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java": "243bbc525c6aec24674e7f172c5fb4f7b50f9a679d8b9dfba40ea278219a2d28", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java": "226628d98b89aadbdd374936575d033945e7064a900dbb050c662204dbc7e119", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPropertiesOracle.java": "82e5cadbcdcba5b4577c56c5a033262b066ccc4cc4a14c7c48ce46c4c6247a03", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSupportOracle.java": "04350901a2d708fb8fa672de61d058f73f332d2e90df1b93a67781862f89c1ad", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSurvivalOracle.java": "00010bad8feea549c4243787e0d594b467a3227236a38c2e528d4247c7ba1c70", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java": "02acfbae94aee306c5a4e1db7c86c68f7d6156ddd3dd477dc9e9d06e5ca98118", + "tools/test_block_survival_parity.py": "e2f661afbf67a8726c9423d610f8b05b9e348c8140c40efb3aafaca0291efe31", + "tools/test_biome_temperature_parity.py": "68f84d02e7802349e491b8cb66e18d9b08c9e72ab2306b663667259e852cc2b1", + "tools/test_material_condition_parity.py": "01c82e1a768d9131f8f7e6d59d01ddb06272074469dbdcd8547f44f0a8fa152d", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_state_provider_parity.py": "f52ab05832e9e9acf8aae779c3e199a1cd836592f1a993837edb0757d87b0f55", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/face.rs": "f243bce81384040a95ce7984b02b5699206c596c537b2713097e86005b4d3a5c", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "e8d88a763de1525f77a30b99591641e8a8b80946263acbde035a9bcc356df960", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/block_properties.rs": "e74b368012d4d440dcdbd4d9bcaf80495220b90557f0e0c733b0aa21ad03c53c", + "crates/horizon-world/src/block_support.rs": "ade4fbd47284b450dabdd682dc86138b2ac05a0fd379525d7110648908245476", + "crates/horizon-world/src/block_survival.rs": "d7e4ba3709fe1fe1b4998d067080bf48ebfc549cdfc883d8d648d13d6fdf4e3f", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "05313e0c1f3089524fe029f9aac3e439cd47f1c9584c8c7e154c9adcfa88c335", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/dynamic_support.rs": "1bf4ad95fcdf7f2df4e33dde38e08959d9b76a6260838c13e97c2bb59e006294", + "crates/horizon-world/src/entity_obstruction.rs": "a4b28a19bf83b23611c59d94535c488db37e4aee24b22c973c545910894a809f", + "crates/horizon-world/src/fluid.rs": "8a2834a9347ee2c2db7cf1c86a064907ec06e9ac16ba9cc3936e315fc4ad49ca", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "69cdc611b7a7e20a7da705fcc25de6b97cdb64cf63f954be49d0a11f9a820465", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/piston_shape.rs": "399c2337103b8e7e0eb5667227c5aa14f9549d6a467b7be7da3d0717f0263500", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "3fe316b875aa32683759c337dc71f624910faf0812a2d6d83b8098d6d0bac7a0", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "d6389c8d1adf900eb8f0e6c8833feafe43dc92d74e5c7ffa6f3950975529d624", + "crates/horizon-world/src/worldgen/biome_predicate.rs": "bfc581bc40077cc74ffda43e990a55fe997adc04c7130f98e039c3305ca79aac", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "6be7c0161cecf1362c196e91ecbeb166e16c8da3731d988ce8f2308f06209265", + "crates/horizon-world/src/worldgen/block_predicate.rs": "074c692367e3f2191a1bb28d87b23402430a843c246bd30a4ea838ee3500280e", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/decoration.rs": "75a79b20b21e133816e729f16e758be6165d0db18a64bfbd5fd3618325a2adf3", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "fe61a5e43179a7588737a71782ea246811fe2c8721e74793e1ac018c8eb93c34", + "crates/horizon-world/src/worldgen/feature_region.rs": "2c78e5f1bdb08307f8d982f231f1abbc3306cd54348d9023b86ee6ed3516fd33", + "crates/horizon-world/src/worldgen/feature_sort.rs": "3488a093dfe1321aaa29d8a30cfb115d8e666a81bf195514e87b170de626835c", + "crates/horizon-world/src/worldgen/fluid_predicate.rs": "e682d13a21f90605215b79f5d254bf2e524d35e89eab2e3b46384709af80b847", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "9218399b4d3757f7bbc550d7729a7201f32a1c83a7030865e0c12aab8a80d116", + "crates/horizon-world/src/worldgen/placement/context.rs": "cd1d2fe305ad4e205e7e01b32128ff895fa8aacc76fa11f200ad6c7c9fba1f49", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "b0397e5818fae84358546193a95f84bcb0b5bffafce909e6fcb3386179ee8023", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/state_provider/catalog.rs": "fa0616353f07460975ab323357ab280b7f35e7bfe2de6edc08d304316766ed26", + "crates/horizon-world/src/worldgen/state_provider/noise.rs": "7ee369c2a032e5620cb9bdf9ee7adad1f70870fb0a27efb7b7c514d92f83491f", + "crates/horizon-world/src/worldgen/state_provider/properties.rs": "9909139aaca1dc4f743957257fadaa9d423d21fa401fa9abc050505f79365139", + "crates/horizon-world/src/worldgen/state_provider.rs": "89cb0410899608545aa1ba3b1b4c1babf533fb25efd341feab1c87661f44f7b9", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "3358b563db8cb0bc8a9cfbbe2b8b3e70941cd2d37a0b519fbb6545f8d0dcbb69", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "821981c893fc84312351503f2be0c06c681d8bc768dade14576697cf047a9f8f", + "crates/horizon-world/examples/state_provider_fixture.rs": "ec20f6ee5b3d1f2e69c4c5345fd31ef98ef660fc26b69ac0145e4d8473bca498" + }, + "fixtures_sha256": { + ".local/rust-state-provider-parity/inputs.txt": "8b4ebd390ba64d0c9af15df6355c1722dffb4485248deb784e141d447cec512d", + ".local/rust-state-provider-parity/survival-classes.json": "361832008eea0aa9151d367a125a19c6353d99a0b88b27dd0682f55b7954553e", + ".local/rust-state-provider-parity/survival-rules.json": "2d82abb640c1235179e195b0234b13f3b74af84741b1b739aa6cec648ab3b3d2", + ".local/rust-state-provider-parity/cached-support.nbt": "b6fdc9471b0b61e904206d3f099f4dc235aad6d723536c210be0cb7c3560d82c", + ".local/rust-state-provider-parity/support-cached-states.json": "353945a58fe69b352925473f1693f9b14a9ad19f13c15159c4184f2c29258622", + ".local/rust-state-provider-parity/block-properties.nbt": "699a994c5c0c9f7ee58e35b9c23c4503a5936efe84133643113232f825ae2216", + ".local/rust-state-provider-parity/cached-collision.nbt": "f3a5c6a5b2d51dad6c52e486e2b9989e79fd55db1a9bda6196db399550b04078", + ".local/rust-state-provider-parity/biomes.json": "9b26dc3b662627dc3bbbf8da209f287882ce79ff4daf8f454b994ddc7510df99", + ".local/rust-state-provider-parity/biome_tags.json": "2c0193d998b196c2b909e92f51e8158f5e8773f5387ade5a8b85a85f063ca560", + ".local/rust-state-provider-parity/fluid-tags.json": "244b4f208fd0d14613e1ded922c13ccb30a57b0b85db77b8922d3564e224774f", + ".local/rust-state-provider-parity/catalog.json": "7331cac31ef90434ab71ac75bad0a68e9abfd96942416a650a7d0e75f0ab558e", + ".local/rust-state-provider-parity/providers.json": "65f3c3a9a45682d9f654f772c871d70bced81fb133209b29cac06e26a1409c75", + ".local/rust-state-provider-parity/tags.json": "58948bd795faff8714b71ba1076afc68a645591e043ab97f1dec69817ed6885a", + ".local/rust-state-provider-parity/facts-client.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b", + ".local/rust-state-provider-parity/facts-server.json": "5e89a805514cabfe46e082d651db406b9479781e1d97b65faa2ab9f6f871309b" + }, + "rust_output_sha256": "aa089984db4632a9b1e2d1c965fa0429f9d8b034e2ceb200bccbe2a4a5b545c8", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "aa089984db4632a9b1e2d1c965fa0429f9d8b034e2ceb200bccbe2a4a5b545c8", + "matched_output_lines": 105340143 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "aa089984db4632a9b1e2d1c965fa0429f9d8b034e2ceb200bccbe2a4a5b545c8", + "matched_output_lines": 105340143 + } + ], + "scope": "Actual BlockStateProvider DIRECT_CODEC/TYPED_CODEC and simple, weighted, random_block, rotated, copy_properties, randomized_int three noise-based providers and rule_based over the pinned state registry. All states and block defaults, full-state versus typed exclusive decoding, ordered holder sets/tags, duplicates, empty optional results versus world-state fallback, zero/overflow weights, query failures, every state across six fixed rotations, nested random rotations, property copying for every target state against representatives of every compatible property value, integer-property ranges/missing properties, composed transforms and subsequent random consumption. Native property equality families are checked for ambiguity; Rust validates Cartesian state tables and uses compact property strides. Both legacy/xoroshiro streams execute directly and through WorldgenRandom. Noise comparisons include every bundled provider definition, independent legacy seeding, float/double scaling, dual-noise variety selection, threshold draw order and coordinate/codec boundaries. Rule-based comparisons cover true/not/all_of/any_of/inside_world_bounds/height_range/volume_match/matching_block_tag/matching_blocks/matching_fluids/matching_biomes/unobstructed/solid/replaceable/has_sturdy_face/would_survive predicates, ordered optional results, fallbacks, nested rules and world-query failures. Every pinned block-state fluid identity, amount, falling/source flag and own-height bits are derived from descriptors and compared. Fluid-holder sets and all bundled fluid tags are tested against every state. Biome-holder membership and all bundled biome tags are compared across every pinned biome identity, including empty sets, missing names, ordered world queries and short-circuit composition. Unobstructed predicates compare null excluded entities, exact translated unit-shape bounds, ignored-but-validated offsets, true/false world results and failures. Named holder versus direct/typed decoding, nested named providers, missing names, inline ambiguity, ordered resource registration and all bundled named definitions are compared. Solidity and replacement predicates cover every block state, offset wrapping/validation, empty-child fallthrough, composed predicates and query failures using privately imported definition flags and Rust-calculated collision solidity. Has-sturdy-face predicates cover all 35,723 states through unified cached/dynamic support dispatch across six directions, native offset rules, failed state reads, block-entity query failures and ordered optional-child/boolean composition. Block entities are absent in this integration corpus; shulker animation-state shape selection is separately tested and active moving-piston entity collision generation remains pending. Would-survive decodes candidate states and bounded offsets, evaluates all supported candidate states and each rule against every neighbor state, and preserves world read/entity failures and short-circuit/optional-child behavior. Survival support is limited to the rule families explicitly recorded here; unsupported survival families, complete registry loading/reloading, full block placement behavior and full feature generation remain pending." +} diff --git a/benchmarks/rust-structure-density-2026-10-06/scoped-parity.json b/benchmarks/rust-structure-density-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..b1b4e9bfd --- /dev/null +++ b/benchmarks/rust-structure-density-2026-10-06/scoped-parity.json @@ -0,0 +1,115 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 183, + "scalar_queries": 28093, + "volumes": 339, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureDensityOracle.java": "24fa3c5ac568997ede53cebc4bf9c8a98ba0586e195c74c2217a2770c8c104ec", + "tools/test_structure_density_parity.py": "9020711ae9f53c950c7a644a5587f0298f3bae272ce501cf653df51b85bddf4a", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry.rs": "f46065659e60eb5e84ad69b9f3b5e94dc87ee19de16408817e26f23d16b6c7e7", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "134cf93b53a40fb1ed0e0170c90316c80e270773b2968c63dc3f9cef2c941bff", + "crates/horizon-world/src/worldgen.rs": "b89dd4a9de02caf6bce457304a105ffbc0f0f220f8647c095852a45a1bf292bb", + "crates/horizon-world/examples/structure_density_fixture.rs": "780cbf5dbf1f948e2d8aac54eff67a900de652fe31eb007f55dd33177f38fdab" + }, + "fixtures_sha256": { + ".local/rust-structure-density-parity/inputs.txt": "1c948f36b4741ce0f5a16ccd5c3bda0626274a40ccdfcaabb95210336ed21836" + }, + "rust_output_sha256": "09f0779c2f39773e4772b259ab06a217f98324b5acb0bda472d603f543ef9bf1", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "09f0779c2f39773e4772b259ab06a217f98324b5acb0bda472d603f543ef9bf1", + "matched_output_lines": 1360095 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "09f0779c2f39773e4772b259ab06a217f98324b5acb0bda472d603f543ef9bf1", + "matched_output_lines": 1360095 + } + ], + "scope": "Actual vanilla Beardifier constructor and scalar/bulk samplers from supplied ordered rigid pieces, jigsaw junctions and normalized affected bounds. Five terrain-adjustment modes, the full 24-cubed junction kernel neighborhood, ground-level offsets and extreme wrapping arithmetic, ordered accumulation, nullable/empty affected bounds, clipped strided volumes including scalar/bulk floor-clipping differences and oversized output tails. Floating outputs compared as canonical-NaN raw bits. Live structure discovery/filtering, invalid bounding-box repair, structure placement and terrain integration remain pending. Local Math.pow-derived kernel results do not establish cross-platform math parity." +} diff --git a/benchmarks/rust-terrain-2026-10-06/scoped-parity.json b/benchmarks/rust-terrain-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..8e06e6bb0 --- /dev/null +++ b/benchmarks/rust-terrain-2026-10-06/scoped-parity.json @@ -0,0 +1,123 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "block_states": 35723, + "block_tag_files": 300, + "fixtures": 114, + "fill_calls": 200, + "noise_aquifer_fixtures": 61, + "structure_density_fixtures": 24, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTerrainOracle.java": "47887c16a4106e6a9ef4d665fd4603ea23b62e38491376bcf9038b904e39b406", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java": "145c943637ed177cc4ef8a85f2484da8afd164868e84a8463882feec1653a860", + "tools/test_terrain_parity.py": "8bb8e716e957ef07d1117ed9939fab1b551ebab94d20e48d11f64bc477e4571f", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/test_worldgen_parity.py": "3574ac73f81e3a6606ac9d3c16fa2c50b57a37b89be52e7d5448e7045c41a9ee", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry.rs": "f46065659e60eb5e84ad69b9f3b5e94dc87ee19de16408817e26f23d16b6c7e7", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "134cf93b53a40fb1ed0e0170c90316c80e270773b2968c63dc3f9cef2c941bff", + "crates/horizon-world/src/worldgen.rs": "b89dd4a9de02caf6bce457304a105ffbc0f0f220f8647c095852a45a1bf292bb", + "crates/horizon-world/examples/terrain_fixture.rs": "eb521404a3e850be522f3bda2f7c724c7d1b66e154e1bc53121b4e7511e5b1bd" + }, + "fixtures_sha256": { + ".local/rust-terrain-parity/inputs.txt": "a9ddccd711b0b6bdcae612a21f2b0dc143e156c9c97f47fce33071c7ceb660bd", + ".local/rust-terrain-parity/registries.json": "2a4e6b29a707ebbb7261f978b9e0dcd372f0c8548e2fb7e00c6bebb043bc49b9", + ".local/rust-terrain-parity/facts-client.json": "1d24883ee807b0b71473f0bbf8ed548ddaf712148caeb3fcc7aa13ab973a97b0", + ".local/rust-terrain-parity/facts-server.json": "1d24883ee807b0b71473f0bbf8ed548ddaf712148caeb3fcc7aa13ab973a97b0" + }, + "rust_output_sha256": "ff3612b2d998278b65c1b453b9df73ecf198151b8d094c150c16872106212bfc", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "ff3612b2d998278b65c1b453b9df73ecf198151b8d094c150c16872106212bfc", + "matched_output_lines": 7950873 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "ff3612b2d998278b65c1b453b9df73ecf198151b8d094c150c16872106212bfc", + "matched_output_lines": 7950873 + } + ], + "scope": "Noise-stage filling only, using actual vanilla NoiseBasedChunkGenerator.doFill and NoiseChunk with empty blending and empty or supplied rigid-piece/junction structure fields. Independently authenticated client/server registry resources and exported block identities/properties/air/fluid facts must agree. Rust compiles the final density and optional aquifer through a shared compiler/context, writes resident block sections, updates ocean-floor/world-surface worldgen heightmaps and records ordered per-section fluid postprocessing offsets. Comparisons cover every raw section state, heightmap word and postprocessing offset after each fill, all bundled routers/aquifers, both seeded random factories, synthetic roots, prefilled chunks, partial vertical volumes, repeated fills and structure-density bindings in final-density/aquifer graphs. Block behavior facts remain imported; actual biome properties and material rules are not evaluated. Surface/material/carver/feature/structure stages, nonempty blending and live structure discovery, complete generated worlds and gameplay/rendering remain pending." +} diff --git a/benchmarks/rust-ticks-2026-10-05/scoped-parity.json b/benchmarks/rust-ticks-2026-10-05/scoped-parity.json new file mode 100644 index 000000000..c30f13981 --- /dev/null +++ b/benchmarks/rust-ticks-2026-10-05/scoped-parity.json @@ -0,0 +1,87 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "commands": { + "reset": 23, + "add": 1507, + "schedule": 13944, + "save": 814, + "tick": 2096, + "chunk": 1067, + "query": 976, + "load": 5, + "unpack": 5, + "remove": 1125, + "restore": 1145, + "copy": 423, + "clear": 558, + "enable": 1350, + "reload": 777 + }, + "inputs_sha256": "74c8b7c4cd29148e7a47834986d26e32d6eb45e59c8727984ecb0911a6c288eb", + "rust_output_sha256": "3f82d7de0cd6d114e8b52920ada98067134e7394880958d599d8faf2088ede98", + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTickOracle.java": "17bfb6ed3b35f20b84ee989e2688fa8754ed6a74c7f95663e75583ca9ac602f2", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTickDataOracle.java": "00a7ac5795ff0a3e489d0b41cb5ba40f00f04e560699d5d6d4641b96736ecda4", + "tools/test_tick_parity.py": "ca1fd537a77a0dfd1144e408028010e76d9bb8d82cf6121db7d7dc99d3a75949", + "tools/test_rust_parity.py": "500652427164c7e067a5eb69310ec81f843d5fe37a7c9d88edd2b1ca6606020a", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "faae2edce8b573fd32fcb4bd1f898be7d700a5b38479439f5bec96df764688fd", + "crates/horizon-core/Cargo.toml": "09243cac4d45e8b4aaed3a6169bf3ee0e1272fdff4298c43c80d5fff0116d01c", + "crates/horizon-world/Cargo.toml": "e3250c38fb21b149b5ccaf3c90b5c87ff15b2902f5204b7159207ef7fbf229f2", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/parity.rs": "7b455f2181862e1430e7387633c146877c2d317c2ea682c1e6fa64345dbc5885", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "acaa0a51a759e1a08d417538e567847a66b8c9ae6a7434872e1621ed210364b1", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random.rs": "2f304dfb580a6bc1b5c51b048a2fa2a57f73c5f28f5eb2447f925bf138513389", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/lib.rs": "521ed8987f9fc21e9df75206795414871611e5b6acbf3906c26f44a4c6e6115e", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry.rs": "f46065659e60eb5e84ad69b9f3b5e94dc87ee19de16408817e26f23d16b6c7e7", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/examples/tick_fixture.rs": "df267c307e0491a238b2d93edf0384514f38f8ee3252e315b989de56c6e17990" + }, + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "3f82d7de0cd6d114e8b52920ada98067134e7394880958d599d8faf2088ede98", + "matched_output_lines": 97776, + "block_ticks": 251, + "fluid_ticks": 251, + "region_chunks": 1 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "3f82d7de0cd6d114e8b52920ada98067134e7394880958d599d8faf2088ede98", + "matched_output_lines": 97776, + "block_ticks": 251, + "fluid_ticks": 251, + "region_chunks": 1 + } + ], + "scope": "Scheduled tick ordering, deduplication, save packing, chunk eligibility/loading and callback mutations only. Block/fluid behavior is not implemented." +} diff --git a/benchmarks/rust-value-provider-2026-10-06/scoped-parity.json b/benchmarks/rust-value-provider-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..d6c3ab752 --- /dev/null +++ b/benchmarks/rust-value-provider-2026-10-06/scoped-parity.json @@ -0,0 +1,151 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 5040, + "definitions": 504, + "samples_per_valid_fixture": 64, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaValueProviderOracle.java": "7cbaea3053efe6d861a05f9ab1cbd772c8010218b95102ff05d4028139c333bd", + "tools/test_value_provider_parity.py": "38f34d1a7b7ecc8acafd563c8acd74f12be930d4b1e181e371782a315cf84a87", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_graph.rs": "5dfb83b9f97eb24b386e3514aaac957b314461b32d59e1fdb6dcac7ca0a32e1b", + "crates/horizon-world/src/worldgen/feature_region.rs": "4a95a30c0987d97e671f84380e13ddea070ad81f996baa65b2a06c4d892971c7", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/placement/chain.rs": "1b976aa4dd2516468196d0af3451e3fdd037493a14d269f54ebdd7254055e05e", + "crates/horizon-world/src/worldgen/placement/context.rs": "b36dfd9297896e62770f2085cf934fc08ebd4c030ecc7ae17d864e819a113201", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "68ecf36954fea5705436d486e9be93836933fd56779022afeb881a0399d6a674", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "f18a6c0e66cadec431d2e3154ad70d96b3be623e675f939d4419858f2cce92ab", + "crates/horizon-world/examples/value_provider_fixture.rs": "ed66e3bb34c3d3c73c1e143843f7245f0c02eb36d584d856b6a15a8600caf5d1" + }, + "fixtures_sha256": { + ".local/rust-value-provider-parity/inputs.txt": "ec80fb8b841488b4167aaecf5417cbcbc39891ffb0fdff18ffd947affdd96492" + }, + "rust_output_sha256": "0115440c04ca851e177582e815b590409ba4af7b0d66e77806c2fba8ee82081d", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "0115440c04ca851e177582e815b590409ba4af7b0d66e77806c2fba8ee82081d", + "matched_output_lines": 429920 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "0115440c04ca851e177582e815b590409ba4af7b0d66e77806c2fba8ee82081d", + "matched_output_lines": 429920 + } + ], + "scope": "Actual FloatProviders.CODEC and IntProviders.CODEC decoding, declared ranges, seeded samples and interleaved subsequent nextLong values. Covers constant/uniform/trapezoid floats and constant/uniform/biased-to-bottom/very-biased-to-bottom/trapezoid/clamped/weighted-list integers, both random modes, numeric narrowing, signed zeros, overflow, equal/reversed bounds, negative plateaus, missing fields, duplicate keys and sampling failures. Float NaNs are canonicalized. Weighted lists include zero weights, singleton draws, nested providers, 63/64/65 weight totals, maximum/overflow totals and malformed entries; native constructor rejections count as decode errors. Gaussian providers, encoding, height providers and complete generation remain outside this scope." +} diff --git a/benchmarks/rust-world-2026-10-05/scoped-parity.json b/benchmarks/rust-world-2026-10-05/scoped-parity.json new file mode 100644 index 000000000..6e441300a --- /dev/null +++ b/benchmarks/rust-world-2026-10-05/scoped-parity.json @@ -0,0 +1,77 @@ +{ + "schema": 1, + "minecraft": "26.3", + "data_version": 5023, + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "references": [ + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "nbt_pairs": 32, + "palettes": 44, + "palette_values": 123776, + "region_chunks": 48, + "registry_states": 35723, + "resident_values": 8192 + }, + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "nbt_pairs": 32, + "palettes": 44, + "palette_values": 123776, + "region_chunks": 48, + "registry_states": 35723, + "resident_values": 8192 + } + ], + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldOracle.java": "d7cf12dda8c284d6a9b3a1e08ee60831a20dea3883e227b51c5b268636421fd0", + "tools/test_world_parity.py": "cb86934e74b0840dcec2c3de1bf252307edc86d1ba650032ca28506536e39438", + "tools/test_rust_parity.py": "500652427164c7e067a5eb69310ec81f843d5fe37a7c9d88edd2b1ca6606020a", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "faae2edce8b573fd32fcb4bd1f898be7d700a5b38479439f5bec96df764688fd", + "crates/horizon-world/Cargo.toml": "e3250c38fb21b149b5ccaf3c90b5c87ff15b2902f5204b7159207ef7fbf229f2", + "crates/horizon-world/examples/collision_fixture.rs": "ee754b5b42e0a51fe0a305b3f4bb56522ff3fffae564180aab8087b1b9e44afc", + "crates/horizon-world/examples/tick_fixture.rs": "df267c307e0491a238b2d93edf0384514f38f8ee3252e315b989de56c6e17990", + "crates/horizon-world/examples/world_fixture.rs": "a3c4c0f5131ae051b24662eff0ed11ed797c6fd5069fbfdf819f0e3fcdfb2cf4", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/lib.rs": "521ed8987f9fc21e9df75206795414871611e5b6acbf3906c26f44a4c6e6115e", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry.rs": "f46065659e60eb5e84ad69b9f3b5e94dc87ee19de16408817e26f23d16b6c7e7", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/tests/collision_data.rs": "45f3d33b36efe720e99ebf75b9f4fbddd777cebea4618bba245ca106b3443391", + "crates/horizon-world/tests/tick_data.rs": "ab345209367db6963b987797992c4a06433bd2039e6021bd834f6305324c04d7", + "crates/horizon-world/tests/world_io.rs": "4a42630c99ce89b27cc2be1a1b961ad880f62762ab661f9e92ef9bcf7f3e76e0", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/parity.rs": "7b455f2181862e1430e7387633c146877c2d317c2ea682c1e6fa64345dbc5885", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "acaa0a51a759e1a08d417538e567847a66b8c9ae6a7434872e1621ed210364b1", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random.rs": "2f304dfb580a6bc1b5c51b048a2fa2a57f73c5f28f5eb2447f925bf138513389", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e" + }, + "notes": [ + "Synthetic NBT and region fixtures serialized and verified by pinned vanilla classes.", + "Includes all four region codecs, external oversized chunks, UTF-16 edge cases, mixed lists, palette mutation, and the full exported block-state ID registry.", + "Storage-only edits; no world generation, simulation, lighting, live multiplayer, renderer, FPS or whole-game parity claim." + ] +} diff --git a/benchmarks/rust-worldgen-2026-10-05/scoped-parity.json b/benchmarks/rust-worldgen-2026-10-05/scoped-parity.json new file mode 100644 index 000000000..bc588a6de --- /dev/null +++ b/benchmarks/rust-worldgen-2026-10-05/scoped-parity.json @@ -0,0 +1,307 @@ +{ + "schema": 1, + "minecraft": "26.3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "commands": 16770, + "command_counts": { + "noise": 2111, + "quantize": 4116, + "index": 229, + "climate_parameter": 25, + "climate_point": 183, + "noise_settings": 217, + "settings_create": 182, + "aquifer": 9136, + "noise_aquifer": 379, + "registry": 24, + "router": 168 + }, + "noise_aquifer_injected_failures": { + "0": 3, + "1": 3, + "2": 3, + "3": 3, + "4": 3, + "5": 3 + }, + "noise_aquifer_outcomes": { + "1 false": 5800, + "0 false": 9995, + "default_solid false": 12655, + "2 false": 35365, + "0 true": 1114, + "2 true": 2021, + "1 true": 43, + "5 false": 443, + "5 true": 5, + "6 false": 295, + "6 true": 8, + "7 false": 49, + "7 true": 1, + "4 false": 51, + "4 true": 4, + "error false": 17, + "3 false": 81, + "error true": 2 + }, + "noise_registry_entries": 64, + "density_registry_entries": 55, + "noise_settings_entries": 7, + "biome_parameter_entries": { + "minecraft:nether": 5, + "minecraft:overworld": 7594 + }, + "biome_tables_sha256": { + "minecraft:nether": "09e477f851380a6e726ea85fee39cd1d41c7f160fe424f58cb3f0056b5c11218", + "minecraft:overworld": "6bc45ce2eed04b6afecdfaf2cf89273e83dad071aeb45638e181d33fe5180f57" + }, + "fixtures_sha256": { + ".local/rust-worldgen-parity/registries.json": "c6868228cc1002755dab31d947e953cc4be785a1b6ae82697755817a238b7de9", + ".local/rust-worldgen-parity/inputs.txt": "4afb482c8aa6e654ef47b9696f76c16fa862414248202c9bf748941bfc8d0877", + ".local/rust-worldgen-parity/biome-presets-client.json": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9", + ".local/rust-worldgen-parity/biome-presets-server.json": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9" + }, + "noise_resources_sha256": { + "data/minecraft/worldgen/noise/aquifer_barrier.json": "864a9d66a03b081adc8d4bf51a6d0cd5fdd94a0ebf1cecadec2aed9e549db7e4", + "data/minecraft/worldgen/noise/aquifer_fluid_level_floodedness.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/aquifer_fluid_level_spread.json": "6afc3f09b6616f799d739b5b114c4436059dcc60308af55fe96a8594de815214", + "data/minecraft/worldgen/noise/aquifer_lava.json": "96e1c4e411ffe302c5541cd2ee8462e1992f0290d623c560f353c39981737346", + "data/minecraft/worldgen/noise/badlands_pillar.json": "79c0d0628db949d3b83bbca145da427bcdc3ff585b0ad736f7cb20e4c593c9a2", + "data/minecraft/worldgen/noise/badlands_pillar_roof.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/badlands_surface.json": "79365a5c2017e93878d989a176520ba9cbdf8685cff8b3cb148730d949d98b09", + "data/minecraft/worldgen/noise/calcite.json": "331259d84572c32b4b268d069e0132da9e6623ba614080e34b815472c7f4ee0c", + "data/minecraft/worldgen/noise/cave_cheese.json": "24c6846b7fc1f7c652bf185797fe98b943146b6aaf8766d1bff2066c59b7ed24", + "data/minecraft/worldgen/noise/cave_entrance.json": "f75146a7b1a033998edd3c77319f78243fe933bdcda2067b78658940f145cac6", + "data/minecraft/worldgen/noise/cave_layer.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/clay_bands_offset.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/continentalness.json": "b7ce5ac29a2c7a7cfbfaa1e1eeca9ba8f4a52139e59318850fa2407242c69ba8", + "data/minecraft/worldgen/noise/continentalness_large.json": "76834cff0227d52b19b5932142925f4fc639e713c2180e489f813701ca45f53e", + "data/minecraft/worldgen/noise/erosion.json": "af8a7a0f16ff3e568ad646df9cbc28e04a31b16dad4f162705c0f7c747da6983", + "data/minecraft/worldgen/noise/erosion_large.json": "d20c2c6ec805a366b105924b3cee29ac5b84cc06d636b539ae0047aac413b60a", + "data/minecraft/worldgen/noise/gravel.json": "87d627634161e51a79512f3d3f42f990d2a185e35198eb5e2161939d866751e0", + "data/minecraft/worldgen/noise/gravel_layer.json": "a4b45bdb6efef2509b053b970f6e84250d7b16d54f3906bc7fcf2665ada2a692", + "data/minecraft/worldgen/noise/ice.json": "85d03cc06d6bc552dc399dcc90ca9749c2625ddf0049dc0f95684631a7c6e66e", + "data/minecraft/worldgen/noise/iceberg_pillar.json": "98816326f84a21ce29421a9cba3ad85e5a26069312c9819aaf5662691e777fd5", + "data/minecraft/worldgen/noise/iceberg_pillar_roof.json": "864a9d66a03b081adc8d4bf51a6d0cd5fdd94a0ebf1cecadec2aed9e549db7e4", + "data/minecraft/worldgen/noise/iceberg_surface.json": "79365a5c2017e93878d989a176520ba9cbdf8685cff8b3cb148730d949d98b09", + "data/minecraft/worldgen/noise/jagged.json": "d64347f4f9acb984075e3b4945b4699907ec6d893588388dd8f738f29f75f4d1", + "data/minecraft/worldgen/noise/nether/temperature.json": "5a67fbc28b5c2578b4ca5f6abdd115c715ea2ef1be3e1a7a8eb1a0de4c3a8f7c", + "data/minecraft/worldgen/noise/nether/vegetation.json": "5a67fbc28b5c2578b4ca5f6abdd115c715ea2ef1be3e1a7a8eb1a0de4c3a8f7c", + "data/minecraft/worldgen/noise/nether_state_selector.json": "116c8bf1d676fd3a3dea3908e074a4f4b7ee55d3263e93abf5889b41bfc77f5b", + "data/minecraft/worldgen/noise/nether_wart.json": "4518b186ffe4b65394a35276c8708037c6f3f73c7cb95ef6d41a5cd4b8d234f6", + "data/minecraft/worldgen/noise/netherrack.json": "cef60938a0304eec78a6bdebd24b80a45c5d1bad894c6c012e3413ecc485a81a", + "data/minecraft/worldgen/noise/noodle.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/noodle_ridge_a.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/noodle_ridge_b.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/noodle_thickness.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/offset.json": "45f51565587e2dc055271648037c0ec3466815e82f0d762e0198c16285fc8ae7", + "data/minecraft/worldgen/noise/ore_gap.json": "6afc3f09b6616f799d739b5b114c4436059dcc60308af55fe96a8594de815214", + "data/minecraft/worldgen/noise/ore_vein_a.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/ore_vein_b.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/ore_veininess.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/packed_ice.json": "0f51993727dcb0aa7c6cb9288e462443e711e9980c12927435126a3c45922786", + "data/minecraft/worldgen/noise/patch.json": "83a0052d4220c67c5513bce689d681e3af3325c18fec612cdd4941fc738f4be0", + "data/minecraft/worldgen/noise/pillar.json": "5a67fbc28b5c2578b4ca5f6abdd115c715ea2ef1be3e1a7a8eb1a0de4c3a8f7c", + "data/minecraft/worldgen/noise/pillar_rareness.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/pillar_thickness.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/powder_snow.json": "98816326f84a21ce29421a9cba3ad85e5a26069312c9819aaf5662691e777fd5", + "data/minecraft/worldgen/noise/ridge.json": "e05d077746b27d662a8c981807819df3e3bb1f1779d2245dd911c8193e03bbf8", + "data/minecraft/worldgen/noise/small_patch.json": "9ecc836feb68b42d717217e028f2a72112179f1097f5bd156b1d3f1db637732e", + "data/minecraft/worldgen/noise/soul_sand_layer.json": "a4b45bdb6efef2509b053b970f6e84250d7b16d54f3906bc7fcf2665ada2a692", + "data/minecraft/worldgen/noise/spaghetti_2d.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/spaghetti_2d_elevation.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/spaghetti_2d_modulator.json": "d210211c0c76c53f15908f0b004a7e98e9d753ed996cd5468f2068f2e23932d1", + "data/minecraft/worldgen/noise/spaghetti_2d_thickness.json": "d210211c0c76c53f15908f0b004a7e98e9d753ed996cd5468f2068f2e23932d1", + "data/minecraft/worldgen/noise/spaghetti_3d_1.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/spaghetti_3d_2.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/spaghetti_3d_rarity.json": "d210211c0c76c53f15908f0b004a7e98e9d753ed996cd5468f2068f2e23932d1", + "data/minecraft/worldgen/noise/spaghetti_3d_thickness.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/spaghetti_roughness.json": "6afc3f09b6616f799d739b5b114c4436059dcc60308af55fe96a8594de815214", + "data/minecraft/worldgen/noise/spaghetti_roughness_modulator.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/sulfur_cave_gradient.json": "4900ffd885ce33b220a673ba0a248504c78f9f2cdfce824106a237d9ad18a6a7", + "data/minecraft/worldgen/noise/surface.json": "79365a5c2017e93878d989a176520ba9cbdf8685cff8b3cb148730d949d98b09", + "data/minecraft/worldgen/noise/surface_secondary.json": "ae23cb210db7b64b66b327dbbf1e7b2acb5c15cb6fe5df0455eb29910d9312eb", + "data/minecraft/worldgen/noise/surface_swamp.json": "19e08e0d1dff257cf748d3cef79e939e8f25cc5e7226653c789008171f40695b", + "data/minecraft/worldgen/noise/temperature.json": "9b1d5a87d575abf2891882ec3e1544b964cd15fedc84ad14d2abbd3b48ee2e4b", + "data/minecraft/worldgen/noise/temperature_large.json": "4fe64b952b751eb7e45b4d1e274add508b504ee8bbc54cad417ce3a3b068d42e", + "data/minecraft/worldgen/noise/vegetation.json": "ff4c10776eb2822f9f66dec4e9878a1bc797aca711480bf8430f851ff9af77dc", + "data/minecraft/worldgen/noise/vegetation_large.json": "20f4a255e3f9452f4cf983b3efed71ead184d04f4070283f355ad4d97993d133" + }, + "density_resources_sha256": { + "data/minecraft/worldgen/density_function/end/base_3d_noise.json": "38db7d590abc3144e3357a79562d649d9880bc2c62ddc99480d93f4b6401c9a6", + "data/minecraft/worldgen/density_function/end/islands.json": "6e4f02929580ecc34bfb059855b4e88d080dc7ca6c9984f216bdaa32e6b47700", + "data/minecraft/worldgen/density_function/end/sloped_cheese.json": "5dee072865321e57e5e231e60a57bfcd1919454f93da33b3c1651b3712f2cfb2", + "data/minecraft/worldgen/density_function/nether/base_3d_noise.json": "76cfd16e6fc2b1ce8bdb5f5ee277d431c167bc01afc2462bffff09eb5f0bd582", + "data/minecraft/worldgen/density_function/overworld/base_3d_noise.json": "2791a1e6c5c730eac1bd35aaea9a7ab22855872fdb92349192d045330fd4614f", + "data/minecraft/worldgen/density_function/overworld/caves/entrances.json": "63a1b8351e6dea212501c36f515f32e5a0e960228b5b5ccf0dc5b43855cbc1ab", + "data/minecraft/worldgen/density_function/overworld/caves/noodle.json": "3bce7453470fd37e3bfc11dc8584494aab094f9fd820038dc5592cb47e825a69", + "data/minecraft/worldgen/density_function/overworld/caves/pillars.json": "069d35fbdaed7d74521fc3e9355a94e778450b52a05f1efbd470ce3917b8a207", + "data/minecraft/worldgen/density_function/overworld/caves/spaghetti_2d.json": "a99c68ac415596788c84e93e81c96c9786e31db21a81157459a13272cda4cb1f", + "data/minecraft/worldgen/density_function/overworld/caves/spaghetti_2d_thickness_modulator.json": "4f987a0b9e8c0adb02df47034fa8b3cebfbfb2c8e607123614ef009a16bfaf6c", + "data/minecraft/worldgen/density_function/overworld/caves/spaghetti_roughness_function.json": "03bd1b405e53aeb75b6a3440d97975c25b6f11c7fc07149471b86c80fbdb6ea4", + "data/minecraft/worldgen/density_function/overworld/chunk_surface_level.json": "93a4e26ce4a1144c42040f52ca375f0dec94648c70ccdcc52db4a7f55ca526a5", + "data/minecraft/worldgen/density_function/overworld/continents.json": "0f2ff487c0556391ae2d56b7cab6990d45766ade2503236fe2669f83a64517be", + "data/minecraft/worldgen/density_function/overworld/depth.json": "9fcd7c8badcae4dc8e86303b0f72b05b5fd998d5bb7ac637729dd7e688688069", + "data/minecraft/worldgen/density_function/overworld/erosion.json": "8173a3df61a3c5cfe352fb4a8fa64e99840836e42f2f4b0ddf8035f4d28f97a5", + "data/minecraft/worldgen/density_function/overworld/factor.json": "f7cd1629f1a034504bd74fd38af5ea75a59257c565b5d919a6212e2e08778e30", + "data/minecraft/worldgen/density_function/overworld/final_density.json": "a7e6b9f4618e27cb08ec37a294d8ca2a96747128a8d65d788dc418fda372cfb1", + "data/minecraft/worldgen/density_function/overworld/jaggedness.json": "5e8acc680409ae0b56596be02954eb5b49a72069d004e5dcf9a92c5e106ccdb2", + "data/minecraft/worldgen/density_function/overworld/offset.json": "da6b4e686d8eb16c19443a1126168b6f2719712c02b690b9d7384ce53badf995", + "data/minecraft/worldgen/density_function/overworld/ore_vein/copper_density.json": "3b16d3a4499981f40bfd2b33786a99046bbca0c958f8f41692ffcbf44ae927d7", + "data/minecraft/worldgen/density_function/overworld/ore_vein/gap.json": "89ccfa58c6b8ae3e3954d2ff2dbcc42a8a3ae24a7b07437dbfb85fdced55945a", + "data/minecraft/worldgen/density_function/overworld/ore_vein/iron_density.json": "8de70a31c97e2a8299679770d53c8e366ace1aa8585e8d840375d25f85b72f8f", + "data/minecraft/worldgen/density_function/overworld/ore_vein/mask.json": "7f92df0b19e7d29fef01abc7025fea2bdae7a57453e186785cde2fc7d08aa5bc", + "data/minecraft/worldgen/density_function/overworld/ore_vein/richness.json": "3eb0183e295a5f9c54aab936b706b4b9d570ddf56c983ae89b91151e6e38fb9d", + "data/minecraft/worldgen/density_function/overworld/ore_vein/toggle.json": "49b9db48740578911d0f8a2de40f02eced3ae742f03ebb05fee381af579cc9ed", + "data/minecraft/worldgen/density_function/overworld/preliminary_surface_level.json": "4b6ce4c38ede0bec7485d4c029b9fcc7ceb5b26977c2c391a650fe8f3a3272b6", + "data/minecraft/worldgen/density_function/overworld/ridges.json": "bf66a03bd8474d09dad4da23f4b7e76816b83e23df9f53d9c0b7c529c25ed9c1", + "data/minecraft/worldgen/density_function/overworld/ridges_folded.json": "c8a4343b56273a476648a84fbbe07d8c473c1dd3769749260db6340ba5b37f9a", + "data/minecraft/worldgen/density_function/overworld/sloped_cheese.json": "5e2e7756881a4f2acf2e8c8dc826a04681939ff1dc7508ce868e865e92a069d7", + "data/minecraft/worldgen/density_function/overworld/temperature.json": "3c2f498cbf4636cd1fa7f555c14220a733c9d07fb5a1563f11c6144a27f31ce8", + "data/minecraft/worldgen/density_function/overworld/vegetation.json": "c902ef045f63a568ef4c3d834716c67b5835f0994997ee45756837de111a806c", + "data/minecraft/worldgen/density_function/overworld_amplified/chunk_surface_level.json": "378eef8542e7ee3adffeaf746e0c776d1e00ff75cf030d9244292acd796739f6", + "data/minecraft/worldgen/density_function/overworld_amplified/depth.json": "35bbe18bc8eaec3bc8d81f1b3130018874d6cc8fa516c1e8380bdb8caf68c803", + "data/minecraft/worldgen/density_function/overworld_amplified/factor.json": "b42bc13d4d3c1cbeb7c6dfa2e16f4ef532ad0cff3a92d20bace01711fee6edd4", + "data/minecraft/worldgen/density_function/overworld_amplified/final_density.json": "cde96d8a5efa63cd20cea615dd1172e5e6f2626e9275d359fa2864e77083ac4f", + "data/minecraft/worldgen/density_function/overworld_amplified/jaggedness.json": "9f9a8993ce50cd2f0736ef98c3f8ff55db02d47b2a3e4f6aacae7c45a3c95bcc", + "data/minecraft/worldgen/density_function/overworld_amplified/offset.json": "0bb9ae6088ea4dbfdf79f6f2b2eed789c68e9a4e919a31bf912f91ddeda28e8b", + "data/minecraft/worldgen/density_function/overworld_amplified/preliminary_surface_level.json": "e8a82a9dfe183f4e624ea7a268efa2c54376caf99139596a26ad1dd27e887e5f", + "data/minecraft/worldgen/density_function/overworld_amplified/sloped_cheese.json": "d8609154b76d0eefcfbc3746fa84f32cb04c5817a2fd1b80e72ee0ae9d88e96c", + "data/minecraft/worldgen/density_function/overworld_large_biomes/chunk_surface_level.json": "72f29b5fa9c01afa296d3679e6be662ee1b0bfdc1ba40cc2092ea74380be5c47", + "data/minecraft/worldgen/density_function/overworld_large_biomes/continents.json": "cfab013269cff17cfdf95497f87e70591378e7a39da44a241199fb64b304d411", + "data/minecraft/worldgen/density_function/overworld_large_biomes/depth.json": "9ec8ced85b58494f5400d4a5f6a27f1d4d44271d7a87adb8c5d842319eb5997f", + "data/minecraft/worldgen/density_function/overworld_large_biomes/erosion.json": "773d626db8e356d92a321270895ce085287d2befcb4504842371c38fd10102ac", + "data/minecraft/worldgen/density_function/overworld_large_biomes/factor.json": "0e7aa57eca20ebd6d2f089a9a4a34502efe902295812650f71b2ff087bb8b15f", + "data/minecraft/worldgen/density_function/overworld_large_biomes/final_density.json": "6f644644293c5489c499dc57663f2c12de60fc720bc4f1120efd343246eb159e", + "data/minecraft/worldgen/density_function/overworld_large_biomes/jaggedness.json": "30090703d4d9e493d40d60e06ee12f1310a608e20b73aeb8f86efa8e31b11453", + "data/minecraft/worldgen/density_function/overworld_large_biomes/offset.json": "75517306420732023e2dfeeb253439d8f0edcde9bb8b10ee7870d1bdb072ec22", + "data/minecraft/worldgen/density_function/overworld_large_biomes/preliminary_surface_level.json": "ece7767faac91980f5349ddfdc6040dc4ebbfce71a9f4d5842fa1b7bb169db3b", + "data/minecraft/worldgen/density_function/overworld_large_biomes/sloped_cheese.json": "347e160b5f951137b5f82a39c18572f8851c5a22484d11f31d1f90f5e5f6ac99", + "data/minecraft/worldgen/density_function/overworld_large_biomes/temperature.json": "051138f2c2f0ca4050b92f7320ddea461dca2038a49eb6f9931ecbf39129f4ef", + "data/minecraft/worldgen/density_function/overworld_large_biomes/vegetation.json": "187b08814a3831cd0ff2f405c6683e7213a79dc7eeec44cd46136e350b0718b7", + "data/minecraft/worldgen/density_function/shift_x.json": "0db6e5f781089feede9d8d2936d7564024752e34006b8bc9f2a138749f91e3e7", + "data/minecraft/worldgen/density_function/shift_z.json": "0b561cdfafa9e82f431a8051576eb2ddc386d01459df571d7040021b0debb762", + "data/minecraft/worldgen/density_function/y.json": "e7766e59792605f5c3d8e05ff6263db1dc6c91343c736b3ab7a58ddee9771282", + "data/minecraft/worldgen/density_function/zero.json": "8aed642bf5118b9d3c859bd4be35ecac75b6e873cce34e7b6f554b06f75550d7" + }, + "noise_settings_resources_sha256": { + "data/minecraft/worldgen/noise_settings/amplified.json": "07fbadd0fd71e16e5497c575d3c86d997166087ccfaaba70a589a440b915024e", + "data/minecraft/worldgen/noise_settings/caves.json": "29a378b845f7bff27a8badecba7ecf2bb22d0d4224b751ab6d91677c83bc6a6a", + "data/minecraft/worldgen/noise_settings/end.json": "d0fd92ddd39081f1779ce5482041a837fb4a03841ea4d843556f17b557e31f4b", + "data/minecraft/worldgen/noise_settings/floating_islands.json": "54923e55bfad4274bea513eccb42e1eb3625fb47ae00905537e0d3d68f82045d", + "data/minecraft/worldgen/noise_settings/large_biomes.json": "dcb29a9e3fb630f2b76a52d759c6925b40e67cd13bc7f9ae93976f0633cc2c05", + "data/minecraft/worldgen/noise_settings/nether.json": "e6d7856fe4523e4c3fa4dce756b6b1e211bfc263c5e417fb6294d032b8f53e9b", + "data/minecraft/worldgen/noise_settings/overworld.json": "d093895d50edd79d53555b33b62d767115399764e32a4f9ae2687739f785d4b9" + }, + "inputs_sha256": "4afb482c8aa6e654ef47b9696f76c16fa862414248202c9bf748941bfc8d0877", + "rust_output_sha256": "c39201a8d64b2ec12dc08d8eddcb962d336885a749200a0a33c0fefd7910c193", + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenOracle.java": "272b7e7c90dfc1344f6964033b61ee27ac867da7b375e406586b88de08d02b08", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeExport.java": "f9a773713cf21b69bfa10018b76f27b953bda140ede9934f43d3aa3091101cf5", + "tools/test_worldgen_parity.py": "699826ef3d3f1ac5419b91153539bf0857e931fd128a39fc47d8c8071cc03268", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "69f89566a78456c29caaa39dacedfe711ca59e49b78f64e68b0414fb6a73d8fc", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-core/tests/density_world_fields.rs": "e193e45080817ef92547828a8d106482a376b9f788e39d4d3831f44e9d693148", + "crates/horizon-world/examples/collision_fixture.rs": "ee754b5b42e0a51fe0a305b3f4bb56522ff3fffae564180aab8087b1b9e44afc", + "crates/horizon-world/examples/tick_fixture.rs": "df267c307e0491a238b2d93edf0384514f38f8ee3252e315b989de56c6e17990", + "crates/horizon-world/examples/world_fixture.rs": "a3c4c0f5131ae051b24662eff0ed11ed797c6fd5069fbfdf819f0e3fcdfb2cf4", + "crates/horizon-world/src/bin/worldgen_parity.rs": "5af97baa6681bc7aa04d981ec5c07c38cb27f28213abf34b1e83270828dd2980", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/lib.rs": "a6376d79c90ebdee539f4b460a9dd18d75e0c049c24f028d00c9c45c85ebf668", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry.rs": "f46065659e60eb5e84ad69b9f3b5e94dc87ee19de16408817e26f23d16b6c7e7", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen.rs": "24f440a4be7546e79b4f462dd18aad9031e94dc87c5f1d32b78912650f7dd162", + "crates/horizon-world/tests/biome_data.rs": "d4de462ccc3e6ad5760490330e0f0cd8a45734077708a2eca95ca06e65f779b0", + "crates/horizon-world/tests/collision_data.rs": "45f3d33b36efe720e99ebf75b9f4fbddd777cebea4618bba245ca106b3443391", + "crates/horizon-world/tests/tick_data.rs": "ab345209367db6963b987797992c4a06433bd2039e6021bd834f6305324c04d7", + "crates/horizon-world/tests/world_io.rs": "4a42630c99ce89b27cc2be1a1b961ad880f62762ab661f9e92ef9bcf7f3e76e0", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e" + }, + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "c39201a8d64b2ec12dc08d8eddcb962d336885a749200a0a33c0fefd7910c193", + "matched_output_lines": 922238, + "biome_export_sha256": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9" + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "c39201a8d64b2ec12dc08d8eddcb962d336885a749200a0a33c0fefd7910c193", + "matched_output_lines": 922238, + "biome_export_sha256": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9" + } + ], + "scope": "Direct normal-noise JSON decoding using the actual pinned vanilla CODEC. Every bundled noise registry resource, explicit/default parameters, empty and full amplitude modifiers, normalization modes, inclusive field bounds with signed-zero comparator ordering, malformed types, null fields, duplicate and ignored keys, decimal/exponent integer truncation and wrapping, signed zero, seeded modern/legacy and Nether construction, octave metadata, range and normalization bits, scalar noise values and parent random state. JSON resource contents stay private. Strict JSON parsing; no claim for Gson's permissive non-JSON syntax. Bundled density registries are also decoded with actual vanilla registry-aware CODECs: named forward references, all bundled function kinds, declared range/axes, raw compilation errors, seeded optimized roots, cache allocation, scalar values, strided bulk values, repeated cache hits and surface-volume errors are compared using RandomState's actual compile context. All seven bundled noise-setting resources contribute their actual eight-field NoiseRouter.CODEC objects to RandomState. Router fields are compiled in declaration order with a shared compiler/context; cache allocation, raw/optimized scalar and repeated strided volume values, successful single-layer surface volumes and invalid surface-volume shapes are compared. Actual RandomState climate sampler binding and quart-to-block coordinate wrapping are checked at ordinary and extreme positions. Float-to-long climate quantization and long-to-float conversion include subnormals, signed zeros, NaNs, infinities, cast saturation and seeded random bit patterns. Actual vanilla Climate.Parameter and ParameterPoint JSON codecs compare scalar, two-element list and min/max object intervals, float endpoint bounds/ordering, required coordinate/offset fields, negative zero, precision-sensitive float parsing, malformed types and duplicate keys. Climate parameter distances, wrapping squared fitness, stable search-tree leaf order and nearest lookup are compared across every supported branching value 2..32, sizes around branch powers, the 65536-entry API bound, duplicates, warm ties, fresh lookups, brute-force lookup and extreme signed-long endpoints/targets. The Rust tree is immutable with per-worker search state instead of hidden thread locals; invalid or degenerate searches return typed errors. Inline arbitrary distance metrics and behavior outside the bounded API are not covered. Built-in Overworld and Nether quantized biome parameter tables are exported independently by each authenticated JAR and required to agree before Rust consumes them. The Rust multi-noise resolver and actual vanilla MultiNoiseBiomeSource compare biome identities through scalar climate queries and prepared bulk quart volumes, including forward/reverse/repeated query order, wrapped extreme origins and shared previous-result state. Biome holder keys in the reference are registration placeholders; no biome property or gameplay behavior is evaluated. The Rust loader reads a Horizon quantized table format, not the vanilla biome codec, and the preset builders themselves have not been ported. Source and private fixture mutations during validation invalidate the report. The two-field 26.3 NoiseSettings codec, create helper and LevelHeightAccessor clamping are also compared across bundled noise members, dimension/alignment bounds, zero/negative runtime heights, disjoint ranges, wrapped integer arithmetic and decimal/exponent integer conversion. Global fluid cutoff selection and the actual disabled Aquifer implementation are compared with original default block-state identities, extreme sea levels/coordinates, signed-zero/subnormal/nonfinite density and counted picker calls; developer fluid-disable behavior is outside the regular-mode corpus. The actual noise-based Aquifer.Config codec and runtime are compared across bundled aquifer settings, modern/legacy world-seeded aquifer factories, synthetic density roots, nondefault water/lava states, cave/void air, nonfinite sampler overrides, strided volume extents, wrapped coordinates, repeated and reversed queries, counted picker calls, sampler call order/values, injected failures and retry state, scheduling flags, populated location/status caches and sorted surface-cache entries. Oversized or wrapped-invalid grid allocations and developer fluid-disable behavior are outside the bounded regular-mode API. Terrain filling is not yet validated. Router, vertical noise and optional aquifer members are decoded from each noise-setting resource; complete NoiseGeneratorSettings, material rules, nonempty world fields, biome registry/codecs and complete chunk biome assignment, generated chunks, gameplay and rendering remain pending. Inline noise holders and general codec behavior beyond the covered fixtures remain pending." +} diff --git a/benchmarks/rust-worldgen-2026-10-06/scoped-parity.json b/benchmarks/rust-worldgen-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..be295c20a --- /dev/null +++ b/benchmarks/rust-worldgen-2026-10-06/scoped-parity.json @@ -0,0 +1,627 @@ +{ + "schema": 1, + "minecraft": "26.3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "commands": 17338, + "command_counts": { + "noise": 2111, + "quantize": 4116, + "index": 229, + "climate_parameter": 25, + "climate_point": 183, + "noise_settings": 217, + "settings_create": 182, + "tag_entry": 32, + "tag_file": 335, + "tags": 200, + "tag_registry": 1, + "aquifer": 9136, + "noise_aquifer": 379, + "registry": 24, + "router": 168 + }, + "noise_aquifer_injected_failures": { + "0": 3, + "1": 3, + "2": 3, + "3": 3, + "4": 3, + "5": 3 + }, + "noise_aquifer_outcomes": { + "1 false": 5800, + "0 false": 9995, + "default_solid false": 12655, + "2 false": 35365, + "0 true": 1114, + "2 true": 2021, + "1 true": 43, + "5 false": 443, + "5 true": 5, + "6 false": 295, + "6 true": 8, + "7 false": 49, + "7 true": 1, + "4 false": 51, + "4 true": 4, + "error false": 17, + "3 false": 81, + "error true": 2 + }, + "block_tag_entries": 300, + "block_identifier_entries": 1286, + "block_tag_resources_sha256": { + "minecraft:acacia_logs": "a3fe4062ef8bb3451c897eb79914295a11f65798067f46125973c6fcbc38cd4a", + "minecraft:air": "8291f3984418fa56cd1ca3f5132344de25cee407647b0f97d6008bc0f3d47d1b", + "minecraft:all_hanging_signs": "33646181d260854e86dbec7cb3bdba15e5eb19a60e73a153ab08a4e6f309b022", + "minecraft:all_signs": "39fb174cfec0c7e7ab900d41688e5891ac054e8da52ed07a6ec9cd0a8e9f6109", + "minecraft:ancient_city_replaceable": "dfe7692dddb25cd1945334741782d2b85048aad2d20fc8e1106585a23ec34acf", + "minecraft:animals_spawnable_on": "29bc3cad17be92ae4b0e091a505cce0f6faf221dac55d2ee45268c9c3c9737ae", + "minecraft:anvil": "35b635afc68b437deab9e22b105f2157142f3c8982e9ae58768fce792794d9f9", + "minecraft:armadillo_spawnable_on": "d51ba988ad47362d4a0125a716d3d489ff97e86f5f81520f696647cbcd0d8e14", + "minecraft:axolotls_spawnable_on": "7cbbc9d5d3bc7c9a5f25486c13e0257beeeb33f5dd9d0e67e3c2e1cd5317fc0c", + "minecraft:azalea_grows_on": "06462d5bcf74a19283aa696ec12252c59f5779fb18919680e24e2632bcfa332f", + "minecraft:azalea_root_replaceable": "ea787c96911c9c031f6a08761a13df0e365f3ad32dd5550a6b467b1b0e6b823a", + "minecraft:badlands_terracotta": "fb20ddb79e6d9cf29cbe40a5712a563305022adbe1daa31ea6c690f99389c50c", + "minecraft:bamboo_blocks": "d31d10554cafb75ae74d3b753d985f2cbd7446902097581021666da9934e0d3c", + "minecraft:banners": "a619cc9e21da600971dcce0ecabbb2d08156e874e2d6eb753e08242a2f80c75c", + "minecraft:bars": "9a6bc562f574cdfff902974ab1165727eb6e81504dc4b4d44ba0f32e5957b268", + "minecraft:base_stone_nether": "8a29caeac2ba106f3b704764bec7d08f51825469933b022302dafd1692067ffa", + "minecraft:base_stone_overworld": "dbc51469f7d53ba1abd680a073c2cc25ba98985f0028404f1119e141dad0218f", + "minecraft:bats_spawnable_on": "69333efdca32f71c9dcee137cf6ffbec22607ee5619d381ea1c68f60efa49aea", + "minecraft:beacon_base_blocks": "14af42fff017cf89fc8386b3159c9257554c24dcf09143232bda49e3576f81c8", + "minecraft:beds": "c60f07a2c3442866abead7f297dc56d835b66d669e84b3bfb5b21e82d59de0cb", + "minecraft:bee_attractive": "079044ad1df6dfdb4db0fd4b0bfaa9b43faa10e2ddeb78375602d6aaf2157963", + "minecraft:bee_growables": "2914a1ec2a067fb0c86da831b73023bd7d877cc6d21bd16415464674724fec8d", + "minecraft:beehives": "f3da4490467e3cd1512d348a0c6fc007531de4709abc5503331db32759cd27e6", + "minecraft:beneath_bamboo_podzol_replaceable": "0e1b480d0de85f7442f0d6a8e2c6de59f85ac6a373cae267cf58f47d4d1fb6d9", + "minecraft:beneath_tree_podzol_replaceable": "0e1b480d0de85f7442f0d6a8e2c6de59f85ac6a373cae267cf58f47d4d1fb6d9", + "minecraft:birch_logs": "2a11ab5f2ebe93d1711c665f111b5ff2d64506a6df2a3fc74c0052ebefa18430", + "minecraft:blocks_dolphin_jump": "50071b6af79dbe9d94c0b98058dc2457d5480854d768bc74668411f7f58b9165", + "minecraft:blocks_fluid_flow": "d4c2425e9fe5472ddda8338490328855c546db5fe1851d6c1f4b4d32756caf56", + "minecraft:blocks_lava_fire_spread": "50071b6af79dbe9d94c0b98058dc2457d5480854d768bc74668411f7f58b9165", + "minecraft:blocks_motion": "35acfdd0a05447730fe2e6f07e32a847bb5b27fb3f4e6171e40c0d9612e81cda", + "minecraft:blocks_motion_in_heightmap": "50071b6af79dbe9d94c0b98058dc2457d5480854d768bc74668411f7f58b9165", + "minecraft:blocks_motion_in_heightmap_no_leaves": "653310d03a663ac3f29b65527057ef8858b6ea1082e9f06e9615f69018a972b4", + "minecraft:blocks_motion_no_leaves": "9b3eb333f9eb30185ec87d3bc81e0ee54c0ab31ddd3e9b7581b3b4266574f214", + "minecraft:blocks_wind_charge_explosions": "ef9816aea3e3beef7ed5c049c3d827955000272e810468e082d98cae0586da12", + "minecraft:buttons": "6f2192e09f74a817ba9861e0cb374e6859ef94cfd584f3d5945bb4b8ce15f360", + "minecraft:camel_sand_step_sound_blocks": "dae4cb2e5b66d4132350b8d27d9d725b6f82d1e0275ae8891aee704ff36d3bd5", + "minecraft:camels_spawnable_on": "99d10c8d690cda2d9334d3cf49f1feb4d1980c8661a0c903e2df7b5a5f23048f", + "minecraft:campfires": "32cb4dd3346afa7bf10901cb37304e6208e6c10dd63c88b1767d693d27b22c1d", + "minecraft:can_glide_through": "e1b304a494b93be2a3280ea6cc7c73ebc0fd76e21654af801d5e4359e94232a8", + "minecraft:candle_cakes": "6074402049e9768ee880ce88e7a00a8382ac0190b95a0534fea33b370b8c9289", + "minecraft:candles": "dc2341cd97a3d8dc1df1d442bacb0a911d1f81c25df08710eea0d7253415f345", + "minecraft:cannot_place_basalt_pillar_on": "d577b04d4223092aa2b1983f4e9802438daa7937c85ee53d1dbd54281ae13a84", + "minecraft:cannot_replace_below_tree_trunk": "b869c9fdac19692d9c365cdffadaabc73633e1588bbfdb08bdceb4a17c837309", + "minecraft:cannot_support_kelp": "c4aa173611f0f072f04e625e5d3d7a7b5e1cdb7f81a54103d7f89e4f4faa487b", + "minecraft:cannot_support_seagrass": "c4aa173611f0f072f04e625e5d3d7a7b5e1cdb7f81a54103d7f89e4f4faa487b", + "minecraft:cannot_support_snow_layer": "282662c1139488dcc43e3bfe48a36a6c4a759e53cb6a4024454236b8f07384cb", + "minecraft:cat_does_not_teleport_to": "c9da7ebe4c3f5cbb5dc72510a64484c68c79414cd63bba2b603cfb3d49a57ebe", + "minecraft:cats_can_lie_on": "bf3cb7e9d117fc573fca34ab86c6979289cc3192b17d84306ad534321e899fd3", + "minecraft:cats_can_sit_on": "4416a8f4f8d5cfcb599958932e3257483f9261c8972ff2defabdb02c7d6493e7", + "minecraft:cauldrons": "12ddaf45c37b545b22dbc7f05da886e6c97300e020e998a9d1bec68cd51b998c", + "minecraft:causes_continuous_geyser_eruptions": "83522a84667866ab21d9776f961368ac345c579f1eeb388580343261f1b21457", + "minecraft:causes_periodic_geyser_eruptions": "c4aa173611f0f072f04e625e5d3d7a7b5e1cdb7f81a54103d7f89e4f4faa487b", + "minecraft:causes_suffocation": "50071b6af79dbe9d94c0b98058dc2457d5480854d768bc74668411f7f58b9165", + "minecraft:cave_vines": "b936bbb57d972003dda38f1d3584e3749915f26220843b941fc2571ef901c75a", + "minecraft:ceiling_hanging_signs": "d1dbf93fc2ffe927d72c0fc6ea5702d7bbf77b5b9a5cd48a93a6ffcadab84598", + "minecraft:chains": "4e3ec3f4c41f349ed0b469c047e6084748b091d14ffd25caa3037ead63e21d48", + "minecraft:cherry_logs": "651f86e2ab999dcd89ca1bdf2e0cf8ed532b15e65d6a71bb6ea4dda59ebcc49e", + "minecraft:climbable": "d0e3e76d7457f3f3f3d7219fe218c7746e4b2e7626d5c388fcf193089069e365", + "minecraft:coal_ores": "a6d65d25fbfef911eb3df9b2fb2eb6412cafefda7e4b0dd3df3cda7d1fcb1df9", + "minecraft:combination_step_sound_blocks": "0f0049644c911eb764bf3b8fdaa59428c4e2fbc7c3de2717af173b649e8f882e", + "minecraft:completes_find_tree_tutorial": "0ba6fb9b71c4350443fc0c9e0a5c2155b95ecf3a13f855e4a58714b9a4955711", + "minecraft:concrete": "57fc0503da49743426d50286c13bb21794d31d566d273e26fe6ff81f5f9a719c", + "minecraft:concrete_powders": "353ec33929acd67fb3fd2d2d9afd400f4b78d728eb98aec54b71670915b101a8", + "minecraft:concrete_slabs": "8bbcc1487efaa92df0a692c6e981071815667f0dd7e54ccee902a68e66855b1a", + "minecraft:concrete_stairs": "f1aef28be2123848182ee00437371d1c654fdd03d5fba9f5dd047bc1146a5a22", + "minecraft:conduit_effect_block": "78203bb255a7f38b712e4901e216e2ba40134a178d6eb5c75513719954ee9280", + "minecraft:convertible_to_mud": "602250ca21d148d2039d75c295eb98a4298d0fdc262240d6d55d7ebb872809c6", + "minecraft:copper": "4e34e2f842a084c1604b7a3df787b35dc3b44a45b1019ada8ea4f50b2fc9c4f0", + "minecraft:copper_chests": "09fd20c394be6e02fd845abc57fd8f50c5731f373707831f54ea49da0b9136e5", + "minecraft:copper_golem_statues": "5f71ff30a9bd7f06790ea7bd7c622644ea01d1cfc609ff056c565194524208a5", + "minecraft:copper_ores": "d89eef2319cb6ee0c5dbd39e1750557ee92c7d94d262354f941fd5dbc323dc5b", + "minecraft:coral_blocks": "d890e6d640cc21a2b692c6e32e25baeeb2c120245105297a78fd4abf8250ff2c", + "minecraft:coral_plants": "f6646184b65ca1bc37deffc95cb56ff01a71374904052bca67985226e1ec85c2", + "minecraft:corals": "421caec9d699d741d7fd69c003fb46e0d551eaa94c9af80ea1a9e75e8d89d029", + "minecraft:crimson_stems": "d8a1ace15b4c981ad4e454dc064c7551e31f40430c93efadca268a008bcf8fbd", + "minecraft:crops": "3b97869fd0e334992d610f1285698384ad2a4d48446f4afb61bc774a066c9c77", + "minecraft:crystal_sound_blocks": "6217bd619dea59a80a48ae687cb20ac977d50bd5cffca7c53f5692fc478c063f", + "minecraft:cushion_uses_collision_shape": "fe4833d3ddebf67fc42ea78907d44c40b58e42bfe4a8a1aa25a6d26265052b9f", + "minecraft:dampens_vibrations": "7cf346b29f2939878163a82291418a9236e8fb5c290e2d07f2acc2469336050f", + "minecraft:dangerous_for_teleportation": "5c411d83a4d828689fad334c774b259120eb47f7c5996f7cc84c569b565a2a10", + "minecraft:dark_oak_logs": "482327a22a5acf4dcd54076ae08ef869c3a05b4ebc3c41eec4349c1c0af8fc6d", + "minecraft:deepslate_ore_replaceables": "358db693d329fa6830f0db25a6287812f04ca16bc76007bd02b27a9a783a09b0", + "minecraft:default_immune_to": "b83114c23eeec820ce7eca52011f13013fb6c64002254be7aebe1e4b36244d48", + "minecraft:diamond_ores": "6061b325909705037f8418bedc24508519507cace911b79369b9c8a2006d4b04", + "minecraft:dirt": "602250ca21d148d2039d75c295eb98a4298d0fdc262240d6d55d7ebb872809c6", + "minecraft:does_not_block_hoppers": "1fe898820d7fafb4b8e154f3f91870571975ca8efdd53041a704162711cf607e", + "minecraft:doors": "07865a23bdc74e0f220b6dc7dbd96bb913f7bf243e71376983de0856e93720d1", + "minecraft:dragon_immune": "b6b5f6eed47888883574b9eccd06178251a730f15c828c2dc83d0870b37a2fd3", + "minecraft:dragon_transparent": "fceddc0e5ad8b41c33a47f6ad3d232a57c04b8f1d3ca2f1fc1edf37741591e03", + "minecraft:dripstone_replaceable_blocks": "69333efdca32f71c9dcee137cf6ffbec22607ee5619d381ea1c68f60efa49aea", + "minecraft:edible_for_sheep": "bd5e054d8a8833a0dd829316196eeb43e9b5ae80d55b0986f26ac6240233cba6", + "minecraft:emerald_ores": "9c4bfb7344364eb612ab4a0cff87356d8538aa508ae0dae134806b946207b6d7", + "minecraft:enables_bubble_column_drag_down": "c4aa173611f0f072f04e625e5d3d7a7b5e1cdb7f81a54103d7f89e4f4faa487b", + "minecraft:enables_bubble_column_push_up": "34064a586d19afe34ef83fbd356eacfe026b9b3a3569efdf28cd88fea8c4bbb1", + "minecraft:enchantment_power_provider": "10d762f960be6460c3c451690b8b2275a339ee188aa6ee2c562611ea2a154cf7", + "minecraft:enchantment_power_transmitter": "994fa10c1ef5d93ac297c5cd254c8487c359c5b8c18b272f02dab1630d4a932c", + "minecraft:enderman_does_not_teleport_to": "791133f6dfd29b7e3dd4f972c520731d5f3ba5ea6a788631e3abb3dc26fbf87d", + "minecraft:enderman_holdable": "62810b2747680097db833ac445364363691001206f22023b73ff54cae43ab289", + "minecraft:entities_can_teleport_to": "50071b6af79dbe9d94c0b98058dc2457d5480854d768bc74668411f7f58b9165", + "minecraft:fall_damage_resetting": "3a765259768c8ecdfcb83e97e00dd808e709d51919d6d52436869bc93bc7b9e4", + "minecraft:features_cannot_replace": "a117e03f857eacf14ff5862ba6f885bb02b476a844b683c2be61211202a9a10d", + "minecraft:fence_gates": "e7f5073f8d01da657f1672b267f11259850f1f516e9682e4d72753bab8f0692f", + "minecraft:fences": "214462701d11703b222317fb7d470caa40e017b5036b127db242986b92fb30cd", + "minecraft:fire": "0074ed2ae89b03a2008a8220636c7544c868326e925b4bfae223891bd5727a97", + "minecraft:flower_pots": "cfcd5bf8e08722705d4c39799b817e6def554f87c39a0c901a3b4a2770f5e754", + "minecraft:flowers": "879e9a5ef65da1212023dfb2f7d842c1053606ef9902c86f45def1efbe5925d8", + "minecraft:forest_rock_can_place_on": "089172380f9dad33704e6f888dad7cbe8ffc5084f1580db5ada9f17ff7509489", + "minecraft:fox_immune_to": "24140175721e7b970c19144465d65d9ad51f2f7eee62b0d46eea2fd9e8b41cde", + "minecraft:foxes_spawnable_on": "235a81e5c7a3fc53d4674d8ace8682999ad357d77f57093af82d50ab8210cc6a", + "minecraft:frog_prefer_jump_to": "746f4240de2b36def3a89d86323027f25e1e9c92cf80cb465e31e581b723ab5c", + "minecraft:frogs_spawnable_on": "26600c631e98396171480739ecef5da2a9a6c988aded4e4fe98e1037c13c5452", + "minecraft:geode_invalid_blocks": "bdf2c9f19d40e9648c58eb6ebe9583e32102a88acda417d89bb8ec8151b93313", + "minecraft:glazed_terracotta": "b26bcf2138eb8a100e648cd036e5ab76142edbbdbf679988e1f816087cda7680", + "minecraft:goats_spawnable_on": "b5da3deb14f0c4e78384638b9b770b628f4a394dd15fac8e4d3266926d802c75", + "minecraft:gold_ores": "65ad25a49ab9172921f468a528cb1a14de1c4f46b14cf275434cbe3e8d069bf0", + "minecraft:grass_blocks": "43e3ca99c7840ab423acdc412cc895a3d420061e5471f79c273de5c3ef665037", + "minecraft:grows_crops": "4d7f9113151ae6fcfc7622ffe89f7c64f3f5bd0cefe5b778c9e7c11491183cea", + "minecraft:guarded_by_piglins": "df149f60e06249fcfb0f70f92a3ea34917bcf5f265729425147597eb2aca0441", + "minecraft:happy_ghast_avoids": "f4e76ec462e4f8b120f14f3eab2dac459348c85090da677a8051c8699919f929", + "minecraft:height_specific_ore_replaceables": "4b5787e3d7aec6d70ce5f9a7919df0aab705e2e368695065e6abcd21005f1681", + "minecraft:hoglin_repellents": "09e4345473c0448dad9192dba6c9273f7dbe919cbe547c8eb6f0cea0247d027b", + "minecraft:huge_brown_mushroom_can_place_on": "334213e1abb6463227cc3d9a24970800047ebc02d596277e9c4e7ba6a9feb013", + "minecraft:huge_red_mushroom_can_place_on": "334213e1abb6463227cc3d9a24970800047ebc02d596277e9c4e7ba6a9feb013", + "minecraft:ice": "85098bdeb333fb4b630565e8679bfaae143d78defa4dbf0398280a9f4d863db7", + "minecraft:ice_melts_when_destroyed_above": "50071b6af79dbe9d94c0b98058dc2457d5480854d768bc74668411f7f58b9165", + "minecraft:ice_spike_replaceable": "5da056adf11b03c033541fc4cbb69ce878bfa31c48d54a6e88656f6b7284e841", + "minecraft:impermeable": "3afa898d24e49ba1e32165e8bfc370aeebd508cc90eec9e3bf0f5a3d202d5ad2", + "minecraft:incorrect_for_copper_tool": "5fe30a57d8935ba07c4b1f3d76498655ac4e8471e118474c18e42ca5caa9ca47", + "minecraft:incorrect_for_diamond_tool": "b83114c23eeec820ce7eca52011f13013fb6c64002254be7aebe1e4b36244d48", + "minecraft:incorrect_for_gold_tool": "dbe4a0337c74949f118c6252dd75488c75c41b672b753f1f5222d5def15711ac", + "minecraft:incorrect_for_iron_tool": "61c0fa3215f263a2bd4a01d504e03e3d83613f9f09a76d060136b37941abc78e", + "minecraft:incorrect_for_netherite_tool": "b83114c23eeec820ce7eca52011f13013fb6c64002254be7aebe1e4b36244d48", + "minecraft:incorrect_for_stone_tool": "5fe30a57d8935ba07c4b1f3d76498655ac4e8471e118474c18e42ca5caa9ca47", + "minecraft:incorrect_for_wooden_tool": "dbe4a0337c74949f118c6252dd75488c75c41b672b753f1f5222d5def15711ac", + "minecraft:infiniburn_end": "f498b235a368f9abe32ab4190fee70924da9af4624d0d2383260805f85882858", + "minecraft:infiniburn_nether": "c5256847f721908d61a51568598a141bc60bd2779aec34505b7b90381064592e", + "minecraft:infiniburn_overworld": "463640bbca53006d499273ffb36499d1f6f596a11d073ccd7ad7156335ba1a58", + "minecraft:inside_step_sound_blocks": "2d97011bfe26d35e5895027ce80f3372b79ced9138bc567bf8cb031520f8a596", + "minecraft:invalid_spawn_inside": "68137e3d5f9fa6a087427c73f686f7c2282011007153eed9377abfb3c57c4a04", + "minecraft:iron_ores": "2f6f3610e361a06ca72bda39893431eeebc864dcf389cb0c4c55826ebe6bb587", + "minecraft:jungle_logs": "4ae9b365f5d403065b424f54a80018da98fbc73dd9b21564dca5a0ed77e89f2d", + "minecraft:lanterns": "ed570e0784f38272eec1325490be861a719e0d3747a591aa865f175cc0ee9f54", + "minecraft:lapis_ores": "2c986a71c5f2819549e17647415b6911250ddba23f03d9720fd10b6ad7c066d4", + "minecraft:lava_pool_stone_cannot_replace": "5b276c48e550fd769a8137a42f7dadf5e15625c336c7def6e07379c60a27bc92", + "minecraft:leaves": "4e531a80db177ab0b6fa8c65bbb6d82179a1fd5c1e31ca2ca8860b9b6c26329f", + "minecraft:lightning_rods": "54efd924cb3670c6894bd5a1d3cefd40f80752a98c8c457c78210a8e3efd0e36", + "minecraft:logs": "439a696d433df1387db440b32017d1ae9a5b1ffad9ffce5d5c9cdc3a02b29484", + "minecraft:logs_that_burn": "6697c4380b98c6d240f59ba291974c61067e6e4e45bce4464ed7a0a15c333b93", + "minecraft:lush_ground_replaceable": "b783ab0f70d5d9aa2807bc852410a0e1b682d46c476a05ca947f6f33001f839d", + "minecraft:maintains_farmland": "8d059a868793fe740b1cd2a6edc013246a068e35fb7477effef2b59b49f07bdc", + "minecraft:mangrove_logs": "0e314f82ca811b358eac141f3fd65b5f886ca1de9a5055a370901118c4096f1e", + "minecraft:mangrove_logs_can_grow_through": "7bd6f349aa8ae59cea0cc1469abad9963d5df24ec797777e3c3d750fe7555ce2", + "minecraft:mangrove_roots_can_grow_through": "64ba58eb3e4e89e8488a641f35dbad02fc2f19517ec690013d6aa2c9266d95a9", + "minecraft:mineable/axe": "14cad4e01465720095785e2d83807ca9b5eff6a1e24a76d50d17eabbee327ee9", + "minecraft:mineable/hoe": "138f9a28a1ca58c362dbcff3d7487f33b5e921b60c82a155a38dc5ef3a1ca26f", + "minecraft:mineable/pickaxe": "1573d7327fd943eb1f58f81e56bf29f55140ab200f4e721773fcb10b6cdfa7fd", + "minecraft:mineable/shovel": "732d8db1157516e8238ed13c85d4d85b5e49313b745007f361970a83b5f0b87e", + "minecraft:mob_interactable_doors": "e1b420c07e8f75bd802a2fded9307c0d13db1b72624660f59bcd99ff0552592d", + "minecraft:mooshrooms_spawnable_on": "67dd8577579b4c563afcb5d0f4c66677af1d0be4c5061b3e87eb4f3438c2f8f5", + "minecraft:moss_blocks": "4302e1e162fddeb21cf18ac8375f57bc2885fbdfa5b5cdcfecf1406b701d73d7", + "minecraft:moss_replaceable": "d53f7ef7d5c4cec3347e1a6aa39dd92655d09685768446e15b7e944ee9d3add2", + "minecraft:mud": "21b98cf5d9598dd147bd1cb169d5ab133083b0af90bfdf343e786c7b2e764ee2", + "minecraft:needs_diamond_tool": "fce3d4bef99721711ffb1bcdd72812c82e55e90d02417fa3065c260c0f96b833", + "minecraft:needs_iron_tool": "38ddda4cdd6d06afa8afa328f3606c944f736ef6e85e376121c84bbb8743d2e5", + "minecraft:needs_stone_tool": "9086735ddeba00745a8fca8d8768d19d638613a50a3835064aaa0188a9867200", + "minecraft:nether_portal_frame": "b72bce8b52e825930a2b907f6d720d8019a98405c4e66db0cd785235d378791e", + "minecraft:nylium": "2bf59f6932ed8a1530f92d4dfe8410eaa25741291f9f882688438814701bfe53", + "minecraft:oak_logs": "939819db71415f16498a0f19ab34e80c9cd60e08a507b31f60d49762575613e0", + "minecraft:occludes_vibration_signals": "b848777c11c4a202a79169339d6f3898c63610b2556cca783395fdbe36377a41", + "minecraft:ores": "0571768a41f42bf46252e9be35515558245b8640f2809bb6be74fd00a7c57da1", + "minecraft:overrides_mushroom_light_requirement": "efdca24061ea4c72dfd92d7fc85ba4febacbe7b2438430ad22fc50a5c31c4a9e", + "minecraft:overworld_natural_logs": "6e0974d475d448f34b0c23f062aaa7ab007afbddaa808870b63ae97aa88d82f5", + "minecraft:pale_oak_logs": "272aa7c38e04ab5616d8b70bd319fb7867fa9fa54ca4f815f338ba22084268ac", + "minecraft:parrots_spawnable_on": "d95d588b2b0971b6a1ea9ec59917c3834c5b6faee760e64455090b024417553c", + "minecraft:piglin_repellents": "e8d41b3b596d6bd2614787d1ad0d9eb79f79243aaf37c4f22be77edd4d6639e3", + "minecraft:planks": "1b2433c0a7edddaea36d87189429fb22d726ba2f8c406532624ba1df49998908", + "minecraft:polar_bear_immune_to": "c9331c65e0f8e076b9556a4951117b5db18676ebeaedd34c98a4c36229721b0e", + "minecraft:polar_bears_spawnable_on_alternate": "0214bf0cf9dc2da33e3c8619b6bc8654ae81126711ce8a55d07fe3af80cd6bdc", + "minecraft:poplar_logs": "9f2c1c5cf9a53e7cb2d21dc770b4c10c1bde4fefe5c2c46e1c3d95b53b69e968", + "minecraft:portals": "fe9759678b07daacfebc3ce9e5aa616489cb432af36d14ce4cc1128cd3a410ef", + "minecraft:pressure_plates": "f230b7dfb4144845d2a5c8686c22d0ee6401ac7688e9941025f322c76b93d807", + "minecraft:prevent_mob_spawning_inside": "6b48540f3809b6cde38322153e4c09a45e91c5d8b6356ac03ac2ed763af40f3d", + "minecraft:prevents_nearby_leaf_decay": "1f97c8515ceb8886dab66238b675a3c4ea0eef6b8a92350bc7667d81a90dcfee", + "minecraft:rabbits_spawnable_on": "a908ed77300ac3d697c8a3c56570fe60e08562b8bd5a3f079aa4671218ac94e7", + "minecraft:rails": "fa33f7e0ee5381b318e70b3a0a96a73ea420c75355ac77e9ae69933491585a99", + "minecraft:redstone_ores": "7884553e4f4b0ac64a7dfdf172271b870ada01b0fbdfbc8a4af3bb8db6ab974b", + "minecraft:replaceable": "6abeeb6e8520263e0876b4ef457f0d38dae703abca63ca4408adf3ba99fe2ecf", + "minecraft:replaceable_by_mushrooms": "f62394a973f927da9b4b667938c03528412ea2dac58663fbf94e0f3eeda31d0d", + "minecraft:replaceable_by_trees": "8aae57fc70df3c4c9a7224adb842df9e35b3456567e75b7598d236a38a0b3f04", + "minecraft:required_for_poplar_leaf_ambience": "14a398b48f6980dabd49663f04bd864effe9fca3287da35d7217f95668abd206", + "minecraft:sand": "8b019e944ba404bfbfadd0389a94e0fe907819b109cbccf577f7bb80826cc8e8", + "minecraft:saplings": "a59858d94b488625036481631db5b63c716ea1027cd89eedcc3749e3832e3ff2", + "minecraft:sculk_growth_inhibitors": "86f2dc2d79bfe4f8a25e9877b2453b0b493654af80f9fd1f77d8133c8abd5377", + "minecraft:sculk_replaceable": "8f5c608ef4e8c74002bf9d13a50e81804d37f72c59faf80dfcb7367f6e1ec476", + "minecraft:sculk_replaceable_world_gen": "35a9d8a4e947c8f09d44a9836766d639ac37e647dd5da23ca5b8b8f3e0afcb34", + "minecraft:shears_extreme_breaking_speed": "5f10b4c2ffc5a5a565fbbf9e36f5ef7a39db59cc52d495e82f59232a87055cfd", + "minecraft:shears_major_breaking_speed": "bbca62b8be3d948489f7a36a58ca63e9a88d7a400ca48c20bd7c16dcab8302e4", + "minecraft:shears_minor_breaking_speed": "400e88cc600815a02e905e834331d8f5f7f06d0f7a8bfeb762b2914a1e1930df", + "minecraft:shulker_boxes": "9bc43c47d90eb246371c67b7d5b631ceed7acdaf489be766f5f03b32cae9d12a", + "minecraft:shulker_does_not_teleport_to": "6948279d2a8c57c2033996a56afb1cdf5f9bb08e54b48449834d25aa11b56b8f", + "minecraft:signs": "f17adec59bd57315440524f6edfe7d18a8f6f372afe887dc9a0151055a15706e", + "minecraft:skulls": "9d95ce3eff65efe58e979dd82eb66fcbf224c8d583a28a12f6f9ed8499e2c987", + "minecraft:slabs": "c29f6f1f62555855b99d525641ce4bd4e6e31516d7c20fb9ff987762ab8d1a9b", + "minecraft:small_flowers": "d54cf92939e90d72302dfe7c0c2f127e56ccb9622e8564729a591089f42e9d0f", + "minecraft:smelts_to_glass": "f32f9a585b721d552bdddd85e3ae92515b24f320508be56e79da1b5dfbe40126", + "minecraft:snaps_goat_horn": "e0adabc6b55755bbe745e2d1ad76a888bc0ddb0946c49066f43781b6d260db27", + "minecraft:sniffer_diggable_block": "882d72a1c6578f0daa93700cb32833ab255fb92b8db0b7008c48d43592cfcc80", + "minecraft:sniffer_egg_hatch_boost": "bb3f57906b51fa5d25833d31618a004ad8674079f221080ad3f725a06dbfab39", + "minecraft:snow": "24d5e3b9042595e734d911caf4d1d59f8d27c865743fd7562fa72d32f0b5acd0", + "minecraft:snow_golem_immune_to": "c9331c65e0f8e076b9556a4951117b5db18676ebeaedd34c98a4c36229721b0e", + "minecraft:soul_fire_base_blocks": "8ba7eac6f7c74d25601ef4455b71e3947fdb8e51b8fafd55dddee48397b144b6", + "minecraft:soul_speed_blocks": "8ba7eac6f7c74d25601ef4455b71e3947fdb8e51b8fafd55dddee48397b144b6", + "minecraft:speeds_up_zombie_villager_curing": "38c66dd46c59f72fe7832706e8f197e2654975aa2c9c8a87d5d9bb3bfe5a80a1", + "minecraft:speleothems": "ab7de03a837a56a0ddba55735f279688546b19a80e4f6cd73332dd3a5da8c286", + "minecraft:spruce_logs": "129c6d79945e1bc246fb8ff32b8a6848035c6ba63f0a6d65c18adfbd41111307", + "minecraft:stairs": "5d25e93ee7bf03994223098ea9bcf2f9a49a619aa345e7097848e441ad63d33c", + "minecraft:standing_signs": "0d212a5664d8626496b70b38aba8cda581db0ccea7021d051be5cc5b1e2f9335", + "minecraft:stone_bricks": "61f8c78df54ce0d2af255dfda5d13d9768c82817518122b77a27da6d5f62e924", + "minecraft:stone_buttons": "1ebb5c3d79c2828ace64c52636451f05ea536411050c3d198646dc60d367051c", + "minecraft:stone_ore_replaceables": "73e4e80760bec9744d8f16343b21c396ce656e21593512264034b71f39164b27", + "minecraft:stone_pressure_plates": "88ef362edff8fcd8911d9e66db8b9e8d7202666e349706399ee97cd532126e01", + "minecraft:stray_immune_to": "c9331c65e0f8e076b9556a4951117b5db18676ebeaedd34c98a4c36229721b0e", + "minecraft:strider_warm_blocks": "83522a84667866ab21d9776f961368ac345c579f1eeb388580343261f1b21457", + "minecraft:substrate_overworld": "bd87412cd52db66ca8be5c79bad2622ec04318a5ccd90da89304e03d15360e5a", + "minecraft:sulfur_spike_replaceable_blocks": "9b691bdeedfa35a01dabb7554b1c32dca4c5de67da85a841c381db7d3ce84bb6", + "minecraft:support_override_cactus_flower": "396c699cd80945fbeda41f41c5797e36464f866c43a0dca08740c790dd428923", + "minecraft:support_override_snow_layer": "c7491ae1bafae440421e90a1387ac87f46f7e003f37315f4acf5ea0d0ee8cd5a", + "minecraft:supports_azalea": "7cd5cc83fc555289eac260b9a6726e531e6590ac4abac92e1de2a9e163d25b31", + "minecraft:supports_bamboo": "3d11eaccececc7c180f07c29103f4e0c0de0eae88cef00cb6c830df27fe6bbb1", + "minecraft:supports_big_dripleaf": "29b86e096da2a2a4c1efdd676b64ad7d7c8db65b537412d374781f068e6c14c7", + "minecraft:supports_cactus": "99d10c8d690cda2d9334d3cf49f1feb4d1980c8661a0c903e2df7b5a5f23048f", + "minecraft:supports_chorus_flower": "fd1861976dd8d10f3181b7070dc066b06d20b1ec6764bec7ef1d26f5c500b989", + "minecraft:supports_chorus_plant": "fd1861976dd8d10f3181b7070dc066b06d20b1ec6764bec7ef1d26f5c500b989", + "minecraft:supports_cocoa": "9c052ed599c8b8c782ae8bfaeb82cf241b8e5fdf0dfb8461f72db7de41991e98", + "minecraft:supports_crimson_fungus": "edfb0dd7ad8c89ecc53d6983332b353b1c9bae7bae38dbf6ef01d9805d79ca66", + "minecraft:supports_crimson_roots": "3c682d1feea46f22e4a1c382321347ef6c7f0c875c472ccb5ee77c5ef6cffda4", + "minecraft:supports_crops": "4d7f9113151ae6fcfc7622ffe89f7c64f3f5bd0cefe5b778c9e7c11491183cea", + "minecraft:supports_dry_vegetation": "15c03a19f25f4e359ce7bbed76e3545b003afee26a6dd1fa9fc54ed13d757f14", + "minecraft:supports_frogspawn": "b83114c23eeec820ce7eca52011f13013fb6c64002254be7aebe1e4b36244d48", + "minecraft:supports_hanging_mangrove_propagule": "568c4172f5e1c709753e9bd5c0b90fd8d00ebf273d3ae41ce2d0b994b3d70e30", + "minecraft:supports_lily_pad": "083ad48f95c51480fe049d717ae88770fb736087f5e654260eb3fea47cefee9b", + "minecraft:supports_mangrove_propagule": "7cd5cc83fc555289eac260b9a6726e531e6590ac4abac92e1de2a9e163d25b31", + "minecraft:supports_melon_stem": "95f16c95de4122a2d1cf36e4a465ea02c9f471adfe846fa3edcf147c5df0cf14", + "minecraft:supports_melon_stem_fruit": "0aec0e82e8fe82cb1900a7c4b25755985f863af73d7f473d2bbcfa51c2dbd14c", + "minecraft:supports_nether_sprouts": "da4cbcf213787b215358c9c671b8a0f675f6066b2b057126b320d7bdc8b7b3c6", + "minecraft:supports_nether_wart": "34064a586d19afe34ef83fbd356eacfe026b9b3a3569efdf28cd88fea8c4bbb1", + "minecraft:supports_pumpkin_stem": "95f16c95de4122a2d1cf36e4a465ea02c9f471adfe846fa3edcf147c5df0cf14", + "minecraft:supports_pumpkin_stem_fruit": "0aec0e82e8fe82cb1900a7c4b25755985f863af73d7f473d2bbcfa51c2dbd14c", + "minecraft:supports_small_dripleaf": "a99bba4f6b9d38de565a516dc3225a44bf1bfb0abcb5a41b741b4391ad82185d", + "minecraft:supports_stem_crops": "95fa800e152c76f36a71d12f471f9410676c5a959685e16067e1858bd6aadc43", + "minecraft:supports_stem_fruit": "d60c648291a7878f5e2b817990e4cf96861a0ff0665f9279cd7ccd2edc9f1502", + "minecraft:supports_sugar_cane": "e14e48890d10f8a260218e45d9461ae7f3d2a8b67f40760e4d61f6e4f1ed082c", + "minecraft:supports_sugar_cane_adjacently": "d423c0f2b573812f5145e497cf05f1a0f58919f8e8102d1cc8e41460c82c0a4e", + "minecraft:supports_vegetation": "4d1b4da00fa525283307235bbf0ccb7d9d0d5b7ca2fb79a9bc526c45cdaed94f", + "minecraft:supports_warped_fungus": "f19d6362b9fae5e2142e3b0dfee12b71ca41f4017d711d1629e374ddff03995b", + "minecraft:supports_warped_roots": "da4cbcf213787b215358c9c671b8a0f675f6066b2b057126b320d7bdc8b7b3c6", + "minecraft:supports_wither_rose": "1e4b2b3e19deb22aa3d5342e530a184f1d9388bb957bd39f5bb4da5f36c7bd08", + "minecraft:suppresses_bounce": "a477a87ac4bcb97971cb0b445f4cc9b6b8e02cd31ba3d01bc842b17a6a8477a8", + "minecraft:sword_efficient": "d7dd01ce779d198112646b71060382d7f6e10fee51f69dd792bb7e70cdbd3796", + "minecraft:sword_instantly_mines": "3160a75a72843c85ea22a98f4cd3b811cd1c9d71b807a3f7ad1fed05d6e2f06f", + "minecraft:terracotta": "d05ea6b1a2f1e794ff11745534938eaf024ac9debed7b29ef272aba4f1b648b9", + "minecraft:trail_ruins_replaceable": "dd61dc33a8cad62aaf6ee212ec69a4cfa06a2548259203d8d5f975048c6d6c68", + "minecraft:trapdoors": "0b72384f2da185aa3727914af7c4b72eb09574b1f3319a8bfd38b7899e77871d", + "minecraft:triggers_ambient_desert_dry_vegetation_block_sounds": "b9a1ed369a8a7d615f5fdb4a189dc6692984f562136502238c31c8b43344f74b", + "minecraft:triggers_ambient_desert_sand_block_sounds": "f32f9a585b721d552bdddd85e3ae92515b24f320508be56e79da1b5dfbe40126", + "minecraft:triggers_ambient_dried_ghast_block_sounds": "8ba7eac6f7c74d25601ef4455b71e3947fdb8e51b8fafd55dddee48397b144b6", + "minecraft:turns_into_dirt_path": "1e1986bfbc635a9c2e8dafe50201c9ab228973770bd4adf60336451b0eaff725", + "minecraft:turns_into_farmland": "b6e5c0b39744b55dff4b471486cf653757095ed24898fec15111a6da6eb21232", + "minecraft:uncarvable": "6948279d2a8c57c2033996a56afb1cdf5f9bb08e54b48449834d25aa11b56b8f", + "minecraft:underwater_bonemeals": "7f145355f4840f498d2e8951e905562df9ec57b35bd2e239db60fe5e6c4b78c4", + "minecraft:unstable_bottom_center": "b7b0ae50f52c2c35c3c2aa266d7365f88d6b6d463eb3c23ddb6f25d7438e0c11", + "minecraft:valid_spawn": "0fa990e0cfe3e367fce4af268e5cb1958b2ce2f1fd569c1bb2ce38c28bd4092b", + "minecraft:vibration_resonators": "21ae4048432850b44fc277224bc0bb04ac26c43ea865b677c4d61d316cf4199d", + "minecraft:villager_babies_can_jump_on_bed": "bf3cb7e9d117fc573fca34ab86c6979289cc3192b17d84306ad534321e899fd3", + "minecraft:villagers_can_sleep_on_bed": "bf3cb7e9d117fc573fca34ab86c6979289cc3192b17d84306ad534321e899fd3", + "minecraft:wall_corals": "e218e0a27b6e0b1ff685c3181a747b25eef3fdecf1d91bd22acc420eed16cf39", + "minecraft:wall_hanging_signs": "4015ec17b365fbbf2790fcc77f9cce25c2bc8f573b2bfb76615920d5b4f480c3", + "minecraft:wall_post_override": "c0aff6e7027ae63685e75d05e9d317ac35b8f0e65ef0702a1a0e7e92dd711c34", + "minecraft:wall_signs": "48193b7fd4ae4ed47b4bd3b143fa2679d3389301c89eeec62f87421b3ae3048a", + "minecraft:walls": "b41e70add357bbf1b1498ad15df2257c3fd8677f27578a2980b6e3f1e9082996", + "minecraft:warped_stems": "7515406d2b3d3f41697dc6b31579d2750730de34638196df3b9ba1618e3afbaa", + "minecraft:wart_blocks": "548bc2c73a5292d7beab476a32329866c2a5c870ae5d537eb20c459578f06b28", + "minecraft:washed_away_by_fluids": "766b16b3c4a49982103214e10398f4dd8a941cd69e100e3ae89c6a7c0267cab1", + "minecraft:wither_immune": "b6e3c98f2ffab1e0c4ac7000ff5a0da7446caddda14128d629ad8e91d1088d21", + "minecraft:wither_immune_to": "6c5034bdd6acf6121eba6ecac49c3492f5a0c640d71d37802231f413331ebdb3", + "minecraft:wither_skeleton_immune_to": "6c5034bdd6acf6121eba6ecac49c3492f5a0c640d71d37802231f413331ebdb3", + "minecraft:wither_summon_base_blocks": "8ba7eac6f7c74d25601ef4455b71e3947fdb8e51b8fafd55dddee48397b144b6", + "minecraft:wolves_spawnable_on": "52048dd1c3d0b7c8e53b50a377759e08da6bc258d874f299809ccf2e3ceaf16f", + "minecraft:wooden_buttons": "9b98c5efd80d70e2c0c242742faadf928c55bb87a12537ceaab819098de59acf", + "minecraft:wooden_doors": "a1119985376529ec73b217cb1fa776232830d03d6504d7479819e49067dc195f", + "minecraft:wooden_fences": "5d2ef0da8c97d26478f44329541792cbd0be1f141a0a347fba32a1f1b292f552", + "minecraft:wooden_pressure_plates": "013f6d8f09d6cd0c0d3a173971fc5aada626122361c164c36ec0291d642de082", + "minecraft:wooden_shelves": "a9934fc780d5e6e533443a842f36eab0c09e14c19ff06d537d77964952f5b91c", + "minecraft:wooden_slabs": "191dbe3c0e7a6a8a1c5cdca0ef89f8e0d5d15d7df01d05afde971e1954944745", + "minecraft:wooden_stairs": "9c6340ce2573c3b988be980ebe15200d9f817bc14d6f4982fab430f0b6696923", + "minecraft:wooden_trapdoors": "b5cd0998d48fe3ecb24b49cffe4eeed411085e3c3b9ed05e794254c29b0afb93", + "minecraft:wool": "02dba7a59e67c70ea0c21e21ff9b081047f9d6f0d39b5b6ad8d95d53eff28ca4", + "minecraft:wool_carpets": "bcf8ca0da1842f340fbb23f7582913a0ede9f33c6b99149fde3cb944c4bef545", + "minecraft:wool_slabs": "7047da1dc7f8f64b74d327b6e491b5ce4d3296ccb73cd8813b01853fcd54c660", + "minecraft:wool_stairs": "7f70163726c2e5632c673f0cf7b0ca3cc39347eff97284c41d3d787c2fb8c7f5" + }, + "noise_registry_entries": 64, + "density_registry_entries": 55, + "noise_settings_entries": 7, + "biome_parameter_entries": { + "minecraft:nether": 5, + "minecraft:overworld": 7594 + }, + "biome_tables_sha256": { + "minecraft:nether": "09e477f851380a6e726ea85fee39cd1d41c7f160fe424f58cb3f0056b5c11218", + "minecraft:overworld": "6bc45ce2eed04b6afecdfaf2cf89273e83dad071aeb45638e181d33fe5180f57" + }, + "fixtures_sha256": { + ".local/rust-worldgen-parity/registries.json": "816a473e6109c3eca1800f15641eb67b909a17b5e638e38428878dfa1ba2bc56", + ".local/rust-worldgen-parity/inputs.txt": "838760bf635afb0ae8925f490cef9dbdc30142bbcc67be088c2b5a65dff91937", + ".local/rust-worldgen-parity/biome-presets-client.json": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9", + ".local/rust-worldgen-parity/biome-presets-server.json": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9", + ".local/rust-worldgen-parity/blocks-client.json": "2e1b3c1c168bd1b54665df724791923f703db859bf62cf8ac1d083a8da9b3ec9", + ".local/rust-worldgen-parity/blocks-server.json": "2e1b3c1c168bd1b54665df724791923f703db859bf62cf8ac1d083a8da9b3ec9" + }, + "noise_resources_sha256": { + "data/minecraft/worldgen/noise/aquifer_barrier.json": "864a9d66a03b081adc8d4bf51a6d0cd5fdd94a0ebf1cecadec2aed9e549db7e4", + "data/minecraft/worldgen/noise/aquifer_fluid_level_floodedness.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/aquifer_fluid_level_spread.json": "6afc3f09b6616f799d739b5b114c4436059dcc60308af55fe96a8594de815214", + "data/minecraft/worldgen/noise/aquifer_lava.json": "96e1c4e411ffe302c5541cd2ee8462e1992f0290d623c560f353c39981737346", + "data/minecraft/worldgen/noise/badlands_pillar.json": "79c0d0628db949d3b83bbca145da427bcdc3ff585b0ad736f7cb20e4c593c9a2", + "data/minecraft/worldgen/noise/badlands_pillar_roof.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/badlands_surface.json": "79365a5c2017e93878d989a176520ba9cbdf8685cff8b3cb148730d949d98b09", + "data/minecraft/worldgen/noise/calcite.json": "331259d84572c32b4b268d069e0132da9e6623ba614080e34b815472c7f4ee0c", + "data/minecraft/worldgen/noise/cave_cheese.json": "24c6846b7fc1f7c652bf185797fe98b943146b6aaf8766d1bff2066c59b7ed24", + "data/minecraft/worldgen/noise/cave_entrance.json": "f75146a7b1a033998edd3c77319f78243fe933bdcda2067b78658940f145cac6", + "data/minecraft/worldgen/noise/cave_layer.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/clay_bands_offset.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/continentalness.json": "b7ce5ac29a2c7a7cfbfaa1e1eeca9ba8f4a52139e59318850fa2407242c69ba8", + "data/minecraft/worldgen/noise/continentalness_large.json": "76834cff0227d52b19b5932142925f4fc639e713c2180e489f813701ca45f53e", + "data/minecraft/worldgen/noise/erosion.json": "af8a7a0f16ff3e568ad646df9cbc28e04a31b16dad4f162705c0f7c747da6983", + "data/minecraft/worldgen/noise/erosion_large.json": "d20c2c6ec805a366b105924b3cee29ac5b84cc06d636b539ae0047aac413b60a", + "data/minecraft/worldgen/noise/gravel.json": "87d627634161e51a79512f3d3f42f990d2a185e35198eb5e2161939d866751e0", + "data/minecraft/worldgen/noise/gravel_layer.json": "a4b45bdb6efef2509b053b970f6e84250d7b16d54f3906bc7fcf2665ada2a692", + "data/minecraft/worldgen/noise/ice.json": "85d03cc06d6bc552dc399dcc90ca9749c2625ddf0049dc0f95684631a7c6e66e", + "data/minecraft/worldgen/noise/iceberg_pillar.json": "98816326f84a21ce29421a9cba3ad85e5a26069312c9819aaf5662691e777fd5", + "data/minecraft/worldgen/noise/iceberg_pillar_roof.json": "864a9d66a03b081adc8d4bf51a6d0cd5fdd94a0ebf1cecadec2aed9e549db7e4", + "data/minecraft/worldgen/noise/iceberg_surface.json": "79365a5c2017e93878d989a176520ba9cbdf8685cff8b3cb148730d949d98b09", + "data/minecraft/worldgen/noise/jagged.json": "d64347f4f9acb984075e3b4945b4699907ec6d893588388dd8f738f29f75f4d1", + "data/minecraft/worldgen/noise/nether/temperature.json": "5a67fbc28b5c2578b4ca5f6abdd115c715ea2ef1be3e1a7a8eb1a0de4c3a8f7c", + "data/minecraft/worldgen/noise/nether/vegetation.json": "5a67fbc28b5c2578b4ca5f6abdd115c715ea2ef1be3e1a7a8eb1a0de4c3a8f7c", + "data/minecraft/worldgen/noise/nether_state_selector.json": "116c8bf1d676fd3a3dea3908e074a4f4b7ee55d3263e93abf5889b41bfc77f5b", + "data/minecraft/worldgen/noise/nether_wart.json": "4518b186ffe4b65394a35276c8708037c6f3f73c7cb95ef6d41a5cd4b8d234f6", + "data/minecraft/worldgen/noise/netherrack.json": "cef60938a0304eec78a6bdebd24b80a45c5d1bad894c6c012e3413ecc485a81a", + "data/minecraft/worldgen/noise/noodle.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/noodle_ridge_a.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/noodle_ridge_b.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/noodle_thickness.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/offset.json": "45f51565587e2dc055271648037c0ec3466815e82f0d762e0198c16285fc8ae7", + "data/minecraft/worldgen/noise/ore_gap.json": "6afc3f09b6616f799d739b5b114c4436059dcc60308af55fe96a8594de815214", + "data/minecraft/worldgen/noise/ore_vein_a.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/ore_vein_b.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/ore_veininess.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/packed_ice.json": "0f51993727dcb0aa7c6cb9288e462443e711e9980c12927435126a3c45922786", + "data/minecraft/worldgen/noise/patch.json": "83a0052d4220c67c5513bce689d681e3af3325c18fec612cdd4941fc738f4be0", + "data/minecraft/worldgen/noise/pillar.json": "5a67fbc28b5c2578b4ca5f6abdd115c715ea2ef1be3e1a7a8eb1a0de4c3a8f7c", + "data/minecraft/worldgen/noise/pillar_rareness.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/pillar_thickness.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/powder_snow.json": "98816326f84a21ce29421a9cba3ad85e5a26069312c9819aaf5662691e777fd5", + "data/minecraft/worldgen/noise/ridge.json": "e05d077746b27d662a8c981807819df3e3bb1f1779d2245dd911c8193e03bbf8", + "data/minecraft/worldgen/noise/small_patch.json": "9ecc836feb68b42d717217e028f2a72112179f1097f5bd156b1d3f1db637732e", + "data/minecraft/worldgen/noise/soul_sand_layer.json": "a4b45bdb6efef2509b053b970f6e84250d7b16d54f3906bc7fcf2665ada2a692", + "data/minecraft/worldgen/noise/spaghetti_2d.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/spaghetti_2d_elevation.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/spaghetti_2d_modulator.json": "d210211c0c76c53f15908f0b004a7e98e9d753ed996cd5468f2068f2e23932d1", + "data/minecraft/worldgen/noise/spaghetti_2d_thickness.json": "d210211c0c76c53f15908f0b004a7e98e9d753ed996cd5468f2068f2e23932d1", + "data/minecraft/worldgen/noise/spaghetti_3d_1.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/spaghetti_3d_2.json": "e755b926628bc49edf48a3bd3b1e1bc3e2895b774f5e2e81f1d4340782a9fc56", + "data/minecraft/worldgen/noise/spaghetti_3d_rarity.json": "d210211c0c76c53f15908f0b004a7e98e9d753ed996cd5468f2068f2e23932d1", + "data/minecraft/worldgen/noise/spaghetti_3d_thickness.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/spaghetti_roughness.json": "6afc3f09b6616f799d739b5b114c4436059dcc60308af55fe96a8594de815214", + "data/minecraft/worldgen/noise/spaghetti_roughness_modulator.json": "7f137a0382721b8c7b3227e65dc32a3f6d9c3d5893458b03e892797ae31d85d7", + "data/minecraft/worldgen/noise/sulfur_cave_gradient.json": "4900ffd885ce33b220a673ba0a248504c78f9f2cdfce824106a237d9ad18a6a7", + "data/minecraft/worldgen/noise/surface.json": "79365a5c2017e93878d989a176520ba9cbdf8685cff8b3cb148730d949d98b09", + "data/minecraft/worldgen/noise/surface_secondary.json": "ae23cb210db7b64b66b327dbbf1e7b2acb5c15cb6fe5df0455eb29910d9312eb", + "data/minecraft/worldgen/noise/surface_swamp.json": "19e08e0d1dff257cf748d3cef79e939e8f25cc5e7226653c789008171f40695b", + "data/minecraft/worldgen/noise/temperature.json": "9b1d5a87d575abf2891882ec3e1544b964cd15fedc84ad14d2abbd3b48ee2e4b", + "data/minecraft/worldgen/noise/temperature_large.json": "4fe64b952b751eb7e45b4d1e274add508b504ee8bbc54cad417ce3a3b068d42e", + "data/minecraft/worldgen/noise/vegetation.json": "ff4c10776eb2822f9f66dec4e9878a1bc797aca711480bf8430f851ff9af77dc", + "data/minecraft/worldgen/noise/vegetation_large.json": "20f4a255e3f9452f4cf983b3efed71ead184d04f4070283f355ad4d97993d133" + }, + "density_resources_sha256": { + "data/minecraft/worldgen/density_function/end/base_3d_noise.json": "38db7d590abc3144e3357a79562d649d9880bc2c62ddc99480d93f4b6401c9a6", + "data/minecraft/worldgen/density_function/end/islands.json": "6e4f02929580ecc34bfb059855b4e88d080dc7ca6c9984f216bdaa32e6b47700", + "data/minecraft/worldgen/density_function/end/sloped_cheese.json": "5dee072865321e57e5e231e60a57bfcd1919454f93da33b3c1651b3712f2cfb2", + "data/minecraft/worldgen/density_function/nether/base_3d_noise.json": "76cfd16e6fc2b1ce8bdb5f5ee277d431c167bc01afc2462bffff09eb5f0bd582", + "data/minecraft/worldgen/density_function/overworld/base_3d_noise.json": "2791a1e6c5c730eac1bd35aaea9a7ab22855872fdb92349192d045330fd4614f", + "data/minecraft/worldgen/density_function/overworld/caves/entrances.json": "63a1b8351e6dea212501c36f515f32e5a0e960228b5b5ccf0dc5b43855cbc1ab", + "data/minecraft/worldgen/density_function/overworld/caves/noodle.json": "3bce7453470fd37e3bfc11dc8584494aab094f9fd820038dc5592cb47e825a69", + "data/minecraft/worldgen/density_function/overworld/caves/pillars.json": "069d35fbdaed7d74521fc3e9355a94e778450b52a05f1efbd470ce3917b8a207", + "data/minecraft/worldgen/density_function/overworld/caves/spaghetti_2d.json": "a99c68ac415596788c84e93e81c96c9786e31db21a81157459a13272cda4cb1f", + "data/minecraft/worldgen/density_function/overworld/caves/spaghetti_2d_thickness_modulator.json": "4f987a0b9e8c0adb02df47034fa8b3cebfbfb2c8e607123614ef009a16bfaf6c", + "data/minecraft/worldgen/density_function/overworld/caves/spaghetti_roughness_function.json": "03bd1b405e53aeb75b6a3440d97975c25b6f11c7fc07149471b86c80fbdb6ea4", + "data/minecraft/worldgen/density_function/overworld/chunk_surface_level.json": "93a4e26ce4a1144c42040f52ca375f0dec94648c70ccdcc52db4a7f55ca526a5", + "data/minecraft/worldgen/density_function/overworld/continents.json": "0f2ff487c0556391ae2d56b7cab6990d45766ade2503236fe2669f83a64517be", + "data/minecraft/worldgen/density_function/overworld/depth.json": "9fcd7c8badcae4dc8e86303b0f72b05b5fd998d5bb7ac637729dd7e688688069", + "data/minecraft/worldgen/density_function/overworld/erosion.json": "8173a3df61a3c5cfe352fb4a8fa64e99840836e42f2f4b0ddf8035f4d28f97a5", + "data/minecraft/worldgen/density_function/overworld/factor.json": "f7cd1629f1a034504bd74fd38af5ea75a59257c565b5d919a6212e2e08778e30", + "data/minecraft/worldgen/density_function/overworld/final_density.json": "a7e6b9f4618e27cb08ec37a294d8ca2a96747128a8d65d788dc418fda372cfb1", + "data/minecraft/worldgen/density_function/overworld/jaggedness.json": "5e8acc680409ae0b56596be02954eb5b49a72069d004e5dcf9a92c5e106ccdb2", + "data/minecraft/worldgen/density_function/overworld/offset.json": "da6b4e686d8eb16c19443a1126168b6f2719712c02b690b9d7384ce53badf995", + "data/minecraft/worldgen/density_function/overworld/ore_vein/copper_density.json": "3b16d3a4499981f40bfd2b33786a99046bbca0c958f8f41692ffcbf44ae927d7", + "data/minecraft/worldgen/density_function/overworld/ore_vein/gap.json": "89ccfa58c6b8ae3e3954d2ff2dbcc42a8a3ae24a7b07437dbfb85fdced55945a", + "data/minecraft/worldgen/density_function/overworld/ore_vein/iron_density.json": "8de70a31c97e2a8299679770d53c8e366ace1aa8585e8d840375d25f85b72f8f", + "data/minecraft/worldgen/density_function/overworld/ore_vein/mask.json": "7f92df0b19e7d29fef01abc7025fea2bdae7a57453e186785cde2fc7d08aa5bc", + "data/minecraft/worldgen/density_function/overworld/ore_vein/richness.json": "3eb0183e295a5f9c54aab936b706b4b9d570ddf56c983ae89b91151e6e38fb9d", + "data/minecraft/worldgen/density_function/overworld/ore_vein/toggle.json": "49b9db48740578911d0f8a2de40f02eced3ae742f03ebb05fee381af579cc9ed", + "data/minecraft/worldgen/density_function/overworld/preliminary_surface_level.json": "4b6ce4c38ede0bec7485d4c029b9fcc7ceb5b26977c2c391a650fe8f3a3272b6", + "data/minecraft/worldgen/density_function/overworld/ridges.json": "bf66a03bd8474d09dad4da23f4b7e76816b83e23df9f53d9c0b7c529c25ed9c1", + "data/minecraft/worldgen/density_function/overworld/ridges_folded.json": "c8a4343b56273a476648a84fbbe07d8c473c1dd3769749260db6340ba5b37f9a", + "data/minecraft/worldgen/density_function/overworld/sloped_cheese.json": "5e2e7756881a4f2acf2e8c8dc826a04681939ff1dc7508ce868e865e92a069d7", + "data/minecraft/worldgen/density_function/overworld/temperature.json": "3c2f498cbf4636cd1fa7f555c14220a733c9d07fb5a1563f11c6144a27f31ce8", + "data/minecraft/worldgen/density_function/overworld/vegetation.json": "c902ef045f63a568ef4c3d834716c67b5835f0994997ee45756837de111a806c", + "data/minecraft/worldgen/density_function/overworld_amplified/chunk_surface_level.json": "378eef8542e7ee3adffeaf746e0c776d1e00ff75cf030d9244292acd796739f6", + "data/minecraft/worldgen/density_function/overworld_amplified/depth.json": "35bbe18bc8eaec3bc8d81f1b3130018874d6cc8fa516c1e8380bdb8caf68c803", + "data/minecraft/worldgen/density_function/overworld_amplified/factor.json": "b42bc13d4d3c1cbeb7c6dfa2e16f4ef532ad0cff3a92d20bace01711fee6edd4", + "data/minecraft/worldgen/density_function/overworld_amplified/final_density.json": "cde96d8a5efa63cd20cea615dd1172e5e6f2626e9275d359fa2864e77083ac4f", + "data/minecraft/worldgen/density_function/overworld_amplified/jaggedness.json": "9f9a8993ce50cd2f0736ef98c3f8ff55db02d47b2a3e4f6aacae7c45a3c95bcc", + "data/minecraft/worldgen/density_function/overworld_amplified/offset.json": "0bb9ae6088ea4dbfdf79f6f2b2eed789c68e9a4e919a31bf912f91ddeda28e8b", + "data/minecraft/worldgen/density_function/overworld_amplified/preliminary_surface_level.json": "e8a82a9dfe183f4e624ea7a268efa2c54376caf99139596a26ad1dd27e887e5f", + "data/minecraft/worldgen/density_function/overworld_amplified/sloped_cheese.json": "d8609154b76d0eefcfbc3746fa84f32cb04c5817a2fd1b80e72ee0ae9d88e96c", + "data/minecraft/worldgen/density_function/overworld_large_biomes/chunk_surface_level.json": "72f29b5fa9c01afa296d3679e6be662ee1b0bfdc1ba40cc2092ea74380be5c47", + "data/minecraft/worldgen/density_function/overworld_large_biomes/continents.json": "cfab013269cff17cfdf95497f87e70591378e7a39da44a241199fb64b304d411", + "data/minecraft/worldgen/density_function/overworld_large_biomes/depth.json": "9ec8ced85b58494f5400d4a5f6a27f1d4d44271d7a87adb8c5d842319eb5997f", + "data/minecraft/worldgen/density_function/overworld_large_biomes/erosion.json": "773d626db8e356d92a321270895ce085287d2befcb4504842371c38fd10102ac", + "data/minecraft/worldgen/density_function/overworld_large_biomes/factor.json": "0e7aa57eca20ebd6d2f089a9a4a34502efe902295812650f71b2ff087bb8b15f", + "data/minecraft/worldgen/density_function/overworld_large_biomes/final_density.json": "6f644644293c5489c499dc57663f2c12de60fc720bc4f1120efd343246eb159e", + "data/minecraft/worldgen/density_function/overworld_large_biomes/jaggedness.json": "30090703d4d9e493d40d60e06ee12f1310a608e20b73aeb8f86efa8e31b11453", + "data/minecraft/worldgen/density_function/overworld_large_biomes/offset.json": "75517306420732023e2dfeeb253439d8f0edcde9bb8b10ee7870d1bdb072ec22", + "data/minecraft/worldgen/density_function/overworld_large_biomes/preliminary_surface_level.json": "ece7767faac91980f5349ddfdc6040dc4ebbfce71a9f4d5842fa1b7bb169db3b", + "data/minecraft/worldgen/density_function/overworld_large_biomes/sloped_cheese.json": "347e160b5f951137b5f82a39c18572f8851c5a22484d11f31d1f90f5e5f6ac99", + "data/minecraft/worldgen/density_function/overworld_large_biomes/temperature.json": "051138f2c2f0ca4050b92f7320ddea461dca2038a49eb6f9931ecbf39129f4ef", + "data/minecraft/worldgen/density_function/overworld_large_biomes/vegetation.json": "187b08814a3831cd0ff2f405c6683e7213a79dc7eeec44cd46136e350b0718b7", + "data/minecraft/worldgen/density_function/shift_x.json": "0db6e5f781089feede9d8d2936d7564024752e34006b8bc9f2a138749f91e3e7", + "data/minecraft/worldgen/density_function/shift_z.json": "0b561cdfafa9e82f431a8051576eb2ddc386d01459df571d7040021b0debb762", + "data/minecraft/worldgen/density_function/y.json": "e7766e59792605f5c3d8e05ff6263db1dc6c91343c736b3ab7a58ddee9771282", + "data/minecraft/worldgen/density_function/zero.json": "8aed642bf5118b9d3c859bd4be35ecac75b6e873cce34e7b6f554b06f75550d7" + }, + "noise_settings_resources_sha256": { + "data/minecraft/worldgen/noise_settings/amplified.json": "07fbadd0fd71e16e5497c575d3c86d997166087ccfaaba70a589a440b915024e", + "data/minecraft/worldgen/noise_settings/caves.json": "29a378b845f7bff27a8badecba7ecf2bb22d0d4224b751ab6d91677c83bc6a6a", + "data/minecraft/worldgen/noise_settings/end.json": "d0fd92ddd39081f1779ce5482041a837fb4a03841ea4d843556f17b557e31f4b", + "data/minecraft/worldgen/noise_settings/floating_islands.json": "54923e55bfad4274bea513eccb42e1eb3625fb47ae00905537e0d3d68f82045d", + "data/minecraft/worldgen/noise_settings/large_biomes.json": "dcb29a9e3fb630f2b76a52d759c6925b40e67cd13bc7f9ae93976f0633cc2c05", + "data/minecraft/worldgen/noise_settings/nether.json": "e6d7856fe4523e4c3fa4dce756b6b1e211bfc263c5e417fb6294d032b8f53e9b", + "data/minecraft/worldgen/noise_settings/overworld.json": "d093895d50edd79d53555b33b62d767115399764e32a4f9ae2687739f785d4b9" + }, + "inputs_sha256": "838760bf635afb0ae8925f490cef9dbdc30142bbcc67be088c2b5a65dff91937", + "rust_output_sha256": "9a006099c19f8527b739ea906bfe3c7db54e7517910562e16a78482ed0f9b4fb", + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenOracle.java": "f81e5e2c3cbdc47ecbc14333f43c10487aa67e1a4166cf96c7c6cb11d8dbd27c", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeExport.java": "f9a773713cf21b69bfa10018b76f27b953bda140ede9934f43d3aa3091101cf5", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTagExport.java": "83b3ae46e8d052eda3f65c044ae742651366138c7014b91464824c79dae24b41", + "tools/test_worldgen_parity.py": "b40972ab2ad222aa6d77537cc36b434a217baa1f1b56bbaad945d6e12fe776af", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "3968e2a337a6a23226c485057c79359e66df16683f00fb4ebc9fabb03910a015", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random.rs": "92135a94c79111cc810b4b071dbd76043ee47c2585fd431e7486ea381f19e5db", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-core/tests/density_world_fields.rs": "e193e45080817ef92547828a8d106482a376b9f788e39d4d3831f44e9d693148", + "crates/horizon-world/examples/collision_fixture.rs": "ee754b5b42e0a51fe0a305b3f4bb56522ff3fffae564180aab8087b1b9e44afc", + "crates/horizon-world/examples/heightmap_fixture.rs": "eddd4c15620eebfc5bd919d3b19b0b2fd69d6fd31a19d8c512121aa297efa848", + "crates/horizon-world/examples/structure_density_fixture.rs": "780cbf5dbf1f948e2d8aac54eff67a900de652fe31eb007f55dd33177f38fdab", + "crates/horizon-world/examples/terrain_fixture.rs": "eb521404a3e850be522f3bda2f7c724c7d1b66e154e1bc53121b4e7511e5b1bd", + "crates/horizon-world/examples/tick_fixture.rs": "df267c307e0491a238b2d93edf0384514f38f8ee3252e315b989de56c6e17990", + "crates/horizon-world/examples/world_fixture.rs": "a3c4c0f5131ae051b24662eff0ed11ed797c6fd5069fbfdf819f0e3fcdfb2cf4", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry.rs": "f46065659e60eb5e84ad69b9f3b5e94dc87ee19de16408817e26f23d16b6c7e7", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "7516e20a20479d1c4a9734d7d8e9826740b324869d7afe51eab94bb1bc7c97ae", + "crates/horizon-world/src/worldgen/terrain.rs": "134cf93b53a40fb1ed0e0170c90316c80e270773b2968c63dc3f9cef2c941bff", + "crates/horizon-world/src/worldgen.rs": "b89dd4a9de02caf6bce457304a105ffbc0f0f220f8647c095852a45a1bf292bb", + "crates/horizon-world/tests/biome_data.rs": "d4de462ccc3e6ad5760490330e0f0cd8a45734077708a2eca95ca06e65f779b0", + "crates/horizon-world/tests/collision_data.rs": "45f3d33b36efe720e99ebf75b9f4fbddd777cebea4618bba245ca106b3443391", + "crates/horizon-world/tests/tick_data.rs": "ab345209367db6963b987797992c4a06433bd2039e6021bd834f6305324c04d7", + "crates/horizon-world/tests/world_io.rs": "4a42630c99ce89b27cc2be1a1b961ad880f62762ab661f9e92ef9bcf7f3e76e0", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e" + }, + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "9a006099c19f8527b739ea906bfe3c7db54e7517910562e16a78482ed0f9b4fb", + "matched_output_lines": 961693, + "biome_export_sha256": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9", + "block_export_sha256": "2e1b3c1c168bd1b54665df724791923f703db859bf62cf8ac1d083a8da9b3ec9" + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "9a006099c19f8527b739ea906bfe3c7db54e7517910562e16a78482ed0f9b4fb", + "matched_output_lines": 961693, + "biome_export_sha256": "b03e2fbe85c191a22f333bc989bd2a73c66f0f9fbcd9ddb54774f17c247832e9", + "block_export_sha256": "2e1b3c1c168bd1b54665df724791923f703db859bf62cf8ac1d083a8da9b3ec9" + } + ], + "scope": "Direct normal-noise JSON decoding using the actual pinned vanilla CODEC. Every bundled noise registry resource, explicit/default parameters, empty and full amplitude modifiers, normalization modes, inclusive field bounds with signed-zero comparator ordering, malformed types, null fields, duplicate and ignored keys, decimal/exponent integer truncation and wrapping, signed zero, seeded modern/legacy and Nether construction, octave metadata, range and normalization bits, scalar noise values and parent random state. JSON resource contents stay private. Strict JSON parsing; no claim for Gson's permissive non-JSON syntax. Bundled density registries are also decoded with actual vanilla registry-aware CODECs: named forward references, all bundled function kinds, declared range/axes, raw compilation errors, seeded optimized roots, cache allocation, scalar values, strided bulk values, repeated cache hits and surface-volume errors are compared using RandomState's actual compile context. All seven bundled noise-setting resources contribute their actual eight-field NoiseRouter.CODEC objects to RandomState. Router fields are compiled in declaration order with a shared compiler/context; cache allocation, raw/optimized scalar and repeated strided volume values, successful single-layer surface volumes and invalid surface-volume shapes are compared. Actual RandomState climate sampler binding and quart-to-block coordinate wrapping are checked at ordinary and extreme positions. Float-to-long climate quantization and long-to-float conversion include subnormals, signed zeros, NaNs, infinities, cast saturation and seeded random bit patterns. Actual vanilla Climate.Parameter and ParameterPoint JSON codecs compare scalar, two-element list and min/max object intervals, float endpoint bounds/ordering, required coordinate/offset fields, negative zero, precision-sensitive float parsing, malformed types and duplicate keys. Climate parameter distances, wrapping squared fitness, stable search-tree leaf order and nearest lookup are compared across every supported branching value 2..32, sizes around branch powers, the 65536-entry API bound, duplicates, warm ties, fresh lookups, brute-force lookup and extreme signed-long endpoints/targets. The Rust tree is immutable with per-worker search state instead of hidden thread locals; invalid or degenerate searches return typed errors. Inline arbitrary distance metrics and behavior outside the bounded API are not covered. Built-in Overworld and Nether quantized biome parameter tables are exported independently by each authenticated JAR and required to agree before Rust consumes them. The Rust multi-noise resolver and actual vanilla MultiNoiseBiomeSource compare biome identities through scalar climate queries and prepared bulk quart volumes, including forward/reverse/repeated query order, wrapped extreme origins and shared previous-result state. Biome holder keys in the reference are registration placeholders; no biome property or gameplay behavior is evaluated. The Rust loader reads a Horizon quantized table format, not the vanilla biome codec, and the preset builders themselves have not been ported. Source and private fixture mutations during validation invalidate the report. The two-field 26.3 NoiseSettings codec, create helper and LevelHeightAccessor clamping are also compared across bundled noise members, dimension/alignment bounds, zero/negative runtime heights, disjoint ranges, wrapped integer arithmetic and decimal/exponent integer conversion. Global fluid cutoff selection and the actual disabled Aquifer implementation are compared with original default block-state identities, extreme sea levels/coordinates, signed-zero/subnormal/nonfinite density and counted picker calls; developer fluid-disable behavior is outside the regular-mode corpus. The actual noise-based Aquifer.Config codec and runtime are compared across bundled aquifer settings, modern/legacy world-seeded aquifer factories, synthetic density roots, nondefault water/lava states, cave/void air, nonfinite sampler overrides, strided volume extents, wrapped coordinates, repeated and reversed queries, counted picker calls, sampler call order/values, injected failures and retry state, scheduling flags, populated location/status caches and sorted surface-cache entries. Oversized or wrapped-invalid grid allocations and developer fluid-disable behavior are outside the bounded regular-mode API. Terrain filling is not yet validated. Router, vertical noise and optional aquifer members are decoded from each noise-setting resource; complete NoiseGeneratorSettings, material rules, nonempty world fields, biome registry/codecs and complete chunk biome assignment, generated chunks, gameplay and rendering remain pending. TagEntry and TagFile codecs, ordered resource-stack replacement, first-occurrence member deduplication, required/optional dependency cycle pruning, lookup order and flags, missing-reference partial results and all bundled block tag members are also compared with actual vanilla TagLoader. Block identifier tables are exported independently by authenticated client/server JARs and required to agree. The bounded tag API supports at most 8192 tags, dependency depth 256 and Java hash buckets without tree nodes; hash-tree ordering and pathological self-cycle failures remain pending. No heightmap or complete terrain integration follows from tag resolution. Inline noise holders and general codec behavior beyond the covered fixtures remain pending." +} diff --git a/benchmarks/rust-worldgen-random-2026-10-06/scoped-parity.json b/benchmarks/rust-worldgen-random-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..f0c80d9d4 --- /dev/null +++ b/benchmarks/rust-worldgen-random-2026-10-06/scoped-parity.json @@ -0,0 +1,162 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "fixtures": 300, + "random_modes": 2, + "wrapper_depths": [ + 1, + 2, + 3 + ], + "operations": 119100, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenRandomOracle.java": "25e4a0c0403d1261038aa525e04e53c0484f4e5ada6c6a32f951bf6af5b057c8", + "tools/test_worldgen_random_parity.py": "be09554796751cfd2c872676f36ebb4a71def368049a7ab413ca478defdc63a3", + "tools/test_rust_parity.py": "7efa699a38c5820424f5fc8992ee601dbfe26d6482da9d2dab2c17c41fe8f12a", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "Cargo.toml": "dc370d5fdde37238c3e4820046f11c3201020406a4edfa1308257c13edbdcda4", + "Cargo.lock": "7307d0c887364db36d327685ecf0671b75305e31e5ba5fbdcdbb15eaf156d20e", + "crates/horizon-core/Cargo.toml": "e21b502c949da93cf67826592459b687a8cbf737ef92fee514e3ed2cc7cd27ad", + "crates/horizon-world/Cargo.toml": "977338bf3e654193685b015d383493b9f59ff6f5d6210bec212cef8ac4a50bed", + "crates/horizon-core/src/bin/density_parity.rs": "e5b1dd33b7d01306c73cf072629b4fb186e9ab87b672a00108999d1a72263fd0", + "crates/horizon-core/src/bin/float_log_parity.rs": "4a655fcf8822ee7668c4bd126bc84d0b118864a6fc7f5a6aeee667d8bf2590b1", + "crates/horizon-core/src/bin/geometry_parity.rs": "27f6c09fe5018ac3de8e70e0f0bbf78f9abb14f5e4783bcaf46e8ca87b9c6f8a", + "crates/horizon-core/src/bin/noise_parity.rs": "c135bfc708d853e7061e81487d2cfe10de64b2f65677d3b4837cbfe0b8341010", + "crates/horizon-core/src/bin/parity.rs": "f35d928c66f958de39fac5e7e836a657eed95f83599e84899f7ea7a5802ba481", + "crates/horizon-core/src/bin/tick_parity.rs": "a54c164fe4814034d369947a887f5273966f5a878ba849204b80d1c729526a8f", + "crates/horizon-core/src/biome/seed_hash.rs": "5afbb4921c750826b395a08bf06f382fc7f01b5759a93de02a2749c523e2a317", + "crates/horizon-core/src/biome.rs": "908efa8cd4aa0a7adf1cb5e1a222e3dfb640eed5e9172e0fe7f0d1287afae7e8", + "crates/horizon-core/src/carving/ellipsoid.rs": "09232a7588610e8a9176fd9c62d40afb1fb89f2ecab6d555536a1d847b142d86", + "crates/horizon-core/src/carving.rs": "0aa3093caa0437868a8c0ed52a6c6e1993bd51c03583c670a2837e749eae5426", + "crates/horizon-core/src/density/arithmetic.rs": "372faec96c923e2cf4aa6c66c1ac398e676853274557823850dbc8933dd15ab1", + "crates/horizon-core/src/density/beardifier.rs": "bb1052e27dae4a01954ca78d7d5babafef85f3b2c704ccaf1920cb85a098cb50", + "crates/horizon-core/src/density/cache.rs": "38d0b6c9dd04ffef979fdad3f29cfebf98d331c8c9d430be5f39aa34f6c30975", + "crates/horizon-core/src/density/end_islands.rs": "168b9384237bd2e41d0ae5a74e944da4dc74e493bdec31fb73184c9a49e3de55", + "crates/horizon-core/src/density/graph/compiler.rs": "ac67deeb16f16d0859aa20e5a165811a29aca0b910037ee6bf5098211f3a6ede", + "crates/horizon-core/src/density/graph/mod.rs": "b776e7da934cb03051a3053d56d461c71e9978e084922fe4194147aa580c07bf", + "crates/horizon-core/src/density/graph/seeded.rs": "6bcdcaa3dffcfa9df673bbbea35120057a16ba3d2b506c52709c36cf8976b74a", + "crates/horizon-core/src/density/graph/tests.rs": "6bfb8cbff462587dd147b0775ea01d370abbd97544b9bd596c792df1b5f7e634", + "crates/horizon-core/src/density/interpolation.rs": "8c890f52b6467f38a94c654986a6a484b8e0b296ab98c398e60a6ce465b5b010", + "crates/horizon-core/src/density/interval.rs": "b42629163baa6b599a233afe8596d1c370cd81d015cc6fc36a9663aa47b98424", + "crates/horizon-core/src/density/mod.rs": "ca0d77d3282e3746ddcbc92bee97dbf640b9a56214e6ac1537f51f9a5b63d6e7", + "crates/horizon-core/src/density/power.rs": "d5b7270a128d4264268cd772109ad16d71a8ec3ff2d3b63b84cb985296d54a91", + "crates/horizon-core/src/density/rounding.rs": "71840c5206ff8d218ac29bf6f66915d5212764ba270c675711a866ba5b55a7a6", + "crates/horizon-core/src/density/selection.rs": "0dd26af2e85004ec5e053039ad11c384c17c56ace9ab45eb3f5cb3503c0b0330", + "crates/horizon-core/src/density/slice.rs": "5d77605573c0deda47778f1f78f7fa3fbf1944d8f5efbcc65cf589181cadf80b", + "crates/horizon-core/src/density/spline.rs": "6bb2e40f940fc6544d6fb09cb0b8cac722be03bc663dbdfb0f61faae207400bc", + "crates/horizon-core/src/density/surface.rs": "159e0e69cda74f870e80ea64fe523c4397e64af4ccb861bb9fd07b2c3cb91b00", + "crates/horizon-core/src/density/terrain_noise.rs": "8d0059d25eb5d248cb97a4c5a2e670d61528928ea151495c004f25adb723fe3e", + "crates/horizon-core/src/density/tests.rs": "7817796ee40d0ae241bfbebec6bca190e0a8e7d5a1caa8ddf858c3eaa58b8858", + "crates/horizon-core/src/density/world_fields.rs": "c1ce305cb8046b384d90c564cafb24af7365d580389637910f3d8b0cc18eb583", + "crates/horizon-core/src/geometry/mod.rs": "dc92f73885dd0a7760743bf74f1ab8afa839d61cef2dfef890f8a23b67b4742e", + "crates/horizon-core/src/geometry/movement.rs": "930e34abef6f6eeec1ee7a6c920b5ba01bfe37b90678884490f4be53241f6b96", + "crates/horizon-core/src/geometry/shape/create.rs": "189812b91d5e0e3ad963afcd1a6e2831b31b8188df91a904ef27061e644806ad", + "crates/horizon-core/src/geometry/shape/join.rs": "f1b51887b7bf9482557e3ffa99e136f2e5db07ceeb05fdb116adf45e87129075", + "crates/horizon-core/src/geometry/shape.rs": "de22acd7430df3f69ef3632d427c57dffe57f3bdb78950bc75eac7e179ccf9df", + "crates/horizon-core/src/geometry/sweep.rs": "abd6009c61555161ef2f18b431b2aa384b126c0871cae8b96a62358498a56a1d", + "crates/horizon-core/src/geometry/traversal.rs": "77a3da570a0b85582b669cf4d841cba4b06327006dda26d4a26df4e8ce05bae4", + "crates/horizon-core/src/geometry/trig.rs": "05cef9341a298a474221a0556a11ddf47650393ea7a97b4b2022a4da6628fe37", + "crates/horizon-core/src/lib.rs": "47350edab5791f5074a54563ba98108818c5c6b1c5818a591388eab2ac9f5490", + "crates/horizon-core/src/noise/mod.rs": "1dab5a713abf702402e69ace1bf9e476bba544b0ede5a61c3c3afc60af0a03f3", + "crates/horizon-core/src/noise/normal.rs": "e9e7a46472a54a02c98c46da819842090567153b32fe0c84249009ef19af7aad", + "crates/horizon-core/src/noise/perlin.rs": "e73815447432eab7542f67366cb3f1b368d164e33f6c9cdbd045ac8e4db0932a", + "crates/horizon-core/src/noise/simplex.rs": "6c0dbc15b2b7510195dd28fceca01dcaac1847ccc4a84d299c351589c642fe7a", + "crates/horizon-core/src/noise/stack.rs": "7f6ef0e7d920139ef1a6ad3ec5640f92765715f86dcc5ec29f1a149984f45fa3", + "crates/horizon-core/src/noise/volume.rs": "3f05d2b1780acfdfee60037677d309937a5033b45ef428fc2d540942d4b56b43", + "crates/horizon-core/src/position/iter.rs": "32d2d8e74821cc4e49e3354202d35d3120e4415bfdda9375a73f2137ef651129", + "crates/horizon-core/src/position.rs": "e10101088e6902386b9b6d27773d44312f1ff72bebb19e57967a54945dde9dcd", + "crates/horizon-core/src/random/hash.rs": "0f88a127a1ba2705d3d6c0ebd009324d6ba86ffa2d27edf2d2a84765e690e4a3", + "crates/horizon-core/src/random/positional.rs": "35494745e5d4cf89e282c3ae0ee245e9f2640ddbbc03bc0055df742006a9c862", + "crates/horizon-core/src/random/worldgen.rs": "9f07ff33bcc038d34e27aa5465753bb21df18f2975e43cae201f709bc186945a", + "crates/horizon-core/src/random.rs": "ddb95d3a83e28ad605ff1f49f5df270cc543ca5ef1130e37d989dc74c8d861e6", + "crates/horizon-core/src/storage.rs": "f6c32201c64aefde06e57a2c767be46918df613548a322801546b133799cc33d", + "crates/horizon-core/src/ticks/heap.rs": "bf28afab8af77c3d243aa96cd8a1fb8d934140a4dbd07dbfdbf4e7908bb4b845", + "crates/horizon-core/src/ticks/index.rs": "1f1a6a568c2a30eafecb020ca4d5f5fc414860de85b8b381fc419a2e3e65c24a", + "crates/horizon-core/src/ticks/mod.rs": "84852599dde78687d782f115a5b4b3ef6856c1f9cc92917255167e89c72ab01e", + "crates/horizon-world/src/bin/worldgen_parity.rs": "3143ceb9b56eecfd7667e5feb5f9f0cd13cfb8754b38d4ea338dbba97f2819da", + "crates/horizon-world/src/chunk.rs": "8843e6f48dbbc4245ce4e95564dfba3a4d7a051ba0b1577fb038c07adb0ff0f9", + "crates/horizon-world/src/collision.rs": "6c40ab491efd0332bd4e65a1a112f3598f9eb0ea2f32f9c8cc7e81278d003251", + "crates/horizon-world/src/compression.rs": "4db73e6ca9a0d552d415ce60e7e88b89c9cf2b7d060a669ff8328f518316e101", + "crates/horizon-world/src/heightmap.rs": "a5edef082b5af40d814421ea17e129b3b06d70abee6434ed263e4bba58571698", + "crates/horizon-world/src/lib.rs": "5476d0a811941c4ea229c9a21c640aec51757b2483133a0f9c222fecbef5cb36", + "crates/horizon-world/src/main.rs": "fce57418b8c22a6a0a9044baa89ed3d9c243bc2e8413fea3ff0f32985daba021", + "crates/horizon-world/src/nbt.rs": "60262c3de8c8f68bc2da0370ccb17393d32b85f5f5022c6358599a7d32119ea6", + "crates/horizon-world/src/region.rs": "72b642e87fed37ed17f54d4c30f96c3b64d26c14bc0589c31ef40ff1616188fc", + "crates/horizon-world/src/registry/json.rs": "40974e8ddbca79f4a4f866f91f1241a7ac7289874527d4729483995dcf9b4f7e", + "crates/horizon-world/src/registry.rs": "566d7ef6a0d0d7e492d73b7f963ff0158544560a86ba33e179ef4d17e1274706", + "crates/horizon-world/src/tick_data.rs": "f8d04a69ea263f4168bce33f92e5b4ee2fe07d7caf50a1621c6b3ef6eb2479f3", + "crates/horizon-world/src/worldgen/anchor.rs": "d156b8a0b147a274cdd143409b441f4f43edecde6e8ee14ef9cf0309f743143a", + "crates/horizon-world/src/worldgen/aquifer/config.rs": "fcd2cc3a520c1527c88f095a3b5d38487e7ebb1ccecc5f757f93d04a069add4f", + "crates/horizon-world/src/worldgen/aquifer/noise_based.rs": "74daaa389b5c3dfdc99214dfff256a9e172f83548d2326cbc941d9637cc53fb7", + "crates/horizon-world/src/worldgen/aquifer.rs": "cb4b66d87de3f9f79ae6ffe4badd6f0f44886cd42ad9de2771b8b56c4f1e28c7", + "crates/horizon-world/src/worldgen/biome.rs": "b3b73091aa5ec989d916206567c5e4b0e997b007a5bb9c0ca5c53ada9d5fe81f", + "crates/horizon-world/src/worldgen/biome_chunk.rs": "32b937832b7058d86e8557a2012df32be1c97be324f15d0ae85245c45c73b314", + "crates/horizon-world/src/worldgen/biome_source/codec.rs": "2b9e4f5d679eb444cb73174f511e3b9f32e9eb138248ab12cffc6cfd76adf3a8", + "crates/horizon-world/src/worldgen/biome_source/runtime.rs": "f0b02c1521178e4d0377c6ca62694604b6a773f1f234f070ff0cde4685911d45", + "crates/horizon-world/src/worldgen/biome_source.rs": "e181e1736f3e0b75f7091a24c88de3fd116e01b98424d02382aea7a503d1eb54", + "crates/horizon-world/src/worldgen/biome_temperature.rs": "cde4bbab5e260c4065b113376c423b8511ade93c5aa5fd976e245ee8a58b5ad1", + "crates/horizon-world/src/worldgen/block_feature.rs": "c215156f2ecf7faf214b3d89e0829b65d54f4ff6d134d778ec941f18a606a327", + "crates/horizon-world/src/worldgen/block_predicate.rs": "dd8cbda2ec110444950f0b31bf4e088897eab0994674a91568c7b063f8f16210", + "crates/horizon-world/src/worldgen/bulk_section.rs": "eecf61532d7793f853884c5a18a7f436a59835c7b13d3ec9075804511553c9ba", + "crates/horizon-world/src/worldgen/carver/canyon.rs": "509c4d5a9d689849e98e894ab14a9fbf82d10707d38e9cc688ded3c4778df3e2", + "crates/horizon-world/src/worldgen/carver/generation.rs": "a4498d0d1457536de3922a08e9c40ccce8d2ef9cc263801c15a412327513c098", + "crates/horizon-world/src/worldgen/carver.rs": "46b251e28225fe1250de38f49dec5dacda4e2c4ba1e556e21e6d1e14e2651fc3", + "crates/horizon-world/src/worldgen/carving.rs": "4e77d4e5c4a0ca55ca3563b9bdf6f379342e0bdf9d019d60f7bc57ce4afb5fbd", + "crates/horizon-world/src/worldgen/climate/codec.rs": "d567adeb5d837816fca69102db51d790f71aec1b51c09298230d24612e400a14", + "crates/horizon-world/src/worldgen/climate/index.rs": "c5ce61679a5f0e0f2f0af2a373424effa124d0cce8250609eff38b7034650756", + "crates/horizon-world/src/worldgen/climate.rs": "1b9ad44407f40aee4c1cd5357a5c9c443c1b105728f01cf5c644072f99f8357e", + "crates/horizon-world/src/worldgen/density.rs": "65a98c156a290a6b374ef670d28cd5dfbe0aa93171824d1bbd96422536273f84", + "crates/horizon-world/src/worldgen/feature.rs": "40500af71ee6628dfb27518262d99f08d0383ae6c7b9397452feef0c213eadd9", + "crates/horizon-world/src/worldgen/feature_catalog.rs": "486fe9d8588eb09e0ee5707a0541b0df167b63b0b56c90a2709bfa09a0a3ad19", + "crates/horizon-world/src/worldgen/feature_graph.rs": "2297b194514925688dba25016a69d5ba5eb8b869bdfff28f2e611a6742ac5954", + "crates/horizon-world/src/worldgen/feature_region.rs": "4a95a30c0987d97e671f84380e13ddea070ad81f996baa65b2a06c4d892971c7", + "crates/horizon-world/src/worldgen/feature_sort.rs": "0b9d1e1c15d8449125d39e400776b8f28eec7b7cbd047660a94f8cb90160adfe", + "crates/horizon-world/src/worldgen/height_provider.rs": "368d4dc119854742a045c4a717679c921456da681fc5f71aa9b37102d6f33b47", + "crates/horizon-world/src/worldgen/material_condition/codec.rs": "09b909bc384472f76d163c8069ec6b507c7d5c6a028a36d5e0e3df20deff7b3b", + "crates/horizon-world/src/worldgen/material_condition/density.rs": "df9d0761e978e5010663ae8b44f2d6c1ecb4907331e333bdb6a2b487c1e107de", + "crates/horizon-world/src/worldgen/material_condition/library.rs": "a55534c5da97575a819af5a7dc0dbec9069993fa8b2619c6c9d5576946e683fa", + "crates/horizon-world/src/worldgen/material_condition/noise.rs": "ffb59cc6be2275d7a5621bf7d768527e74a8326ed7ad78618746711540921675", + "crates/horizon-world/src/worldgen/material_condition/rule.rs": "fed643352efbcb1f68f29b6241896617db889fc7c577a6247564e01922fec1fe", + "crates/horizon-world/src/worldgen/material_condition.rs": "d638dcb8cbcb5da20b3cb29602b0ae6a86c4fdf9d8c0fb725de8ec5fc108717e", + "crates/horizon-world/src/worldgen/material_extensions.rs": "ab806eb679d5116e1aebb64fca70e1499ae71f83c9507a8cb4c3201c2b1bf037", + "crates/horizon-world/src/worldgen/material_stage.rs": "698cbc786eff13c246e2bc2ea062401918cd4265899fbc3d53abc87e45a8e7a1", + "crates/horizon-world/src/worldgen/material_surface.rs": "5d37b90099df3d6da0845dab164e71469fb287019c2ee74bc6714f3b9d6d6d5b", + "crates/horizon-world/src/worldgen/ore_feature.rs": "83b89fd3be691c5412c0215b6abefdcaa44119a05aa41217e061970eb7e12ebd", + "crates/horizon-world/src/worldgen/placement/chain.rs": "1b976aa4dd2516468196d0af3451e3fdd037493a14d269f54ebdd7254055e05e", + "crates/horizon-world/src/worldgen/placement/context.rs": "b36dfd9297896e62770f2085cf934fc08ebd4c030ecc7ae17d864e819a113201", + "crates/horizon-world/src/worldgen/placement/layer.rs": "a0f5ca776f33f9d4f72b8fdcd163426152e5e43cb4a7572fc1d4fc57bf965de1", + "crates/horizon-world/src/worldgen/placement.rs": "68ecf36954fea5705436d486e9be93836933fd56779022afeb881a0399d6a674", + "crates/horizon-world/src/worldgen/router.rs": "2cee7cf15a0d2ada12be6b39d83e78177fd3033922e4f4cce87a64073cec2847", + "crates/horizon-world/src/worldgen/rule_test.rs": "d1662ec492489ebaa4b87e20f9a8c809dcf3a223a151211bd65ec241a63692fc", + "crates/horizon-world/src/worldgen/settings.rs": "a8fe87752e1982ef11cb67f8d80d8e3428b2c27db178044cb425ba803e689e59", + "crates/horizon-world/src/worldgen/tags.rs": "d35ded93fe6e95ea045cadcf4925e656dc34ef832b742179b9ad0cc49f902f31", + "crates/horizon-world/src/worldgen/terrain.rs": "7fb7130111654563f7217f7b84563adde0b11c3ebd6a499a514dc98ebef7c733", + "crates/horizon-world/src/worldgen/value_provider.rs": "ad1c0efffcc201839e3471d7dfa06c39307d8cbabddb4c5aed8389ee7b68737a", + "crates/horizon-world/src/worldgen/weighted.rs": "839840aae25302933bbd97a81a2336330e2d03a0ad1684e1e16ac769ed408e6b", + "crates/horizon-world/src/worldgen.rs": "55c4317bd9c782378de7c2a7d58be5aa08febc5b8f2f4b86379a39e0ba500b3c", + "crates/horizon-world/examples/worldgen_random_fixture.rs": "9b1d7c9035245edd112b6ea93f49cefb9ae1a64d34ff75a16d66598d6b152664" + }, + "fixtures_sha256": { + ".local/rust-worldgen-random-parity/inputs.txt": "a2315c27a8afa09528edc6d1c71c3f429b395b2cdad648ee76f13029b367870d" + }, + "rust_output_sha256": "87634cb2d11a28031ef8b2ed0dc7c8afafad5dc1dca5a53a67f57f4727e11397", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "87634cb2d11a28031ef8b2ed0dc7c8afafad5dc1dca5a53a67f57f4727e11397", + "matched_output_lines": 238800 + }, + { + "side": "server", + "jar_sha256": "a362163eec5d1612d520772bc16e5b39c09e3b234fdc045f56bf544284ee8ae6", + "output_sha256": "87634cb2d11a28031ef8b2ed0dc7c8afafad5dc1dca5a53a67f57f4727e11397", + "matched_output_lines": 238800 + } + ], + "scope": "Actual WorldgenRandom bit sampling over legacy and xoroshiro sources, nested wrappers, signed bit-width shifts, draw counters, valid/invalid bounds, reseeding, fork and positional-factory delegation. Decoration, per-feature, large-feature, salt and slime-chunk seeds exercise signed int/long overflow, extreme coordinates and inherited legacy multi-draw behavior. Gaussian samples, concurrent access and full chunk decoration remain pending." +} diff --git a/crates/horizon-core/Cargo.toml b/crates/horizon-core/Cargo.toml new file mode 100644 index 000000000..65b2acc65 --- /dev/null +++ b/crates/horizon-core/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "horizon-core" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version.workspace = true +description = "Horizon simulation foundations for the pinned vanilla Java Edition target" + +[[bin]] +name = "horizon-parity" +path = "src/bin/parity.rs" + +[[bin]] +name = "horizon-tick-parity" +path = "src/bin/tick_parity.rs" + +[[bin]] +name = "horizon-geometry-parity" +path = "src/bin/geometry_parity.rs" + +[[bin]] +name = "horizon-noise-parity" +path = "src/bin/noise_parity.rs" + +[[bin]] +name = "horizon-density-parity" +path = "src/bin/density_parity.rs" + +[[bin]] +name = "horizon-float-log-parity" +path = "src/bin/float_log_parity.rs" diff --git a/crates/horizon-core/examples/biome_zoom_fixture.rs b/crates/horizon-core/examples/biome_zoom_fixture.rs new file mode 100644 index 000000000..4099bed13 --- /dev/null +++ b/crates/horizon-core/examples/biome_zoom_fixture.rs @@ -0,0 +1,46 @@ +//! Text transport for native BiomeManager comparisons. +use horizon_core::{ + biome::{BiomeZoom, noise_quart_at_block, noise_quart_at_position, obfuscate_seed}, + position::BlockPos, +}; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let mut values = line.split_whitespace(); + match values.next().unwrap() { + "s" => writeln!(out, "s {}", obfuscate_seed(values.next().unwrap().parse()?))?, + "b" => { + let seed: i64 = values.next().unwrap().parse()?; + let xyz: Vec = values.map(str::parse).collect::>()?; + let pos = BlockPos::new(xyz[0], xyz[1], xyz[2]); + let zoom = BiomeZoom::new(seed); + write!(out, "b")?; + for value in zoom + .quart_at_block(pos) + .into_iter() + .chain(noise_quart_at_block(pos)) + .chain(zoom.quart_at_block(pos)) + { + write!(out, " {value}")?; + } + writeln!(out)?; + } + "p" => { + let bits: Vec<_> = values + .map(|v| u64::from_str_radix(v, 16).map(f64::from_bits)) + .collect::>()?; + let xyz = noise_quart_at_position(bits.try_into().unwrap()); + writeln!(out, "p {} {} {}", xyz[0], xyz[1], xyz[2])?; + } + _ => panic!("unknown fixture operation"), + } + } + Ok(()) +} diff --git a/crates/horizon-core/src/bin/density_parity.rs b/crates/horizon-core/src/bin/density_parity.rs new file mode 100644 index 000000000..07bdf6537 --- /dev/null +++ b/crates/horizon-core/src/bin/density_parity.rs @@ -0,0 +1,1103 @@ +//! Original line transport for differential tests of density evaluation. +use horizon_core::density::graph::{ + DensityCompiler, DensityGraph, FunctionId, GraphBinary, GraphNode, GraphUnary, NoiseId, +}; +use horizon_core::{ + density::{ + BinaryOp, BinarySampler, BlendDensitySampler, BlendedNoise, CachingDensitySampler, + ConstantSampler, ContextBoundSampler, CubicSpline, DensitySampler, DensityValue, + DistanceMetric, DistanceToPointSampler, EmptyBlender, FindTopSurfaceSampler, + GradientSampler, InterpolatedSampler, Interval, IntervalError, IntervalSelectSampler, + LerpSampler, NoiseSampler, PowerSampler, RangeChoiceSampler, RoundMode, RoundSampler, + SamplerContext, ShiftNoiseKind, ShiftedNoiseSampler, SliceAxes, SliceSampler, SplinePoint, + SplineSampler, TilingMode, UnaryOp, UnarySampler, WorldField, WorldFields, + compile_shift_noise, compile_surface_search, create_blended_fbm, + }, + geometry::Axis, + noise::{ + DensityVolume, Noise, NormalNoise, Normalization, PerlinNoise, SimplexNoise, + SmearedPerlinNoise, + }, + random::{LegacyRandom, RandomSource, XoroshiroRandom}, +}; +use std::{ + io::{self, BufRead, BufWriter, Write}, + sync::Arc, +}; +#[derive(Debug)] +struct CountedSampler { + input: Arc, + calls: Arc<[std::sync::atomic::AtomicUsize; 2]>, +} +impl DensitySampler for CountedSampler { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + self.calls[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + self.input.sample_value(context, position) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), horizon_core::density::SampleError> { + self.calls[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + self.input.sample_volume(context, buffer, volume) + } +} +fn read( + args: &mut std::str::SplitWhitespace<'_>, +) -> Result> { + args.next() + .ok_or("missing argument")? + .parse() + .map_err(|_| "invalid argument".into()) +} +fn float(args: &mut std::str::SplitWhitespace<'_>) -> Result> { + Ok(f32::from_bits(u32::from_str_radix( + args.next().ok_or("missing float")?, + 16, + )?)) +} +fn double(args: &mut std::str::SplitWhitespace<'_>) -> Result> { + Ok(f64::from_bits(u64::from_str_radix( + args.next().ok_or("missing double")?, + 16, + )?)) +} +fn bits(v: f32) -> u32 { + if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() } +} +fn noise(kind: &str, mut random: impl RandomSource, scale: f64) -> Arc { + match kind { + "normal" => { + let mut definition = NormalNoise::builder(); + definition.set_base_octave(-7); + definition.set_octave_count(4).unwrap(); + Arc::new(definition.build().unwrap().create(&mut random).unwrap()) + } + "perlin" => Arc::new(PerlinNoise::new(&mut random)), + "simplex" => Arc::new(SimplexNoise::new(&mut random)), + "smeared" => Arc::new(SmearedPerlinNoise::new(&mut random, scale)), + _ => panic!("unknown noise kind"), + } +} +fn interval_output( + out: &mut impl Write, + name: &str, + result: Result, +) -> io::Result<()> { + match result { + Ok(range) => writeln!( + out, + "bounds {name} {} {} {} {}", + bits(range.min()), + bits(range.max()), + u8::from(range.is_nai()), + range.java_hash_code() + ), + Err(_) => writeln!(out, "bounds {name} error"), + } +} +fn blended_probe( + random: &mut impl RandomSource, + definition: BlendedNoise, + out: &mut impl Write, +) -> Result>, Box> { + interval_output(out, "blended", definition.range())?; + let result = definition.compile(random); + writeln!( + out, + "blended {} {}", + if result.is_ok() { "ok" } else { "error" }, + random.next_long() + )?; + Ok(result + .ok() + .map(|value| Arc::new(value) as Arc)) +} +fn fbm_probe( + random: &mut impl RandomSource, + octave: i32, + smear: f64, + amplitude: f64, + out: &mut impl Write, +) -> Result<(), Box> { + let result = create_blended_fbm(random, octave, smear, amplitude); + match result { + Ok(stack) => { + let range = stack.range()?; + writeln!( + out, + "fbm {} {} {}", + stack.layers().len(), + bits(range[0]), + bits(range[1]) + )?; + for layer in stack.layers() { + writeln!( + out, + "fbm-layer {} {} {}", + layer.frequency.to_bits(), + bits(layer.amplitude), + bits(layer.noise.get3(-17.25, 64.125, 32.5)) + )?; + } + for point in [ + [0.0; 3], + [-17.25, 64.125, 32.5], + [3e7, -64.0, -3e7], + [f64::INFINITY; 3], + ] { + writeln!( + out, + "fbm-query {} {}", + bits(stack.get2(point[0], point[2])), + bits(stack.get3(point[0], point[1], point[2])) + )?; + } + let volume = DensityVolume::new([2, 5, 2], [-17, -64, 32], [4, 1, 4])?; + let mut buffer = vec![0.0; volume.size() + 2]; + for (i, v) in buffer.iter_mut().enumerate() { + *v = (i as f32 - 10.0) * 0.125; + } + stack.add_to_volume(&mut buffer, volume, 0.125, 0.25, -0.5)?; + for value in buffer { + writeln!(out, "fbm-cell {}", bits(value))?; + } + } + Err(_) => writeln!(out, "fbm error")?, + } + writeln!(out, "fbm-parent {}", random.next_long())?; + Ok(()) +} +fn main() -> Result<(), Box> { + let mut samplers: Vec> = Vec::new(); + let mut graph_compiler = DensityCompiler::new(DensityGraph::new()); + let mut functions: Vec = Vec::new(); + let mut graph_splines: Vec> = Vec::new(); + let mut graph_noises: Vec = Vec::new(); + let mut noises = Vec::new(); + let mut splines: Vec = Vec::new(); + let mut counters: Vec> = Vec::new(); + let mut context = SamplerContext::default(); + let mut out = BufWriter::new(io::stdout().lock()); + for line in io::stdin().lock().lines() { + let line = line?; + let mut args = line.split_whitespace(); + match args.next().ok_or("empty command")? { + "constant" => { + samplers.push(Arc::new(ConstantSampler(float(&mut args)?))); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "gradient" => { + let axis = Axis::ALL[read::(&mut args)?]; + let tiling = [ + TilingMode::ClampToEdge, + TilingMode::Repeat, + TilingMode::MirroredRepeat, + ][read::(&mut args)?]; + let from = read(&mut args)?; + let to = read(&mut args)?; + let low = float(&mut args)?; + let high = float(&mut args)?; + samplers.push(Arc::new(GradientSampler::new( + axis, tiling, from, to, low, high, + ))); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "noise" => { + let kind = args.next().ok_or("missing noise kind")?; + let stream = args.next().ok_or("missing stream")?; + let seed = read(&mut args)?; + let scale = double(&mut args)?; + let source = if stream == "legacy" { + noise(kind, LegacyRandom::new(seed), scale) + } else { + noise(kind, XoroshiroRandom::new(seed), scale) + }; + let sampler = NoiseSampler { + noise: source, + xz_scale: double(&mut args)?, + y_scale: double(&mut args)?, + }; + noises.push(sampler.clone()); + samplers.push(Arc::new(sampler)); + writeln!(out, "noise {} {}", noises.len() - 1, samplers.len() - 1)?; + } + "shift" => { + let source = noises[read::(&mut args)?].clone(); + let x = read::(&mut args)?; + let y = read::(&mut args)?; + let z = read::(&mut args)?; + samplers.push(Arc::new(ShiftedNoiseSampler { + source, + shift_x: samplers[x].clone(), + shift_y: if y < 0 { + None + } else { + Some(samplers[y as usize].clone()) + }, + shift_z: samplers[z].clone(), + })); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "unary" => { + let kind = args.next().ok_or("missing unary kind")?; + let input = samplers[read::(&mut args)?].clone(); + let a = float(&mut args)?; + let b = float(&mut args)?; + let operation = match kind { + "abs" => UnaryOp::Abs, + "negate" => UnaryOp::Negate, + "square" => UnaryOp::Square, + "cube" => UnaryOp::Cube, + "sqrt" => UnaryOp::Sqrt, + "log" => UnaryOp::Log, + "reciprocal" => UnaryOp::Reciprocal, + "sign" => UnaryOp::Sign, + "squeeze" => UnaryOp::Squeeze, + "leaky" => UnaryOp::LeakyRelu(a), + "add" => UnaryOp::Add(a), + "sub" => UnaryOp::SubtractFrom(a), + "mul" => UnaryOp::Multiply(a), + "div" => UnaryOp::DivideInto(a), + "min" => UnaryOp::Minimum(a), + "max" => UnaryOp::Maximum(a), + "clamp" => UnaryOp::Clamp { min: a, max: b }, + _ => return Err("unknown unary kind".into()), + }; + samplers.push(Arc::new(UnarySampler { input, operation })); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "power" => { + let mode = read::(&mut args)?; + let sampler: Arc = match mode { + 0 => Arc::new(PowerSampler { + base: samplers[read::(&mut args)?].clone(), + exponent: samplers[read::(&mut args)?].clone(), + }), + 1 => { + let base = double(&mut args)?; + Arc::new(UnarySampler { + input: samplers[read::(&mut args)?].clone(), + operation: UnaryOp::PowerBase(base), + }) + } + 2 => { + let base = samplers[read::(&mut args)?].clone(); + Arc::new(UnarySampler { + input: base, + operation: UnaryOp::PowerExponent(double(&mut args)?), + }) + } + _ => return Err("unknown power mode".into()), + }; + samplers.push(sampler); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "round" => { + let mode = [ + RoundMode::Floor, + RoundMode::Round, + RoundMode::Ceil, + RoundMode::Truncate, + ][read::(&mut args)?]; + let input = samplers[read::(&mut args)?].clone(); + let multiple = read::(&mut args)?; + let multiple = if multiple < 0 { + None + } else { + Some(samplers[multiple as usize].clone()) + }; + samplers.push(Arc::new(RoundSampler { + mode, + input, + multiple, + })); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "binary" => { + let kind = args.next().ok_or("missing binary kind")?; + let left = samplers[read::(&mut args)?].clone(); + let right = samplers[read::(&mut args)?].clone(); + let bound = float(&mut args)?; + let operation = match kind { + "add" => BinaryOp::Add, + "sub" => BinaryOp::Subtract, + "mul" => BinaryOp::Multiply, + "div" => BinaryOp::Divide, + "min" => BinaryOp::Minimum { right_min: bound }, + "max" => BinaryOp::Maximum { right_max: bound }, + _ => return Err("unknown binary kind".into()), + }; + samplers.push(Arc::new(BinarySampler { + left, + right, + operation, + })); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "choice" => { + let mode = read::(&mut args)?; + let input = samplers[read::(&mut args)?].clone(); + let min_inclusive = float(&mut args)?; + let max_exclusive = float(&mut args)?; + let sampler: Arc = if mode == 1 { + let inside = float(&mut args)?; + let outside = float(&mut args)?; + Arc::new(UnarySampler { + input, + operation: UnaryOp::ConstantRangeChoice { + min_inclusive, + max_exclusive, + inside, + outside, + }, + }) + } else { + let when_in_range = samplers[read::(&mut args)?].clone(); + let when_out_of_range = samplers[read::(&mut args)?].clone(); + Arc::new(RangeChoiceSampler { + input, + min_inclusive, + max_exclusive, + when_in_range, + when_out_of_range, + }) + }; + samplers.push(sampler); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "lerp" => { + let mode = read::(&mut args)?; + let alpha = samplers[read::(&mut args)?].clone(); + let first = if mode == 1 { + DensityValue::Constant(float(&mut args)?) + } else { + DensityValue::Sampler(samplers[read::(&mut args)?].clone()) + }; + let second = if mode == 2 { + DensityValue::Constant(float(&mut args)?) + } else { + DensityValue::Sampler(samplers[read::(&mut args)?].clone()) + }; + samplers.push(Arc::new(LerpSampler { + alpha, + first, + second, + })); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "interval" => { + let _specialization = read::(&mut args)?; + let input = samplers[read::(&mut args)?].clone(); + let count = read::(&mut args)?; + let thresholds = (0..count) + .map(|_| float(&mut args)) + .collect::, _>>()?; + let branches = (0..=count) + .map(|_| read::(&mut args).map(|id| samplers[id].clone())) + .collect::, _>>()?; + samplers.push(Arc::new(IntervalSelectSampler::new( + input, thresholds, branches, + )?)); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "bounds" => { + let mode = read::(&mut args)?; + let a = float(&mut args)?; + let b = float(&mut args)?; + let c = float(&mut args)?; + let d = float(&mut args)?; + let e = float(&mut args)?; + let f = float(&mut args)?; + let result = match mode { + 0 => Interval::new(a, b), + 1 => Interval::symmetric(a), + 2 => Interval::exact(a), + 3 => Ok(Interval::encapsulating_values(a, b)), + 4 => Ok(Interval::NAI), + 5 => Ok(Interval::INFINITE), + _ => return Err("unknown interval constructor".into()), + }; + interval_output(&mut out, "create", result)?; + if let Ok(left) = result { + let right = Interval::encapsulating_values(c, d); + let third = Interval::encapsulating_values(e, f); + interval_output(&mut out, "right", Ok(right))?; + for (name, value) in [ + ("add", left.add_range(right)), + ("sub", left.subtract_range(right)), + ("mul", left.multiply_range(right)), + ("div", left.divide_range(right)), + ("min", left.minimum(right)), + ("max", left.maximum(right)), + ("reciprocal", left.reciprocal()), + ("abs", left.abs()), + ("square", left.square()), + ("sign", left.sign()), + ("power", left.power(right)), + ] { + interval_output(&mut out, name, Ok(value))?; + } + interval_output(&mut out, "clamp", left.clamp(c, d))?; + interval_output(&mut out, "log", left.log())?; + interval_output(&mut out, "lerp-values", Ok(left.lerp_values(c, d)))?; + interval_output(&mut out, "lerp-ranges", Ok(left.lerp_ranges(right, third)))?; + interval_output(&mut out, "map-negate", left.map_monotonic(|v| -v))?; + interval_output(&mut out, "map-cube", left.map_monotonic(|v| v * v * v))?; + interval_output( + &mut out, + "map-sqrt", + left.map_monotonic(|v| (v as f64).sqrt() as f32), + )?; + interval_output(&mut out, "map-reciprocal", left.map_monotonic(|v| 1.0 / v))?; + interval_output( + &mut out, + "hull", + Interval::encapsulating(&[left, right, third]), + )?; + interval_output(&mut out, "empty", Interval::encapsulating(&[]))?; + writeln!( + out, + "bounds query {} {} {} {}", + u8::from(left.contains(e)), + u8::from(left.intersects(right)), + u8::from(left == right), + u8::from(left == result.unwrap()) + )?; + } + } + "offset" => { + let kind = [ + ShiftNoiseKind::Shift, + ShiftNoiseKind::ShiftA, + ShiftNoiseKind::ShiftB, + ][read::(&mut args)?]; + let noise = noises[read::(&mut args)?].noise.clone(); + samplers.push(compile_shift_noise(noise, kind)); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "blended" | "blendfail" => { + let stream = args.next().ok_or("missing stream")?; + let seed = read(&mut args)?; + let definition = BlendedNoise { + xz_scale: double(&mut args)?, + y_scale: double(&mut args)?, + xz_factor: double(&mut args)?, + y_factor: double(&mut args)?, + smear_scale_multiplier: double(&mut args)?, + }; + let result = if stream == "legacy" { + blended_probe(&mut LegacyRandom::new(seed), definition, &mut out)? + } else { + blended_probe(&mut XoroshiroRandom::new(seed), definition, &mut out)? + }; + if let Some(sampler) = result { + samplers.push(sampler); + writeln!(out, "create {}", samplers.len() - 1)?; + } + } + "blendfbm" => { + let stream = args.next().ok_or("missing stream")?; + let seed = read(&mut args)?; + let octave = read(&mut args)?; + let smear = double(&mut args)?; + let amplitude = double(&mut args)?; + if stream == "legacy" { + fbm_probe( + &mut LegacyRandom::new(seed), + octave, + smear, + amplitude, + &mut out, + )?; + } else { + fbm_probe( + &mut XoroshiroRandom::new(seed), + octave, + smear, + amplitude, + &mut out, + )?; + } + } + "distance" => { + let metric = [ + DistanceMetric::Euclidean, + DistanceMetric::EuclideanSquared, + DistanceMetric::Manhattan, + DistanceMetric::Chebyshev, + ][read::(&mut args)?]; + let point = [read(&mut args)?, read(&mut args)?, read(&mut args)?]; + samplers.push(Arc::new(DistanceToPointSampler { point, metric })); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "metric" => { + let x = float(&mut args)?; + let y = float(&mut args)?; + let z = float(&mut args)?; + for metric in [ + DistanceMetric::Euclidean, + DistanceMetric::EuclideanSquared, + DistanceMetric::Manhattan, + DistanceMetric::Chebyshev, + ] { + writeln!( + out, + "metric {} {}", + bits(metric.compute2(x, y)), + bits(metric.compute3(x, y, z)) + )?; + } + } + "wcontext" => { + let cached = read::(&mut args)? != 0; + let mut fields = WorldFields::default(); + for field in [ + WorldField::BlendAlpha, + WorldField::BlendOffset, + WorldField::Beardifier, + ] { + let binding = read::(&mut args)?; + if binding >= 0 { + fields = fields.with_field(field, samplers[binding as usize].clone()); + } + } + if read::(&mut args)? != 0 { + fields = fields.with_blender(Arc::new(EmptyBlender)); + } + context = (if cached { + SamplerContext::cached() + } else { + SamplerContext::default() + }) + .with_world_fields(fields); + writeln!(out, "context")?; + } + "wfield" => { + let field = [ + WorldField::BlendAlpha, + WorldField::BlendOffset, + WorldField::Beardifier, + ][read::(&mut args)?]; + let fallback = read::(&mut args)?; + samplers.push(Arc::new(if fallback < 0 { + ContextBoundSampler::new(field) + } else { + ContextBoundSampler::with_fallback(field, samplers[fallback as usize].clone()) + })); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "blenddensity" => { + let input = samplers[read::(&mut args)?].clone(); + samplers.push(Arc::new(BlendDensitySampler { input })); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "context" => { + context = if read::(&mut args)? == 0 { + SamplerContext::default() + } else { + SamplerContext::cached() + }; + writeln!(out, "context")?; + } + "counted" => { + let input = samplers[read::(&mut args)?].clone(); + let calls = Arc::new(std::array::from_fn(|_| { + std::sync::atomic::AtomicUsize::new(0) + })); + counters.push(calls.clone()); + samplers.push(Arc::new(CountedSampler { input, calls })); + writeln!(out, "counted {} {}", counters.len() - 1, samplers.len() - 1)?; + } + "counts" => { + let calls = &counters[read::(&mut args)?]; + writeln!( + out, + "counts {} {}", + calls[0].load(std::sync::atomic::Ordering::Relaxed), + calls[1].load(std::sync::atomic::Ordering::Relaxed) + )?; + } + "greset" => { + graph_compiler = DensityCompiler::new(DensityGraph::new()); + functions.clear(); + graph_splines.clear(); + graph_noises.clear(); + context = SamplerContext::default(); + writeln!(out, "graph-reset")?; + } + "gseed" => { + let seed = read::(&mut args)?; + let legacy = read::(&mut args)? != 0; + graph_compiler = DensityCompiler::new_seeded(DensityGraph::new(), seed, legacy); + functions.clear(); + graph_splines.clear(); + graph_noises.clear(); + context = SamplerContext::default(); + writeln!(out, "graph-seed")?; + } + "gready" => writeln!(out, "graph-ready")?, + "gend" => { + functions.push(graph_compiler.graph_mut().insert(GraphNode::EndIslands)?); + writeln!(out, "graph-create {}", functions.len() - 1)?; + } + "gregister" => { + let name = args.next().ok_or("missing noise identifier")?.to_owned(); + let mut builder = NormalNoise::builder(); + builder + .set_base_octave(read(&mut args)?) + .set_base_amplitude(double(&mut args)?); + builder.set_octave_count(read(&mut args)?)?; + builder.set_normalization( + [ + Normalization::Disabled, + Normalization::Enabled, + Normalization::Legacy, + ][read::(&mut args)?], + ); + let modifiers = read::(&mut args)?; + for index in 0..modifiers { + builder.set_amplitude_modifier(index as i32, double(&mut args)?)?; + } + graph_noises.push( + graph_compiler + .graph_mut() + .register_noise(name, builder.build()?)?, + ); + writeln!(out, "graph-noise {}", graph_noises.len() - 1)?; + } + "ginstance" => { + let id = graph_noises[read::(&mut args)?]; + let a = graph_compiler.get_noise_sampler(id)?; + let b = graph_compiler.get_noise_sampler(id)?; + writeln!(out, "graph-instance {}", u8::from(Arc::ptr_eq(&a, &b)))?; + } + "gbind" => { + let sampler = samplers[read::(&mut args)?].clone(); + let range = Interval::encapsulating_values(float(&mut args)?, float(&mut args)?); + let axes = read(&mut args)?; + functions.push(graph_compiler.graph_mut().bind(sampler, range, axes)?); + writeln!(out, "graph-create {}", functions.len() - 1)?; + } + "gsconstant" => { + graph_splines.push(CubicSpline::Constant(float(&mut args)?)); + writeln!(out, "graph-spline {}", graph_splines.len() - 1)?; + } + "gspoints" => { + let coordinate = functions[read::(&mut args)?]; + let count = read::(&mut args)?; + let mut points = Vec::with_capacity(count); + for _ in 0..count { + let location = float(&mut args)?; + let derivative = float(&mut args)?; + let value = graph_splines[read::(&mut args)?].clone(); + points.push(SplinePoint { + location, + derivative, + value, + }); + } + graph_splines.push(CubicSpline::multipoint(coordinate, points)?); + writeln!(out, "graph-spline {}", graph_splines.len() - 1)?; + } + "gref" => { + let input = functions[read::(&mut args)?]; + functions.push(graph_compiler.graph_mut().insert(GraphNode::Reference { + input, + holder: None, + })?); + writeln!(out, "graph-create {}", functions.len() - 1)?; + } + "gnamed" => { + let name = read::(&mut args)?; + let input = functions[read::(&mut args)?]; + functions.push(graph_compiler.graph_mut().register_function(name, input)?); + writeln!(out, "graph-create {}", functions.len() - 1)?; + } + "glookup" => { + let name = read::(&mut args)?; + functions.push( + graph_compiler + .graph() + .function(&name) + .ok_or("unknown density name")?, + ); + writeln!(out, "graph-create {}", functions.len() - 1)?; + } + "gspline" => { + let spline = graph_splines[read::(&mut args)?].clone(); + functions.push( + graph_compiler + .graph_mut() + .insert(GraphNode::Spline(spline))?, + ); + writeln!(out, "graph-create {}", functions.len() - 1)?; + } + command @ ("gconst" | "ggradient" | "gunary" | "gbinary" | "gclamp" | "gchoice" + | "glerp" | "gslice" | "gcache" | "ginterp" | "gsurface" | "ginterval" + | "gdistance" | "gnoise" | "goffset" | "gblended" | "ground" | "gpow" + | "gwfield" | "gblenddensity") => { + let reference = |args: &mut std::str::SplitWhitespace<'_>| -> Result> { Ok(functions[read::(args)?]) }; + let node = match command { + "gconst" => GraphNode::Constant(float(&mut args)?), + "gwfield" => GraphNode::WorldField( + [ + WorldField::BlendAlpha, + WorldField::BlendOffset, + WorldField::Beardifier, + ][read::(&mut args)?], + ), + "gblenddensity" => GraphNode::BlendDensity(reference(&mut args)?), + "gpow" => GraphNode::Power { + base: reference(&mut args)?, + exponent: reference(&mut args)?, + }, + "ground" => GraphNode::Round { + mode: [ + RoundMode::Floor, + RoundMode::Round, + RoundMode::Ceil, + RoundMode::Truncate, + ][read::(&mut args)?], + input: reference(&mut args)?, + multiple: reference(&mut args)?, + }, + "gnoise" => GraphNode::Noise { + noise: graph_noises[read::(&mut args)?], + xz_scale: double(&mut args)?, + y_scale: double(&mut args)?, + shift_x: reference(&mut args)?, + shift_y: reference(&mut args)?, + shift_z: reference(&mut args)?, + }, + "goffset" => GraphNode::OffsetNoise { + noise: graph_noises[read::(&mut args)?], + kind: [ + ShiftNoiseKind::Shift, + ShiftNoiseKind::ShiftA, + ShiftNoiseKind::ShiftB, + ][read::(&mut args)?], + }, + "gblended" => GraphNode::BlendedNoise(BlendedNoise { + xz_scale: double(&mut args)?, + y_scale: double(&mut args)?, + xz_factor: double(&mut args)?, + y_factor: double(&mut args)?, + smear_scale_multiplier: double(&mut args)?, + }), + "gdistance" => GraphNode::DistanceToPoint { + point: [read(&mut args)?, read(&mut args)?, read(&mut args)?], + metric: [ + DistanceMetric::Euclidean, + DistanceMetric::EuclideanSquared, + DistanceMetric::Manhattan, + DistanceMetric::Chebyshev, + ][read::(&mut args)?], + }, + "ginterval" => { + let input = reference(&mut args)?; + let count: usize = read(&mut args)?; + let thresholds = (0..count) + .map(|_| float(&mut args)) + .collect::, _>>()?; + let branches = + (0..=count) + .map(|_| reference(&mut args)) + .collect::, _>>()?; + GraphNode::IntervalSelect { + input, + thresholds: thresholds.into(), + branches, + } + } + "ggradient" => { + let axis = [Axis::X, Axis::Y, Axis::Z][read::(&mut args)?]; + let tiling = [ + TilingMode::ClampToEdge, + TilingMode::Repeat, + TilingMode::MirroredRepeat, + ][read::(&mut args)?]; + GraphNode::Gradient { + axis, + tiling, + from: read(&mut args)?, + to: read(&mut args)?, + low: float(&mut args)?, + high: float(&mut args)?, + } + } + "gunary" => { + let kind = [ + GraphUnary::Abs, + GraphUnary::Square, + GraphUnary::Cube, + GraphUnary::HalfNegative, + GraphUnary::QuarterNegative, + GraphUnary::Reciprocal, + GraphUnary::Negate, + GraphUnary::Squeeze, + GraphUnary::Sign, + GraphUnary::Log, + GraphUnary::Sqrt, + ][read::(&mut args)?]; + GraphNode::Unary { + kind, + input: reference(&mut args)?, + } + } + "gbinary" => { + let kind = [ + GraphBinary::Add, + GraphBinary::Subtract, + GraphBinary::Multiply, + GraphBinary::Divide, + GraphBinary::Minimum, + GraphBinary::Maximum, + ][read::(&mut args)?]; + GraphNode::Binary { + kind, + left: reference(&mut args)?, + right: reference(&mut args)?, + } + } + "gclamp" => GraphNode::Clamp { + input: reference(&mut args)?, + min: float(&mut args)?, + max: float(&mut args)?, + }, + "gchoice" => GraphNode::Choice { + input: reference(&mut args)?, + min: float(&mut args)?, + max: float(&mut args)?, + inside: reference(&mut args)?, + outside: reference(&mut args)?, + }, + "glerp" => GraphNode::Lerp { + alpha: reference(&mut args)?, + first: reference(&mut args)?, + second: reference(&mut args)?, + }, + "gslice" => GraphNode::Slice { + axis: [Axis::X, Axis::Y, Axis::Z][read::(&mut args)?], + coordinate: read(&mut args)?, + input: reference(&mut args)?, + }, + "gcache" => GraphNode::Cache(reference(&mut args)?), + "ginterp" => GraphNode::Interpolated { + input: reference(&mut args)?, + xz: read(&mut args)?, + y: read(&mut args)?, + }, + "gsurface" => GraphNode::Surface { + density: reference(&mut args)?, + upper: reference(&mut args)?, + lower: read(&mut args)?, + height: read(&mut args)?, + }, + _ => unreachable!(), + }; + functions.push(graph_compiler.graph_mut().insert(node)?); + writeln!(out, "graph-create {}", functions.len() - 1)?; + } + "ginfo" => { + let id = functions[read::(&mut args)?]; + let range = graph_compiler + .graph() + .range(id) + .map_err(|_| IntervalError::NanBound); + interval_output(&mut out, "graph", range)?; + writeln!( + out, + "graph-axes {}", + graph_compiler.graph().domain_axes(id)? + )?; + } + "gsame" => { + let a = functions[read::(&mut args)?]; + let b = functions[read::(&mut args)?]; + writeln!( + out, + "graph-same {}", + u8::from(graph_compiler.graph().java_equals(a, b)?) + )?; + } + command @ ("gcompile" | "gtry") => { + let mode = read::(&mut args)?; + let id = functions[read::(&mut args)?]; + let result = if mode == 0 { + graph_compiler.compile_raw(id) + } else { + graph_compiler.get_sampler(id) + }; + if command == "gtry" { + writeln!( + out, + "graph-try {} {}", + if result.is_ok() { "ok" } else { "error" }, + graph_compiler.cache_count() + )?; + } else { + let sampler = result?; + let same = if mode == 0 { + -1 + } else { + i32::from(Arc::ptr_eq(&sampler, &graph_compiler.get_sampler(id)?)) + }; + samplers.push(sampler); + writeln!( + out, + "graph-compile {} {} {}", + samplers.len() - 1, + graph_compiler.cache_count(), + same + )?; + } + } + "spconstant" => { + splines.push(CubicSpline::Constant(float(&mut args)?)); + writeln!(out, "spline {}", splines.len() - 1)?; + } + "sppoints" => { + let coordinate = read(&mut args)?; + let count = read::(&mut args)?; + let mut points = Vec::new(); + for _ in 0..count { + let location = float(&mut args)?; + let derivative = float(&mut args)?; + let value = splines[read::(&mut args)?].clone(); + points.push(SplinePoint { + location, + derivative, + value, + }); + } + splines.push(CubicSpline::multipoint(coordinate, points)?); + writeln!(out, "spline {}", splines.len() - 1)?; + } + "spfail" => { + let spline = &splines[read::(&mut args)?]; + writeln!( + out, + "spline-compile {}", + if SplineSampler::new(spline, &samplers).is_err() { + "error" + } else { + "ok" + } + )?; + } + "sprange" => { + let spline = &splines[read::(&mut args)?]; + let mut ranges = [Interval::NAI; 3]; + for range in &mut ranges { + *range = Interval::encapsulating_values(float(&mut args)?, float(&mut args)?); + } + interval_output(&mut out, "spline", spline.range(&mut |id| ranges[id % 3]))?; + } + "spsampler" => { + let spline = &splines[read::(&mut args)?]; + samplers.push(Arc::new(SplineSampler::new(spline, &samplers)?)); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "surface" => { + let mode = read::(&mut args)?; + let density = samplers[read::(&mut args)?].clone(); + let upper = samplers[read::(&mut args)?].clone(); + let lower = read(&mut args)?; + let height = read(&mut args)?; + let sampler: Arc = if mode == 0 { + Arc::new(FindTopSurfaceSampler::new(density, upper, lower, height)?) + } else { + Arc::new(compile_surface_search(density, upper, lower, height)?) + }; + samplers.push(sampler); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "interpolate" => { + let input = samplers[read::(&mut args)?].clone(); + let xz = read(&mut args)?; + let y = read(&mut args)?; + samplers.push(Arc::new(InterpolatedSampler::new(input, xz, y)?)); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "slice" => { + let mode = read::(&mut args)?; + let input = samplers[read::(&mut args)?].clone(); + let a = read(&mut args)?; + let b = read(&mut args)?; + let axes = match mode { + 0 => SliceAxes::X(a), + 1 => SliceAxes::Y(a), + 2 => SliceAxes::Z(a), + 3 => SliceAxes::Xz { x: a, z: b }, + _ => return Err("invalid slice mode".into()), + }; + samplers.push(Arc::new(SliceSampler { input, axes })); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "cache" => { + let id = read::(&mut args)?; + let input = samplers[read::(&mut args)?].clone(); + samplers.push(Arc::new(CachingDensitySampler::new(id, input)?)); + writeln!(out, "create {}", samplers.len() - 1)?; + } + "lookup" => { + let sizes = [read(&mut args)?, read(&mut args)?, read(&mut args)?]; + let minimum = [read(&mut args)?, read(&mut args)?, read(&mut args)?]; + let steps = [read(&mut args)?, read(&mut args)?, read(&mut args)?]; + let position = [read(&mut args)?, read(&mut args)?, read(&mut args)?]; + let volume = DensityVolume::new(sizes, minimum, steps)?; + writeln!( + out, + "lookup {}", + volume.index_of_block(position).map_or(-1, |v| v as i32) + )?; + } + "query" => { + let sampler = &samplers[read::(&mut args)?]; + let position = [read(&mut args)?, read(&mut args)?, read(&mut args)?]; + match sampler.sample_value(&mut context, position) { + Ok(value) => writeln!(out, "query {}", bits(value))?, + Err(_) => writeln!(out, "query error")?, + } + } + "volume" => { + let sampler = &samplers[read::(&mut args)?]; + let sizes = [read(&mut args)?, read(&mut args)?, read(&mut args)?]; + let minimum = [read(&mut args)?, read(&mut args)?, read(&mut args)?]; + let steps = [read(&mut args)?, read(&mut args)?, read(&mut args)?]; + let tail = read::(&mut args)?; + let seed = read(&mut args)?; + let repeats = read::(&mut args)?; + let volume = DensityVolume::new(sizes, minimum, steps)?; + let mut random = LegacyRandom::new(seed); + let mut buffer: Vec<_> = (0..volume.size() + tail) + .map(|_| f32::from_bits(random.next_int() as u32)) + .collect(); + for pass in 0..repeats { + let result = sampler.sample_volume(&mut context, &mut buffer, volume); + writeln!( + out, + "volume {pass} {}", + if result.is_ok() { "ok" } else { "error" } + )?; + for (i, value) in buffer.iter().enumerate() { + writeln!(out, "cell {i} {}", bits(*value))?; + } + } + } + _ => return Err("unknown command".into()), + } + if args.next().is_some() { + return Err("extra argument".into()); + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-core/src/bin/float_log_parity.rs b/crates/horizon-core/src/bin/float_log_parity.rs new file mode 100644 index 000000000..570a7c666 --- /dev/null +++ b/crates/horizon-core/src/bin/float_log_parity.rs @@ -0,0 +1,55 @@ +//! Binary transport for exhaustive comparison of the compiled float log sampler. +use horizon_core::density::{DensitySampler, SampleError, SamplerContext, UnaryOp, UnarySampler}; +use std::{ + io::{self, Write}, + sync::Arc, +}; + +#[derive(Debug)] +struct FloatBitsInput; +impl DensitySampler for FloatBitsInput { + fn sample_value(&self, _: &mut SamplerContext, position: [i32; 3]) -> Result { + Ok(f32::from_bits(position[0] as u32)) + } +} + +fn main() -> Result<(), Box> { + let mut args = std::env::args().skip(1); + let mut start = args + .next() + .ok_or("missing first float bits")? + .parse::()?; + let mut remaining = args.next().ok_or("missing float count")?.parse::()?; + if args.next().is_some() + || start + .checked_add(remaining) + .is_none_or(|end| end > 1_u64 << 32) + { + return Err("invalid float bit range".into()); + } + let sampler = UnarySampler { + input: Arc::new(FloatBitsInput), + operation: UnaryOp::Log, + }; + let mut context = SamplerContext::default(); + let mut out = io::BufWriter::with_capacity(1 << 20, io::stdout().lock()); + let mut buffer = vec![0_u8; 1 << 20]; + while remaining > 0 { + let entries = remaining.min((buffer.len() / 4) as u64) as usize; + for (offset, bytes) in buffer[..entries * 4].chunks_exact_mut(4).enumerate() { + let bits = (start + offset as u64) as u32; + let value = sampler.sample_value(&mut context, [bits as i32, 0, 0])?; + let result = if value.is_nan() { + 0x7fc0_0000 + } else { + value.to_bits() + }; + bytes.copy_from_slice(&result.to_be_bytes()); + } + out.write_all(&buffer[..entries * 4])?; + start += entries as u64; + remaining -= entries as u64; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-core/src/bin/geometry_parity.rs b/crates/horizon-core/src/bin/geometry_parity.rs new file mode 100644 index 000000000..a51f51887 --- /dev/null +++ b/crates/horizon-core/src/bin/geometry_parity.rs @@ -0,0 +1,564 @@ +//! Text adapter for differential checks; no vanilla logic lives in the adapter. +use horizon_core::geometry::{ + Aabb, Axis, BlockHit, Direction, Vec3, VoxelShape, block_floor_height, candidate_step_heights, + entity_collision_bounds, resolve_shape_movement, resolve_step_movement, + sweep_intersected_blocks, +}; +use horizon_core::position::BlockPos; +use std::io::{self, BufRead, Write}; + +struct Input<'a>(std::str::SplitWhitespace<'a>); +impl Input<'_> { + fn word(&mut self) -> &str { + self.0.next().expect("missing input") + } + fn integer(&mut self) -> i32 { + self.word().parse().expect("integer") + } + fn number(&mut self) -> f64 { + f64::from_bits(u64::from_str_radix(self.word(), 16).expect("double bits")) + } + fn vector(&mut self) -> Vec3 { + Vec3::new(self.number(), self.number(), self.number()) + } + fn aabb(&mut self) -> Aabb { + Aabb::new(self.vector(), self.vector()) + } + fn pos(&mut self) -> BlockPos { + BlockPos::new(self.integer(), self.integer(), self.integer()) + } +} +fn bits(value: f64) -> String { + format!( + "{:016x}", + if value.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + value.to_bits() + } + ) +} +fn positions( + out: &mut impl Write, + label: &str, + iter: impl Iterator, + limit: usize, +) -> io::Result<()> { + let mut count = 0; + for pos in iter.take(limit) { + writeln!(out, "{label} {} {} {}", pos.x, pos.y, pos.z)?; + count += 1; + } + writeln!(out, "{label}-count {count}") +} +fn values( + out: &mut impl Write, + label: &str, + values: impl IntoIterator, +) -> io::Result<()> { + write!(out, "{label}")?; + for value in values { + write!(out, " {}", bits(value))?; + } + writeln!(out) +} +fn vector(out: &mut impl Write, label: &str, v: Vec3) -> io::Result<()> { + values(out, label, v.components()) +} +fn aabb(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { + values( + out, + label, + b.min_position() + .components() + .into_iter() + .chain(b.max_position().components()), + ) +} +fn point(out: &mut impl Write, label: &str, p: Option) -> io::Result<()> { + match p { + Some(v) => vector(out, label, v), + None => writeln!(out, "{label} none"), + } +} +fn hit(out: &mut impl Write, h: Option) -> io::Result<()> { + match h { + Some(h) => { + write!( + out, + "hit {} {} {} {} {}", + h.direction as u8, + u8::from(h.inside), + h.block.x, + h.block.y, + h.block.z + )?; + for c in h.location.components() { + write!(out, " {}", bits(c))?; + } + writeln!(out) + } + None => writeln!(out, "hit none"), + } +} +fn shape_values(out: &mut impl Write, id: usize, shape: &VoxelShape) -> io::Result<()> { + values( + out, + "axis-extrema", + Axis::ALL + .map(|axis| shape.min(axis)) + .into_iter() + .chain(Axis::ALL.map(|axis| shape.max(axis))), + )?; + writeln!(out, "shape {id} {}", shape.boxes().len())?; + let flags = shape.cube_coordinate_axes(); + writeln!( + out, + "cube {} {}", + u8::from(shape.is_cube()), + u8::from(flags[0]) + 2 * u8::from(flags[1]) + 4 * u8::from(flags[2]) + )?; + for (axis, label) in Axis::ALL + .into_iter() + .zip(["x-coords", "y-coords", "z-coords"]) + { + values(out, label, shape.coordinates(axis).iter().copied())?; + } + if let Some(b) = shape.bounds() { + aabb(out, "shape-bounds", b)?; + } else { + writeln!(out, "shape-bounds none")?; + } + for b in shape.boxes() { + aabb(out, "part", *b)?; + } + Ok(()) +} +fn main() -> io::Result<()> { + let mut out = io::BufWriter::new(io::stdout().lock()); + let mut shapes = Vec::::new(); + for (line_number, line) in io::stdin().lock().lines().enumerate() { + let line = line?; + let mut input = Input(line.split_whitespace()); + let operation = input.word().to_owned(); + writeln!(out, "command {} {operation}", line_number + 1)?; + match operation.as_str() { + "make-box" => { + let shape = VoxelShape::from_box(input.aabb()).expect("valid box"); + shape_values(&mut out, shapes.len(), &shape)?; + shapes.push(shape); + } + "optimize" => { + let shape = shapes[input.integer() as usize] + .optimized() + .expect("bounded optimization"); + shape_values(&mut out, shapes.len(), &shape)?; + shapes.push(shape); + } + "join" | "join-optimized" => { + let optimized = operation == "join-optimized"; + let a = input.integer() as usize; + let b = input.integer() as usize; + let operation = + horizon_core::geometry::ShapeOp::from_truth_table(input.integer() as u8); + let result = if optimized { + shapes[a].join(&shapes[b], operation) + } else { + shapes[a].join_unoptimized(&shapes[b], operation) + }; + match result { + Err(horizon_core::geometry::ShapeError::UnboundedBoolean) => { + writeln!(out, "join invalid")? + } + Err(error) => panic!("join failed: {error}"), + Ok(shape) => { + writeln!( + out, + "overlap {}", + u8::from( + shapes[a] + .join_is_not_empty(&shapes[b], operation) + .expect("bounded Boolean") + ) + )?; + shape_values(&mut out, shapes.len(), &shape)?; + shapes.push(shape); + } + } + } + "traverse" => { + let start = input.vector(); + let end = input.vector(); + let stop = input.integer(); + let mut count = 0; + let result = horizon_core::geometry::traverse_blocks(start, end, 10000, |pos| { + count += 1; + writeln!(out, "visit {} {} {}", pos.x, pos.y, pos.z).expect("write visit"); + (count == stop).then_some(pos) + }) + .expect("finite bounded corpus"); + match result { + Some(pos) => writeln!(out, "traverse {} {} {} {count}", pos.x, pos.y, pos.z)?, + None => writeln!(out, "traverse none {count}")?, + } + } + "trig-table" => { + for (i, value) in horizon_core::geometry::trig::sine_table() + .iter() + .enumerate() + { + writeln!(out, "sine {i} {:08x}", value.to_bits())?; + } + } + "rotation" => { + let v = input.vector(); + let angle = input.number(); + let pitch = input.number() as f32; + let yaw = input.number() as f32; + let axes = input.integer(); + let axis = Axis::ALL[input.integer() as usize]; + let direction = Direction::ALL[input.integer() as usize]; + let amount = input.number(); + values( + &mut out, + "trig", + [ + horizon_core::geometry::trig::sin(angle) as f64, + horizon_core::geometry::trig::cos(angle) as f64, + ], + )?; + vector(&mut out, "rotate-x", v.rotate_x(angle as f32))?; + vector(&mut out, "rotate-y", v.rotate_y(angle as f32))?; + vector(&mut out, "rotate-z", v.rotate_z(angle as f32))?; + vector(&mut out, "clockwise", v.rotate_clockwise_90())?; + vector(&mut out, "look", Vec3::direction_from_rotation(pitch, yaw))?; + values(&mut out, "rotation", v.rotation().map(|v| v as f64))?; + vector( + &mut out, + "align", + v.align([axes & 1 != 0, axes & 2 != 0, axes & 4 != 0]), + )?; + vector(&mut out, "with", v.with_component(axis, amount))?; + vector(&mut out, "relative", v.relative(direction, amount))?; + } + "vec" => { + let a = input.vector(); + let b = input.vector(); + let t = input.number(); + for (label, v) in [ + ("add", a.add_vector(b)), + ("subtract", a.subtract(b)), + ("vector-to", a.vector_to(b)), + ("multiply", a.multiply(b)), + ("scale", a.scale(t)), + ("normalize", a.normalize()), + ("cross", a.cross(b)), + ("lerp", a.lerp(b, t)), + ("projected", a.projected_on(b)), + ("reverse", a.reverse()), + ("horizontal", a.horizontal()), + ] { + vector(&mut out, label, v)?; + } + values( + &mut out, + "scalar", + [ + a.dot(b), + a.length_squared(), + a.length(), + a.horizontal_distance_squared(), + a.horizontal_distance(), + a.distance_squared(b), + a.distance(b), + ], + )?; + writeln!( + out, + "flags {} {} {} {}", + u8::from(a == b), + u8::from(a.is_finite()), + u8::from(a.closer_than(b, t)), + Direction::approximate_nearest(a) as u8 + )?; + let order = Axis::step_order(a); + writeln!( + out, + "order {} {} {}", + order[0] as u8, order[1] as u8, order[2] as u8 + )?; + } + "box" => { + let a = input.aabb(); + let b = input.aabb(); + let start = input.vector(); + let end = input.vector(); + let amount = input.vector(); + let axis = Axis::ALL[input.integer() as usize]; + let value = input.number(); + for (label, b) in [ + ("bounds", a), + ("move", a.move_by(amount)), + ("inflate", a.inflate(amount)), + ("deflate", a.deflate(amount)), + ("contract", a.contract(amount)), + ("expand", a.expand_towards(amount)), + ("intersect", a.intersect(b)), + ("union", a.union_bounds(b)), + ("next", a.next_deflated()), + ("set-min", a.with_min(axis, value)), + ("set-max", a.with_max(axis, value)), + ("of-size", Aabb::of_size(start, amount)), + ("unit", Aabb::unit_cube(start)), + ] { + aabb(&mut out, label, b)?; + } + vector(&mut out, "center", a.center())?; + vector(&mut out, "bottom", a.bottom_center())?; + vector(&mut out, "size", a.size())?; + values( + &mut out, + "distance", + [ + a.average_size(), + a.distance_squared_to_point(start), + a.distance_squared_to_box(b), + ], + )?; + writeln!( + out, + "flags {} {} {} {}", + u8::from(a.intersects(b)), + u8::from(a.contains(start)), + u8::from(a.has_nan()), + u8::from(a.collided_along_vector(amount, &[b])) + )?; + point(&mut out, "clip", a.clip(start, end))?; + hit( + &mut out, + Aabb::clip_boxes([a, b], start, end, BlockPos::default()), + )?; + } + "block-box" => { + let a = input.pos(); + let b = input.pos(); + aabb(&mut out, "block", Aabb::block(a))?; + aabb(&mut out, "encapsulate", Aabb::encapsulating_blocks(a, b))?; + } + "grid" => { + let cube = input.integer() != 0; + let sizes = std::array::from_fn(|_| input.integer() as usize); + let coords = std::array::from_fn(|i| { + (0..=sizes[i]).map(|_| input.number()).collect::>() + }); + let occupied = input.word().bytes().map(|b| b == b'1').collect::>(); + let occupied = if sizes.contains(&0) { + &[][..] + } else { + &occupied[..] + }; + let shape = if cube { + VoxelShape::from_cube(sizes, occupied) + } else { + VoxelShape::from_grid(coords, occupied) + } + .expect("valid shape"); + writeln!(out, "shape {} {}", shapes.len(), shape.boxes().len())?; + values( + &mut out, + "axis-extrema", + Axis::ALL + .map(|axis| shape.min(axis)) + .into_iter() + .chain(Axis::ALL.map(|axis| shape.max(axis))), + )?; + if let Some(b) = shape.bounds() { + aabb(&mut out, "shape-bounds", b)?; + } else { + writeln!(out, "shape-bounds none")?; + } + for b in shape.boxes() { + aabb(&mut out, "part", *b)?; + } + shapes.push(shape); + } + "query" => { + let id = input.integer() as usize; + let b = input.aabb(); + let start = input.vector(); + let end = input.vector(); + let p = input.vector(); + let block = input.pos(); + let axis = Axis::ALL[input.integer() as usize]; + let amount = input.number(); + let shape = &shapes[id]; + values( + &mut out, + "column", + [shape.min_at(axis, p.x, p.y), shape.max_at(axis, p.x, p.y)], + )?; + values(&mut out, "collide", [shape.collide(axis, b, amount)])?; + hit(&mut out, shape.clip(start, end, block))?; + point(&mut out, "closest", shape.closest_point(p))?; + writeln!( + out, + "index {} {} {}", + shape.find_index(Axis::X, p.x), + shape.find_index(Axis::Y, p.y), + shape.find_index(Axis::Z, p.z) + )?; + } + "many" => { + let b = input.aabb(); + let axis = Axis::ALL[input.integer() as usize]; + let amount = input.number(); + let count = input.integer(); + let selected = (0..count) + .map(|_| &shapes[input.integer() as usize]) + .collect::>(); + values( + &mut out, + "many", + [VoxelShape::collide_all(axis, b, selected, amount)], + )?; + } + "floor-height" => { + let shape = &shapes[input.integer() as usize]; + let below = &shapes[input.integer() as usize]; + let mut calls = 0; + let height = block_floor_height(shape, || { + calls += 1; + below + }); + values(&mut out, "floor-height", [height])?; + writeln!(out, "below-calls {calls}")?; + } + "block-iterate" => { + let a = input.pos(); + let b = input.pos(); + let direction = input.vector(); + let limit = input.integer() as usize; + positions( + &mut out, + "closed", + BlockPos::between_closed(a, b).expect("bounded block box"), + limit, + )?; + positions( + &mut out, + "direction", + BlockPos::between_corners_in_direction(a, b, direction) + .expect("bounded block box"), + limit, + )?; + } + "box-iterate" => { + let b = input.aabb(); + let direction = input.vector(); + let limit = input.integer() as usize; + positions( + &mut out, + "closed", + BlockPos::between_closed_box(b).expect("bounded block box"), + limit, + )?; + positions( + &mut out, + "direction", + BlockPos::between_box_corners_in_direction(b, direction) + .expect("bounded block box"), + limit, + )?; + } + "sweep" => { + let start = input.vector(); + let end = input.vector(); + let b = input.aabb(); + let stop = input.integer() as usize; + let mut visits = Vec::new(); + let completed = sweep_intersected_blocks(start, end, b, 1_000_000, |pos, step| { + visits.push((pos, step)); + visits.len() != stop + }) + .expect("bounded finite sweep"); + for (pos, step) in &visits { + writeln!(out, "block-visit {} {} {} {step}", pos.x, pos.y, pos.z)?; + } + writeln!(out, "sweep {} {}", u8::from(completed), visits.len())?; + } + "step-motion" => { + let b = input.aabb(); + let movement = input.vector(); + let max_step = input.number() as f32; + let grounded = input.integer() != 0; + let mut read_shapes = || { + let count = input.integer(); + (0..count) + .map(|_| &shapes[input.integer() as usize]) + .collect::>() + }; + let entities = read_shapes(); + let initial = read_shapes(); + let stepping = read_shapes(); + let border = input.integer(); + aabb( + &mut out, + "entity-query", + entity_collision_bounds(movement, b, max_step), + )?; + let mut queries = Vec::new(); + let result = resolve_step_movement(movement, b, max_step, grounded, |query| { + let blocks = if queries.is_empty() { + &initial + } else { + &stepping + }; + queries.push(query); + let mut selected = entities.clone(); + if border >= 0 { + selected.push(&shapes[border as usize]); + } + selected.extend(blocks.iter().copied()); + selected + }); + for query in &queries { + aabb(&mut out, "block-query", *query)?; + } + vector(&mut out, "step-motion", result)?; + writeln!(out, "block-queries {}", queries.len())?; + } + "motion" => { + let b = input.aabb(); + let movement = input.vector(); + let max_step = input.number() as f32; + let current_y = input.number() as f32; + let count = input.integer(); + let selected = (0..count) + .map(|_| &shapes[input.integer() as usize]) + .collect::>(); + vector( + &mut out, + "motion", + resolve_shape_movement(movement, b, &selected), + )?; + let candidates = candidate_step_heights(b, &selected, max_step, current_y); + write!(out, "steps {}", candidates.len())?; + for value in candidates { + write!( + out, + " {:08x}", + if value.is_nan() { + 0x7fc0_0000 + } else { + value.to_bits() + } + )?; + } + writeln!(out)?; + } + _ => panic!("unknown command {operation}"), + } + assert!(input.0.next().is_none(), "trailing input"); + } + out.flush() +} diff --git a/crates/horizon-core/src/bin/noise_parity.rs b/crates/horizon-core/src/bin/noise_parity.rs new file mode 100644 index 000000000..52085cddd --- /dev/null +++ b/crates/horizon-core/src/bin/noise_parity.rs @@ -0,0 +1,423 @@ +//! Test transport for comparing noise with the downloaded vanilla artifacts. +use horizon_core::{ + geometry::Axis, + noise::{ + DensityVolume, GradientTable, Noise, NoiseBuildError, NoiseStack, NormalNoise, + Normalization, PerlinNoise, SimplexNoise, SmearedPerlinNoise, wrap, + }, + random::{LegacyRandom, RandomSource, XoroshiroRandom}, +}; +use std::io::{self, BufRead, BufWriter, Write}; +use std::sync::Arc; + +enum Sampler { + Perlin(PerlinNoise), + Simplex(SimplexNoise), + Smeared(SmearedPerlinNoise), + Stack(NoiseStack), +} +impl Sampler { + fn table(&self) -> &GradientTable { + match self { + Self::Perlin(n) => n.table(), + Self::Simplex(n) => n.table(), + Self::Smeared(n) => n.table(), + Self::Stack(_) => panic!("stack has no gradient table"), + } + } + fn as_noise(&self) -> &dyn Noise { + match self { + Self::Perlin(n) => n, + Self::Simplex(n) => n, + Self::Smeared(n) => n, + Self::Stack(n) => n, + } + } + fn shared_noise(&self) -> Arc { + match self { + Self::Perlin(n) => Arc::new(n.clone()), + Self::Simplex(n) => Arc::new(n.clone()), + Self::Smeared(n) => Arc::new(n.clone()), + Self::Stack(n) => Arc::new(n.clone()), + } + } + fn range(&self) -> Result<[f32; 2], horizon_core::noise::NanRange> { + self.as_noise().range() + } + fn get2(&self, x: f64, z: f64) -> f32 { + self.as_noise().get2(x, z) + } + fn get3(&self, x: f64, y: f64, z: f64) -> f32 { + self.as_noise().get3(x, y, z) + } +} +fn read( + args: &mut std::str::SplitWhitespace<'_>, +) -> Result> { + args.next() + .ok_or("missing argument")? + .parse() + .map_err(|_| "invalid argument".into()) +} +fn double(args: &mut std::str::SplitWhitespace<'_>) -> Result> { + Ok(f64::from_bits(u64::from_str_radix( + args.next().ok_or("missing double")?, + 16, + )?)) +} +fn float(args: &mut std::str::SplitWhitespace<'_>) -> Result> { + Ok(f32::from_bits(u32::from_str_radix( + args.next().ok_or("missing float")?, + 16, + )?)) +} +fn bits(v: f32) -> u32 { + if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() } +} +fn dbits(v: f64) -> u64 { + if v.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + v.to_bits() + } +} +fn create( + kind: &str, + mut rng: R, + skip: bool, + scale: f64, + out: &mut impl Write, +) -> io::Result { + let sampler = match kind { + "perlin" => Sampler::Perlin(PerlinNoise::new(&mut rng)), + "simplex" => Sampler::Simplex(SimplexNoise::with_skipped_offsets(&mut rng, skip)), + "smeared" => Sampler::Smeared(SmearedPerlinNoise::new(&mut rng, scale)), + _ => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "unknown sampler", + )); + } + }; + let offsets = sampler.table().offsets(); + let range = sampler.range(); + let (lower, upper) = match range { + Ok(range) => (bits(range[0]).to_string(), bits(range[1]).to_string()), + Err(_) => ("error".to_owned(), "error".to_owned()), + }; + writeln!( + out, + "create {} {} {} {} {} {}", + dbits(offsets[0]), + dbits(offsets[1]), + dbits(offsets[2]), + lower, + upper, + rng.next_long() + )?; + write!(out, "permutations")?; + for v in sampler.table().permutations() { + write!(out, " {v}")?; + } + writeln!(out)?; + Ok(sampler) +} +fn normal_probe( + out: &mut impl Write, + definition: Result, + mut random: R, + points: &[[f64; 3]], + legacy: bool, +) -> Result<(), Box> { + let Ok(definition) = definition else { + writeln!(out, "normal error {}", random.next_long())?; + return Ok(()); + }; + let range = definition.range(); + writeln!( + out, + "normal {} {} {} {}", + definition.octaves().len(), + dbits(definition.normalization_factor()), + bits(range[0]), + bits(range[1]) + )?; + for octave in definition.octaves() { + writeln!( + out, + "octave {} {} {} {}", + octave.octave_index, + dbits(octave.frequency), + dbits(octave.amplitude), + octave.seed() + )?; + } + let created = if legacy { + definition.create_for_legacy_nether_biome(&mut random) + } else { + definition.create(&mut random) + }; + match created { + Err(_) => writeln!(out, "normal-create error")?, + Ok(noise) => { + let range = noise.range()?; + writeln!( + out, + "normal-create {} {} {}", + noise.layers().len(), + bits(range[0]), + bits(range[1]) + )?; + for layer in noise.layers() { + writeln!( + out, + "normal-layer {} {} {} {}", + dbits(layer.frequency), + bits(layer.amplitude), + bits(layer.noise.get2(0.25, 0.75)), + bits(layer.noise.get3(-17.25, 64.125, 32.5)) + )?; + } + for &[x, y, z] in points { + writeln!( + out, + "normal-query {} {}", + bits(noise.get2(x, z)), + bits(noise.get3(x, y, z)) + )?; + } + let volume = DensityVolume::new([2, 5, 2], [-17, -64, 32], [4, 1, 4])?; + let mut values: Vec = (0..volume.size()) + .map(|i| (i as f32 - 10.0) * 0.125) + .collect(); + for (pass, amplitude) in [0.5, -0.25].into_iter().enumerate() { + noise.add_to_volume(&mut values, volume, 0.125, 0.25, amplitude)?; + for (i, value) in values.iter().enumerate() { + writeln!(out, "normal-volume {pass} {i} {}", bits(*value))?; + } + } + } + } + writeln!(out, "normal-parent {}", random.next_long())?; + Ok(()) +} +fn main() -> Result<(), Box> { + let stdin = io::stdin(); + let mut out = BufWriter::new(io::stdout().lock()); + let mut samplers = Vec::new(); + for line in stdin.lock().lines() { + let line = line?; + let mut args = line.split_whitespace(); + match args.next().ok_or("missing operation")? { + "normal" => { + let kind = args.next().ok_or("missing RNG kind")?; + let seed: i64 = read(&mut args)?; + let parity: i32 = read(&mut args)?; + let base: i32 = read(&mut args)?; + let count: i32 = read(&mut args)?; + let normalization: i32 = read(&mut args)?; + let amplitude = double(&mut args)?; + let modifiers: usize = read(&mut args)?; + let modifiers = (0..modifiers) + .map(|_| double(&mut args)) + .collect::, _>>()?; + let point_count: usize = read(&mut args)?; + let points = (0..point_count) + .map(|_| Ok([double(&mut args)?, double(&mut args)?, double(&mut args)?])) + .collect::, Box>>()?; + let definition = if parity & 1 != 0 { + NormalNoise::create_parity(base, &modifiers) + } else { + (|| { + let mut builder = NormalNoise::builder(); + builder + .set_base_octave(base) + .set_base_amplitude(amplitude) + .set_normalization(match normalization { + 0 => Normalization::Disabled, + 1 => Normalization::Enabled, + _ => Normalization::Legacy, + }); + builder.set_octave_count(count)?; + for (index, value) in modifiers.iter().enumerate() { + builder.set_amplitude_modifier(index as i32, *value)?; + } + builder.build() + })() + }; + match kind { + "legacy" => normal_probe( + &mut out, + definition, + LegacyRandom::new(seed), + &points, + parity & 2 != 0, + )?, + "xoroshiro" => normal_probe( + &mut out, + definition, + XoroshiroRandom::new(seed), + &points, + parity & 2 != 0, + )?, + _ => return Err("unknown stream".into()), + } + } + "create" => { + let kind = args.next().ok_or("missing sampler")?; + let stream = args.next().ok_or("missing stream")?; + let seed: i64 = read(&mut args)?; + let skip: i32 = read(&mut args)?; + let scale = double(&mut args)?; + let sampler = match stream { + "legacy" => create(kind, LegacyRandom::new(seed), skip != 0, scale, &mut out)?, + "xoroshiro" => { + create(kind, XoroshiroRandom::new(seed), skip != 0, scale, &mut out)? + } + _ => return Err("unknown stream".into()), + }; + samplers.push(sampler); + } + operation @ ("query" | "local") => { + let id: usize = read(&mut args)?; + let mut point = [double(&mut args)?, double(&mut args)?, double(&mut args)?]; + let mut derivative = [float(&mut args)?, float(&mut args)?, float(&mut args)?]; + let sampler = &samplers[id]; + if operation == "local" { + for (value, offset) in point.iter_mut().zip(sampler.table().offsets()) { + *value -= offset; + } + } + let [x, y, z] = point; + write!( + out, + "query {} {}", + bits(sampler.get2(x, z)), + bits(sampler.get3(x, y, z)) + )?; + let value = match sampler { + Sampler::Perlin(n) => Some(n.noise_with_derivative(x, y, z, &mut derivative)), + Sampler::Smeared(n) => Some(n.noise_with_derivative(x, y, z, &mut derivative)), + Sampler::Simplex(_) | Sampler::Stack(_) => None, + }; + if let Some(value) = value { + write!( + out, + " {} {} {} {}", + bits(value), + bits(derivative[0]), + bits(derivative[1]), + bits(derivative[2]) + )?; + } + writeln!(out)?; + } + "volume" => { + let id: usize = read(&mut args)?; + let sizes = [read(&mut args)?, read(&mut args)?, read(&mut args)?]; + let minimum = [read(&mut args)?, read(&mut args)?, read(&mut args)?]; + let steps = [read(&mut args)?, read(&mut args)?, read(&mut args)?]; + let xz_scale = double(&mut args)?; + let y_scale = double(&mut args)?; + let amplitude = float(&mut args)?; + let seed: i64 = read(&mut args)?; + let repeats: usize = read(&mut args)?; + match DensityVolume::new(sizes, minimum, steps) { + Err(_) => writeln!(out, "volume error")?, + Ok(volume) => { + let mut random = LegacyRandom::new(seed); + let mut values: Vec = (0..volume.size() + 4) + .map(|_| f32::from_bits(random.next_int() as u32)) + .collect(); + let sampler = &samplers[id]; + for _ in 0..repeats { + sampler.as_noise().add_to_volume( + &mut values, + volume, + xz_scale, + y_scale, + amplitude, + )?; + } + let maximum = volume.maximum(); + writeln!( + out, + "volume {} {} {} {}", + volume.size(), + maximum[0], + maximum[1], + maximum[2] + )?; + let [sx, sy, sz] = volume.sizes(); + for z in 0..sz { + for x in 0..sx { + for y in 0..sy { + let index = volume.index([x, y, z]).unwrap(); + writeln!( + out, + "cell {index} {} {} {} {}", + volume.block(Axis::X, x).unwrap(), + volume.block(Axis::Y, y).unwrap(), + volume.block(Axis::Z, z).unwrap(), + bits(values[index]) + )?; + } + } + } + for value in &values[volume.size()..] { + writeln!(out, "tail {}", bits(*value))?; + } + } + } + } + "stack" => { + let count: usize = read(&mut args)?; + let mut builder = NoiseStack::builder(); + for _ in 0..count { + let flatten: i32 = read(&mut args)?; + let id: usize = read(&mut args)?; + let frequency = double(&mut args)?; + let amplitude = float(&mut args)?; + if flatten != 0 { + let Sampler::Stack(stack) = &samplers[id] else { + return Err("flatten expects a stack".into()); + }; + builder.add_stack(stack, frequency, amplitude); + } else { + builder.add(samplers[id].shared_noise(), frequency, amplitude); + } + } + match builder.build() { + Err(_) => writeln!(out, "stack error")?, + Ok(stack) => { + let range = stack.range()?; + writeln!( + out, + "stack {} {} {}", + stack.layers().len(), + bits(range[0]), + bits(range[1]) + )?; + for (index, layer) in stack.layers().iter().enumerate() { + writeln!( + out, + "layer {} {} {}", + dbits(layer.frequency), + bits(layer.amplitude), + bits(stack.get_layer(index).unwrap().get3(0.0, 0.0, 0.0)) + )?; + } + samplers.push(Sampler::Stack(stack)); + } + } + } + "wrap" => writeln!(out, "wrap {}", dbits(wrap(double(&mut args)?)))?, + _ => return Err("unknown operation".into()), + } + if args.next().is_some() { + return Err("extra argument".into()); + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-core/src/bin/parity.rs b/crates/horizon-core/src/bin/parity.rs new file mode 100644 index 000000000..964391b3f --- /dev/null +++ b/crates/horizon-core/src/bin/parity.rs @@ -0,0 +1,321 @@ +//! Line-based differential probe. Not a game client or server. +use horizon_core::{ + position::{BlockPos, ChunkPos, SectionPos}, + random::{ + LegacyPositionalRandom, LegacyRandom, PositionalRandom, RandomSource, + XoroshiroPositionalRandom, XoroshiroRandom, java_string_hash, position_seed, + seed_from_hash_utf16, + }, + storage::PackedStorage, +}; +use std::io::{self, BufRead, BufWriter, Write}; + +fn random_probe(out: &mut impl Write, mut rng: R, count: usize) -> io::Result<()> { + let bounds = [1, 2, 3, 16, 31, 256, 65_537, 1_073_741_825, i32::MAX, 0, -1]; + for i in 0..count { + let value = match i % 10 { + 0 => rng.next_int().to_string(), + 1 => rng.next_long().to_string(), + 2 => match rng.next_int_bound(bounds[(i / 10) % bounds.len()]) { + Ok(value) => value.to_string(), + Err(_) => "error".to_owned(), + }, + 3 => u8::from(rng.next_boolean()).to_string(), + 4 => rng.next_float().to_bits().to_string(), + 5 => rng.next_double().to_bits().to_string(), + 6 => rng.fork().next_long().to_string(), + 7 => { + rng.consume_count((i % 7) as i32 - 2); + rng.next_long().to_string() + } + 8 => { + if i % 101 == 8 { + let seed = rng.next_long().wrapping_sub(i as i64); + rng.set_seed(seed); + } + rng.next_int_bound(1_073_741_825).unwrap().to_string() + } + _ => rng.next_int().to_string(), + }; + writeln!(out, "rng {i} {value}")?; + } + Ok(()) +} + +fn read(args: &mut std::str::SplitWhitespace<'_>) -> Result { + args.next() + .ok_or_else(|| "missing argument".to_owned())? + .parse() + .map_err(|_| "invalid argument".to_owned()) +} +fn helpers( + out: &mut impl Write, + mut rng: R, + bounds: [i32; 2], + double: [f64; 2], + float: [f32; 2], +) -> io::Result<()> { + for i in 0..32 { + let inclusive = rng + .next_int_between_inclusive(bounds[0], bounds[1]) + .map_or_else(|_| "error".to_owned(), |v| v.to_string()); + let exclusive = rng + .next_int_between(bounds[0], bounds[1]) + .map_or_else(|_| "error".to_owned(), |v| v.to_string()); + let d = rng.triangle(double[0], double[1]); + let f = rng.triangle_float(float[0], float[1]); + let d = if d.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + d.to_bits() + }; + let f = if f.is_nan() { 0x7fc0_0000 } else { f.to_bits() }; + writeln!( + out, + "helpers {i} {inclusive} {exclusive} {d} {f} {}", + rng.next_long() + )?; + } + random_probe(out, rng, 24) +} +fn utf16(token: &str) -> Result, String> { + if token == "-" { + return Ok(Vec::new()); + } + if token.len() % 4 != 0 { + return Err("invalid UTF-16 hex".to_owned()); + } + token + .as_bytes() + .chunks_exact(4) + .map(|part| { + u16::from_str_radix( + std::str::from_utf8(part).map_err(|_| "invalid UTF-16 hex")?, + 16, + ) + .map_err(|_| "invalid UTF-16 hex".to_owned()) + }) + .collect() +} +fn factory_probe( + out: &mut impl Write, + factory: P, + position: BlockPos, + seed: i64, + name: &[u16], + count: usize, +) -> io::Result<()> { + for (label, rng) in [ + ("at", factory.at(position)), + ("seed", factory.from_seed(seed)), + ("hash", factory.from_hash_of_utf16(name)), + ] { + writeln!(out, "factory {label}")?; + random_probe(out, rng, count)?; + } + Ok(()) +} + +fn probe(line: &str, out: &mut impl Write) -> Result<(), Box> { + let mut args = line.split_whitespace(); + match args.next().ok_or("missing operation")? { + "helpers" => { + let kind = args.next().ok_or("missing RNG kind")?; + let seed: i64 = read(&mut args)?; + let bounds = [read(&mut args)?, read(&mut args)?]; + let d = [ + f64::from_bits(u64::from_str_radix( + args.next().ok_or("missing double")?, + 16, + )?), + f64::from_bits(u64::from_str_radix( + args.next().ok_or("missing double")?, + 16, + )?), + ]; + let f = [ + f32::from_bits(u32::from_str_radix( + args.next().ok_or("missing float")?, + 16, + )?), + f32::from_bits(u32::from_str_radix( + args.next().ok_or("missing float")?, + 16, + )?), + ]; + match kind { + "legacy" => helpers(out, LegacyRandom::new(seed), bounds, d, f)?, + "xoroshiro" => helpers(out, XoroshiroRandom::new(seed), bounds, d, f)?, + _ => return Err("unknown RNG kind".into()), + } + } + "factory" => { + let kind = args.next().ok_or("missing RNG kind")?; + let mode: i32 = read(&mut args)?; + let lo: i64 = read(&mut args)?; + let hi: i64 = read(&mut args)?; + let position = BlockPos::new(read(&mut args)?, read(&mut args)?, read(&mut args)?); + let seed: i64 = read(&mut args)?; + let name = utf16(args.next().ok_or("missing name")?)?; + let count: usize = read(&mut args)?; + let hash = seed_from_hash_utf16(&name); + writeln!( + out, + "seeds {} {} {} {}", + position_seed(position), + java_string_hash(name.iter().copied()), + hash[0] as i64, + hash[1] as i64 + )?; + if kind == "legacy" { + let mut source = LegacyRandom::new(lo); + let factory = if mode == 0 { + LegacyPositionalRandom::new(lo) + } else { + source.fork_positional() + }; + factory_probe(out, factory, position, seed, &name, count)?; + if mode != 0 { + writeln!(out, "parent {}", source.next_long())?; + } + } else { + let mut source = XoroshiroRandom::new(lo); + let factory = if mode == 0 { + XoroshiroPositionalRandom::new(lo as u64, hi as u64) + } else { + source.fork_positional() + }; + factory_probe(out, factory, position, seed, &name, count)?; + if mode != 0 { + writeln!(out, "parent {}", source.next_long())?; + } + } + } + "position" => { + let p = BlockPos::new(read(&mut args)?, read(&mut args)?, read(&mut args)?); + let offset = p.offset(read(&mut args)?, read(&mut args)?, read(&mut args)?); + let packed = p.pack(); + let decoded = BlockPos::unpack(packed); + let section = p.section(); + let sp = section.pack(); + let sd = SectionPos::unpack(sp); + let chunk = p.chunk(); + let cp = chunk.pack(); + let cd = ChunkPos::unpack(cp); + let region = chunk.region(); + let (rx, rz) = chunk.region_local(); + let relative = p.section_relative(); + let rebuilt = section.relative_to_block(relative); + writeln!( + out, + "position {packed} {} {} {} {sp} {} {} {} {cp} {} {} {} {} {rx} {rz} {relative} {} {} {} {} {} {} {}", + decoded.x, + decoded.y, + decoded.z, + sd.x, + sd.y, + sd.z, + cd.x, + cd.z, + region.x, + region.z, + p.section_index(), + rebuilt.x, + rebuilt.y, + rebuilt.z, + offset.x, + offset.y, + offset.z + )?; + } + "legacy" => random_probe(out, LegacyRandom::new(read(&mut args)?), read(&mut args)?)?, + "xoroshiro" => random_probe( + out, + XoroshiroRandom::new(read(&mut args)?), + read(&mut args)?, + )?, + "xoroshiro_state" => random_probe( + out, + XoroshiroRandom::from_state( + read::(&mut args)? as u64, + read::(&mut args)? as u64, + ), + read(&mut args)?, + )?, + "storage" => { + let bits: u8 = read(&mut args)?; + let len: usize = read(&mut args)?; + let seed: i64 = read(&mut args)?; + let mut storage = PackedStorage::new(bits, len)?; + let mut rng = LegacyRandom::new(seed); + let mask = ((1_u64 << bits) - 1).min(i32::MAX as u64); + for i in 0..len * 3 { + let index = rng.next_int_bound(len as i32)? as usize; + let value = (rng.next_int() as u32 as u64 & mask) as u32; + let old = storage.set(index, value)?; + writeln!(out, "set {i} {index} {old} {}", storage.get(index)?)?; + } + for (i, &word) in storage.words().iter().enumerate() { + writeln!(out, "word {i} {}", word as i64)?; + } + for (i, value) in storage.unpack().iter().enumerate() { + writeln!(out, "value {i} {}", *value as i32)?; + } + let mut imported = + PackedStorage::from_words(bits, len, vec![u64::MAX; storage.words().len()])?; + for i in 0..len { + writeln!(out, "import {i} {}", imported.get(i)? as i32)?; + } + if len > 0 { + imported.set(len - 1, 0)?; + } + for (i, &word) in imported.words().iter().enumerate() { + writeln!(out, "import_word {i} {}", word as i64)?; + } + for value in [0, 1, mask as u32] { + imported.fill(value)?; + for (i, &word) in imported.words().iter().enumerate() { + writeln!(out, "fill {value} {i} {}", word as i64)?; + } + } + let before = storage.clone(); + writeln!( + out, + "invalid_index {}", + u8::from(storage.set(len, 0).is_err()) + )?; + let invalid_value = if bits == 32 { u32::MAX } else { 1_u32 << bits }; + // An empty storage has no valid index at which to test value errors. + if len > 0 { + writeln!( + out, + "invalid_value {}", + u8::from(storage.set(0, invalid_value).is_err()) + )?; + } + writeln!(out, "unchanged {}", u8::from(storage == before))?; + } + _ => return Err("unknown operation".into()), + } + if args.next().is_some() { + return Err("unexpected trailing argument".into()); + } + Ok(()) +} + +fn main() { + let mut out = BufWriter::new(io::stdout().lock()); + for (i, line) in io::stdin().lock().lines().enumerate() { + let result = line + .map_err(|e| e.to_string()) + .and_then(|line| probe(&line, &mut out).map_err(|e| e.to_string())); + if let Err(error) = result { + eprintln!("line {}: {error}", i + 1); + std::process::exit(2); + } + } + if let Err(error) = out.flush() { + eprintln!("output failed: {error}"); + std::process::exit(2); + } +} diff --git a/crates/horizon-core/src/bin/tick_parity.rs b/crates/horizon-core/src/bin/tick_parity.rs new file mode 100644 index 000000000..e4b8c46ea --- /dev/null +++ b/crates/horizon-core/src/bin/tick_parity.rs @@ -0,0 +1,246 @@ +//! Original trace adapter for pinned vanilla scheduler comparisons. +use horizon_core::{ + position::{BlockPos, ChunkPos}, + ticks::{ + ChunkTicks, LevelTicks, SavedTick, ScheduleResult, ScheduledTick, TickArea, TickPriority, + TickTypeId, + }, +}; +use std::{ + collections::{HashMap, HashSet}, + error::Error, + io::{self, BufRead, Write}, + str::{FromStr, SplitWhitespace}, +}; +struct Input<'a>(SplitWhitespace<'a>); +impl Input<'_> { + fn value(&mut self) -> Result> + where + T::Err: Error + 'static, + { + Ok(self.0.next().ok_or("missing argument")?.parse()?) + } + fn pos(&mut self) -> Result> { + Ok(BlockPos::new(self.value()?, self.value()?, self.value()?)) + } + fn chunk(&mut self) -> Result> { + Ok(ChunkPos::new(self.value()?, self.value()?)) + } + fn area(&mut self) -> Result> { + Ok(TickArea::new(self.pos()?, self.pos()?)) + } +} +fn result(result: ScheduleResult) -> u8 { + match result { + ScheduleResult::Added => 1, + ScheduleResult::Duplicate => 0, + ScheduleResult::MissingChunk => 2, + } +} +fn scheduled(out: &mut impl Write, tick: ScheduledTick) -> io::Result<()> { + writeln!( + out, + "queued {} {} {} {} {} {} {}", + tick.kind.0, + tick.pos.x, + tick.pos.y, + tick.pos.z, + tick.trigger_tick, + tick.priority as i8, + tick.sub_tick_order + ) +} +fn main() -> Result<(), Box> { + let mut level = LevelTicks::default(); + let mut detached = HashMap::::new(); + let mut blocked = HashSet::new(); + let mut out = io::BufWriter::new(io::stdout().lock()); + for (line_number, line) in io::stdin().lock().lines().enumerate() { + let line = line?; + let mut input = Input(line.split_whitespace()); + let operation = input.0.next().ok_or("empty command")?; + writeln!(out, "command {} {}", line_number, operation)?; + match operation { + "reset" => { + level = LevelTicks::default(); + detached.clear(); + blocked.clear(); + } + "add" => { + let pos = input.chunk()?; + if level.chunk(pos).is_none() { + level.add_chunk(pos, ChunkTicks::default())?; + } + } + "load" => { + let pos = input.chunk()?; + let count: usize = input.value()?; + let mut ticks = Vec::with_capacity(count); + for _ in 0..count { + ticks.push(SavedTick { + kind: TickTypeId(input.value()?), + pos: input.pos()?, + delay: input.value()?, + priority: TickPriority::by_value(input.value()?), + }); + } + if level.chunk(pos).is_some() { + level.remove_chunk(pos); + } + level.add_chunk(pos, ChunkTicks::from_saved(ticks))?; + } + "unpack" => { + let pos = input.chunk()?; + level.unpack_chunk(pos, input.value()?); + } + "remove" => { + let pos = input.chunk()?; + if let Some(chunk) = level.remove_chunk(pos) { + detached.insert(pos, chunk); + } + } + "restore" => { + let pos = input.chunk()?; + if level.chunk(pos).is_none() { + if let Some(chunk) = detached.remove(&pos) { + level.add_chunk(pos, chunk)?; + } + } + } + "enable" => { + let pos = input.chunk()?; + if input.value::()? == 0 { + blocked.insert(pos); + } else { + blocked.remove(&pos); + } + } + "schedule" => { + let tick = ScheduledTick { + kind: TickTypeId(input.value()?), + pos: input.pos()?, + trigger_tick: input.value()?, + priority: TickPriority::by_value(input.value()?), + sub_tick_order: input.value()?, + }; + writeln!(out, "schedule {}", result(level.schedule(tick)))?; + } + "query" => { + let kind = TickTypeId(input.value()?); + let pos = input.pos()?; + writeln!( + out, + "query {} {}", + u8::from(level.has_scheduled(pos, kind)), + u8::from(level.will_tick_this_tick(pos, kind)) + )?; + } + "chunk" => { + let pos = input.chunk()?; + if let Some(chunk) = level.chunk(pos) { + writeln!(out, "chunk {}", chunk.count())?; + for &tick in chunk.queued() { + scheduled(&mut out, tick)?; + } + } else { + writeln!(out, "chunk absent")?; + } + } + "save" => { + let pos = input.chunk()?; + let time = input.value()?; + if let Some(chunk) = level.chunk(pos) { + let ticks = chunk.pack(time); + writeln!(out, "saved {}", ticks.len())?; + for tick in ticks { + writeln!( + out, + "saved-value {} {} {} {} {} {}", + tick.kind.0, + tick.pos.x, + tick.pos.y, + tick.pos.z, + tick.delay, + tick.priority as i8 + )?; + } + } else { + writeln!(out, "saved absent")?; + } + } + "reload" => { + let pos = input.chunk()?; + let save_time = input.value()?; + let load_time = input.value()?; + if let Some(old) = level.remove_chunk(pos) { + let mut chunk = ChunkTicks::from_saved(old.pack(save_time)); + chunk.unpack(load_time); + level.add_chunk(pos, chunk)?; + } + } + "clear" => level.clear_area(input.area()?), + "copy" => { + let area = input.area()?; + level.copy_area(area, input.pos()?); + } + "tick" => { + let time: i64 = input.value()?; + let maximum: i32 = input.value()?; + let action: i32 = input.value()?; + let probe_kind = TickTypeId(input.value()?); + let probe = input.pos()?; + let mut order: i64 = input.value()?; + level.begin_tick(time, maximum, |pos| !blocked.contains(&pos))?; + while let Some(tick) = level.next_tick()? { + scheduled(&mut out, tick)?; + writeln!( + out, + "running {} {} {}", + u8::from(level.will_tick_this_tick(tick.pos, tick.kind)), + u8::from(level.has_scheduled(tick.pos, tick.kind)), + u8::from(level.will_tick_this_tick(probe, probe_kind)) + )?; + match action { + 1 => { + let mut next = tick; + next.trigger_tick = time; + next.sub_tick_order = order; + order = order.wrapping_add(1); + writeln!(out, "callback-schedule {}", result(level.schedule(next)))?; + } + 2 => { + level.clear_area(TickArea::new(tick.pos, tick.pos.offset(1, 1, 1))); + writeln!( + out, + "callback-clear {}", + u8::from(level.will_tick_this_tick(probe, probe_kind)) + )?; + } + 3 => level.copy_area( + TickArea::new(tick.pos.offset(-2, -2, -2), tick.pos.offset(2, 2, 2)), + BlockPos::new(16, 0, 0), + ), + 4 => { + let pos = tick.pos.chunk(); + if let Some(chunk) = level.remove_chunk(pos) { + detached.insert(pos, chunk); + } + } + 5 => { + blocked.insert(tick.pos.chunk()); + } + 0 => {} + _ => return Err("unknown callback action".into()), + } + } + level.finish_tick()?; + } + _ => return Err(format!("unknown command {operation}").into()), + } + if input.0.next().is_some() { + return Err("extra arguments".into()); + } + writeln!(out, "count {}", level.count())?; + } + Ok(()) +} diff --git a/crates/horizon-core/src/biome.rs b/crates/horizon-core/src/biome.rs new file mode 100644 index 000000000..4f8c9ff54 --- /dev/null +++ b/crates/horizon-core/src/biome.rs @@ -0,0 +1,74 @@ +//! Block-to-quart biome lookup for Java Edition 26.3. +//! Selection is independent of the provider that stores or generates quart biomes. +mod seed_hash; +use crate::position::BlockPos; + +/// The seed sent to clients: SHA-256 of the little-endian world seed, with the +/// first eight digest bytes interpreted as a little-endian signed long. +pub fn obfuscate_seed(world_seed: i64) -> i64 { + seed_hash::hash(world_seed) +} + +#[derive(Clone, Copy, Debug)] +pub struct BiomeZoom { + seed: i64, +} +impl BiomeZoom { + /// Accepts the obfuscated biome seed, not the original world seed. + pub const fn new(obfuscated_seed: i64) -> Self { + Self { + seed: obfuscated_seed, + } + } + /// Choose the closest of eight jittered quart corners, preserving vanilla's + /// corner order, strict tie comparison and signed coordinate wrapping. + pub fn quart_at_block(self, block: BlockPos) -> [i32; 3] { + let shifted = [block.x, block.y, block.z].map(|v| v.wrapping_sub(2)); + let base = shifted.map(|v| v >> 2); + let fractions = shifted.map(|v| f64::from(v & 3) / 4.); + let mut selected = base; + let mut best = f64::INFINITY; + for corner in 0..8 { + let offsets = [(corner >> 2) & 1, (corner >> 1) & 1, corner & 1]; + let quart = std::array::from_fn(|i| base[i].wrapping_add(offsets[i])); + let delta = std::array::from_fn(|i| fractions[i] - f64::from(offsets[i])); + let distance = fiddled_distance(self.seed, quart, delta); + if best > distance { + best = distance; + selected = quart; + } + } + selected + } +} + +/// Direct noise-biome lookup bypasses the eight-corner zoom. +pub fn noise_quart_at_block(block: BlockPos) -> [i32; 3] { + [block.x, block.y, block.z].map(|v| v >> 2) +} +/// Java floors each double to a saturating int (NaN becomes zero) before shifting. +pub fn noise_quart_at_position(position: [f64; 3]) -> [i32; 3] { + position.map(|v| (v.floor() as i32) >> 2) +} +fn next(seed: i64, salt: i64) -> i64 { + seed.wrapping_mul( + seed.wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407), + ) + .wrapping_add(salt) +} +fn fiddle(seed: i64) -> f64 { + (((seed >> 24) & 1023) as f64 / 1024. - 0.5) * 0.9 +} +fn fiddled_distance(seed: i64, quart: [i32; 3], delta: [f64; 3]) -> f64 { + let mut mixed = seed; + for coordinate in quart.into_iter().cycle().take(6) { + mixed = next(mixed, i64::from(coordinate)); + } + let x = delta[0] + fiddle(mixed); + mixed = next(mixed, seed); + let y = delta[1] + fiddle(mixed); + mixed = next(mixed, seed); + let z = delta[2] + fiddle(mixed); + z * z + y * y + x * x +} diff --git a/crates/horizon-core/src/biome/seed_hash.rs b/crates/horizon-core/src/biome/seed_hash.rs new file mode 100644 index 000000000..e88d67ae1 --- /dev/null +++ b/crates/horizon-core/src/biome/seed_hash.rs @@ -0,0 +1,66 @@ +// SHA-256 specialized to one eight-byte input. This is a world-seed compatibility +// transform, not a general-purpose cryptography interface. +const K: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]; +pub(super) fn hash(seed: i64) -> i64 { + let bytes = seed.to_le_bytes(); + let mut words = [0_u32; 64]; + words[0] = u32::from_be_bytes(bytes[..4].try_into().unwrap()); + words[1] = u32::from_be_bytes(bytes[4..].try_into().unwrap()); + words[2] = 0x80000000; + words[15] = 64; + for i in 16..64 { + let a = words[i - 15]; + let b = words[i - 2]; + let small0 = a.rotate_right(7) ^ a.rotate_right(18) ^ (a >> 3); + let small1 = b.rotate_right(17) ^ b.rotate_right(19) ^ (b >> 10); + words[i] = words[i - 16] + .wrapping_add(small0) + .wrapping_add(words[i - 7]) + .wrapping_add(small1); + } + let initial = [ + 0x6a09e667_u32, + 0xbb67ae85, + 0x3c6ef372, + 0xa54ff53a, + 0x510e527f, + 0x9b05688c, + 0x1f83d9ab, + 0x5be0cd19, + ]; + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = initial; + for i in 0..64 { + let sum1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let choice = (e & f) ^ (!e & g); + let t1 = h + .wrapping_add(sum1) + .wrapping_add(choice) + .wrapping_add(K[i]) + .wrapping_add(words[i]); + let sum0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let majority = (a & b) ^ (a & c) ^ (b & c); + let t2 = sum0.wrapping_add(majority); + h = g; + g = f; + f = e; + e = d.wrapping_add(t1); + d = c; + c = b; + b = a; + a = t1.wrapping_add(t2); + } + let first = a.wrapping_add(initial[0]).to_be_bytes(); + let second = b.wrapping_add(initial[1]).to_be_bytes(); + i64::from_le_bytes([ + first[0], first[1], first[2], first[3], second[0], second[1], second[2], second[3], + ]) +} diff --git a/crates/horizon-core/src/carving.rs b/crates/horizon-core/src/carving.rs new file mode 100644 index 000000000..e539203f3 --- /dev/null +++ b/crates/horizon-core/src/carving.rs @@ -0,0 +1,164 @@ +//! Packed carving masks and vanilla's ordered inclusive column segments. +mod ellipsoid; +pub use ellipsoid::{ + CarveError, CarverOutput, can_reach, carve_ellipsoid, carve_ellipsoid_with_budget, +}; + +/// A contiguous carved interval in a local chunk column. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CarvingColumn { + pub x: i32, + pub z: i32, + pub min_y: i32, + pub max_y: i32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CarvingMaskError { + InvalidBounds, + NegativeIndex, + Capacity, +} +impl std::fmt::Display for CarvingMaskError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::InvalidBounds => "carving mask height must be between 1 and 4064", + Self::NegativeIndex => "carving mask index is negative", + Self::Capacity => "carving mask exceeds its bounded bit capacity", + }) + } +} +impl std::error::Error for CarvingMaskError {} + +/// Bits are contiguous in Y, then Z, then X. Coordinates retain Java's wrapping +/// index arithmetic and positive out-of-range aliases. Growth is capped at +/// 2^24 bits; valid chunk coordinates use at most 256 * 4064 bits. +#[derive(Clone, Debug)] +pub struct CarvingMask { + min_y: i32, + max_y: i32, + height: i32, + words: Vec, + used_words: usize, +} +impl CarvingMask { + pub fn new(min_y: i32, max_y: i32) -> Result { + let height = i64::from(max_y) - i64::from(min_y) + 1; + if !(1..=4064).contains(&height) { + return Err(CarvingMaskError::InvalidBounds); + } + Ok(Self { + min_y, + max_y, + height: height as i32, + words: vec![0; (height as usize * 256).div_ceil(64)], + used_words: 0, + }) + } + pub fn min_y(&self) -> i32 { + self.min_y + } + pub fn max_y(&self) -> i32 { + self.max_y + } + pub fn is_empty(&self) -> bool { + self.used_words == 0 + } + pub fn carve(&mut self, x: i32, y: i32, z: i32) -> Result<(), CarvingMaskError> { + let index = y + .wrapping_sub(self.min_y) + .wrapping_add(z.wrapping_add(x.wrapping_shl(4)).wrapping_mul(self.height)); + if index < 0 { + return Err(CarvingMaskError::NegativeIndex); + } + if index >= 1 << 24 { + return Err(CarvingMaskError::Capacity); + } + let index = index as usize; + let word = index / 64; + if word >= self.words.len() { + self.words.resize(word + 1, 0); + } + self.words[word] |= 1 << (index & 63); + self.used_words = self.used_words.max(word + 1); + Ok(()) + } + /// Traverse ascending packed runs, splitting each run at column boundaries. + /// No per-cell or per-column allocation is required. + pub fn columns(&self) -> impl Iterator + '_ { + let mut cursor = Cursor::default(); + std::iter::from_fn(move || cursor.next(self)) + } + /// Like vanilla's callback traversal, changes made by the visitor affect the + /// next run search, but do not change the already selected run's boundaries. + /// An error stops traversal immediately and retains visitor mutations. + pub fn try_visit_mut( + &mut self, + mut visitor: impl FnMut(&mut Self, CarvingColumn) -> Result<(), E>, + ) -> Result<(), E> { + let mut cursor = Cursor::default(); + while let Some(column) = cursor.next(self) { + visitor(self, column)?; + } + Ok(()) + } + fn next_set(&self, from: usize) -> Option { + let mut word = from / 64; + if word >= self.used_words { + return None; + } + let mut bits = self.words[word] & (u64::MAX << (from & 63)); + loop { + if bits != 0 { + return Some(word * 64 + bits.trailing_zeros() as usize); + } + word += 1; + if word == self.used_words { + return None; + } + bits = self.words[word]; + } + } + fn next_clear(&self, from: usize) -> usize { + let mut word = from / 64; + let mut bits = !self.words[word] & (u64::MAX << (from & 63)); + loop { + if bits != 0 { + return word * 64 + bits.trailing_zeros() as usize; + } + word += 1; + if word == self.used_words { + return word * 64; + } + bits = !self.words[word]; + } + } +} + +#[derive(Default)] +struct Cursor { + search: usize, + run: Option<(usize, usize, usize)>, +} +impl Cursor { + fn next(&mut self, mask: &CarvingMask) -> Option { + let height = mask.height as usize; + let (start, end, column) = match self.run { + Some(run) => run, + None => { + let start = mask.next_set(self.search)?; + let end = mask.next_clear(start) - 1; + self.search = end + 1; + (start, end, start / height) + } + }; + self.run = (column < end / height).then_some((start, end, column + 1)); + let base = column * height; + Some(CarvingColumn { + x: ((column >> 4) & 15) as i32, + z: (column & 15) as i32, + min_y: mask.min_y.wrapping_add(start.saturating_sub(base) as i32), + max_y: mask.min_y.wrapping_add((end - base).min(height - 1) as i32), + }) + } +} diff --git a/crates/horizon-core/src/carving/ellipsoid.rs b/crates/horizon-core/src/carving/ellipsoid.rs new file mode 100644 index 000000000..49b9d0e3a --- /dev/null +++ b/crates/horizon-core/src/carving/ellipsoid.rs @@ -0,0 +1,124 @@ +//! Shared cave/canyon ellipsoid traversal and path reachability. +use super::{CarvingMask, CarvingMaskError}; +use crate::{geometry::floor_i32, position::ChunkPos}; + +pub trait CarverOutput { + type Error; + fn min_y(&self) -> i32; + fn max_y(&self) -> i32; + fn carve(&mut self, x: i32, y: i32, z: i32) -> Result<(), Self::Error>; +} +impl CarverOutput for CarvingMask { + type Error = CarvingMaskError; + fn min_y(&self) -> i32 { + CarvingMask::min_y(self) + } + fn max_y(&self) -> i32 { + CarvingMask::max_y(self) + } + fn carve(&mut self, x: i32, y: i32, z: i32) -> Result<(), Self::Error> { + CarvingMask::carve(self, x, y, z) + } +} +#[derive(Debug, PartialEq, Eq)] +pub enum CarveError { + Output(E), + IterationLimit, +} +impl std::fmt::Display for CarveError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Output(e) => e.fmt(f), + Self::IterationLimit => f.write_str("carver traversal budget exhausted"), + } + } +} +impl std::error::Error for CarveError {} + +/// Tests a cave/canyon path against the target chunk's center. Thickness math +/// first rounds in float precision, while distances use doubles. +pub fn can_reach(chunk: ChunkPos, x: f64, z: f64, step: i32, end: i32, thickness: f32) -> bool { + let dx = x - f64::from(chunk.x.wrapping_shl(4).wrapping_add(8)); + let dz = z - f64::from(chunk.z.wrapping_shl(4).wrapping_add(8)); + let remaining = f64::from(end.wrapping_sub(step)); + let radius = f64::from((thickness + 2.) + 16.); + dx * dx + dz * dz - remaining * remaining <= radius * radius +} + +/// Visit candidate cells in X/Z/descending-Y order. The lower Y limit is +/// exclusive; normalized vertical coordinates use Y-0.5. The caller supplies +/// the cave/canyon skip predicate, which receives each candidate's absolute Y. +/// Failure retains previous output writes. Work is capped at 2^24 candidates. +pub fn carve_ellipsoid( + chunk: ChunkPos, + center: [f64; 3], + horizontal: f64, + vertical: f64, + output: &mut O, + skip: impl FnMut([f64; 3], i32) -> bool, +) -> Result<(), CarveError> { + carve_ellipsoid_with_budget( + chunk, + center, + horizontal, + vertical, + output, + skip, + &mut (1 << 24), + ) +} + +/// The same traversal with a shared candidate budget for a complete carver path. +/// Each tested cell consumes one unit, including cells rejected by the predicate. +pub fn carve_ellipsoid_with_budget( + chunk: ChunkPos, + [x, y, z]: [f64; 3], + horizontal: f64, + vertical: f64, + output: &mut O, + mut skip: impl FnMut([f64; 3], i32) -> bool, + remaining: &mut usize, +) -> Result<(), CarveError> { + let cx = chunk.x.wrapping_shl(4); + let cz = chunk.z.wrapping_shl(4); + let reach = 16. + horizontal * 2.; + if (x - f64::from(cx.wrapping_add(8))).abs() > reach + || (z - f64::from(cz.wrapping_add(8))).abs() > reach + { + return Ok(()); + } + let min_x = floor_i32(x - horizontal) + .wrapping_sub(cx) + .wrapping_sub(1) + .max(0); + let max_x = floor_i32(x + horizontal).wrapping_sub(cx).min(15); + let min_y = floor_i32(y - vertical).wrapping_sub(1).max(output.min_y()); + let max_y = floor_i32(y + vertical).wrapping_add(1).min(output.max_y()); + let min_z = floor_i32(z - horizontal) + .wrapping_sub(cz) + .wrapping_sub(1) + .max(0); + let max_z = floor_i32(z + horizontal).wrapping_sub(cz).min(15); + for lx in min_x..=max_x { + let nx = (f64::from(cx.wrapping_add(lx)) + 0.5 - x) / horizontal; + for lz in min_z..=max_z { + let nz = (f64::from(cz.wrapping_add(lz)) + 0.5 - z) / horizontal; + if nx * nx + nz * nz >= 1. { + continue; + } + let mut by = max_y; + while by > min_y { + if *remaining == 0 { + return Err(CarveError::IterationLimit); + } + *remaining -= 1; + let ny = (f64::from(by) - 0.5 - y) / vertical; + if !skip([nx, ny, nz], by) { + output.carve(lx, by, lz).map_err(CarveError::Output)?; + } + by -= 1; + } + } + } + Ok(()) +} diff --git a/crates/horizon-core/src/density/arithmetic.rs b/crates/horizon-core/src/density/arithmetic.rs new file mode 100644 index 000000000..296a071e8 --- /dev/null +++ b/crates/horizon-core/src/density/arithmetic.rs @@ -0,0 +1,248 @@ +use super::*; + +pub(super) fn java_power(base: f64, exponent: f64) -> f64 { + // Native libm can propagate a signaling NaN base even for exponent zero; + // Java returns one for every base in this case. + if exponent == 0.0 { + 1.0 + } else if exponent.is_nan() || (base.abs() == 1.0 && exponent.is_infinite()) { + f64::NAN + } else { + base.powf(exponent) + } +} + +pub(super) fn java_min(a: f32, b: f32) -> f32 { + if a.is_nan() || b.is_nan() { + f32::NAN + } else if a == 0.0 && b == 0.0 { + f32::from_bits(a.to_bits() | b.to_bits()) + } else if a <= b { + a + } else { + b + } +} +pub(super) fn java_max(a: f32, b: f32) -> f32 { + if a.is_nan() || b.is_nan() { + f32::NAN + } else if a == 0.0 && b == 0.0 { + f32::from_bits(a.to_bits() & b.to_bits()) + } else if a >= b { + a + } else { + b + } +} +fn clamp(value: f32, min: f32, max: f32) -> f32 { + if value < min { + min + } else { + java_min(value, max) + } +} + +/// Selected compiled unary samplers, including constant-operand specializations. +/// Graph compilation is implemented separately. +#[derive(Clone, Copy, Debug)] +pub enum UnaryOp { + Abs, + Negate, + Square, + Cube, + Sqrt, + Log, + PowerBase(f64), + PowerExponent(f64), + Reciprocal, + Sign, + Squeeze, + LeakyRelu(f32), + Add(f32), + SubtractFrom(f32), + Multiply(f32), + DivideInto(f32), + Minimum(f32), + Maximum(f32), + ConstantRangeChoice { + min_inclusive: f32, + max_exclusive: f32, + inside: f32, + outside: f32, + }, + Clamp { + min: f32, + max: f32, + }, +} +impl UnaryOp { + pub(super) fn apply(self, value: f32, bulk: bool) -> f32 { + match self { + Self::Abs => value.abs(), + Self::Negate => -value, + Self::Square => value * value, + Self::Cube => value * value * value, + Self::Sqrt => (value as f64).sqrt() as f32, + Self::Log => (value as f64).ln() as f32, + Self::PowerBase(base) => java_power(base, value as f64) as f32, + Self::PowerExponent(exponent) => java_power(value as f64, exponent) as f32, + Self::Reciprocal => 1.0 / value, + Self::Sign => { + if value == 0.0 || value.is_nan() { + value + } else { + value.signum() + } + } + Self::Squeeze => { + let v = clamp(value, -1.0, 1.0); + v / 2.0 - v * v * v / 24.0 + } + Self::LeakyRelu(factor) => { + if value > 0.0 { + value + } else { + value * factor + } + } + Self::Add(right) => value + right, + Self::SubtractFrom(left) => left - value, + Self::Multiply(right) => value * right, + Self::DivideInto(left) => left / value, + Self::Minimum(right) => { + if bulk { + if right < value { right } else { value } + } else { + java_min(value, right) + } + } + Self::Maximum(right) => { + if bulk { + if right > value { right } else { value } + } else { + java_max(value, right) + } + } + Self::Clamp { min, max } => clamp(value, min, max), + Self::ConstantRangeChoice { + min_inclusive, + max_exclusive, + inside, + outside, + } => { + if value >= min_inclusive && value < max_exclusive { + inside + } else { + outside + } + } + } + } +} +#[derive(Clone, Debug)] +pub struct UnarySampler { + pub input: Arc, + pub operation: UnaryOp, +} +impl DensitySampler for UnarySampler { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + Ok(self + .operation + .apply(self.input.sample_value(context, position)?, false)) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_buffer(buffer, volume)?; + self.input.sample_volume(context, buffer, volume)?; + for value in buffer { + *value = self.operation.apply(*value, true); + } + Ok(()) + } +} + +/// Range bounds are the values baked into vanilla's compiled min/max samplers. +/// Computing those bounds from a density graph is a separate compiler step. +#[derive(Clone, Copy, Debug)] +pub enum BinaryOp { + Add, + Subtract, + Multiply, + Divide, + Minimum { right_min: f32 }, + Maximum { right_max: f32 }, +} +impl BinaryOp { + fn apply(self, left: f32, right: f32, bulk: bool) -> f32 { + match self { + Self::Add => left + right, + Self::Subtract => left - right, + Self::Multiply => left * right, + Self::Divide => left / right, + Self::Minimum { .. } => { + if bulk { + if right < left { right } else { left } + } else { + java_min(left, right) + } + } + Self::Maximum { .. } => { + if bulk { + if right > left { right } else { left } + } else { + java_max(left, right) + } + } + } + } +} +#[derive(Clone, Debug)] +pub struct BinarySampler { + pub left: Arc, + pub right: Arc, + pub operation: BinaryOp, +} +impl DensitySampler for BinarySampler { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + let left = self.left.sample_value(context, position)?; + match self.operation { + BinaryOp::Multiply | BinaryOp::Divide if left == 0.0 => return Ok(0.0), + BinaryOp::Minimum { right_min } if left <= right_min => return Ok(left), + BinaryOp::Maximum { right_max } if left >= right_max => return Ok(left), + _ => {} + } + Ok(self + .operation + .apply(left, self.right.sample_value(context, position)?, false)) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_exact_buffer(buffer, volume)?; + // Vanilla reads a volume-sized temporary through every output index. + // Restrict this API to the valid equal-size case before invoking children. + self.left.sample_volume(context, buffer, volume)?; + context.with_buffer(volume.size(), |context, right| { + self.right.sample_volume(context, right, volume)?; + for (left, right) in buffer.iter_mut().zip(right) { + *left = self.operation.apply(*left, *right, true); + } + Ok(()) + }) + } +} diff --git a/crates/horizon-core/src/density/beardifier.rs b/crates/horizon-core/src/density/beardifier.rs new file mode 100644 index 000000000..225f74714 --- /dev/null +++ b/crates/horizon-core/src/density/beardifier.rs @@ -0,0 +1,214 @@ +//! Structure terrain adaptation from ordered rigid pieces and jigsaw junctions. +//! Discovery/filtering of live structure starts is a separate world subsystem. +use super::{DensitySampler, SampleError, SamplerContext, check_buffer}; +use crate::noise::DensityVolume; +use std::sync::OnceLock; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StructureBounds { + minimum: [i32; 3], + maximum: [i32; 3], +} +impl StructureBounds { + /// Already normalized inclusive bounds. Invalid inputs are rejected rather + /// than invoking vanilla's development-mode logging/repair path. + pub fn new(minimum: [i32; 3], maximum: [i32; 3]) -> Option { + (0..3) + .all(|axis| minimum[axis] <= maximum[axis]) + .then_some(Self { minimum, maximum }) + } + pub fn minimum(self) -> [i32; 3] { + self.minimum + } + pub fn maximum(self) -> [i32; 3] { + self.maximum + } + pub fn contains(self, position: [i32; 3]) -> bool { + (0..3).all(|i| position[i] >= self.minimum[i] && position[i] <= self.maximum[i]) + } + fn intersects(self, minimum: [i32; 3], maximum: [i32; 3]) -> bool { + (0..3).all(|i| self.maximum[i] >= minimum[i] && self.minimum[i] <= maximum[i]) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TerrainAdjustment { + None, + Bury, + BeardThin, + BeardBox, + Encapsulate, +} +#[derive(Clone, Copy, Debug)] +pub struct RigidPiece { + pub bounds: StructureBounds, + pub adjustment: TerrainAdjustment, + pub ground_level_delta: i32, +} +#[derive(Clone, Copy, Debug)] +pub struct JigsawJunction { + pub source_x: i32, + pub source_ground_y: i32, + pub source_z: i32, +} + +#[derive(Clone, Debug, Default)] +pub struct Beardifier { + pieces: Vec, + junctions: Vec, + affected: Option, +} +impl Beardifier { + /// Matches the runtime constructor. A missing affected box makes the entire + /// sampler empty, even when the supplied component lists are nonempty. + pub fn new( + pieces: Vec, + junctions: Vec, + affected: Option, + ) -> Self { + Self { + pieces, + junctions, + affected, + } + } + pub fn affected_bounds(&self) -> Option { + self.affected + } + fn sample_unchecked(&self, [x, y, z]: [i32; 3]) -> f32 { + let mut value = 0.; + for piece in &self.pieces { + let low = piece.bounds.minimum; + let high = piece.bounds.maximum; + let dx = 0.max(low[0].wrapping_sub(x).max(x.wrapping_sub(high[0]))); + let dz = 0.max(low[2].wrapping_sub(z).max(z.wrapping_sub(high[2]))); + let ground = low[1].wrapping_add(piece.ground_level_delta); + let dy = y.wrapping_sub(ground); + let distance_y = match piece.adjustment { + TerrainAdjustment::None => 0, + TerrainAdjustment::Bury | TerrainAdjustment::BeardThin => dy, + TerrainAdjustment::BeardBox => { + 0.max(ground.wrapping_sub(y).max(y.wrapping_sub(high[1]))) + } + TerrainAdjustment::Encapsulate => { + 0.max(low[1].wrapping_sub(y).max(y.wrapping_sub(high[1]))) + } + }; + value += match piece.adjustment { + TerrainAdjustment::None => 0., + TerrainAdjustment::Bury => bury(dx as f32, distance_y as f32 / 2., dz as f32), + TerrainAdjustment::BeardThin | TerrainAdjustment::BeardBox => { + beard(dx, distance_y, dz, dy) * 0.8 + } + TerrainAdjustment::Encapsulate => { + bury(dx as f32 / 2., distance_y as f32 / 2., dz as f32 / 2.) * 0.8 + } + }; + } + for junction in &self.junctions { + let dx = x.wrapping_sub(junction.source_x); + let dy = y.wrapping_sub(junction.source_ground_y); + let dz = z.wrapping_sub(junction.source_z); + value += beard(dx, dy, dz, dy) * 0.4; + } + value + } +} +impl DensitySampler for Beardifier { + fn sample_value(&self, _: &mut SamplerContext, position: [i32; 3]) -> Result { + Ok( + if self + .affected + .is_some_and(|bounds| bounds.contains(position)) + { + self.sample_unchecked(position) + } else { + 0. + }, + ) + } + fn sample_volume( + &self, + _: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_buffer(buffer, volume)?; + buffer.fill(0.); + let Some(bounds) = self.affected else { + return Ok(()); + }; + let minimum = volume.minimum(); + if !bounds.intersects(minimum, volume.maximum()) { + return Ok(()); + } + let steps = volume.steps(); + let sizes = volume.sizes(); + // Deliberately floor, not ceil: the first bulk lattice sample can lie + // below the affected bounds and is evaluated without the scalar guard. + let low: [i32; 3] = std::array::from_fn(|i| { + bounds.minimum[i] + .wrapping_sub(minimum[i]) + .max(0) + .div_euclid(steps[i]) + }); + let high: [i32; 3] = std::array::from_fn(|i| { + ((sizes[i] - 1) as i32).min( + bounds.maximum[i] + .wrapping_sub(minimum[i]) + .div_euclid(steps[i]), + ) + }); + for z in low[2]..=high[2] { + for x in low[0]..=high[0] { + for y in low[1]..=high[1] { + let index = volume + .index([x as usize, y as usize, z as usize]) + .expect("bounded structure density indices"); + let local = [x, y, z]; + let point = std::array::from_fn(|i| { + minimum[i].wrapping_add(local[i].wrapping_mul(steps[i])) + }); + buffer[index] = self.sample_unchecked(point); + } + } + } + Ok(()) + } +} +fn bury(x: f32, y: f32, z: f32) -> f32 { + let squared = (x * x + y * y) + z * z; + if squared >= 36. { + 0. + } else { + 1. - squared.sqrt() / 6. + } +} +fn beard(x: i32, y: i32, z: i32, ground_delta: i32) -> f32 { + let indices = [x, y, z].map(|v| v.wrapping_add(12)); + if indices.iter().any(|v| !(0..24).contains(v)) { + return 0.; + } + let vertical = ground_delta as f32 + 0.5; + let squared = (x as f32 * x as f32 + vertical * vertical) + z as f32 * z as f32; + let factor = (-vertical * fast_inverse_sqrt(f64::from(squared / 2.)) as f32) / 2.; + factor * kernel()[((indices[2] * 24 + indices[0]) * 24 + indices[1]) as usize] +} +fn fast_inverse_sqrt(value: f64) -> f64 { + let half = 0.5 * value; + let bits = 6_910_469_410_427_058_090i64.wrapping_sub((value.to_bits() as i64) >> 1); + let estimate = f64::from_bits(bits as u64); + estimate * (1.5 - half * estimate * estimate) +} +fn kernel() -> &'static [f32; 13824] { + static KERNEL: OnceLock<[f32; 13824]> = OnceLock::new(); + KERNEL.get_or_init(|| { + std::array::from_fn(|i| { + let z = (i / 576) as f64 - 12.; + let x = ((i / 24) % 24) as f64 - 12.; + let y = (i % 24) as f64 - 12. + 0.5; + let squared = (x * x + y * y) + z * z; + std::f64::consts::E.powf(-squared / 16.) as f32 + }) + }) +} diff --git a/crates/horizon-core/src/density/cache.rs b/crates/horizon-core/src/density/cache.rs new file mode 100644 index 000000000..8e5b46f44 --- /dev/null +++ b/crates/horizon-core/src/density/cache.rs @@ -0,0 +1,128 @@ +use super::*; +use crate::position::BlockPos; + +#[derive(Debug)] +pub(super) struct CacheCell { + volume: Option, + buffer: Vec, + value_key: i64, + value: f32, + active: bool, +} +impl Default for CacheCell { + fn default() -> Self { + Self { + volume: None, + buffer: Vec::new(), + value_key: 0, + value: f32::NAN, + active: false, + } + } +} +impl SamplerContext { + /// Cache cells belong to this evaluation context, never to shared samplers. + pub fn cached() -> Self { + Self { + caches: Some(Vec::new()), + ..Self::default() + } + } + pub fn clear_caches(&mut self) { + if let Some(caches) = &mut self.caches { + caches.clear(); + } + } + fn prepare_cache(&mut self, id: usize) -> Result { + let Some(caches) = &mut self.caches else { + return Ok(false); + }; + if id >= caches.len() { + caches.resize_with((id + 16) & !15, CacheCell::default); + } + if caches[id].active { + return Err(SampleError::RecursiveCache); + } + Ok(true) + } +} + +/// A compiled acyclic cache node. IDs are allocated by the graph compiler and +/// shared only for the same function. The bounded API accepts IDs 0..=65535. +#[derive(Clone, Debug)] +pub struct CachingDensitySampler { + id: usize, + input: Arc, +} +impl CachingDensitySampler { + pub fn new(id: usize, input: Arc) -> Result { + if id > 65535 { + return Err(SampleError::CacheIdOutOfRange); + } + Ok(Self { id, input }) + } + pub fn id(&self) -> usize { + self.id + } +} +impl DensitySampler for CachingDensitySampler { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + if !context.prepare_cache(self.id)? { + return self.input.sample_value(context, position); + } + let key = BlockPos::new(position[0], position[1], position[2]).pack(); + let cell = &mut context.caches.as_mut().unwrap()[self.id]; + if cell.value_key == key && !cell.value.is_nan() { + return Ok(cell.value); + } + if let Some(volume) = cell.volume { + if let Some(index) = volume.index_of_block(position) { + return Ok(cell.buffer[index]); + } + } + cell.active = true; + let result = self.input.sample_value(context, position); + let cell = &mut context.caches.as_mut().unwrap()[self.id]; + cell.active = false; + if let Ok(value) = result { + cell.value_key = key; + cell.value = value; + } + result + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_buffer(buffer, volume)?; + if !context.prepare_cache(self.id)? { + return self.input.sample_volume(context, buffer, volume); + } + check_exact_buffer(buffer, volume)?; + let cell = &mut context.caches.as_mut().unwrap()[self.id]; + if cell.volume == Some(volume) { + buffer.copy_from_slice(&cell.buffer); + return Ok(()); + } + let mut cached = std::mem::take(&mut cell.buffer); + cached.resize(volume.size(), 0.0); + // Unwritten values after a failed child are deterministic. Differential + // error tests use a reference arena with the same zero-initialization. + cached.fill(0.0); + cell.volume = Some(volume); + cell.active = true; + let result = self.input.sample_volume(context, &mut cached, volume); + let cell = &mut context.caches.as_mut().unwrap()[self.id]; + cell.active = false; + cell.buffer = cached; + result?; + buffer.copy_from_slice(&cell.buffer); + Ok(()) + } +} diff --git a/crates/horizon-core/src/density/end_islands.rs b/crates/horizon-core/src/density/end_islands.rs new file mode 100644 index 000000000..148f3575d --- /dev/null +++ b/crates/horizon-core/src/density/end_islands.rs @@ -0,0 +1,79 @@ +use super::*; +use crate::{ + noise::SimplexNoise, + random::{LegacyRandom, RandomSource}, +}; + +/// Java Edition 26.3's outer End island density. The center island is supplied +/// by the surrounding terrain graph, rather than by this sampler. +#[derive(Clone, Debug)] +pub struct EndIslandSampler { + noise: SimplexNoise, +} +impl EndIslandSampler { + pub fn new(world_seed: i64) -> Self { + let mut random = LegacyRandom::new(world_seed); + random.consume_count(17_292); + Self { + noise: SimplexNoise::with_skipped_offsets(&mut random, true), + } + } + fn height(&self, x: i32, z: i32) -> f32 { + // These divisions and remainders truncate toward zero, including for + // negative coordinates. They are not block/chunk floor conversions. + let center_x = x / 2; + let center_z = z / 2; + let local_x = x % 2; + let local_z = z % 2; + let mut height = -100.0; + for offset_x in -12_i32..=12 { + for offset_z in -12_i32..=12 { + let island_x = i64::from(center_x.wrapping_add(offset_x)); + let island_z = i64::from(center_z.wrapping_add(offset_z)); + if island_x * island_x + island_z * island_z <= 4096 + || self.noise.get2(island_x as f64, island_z as f64) >= -0.9 + { + continue; + } + let scale = ((island_x as f32).abs() * 3439.0 + (island_z as f32).abs() * 147.0) + % 13.0 + + 9.0; + let dx = (local_x - offset_x * 2) as f32; + let dz = (local_z - offset_z * 2) as f32; + let candidate = 100.0 - ((dx * dx + dz * dz) as f64).sqrt() as f32 * scale; + let candidate = super::arithmetic::java_min( + super::arithmetic::java_max(candidate, -100.0), + 80.0, + ); + height = super::arithmetic::java_max(height, candidate); + } + } + height + } + fn density(&self, x: i32, z: i32) -> f32 { + (self.height(x / 8, z / 8) - 8.0) / 128.0 + } +} +impl DensitySampler for EndIslandSampler { + fn sample_value(&self, _: &mut SamplerContext, position: [i32; 3]) -> Result { + Ok(self.density(position[0], position[2])) + } + fn sample_volume( + &self, + _: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_buffer(buffer, volume)?; + let [sx, sy, sz] = volume.sizes(); + for z in 0..sz { + let block_z = volume.block(Axis::Z, z).unwrap(); + for x in 0..sx { + let value = self.density(volume.block(Axis::X, x).unwrap(), block_z); + let start = (x + z * sx) * sy; + buffer[start..start + sy].fill(value); + } + } + Ok(()) + } +} diff --git a/crates/horizon-core/src/density/graph/compiler.rs b/crates/horizon-core/src/density/graph/compiler.rs new file mode 100644 index 000000000..53d8fe2eb --- /dev/null +++ b/crates/horizon-core/src/density/graph/compiler.rs @@ -0,0 +1,498 @@ +use super::*; + +/// A compiler and cache-ID namespace for one immutable set of density inputs. +/// Share resulting samplers across workers, with a separate SamplerContext per +/// worker. Context cache cells must not be reused across compiler namespaces. +#[derive(Debug)] +pub struct DensityCompiler { + graph: DensityGraph, + samplers: HashMap>, + prepared: HashMap, + next_cache: usize, + context: Option, +} +impl DensityCompiler { + pub fn new(graph: DensityGraph) -> Self { + Self { + graph, + samplers: HashMap::new(), + prepared: HashMap::new(), + next_cache: 0, + context: None, + } + } + pub fn new_seeded(graph: DensityGraph, seed: i64, use_legacy_random: bool) -> Self { + let mut compiler = Self::new(graph); + compiler.context = Some(seeded::SeededContext::new(seed, use_legacy_random)); + compiler + } + pub fn graph(&self) -> &DensityGraph { + &self.graph + } + pub fn graph_mut(&mut self) -> &mut DensityGraph { + &mut self.graph + } + pub fn cache_count(&self) -> usize { + self.next_cache + } + /// Resolve a registered noise using this compiler's fixed world seed. + /// Ordinary names reuse their sampler; Nether biome compatibility names + /// create a fresh sampler from their dedicated legacy seed on each call. + pub fn get_noise_sampler(&self, noise: NoiseId) -> Result, CompileError> { + self.context + .as_ref() + .ok_or(CompileError::MissingSeededContext)? + .noise(&self.graph, noise) + } + pub fn get_sampler(&mut self, id: FunctionId) -> Result, CompileError> { + if let Some(sampler) = self.samplers.get(&id) { + return Ok(sampler.clone()); + } + let optimized = self.optimize(id)?; + let sampler = self.compile_raw(optimized)?; + self.samplers.insert(id, sampler.clone()); + Ok(sampler) + } + fn rewrite_children( + &mut self, + id: FunctionId, + mut rewrite: impl FnMut(&mut Self, FunctionId) -> Result, + ) -> Result { + let Definition::Node(mut node) = self.graph.entry(id)?.definition.clone() else { + return Ok(id); + }; + if let GraphNode::Reference { input, .. } = node { + let rewritten = rewrite(self, input)?; + return Ok(if rewritten == input { id } else { rewritten }); + } + for child in node.children_mut() { + *child = rewrite(self, *child)?; + } + self.graph.insert(node) + } + fn optimize(&mut self, id: FunctionId) -> Result { + let prepared = self.prepare(id)?; + self.slice_uniform_axes(prepared, 7) + } + fn prepare(&mut self, mut id: FunctionId) -> Result { + // Vanilla INLINE_REFERENCE unwraps one holder before detecting caches. + // Nested holders still follow their own rewriteChildren identity rule. + if let Definition::Node(GraphNode::Reference { input, .. }) = + self.graph.entry(id)?.definition + { + id = input; + } + if let Definition::Node(GraphNode::Cache(input)) = self.graph.entry(id)?.definition.clone() + { + if let Some(prepared) = self.prepared.get(&input) { + return Ok(*prepared); + } + let cache_id = self.next_cache; + self.next_cache += 1; + let optimized = self.optimize(input)?; + let sampler = self.compile_raw(optimized)?; + let sampler = Arc::new(CachingDensitySampler::new(cache_id, sampler)?); + let range = self.graph.range(optimized)?; + let axes = self.graph.domain_axes(optimized)?; + let prepared = self.graph.bind(sampler, range, axes)?; + self.prepared.insert(input, prepared); + return Ok(prepared); + } + self.rewrite_children(id, Self::prepare) + } + fn slice_uniform_axes( + &mut self, + id: FunctionId, + parent_axes: u8, + ) -> Result { + if matches!( + self.graph.entry(id)?.definition, + Definition::Node(GraphNode::Constant(_) | GraphNode::Gradient { .. }) + ) { + return Ok(id); + } + let axes = self.graph.domain_axes(id)?; + let mut result = self.rewrite_children(id, |compiler, child| { + compiler.slice_uniform_axes(child, axes) + })?; + if axes == parent_axes { + return Ok(result); + } + let mut existing = 0; + let mut cursor = result; + while let Definition::Node(GraphNode::Slice { axis, input, .. }) = + self.graph.entry(cursor)?.definition + { + existing |= 1 << axis as u8; + cursor = input; + } + let remove = parent_axes & !axes & !existing; + // X then Z places these slices adjacent for the XZ sampler specialization. + for axis in [Axis::X, Axis::Z, Axis::Y] { + if remove & (1 << axis as u8) != 0 { + result = self.graph.insert(GraphNode::Slice { + axis, + coordinate: 0, + input: result, + })?; + } + } + Ok(result) + } + fn constant(&self, id: FunctionId) -> Option { + match self.graph.entries[id.0].definition { + Definition::Node(GraphNode::Constant(value)) => Some(value), + _ => None, + } + } + /// Compile exactly the supplied definition, without rewriting. Cache nodes + /// require get_sampler's preparation pass and are rejected here. + pub fn compile_raw(&self, id: FunctionId) -> Result, CompileError> { + let node = match &self.graph.entry(id)?.definition { + Definition::Bound { sampler, .. } => return Ok(sampler.clone()), + Definition::Node(node) => node, + }; + let sampler: Arc = match *node { + GraphNode::Constant(value) => Arc::new(ConstantSampler(value)), + GraphNode::Reference { input, .. } => self.compile_raw(input)?, + GraphNode::WorldField(field) => Arc::new(ContextBoundSampler::new(field)), + GraphNode::BlendDensity(input) => Arc::new(BlendDensitySampler { + input: self.compile_raw(input)?, + }), + GraphNode::EndIslands => self + .context + .as_ref() + .ok_or(CompileError::MissingSeededContext)? + .end_islands(), + GraphNode::Noise { + noise, + xz_scale, + y_scale, + shift_x, + shift_y, + shift_z, + } => { + let noise = self + .context + .as_ref() + .ok_or(CompileError::MissingSeededContext)? + .noise(&self.graph, noise)?; + let zero = |id: FunctionId| matches!(self.graph.entries[id.0].definition, Definition::Node(GraphNode::Constant(value)) if value.to_bits() == 0); + if zero(shift_x) && zero(shift_y) && zero(shift_z) { + Arc::new(NoiseSampler { + noise, + xz_scale, + y_scale, + }) + } else { + // Compilation order differs from the XYZ sampler's sampling + // order: vanilla compiles X, then Z, then optional Y. + let x = self.compile_raw(shift_x)?; + let z = self.compile_raw(shift_z)?; + let y = if zero(shift_y) { + None + } else { + Some(self.compile_raw(shift_y)?) + }; + Arc::new(ShiftedNoiseSampler { + source: NoiseSampler { + noise, + xz_scale, + y_scale, + }, + shift_x: x, + shift_y: y, + shift_z: z, + }) + } + } + GraphNode::OffsetNoise { noise, kind } => compile_shift_noise( + self.context + .as_ref() + .ok_or(CompileError::MissingSeededContext)? + .noise(&self.graph, noise)?, + kind, + ), + GraphNode::BlendedNoise(definition) => self + .context + .as_ref() + .ok_or(CompileError::MissingSeededContext)? + .blended(definition)?, + GraphNode::Spline(ref spline) => { + let mut ids = HashMap::new(); + let mut coordinates = Vec::new(); + let compiled = spline.try_map_coordinates(&mut |id| { + if let Some(index) = ids.get(&id) { + return Ok::(*index); + } + let sampler = self.compile_raw(id)?; + // Vanilla validates each unique coordinate range immediately + // after compiling it, even if sampling never selects it. + self.graph.range(id)?; + let index = coordinates.len(); + coordinates.push(sampler); + ids.insert(id, index); + Ok(index) + })?; + Arc::new(SplineSampler::new(&compiled, &coordinates)?) + } + GraphNode::DistanceToPoint { point, metric } => { + Arc::new(DistanceToPointSampler { point, metric }) + } + GraphNode::IntervalSelect { + input, + ref thresholds, + ref branches, + } => { + let input = self.compile_raw(input)?; + let branches = branches + .iter() + .map(|id| self.compile_raw(*id)) + .collect::, _>>()?; + Arc::new( + IntervalSelectSampler::new(input, thresholds.to_vec(), branches) + .map_err(|_| CompileError::InvalidIntervals)?, + ) + } + GraphNode::Gradient { + axis, + tiling, + from, + to, + low, + high, + } => Arc::new(GradientSampler::new(axis, tiling, from, to, low, high)), + GraphNode::Unary { kind, input } => Arc::new(UnarySampler { + input: self.compile_raw(input)?, + operation: kind.operation(), + }), + GraphNode::Round { + mode, + input, + multiple, + } => { + let input = self.compile_raw(input)?; + let multiple = if self.constant(multiple) == Some(1.0) { + None + } else { + Some(self.compile_raw(multiple)?) + }; + Arc::new(RoundSampler { + mode, + input, + multiple, + }) + } + GraphNode::Power { base, exponent } => { + // Both children compile before literal selection, even when one + // compiled child will be discarded by the specialization. + let compiled_base = self.compile_raw(base)?; + let compiled_exponent = self.compile_raw(exponent)?; + if let Some(value) = self.constant(base) { + Arc::new(UnarySampler { + input: compiled_exponent, + operation: UnaryOp::PowerBase(value as f64), + }) + } else if let Some(value) = self.constant(exponent) { + compile_constant_exponent(compiled_base, value) + } else { + Arc::new(PowerSampler { + base: compiled_base, + exponent: compiled_exponent, + }) + } + } + GraphNode::Binary { kind, left, right } => { + return self.compile_binary(kind, left, right); + } + GraphNode::Clamp { input, min, max } => Arc::new(UnarySampler { + input: self.compile_raw(input)?, + operation: UnaryOp::Clamp { min, max }, + }), + GraphNode::Choice { + input, + min, + max, + inside, + outside, + } => { + let input = self.compile_raw(input)?; + if let (Some(inside), Some(outside)) = + (self.constant(inside), self.constant(outside)) + { + Arc::new(UnarySampler { + input, + operation: UnaryOp::ConstantRangeChoice { + min_inclusive: min, + max_exclusive: max, + inside, + outside, + }, + }) + } else { + Arc::new(RangeChoiceSampler { + input, + min_inclusive: min, + max_exclusive: max, + when_in_range: self.compile_raw(inside)?, + when_out_of_range: self.compile_raw(outside)?, + }) + } + } + GraphNode::Lerp { + alpha, + first, + second, + } => { + let alpha = self.compile_raw(alpha)?; + let first_sampler = self.compile_raw(first)?; + let second_sampler = self.compile_raw(second)?; + let (first, second) = if let Some(value) = self.constant(first) { + ( + DensityValue::Constant(value), + DensityValue::Sampler(second_sampler), + ) + } else if let Some(value) = self.constant(second) { + ( + DensityValue::Sampler(first_sampler), + DensityValue::Constant(value), + ) + } else { + ( + DensityValue::Sampler(first_sampler), + DensityValue::Sampler(second_sampler), + ) + }; + Arc::new(LerpSampler { + alpha, + first, + second, + }) + } + GraphNode::Slice { + axis, + coordinate, + input, + } => { + let mut axes = match axis { + Axis::X => SliceAxes::X(coordinate), + Axis::Y => SliceAxes::Y(coordinate), + Axis::Z => SliceAxes::Z(coordinate), + }; + let mut child = input; + if let Definition::Node(GraphNode::Slice { + axis: inner_axis, + coordinate: inner_coordinate, + input: inner, + }) = self.graph.entry(input)?.definition + { + if axis == Axis::X && inner_axis == Axis::Z { + axes = SliceAxes::Xz { + x: coordinate, + z: inner_coordinate, + }; + child = inner; + } else if axis == Axis::Z && inner_axis == Axis::X { + axes = SliceAxes::Xz { + x: inner_coordinate, + z: coordinate, + }; + child = inner; + } + } + Arc::new(SliceSampler { + axes, + input: self.compile_raw(child)?, + }) + } + GraphNode::Cache(_) => return Err(CompileError::UnpreparedCache), + GraphNode::Interpolated { input, xz, y } => { + Arc::new(InterpolatedSampler::new(self.compile_raw(input)?, xz, y)?) + } + GraphNode::Surface { + density, + upper, + lower, + height, + } => Arc::new(compile_surface_search( + self.compile_raw(density)?, + self.compile_raw(upper)?, + lower, + height, + )?), + }; + Ok(sampler) + } + fn compile_binary( + &self, + kind: GraphBinary, + left_id: FunctionId, + right_id: FunctionId, + ) -> Result, CompileError> { + let left = self.compile_raw(left_id)?; + let right = self.compile_raw(right_id)?; + let unary = |input, operation| { + Arc::new(UnarySampler { input, operation }) as Arc + }; + let bounds = if matches!(kind, GraphBinary::Minimum | GraphBinary::Maximum) { + let a = self.graph.range(left_id)?; + let b = self.graph.range(right_id)?; + if (kind == GraphBinary::Minimum && a.max() < b.min()) + || (kind == GraphBinary::Maximum && a.min() > b.max()) + { + return Ok(left); + } + if (kind == GraphBinary::Minimum && b.max() < a.min()) + || (kind == GraphBinary::Maximum && b.min() > a.max()) + { + return Ok(right); + } + Some(b) + } else { + None + }; + if let Some(value) = self.constant(left_id) { + return Ok(unary( + right, + match kind { + GraphBinary::Add => UnaryOp::Add(value), + GraphBinary::Subtract => UnaryOp::SubtractFrom(value), + GraphBinary::Multiply => UnaryOp::Multiply(value), + GraphBinary::Divide => UnaryOp::DivideInto(value), + GraphBinary::Minimum => UnaryOp::Minimum(value), + GraphBinary::Maximum => UnaryOp::Maximum(value), + }, + )); + } + if let Some(value) = self.constant(right_id) { + return Ok(unary( + left, + match kind { + GraphBinary::Add => UnaryOp::Add(value), + GraphBinary::Subtract => UnaryOp::Add(-value), + GraphBinary::Multiply => UnaryOp::Multiply(value), + GraphBinary::Divide => UnaryOp::Multiply(1.0 / value), + GraphBinary::Minimum => UnaryOp::Minimum(value), + GraphBinary::Maximum => UnaryOp::Maximum(value), + }, + )); + } + let operation = match kind { + GraphBinary::Add => BinaryOp::Add, + GraphBinary::Subtract => BinaryOp::Subtract, + GraphBinary::Multiply => BinaryOp::Multiply, + GraphBinary::Divide => BinaryOp::Divide, + GraphBinary::Minimum => BinaryOp::Minimum { + right_min: bounds.unwrap().min(), + }, + GraphBinary::Maximum => BinaryOp::Maximum { + right_max: bounds.unwrap().max(), + }, + }; + Ok(Arc::new(BinarySampler { + left, + right, + operation, + })) + } +} diff --git a/crates/horizon-core/src/density/graph/mod.rs b/crates/horizon-core/src/density/graph/mod.rs new file mode 100644 index 000000000..8eefe2d1d --- /dev/null +++ b/crates/horizon-core/src/density/graph/mod.rs @@ -0,0 +1,712 @@ +//! Immutable density definitions and the first integrated compiler operations. +//! Seeded noise registration is supported; serialized codecs and remaining +//! function kinds are pending. +use super::*; +use std::collections::HashMap; +mod compiler; +mod seeded; +#[cfg(test)] +mod tests; +pub use compiler::DensityCompiler; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct FunctionId(usize); +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct NoiseId(usize); +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct HolderId(usize); + +#[derive(Clone, Copy, Debug)] +pub enum GraphUnary { + Abs, + Square, + Cube, + HalfNegative, + QuarterNegative, + Reciprocal, + Negate, + Squeeze, + Sign, + Log, + Sqrt, +} +impl GraphUnary { + fn operation(self) -> UnaryOp { + match self { + Self::Abs => UnaryOp::Abs, + Self::Square => UnaryOp::Square, + Self::Cube => UnaryOp::Cube, + Self::HalfNegative => UnaryOp::LeakyRelu(0.5), + Self::QuarterNegative => UnaryOp::LeakyRelu(0.25), + Self::Reciprocal => UnaryOp::Reciprocal, + Self::Negate => UnaryOp::Negate, + Self::Squeeze => UnaryOp::Squeeze, + Self::Sign => UnaryOp::Sign, + Self::Log => UnaryOp::Log, + Self::Sqrt => UnaryOp::Sqrt, + } + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GraphBinary { + Add, + Subtract, + Multiply, + Divide, + Minimum, + Maximum, +} + +/// References belong to the graph that creates them. New nodes may refer only +/// to existing immutable nodes, keeping the definition graph acyclic. +#[derive(Clone, Debug)] +pub enum GraphNode { + Constant(f32), + Spline(CubicSpline), + Noise { + noise: NoiseId, + xz_scale: f64, + y_scale: f64, + shift_x: FunctionId, + shift_y: FunctionId, + shift_z: FunctionId, + }, + OffsetNoise { + noise: NoiseId, + kind: ShiftNoiseKind, + }, + BlendedNoise(BlendedNoise), + EndIslands, + WorldField(WorldField), + BlendDensity(FunctionId), + /// A direct holder compares by value; a registry holder by identity. + Reference { + input: FunctionId, + holder: Option, + }, + Gradient { + axis: Axis, + tiling: TilingMode, + from: i32, + to: i32, + low: f32, + high: f32, + }, + Unary { + kind: GraphUnary, + input: FunctionId, + }, + Binary { + kind: GraphBinary, + left: FunctionId, + right: FunctionId, + }, + Round { + mode: RoundMode, + input: FunctionId, + multiple: FunctionId, + }, + Power { + base: FunctionId, + exponent: FunctionId, + }, + Clamp { + input: FunctionId, + min: f32, + max: f32, + }, + Choice { + input: FunctionId, + min: f32, + max: f32, + inside: FunctionId, + outside: FunctionId, + }, + Lerp { + alpha: FunctionId, + first: FunctionId, + second: FunctionId, + }, + Slice { + axis: Axis, + coordinate: i32, + input: FunctionId, + }, + Cache(FunctionId), + Interpolated { + input: FunctionId, + xz: i32, + y: i32, + }, + Surface { + density: FunctionId, + upper: FunctionId, + lower: i32, + height: i32, + }, + IntervalSelect { + input: FunctionId, + thresholds: Arc<[f32]>, + branches: Vec, + }, + DistanceToPoint { + point: [i32; 3], + metric: DistanceMetric, + }, +} +impl GraphNode { + fn children_mut(&mut self) -> Vec<&mut FunctionId> { + match self { + Self::Spline(spline) => spline.coordinates_mut(), + Self::Constant(_) + | Self::Gradient { .. } + | Self::DistanceToPoint { .. } + | Self::OffsetNoise { .. } + | Self::BlendedNoise(_) + | Self::EndIslands + | Self::WorldField(_) => vec![], + Self::Noise { + shift_x, + shift_y, + shift_z, + .. + } => vec![shift_x, shift_y, shift_z], + Self::Reference { input, .. } + | Self::Unary { input, .. } + | Self::Clamp { input, .. } + | Self::Slice { input, .. } + | Self::Cache(input) + | Self::BlendDensity(input) + | Self::Interpolated { input, .. } => vec![input], + Self::Binary { left, right, .. } => vec![left, right], + Self::Round { + input, multiple, .. + } => vec![input, multiple], + Self::Power { base, exponent } => vec![base, exponent], + Self::Choice { + input, + inside, + outside, + .. + } => vec![input, inside, outside], + Self::Lerp { + alpha, + first, + second, + } => vec![alpha, first, second], + Self::Surface { density, upper, .. } => vec![density, upper], + Self::IntervalSelect { + input, branches, .. + } => std::iter::once(input).chain(branches.iter_mut()).collect(), + } + } + fn key(&self) -> Vec { + let f = |v: f32| u64::from(if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() }); + let i = |v: i32| u64::from(v as u32); + let d = |v: f64| { + if v.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + v.to_bits() + } + }; + let id = |v: FunctionId| v.0 as u64; + match *self { + Self::Reference { input, holder } => match holder { + Some(holder) => vec![22, 1, holder.0 as u64], + None => vec![22, 0, id(input)], + }, + Self::EndIslands => vec![17], + Self::WorldField(field) => vec![20, field as u64], + Self::BlendDensity(input) => vec![21, id(input)], + Self::Power { base, exponent } => vec![19, id(base), id(exponent)], + Self::Round { + mode, + input, + multiple, + } => vec![18, mode as u64, id(input), id(multiple)], + Self::Noise { + noise, + xz_scale, + y_scale, + shift_x, + shift_y, + shift_z, + } => vec![ + 14, + noise.0 as u64, + d(xz_scale), + d(y_scale), + id(shift_x), + id(shift_y), + id(shift_z), + ], + Self::OffsetNoise { noise, kind } => vec![15, noise.0 as u64, kind as u64], + Self::BlendedNoise(v) => vec![ + 16, + d(v.xz_scale), + d(v.y_scale), + d(v.xz_factor), + d(v.y_factor), + d(v.smear_scale_multiplier), + ], + Self::Spline(ref spline) => { + fn append(spline: &CubicSpline, key: &mut Vec) { + let bits = + |v: f32| u64::from(if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() }); + match spline { + CubicSpline::Constant(value) => key.extend([0, bits(*value)]), + CubicSpline::Multipoint(node) => { + key.extend([1, node.coordinate.0 as u64, node.points.len() as u64]); + for point in &node.points { + key.extend([bits(point.location), bits(point.derivative)]); + append(&point.value, key); + } + } + } + } + let mut key = vec![13]; + append(spline, &mut key); + key + } + Self::Constant(v) => vec![0, f(v)], + Self::Gradient { + axis, + tiling, + from, + to, + low, + high, + } => vec![ + 1, + axis as u64, + tiling as u64, + i(from), + i(to), + f(low), + f(high), + ], + Self::Unary { kind, input } => vec![2, kind as u64, id(input)], + Self::Binary { kind, left, right } => vec![3, kind as u64, id(left), id(right)], + Self::Clamp { input, min, max } => vec![4, id(input), f(min), f(max)], + Self::Choice { + input, + min, + max, + inside, + outside, + } => vec![5, id(input), f(min), f(max), id(inside), id(outside)], + Self::Lerp { + alpha, + first, + second, + } => vec![6, id(alpha), id(first), id(second)], + Self::Slice { + axis, + coordinate, + input, + } => vec![7, axis as u64, i(coordinate), id(input)], + Self::Cache(input) => vec![8, id(input)], + Self::Interpolated { input, xz, y } => vec![9, id(input), i(xz), i(y)], + Self::Surface { + density, + upper, + lower, + height, + } => vec![10, id(density), id(upper), i(lower), i(height)], + Self::IntervalSelect { + input, + ref thresholds, + ref branches, + } => { + let mut key = vec![11, id(input), thresholds.len() as u64]; + key.push(if thresholds.iter().any(|v| v.is_nan()) { + Arc::as_ptr(thresholds) as *const f32 as usize as u64 + } else { + 0 + }); + key.extend(thresholds.iter().map(|v| if *v == 0.0 { 0 } else { f(*v) })); + key.extend(branches.iter().copied().map(id)); + key + } + Self::DistanceToPoint { point, metric } => { + vec![12, i(point[0]), i(point[1]), i(point[2]), metric as u64] + } + } + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CompileError { + UnknownFunction, + NestingTooDeep, + InvalidAxes, + UnpreparedCache, + InvalidIntervals, + UnknownNoise, + DuplicateNoise, + DuplicateFunction, + UnknownHolder, + MissingSeededContext, + PoisonedNoiseCache, + Noise(crate::noise::NoiseBuildError), + Spline(SplineError), + Range(IntervalError), + Sample(SampleError), +} +impl From for CompileError { + fn from(e: IntervalError) -> Self { + Self::Range(e) + } +} +impl From for CompileError { + fn from(e: SampleError) -> Self { + Self::Sample(e) + } +} +impl From for CompileError { + fn from(e: SplineError) -> Self { + Self::Spline(e) + } +} +impl From for CompileError { + fn from(e: crate::noise::NoiseBuildError) -> Self { + Self::Noise(e) + } +} +impl std::fmt::Display for CompileError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "density graph compilation failed: {self:?}") + } +} +impl std::error::Error for CompileError {} + +#[derive(Clone, Debug)] +enum Definition { + Node(GraphNode), + Bound { + sampler: Arc, + range: Interval, + axes: u8, + }, +} +#[derive(Clone, Debug)] +struct Entry { + definition: Definition, + depth: usize, + equality_id: FunctionId, + hash_variant: bool, +} +#[derive(Clone, Debug, Default)] +pub struct DensityGraph { + entries: Vec, + interned: HashMap<(Vec, bool), FunctionId>, + equal: HashMap, FunctionId>, + noises: Vec, + noise_names: HashMap, + holders: Vec, + function_names: HashMap, +} +impl DensityGraph { + pub fn new() -> Self { + Self::default() + } + pub fn insert(&mut self, node: GraphNode) -> Result { + if let GraphNode::Reference { + input, + holder: Some(holder), + } = node + { + if self.holders.get(holder.0) != Some(&input) { + return Err(CompileError::UnknownHolder); + } + } + if let GraphNode::Noise { noise, .. } | GraphNode::OffsetNoise { noise, .. } = node { + self.noise_entry(noise)?; + } + if let GraphNode::IntervalSelect { + thresholds, + branches, + .. + } = &node + { + if branches.len() != thresholds.len().saturating_add(1) || branches.len() > 256 { + return Err(CompileError::InvalidIntervals); + } + } + // Fastutil threshold lists compare zeros numerically but hash their + // signed bits. Among equal definitions, the only possible hash delta + // is 0x80000000. Java record/list hashes use odd (31) multipliers, so + // these deltas XOR through children and cancel in pairs. Keep equality + // classes separate from this hash variant to reproduce Java map reuse, + // including equal parents whose differing child hashes cancel. + let mut hash_variant = match &node { + GraphNode::IntervalSelect { thresholds, .. } => { + thresholds + .iter() + .filter(|v| v.to_bits() == 0x8000_0000) + .count() + % 2 + != 0 + } + _ => false, + }; + let mut canonical = node.clone(); + let mut depth = if let GraphNode::Spline(spline) = &node { + fn spline_depth( + spline: &CubicSpline, + graph: &DensityGraph, + ) -> Result { + Ok(match spline { + CubicSpline::Constant(_) => 0, + CubicSpline::Multipoint(node) => { + let mut depth = graph.entry(node.coordinate)?.depth; + for point in &node.points { + depth = depth.max(spline_depth(&point.value, graph)?); + } + depth + 1 + } + }) + } + spline_depth(spline, self)? + 1 + } else { + 1 + }; + for child in canonical.children_mut() { + let entry = self.entry(*child)?; + depth = depth.max(entry.depth + 1); + // Registry references hash their holder identity, not its value. + if !matches!( + node, + GraphNode::Reference { + holder: Some(_), + .. + } + ) { + hash_variant ^= entry.hash_variant; + } + *child = entry.equality_id; + } + let key = canonical.key(); + if let Some(id) = self.interned.get(&(key.clone(), hash_variant)) { + return Ok(*id); + } + if depth > 256 { + return Err(CompileError::NestingTooDeep); + } + let id = FunctionId(self.entries.len()); + let equality_id = *self.equal.entry(key.clone()).or_insert(id); + self.entries.push(Entry { + definition: Definition::Node(node), + depth, + equality_id, + hash_variant, + }); + self.interned.insert((key, hash_variant), id); + Ok(id) + } + /// Bind a precompiled input with its declared range and axis dependency + /// mask (X=1, Y=2, Z=4). Each binding has distinct function identity. + pub fn bind( + &mut self, + sampler: Arc, + range: Interval, + axes: u8, + ) -> Result { + if axes & !7 != 0 { + return Err(CompileError::InvalidAxes); + } + let id = FunctionId(self.entries.len()); + self.entries.push(Entry { + definition: Definition::Bound { + sampler, + range, + axes, + }, + depth: 1, + equality_id: id, + hash_variant: false, + }); + Ok(id) + } + fn entry(&self, id: FunctionId) -> Result<&Entry, CompileError> { + self.entries.get(id.0).ok_or(CompileError::UnknownFunction) + } + /// Register a noise under its canonical namespaced registry identifier. + /// Definitions and names are immutable after registration. + pub fn register_noise( + &mut self, + name: String, + definition: crate::noise::NormalNoise, + ) -> Result { + if self.noise_names.contains_key(&name) { + return Err(CompileError::DuplicateNoise); + } + let id = NoiseId(self.noises.len()); + self.noise_names.insert(name.clone(), id); + self.noises.push(seeded::NoiseEntry { name, definition }); + Ok(id) + } + /// Register an immutable named density value and return its holder wrapper. + /// Names must already be canonical namespaced registry identifiers. + pub fn register_function( + &mut self, + name: String, + input: FunctionId, + ) -> Result { + if self.function_names.contains_key(&name) { + return Err(CompileError::DuplicateFunction); + } + self.entry(input)?; + let holder = HolderId(self.holders.len()); + self.holders.push(input); + let result = self.insert(GraphNode::Reference { + input, + holder: Some(holder), + }); + match result { + Ok(id) => { + self.function_names.insert(name, id); + Ok(id) + } + Err(error) => { + self.holders.pop(); + Err(error) + } + } + } + pub fn function(&self, name: &str) -> Option { + self.function_names.get(name).copied() + } + fn noise_entry(&self, id: NoiseId) -> Result<&seeded::NoiseEntry, CompileError> { + self.noises.get(id.0).ok_or(CompileError::UnknownNoise) + } + /// Vanilla definition equality, separate from interned identity. Interval + /// threshold lists can compare equal despite having different Java hashes. + pub fn java_equals(&self, left: FunctionId, right: FunctionId) -> Result { + Ok(self.entry(left)?.equality_id == self.entry(right)?.equality_id) + } + pub fn domain_axes(&self, id: FunctionId) -> Result { + let mut node = match &self.entry(id)?.definition { + Definition::Bound { axes, .. } => return Ok(*axes), + Definition::Node(node) => node.clone(), + }; + let mask = match node { + GraphNode::EndIslands => return Ok(5), + GraphNode::WorldField(field) => return Ok(field.domain_axes()), + GraphNode::OffsetNoise { kind, .. } => { + return Ok(if kind == ShiftNoiseKind::Shift { 7 } else { 5 }); + } + GraphNode::BlendedNoise(_) => return Ok(7), + GraphNode::Noise { + xz_scale, y_scale, .. + } => { + let mut axes = if xz_scale == 0.0 { 0 } else { 5 }; + if y_scale != 0.0 { + axes |= 2; + } + for child in node.children_mut() { + axes |= self.domain_axes(*child)?; + } + return Ok(axes); + } + GraphNode::Constant(_) => return Ok(0), + GraphNode::Gradient { axis, .. } => return Ok(1 << axis as u8), + GraphNode::DistanceToPoint { .. } => return Ok(7), + GraphNode::Slice { axis, .. } => !(1 << axis as u8), + GraphNode::Surface { .. } => !2, + _ => 7, + }; + let mut axes = 0; + for child in node.children_mut() { + axes |= self.domain_axes(*child)?; + } + Ok(axes & mask) + } + pub fn range(&self, id: FunctionId) -> Result { + let node = match &self.entry(id)?.definition { + Definition::Bound { range, .. } => return Ok(*range), + Definition::Node(node) => node, + }; + Ok(match *node { + GraphNode::EndIslands => Interval::new(-0.84375, 0.5625)?, + GraphNode::WorldField(field) => field.range(), + GraphNode::Noise { noise, .. } => { + let [min, max] = self.noise_entry(noise)?.definition.range(); + Interval::new(min, max)? + } + GraphNode::OffsetNoise { noise, .. } => { + let [min, max] = self.noise_entry(noise)?.definition.range(); + Interval::new(min, max)?.multiply_range(Interval::exact(4.0)?) + } + GraphNode::BlendedNoise(definition) => definition.range()?, + GraphNode::Spline(ref spline) => spline.try_range(&mut |id| self.range(id))?, + GraphNode::Constant(v) => Interval::exact(v)?, + GraphNode::Gradient { low, high, .. } => Interval::encapsulating_values(low, high), + GraphNode::DistanceToPoint { .. } => Interval::new(0.0, f32::INFINITY)?, + GraphNode::IntervalSelect { ref branches, .. } => { + let ranges = branches + .iter() + .map(|id| self.range(*id)) + .collect::, _>>()?; + Interval::encapsulating(&ranges)? + } + GraphNode::Unary { kind, input } => { + let range = self.range(input)?; + match kind { + GraphUnary::Abs => range.abs(), + GraphUnary::Square => range.square(), + GraphUnary::Reciprocal => range.reciprocal(), + GraphUnary::Sign => range.sign(), + GraphUnary::Negate => Interval::exact(0.0)?.subtract_range(range), + GraphUnary::Log => range.log()?, + GraphUnary::Sqrt => range.power(Interval::exact(0.5)?), + _ => range.map_monotonic(|v| kind.operation().apply(v, false))?, + } + } + GraphNode::Binary { kind, left, right } => { + let left = self.range(left)?; + let right = self.range(right)?; + match kind { + GraphBinary::Add => left.add_range(right), + GraphBinary::Subtract => left.subtract_range(right), + GraphBinary::Multiply => left.multiply_range(right), + GraphBinary::Divide => left.divide_range(right), + GraphBinary::Minimum => left.minimum(right), + GraphBinary::Maximum => left.maximum(right), + } + } + GraphNode::Round { + mode, + input, + multiple, + } => { + let multiple = self.range(multiple)?; + self.range(input)? + .divide_range(multiple) + .map_monotonic(|v| mode.integer(v))? + .multiply_range(multiple) + } + GraphNode::Power { base, exponent } => self.range(base)?.power(self.range(exponent)?), + GraphNode::Clamp { input, min, max } => self.range(input)?.clamp(min, max)?, + GraphNode::Choice { + inside, outside, .. + } => Interval::encapsulating(&[self.range(inside)?, self.range(outside)?])?, + GraphNode::Lerp { + alpha, + first, + second, + } => self + .range(alpha)? + .lerp_ranges(self.range(first)?, self.range(second)?), + GraphNode::Slice { input, .. } + | GraphNode::Cache(input) + | GraphNode::BlendDensity(input) + | GraphNode::Reference { input, .. } + | GraphNode::Interpolated { input, .. } => self.range(input)?, + GraphNode::Surface { upper, lower, .. } => Interval::new( + lower as f32, + super::arithmetic::java_max(lower as f32, self.range(upper)?.max()), + )?, + }) + } +} diff --git a/crates/horizon-core/src/density/graph/seeded.rs b/crates/horizon-core/src/density/graph/seeded.rs new file mode 100644 index 000000000..17d66ce0f --- /dev/null +++ b/crates/horizon-core/src/density/graph/seeded.rs @@ -0,0 +1,97 @@ +use super::*; +use crate::{ + noise::NormalNoise, + random::{ + LegacyPositionalRandom, LegacyRandom, PositionalRandom, RandomSource, + XoroshiroPositionalRandom, XoroshiroRandom, + }, +}; +use std::sync::Mutex; + +#[derive(Debug)] +enum Factory { + Legacy(LegacyPositionalRandom), + Xoroshiro(XoroshiroPositionalRandom), +} + +/// The seed-dependent portion of vanilla's RandomState compile context. +#[derive(Debug)] +pub(super) struct SeededContext { + seed: i64, + factory: Factory, + instances: Mutex>>, +} +impl SeededContext { + pub(super) fn end_islands(&self) -> Arc { + Arc::new(EndIslandSampler::new(self.seed)) + } + pub(super) fn new(seed: i64, legacy: bool) -> Self { + let factory = if legacy { + Factory::Legacy(LegacyRandom::new(seed).fork_positional()) + } else { + Factory::Xoroshiro(XoroshiroRandom::new(seed).fork_positional()) + }; + Self { + seed, + factory, + instances: Mutex::new(HashMap::new()), + } + } + pub(super) fn noise( + &self, + graph: &DensityGraph, + id: NoiseId, + ) -> Result, CompileError> { + let entry = graph.noise_entry(id)?; + // Nether biome compatibility samplers are recreated on every lookup; + // vanilla bypasses its normal named-noise instance map for these keys. + let legacy_offset = match entry.name.as_str() { + "minecraft:nether/temperature" => Some(0), + "minecraft:nether/vegetation" => Some(1), + _ => None, + }; + if let Some(offset) = legacy_offset { + return Ok(Arc::new(entry.definition.create_for_legacy_nether_biome( + &mut LegacyRandom::new(self.seed.wrapping_add(offset)), + )?)); + } + let mut instances = self + .instances + .lock() + .map_err(|_| CompileError::PoisonedNoiseCache)?; + if let Some(noise) = instances.get(&id) { + return Ok(noise.clone()); + } + let noise: Arc = match &self.factory { + Factory::Legacy(factory) => Arc::new( + entry + .definition + .create(&mut factory.from_hash_of(&entry.name))?, + ), + Factory::Xoroshiro(factory) => Arc::new( + entry + .definition + .create(&mut factory.from_hash_of(&entry.name))?, + ), + }; + instances.insert(id, noise.clone()); + Ok(noise) + } + pub(super) fn blended( + &self, + definition: BlendedNoise, + ) -> Result, CompileError> { + Ok(match &self.factory { + Factory::Legacy(_) => Arc::new(definition.compile(&mut LegacyRandom::new(self.seed))?), + Factory::Xoroshiro(factory) => { + Arc::new(definition.compile(&mut factory.from_hash_of("minecraft:terrain"))?) + } + }) + } +} + +#[derive(Clone, Debug)] +pub(super) struct NoiseEntry { + pub(super) name: String, + pub(super) definition: NormalNoise, +} diff --git a/crates/horizon-core/src/density/graph/tests.rs b/crates/horizon-core/src/density/graph/tests.rs new file mode 100644 index 000000000..4f3358460 --- /dev/null +++ b/crates/horizon-core/src/density/graph/tests.rs @@ -0,0 +1,552 @@ +use super::*; +use std::sync::Mutex; + +#[test] +fn power_literal_selection_retains_signed_zeros_and_negative_fallback_behavior() { + let signaling_base = UnarySampler { + input: Arc::new(ConstantSampler(0.0)), + operation: UnaryOp::PowerBase(f64::from_bits(0x7ff4_0000_2000_0000)), + }; + assert_eq!( + signaling_base.sample_value(&mut SamplerContext::default(), [0; 3]), + Ok(1.0) + ); + let mut graph = DensityGraph::new(); + let negative_zero = graph.insert(GraphNode::Constant(-0.0)).unwrap(); + let two = graph.insert(GraphNode::Constant(2.0)).unwrap(); + let half = graph.insert(GraphNode::Constant(0.5)).unwrap(); + let minus_four = graph.insert(GraphNode::Constant(-4.0)).unwrap(); + let bound_zero = graph + .bind( + Arc::new(ConstantSampler(-0.0)), + Interval::exact(-0.0).unwrap(), + 7, + ) + .unwrap(); + let bound_two = graph + .bind( + Arc::new(ConstantSampler(2.0)), + Interval::exact(2.0).unwrap(), + 7, + ) + .unwrap(); + let roots = [ + (negative_zero, half), + (bound_zero, half), + (two, minus_four), + (bound_two, minus_four), + ] + .map(|(base, exponent)| graph.insert(GraphNode::Power { base, exponent }).unwrap()); + let cached_half = graph.insert(GraphNode::Cache(half)).unwrap(); + let invalid_raw = graph + .insert(GraphNode::Power { + base: two, + exponent: cached_half, + }) + .unwrap(); + let compiler = DensityCompiler::new(graph); + assert_eq!( + compiler.compile_raw(invalid_raw).unwrap_err(), + CompileError::UnpreparedCache + ); + for (root, expected) in roots.into_iter().zip([0.0_f32, -0.0, 0.0625, 0.0625]) { + let value = compiler + .compile_raw(root) + .unwrap() + .sample_value(&mut SamplerContext::default(), [0; 3]) + .unwrap(); + assert_eq!(value.to_bits(), expected.to_bits()); + } + let sampler = PowerSampler { + base: Arc::new(ConstantSampler(0.0)), + exponent: Arc::new(FailingSampler), + }; + assert_eq!( + sampler.sample_value(&mut SamplerContext::default(), [0; 3]), + Err(SampleError::ZeroGradientPeriod) + ); + let mut output = [17.0]; + let volume = DensityVolume::new([1; 3], [0; 3], [1; 3]).unwrap(); + assert_eq!( + sampler.sample_volume(&mut SamplerContext::default(), &mut output, volume), + Err(SampleError::ZeroGradientPeriod) + ); + assert_eq!(output, [0.0]); +} + +#[test] +fn rounding_specializes_only_literal_one_and_preserves_input_on_multiple_failure() { + let mut graph = DensityGraph::new(); + let input = graph.insert(GraphNode::Constant(0.5)).unwrap(); + let one = graph.insert(GraphNode::Constant(1.0)).unwrap(); + let bound = graph + .bind( + Arc::new(ConstantSampler(1.0)), + Interval::exact(1.0).unwrap(), + 0, + ) + .unwrap(); + let failing = graph + .bind(Arc::new(FailingSampler), Interval::INFINITE, 7) + .unwrap(); + let roots = [one, bound, failing].map(|multiple| { + graph + .insert(GraphNode::Round { + mode: RoundMode::Round, + input, + multiple, + }) + .unwrap() + }); + let compiler = DensityCompiler::new(graph); + let volume = DensityVolume::new([1; 3], [0; 3], [1; 3]).unwrap(); + let mut output = [17.0; 2]; + compiler + .compile_raw(roots[0]) + .unwrap() + .sample_volume(&mut SamplerContext::default(), &mut output, volume) + .unwrap(); + assert_eq!(output, [1.0; 2]); + assert_eq!( + compiler.compile_raw(roots[1]).unwrap().sample_volume( + &mut SamplerContext::default(), + &mut output, + volume + ), + Err(SampleError::ExactBufferSizeRequired) + ); + assert_eq!( + compiler.compile_raw(roots[2]).unwrap().sample_volume( + &mut SamplerContext::default(), + &mut output[..1], + volume + ), + Err(SampleError::ZeroGradientPeriod) + ); + assert_eq!(output[0], 0.5); +} + +#[test] +fn end_islands_use_the_world_seed_independently_of_the_noise_algorithm() { + let mut graph = DensityGraph::new(); + let root = graph.insert(GraphNode::EndIslands).unwrap(); + assert_eq!(graph.domain_axes(root), Ok(5)); + assert_eq!( + graph.range(root).unwrap(), + Interval::new(-0.84375, 0.5625).unwrap() + ); + assert_eq!( + DensityCompiler::new(graph.clone()) + .compile_raw(root) + .unwrap_err(), + CompileError::MissingSeededContext + ); + let volume = DensityVolume::new([3, 4, 2], [-2049, -64, 4096], [17, 8, 31]).unwrap(); + let mut outputs = Vec::new(); + for legacy in [false, true] { + let mut compiler = DensityCompiler::new_seeded(graph.clone(), i64::MIN, legacy); + let sampler = compiler.get_sampler(root).unwrap(); + let mut output = vec![17.0; volume.size() + 1]; + sampler + .sample_volume(&mut SamplerContext::default(), &mut output, volume) + .unwrap(); + for column in output[..volume.size()].chunks_exact(4) { + assert!(column.iter().all(|&value| value == column[0])); + } + assert_eq!(output[volume.size()], 17.0); + outputs.push(output); + } + assert_eq!(outputs[0], outputs[1]); +} + +#[test] +fn registered_noises_share_ordinary_instances_and_recreate_nether_instances() { + let mut builder = crate::noise::NormalNoise::builder(); + builder.set_base_octave(-3).set_octave_count(3).unwrap(); + let definition = builder.build().unwrap(); + let mut graph = DensityGraph::new(); + let ordinary = graph + .register_noise("horizon:sample".to_owned(), definition.clone()) + .unwrap(); + assert_eq!( + graph.register_noise("horizon:sample".to_owned(), definition.clone()), + Err(CompileError::DuplicateNoise) + ); + let nether = graph + .register_noise("minecraft:nether/vegetation".to_owned(), definition) + .unwrap(); + let unseeded = DensityCompiler::new(graph.clone()); + assert_eq!( + unseeded.get_noise_sampler(ordinary).unwrap_err(), + CompileError::MissingSeededContext + ); + for legacy in [false, true] { + let compiler = DensityCompiler::new_seeded(graph.clone(), i64::MAX, legacy); + let a = compiler.get_noise_sampler(ordinary).unwrap(); + let b = compiler.get_noise_sampler(ordinary).unwrap(); + assert!(Arc::ptr_eq(&a, &b)); + let a = compiler.get_noise_sampler(nether).unwrap(); + let b = compiler.get_noise_sampler(nether).unwrap(); + assert!(!Arc::ptr_eq(&a, &b)); + assert_eq!( + a.get3(-17.25, 64.0, 32.5).to_bits(), + b.get3(-17.25, 64.0, 32.5).to_bits() + ); + } +} + +#[test] +fn noise_specialization_requires_literal_positive_zero_shifts() { + let mut graph = DensityGraph::new(); + let noise = graph + .register_noise( + "horizon:empty".to_owned(), + crate::noise::NormalNoise::builder() + .set_octave_count(0) + .unwrap() + .build() + .unwrap(), + ) + .unwrap(); + let zero = graph.insert(GraphNode::Constant(0.0)).unwrap(); + let negative = graph.insert(GraphNode::Constant(-0.0)).unwrap(); + let roots = [zero, negative].map(|shift_x| { + graph + .insert(GraphNode::Noise { + noise, + xz_scale: 1.0, + y_scale: 1.0, + shift_x, + shift_y: zero, + shift_z: zero, + }) + .unwrap() + }); + let compiler = DensityCompiler::new_seeded(graph, 1, false); + let volume = DensityVolume::new([1; 3], [0; 3], [1; 3]).unwrap(); + let mut buffer = [17.0; 2]; + compiler + .compile_raw(roots[0]) + .unwrap() + .sample_volume(&mut SamplerContext::default(), &mut buffer, volume) + .unwrap(); + assert_eq!(buffer, [0.0; 2]); + compiler + .compile_raw(roots[1]) + .unwrap() + .sample_volume(&mut SamplerContext::default(), &mut buffer, volume) + .unwrap(); + assert_eq!(buffer[0].to_bits(), 0); + assert_eq!(buffer[1].to_bits(), (-0.0_f32).to_bits()); +} + +#[test] +fn spline_range_early_return_does_not_skip_coordinate_validation_during_compilation() { + let mut graph = DensityGraph::new(); + let unavailable = graph + .bind(Arc::new(FailingSampler), Interval::NAI, 2) + .unwrap(); + let invalid = graph.insert(GraphNode::Constant(f32::NAN)).unwrap(); + let nested = CubicSpline::multipoint( + invalid, + vec![SplinePoint { + location: 0.0, + value: CubicSpline::Constant(1.0), + derivative: 0.0, + }], + ) + .unwrap(); + let root = graph + .insert(GraphNode::Spline( + CubicSpline::multipoint( + unavailable, + vec![SplinePoint { + location: 0.0, + value: nested, + derivative: 0.0, + }], + ) + .unwrap(), + )) + .unwrap(); + assert_eq!(graph.range(root), Ok(Interval::NAI)); + let compiler = DensityCompiler::new(graph); + assert!(matches!( + compiler.compile_raw(root), + Err(CompileError::Range(_)) + )); +} + +#[test] +fn spline_coordinates_share_bulk_evaluation_after_graph_rewriting() { + let trace = Arc::new(VerticalTrace::default()); + let mut graph = DensityGraph::new(); + let coordinate = graph + .bind(trace.clone(), Interval::new(-1.0, 1.0).unwrap(), 2) + .unwrap(); + let inner = CubicSpline::multipoint( + coordinate, + vec![SplinePoint { + location: 0.0, + value: CubicSpline::Constant(3.0), + derivative: 1.0, + }], + ) + .unwrap(); + let root = graph + .insert(GraphNode::Spline( + CubicSpline::multipoint( + coordinate, + vec![ + SplinePoint { + location: -1.0, + value: inner.clone(), + derivative: 0.0, + }, + SplinePoint { + location: 1.0, + value: inner, + derivative: 0.0, + }, + ], + ) + .unwrap(), + )) + .unwrap(); + let mut compiler = DensityCompiler::new(graph); + let sampler = compiler.get_sampler(root).unwrap(); + let volume = DensityVolume::new([3, 3, 2], [-1; 3], [1; 3]).unwrap(); + let mut output = vec![0.0; volume.size()]; + sampler + .sample_volume(&mut SamplerContext::default(), &mut output, volume) + .unwrap(); + assert_eq!(trace.0.lock().unwrap().len(), 1); + for column in output.chunks_exact(3) { + assert_eq!(column, [2.0, 3.0, 4.0]); + } +} + +#[test] +fn interval_threshold_equality_and_hashing_preserve_distinct_cache_inputs() { + let mut graph = DensityGraph::new(); + let one = graph.insert(GraphNode::Constant(1.0)).unwrap(); + let zero = graph.insert(GraphNode::Constant(0.0)).unwrap(); + let shared_nan: Arc<[f32]> = Arc::from([f32::NAN]); + let mut ids = Vec::new(); + for thresholds in [ + shared_nan.clone(), + shared_nan, + Arc::from([f32::NAN]), + Arc::from([0.0]), + Arc::from([-0.0]), + ] { + ids.push( + graph + .insert(GraphNode::IntervalSelect { + input: one, + thresholds, + branches: vec![zero, one], + }) + .unwrap(), + ); + } + assert_eq!(ids[0], ids[1]); + assert!(!graph.java_equals(ids[0], ids[2]).unwrap()); + assert!(graph.java_equals(ids[3], ids[4]).unwrap()); + assert_ne!(ids[3], ids[4]); + let doubled_positive = graph + .insert(GraphNode::Binary { + kind: GraphBinary::Add, + left: ids[3], + right: ids[3], + }) + .unwrap(); + let doubled_negative = graph + .insert(GraphNode::Binary { + kind: GraphBinary::Add, + left: ids[4], + right: ids[4], + }) + .unwrap(); + assert_eq!(doubled_positive, doubled_negative); + let caches = ids + .into_iter() + .map(|input| graph.insert(GraphNode::Cache(input)).unwrap()) + .collect::>(); + let mut compiler = DensityCompiler::new(graph); + for cache in caches { + compiler.get_sampler(cache).unwrap(); + } + assert_eq!(compiler.cache_count(), 4); +} + +#[test] +fn structural_identity_preserves_java_float_keys_and_shared_cache_ids() { + let mut graph = DensityGraph::new(); + let positive = graph.insert(GraphNode::Constant(0.0)).unwrap(); + let negative = graph.insert(GraphNode::Constant(-0.0)).unwrap(); + assert_ne!(positive, negative); + let nan = graph.insert(GraphNode::Constant(f32::NAN)).unwrap(); + assert_eq!( + nan, + graph + .insert(GraphNode::Constant(f32::from_bits(0xffa00001))) + .unwrap() + ); + let first = graph.insert(GraphNode::Cache(positive)).unwrap(); + let second = graph.insert(GraphNode::Cache(positive)).unwrap(); + assert_eq!(first, second); + let root = graph + .insert(GraphNode::Binary { + kind: GraphBinary::Add, + left: first, + right: second, + }) + .unwrap(); + let mut compiler = DensityCompiler::new(graph); + assert_eq!( + compiler.compile_raw(first).unwrap_err(), + CompileError::UnpreparedCache + ); + let sampler = compiler.get_sampler(root).unwrap(); + assert_eq!(compiler.cache_count(), 1); + assert!(Arc::ptr_eq(&sampler, &compiler.get_sampler(root).unwrap())); +} + +#[test] +fn failed_parent_preparation_retains_successful_child_and_consumes_new_id_on_retry() { + let mut graph = DensityGraph::new(); + let good = graph.insert(GraphNode::Constant(1.0)).unwrap(); + let child = graph.insert(GraphNode::Cache(good)).unwrap(); + let bad = graph.insert(GraphNode::Constant(f32::NAN)).unwrap(); + let sum = graph + .insert(GraphNode::Binary { + kind: GraphBinary::Add, + left: child, + right: bad, + }) + .unwrap(); + let root = graph.insert(GraphNode::Cache(sum)).unwrap(); + let mut compiler = DensityCompiler::new(graph); + assert!(matches!( + compiler.get_sampler(root), + Err(CompileError::Range(_)) + )); + assert_eq!(compiler.cache_count(), 2); + assert!(matches!( + compiler.get_sampler(root), + Err(CompileError::Range(_)) + )); + assert_eq!(compiler.cache_count(), 3); + let sampler = compiler.get_sampler(child).unwrap(); + assert_eq!(compiler.cache_count(), 3); + assert_eq!( + sampler.sample_value(&mut SamplerContext::default(), [3; 3]), + Ok(1.0) + ); +} + +#[derive(Debug)] +struct FailingSampler; +impl DensitySampler for FailingSampler { + fn sample_value(&self, _: &mut SamplerContext, _: [i32; 3]) -> Result { + Err(SampleError::ZeroGradientPeriod) + } +} + +#[test] +fn min_range_elimination_is_strict_and_does_not_skip_child_compilation() { + let mut graph = DensityGraph::new(); + let one = graph.insert(GraphNode::Constant(1.0)).unwrap(); + let disjoint = graph + .bind( + Arc::new(FailingSampler), + Interval::new(2.0, 3.0).unwrap(), + 7, + ) + .unwrap(); + let touching = graph + .bind( + Arc::new(FailingSampler), + Interval::new(1.0, 3.0).unwrap(), + 7, + ) + .unwrap(); + let cached = graph.insert(GraphNode::Cache(disjoint)).unwrap(); + let roots: Vec<_> = [disjoint, touching, cached] + .into_iter() + .map(|right| { + graph + .insert(GraphNode::Binary { + kind: GraphBinary::Minimum, + left: one, + right, + }) + .unwrap() + }) + .collect(); + let compiler = DensityCompiler::new(graph); + let volume = DensityVolume::new([1; 3], [0; 3], [1; 3]).unwrap(); + let mut context = SamplerContext::default(); + let mut output = [17.0]; + compiler + .compile_raw(roots[0]) + .unwrap() + .sample_volume(&mut context, &mut output, volume) + .unwrap(); + assert_eq!(output, [1.0]); + assert_eq!( + compiler + .compile_raw(roots[1]) + .unwrap() + .sample_volume(&mut context, &mut output, volume), + Err(SampleError::ZeroGradientPeriod) + ); + assert_eq!( + compiler.compile_raw(roots[2]).unwrap_err(), + CompileError::UnpreparedCache + ); +} + +#[derive(Debug, Default)] +struct VerticalTrace(Mutex>); +impl DensitySampler for VerticalTrace { + fn sample_value(&self, _: &mut SamplerContext, position: [i32; 3]) -> Result { + Ok(position[1] as f32) + } + fn sample_volume( + &self, + _: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + self.0.lock().unwrap().push(volume); + visit(volume, |index, position| { + buffer[index] = position[1] as f32; + Ok(()) + }) + } +} + +#[test] +fn compiler_reduces_uniform_axes_and_preserves_strided_vertical_samples() { + let trace = Arc::new(VerticalTrace::default()); + let mut graph = DensityGraph::new(); + let root = graph.bind(trace.clone(), Interval::INFINITE, 2).unwrap(); + let mut compiler = DensityCompiler::new(graph); + let sampler = compiler.get_sampler(root).unwrap(); + let volume = DensityVolume::new([3, 4, 2], [-9, -7, 11], [2, 3, 5]).unwrap(); + let mut output = vec![17.0; volume.size() + 1]; + sampler + .sample_volume(&mut SamplerContext::default(), &mut output, volume) + .unwrap(); + assert_eq!( + *trace.0.lock().unwrap(), + vec![DensityVolume::new([1, 4, 1], [0, -7, 0], [2, 3, 5]).unwrap()] + ); + for column in output[..volume.size()].chunks_exact(4) { + assert_eq!(column, [-7.0, -4.0, -1.0, 2.0]); + } + assert_eq!(output[volume.size()], 17.0); + assert_eq!(compiler.graph().domain_axes(root), Ok(2)); +} diff --git a/crates/horizon-core/src/density/interpolation.rs b/crates/horizon-core/src/density/interpolation.rs new file mode 100644 index 000000000..25a5e826b --- /dev/null +++ b/crates/horizon-core/src/density/interpolation.rs @@ -0,0 +1,207 @@ +use super::*; + +/// Interpolation over a coarse density grid. Scalar queries and volume queries +/// retain vanilla's distinct floating-point paths and child bulk calls. +#[derive(Clone, Debug)] +pub struct InterpolatedSampler { + input: Arc, + cell_size: [i32; 3], + inverse: [f32; 3], +} +impl InterpolatedSampler { + pub fn new( + input: Arc, + cell_size_xz: i32, + cell_size_y: i32, + ) -> Result { + if cell_size_xz <= 0 || cell_size_y <= 0 { + return Err(DensityError::NonpositiveSteps.into()); + } + let cell_size = [cell_size_xz, cell_size_y, cell_size_xz]; + Ok(Self { + input, + cell_size, + inverse: cell_size.map(|size| 1.0 / size as f32), + }) + } + + fn sample_block_volume( + &self, + context: &mut SamplerContext, + output: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + let minimum = volume.minimum(); + let maximum = volume.maximum(); + let first: [i32; 3] = std::array::from_fn(|i| minimum[i].div_euclid(self.cell_size[i])); + let counts: [i32; 3] = std::array::from_fn(|i| { + maximum[i] + .div_euclid(self.cell_size[i]) + .wrapping_sub(first[i]) + .wrapping_add(1) + }); + let sizes = std::array::from_fn(|i| { + counts[i].wrapping_add(i32::from(maximum[i].rem_euclid(self.cell_size[i]) != 0)) + }); + let coarse = DensityVolume::new( + sizes, + std::array::from_fn(|i| first[i].wrapping_mul(self.cell_size[i])), + self.cell_size, + )?; + context.with_buffer(coarse.size(), |context, samples| { + self.input.sample_volume(context, samples, coarse)?; + for z in 0..counts[2] { + for x in 0..counts[0] { + for y in 0..counts[1] { + let cell = [x as usize, y as usize, z as usize]; + let corners = std::array::from_fn(|corner| { + let position = std::array::from_fn(|axis| { + (cell[axis] + ((corner >> axis) & 1)).min(coarse.sizes()[axis] - 1) + }); + samples[coarse.index(position).unwrap()] + }); + self.fill_cell(output, volume, coarse, cell, corners)?; + } + } + } + Ok(()) + }) + } + + fn fill_cell( + &self, + output: &mut [f32], + volume: DensityVolume, + coarse: DensityVolume, + cell: [usize; 3], + corners: [f32; 8], + ) -> Result<(), SampleError> { + let offset: [i32; 3] = std::array::from_fn(|i| { + coarse.minimum()[i] + .wrapping_add((cell[i] as i32).wrapping_mul(self.cell_size[i])) + .wrapping_sub(volume.minimum()[i]) + }); + let start = offset.map(|offset| offset.wrapping_neg().max(0)); + let end: [i32; 3] = std::array::from_fn(|i| { + self.cell_size[i] + .min((volume.sizes()[i] as i32).wrapping_sub(offset[i])) + .wrapping_sub(1) + }); + for z in start[2]..=end[2] { + let alpha_z = z as f32 * self.inverse[2]; + let z00 = lerp(alpha_z, corners[0], corners[4]); + let z01 = lerp(alpha_z, corners[2], corners[6]); + let z10 = lerp(alpha_z, corners[1], corners[5]); + let z11 = lerp(alpha_z, corners[3], corners[7]); + for x in start[0]..=end[0] { + let alpha_x = x as f32 * self.inverse[0]; + let low = lerp(alpha_x, z00, z10); + let high = lerp(alpha_x, z01, z11); + let increment = (high - low) * self.inverse[1]; + let mut value = low + increment * start[1] as f32; + if end[1] < start[1] { + continue; + } + let index = volume + .index([ + offset[0].wrapping_add(x) as usize, + offset[1].wrapping_add(start[1]) as usize, + offset[2].wrapping_add(z) as usize, + ]) + .ok_or(DensityError::VolumeTooLarge)?; + let length = (end[1] - start[1] + 1) as usize; + let end_index = index + .checked_add(length) + .ok_or(DensityError::VolumeTooLarge)?; + let column = output + .get_mut(index..end_index) + .ok_or(DensityError::VolumeTooLarge)?; + for output in column { + *output = value; + // Repeated addition is observable: multiplication by the + // current Y offset does not have the same rounding. + value += increment; + } + } + } + Ok(()) + } +} + +fn lerp(alpha: f32, first: f32, second: f32) -> f32 { + first + alpha * (second - first) +} +impl DensitySampler for InterpolatedSampler { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + let remainder: [i32; 3] = + std::array::from_fn(|i| position[i].rem_euclid(self.cell_size[i])); + if remainder == [0; 3] { + return self.input.sample_value(context, position); + } + let volume = DensityVolume::new( + [2; 3], + std::array::from_fn(|i| position[i].wrapping_sub(remainder[i])), + self.cell_size, + )?; + context.with_buffer(8, |context, corners| { + self.input.sample_volume(context, corners, volume)?; + let alpha: [f32; 3] = + std::array::from_fn(|i| remainder[i] as f32 / self.cell_size[i] as f32); + // Samples use Y-innermost storage; interpolation blends X, Y, Z. + let xy0 = lerp( + alpha[1], + lerp(alpha[0], corners[0], corners[2]), + lerp(alpha[0], corners[1], corners[3]), + ); + let xy1 = lerp( + alpha[1], + lerp(alpha[0], corners[4], corners[6]), + lerp(alpha[0], corners[5], corners[7]), + ); + Ok(lerp(alpha[2], xy0, xy1)) + }) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + output: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_buffer(output, volume)?; + if (0..3).all(|i| { + (volume.steps()[i] == self.cell_size[i] || volume.sizes()[i] == 1) + && volume.minimum()[i].rem_euclid(self.cell_size[i]) == 0 + }) { + return self.input.sample_volume(context, output, volume); + } + if volume.steps() == [1; 3] { + return self.sample_block_volume(context, output, volume); + } + // The reference evaluates the complete block-resolution bounding volume + // before selecting strided samples, including trailing unsampled blocks. + let dense = DensityVolume::new( + std::array::from_fn(|i| (volume.sizes()[i] as i32).wrapping_mul(volume.steps()[i])), + volume.minimum(), + [1; 3], + )?; + context.with_buffer(dense.size(), |context, samples| { + self.sample_block_volume(context, samples, dense)?; + let [sx, sy, sz] = volume.sizes(); + for z in 0..sz { + for x in 0..sx { + for y in 0..sy { + let source = dense.index(std::array::from_fn(|i| { + [x, y, z][i] * volume.steps()[i] as usize + })); + output[(x + z * sx) * sy + y] = samples[source.unwrap()]; + } + } + } + Ok(()) + }) + } +} diff --git a/crates/horizon-core/src/density/interval.rs b/crates/horizon-core/src/density/interval.rs new file mode 100644 index 000000000..0375dba6d --- /dev/null +++ b/crates/horizon-core/src/density/interval.rs @@ -0,0 +1,412 @@ +//! Selected vanilla interval operations used for density graph range analysis. +use super::arithmetic::{java_max, java_min}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum IntervalError { + NanBound, + InvertedBounds, + EmptyInput, + NanMappedBound, +} +impl std::fmt::Display for IntervalError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::NanBound => "interval endpoint is NaN", + Self::InvertedBounds => "interval endpoints are reversed", + Self::EmptyInput => "at least one interval is required", + Self::NanMappedBound => "monotonic range operator produced NaN", + }) + } +} +impl std::error::Error for IntervalError {} + +#[derive(Clone, Copy, Debug)] +pub struct Interval { + min: f32, + max: f32, +} +impl PartialEq for Interval { + fn eq(&self, other: &Self) -> bool { + (self.is_nai() && other.is_nai()) || (self.min == other.min && self.max == other.max) + } +} +impl Eq for Interval {} +impl Interval { + pub const NAI: Self = Self { + min: f32::NAN, + max: f32::NAN, + }; + pub const INFINITE: Self = Self { + min: f32::NEG_INFINITY, + max: f32::INFINITY, + }; + pub fn new(min: f32, max: f32) -> Result { + if max < min { + return Err(IntervalError::InvertedBounds); + } + if min.is_nan() || max.is_nan() { + return Err(IntervalError::NanBound); + } + // The reference returns a cached [0, 1], canonicalizing a negative zero. + Ok(Self { + min: if min == 0.0 && max == 1.0 { 0.0 } else { min }, + max, + }) + } + pub fn symmetric(value: f32) -> Result { + Self::new(-value, value) + } + pub fn exact(value: f32) -> Result { + Self::new(value, value) + } + pub fn min(self) -> f32 { + self.min + } + pub fn max(self) -> f32 { + self.max + } + pub fn is_nai(self) -> bool { + self.min.is_nan() + } + pub fn contains(self, value: f32) -> bool { + value >= self.min && value <= self.max + } + pub fn intersects(self, other: Self) -> bool { + self.min <= other.max && self.max >= other.min + } + /// Kept separate from Rust's Hash contract: Java compares signed zeros equal + /// here, but its endpoint-based hash can distinguish them. + pub fn java_hash_code(self) -> i32 { + let bits = |v: f32| { + if v.is_nan() { + 0x7fc0_0000_i32 + } else { + v.to_bits() as i32 + } + }; + bits(self.min).wrapping_mul(31).wrapping_add(bits(self.max)) + } + pub fn encapsulating_values(a: f32, b: f32) -> Self { + if a.is_nan() && b.is_nan() { + Self::NAI + } else if a.is_nan() { + Self::exact(b).unwrap() + } else if b.is_nan() { + Self::exact(a).unwrap() + } else { + Self::new(java_min(a, b), java_max(a, b)).unwrap() + } + } + pub fn encapsulating(intervals: &[Self]) -> Result { + if intervals.is_empty() { + return Err(IntervalError::EmptyInput); + } + let mut min = f32::INFINITY; + let mut max = f32::NEG_INFINITY; + for interval in intervals { + if !interval.is_nai() { + min = java_min(interval.min, min); + max = java_max(interval.max, max); + } + } + if max < min { + Ok(Self::NAI) + } else { + Self::new(min, max) + } + } + fn arithmetic_bounds(min: f32, max: f32) -> Self { + if min.is_nan() || max.is_nan() { + Self::NAI + } else { + Self::new(min, max).expect("ordered interval arithmetic") + } + } + pub fn add_range(self, right: Self) -> Self { + Self::arithmetic_bounds(self.min + right.min, self.max + right.max) + } + pub fn subtract_range(self, right: Self) -> Self { + Self::arithmetic_bounds(self.min - right.max, self.max - right.min) + } + pub fn multiply_range(self, right: Self) -> Self { + if self.is_nai() || right.is_nai() { + return Self::NAI; + } + let a = mul_bound(self.min, right.min); + let b = mul_bound(self.min, right.max); + let c = mul_bound(self.max, right.min); + let d = mul_bound(self.max, right.max); + Self::new( + java_min(java_min(a, b), java_min(c, d)), + java_max(java_max(a, b), java_max(c, d)), + ) + .unwrap() + } + pub fn reciprocal(self) -> Self { + if self.is_nai() || (self.min == 0.0 && self.max == 0.0) { + Self::NAI + } else if !self.contains(0.0) { + Self::new(1.0 / self.max, 1.0 / self.min).unwrap() + } else if self.max == 0.0 { + Self::new(f32::NEG_INFINITY, 1.0 / self.min).unwrap() + } else if self.min == 0.0 { + Self::new(1.0 / self.max, f32::INFINITY).unwrap() + } else { + Self::INFINITE + } + } + pub fn divide_range(self, right: Self) -> Self { + self.multiply_range(right.reciprocal()) + } + pub fn minimum(self, right: Self) -> Self { + Self::arithmetic_bounds(java_min(self.min, right.min), java_min(self.max, right.max)) + } + pub fn maximum(self, right: Self) -> Self { + Self::arithmetic_bounds(java_max(self.min, right.min), java_max(self.max, right.max)) + } + pub fn clamp(self, min: f32, max: f32) -> Result { + if min > max { + return Err(IntervalError::InvertedBounds); + } + if self.is_nai() { + Ok(Self::NAI) + } else if self.min >= max { + Self::exact(max) + } else if self.max <= min { + Self::exact(min) + } else { + Self::new(java_max(self.min, min), java_min(self.max, max)) + } + } + pub fn abs(self) -> Self { + self.even_bounds(f32::abs) + } + pub fn square(self) -> Self { + self.even_bounds(|v| v * v) + } + pub fn log(self) -> Result { + if self.is_nai() || self.max < 0.0 { + Ok(Self::NAI) + } else { + self.maximum(Self::exact(0.0)?) + .map_monotonic(|v| (v as f64).ln() as f32) + } + } + pub fn power(self, exponent: Self) -> Self { + if self.is_nai() || exponent.is_nai() { + return Self::NAI; + } + if self.min == self.max { + return Self::power_base(self.min, exponent); + } + let mut result = Self::encapsulating(&[ + Self::power_base(self.min, exponent), + Self::power_base(self.max, exponent), + ]) + .unwrap(); + if self.contains(0.0) { + if self.max > 0.0 { + result = Self::encapsulating(&[result, Self::power_base(0.0, exponent)]).unwrap(); + } + if self.min < 0.0 { + result = Self::encapsulating(&[result, Self::power_base(-0.0, exponent)]).unwrap(); + } + } + result + } + fn including_value(self, value: f32) -> Self { + if value.is_nan() { + self + } else if self.is_nai() { + Self::exact(value).unwrap() + } else { + Self::new(java_min(self.min, value), java_max(self.max, value)).unwrap() + } + } + fn power_base(base: f32, exponent: Self) -> Self { + if base.is_nan() || exponent.is_nai() { + return Self::NAI; + } + if exponent.min == exponent.max { + let value = java_power(base, exponent.min); + return Self::encapsulating_values(value, value); + } + if base == 0.0 { + let range = if exponent.contains(0.0) { + if exponent.max == 0.0 { + Self::new(1.0, f32::INFINITY).unwrap() + } else if exponent.min == 0.0 { + Self::new(0.0, 1.0).unwrap() + } else { + Self::new(0.0, f32::INFINITY).unwrap() + } + } else if exponent.max < 0.0 { + Self::exact(f32::INFINITY).unwrap() + } else { + Self::exact(0.0).unwrap() + }; + return range.multiply_range(Self::exact(1.0_f32.copysign(base)).unwrap()); + } + if base == 1.0 { + return Self::exact(1.0).unwrap(); + } + if base > 0.0 { + if exponent.min.is_finite() && exponent.max.is_finite() { + return Self::encapsulating_values( + java_power(base, exponent.min), + java_power(base, exponent.max), + ); + } + if exponent.min.is_infinite() && exponent.max.is_infinite() { + return Self::new(0.0, f32::INFINITY).unwrap(); + } + let (min, max) = if exponent.min.is_infinite() { + if base < 1.0 { + (java_power(base, exponent.max), f32::INFINITY) + } else { + (0.0, java_power(base, exponent.max)) + } + } else if base < 1.0 { + (0.0, java_power(base, exponent.min)) + } else { + (java_power(base, exponent.min), f32::INFINITY) + }; + return Self::new(min, max).unwrap(); + } + let first = (exponent.min as f64).ceil() as f32; + let last = (exponent.max as f64).floor() as f32; + if last < first { + return Self::NAI; + } + let a = java_power(base, first); + let b = java_power(base, last); + let mut result = Self::encapsulating_values(a, b); + if first.is_infinite() { + result = result.including_value(-a); + } else if first + 1.0 < last { + result = result.including_value(java_power(base, first + 1.0)); + } + if last.is_infinite() { + result = result.including_value(-b); + } else if last - 1.0 > first { + result = result.including_value(java_power(base, last - 1.0)); + } + result + } + fn even_bounds(self, transform: impl Fn(f32) -> f32) -> Self { + if self.is_nai() { + return self; + } + let a = transform(self.min); + let b = transform(self.max); + Self::new( + if self.contains(0.0) { + 0.0 + } else { + java_min(a, b) + }, + java_max(a, b), + ) + .unwrap() + } + /// The caller supplies a monotonic transformation. As in vanilla, this maps + /// only the endpoints; it does not attempt to prove monotonicity. + pub fn map_monotonic( + self, + mut transform: impl FnMut(f32) -> f32, + ) -> Result { + if self.is_nai() { + return Ok(self); + } + let a = transform(self.min); + let b = transform(self.max); + if a.is_nan() || b.is_nan() { + Err(IntervalError::NanMappedBound) + } else { + Self::new(java_min(a, b), java_max(a, b)) + } + } + pub fn lerp_ranges(self, first: Self, second: Self) -> Self { + if self.is_nai() || first.is_nai() || second.is_nai() { + return Self::NAI; + } + Self::encapsulating(&[ + self.lerp_values(first.min, second.min), + self.lerp_values(first.max, second.min), + self.lerp_values(first.min, second.max), + self.lerp_values(first.max, second.max), + ]) + .unwrap() + } + pub fn lerp_values(self, first: f32, second: f32) -> Self { + if self.is_nai() || first.is_nan() || second.is_nan() { + return Self::NAI; + } + if first.is_finite() && second.is_finite() { + return Self::encapsulating_values( + first + mul_bound(self.min, second - first), + first + mul_bound(self.max, second - first), + ); + } + if first == second { + return Self::exact(first).unwrap(); + } + let a = lerp_infinite_bound(self.min, first, second); + let b = lerp_infinite_bound(self.max, first, second); + if a.is_nan() || b.is_nan() { + Self::NAI + } else { + Self::encapsulating_values(a, b) + } + } + pub fn sign(self) -> Self { + if self.is_nai() { + self + } else if self.min == self.max { + Self::exact(if self.min == 0.0 { + self.min + } else { + self.min.signum() + }) + .unwrap() + } else if self.contains(0.0) { + Self::new( + if self.min == 0.0 { 0.0 } else { -1.0 }, + if self.max == 0.0 { 0.0 } else { 1.0 }, + ) + .unwrap() + } else { + Self::exact(if self.min > 0.0 { 1.0 } else { -1.0 }).unwrap() + } + } +} +fn java_power(base: f32, exponent: f32) -> f32 { + super::arithmetic::java_power(base as f64, exponent as f64) as f32 +} +fn mul_bound(a: f32, b: f32) -> f32 { + if a == 0.0 || b == 0.0 { 0.0 } else { a * b } +} + +fn lerp_infinite_bound(alpha: f32, first: f32, second: f32) -> f32 { + let a = mul_bound(1.0 - alpha, first); + let b = mul_bound(alpha, second); + if a.is_infinite() && b.is_infinite() { + if alpha <= 0.0 { + if second > first { + f32::NEG_INFINITY + } else { + f32::INFINITY + } + } else if alpha >= 1.0 { + if second > first { + f32::INFINITY + } else { + f32::NEG_INFINITY + } + } else { + f32::NAN + } + } else { + a + b + } +} diff --git a/crates/horizon-core/src/density/mod.rs b/crates/horizon-core/src/density/mod.rs new file mode 100644 index 000000000..6bc84a8d1 --- /dev/null +++ b/crates/horizon-core/src/density/mod.rs @@ -0,0 +1,391 @@ +//! Compiled density samplers for Java Edition 26.3. +//! +//! Evaluation primitives and an initial graph compiler; complete terrain +//! generation is pending. Bulk evaluation retains its own floating-point path. +use crate::{ + geometry::Axis, + noise::{DensityError, DensityVolume, Noise}, +}; +use std::sync::Arc; + +mod beardifier; +pub use beardifier::{Beardifier, JigsawJunction, RigidPiece, StructureBounds, TerrainAdjustment}; +mod cache; +mod world_fields; +pub use world_fields::{ + BlendDensitySampler, ContextBoundSampler, DensityBlender, EmptyBlender, WorldField, WorldFields, +}; +mod end_islands; +pub use end_islands::EndIslandSampler; +pub mod graph; +pub use cache::CachingDensitySampler; +mod arithmetic; +mod interpolation; +mod interval; +pub use interpolation::InterpolatedSampler; +pub use interval::{Interval, IntervalError}; +mod rounding; +mod selection; +pub use rounding::{RoundMode, RoundSampler}; +mod power; +pub use power::{PowerSampler, compile_constant_exponent}; +mod slice; +pub use slice::{SliceAxes, SliceSampler}; +mod spline; +pub use spline::{CubicSpline, MultipointSpline, SplineError, SplinePoint, SplineSampler}; +mod surface; +pub use surface::{FindTopSurfaceSampler, compile_surface_search}; +mod terrain_noise; +pub use arithmetic::{BinaryOp, BinarySampler, UnaryOp, UnarySampler}; +pub use selection::{ + DensityValue, IntervalSelectSampler, InvalidIntervals, LerpSampler, RangeChoiceSampler, +}; +pub use terrain_noise::{ + BlendedFbmSet, BlendedNoise, DistanceMetric, DistanceToPointSampler, ShiftNoiseKind, + compile_shift_noise, create_blended_fbm, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SampleError { + Volume(DensityError), + ZeroGradientPeriod, + ExactBufferSizeRequired, + CacheIdOutOfRange, + RecursiveCache, + SurfaceRequiresSingleLayer, + SurfaceSearchOverflow, +} +impl From for SampleError { + fn from(value: DensityError) -> Self { + Self::Volume(value) + } +} +impl std::fmt::Display for SampleError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Volume(error) => error.fmt(f), + Self::SurfaceRequiresSingleLayer => { + f.write_str("surface search requires a single Y layer") + } + Self::SurfaceSearchOverflow => { + f.write_str("surface search crossed the integer height domain") + } + Self::CacheIdOutOfRange => f.write_str("density cache id exceeds 65535"), + Self::RecursiveCache => f.write_str("density cache reentered its own evaluation"), + Self::ExactBufferSizeRequired => { + f.write_str("this density sampler requires exactly a volume-sized output") + } + Self::ZeroGradientPeriod => { + f.write_str("repeating gradient has a zero coordinate period") + } + } + } +} +impl std::error::Error for SampleError {} + +/// Worker-owned temporary storage. Samplers can be shared across workers; their +/// scratch buffers cannot. World fields are immutable for an evaluation context. +#[derive(Debug, Default)] +pub struct SamplerContext { + scratch: Vec>, + caches: Option>, + fields: WorldFields, +} +impl SamplerContext { + fn with_buffer( + &mut self, + size: usize, + sample: impl FnOnce(&mut Self, &mut [f32]) -> Result, + ) -> Result { + let mut buffer = self.scratch.pop().unwrap_or_default(); + buffer.resize(size, 0.0); + let result = sample(self, &mut buffer); + self.scratch.push(buffer); + result + } + /// Release retained storage between worlds or after unusually large work. + pub fn clear_scratch(&mut self) { + self.scratch.clear(); + } +} + +pub trait DensitySampler: std::fmt::Debug + Send + Sync { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result; + + /// The slice length is the logical buffer size. Some samplers fill its tail; + /// others leave it untouched. A short buffer is rejected before any writes. + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_buffer(buffer, volume)?; + visit(volume, |index, position| { + buffer[index] = self.sample_value(context, position)?; + Ok(()) + }) + } +} +fn check_buffer(buffer: &[f32], volume: DensityVolume) -> Result<(), SampleError> { + if buffer.len() < volume.size() { + Err(DensityError::BufferTooShort.into()) + } else { + Ok(()) + } +} +fn check_exact_buffer(buffer: &[f32], volume: DensityVolume) -> Result<(), SampleError> { + check_buffer(buffer, volume)?; + if buffer.len() != volume.size() { + Err(SampleError::ExactBufferSizeRequired) + } else { + Ok(()) + } +} +fn visit( + volume: DensityVolume, + mut cell: impl FnMut(usize, [i32; 3]) -> Result<(), SampleError>, +) -> Result<(), SampleError> { + let [sx, sy, sz] = volume.sizes(); + let mut index = 0; + for z in 0..sz { + let bz = volume.block(Axis::Z, z).unwrap(); + for x in 0..sx { + let bx = volume.block(Axis::X, x).unwrap(); + for y in 0..sy { + cell(index, [bx, volume.block(Axis::Y, y).unwrap(), bz])?; + index += 1; + } + } + } + Ok(()) +} + +#[derive(Clone, Copy, Debug)] +pub struct ConstantSampler(pub f32); +impl DensitySampler for ConstantSampler { + fn sample_value(&self, _: &mut SamplerContext, _: [i32; 3]) -> Result { + Ok(self.0) + } + fn sample_volume( + &self, + _: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_buffer(buffer, volume)?; + buffer.fill(self.0); + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TilingMode { + ClampToEdge, + Repeat, + MirroredRepeat, +} + +#[derive(Clone, Copy, Debug)] +pub struct GradientSampler { + axis: Axis, + tiling: TilingMode, + from: i32, + to: i32, + period: i32, + value: f32, + factor: f32, +} +impl GradientSampler { + pub fn new( + axis: Axis, + tiling: TilingMode, + from: i32, + to: i32, + from_value: f32, + to_value: f32, + ) -> Self { + let period = to.wrapping_sub(from); + Self { + axis, + tiling, + from, + to, + period, + value: from_value, + factor: (to_value - from_value) / period as f32, + } + } + pub fn compute(&self, coordinate: i32) -> Result { + let distance = match self.tiling { + TilingMode::ClampToEdge => coordinate + .clamp(self.from.min(self.to), self.from.max(self.to)) + .wrapping_sub(self.from), + TilingMode::Repeat | TilingMode::MirroredRepeat => { + if self.period == 0 { + return Err(SampleError::ZeroGradientPeriod); + } + let delta = coordinate.wrapping_sub(self.from); + // Java floorDiv/floorMod wrap MIN / -1, and round toward -infinity. + let mut cycle = delta.wrapping_div(self.period); + let mut remainder = delta.wrapping_rem(self.period); + if remainder != 0 && (delta ^ self.period) < 0 { + cycle = cycle.wrapping_sub(1); + remainder = remainder.wrapping_add(self.period); + } + if self.tiling == TilingMode::MirroredRepeat && cycle & 1 != 0 { + self.period.wrapping_sub(remainder) + } else { + remainder + } + } + }; + Ok(self.value + distance as f32 * self.factor) + } +} +impl DensitySampler for GradientSampler { + fn sample_value(&self, _: &mut SamplerContext, position: [i32; 3]) -> Result { + self.compute(position[self.axis as usize]) + } + fn sample_volume( + &self, + _: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_buffer(buffer, volume)?; + let [sx, sy, sz] = volume.sizes(); + for coordinate in 0..volume.sizes()[self.axis as usize] { + let value = self.compute(volume.block(self.axis, coordinate).unwrap())?; + match self.axis { + Axis::X => { + for z in 0..sz { + let start = (coordinate + z * sx) * sy; + buffer[start..start + sy].fill(value); + } + } + Axis::Y => { + for z in 0..sz { + for x in 0..sx { + buffer[(x + z * sx) * sy + coordinate] = value; + } + } + } + Axis::Z => { + let start = coordinate * sx * sy; + buffer[start..start + sx * sy].fill(value); + } + } + } + Ok(()) + } +} + +#[derive(Clone, Debug)] +pub struct NoiseSampler { + pub noise: Arc, + pub xz_scale: f64, + pub y_scale: f64, +} +impl DensitySampler for NoiseSampler { + fn sample_value( + &self, + _: &mut SamplerContext, + [x, y, z]: [i32; 3], + ) -> Result { + Ok(self.noise.get3( + x as f64 * self.xz_scale, + y as f64 * self.y_scale, + z as f64 * self.xz_scale, + )) + } + fn sample_volume( + &self, + _: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_buffer(buffer, volume)?; + buffer.fill(0.0); + Ok(self + .noise + .add_to_volume(buffer, volume, self.xz_scale, self.y_scale, 1.0)?) + } +} + +/// Compiled XZ or XYZ shifted noise. `None` selects vanilla's XZ specialization; +/// it must not add a synthetic zero Y shift (that would change signed zeros). +#[derive(Clone, Debug)] +pub struct ShiftedNoiseSampler { + pub source: NoiseSampler, + pub shift_x: Arc, + pub shift_y: Option>, + pub shift_z: Arc, +} +impl DensitySampler for ShiftedNoiseSampler { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + let x = position[0] as f64 * self.source.xz_scale + + self.shift_x.sample_value(context, position)? as f64; + let mut y = position[1] as f64 * self.source.y_scale; + if let Some(shift) = &self.shift_y { + y += shift.sample_value(context, position)? as f64; + } + let z = position[2] as f64 * self.source.xz_scale + + self.shift_z.sample_value(context, position)? as f64; + Ok(self.source.noise.get3(x, y, z)) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_buffer(buffer, volume)?; + self.shift_x.sample_volume(context, buffer, volume)?; + if let Some(shift_y) = &self.shift_y { + context.with_buffer(volume.size(), |context, y| { + shift_y.sample_volume(context, y, volume)?; + context.with_buffer(volume.size(), |context, z| { + self.shift_z.sample_volume(context, z, volume)?; + self.sample_shifted_volume(buffer, volume, Some(y), z) + }) + }) + } else { + context.with_buffer(volume.size(), |context, z| { + self.shift_z.sample_volume(context, z, volume)?; + self.sample_shifted_volume(buffer, volume, None, z) + }) + } + } +} +impl ShiftedNoiseSampler { + fn sample_shifted_volume( + &self, + buffer: &mut [f32], + volume: DensityVolume, + shift_y: Option<&[f32]>, + shift_z: &[f32], + ) -> Result<(), SampleError> { + visit(volume, |index, [x, y, z]| { + let x = x as f64 * self.source.xz_scale + buffer[index] as f64; + let mut y = y as f64 * self.source.y_scale; + if let Some(shift) = shift_y { + y += shift[index] as f64; + } + let z = z as f64 * self.source.xz_scale + shift_z[index] as f64; + buffer[index] = self.source.noise.get3(x, y, z); + Ok(()) + }) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/horizon-core/src/density/power.rs b/crates/horizon-core/src/density/power.rs new file mode 100644 index 000000000..b400093ae --- /dev/null +++ b/crates/horizon-core/src/density/power.rs @@ -0,0 +1,72 @@ +use super::*; + +/// Both operands evaluate in base/exponent order, including zero and one bases. +#[derive(Clone, Debug)] +pub struct PowerSampler { + pub base: Arc, + pub exponent: Arc, +} +impl DensitySampler for PowerSampler { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + let base = self.base.sample_value(context, position)?; + let exponent = self.exponent.sample_value(context, position)?; + Ok(super::arithmetic::java_power(base as f64, exponent as f64) as f32) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_exact_buffer(buffer, volume)?; + self.base.sample_volume(context, buffer, volume)?; + context.with_buffer(volume.size(), |context, scratch| { + self.exponent.sample_volume(context, scratch, volume)?; + for (base, exponent) in buffer.iter_mut().zip(scratch) { + *base = super::arithmetic::java_power(*base as f64, *exponent as f64) as f32; + } + Ok(()) + }) + } +} + +/// Only sqrt/identity/square/cube receive the negative-exponent reciprocal. +/// Other exponents return directly from vanilla's signed fallback sampler. +pub fn compile_constant_exponent( + base: Arc, + exponent: f32, +) -> Arc { + let positive: Arc = match exponent.abs() { + 0.5 => Arc::new(UnarySampler { + input: base, + operation: UnaryOp::Sqrt, + }), + 1.0 => base, + 2.0 => Arc::new(UnarySampler { + input: base, + operation: UnaryOp::Square, + }), + 3.0 => Arc::new(UnarySampler { + input: base, + operation: UnaryOp::Cube, + }), + _ => { + return Arc::new(UnarySampler { + input: base, + operation: UnaryOp::PowerExponent(exponent as f64), + }); + } + }; + if exponent < 0.0 { + Arc::new(UnarySampler { + input: positive, + operation: UnaryOp::Reciprocal, + }) + } else { + positive + } +} diff --git a/crates/horizon-core/src/density/rounding.rs b/crates/horizon-core/src/density/rounding.rs new file mode 100644 index 000000000..4ac9bbe83 --- /dev/null +++ b/crates/horizon-core/src/density/rounding.rs @@ -0,0 +1,98 @@ +use super::*; + +#[derive(Clone, Copy, Debug)] +pub enum RoundMode { + Floor, + Round, + Ceil, + Truncate, +} +impl RoundMode { + pub(super) fn integer(self, value: f32) -> f32 { + match self { + Self::Floor => (value as f64).floor() as f32, + Self::Ceil => (value as f64).ceil() as f32, + Self::Truncate => { + if value > 0.0 { + (value as f64).floor() as f32 + } else { + (value as f64).ceil() as f32 + } + } + Self::Round => { + // Math.round(float): ties go toward positive infinity, NaNs + // become zero, and the result saturates to Java's int domain. + let bits = value.to_bits() as i32; + let shift = 149 - ((bits >> 23) & 0xff); + let rounded = if (0..32).contains(&shift) { + let mut significand = (bits & 0x7f_ffff) | 0x80_0000; + if bits < 0 { + significand = -significand; + } + ((significand >> shift) + 1) >> 1 + } else { + value as i32 + }; + rounded as f32 + } + } + } + fn apply(self, input: f32, multiple: f32) -> f32 { + if multiple == 0.0 { + input + } else { + self.integer(input / multiple) * multiple + } + } +} + +/// A missing multiple selects vanilla's literal-one specialization. A supplied +/// sampler is evaluated even when its value is zero or always one. +#[derive(Clone, Debug)] +pub struct RoundSampler { + pub mode: RoundMode, + pub input: Arc, + pub multiple: Option>, +} +impl DensitySampler for RoundSampler { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + let input = self.input.sample_value(context, position)?; + Ok(if let Some(multiple) = &self.multiple { + self.mode + .apply(input, multiple.sample_value(context, position)?) + } else { + self.mode.integer(input) + }) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + if self.multiple.is_some() { + check_exact_buffer(buffer, volume)?; + } else { + check_buffer(buffer, volume)?; + } + self.input.sample_volume(context, buffer, volume)?; + if let Some(multiple) = &self.multiple { + context.with_buffer(volume.size(), |context, scratch| { + multiple.sample_volume(context, scratch, volume)?; + for (input, multiple) in buffer.iter_mut().zip(scratch) { + *input = self.mode.apply(*input, *multiple); + } + Ok(()) + }) + } else { + for value in buffer { + *value = self.mode.integer(*value); + } + Ok(()) + } + } +} diff --git a/crates/horizon-core/src/density/selection.rs b/crates/horizon-core/src/density/selection.rs new file mode 100644 index 000000000..eed6145ff --- /dev/null +++ b/crates/horizon-core/src/density/selection.rs @@ -0,0 +1,228 @@ +use super::*; + +#[derive(Clone, Debug)] +pub struct RangeChoiceSampler { + pub input: Arc, + pub min_inclusive: f32, + pub max_exclusive: f32, + pub when_in_range: Arc, + pub when_out_of_range: Arc, +} +impl RangeChoiceSampler { + fn contains(&self, value: f32) -> bool { + value >= self.min_inclusive && value < self.max_exclusive + } +} +impl DensitySampler for RangeChoiceSampler { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + if self.contains(self.input.sample_value(context, position)?) { + self.when_in_range.sample_value(context, position) + } else { + self.when_out_of_range.sample_value(context, position) + } + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_exact_buffer(buffer, volume)?; + // Vanilla evaluates the in-range branch before the selector in bulk. + self.when_in_range.sample_volume(context, buffer, volume)?; + context.with_buffer(volume.size(), |context, input| { + self.input.sample_volume(context, input, volume)?; + context.with_buffer(volume.size(), |context, outside| { + self.when_out_of_range + .sample_volume(context, outside, volume)?; + for i in 0..buffer.len() { + if !self.contains(input[i]) { + buffer[i] = outside[i]; + } + } + Ok(()) + }) + }) + } +} + +/// An explicitly compiled value. Distinguishing literal constants here avoids +/// scratch allocation in the constant-endpoint interpolation specializations. +#[derive(Clone, Debug)] +pub enum DensityValue { + Constant(f32), + Sampler(Arc), +} +impl DensityValue { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + match self { + Self::Constant(value) => Ok(*value), + Self::Sampler(sampler) => sampler.sample_value(context, position), + } + } + fn with_volume( + &self, + context: &mut SamplerContext, + volume: DensityVolume, + use_values: impl FnOnce(&mut SamplerContext, Values<'_>) -> Result, + ) -> Result { + match self { + Self::Constant(value) => use_values(context, Values::Constant(*value)), + Self::Sampler(sampler) => context.with_buffer(volume.size(), |context, buffer| { + sampler.sample_volume(context, buffer, volume)?; + use_values(context, Values::Buffer(buffer)) + }), + } + } +} +#[derive(Clone, Copy)] +enum Values<'a> { + Constant(f32), + Buffer(&'a [f32]), +} +impl Values<'_> { + fn get(self, index: usize) -> f32 { + match self { + Self::Constant(value) => value, + Self::Buffer(buffer) => buffer[index], + } + } +} +#[derive(Clone, Debug)] +pub struct LerpSampler { + pub alpha: Arc, + pub first: DensityValue, + pub second: DensityValue, +} +fn interpolate(alpha: f32, first: f32, second: f32) -> f32 { + if alpha == 0.0 { + first + } else if alpha == 1.0 { + second + } else { + first + alpha * (second - first) + } +} +impl DensitySampler for LerpSampler { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + let alpha = self.alpha.sample_value(context, position)?; + if alpha == 0.0 { + return self.first.sample_value(context, position); + } + if alpha == 1.0 { + return self.second.sample_value(context, position); + } + let first = self.first.sample_value(context, position)?; + let second = self.second.sample_value(context, position)?; + Ok(interpolate(alpha, first, second)) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_exact_buffer(buffer, volume)?; + self.alpha.sample_volume(context, buffer, volume)?; + self.first.with_volume(context, volume, |context, first| { + self.second.with_volume(context, volume, |_, second| { + for (index, alpha) in buffer.iter_mut().enumerate() { + *alpha = interpolate(*alpha, first.get(index), second.get(index)); + } + Ok(()) + }) + }) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InvalidIntervals; +impl std::fmt::Display for InvalidIntervals { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("compiled interval selection requires one more branch than thresholds, at most 256 branches") + } +} +impl std::error::Error for InvalidIntervals {} + +/// Compiled interval selection. Threshold order is preserved, including NaNs +/// and equal thresholds; sorting and codec validation belong to the compiler. +#[derive(Clone, Debug)] +pub struct IntervalSelectSampler { + input: Arc, + thresholds: Vec, + branches: Vec>, +} +impl IntervalSelectSampler { + pub fn new( + input: Arc, + thresholds: Vec, + branches: Vec>, + ) -> Result { + if branches.len() > 256 || thresholds.len().checked_add(1) != Some(branches.len()) { + return Err(InvalidIntervals); + } + Ok(Self { + input, + thresholds, + branches, + }) + } + fn select(&self, value: f32) -> usize { + self.thresholds + .iter() + .position(|threshold| value < *threshold) + .unwrap_or(self.branches.len() - 1) + } +} +impl DensitySampler for IntervalSelectSampler { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + let value = self.input.sample_value(context, position)?; + self.branches[self.select(value)].sample_value(context, position) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_exact_buffer(buffer, volume)?; + let total = volume + .size() + .checked_mul(self.branches.len()) + .filter(|count| *count <= isize::MAX as usize / size_of::()) + .ok_or(DensityError::VolumeTooLarge)?; + self.input.sample_volume(context, buffer, volume)?; + // Contiguous retained storage replaces a separate allocation per branch. + // Each child still receives a slice with exactly the logical volume size. + context.with_buffer(total, |context, values| { + for (branch, output) in self + .branches + .iter() + .zip(values.chunks_exact_mut(volume.size())) + { + branch.sample_volume(context, output, volume)?; + } + // Delay every output selection until all child volumes have returned. + for (index, input) in buffer.iter_mut().enumerate() { + *input = values[self.select(*input) * volume.size() + index]; + } + Ok(()) + }) + } +} diff --git a/crates/horizon-core/src/density/slice.rs b/crates/horizon-core/src/density/slice.rs new file mode 100644 index 000000000..e1f6d4ed7 --- /dev/null +++ b/crates/horizon-core/src/density/slice.rs @@ -0,0 +1,85 @@ +use super::*; + +/// Coordinates fixed by the compiled single-axis or combined XZ slice node. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SliceAxes { + X(i32), + Y(i32), + Z(i32), + Xz { x: i32, z: i32 }, +} +impl SliceAxes { + fn coordinates(self) -> [Option; 3] { + match self { + Self::X(x) => [Some(x), None, None], + Self::Y(y) => [None, Some(y), None], + Self::Z(z) => [None, None, Some(z)], + Self::Xz { x, z } => [Some(x), None, Some(z)], + } + } +} + +#[derive(Clone, Debug)] +pub struct SliceSampler { + pub input: Arc, + pub axes: SliceAxes, +} +impl DensitySampler for SliceSampler { + fn sample_value( + &self, + context: &mut SamplerContext, + mut position: [i32; 3], + ) -> Result { + for (axis, fixed) in self.axes.coordinates().into_iter().enumerate() { + if let Some(coordinate) = fixed { + position[axis] = coordinate; + } + } + self.input.sample_value(context, position) + } + + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_buffer(buffer, volume)?; + let fixed = self.axes.coordinates(); + let mut sizes = volume.sizes().map(|size| size as i32); + let mut minimum = volume.minimum(); + for (axis, coordinate) in fixed.into_iter().enumerate() { + if let Some(coordinate) = coordinate { + sizes[axis] = 1; + minimum[axis] = coordinate; + } + } + // Keep the original steps, even on fixed axes: cached children observe + // the complete volume descriptor. An unchanged slice delegates directly + // and therefore retains the child's tail and partial-write behavior. + let reduced = DensityVolume::new(sizes, minimum, volume.steps())?; + if reduced == volume { + return self.input.sample_volume(context, buffer, volume); + } + context.with_buffer(reduced.size(), |context, samples| { + self.input.sample_volume(context, samples, reduced)?; + let [sx, sy, sz] = volume.sizes(); + let [rx, ry, _] = reduced.sizes(); + for z in 0..sz { + let source_z = if fixed[2].is_some() { 0 } else { z }; + for x in 0..sx { + let source_x = if fixed[0].is_some() { 0 } else { x }; + let source = (source_x + source_z * rx) * ry; + let target = (x + z * sx) * sy; + let column = &mut buffer[target..target + sy]; + if fixed[1].is_some() { + column.fill(samples[source]); + } else { + column.copy_from_slice(&samples[source..source + sy]); + } + } + } + Ok(()) + }) + } +} diff --git a/crates/horizon-core/src/density/spline.rs b/crates/horizon-core/src/density/spline.rs new file mode 100644 index 000000000..14eaa0adf --- /dev/null +++ b/crates/horizon-core/src/density/spline.rs @@ -0,0 +1,344 @@ +use super::*; +use std::collections::HashMap; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SplineError { + EmptyPoints, + NestingTooDeep, + MissingCoordinate, + NanConstant, +} +impl std::fmt::Display for SplineError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::NanConstant => "a compiled constant spline cannot be NaN", + Self::EmptyPoints => "a multipoint spline requires at least one point", + Self::NestingTooDeep => "spline nesting exceeds 256 levels", + Self::MissingCoordinate => "spline coordinate has no density sampler", + }) + } +} +impl std::error::Error for SplineError {} + +#[derive(Clone, Debug)] +pub struct SplinePoint { + pub location: f32, + pub value: CubicSpline, + pub derivative: f32, +} +#[derive(Clone, Debug)] +pub struct MultipointSpline { + pub(super) coordinate: C, + pub(super) points: Vec>, + pub(super) depth: usize, +} +/// An immutable spline definition. Coordinate indices are resolved against a +/// sampler table at compilation. Point order is retained, including NaNs and +/// equal locations; codec ordering constraints belong to serialized definitions. +#[derive(Clone, Debug)] +pub enum CubicSpline { + Constant(f32), + Multipoint(Arc>), +} +impl CubicSpline { + pub fn multipoint(coordinate: C, points: Vec>) -> Result { + let depth = points + .iter() + .map(|p| match &p.value { + Self::Constant(_) => 0, + Self::Multipoint(node) => node.depth, + }) + .max() + .ok_or(SplineError::EmptyPoints)? + + 1; + if depth > 256 { + return Err(SplineError::NestingTooDeep); + } + Ok(Self::Multipoint(Arc::new(MultipointSpline { + coordinate, + points, + depth, + }))) + } + fn sample( + &self, + coordinate: &mut impl FnMut(C) -> Result, + ) -> Result { + let node = match self { + Self::Constant(value) => return Ok(*value), + Self::Multipoint(node) => node, + }; + let input = coordinate(node.coordinate)?; + // Vanilla binarySearch finds the first strictly greater location. Keep + // this search even for manually supplied unsorted or NaN locations. + let mut first = 0; + let mut remaining = node.points.len(); + while remaining != 0 { + let half = remaining / 2; + let middle = first + half; + if input < node.points[middle].location { + remaining = half; + } else { + first = middle + 1; + remaining -= half + 1; + } + } + if first == 0 || first == node.points.len() { + let endpoint = if first == 0 { 0 } else { first - 1 }; + let point = &node.points[endpoint]; + let value = point.value.sample(coordinate)?; + return Ok(if point.derivative == 0.0 { + value + } else { + value + point.derivative * (input - point.location) + }); + } + let left = &node.points[first - 1]; + let right = &node.points[first]; + let width = right.location - left.location; + let alpha = (input - left.location) / width; + let left_value = left.value.sample(coordinate)?; + let right_value = right.value.sample(coordinate)?; + let left_correction = left.derivative * width - (right_value - left_value); + let right_correction = -right.derivative * width + (right_value - left_value); + let linear = left_value + alpha * (right_value - left_value); + let correction = left_correction + alpha * (right_correction - left_correction); + Ok(linear + (alpha * (1.0 - alpha)) * correction) + } + /// Vanilla's conservative range analysis, with coordinate ranges supplied + /// by the enclosing graph. Child ranges are evaluated in reference order. + pub fn range( + &self, + coordinate: &mut impl FnMut(C) -> Interval, + ) -> Result { + self.try_range(&mut |id| Ok(coordinate(id))) + } + /// Fallible coordinate range lookup, preserving early returns and error order. + pub fn try_range>( + &self, + coordinate: &mut impl FnMut(C) -> Result, + ) -> Result { + use super::arithmetic::{java_max, java_min}; + let node = match self { + Self::Constant(value) => return Interval::exact(*value).map_err(E::from), + Self::Multipoint(node) => node, + }; + let input = coordinate(node.coordinate)?; + if input.is_nai() { + return Ok(input); + } + let mut minimum = f32::INFINITY; + let mut maximum = f32::NEG_INFINITY; + let first = &node.points[0]; + let last = node.points.last().unwrap(); + let extend = |point: &SplinePoint, input: f32, value: f32| { + if point.derivative == 0.0 { + value + } else { + value + point.derivative * (input - point.location) + } + }; + if input.min() < first.location { + let value = first.value.try_range(coordinate)?; + let low = extend(first, input.min(), value.min()); + let high = extend(first, input.min(), value.max()); + minimum = java_min(minimum, java_min(low, high)); + maximum = java_max(maximum, java_max(low, high)); + } + if input.max() > last.location { + let value = last.value.try_range(coordinate)?; + let low = extend(last, input.max(), value.min()); + let high = extend(last, input.max(), value.max()); + minimum = java_min(minimum, java_min(low, high)); + maximum = java_max(maximum, java_max(low, high)); + } + let ranges = node + .points + .iter() + .map(|point| point.value.try_range(coordinate)) + .collect::, _>>()?; + for range in &ranges { + minimum = java_min(minimum, range.min()); + maximum = java_max(maximum, range.max()); + } + for (points, ranges) in node.points.windows(2).zip(ranges.windows(2)) { + let width = points[1].location - points[0].location; + let left = ranges[0]; + let right = ranges[1]; + let derivative_left = points[0].derivative; + let derivative_right = points[1].derivative; + if derivative_left == 0.0 && derivative_right == 0.0 { + continue; + } + let tangent_left = derivative_left * width; + let tangent_right = derivative_right * width; + let value_min = java_min(left.min(), right.min()); + let value_max = java_max(left.max(), right.max()); + let low_left = tangent_left - right.max() + left.min(); + let high_left = tangent_left - right.min() + left.max(); + let low_right = -tangent_right + right.min() - left.max(); + let high_right = -tangent_right + right.max() - left.min(); + minimum = java_min(minimum, value_min + 0.25 * java_min(low_left, low_right)); + maximum = java_max(maximum, value_max + 0.25 * java_max(high_left, high_right)); + } + Interval::new(minimum, maximum).map_err(E::from) + } + pub(super) fn coordinates_mut(&mut self) -> Vec<&mut C> { + match self { + Self::Constant(_) => Vec::new(), + Self::Multipoint(node) => { + let node = Arc::make_mut(node); + let mut coordinates = vec![&mut node.coordinate]; + for point in &mut node.points { + coordinates.extend(point.value.coordinates_mut()); + } + coordinates + } + } + } + pub(super) fn try_map_coordinates( + &self, + map: &mut impl FnMut(C) -> Result, + ) -> Result, E> { + Ok(match self { + Self::Constant(value) => CubicSpline::Constant(*value), + Self::Multipoint(node) => { + let coordinate = map(node.coordinate)?; + let points = node + .points + .iter() + .map(|point| { + Ok(SplinePoint { + location: point.location, + value: point.value.try_map_coordinates(map)?, + derivative: point.derivative, + }) + }) + .collect::, E>>()?; + CubicSpline::Multipoint(Arc::new(MultipointSpline { + coordinate, + points, + depth: node.depth, + })) + } + }) + } +} +impl CubicSpline { + fn compile( + &self, + inputs: &[Arc], + ids: &mut HashMap, + coordinates: &mut Vec>, + ) -> Result { + match self { + Self::Constant(value) => Ok(Self::Constant(*value)), + Self::Multipoint(node) => { + let coordinate = if let Some(index) = ids.get(&node.coordinate) { + *index + } else { + let input = inputs + .get(node.coordinate) + .ok_or(SplineError::MissingCoordinate)?; + let index = coordinates.len(); + coordinates.push(input.clone()); + ids.insert(node.coordinate, index); + index + }; + let points = node + .points + .iter() + .map(|point| { + Ok(SplinePoint { + location: point.location, + derivative: point.derivative, + value: point.value.compile(inputs, ids, coordinates)?, + }) + }) + .collect::, SplineError>>()?; + Self::multipoint(coordinate, points) + } + } + } +} + +#[derive(Clone, Debug)] +pub struct SplineSampler { + spline: CubicSpline, + coordinates: Vec>, +} +impl SplineSampler { + /// Equal coordinate IDs share evaluation results. Structural function + /// identity and deduplication are supplied by the density graph compiler. + pub fn new( + spline: &CubicSpline, + inputs: &[Arc], + ) -> Result { + if matches!(spline, CubicSpline::Constant(value) if value.is_nan()) { + return Err(SplineError::NanConstant); + } + let mut coordinates = Vec::new(); + let spline = spline.compile(inputs, &mut HashMap::new(), &mut coordinates)?; + Ok(Self { + spline, + coordinates, + }) + } + pub fn coordinate_count(&self) -> usize { + self.coordinates.len() + } +} +impl DensitySampler for SplineSampler { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + context.with_buffer(self.coordinates.len(), |context, values| { + values.fill(f32::NAN); + self.spline.sample(&mut |id| { + if values[id].is_nan() { + values[id] = self.coordinates[id].sample_value(context, position)?; + } + Ok(values[id]) + }) + }) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + output: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_buffer(output, volume)?; + if let CubicSpline::Constant(value) = self.spline { + output.fill(value); + return Ok(()); + } + check_exact_buffer(output, volume)?; + let mut buffers: Vec>> = + (0..self.coordinates.len()).map(|_| None).collect(); + let result = (|| { + for (index, value) in output.iter_mut().enumerate() { + *value = self.spline.sample(&mut |id| { + if buffers[id].is_none() { + let mut buffer = context.scratch.pop().unwrap_or_default(); + buffer.resize(volume.size(), 0.0); + if let Err(error) = + self.coordinates[id].sample_volume(context, &mut buffer, volume) + { + context.scratch.push(buffer); + return Err(error); + } + buffers[id] = Some(buffer); + } + Ok(buffers[id].as_ref().unwrap()[index]) + })?; + } + Ok(()) + })(); + // Release in coordinate-ID order, also after a later lazy child fails. + context.scratch.extend(buffers.into_iter().flatten()); + result + } +} diff --git a/crates/horizon-core/src/density/surface.rs b/crates/horizon-core/src/density/surface.rs new file mode 100644 index 000000000..df437bc2b --- /dev/null +++ b/crates/horizon-core/src/density/surface.rs @@ -0,0 +1,99 @@ +use super::*; + +/// The unsliced search primitive. Compiled terrain graphs wrap this in a Y=0 +/// slice through `compile_surface_search`, so their upper bound is horizontal. +#[derive(Clone, Debug)] +pub struct FindTopSurfaceSampler { + density: Arc, + upper_bound: Arc, + lower_bound: i32, + cell_height: i32, +} +impl FindTopSurfaceSampler { + pub fn new( + density: Arc, + upper_bound: Arc, + lower_bound: i32, + cell_height: i32, + ) -> Result { + if cell_height <= 0 { + return Err(DensityError::NonpositiveSteps.into()); + } + Ok(Self { + density, + upper_bound, + lower_bound, + cell_height, + }) + } + fn find_surface_from( + &self, + context: &mut SamplerContext, + x: i32, + z: i32, + upper: f32, + ) -> Result { + let quotient = upper / self.cell_height as f32; + // Java 26.3 Mth.floor(float) widens to double, calls Math.floor, + // then uses a saturating double-to-int conversion (NaN becomes zero). + let floor = (quotient as f64).floor() as i32; + let mut y = floor.wrapping_mul(self.cell_height); + if y <= self.lower_bound { + return Ok(self.lower_bound); + } + while y >= self.lower_bound { + if self.density.sample_value(context, [x, y, z])? > 0.0 { + return Ok(y); + } + // Malformed manually constructed bounds can otherwise wrap and + // loop forever; serialized vanilla terrain bounds do not reach this. + y = y + .checked_sub(self.cell_height) + .ok_or(SampleError::SurfaceSearchOverflow)?; + } + Ok(self.lower_bound) + } +} +impl DensitySampler for FindTopSurfaceSampler { + fn sample_value( + &self, + context: &mut SamplerContext, + [x, y, z]: [i32; 3], + ) -> Result { + let upper = self.upper_bound.sample_value(context, [x, y, z])?; + Ok(self.find_surface_from(context, x, z, upper)? as f32) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + output: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_buffer(output, volume)?; + if volume.sizes()[1] != 1 { + return Err(SampleError::SurfaceRequiresSingleLayer); + } + self.upper_bound.sample_volume(context, output, volume)?; + visit(volume, |index, [x, _, z]| { + output[index] = self.find_surface_from(context, x, z, output[index])? as f32; + Ok(()) + }) + } +} + +pub fn compile_surface_search( + density: Arc, + upper_bound: Arc, + lower_bound: i32, + cell_height: i32, +) -> Result { + Ok(SliceSampler { + input: Arc::new(FindTopSurfaceSampler::new( + density, + upper_bound, + lower_bound, + cell_height, + )?), + axes: SliceAxes::Y(0), + }) +} diff --git a/crates/horizon-core/src/density/terrain_noise.rs b/crates/horizon-core/src/density/terrain_noise.rs new file mode 100644 index 000000000..908a06576 --- /dev/null +++ b/crates/horizon-core/src/density/terrain_noise.rs @@ -0,0 +1,220 @@ +use super::*; +use crate::{ + noise::{NoiseBuildError, NoiseStack, SmearedPerlinNoise}, + random::RandomSource, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ShiftNoiseKind { + Shift, + ShiftA, + ShiftB, +} + +/// Compile the three offset-noise variants without changing their bulk paths. +pub fn compile_shift_noise(noise: Arc, kind: ShiftNoiseKind) -> Arc { + if kind == ShiftNoiseKind::ShiftB { + return Arc::new(ShiftBSampler { noise }); + } + Arc::new(UnarySampler { + input: Arc::new(NoiseSampler { + noise, + xz_scale: 0.25, + y_scale: if kind == ShiftNoiseKind::ShiftA { + 0.0 + } else { + 0.25 + }, + }), + operation: UnaryOp::Multiply(4.0), + }) +} +#[derive(Clone, Debug)] +struct ShiftBSampler { + noise: Arc, +} +impl DensitySampler for ShiftBSampler { + fn sample_value( + &self, + _: &mut SamplerContext, + [x, _, z]: [i32; 3], + ) -> Result { + Ok(self.noise.get3(z as f64 * 0.25, x as f64 * 0.25, 0.0) * 4.0) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + check_buffer(buffer, volume)?; + let [sx, sy, sz] = volume.sizes(); + let [mx, _, mz] = volume.minimum(); + let [dx, _, dz] = volume.steps(); + let transposed = DensityVolume::new([sz as i32, sx as i32, 1], [mz, mx, 0], [dz, dx, 1])?; + context.with_buffer(transposed.size(), |_, plane| { + plane.fill(0.0); + self.noise + .add_to_volume(plane, transposed, 0.25, 0.25, 4.0)?; + for z in 0..sz { + for x in 0..sx { + let start = (x + z * sx) * sy; + buffer[start..start + sy].fill(plane[x + z * sx]); + } + } + Ok(()) + }) + } +} + +/// Parameters for vanilla's old blended terrain density function. Serialized +/// codec limits and compile-context seed lookup are separate integration work. +#[derive(Clone, Copy, Debug)] +pub struct BlendedNoise { + pub xz_scale: f64, + pub y_scale: f64, + pub xz_factor: f64, + pub y_factor: f64, + pub smear_scale_multiplier: f64, +} +#[derive(Clone, Debug)] +pub struct BlendedFbmSet { + pub min_limit: NoiseStack, + pub max_limit: NoiseStack, + pub main: NoiseStack, +} +impl BlendedNoise { + pub fn create_fbm_set( + &self, + random: &mut impl RandomSource, + ) -> Result { + let smear = (684.412 * self.y_scale) * self.smear_scale_multiplier; + let main_smear = smear / self.y_factor; + Ok(BlendedFbmSet { + min_limit: create_blended_fbm(random, -15, smear, 0.9999847412109375)?, + max_limit: create_blended_fbm(random, -15, smear, 0.9999847412109375)?, + main: create_blended_fbm(random, -7, main_smear, 12.75)?, + }) + } + pub fn compile(&self, random: &mut impl RandomSource) -> Result { + let layers = self.create_fbm_set(random)?; + let xz_scale = 684.412 * self.xz_scale; + let y_scale = 684.412 * self.y_scale; + let min_limit = Arc::new(NoiseSampler { + noise: Arc::new(layers.min_limit), + xz_scale, + y_scale, + }); + let max_limit = Arc::new(NoiseSampler { + noise: Arc::new(layers.max_limit), + xz_scale, + y_scale, + }); + let main = Arc::new(NoiseSampler { + noise: Arc::new(layers.main), + xz_scale: xz_scale / self.xz_factor, + y_scale: y_scale / self.y_factor, + }); + let shifted = Arc::new(UnarySampler { + input: main, + operation: UnaryOp::Add(0.5), + }); + let alpha = Arc::new(UnarySampler { + input: shifted, + operation: UnaryOp::Clamp { min: 0.0, max: 1.0 }, + }); + Ok(LerpSampler { + alpha, + first: DensityValue::Sampler(min_limit), + second: DensityValue::Sampler(max_limit), + }) + } + pub fn range(&self) -> Result { + let smear = (684.412 * self.y_scale) * self.smear_scale_multiplier; + let mut range = Interval::exact(0.0)?; + let mut frequency = 1.0; + let mut amplitude = 0.9999847412109375 / 65535.0; + for _ in 0..16 { + let base = Interval::symmetric(((smear * frequency).abs() + 2.0) as f32)?; + range = range.add_range(base.multiply_range(Interval::exact(amplitude as f32)?)); + frequency /= 2.0; + amplitude *= 2.0; + } + Ok(range) + } +} + +/// Construct high-to-low frequency smeared octaves, consuming the caller's +/// stream directly. The public API caps work at 4096 layers before any draws. +pub fn create_blended_fbm( + random: &mut impl RandomSource, + first_octave: i32, + smear: f64, + amplitude: f64, +) -> Result { + if first_octave > 0 { + return Err(NoiseBuildError::PositiveLegacyOctaves); + } + if first_octave < -4095 { + return Err(NoiseBuildError::TooManyOctaves); + } + let count = 1 - first_octave; + let power = if count > 1023 { + f64::INFINITY + } else { + f64::from_bits(((count + 1023) as u64) << 52) + }; + let mut amplitude = amplitude / (power - 1.0); + let mut frequency = 1.0; + let mut builder = NoiseStack::builder(); + for _ in 0..count { + builder.add( + Arc::new(SmearedPerlinNoise::new(random, smear * frequency)), + frequency, + amplitude as f32, + ); + frequency /= 2.0; + amplitude *= 2.0; + } + Ok(builder.build()?) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DistanceMetric { + Euclidean, + EuclideanSquared, + Manhattan, + Chebyshev, +} +impl DistanceMetric { + pub fn compute2(self, x: f32, y: f32) -> f32 { + match self { + Self::Euclidean => ((x * x + y * y) as f64).sqrt() as f32, + Self::EuclideanSquared => x * x + y * y, + Self::Manhattan => x.abs() + y.abs(), + Self::Chebyshev => arithmetic::java_max(x.abs(), y.abs()), + } + } + pub fn compute3(self, x: f32, y: f32, z: f32) -> f32 { + match self { + Self::Euclidean => ((x * x + y * y + z * z) as f64).sqrt() as f32, + Self::EuclideanSquared => x * x + y * y + z * z, + Self::Manhattan => x.abs() + y.abs() + z.abs(), + Self::Chebyshev => { + arithmetic::java_max(arithmetic::java_max(x.abs(), y.abs()), z.abs()) + } + } + } +} +#[derive(Clone, Copy, Debug)] +pub struct DistanceToPointSampler { + pub point: [i32; 3], + pub metric: DistanceMetric, +} +impl DensitySampler for DistanceToPointSampler { + fn sample_value(&self, _: &mut SamplerContext, position: [i32; 3]) -> Result { + let delta: [f32; 3] = + std::array::from_fn(|i| self.point[i].wrapping_sub(position[i]) as f32); + Ok(self.metric.compute3(delta[0], delta[1], delta[2])) + } +} diff --git a/crates/horizon-core/src/density/tests.rs b/crates/horizon-core/src/density/tests.rs new file mode 100644 index 000000000..77a643097 --- /dev/null +++ b/crates/horizon-core/src/density/tests.rs @@ -0,0 +1,757 @@ +use super::*; +use crate::{noise::PerlinNoise, random::LegacyRandom}; + +#[test] +fn tail_writes_follow_the_selected_bulk_sampler() { + let mut context = SamplerContext::default(); + let volume = DensityVolume::new([2, 3, 2], [-3, -4, -5], [1, 2, 1]).unwrap(); + let mut buffer = vec![17.0; volume.size() + 2]; + ConstantSampler(-0.0) + .sample_volume(&mut context, &mut buffer, volume) + .unwrap(); + assert!(buffer.iter().all(|v| v.to_bits() == (-0.0_f32).to_bits())); + GradientSampler::new(Axis::Y, TilingMode::ClampToEdge, -4, 0, -1.0, 1.0) + .sample_volume(&mut context, &mut buffer, volume) + .unwrap(); + assert_eq!(&buffer[..3], &[-1.0, 0.0, 1.0]); + assert_eq!(buffer[volume.size()].to_bits(), (-0.0_f32).to_bits()); + let noise = NoiseSampler { + noise: Arc::new(PerlinNoise::new(&mut LegacyRandom::new(0))), + xz_scale: 0.1, + y_scale: 0.2, + }; + noise + .sample_volume(&mut context, &mut buffer, volume) + .unwrap(); + assert!(buffer[volume.size()..].iter().all(|v| v.to_bits() == 0)); +} + +#[test] +fn invalid_buffer_is_rejected_before_child_evaluation() { + let volume = DensityVolume::new([1, 2, 1], [0; 3], [1; 3]).unwrap(); + let mut context = SamplerContext::default(); + let mut buffer = [19.0]; + let gradient = GradientSampler::new(Axis::X, TilingMode::Repeat, 0, 0, 1.0, 2.0); + assert_eq!( + gradient.sample_volume(&mut context, &mut buffer, volume), + Err(SampleError::Volume(DensityError::BufferTooShort)) + ); + assert_eq!(buffer, [19.0]); +} + +#[test] +fn scratch_returns_to_context_after_nested_sampling_errors() { + let mut context = SamplerContext::default(); + let error = context.with_buffer(16, |context, _| { + context.with_buffer(32, |_, _| Err::<(), _>(SampleError::ZeroGradientPeriod)) + }); + assert_eq!(error, Err(SampleError::ZeroGradientPeriod)); + assert_eq!(context.scratch.len(), 2); + context + .with_buffer(8, |context, outer| { + outer.fill(17.0); + context.with_buffer(8, |_, inner| { + inner.fill(29.0); + Ok(()) + })?; + assert!(outer.iter().all(|v| *v == 17.0)); + Ok(()) + }) + .unwrap(); + assert_eq!(context.scratch.len(), 2); + context.clear_scratch(); + assert!(context.scratch.is_empty()); +} + +#[test] +fn scalar_shortcuts_and_bulk_arithmetic_keep_distinct_results() { + let mut context = SamplerContext::default(); + let volume = DensityVolume::new([1; 3], [0; 3], [1; 3]).unwrap(); + let multiply = BinarySampler { + left: Arc::new(ConstantSampler(-0.0)), + right: Arc::new(ConstantSampler(f32::NAN)), + operation: BinaryOp::Multiply, + }; + assert_eq!( + multiply + .sample_value(&mut context, [0; 3]) + .unwrap() + .to_bits(), + 0 + ); + let mut buffer = [17.0]; + multiply + .sample_volume(&mut context, &mut buffer, volume) + .unwrap(); + assert!(buffer[0].is_nan()); + let minimum = BinarySampler { + left: Arc::new(ConstantSampler(0.0)), + right: Arc::new(ConstantSampler(-0.0)), + operation: BinaryOp::Minimum { + right_min: f32::NEG_INFINITY, + }, + }; + assert_eq!( + minimum + .sample_value(&mut context, [0; 3]) + .unwrap() + .to_bits(), + (-0.0_f32).to_bits() + ); + minimum + .sample_volume(&mut context, &mut buffer, volume) + .unwrap(); + assert_eq!(buffer[0].to_bits(), 0); +} + +#[test] +fn bulk_choice_evaluates_in_range_before_a_failing_selector() { + let mut context = SamplerContext::default(); + let volume = DensityVolume::new([1; 3], [0; 3], [1; 3]).unwrap(); + let choice = RangeChoiceSampler { + input: Arc::new(GradientSampler::new( + Axis::X, + TilingMode::Repeat, + 0, + 0, + 0.0, + 1.0, + )), + min_inclusive: 0.0, + max_exclusive: 1.0, + when_in_range: Arc::new(ConstantSampler(3.0)), + when_out_of_range: Arc::new(ConstantSampler(7.0)), + }; + let mut buffer = [19.0]; + assert_eq!( + choice.sample_volume(&mut context, &mut buffer, volume), + Err(SampleError::ZeroGradientPeriod) + ); + assert_eq!(buffer, [3.0]); + assert_eq!(context.scratch.len(), 1); + let mut too_long = [19.0; 2]; + assert_eq!( + choice.sample_volume(&mut context, &mut too_long, volume), + Err(SampleError::ExactBufferSizeRequired) + ); + assert_eq!(too_long, [19.0; 2]); +} + +#[test] +fn interval_branch_errors_keep_selector_output_and_return_scratch() { + let mut context = SamplerContext::default(); + let volume = DensityVolume::new([1; 3], [0; 3], [1; 3]).unwrap(); + let selector = IntervalSelectSampler::new( + Arc::new(ConstantSampler(-3.0)), + vec![0.0], + vec![ + Arc::new(ConstantSampler(7.0)), + Arc::new(GradientSampler::new( + Axis::X, + TilingMode::Repeat, + 0, + 0, + 0.0, + 1.0, + )), + ], + ) + .unwrap(); + assert_eq!(selector.sample_value(&mut context, [0; 3]), Ok(7.0)); + let mut buffer = [19.0]; + assert_eq!( + selector.sample_volume(&mut context, &mut buffer, volume), + Err(SampleError::ZeroGradientPeriod) + ); + assert_eq!(buffer, [-3.0]); + assert_eq!(context.scratch.len(), 1); + assert_eq!(context.scratch[0].len(), 2); + assert!(IntervalSelectSampler::new(Arc::new(ConstantSampler(0.0)), vec![], vec![]).is_err()); +} + +#[test] +fn range_arithmetic_and_zero_equality_match_reference_special_cases() { + let zero = Interval::exact(0.0).unwrap(); + assert_eq!(zero.multiply_range(Interval::INFINITE), zero); + assert!(zero.reciprocal().is_nai()); + assert!( + Interval::exact(f32::INFINITY) + .unwrap() + .add_range(Interval::exact(f32::NEG_INFINITY).unwrap()) + .is_nai() + ); + let cached = Interval::new(-0.0, 1.0).unwrap(); + assert_eq!(cached.min().to_bits(), 0); + let mixed_zero = Interval::new(-0.0, 0.0).unwrap(); + assert_eq!(mixed_zero, zero); + assert_ne!(mixed_zero.java_hash_code(), zero.java_hash_code()); + assert_eq!(Interval::NAI, Interval::NAI); + assert_eq!( + Interval::encapsulating(&[Interval::NAI, cached]), + Ok(cached) + ); + assert_eq!(Interval::encapsulating(&[]), Err(IntervalError::EmptyInput)); +} + +#[test] +fn monotonic_mapping_skips_nai_and_rejects_nan_after_both_endpoints() { + let mut calls = Vec::new(); + assert_eq!( + Interval::NAI.map_monotonic(|v| { + calls.push(v); + v + }), + Ok(Interval::NAI) + ); + assert!(calls.is_empty()); + assert_eq!( + Interval::new(-1.0, 1.0).unwrap().map_monotonic(|v| { + calls.push(v); + v.sqrt() + }), + Err(IntervalError::NanMappedBound) + ); + assert_eq!(calls, [-1.0, 1.0]); + assert_eq!( + Interval::exact(0.0) + .unwrap() + .lerp_values(f32::INFINITY, f32::NEG_INFINITY), + Interval::exact(f32::INFINITY).unwrap() + ); +} + +#[test] +fn shift_b_repeats_each_horizontal_sample_and_preserves_tail() { + let mut context = SamplerContext::default(); + let volume = DensityVolume::new([2, 3, 4], [-17, -64, 32], [4, 8, 16]).unwrap(); + let source = Arc::new(PerlinNoise::new(&mut LegacyRandom::new(0))); + let sampler = compile_shift_noise(source, ShiftNoiseKind::ShiftB); + let mut buffer = vec![19.0; volume.size() + 2]; + sampler + .sample_volume(&mut context, &mut buffer, volume) + .unwrap(); + for column in buffer[..volume.size()].chunks_exact(3) { + assert!(column.iter().all(|v| v.to_bits() == column[0].to_bits())); + } + assert_eq!(&buffer[volume.size()..], &[19.0, 19.0]); + assert_eq!(context.scratch.len(), 1); + assert_eq!(context.scratch[0].len(), 8); + let mut short = [23.0; 2]; + assert_eq!( + sampler.sample_volume(&mut context, &mut short, volume), + Err(SampleError::Volume(DensityError::BufferTooShort)) + ); + assert_eq!(short, [23.0; 2]); +} + +#[test] +fn blended_fbm_work_bound_rejects_before_random_draws() { + let mut random = LegacyRandom::new(0); + let mut expected = random.clone(); + assert!(matches!( + create_blended_fbm(&mut random, i32::MIN, 1.0, 1.0), + Err(crate::noise::NoiseBuildError::TooManyOctaves) + )); + assert!(matches!( + create_blended_fbm(&mut random, 1, 1.0, 1.0), + Err(crate::noise::NoiseBuildError::PositiveLegacyOctaves) + )); + use crate::random::RandomSource; + assert_eq!(random.next_long(), expected.next_long()); +} + +#[test] +fn volume_lookup_requires_exact_lattice_and_preserves_java_overflow() { + let volume = DensityVolume::new([2, 3, 2], [i32::MAX, -64, 32], [4, 1, 4]).unwrap(); + assert_eq!(volume.index_of_block([i32::MIN + 3, -63, 36]), Some(10)); + assert_eq!(volume.index_of_block([i32::MIN, -64, 32]), None); + let overflow = DensityVolume::new([2, 1, 1], [0; 3], [i32::MAX, 1, 1]).unwrap(); + assert_eq!(overflow.index_of_block([0; 3]), None); +} + +#[test] +fn cache_returns_filled_failure_buffer_on_the_next_volume_request() { + let mut context = SamplerContext::cached(); + let volume = DensityVolume::new([1; 3], [0; 3], [1; 3]).unwrap(); + let input = RangeChoiceSampler { + input: Arc::new(GradientSampler::new( + Axis::X, + TilingMode::Repeat, + 0, + 0, + 0.0, + 1.0, + )), + min_inclusive: 0.0, + max_exclusive: 1.0, + when_in_range: Arc::new(ConstantSampler(7.0)), + when_out_of_range: Arc::new(ConstantSampler(9.0)), + }; + let cached = CachingDensitySampler::new(0, Arc::new(input)).unwrap(); + let mut buffer = [19.0]; + assert_eq!( + cached.sample_volume(&mut context, &mut buffer, volume), + Err(SampleError::ZeroGradientPeriod) + ); + assert_eq!(buffer, [19.0]); + cached + .sample_volume(&mut context, &mut buffer, volume) + .unwrap(); + assert_eq!(buffer, [7.0]); + assert_eq!(cached.sample_value(&mut context, [0; 3]), Ok(7.0)); + context.clear_caches(); + assert_eq!( + cached.sample_value(&mut context, [0; 3]), + Err(SampleError::ZeroGradientPeriod) + ); + assert!(matches!( + CachingDensitySampler::new(65536, Arc::new(ConstantSampler(0.0))), + Err(SampleError::CacheIdOutOfRange) + )); +} + +#[test] +fn slices_delegate_matching_volumes_and_isolate_reduced_child_failures() { + let mut context = SamplerContext::default(); + let slice = SliceSampler { + input: Arc::new(ConstantSampler(-0.0)), + axes: SliceAxes::Xz { x: 7, z: 9 }, + }; + for (sizes, minimum, delegated) in [ + ([1, 2, 1], [7, -64, 9], true), + ([1, 2, 1], [8, -64, 9], false), + ([2, 2, 1], [7, -64, 9], false), + ([1, 2, 2], [7, -64, 9], false), + ] { + let volume = DensityVolume::new(sizes, minimum, [4, 8, 16]).unwrap(); + let mut output = vec![19.0; volume.size() + 2]; + slice + .sample_volume(&mut context, &mut output, volume) + .unwrap(); + assert!( + output[..volume.size()] + .iter() + .all(|v| v.to_bits() == (-0.0_f32).to_bits()) + ); + let expected_tail = if delegated { -0.0_f32 } else { 19.0 }; + assert!( + output[volume.size()..] + .iter() + .all(|v| v.to_bits() == expected_tail.to_bits()) + ); + } + let failing = SliceSampler { + axes: SliceAxes::Y(3), + input: Arc::new(RangeChoiceSampler { + input: Arc::new(GradientSampler::new( + Axis::X, + TilingMode::Repeat, + 0, + 0, + 0.0, + 1.0, + )), + min_inclusive: 0.0, + max_exclusive: 1.0, + when_in_range: Arc::new(ConstantSampler(7.0)), + when_out_of_range: Arc::new(ConstantSampler(9.0)), + }), + }; + for (y, expected) in [(2, 19.0), (3, 7.0)] { + let volume = DensityVolume::new([1; 3], [0, y, 0], [4, 8, 16]).unwrap(); + let mut output = [19.0]; + assert_eq!( + failing.sample_volume(&mut context, &mut output, volume), + Err(SampleError::ZeroGradientPeriod) + ); + assert_eq!(output, [expected]); + } + assert!(!context.scratch.is_empty()); +} + +#[test] +fn slices_preserve_reduced_volume_steps_in_cached_children() { + let input = Arc::new( + CachingDensitySampler::new( + 0, + Arc::new(DistanceToPointSampler { + point: [0; 3], + metric: DistanceMetric::Manhattan, + }), + ) + .unwrap(), + ); + let mut context = SamplerContext::cached(); + let slice = SliceSampler { + input: input.clone(), + axes: SliceAxes::X(7), + }; + let volume = DensityVolume::new([3, 2, 2], [-17, -64, 32], [4, 8, 16]).unwrap(); + let mut output = vec![0.0; volume.size()]; + slice + .sample_volume(&mut context, &mut output, volume) + .unwrap(); + for z in 0..2 { + for x in 0..3 { + assert_eq!( + &output[(x + z * 3) * 2..(x + z * 3) * 2 + 2], + &[103.0 + z as f32 * 16.0, 95.0 + z as f32 * 16.0] + ); + } + } + // The following matching request must hit the cached reduced descriptor. + // A short logical output is still rejected before touching that child. + let reduced = DensityVolume::new([1, 2, 2], [7, -64, 32], [4, 8, 16]).unwrap(); + let mut reduced_output = [0.0; 4]; + input + .sample_volume(&mut context, &mut reduced_output, reduced) + .unwrap(); + assert_eq!(reduced_output, [103.0, 95.0, 119.0, 111.0]); + let mut short = [19.0]; + assert_eq!( + slice.sample_volume(&mut context, &mut short, volume), + Err(SampleError::Volume(DensityError::BufferTooShort)) + ); + assert_eq!(short, [19.0]); +} + +#[test] +fn grid_interpolation_keeps_incremental_bulk_rounding() { + let input = Arc::new(GradientSampler::new( + Axis::Y, + TilingMode::ClampToEdge, + 0, + 10, + 0.0, + 1.0, + )); + let sampler = InterpolatedSampler::new(input, 4, 10).unwrap(); + let mut context = SamplerContext::default(); + let volume = DensityVolume::new([1, 10, 1], [0; 3], [1; 3]).unwrap(); + let mut output = [19.0; 11]; + sampler + .sample_volume(&mut context, &mut output, volume) + .unwrap(); + assert_eq!(output[7].to_bits(), 0x3f333334); + assert_eq!( + sampler + .sample_value(&mut context, [0, 7, 0]) + .unwrap() + .to_bits(), + 0x3f333333 + ); + assert_eq!(output[10], 19.0); + let strided = DensityVolume::new([1, 5, 1], [0; 3], [1, 2, 1]).unwrap(); + let mut selected = [0.0; 5]; + sampler + .sample_volume(&mut context, &mut selected, strided) + .unwrap(); + for (i, value) in selected.iter().enumerate() { + assert_eq!(value.to_bits(), output[i * 2].to_bits()); + } +} + +#[test] +fn grid_interpolation_uses_child_bulk_corners_and_preserves_aligned_delegation() { + #[derive(Debug, Default)] + struct Traced { + volumes: std::sync::Mutex>, + points: std::sync::Mutex>, + } + impl DensitySampler for Traced { + fn sample_value( + &self, + _: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + self.points.lock().unwrap().push(position); + Ok(-0.0) + } + fn sample_volume( + &self, + _: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + self.volumes.lock().unwrap().push(volume); + buffer.fill(-0.0); + Ok(()) + } + } + let traced = Arc::new(Traced::default()); + let sampler = InterpolatedSampler::new(traced.clone(), 4, 8).unwrap(); + let mut context = SamplerContext::default(); + assert_eq!( + sampler + .sample_value(&mut context, [-4, -8, 4]) + .unwrap() + .to_bits(), + (-0.0_f32).to_bits() + ); + sampler.sample_value(&mut context, [-1, -1, -1]).unwrap(); + assert_eq!(*traced.points.lock().unwrap(), [[-4, -8, 4]]); + assert_eq!( + *traced.volumes.lock().unwrap(), + [DensityVolume::new([2; 3], [-4, -8, -4], [4, 8, 4]).unwrap()] + ); + let volume = DensityVolume::new([2, 1, 2], [-4, -8, 4], [4, 1, 4]).unwrap(); + let mut output = [19.0; 6]; + sampler + .sample_volume(&mut context, &mut output, volume) + .unwrap(); + assert!(output.iter().all(|v| v.to_bits() == (-0.0_f32).to_bits())); + assert_eq!(traced.volumes.lock().unwrap()[1], volume); + assert!(InterpolatedSampler::new(traced.clone(), 0, 8).is_err()); + assert!(InterpolatedSampler::new(traced, 4, -1).is_err()); +} + +#[test] +fn surface_search_fixes_upper_bound_y_and_visits_descending_cell_boundaries() { + #[derive(Debug, Default)] + struct DensityTrace(std::sync::Mutex>); + impl DensitySampler for DensityTrace { + fn sample_value( + &self, + _: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + self.0.lock().unwrap().push(position); + Ok(match position[1] { + 12 => f32::NAN, + 8 => -0.0, + _ => 1.0, + }) + } + } + let density = Arc::new(DensityTrace::default()); + let upper = Arc::new(GradientSampler::new( + Axis::Y, + TilingMode::ClampToEdge, + 0, + 10, + 14.0, + 54.0, + )); + let sampler = compile_surface_search(density.clone(), upper, -64, 4).unwrap(); + assert_eq!( + sampler.sample_value(&mut SamplerContext::default(), [7, 1000, -9]), + Ok(4.0) + ); + assert_eq!( + *density.0.lock().unwrap(), + [[7, 12, -9], [7, 8, -9], [7, 4, -9]] + ); + density.0.lock().unwrap().clear(); + let shortcut = + FindTopSurfaceSampler::new(density.clone(), Arc::new(ConstantSampler(-63.0)), -64, 8) + .unwrap(); + assert_eq!( + shortcut.sample_value(&mut SamplerContext::default(), [0; 3]), + Ok(-64.0) + ); + assert!(density.0.lock().unwrap().is_empty()); + let negative_infinity = FindTopSurfaceSampler::new( + density.clone(), + Arc::new(ConstantSampler(f32::NEG_INFINITY)), + -64, + 1, + ) + .unwrap(); + assert_eq!( + negative_infinity.sample_value(&mut SamplerContext::default(), [0; 3]), + Ok(-64.0) + ); + assert!(density.0.lock().unwrap().is_empty()); +} + +#[test] +fn surface_bulk_preserves_upper_bound_writes_and_sliced_error_isolation() { + #[derive(Debug)] + struct FailSecondColumn; + impl DensitySampler for FailSecondColumn { + fn sample_value( + &self, + _: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + if position[0] == 1 { + Err(SampleError::ZeroGradientPeriod) + } else { + Ok(if position[1] <= 4 { 1.0 } else { 0.0 }) + } + } + } + let raw = Arc::new( + FindTopSurfaceSampler::new( + Arc::new(FailSecondColumn), + Arc::new(ConstantSampler(14.0)), + -64, + 4, + ) + .unwrap(), + ); + let mut context = SamplerContext::default(); + let volume = DensityVolume::new([2, 1, 1], [0; 3], [1; 3]).unwrap(); + let mut output = [19.0; 3]; + assert_eq!( + raw.sample_volume(&mut context, &mut output, volume), + Err(SampleError::ZeroGradientPeriod) + ); + assert_eq!(output, [4.0, 14.0, 14.0]); + let volume = DensityVolume::new([2, 2, 1], [0; 3], [1; 3]).unwrap(); + let mut output = [19.0; 5]; + assert_eq!( + raw.sample_volume(&mut context, &mut output, volume), + Err(SampleError::SurfaceRequiresSingleLayer) + ); + assert_eq!(output, [19.0; 5]); + let sliced = SliceSampler { + input: raw, + axes: SliceAxes::Y(0), + }; + assert_eq!( + sliced.sample_volume(&mut context, &mut output, volume), + Err(SampleError::ZeroGradientPeriod) + ); + assert_eq!(output, [19.0; 5]); + assert!(!context.scratch.is_empty()); +} + +#[test] +fn spline_coordinate_cache_retries_nan_scalars_but_reuses_nan_volumes() { + use std::sync::atomic::{AtomicUsize, Ordering}; + #[derive(Debug)] + struct Counted { + value: f32, + scalar: AtomicUsize, + bulk: AtomicUsize, + } + impl DensitySampler for Counted { + fn sample_value(&self, _: &mut SamplerContext, _: [i32; 3]) -> Result { + self.scalar.fetch_add(1, Ordering::Relaxed); + Ok(self.value) + } + fn sample_volume( + &self, + _: &mut SamplerContext, + output: &mut [f32], + _: DensityVolume, + ) -> Result<(), SampleError> { + self.bulk.fetch_add(1, Ordering::Relaxed); + output.fill(self.value); + Ok(()) + } + } + let inner = CubicSpline::multipoint( + 1, + vec![SplinePoint { + location: 0.0, + derivative: -0.0, + value: CubicSpline::Constant(7.0), + }], + ) + .unwrap(); + let root = CubicSpline::multipoint( + 1, + vec![ + SplinePoint { + location: -1.0, + derivative: 0.0, + value: inner.clone(), + }, + SplinePoint { + location: 1.0, + derivative: 0.0, + value: inner, + }, + ], + ) + .unwrap(); + for (value, scalar_calls) in [(0.0, 1), (f32::NAN, 2)] { + let input = Arc::new(Counted { + value, + scalar: AtomicUsize::new(0), + bulk: AtomicUsize::new(0), + }); + let sampler = + SplineSampler::new(&root, &[Arc::new(ConstantSampler(99.0)), input.clone()]).unwrap(); + assert_eq!(sampler.coordinate_count(), 1); + let mut context = SamplerContext::default(); + assert_eq!(sampler.sample_value(&mut context, [0; 3]), Ok(7.0)); + assert_eq!(input.scalar.load(Ordering::Relaxed), scalar_calls); + let volume = DensityVolume::new([2, 3, 2], [0; 3], [1; 3]).unwrap(); + let mut output = [19.0; 12]; + sampler + .sample_volume(&mut context, &mut output, volume) + .unwrap(); + assert_eq!(output, [7.0; 12]); + assert_eq!(input.bulk.load(Ordering::Relaxed), 1); + assert_eq!(input.scalar.load(Ordering::Relaxed), scalar_calls); + } + assert!(matches!( + SplineSampler::new(&root, &[]), + Err(SplineError::MissingCoordinate) + )); + assert!(matches!( + CubicSpline::multipoint(0, vec![]), + Err(SplineError::EmptyPoints) + )); +} + +#[test] +fn spline_lazy_branch_failure_preserves_completed_output_and_returns_scratch() { + let fail = CubicSpline::multipoint( + 1, + vec![SplinePoint { + location: 0.0, + derivative: 0.0, + value: CubicSpline::Constant(11.0), + }], + ) + .unwrap(); + let root = CubicSpline::multipoint( + 0, + vec![ + SplinePoint { + location: -1.0, + derivative: 0.0, + value: CubicSpline::Constant(7.0), + }, + SplinePoint { + location: 1.0, + derivative: 0.0, + value: fail, + }, + ], + ) + .unwrap(); + let inputs: Vec> = vec![ + Arc::new(GradientSampler::new( + Axis::X, + TilingMode::ClampToEdge, + 0, + 1, + -2.0, + 0.0, + )), + Arc::new(GradientSampler::new( + Axis::X, + TilingMode::Repeat, + 0, + 0, + 0.0, + 1.0, + )), + ]; + let sampler = SplineSampler::new(&root, &inputs).unwrap(); + let mut context = SamplerContext::default(); + let volume = DensityVolume::new([2, 1, 1], [0; 3], [1; 3]).unwrap(); + let mut output = [19.0; 2]; + assert_eq!( + sampler.sample_volume(&mut context, &mut output, volume), + Err(SampleError::ZeroGradientPeriod) + ); + assert_eq!(output, [7.0, 19.0]); + assert_eq!(context.scratch.len(), 2); + assert_eq!(sampler.sample_value(&mut context, [0; 3]), Ok(7.0)); +} diff --git a/crates/horizon-core/src/density/world_fields.rs b/crates/horizon-core/src/density/world_fields.rs new file mode 100644 index 000000000..7709de819 --- /dev/null +++ b/crates/horizon-core/src/density/world_fields.rs @@ -0,0 +1,151 @@ +use super::*; + +/// Vanilla's three density fields, resolved at evaluation time rather than +/// during graph compilation. Their declared ranges do not inspect bindings. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WorldField { + BlendAlpha, + BlendOffset, + Beardifier, +} +impl WorldField { + pub fn domain_axes(self) -> u8 { + match self { + Self::BlendAlpha | Self::BlendOffset => 5, + Self::Beardifier => 7, + } + } + pub fn range(self) -> Interval { + match self { + Self::BlendAlpha => Interval::new(0.0, 1.0).unwrap(), + Self::BlendOffset | Self::Beardifier => Interval::INFINITE, + } + } + fn fallback(self) -> f32 { + match self { + Self::BlendAlpha => 1.0, + Self::BlendOffset | Self::Beardifier => 0.0, + } + } +} + +/// Old-world blending provider. The full vanilla Blender data model and +/// distance-weighting algorithm are a separate, still pending implementation. +pub trait DensityBlender: std::fmt::Debug + Send + Sync { + fn is_empty(&self) -> bool; + fn blend_density(&self, position: [i32; 3], input: f32) -> f32; +} + +#[derive(Debug)] +pub struct EmptyBlender; +impl DensityBlender for EmptyBlender { + fn is_empty(&self) -> bool { + true + } + fn blend_density(&self, _: [i32; 3], input: f32) -> f32 { + input + } +} + +/// Bindings can be assembled and shared between workers. Attaching new +/// bindings consumes the worker context and invalidates its cached densities. +#[derive(Clone, Debug, Default)] +pub struct WorldFields { + samplers: [Option>; 3], + blender: Option>, +} +impl WorldFields { + pub fn with_field(mut self, field: WorldField, sampler: Arc) -> Self { + self.samplers[field as usize] = Some(sampler); + self + } + pub fn with_blender(mut self, blender: Arc) -> Self { + self.blender = Some(blender); + self + } +} +impl SamplerContext { + pub fn with_world_fields(mut self, fields: WorldFields) -> Self { + self.clear_caches(); + self.fields = fields; + self + } +} + +#[derive(Clone, Debug)] +pub struct ContextBoundSampler { + field: WorldField, + fallback: Arc, +} +impl ContextBoundSampler { + pub fn new(field: WorldField) -> Self { + Self::with_fallback(field, Arc::new(ConstantSampler(field.fallback()))) + } + /// The vanilla sampler also permits a fallback supplied by its caller. + pub fn with_fallback(field: WorldField, fallback: Arc) -> Self { + Self { field, fallback } + } + fn resolve(&self, context: &SamplerContext) -> Arc { + context.fields.samplers[self.field as usize] + .as_ref() + .unwrap_or(&self.fallback) + .clone() + } +} +impl DensitySampler for ContextBoundSampler { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + self.resolve(context).sample_value(context, position) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + self.resolve(context).sample_volume(context, buffer, volume) + } +} + +#[derive(Clone, Debug)] +pub struct BlendDensitySampler { + pub input: Arc, +} +impl DensitySampler for BlendDensitySampler { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + let input = self.input.sample_value(context, position)?; + let Some(blender) = &context.fields.blender else { + return Ok(input); + }; + Ok(if blender.is_empty() { + input + } else { + blender.blend_density(position, input) + }) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + self.input.sample_volume(context, buffer, volume)?; + let Some(blender) = &context.fields.blender else { + return Ok(()); + }; + if blender.is_empty() { + return Ok(()); + } + visit(volume, |index, position| { + buffer[index] = blender.blend_density(position, buffer[index]); + Ok(()) + }) + } +} diff --git a/crates/horizon-core/src/geometry/mod.rs b/crates/horizon-core/src/geometry/mod.rs new file mode 100644 index 000000000..b41c36af9 --- /dev/null +++ b/crates/horizon-core/src/geometry/mod.rs @@ -0,0 +1,656 @@ +//! Double-precision simulation geometry for the pinned Java Edition target. +//! +//! Operation order and Java floating-point edge cases are deliberate. These are +//! simulation coordinates; rendering may use a separate camera-relative format. + +mod movement; +mod shape; +mod sweep; +mod traversal; +pub mod trig; +use crate::position::BlockPos; +pub use movement::{ + block_floor_height, candidate_step_heights, entity_collision_bounds, resolve_shape_movement, + resolve_step_movement, +}; +pub use shape::{ShapeError, ShapeOp, VoxelShape}; +pub use sweep::sweep_intersected_blocks; +pub use traversal::{TraversalError, traverse_blocks}; + +pub const COLLISION_EPSILON: f64 = 1.0e-7; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(usize)] +pub enum Axis { + X, + Y, + Z, +} + +impl Axis { + pub const ALL: [Self; 3] = [Self::X, Self::Y, Self::Z]; + pub fn step_order(movement: Vec3) -> [Self; 3] { + if movement.x.abs() < movement.z.abs() { + [Self::Y, Self::Z, Self::X] + } else { + [Self::Y, Self::X, Self::Z] + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum Direction { + Down, + Up, + North, + South, + West, + East, +} + +impl Direction { + pub const ALL: [Self; 6] = [ + Self::Down, + Self::Up, + Self::North, + Self::South, + Self::West, + Self::East, + ]; + pub const fn opposite(self) -> Self { + match self { + Self::Down => Self::Up, + Self::Up => Self::Down, + Self::North => Self::South, + Self::South => Self::North, + Self::West => Self::East, + Self::East => Self::West, + } + } + pub const fn normal(self) -> [i32; 3] { + match self { + Self::Down => [0, -1, 0], + Self::Up => [0, 1, 0], + Self::North => [0, 0, -1], + Self::South => [0, 0, 1], + Self::West => [-1, 0, 0], + Self::East => [1, 0, 0], + } + } + pub fn approximate_nearest(vector: Vec3) -> Self { + let [x, y, z] = vector.components().map(|v| v as f32); + let mut best = f32::from_bits(1); + let mut result = Self::North; + for direction in Self::ALL { + let [nx, ny, nz] = direction.normal().map(|v| v as f32); + let dot = x * nx + y * ny + z * nz; + if dot > best { + best = dot; + result = direction; + } + } + result + } +} + +/// Component equality follows Java Double.compare, including NaNs and -0.0. +#[derive(Clone, Copy, Debug, Default)] +pub struct Vec3 { + pub x: f64, + pub y: f64, + pub z: f64, +} + +impl PartialEq for Vec3 { + fn eq(&self, other: &Self) -> bool { + self.components() + .into_iter() + .zip(other.components()) + .all(|(a, b)| canonical_bits(a) == canonical_bits(b)) + } +} +impl Vec3 { + pub const ZERO: Self = Self::new(0.0, 0.0, 0.0); + pub const fn new(x: f64, y: f64, z: f64) -> Self { + Self { x, y, z } + } + pub const fn components(self) -> [f64; 3] { + [self.x, self.y, self.z] + } + pub fn component(self, axis: Axis) -> f64 { + self.components()[axis as usize] + } + pub fn from_block(pos: BlockPos) -> Self { + Self::new(pos.x as f64, pos.y as f64, pos.z as f64) + } + pub fn add_vector(self, other: Self) -> Self { + Self::new(self.x + other.x, self.y + other.y, self.z + other.z) + } + pub fn subtract(self, other: Self) -> Self { + self.add_vector(Self::new(-other.x, -other.y, -other.z)) + } + pub fn vector_to(self, other: Self) -> Self { + Self::new(other.x - self.x, other.y - self.y, other.z - self.z) + } + pub fn multiply(self, other: Self) -> Self { + Self::new(self.x * other.x, self.y * other.y, self.z * other.z) + } + pub fn scale(self, scale: f64) -> Self { + self.multiply(Self::new(scale, scale, scale)) + } + pub fn reverse(self) -> Self { + self.scale(-1.0) + } + pub fn horizontal(self) -> Self { + Self::new(self.x, 0.0, self.z) + } + pub fn dot(self, other: Self) -> f64 { + self.x * other.x + self.y * other.y + self.z * other.z + } + pub fn cross(self, other: Self) -> Self { + Self::new( + self.y * other.z - self.z * other.y, + self.z * other.x - self.x * other.z, + self.x * other.y - self.y * other.x, + ) + } + pub fn length_squared(self) -> f64 { + self.x * self.x + self.y * self.y + self.z * self.z + } + pub fn length(self) -> f64 { + self.length_squared().sqrt() + } + pub fn horizontal_distance_squared(self) -> f64 { + self.x * self.x + self.z * self.z + } + pub fn horizontal_distance(self) -> f64 { + self.horizontal_distance_squared().sqrt() + } + pub fn distance_squared(self, other: Self) -> f64 { + let x = self.x - other.x; + let y = self.y - other.y; + let z = self.z - other.z; + x * x + y * y + z * z + } + pub fn distance(self, other: Self) -> f64 { + self.distance_squared(other).sqrt() + } + pub fn normalize(self) -> Self { + let length = self.length(); + if length < 9.999999747378752e-6 { + Self::ZERO + } else { + Self::new(self.x / length, self.y / length, self.z / length) + } + } + pub fn lerp(self, other: Self, amount: f64) -> Self { + Self::new( + lerp(amount, self.x, other.x), + lerp(amount, self.y, other.y), + lerp(amount, self.z, other.z), + ) + } + pub fn projected_on(self, other: Self) -> Self { + if other.length_squared() == 0.0 { + other + } else { + other + .scale(self.dot(other)) + .scale(1.0 / other.length_squared()) + } + } + pub fn closer_than(self, other: Self, distance: f64) -> bool { + self.distance_squared(other) < distance * distance + } + pub fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() && self.z.is_finite() + } + pub fn with_component(self, axis: Axis, value: f64) -> Self { + let mut coordinates = self.components(); + coordinates[axis as usize] = value; + Self::new(coordinates[0], coordinates[1], coordinates[2]) + } + pub fn align(self, axes: [bool; 3]) -> Self { + let coordinates = std::array::from_fn::<_, 3, _>(|i| { + if axes[i] { + floor_i32(self.components()[i]) as f64 + } else { + self.components()[i] + } + }); + Self::new(coordinates[0], coordinates[1], coordinates[2]) + } + pub fn relative(self, direction: Direction, distance: f64) -> Self { + let normal = direction.normal(); + Self::new( + self.x + distance * normal[0] as f64, + self.y + distance * normal[1] as f64, + self.z + distance * normal[2] as f64, + ) + } + pub fn rotate_x(self, angle: f32) -> Self { + let c = trig::cos(angle as f64) as f64; + let s = trig::sin(angle as f64) as f64; + Self::new(self.x, self.y * c + self.z * s, self.z * c - self.y * s) + } + pub fn rotate_y(self, angle: f32) -> Self { + let c = trig::cos(angle as f64) as f64; + let s = trig::sin(angle as f64) as f64; + Self::new(self.x * c + self.z * s, self.y, self.z * c - self.x * s) + } + pub fn rotate_z(self, angle: f32) -> Self { + let c = trig::cos(angle as f64) as f64; + let s = trig::sin(angle as f64) as f64; + Self::new(self.x * c + self.y * s, self.y * c - self.x * s, self.z) + } + pub fn rotate_clockwise_90(self) -> Self { + Self::new(-self.z, self.y, self.x) + } + pub fn direction_from_rotation(pitch: f32, yaw: f32) -> Self { + let yaw_radians = -yaw * trig::DEG_TO_RAD - std::f32::consts::PI; + let cy = trig::cos(yaw_radians as f64); + let sy = trig::sin(yaw_radians as f64); + let pitch_radians = -pitch * trig::DEG_TO_RAD; + let cp = -trig::cos(pitch_radians as f64); + let sp = trig::sin(pitch_radians as f64); + Self::new((sy * cp) as f64, sp as f64, (cy * cp) as f64) + } + /// Return vanilla's (pitch, yaw) float pair in degrees. + pub fn rotation(self) -> [f32; 2] { + let yaw = ((-self.x).atan2(self.z) as f32) * trig::RAD_TO_DEG; + let pitch = ((-self.y / self.length()).asin() as f32) * trig::RAD_TO_DEG; + [pitch, yaw] + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Aabb { + min: Vec3, + max: Vec3, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BlockHit { + pub location: Vec3, + pub direction: Direction, + pub block: BlockPos, + pub inside: bool, +} + +impl Aabb { + pub fn new(min: Vec3, max: Vec3) -> Self { + Self { + min: Vec3::new( + java_min(min.x, max.x), + java_min(min.y, max.y), + java_min(min.z, max.z), + ), + max: Vec3::new( + java_max(min.x, max.x), + java_max(min.y, max.y), + java_max(min.z, max.z), + ), + } + } + pub fn block(pos: BlockPos) -> Self { + Self::new(Vec3::from_block(pos), Vec3::from_block(pos.offset(1, 1, 1))) + } + pub fn unit_cube(lower: Vec3) -> Self { + Self::new(lower, lower.add_vector(Vec3::new(1.0, 1.0, 1.0))) + } + pub fn of_size(center: Vec3, size: Vec3) -> Self { + Self::new( + Vec3::new( + center.x - size.x / 2.0, + center.y - size.y / 2.0, + center.z - size.z / 2.0, + ), + Vec3::new( + center.x + size.x / 2.0, + center.y + size.y / 2.0, + center.z + size.z / 2.0, + ), + ) + } + pub fn encapsulating_blocks(a: BlockPos, b: BlockPos) -> Self { + Self::new( + Vec3::from_block(BlockPos::new(a.x.min(b.x), a.y.min(b.y), a.z.min(b.z))), + Vec3::from_block(BlockPos::new( + a.x.max(b.x).wrapping_add(1), + a.y.max(b.y).wrapping_add(1), + a.z.max(b.z).wrapping_add(1), + )), + ) + } + pub const fn min_position(self) -> Vec3 { + self.min + } + pub const fn max_position(self) -> Vec3 { + self.max + } + pub fn min(self, axis: Axis) -> f64 { + self.min.component(axis) + } + pub fn max(self, axis: Axis) -> f64 { + self.max.component(axis) + } + pub fn with_min(self, axis: Axis, value: f64) -> Self { + let mut a = self.min.components(); + a[axis as usize] = value; + Self::new(Vec3::new(a[0], a[1], a[2]), self.max) + } + pub fn with_max(self, axis: Axis, value: f64) -> Self { + let mut a = self.max.components(); + a[axis as usize] = value; + Self::new(self.min, Vec3::new(a[0], a[1], a[2])) + } + pub fn size(self) -> Vec3 { + self.min.vector_to(self.max) + } + pub fn average_size(self) -> f64 { + let v = self.size(); + (v.x + v.y + v.z) / 3.0 + } + pub fn center(self) -> Vec3 { + self.min.lerp(self.max, 0.5) + } + pub fn bottom_center(self) -> Vec3 { + let v = self.center(); + Vec3::new(v.x, self.min.y, v.z) + } + pub fn move_by(self, offset: Vec3) -> Self { + Self::new(self.min.add_vector(offset), self.max.add_vector(offset)) + } + pub fn inflate(self, amount: Vec3) -> Self { + Self::new( + Vec3::new( + self.min.x - amount.x, + self.min.y - amount.y, + self.min.z - amount.z, + ), + self.max.add_vector(amount), + ) + } + pub fn deflate(self, amount: Vec3) -> Self { + self.inflate(amount.reverse()) + } + pub fn expand_towards(self, amount: Vec3) -> Self { + self.change_extent(amount, false) + } + pub fn contract(self, amount: Vec3) -> Self { + self.change_extent(amount, true) + } + fn change_extent(self, amount: Vec3, contract: bool) -> Self { + let mut min = self.min.components(); + let mut max = self.max.components(); + for (i, v) in amount.components().into_iter().enumerate() { + if v < 0.0 { + min[i] = if contract { min[i] - v } else { min[i] + v }; + } else if v > 0.0 { + max[i] = if contract { max[i] - v } else { max[i] + v }; + } + } + Self::new( + Vec3::new(min[0], min[1], min[2]), + Vec3::new(max[0], max[1], max[2]), + ) + } + pub fn intersect(self, other: Self) -> Self { + Self::new( + Vec3::new( + java_max(self.min.x, other.min.x), + java_max(self.min.y, other.min.y), + java_max(self.min.z, other.min.z), + ), + Vec3::new( + java_min(self.max.x, other.max.x), + java_min(self.max.y, other.max.y), + java_min(self.max.z, other.max.z), + ), + ) + } + pub fn union_bounds(self, other: Self) -> Self { + Self::new( + Vec3::new( + java_min(self.min.x, other.min.x), + java_min(self.min.y, other.min.y), + java_min(self.min.z, other.min.z), + ), + Vec3::new( + java_max(self.max.x, other.max.x), + java_max(self.max.y, other.max.y), + java_max(self.max.z, other.max.z), + ), + ) + } + pub fn intersects(self, other: Self) -> bool { + self.min.x < other.max.x + && self.max.x > other.min.x + && self.min.y < other.max.y + && self.max.y > other.min.y + && self.min.z < other.max.z + && self.max.z > other.min.z + } + pub fn contains(self, point: Vec3) -> bool { + point.x >= self.min.x + && point.x < self.max.x + && point.y >= self.min.y + && point.y < self.max.y + && point.z >= self.min.z + && point.z < self.max.z + } + pub fn has_nan(self) -> bool { + self.min + .components() + .into_iter() + .chain(self.max.components()) + .any(f64::is_nan) + } + pub fn distance_squared_to_point(self, point: Vec3) -> f64 { + let distances = Axis::ALL.map(|a| { + java_max( + java_max( + self.min(a) - point.component(a), + point.component(a) - self.max(a), + ), + 0.0, + ) + }); + distances[0] * distances[0] + distances[1] * distances[1] + distances[2] * distances[2] + } + pub fn distance_squared_to_box(self, other: Self) -> f64 { + let distances = Axis::ALL.map(|a| { + java_max( + java_max(self.min(a) - other.max(a), other.min(a) - self.max(a)), + 0.0, + ) + }); + distances[0] * distances[0] + distances[1] * distances[1] + distances[2] * distances[2] + } + pub fn next_deflated(self) -> Self { + let lo = self.min.components().map(next_up); + let hi = self.max.components().map(next_down); + Self::new( + Vec3::new(lo[0], lo[1], lo[2]), + Vec3::new(hi[0], hi[1], hi[2]), + ) + } + fn clip_direction(self, start: Vec3, delta: Vec3, best: &mut f64) -> Option { + let mut result = None; + for axis in Axis::ALL { + let i = axis as usize; + let j = (i + 1) % 3; + let k = (i + 2) % 3; + let ds = delta.components(); + let origins = start.components(); + let (plane, face) = if ds[i] > COLLISION_EPSILON { + ( + self.min(axis), + [Direction::West, Direction::Down, Direction::North][i], + ) + } else if ds[i] < -COLLISION_EPSILON { + ( + self.max(axis), + [Direction::East, Direction::Up, Direction::South][i], + ) + } else { + continue; + }; + let t = (plane - origins[i]) / ds[i]; + let u = origins[j] + t * ds[j]; + let v = origins[k] + t * ds[k]; + if 0.0 < t + && t < *best + && self.min.components()[j] - COLLISION_EPSILON < u + && u < self.max.components()[j] + COLLISION_EPSILON + && self.min.components()[k] - COLLISION_EPSILON < v + && v < self.max.components()[k] + COLLISION_EPSILON + { + *best = t; + result = Some(face); + } + } + result + } + pub fn clip(self, start: Vec3, end: Vec3) -> Option { + let delta = start.vector_to(end); + let mut best = 1.0; + self.clip_direction(start, delta, &mut best) + .map(|_| start.add_vector(delta.scale(best))) + } + pub fn clip_boxes( + boxes: impl IntoIterator, + start: Vec3, + end: Vec3, + block: BlockPos, + ) -> Option { + let delta = start.vector_to(end); + let mut best = 1.0; + let mut direction = None; + for aabb in boxes { + if let Some(face) = aabb + .move_by(Vec3::from_block(block)) + .clip_direction(start, delta, &mut best) + { + direction = Some(face); + } + } + direction.map(|face| BlockHit { + location: start.add_vector(delta.scale(best)), + direction: face, + block, + inside: false, + }) + } + pub fn collided_along_vector(self, movement: Vec3, boxes: &[Self]) -> bool { + let start = self.center(); + let end = start.add_vector(movement); + let amount = self.size().scale(0.5).subtract(Vec3::new( + COLLISION_EPSILON, + COLLISION_EPSILON, + COLLISION_EPSILON, + )); + boxes.iter().any(|b| { + let b = b.inflate(amount); + b.contains(end) || b.contains(start) || b.clip(start, end).is_some() + }) + } +} + +pub(crate) fn java_min(a: f64, b: f64) -> f64 { + if a.is_nan() { + a + } else if b.is_nan() { + b + } else if a == 0.0 && b == 0.0 { + f64::from_bits(a.to_bits() | b.to_bits()) + } else if a <= b { + a + } else { + b + } +} +pub(crate) fn java_max(a: f64, b: f64) -> f64 { + if a.is_nan() { + a + } else if b.is_nan() { + b + } else if a == 0.0 && b == 0.0 { + f64::from_bits(a.to_bits() & b.to_bits()) + } else if a >= b { + a + } else { + b + } +} +pub(crate) fn clamp(value: f64, min: f64, max: f64) -> f64 { + if value < min { + min + } else { + java_min(value, max) + } +} +pub(crate) fn floor_i32(value: f64) -> i32 { + value.floor() as i32 +} +fn lerp(amount: f64, start: f64, end: f64) -> f64 { + start + amount * (end - start) +} +fn canonical_bits(value: f64) -> u64 { + if value.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + value.to_bits() + } +} +fn next_up(value: f64) -> f64 { + if value.is_nan() || value == f64::INFINITY { + value + } else if value == 0.0 { + f64::from_bits(1) + } else { + f64::from_bits(if value > 0.0 { + value.to_bits() + 1 + } else { + value.to_bits() - 1 + }) + } +} +fn next_down(value: f64) -> f64 { + -next_up(-value) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn ray_faces_and_half_open_bounds() { + let b = Aabb::block(BlockPos::new(0, 0, 0)); + assert!(b.contains(Vec3::ZERO)); + assert!(!b.contains(Vec3::new(1.0, 0.0, 0.0))); + assert_eq!( + b.clip(Vec3::new(-1.0, 0.5, 0.5), Vec3::new(2.0, 0.5, 0.5)), + Some(Vec3::new(0.0, 0.5, 0.5)) + ); + assert!( + b.clip(Vec3::new(0.5, 0.5, 0.5), Vec3::new(2.0, 0.5, 0.5)) + .is_none() + ); + assert!( + b.clip(Vec3::new(-1.0, 0.5, 0.5), Vec3::new(0.0, 0.5, 0.5)) + .is_none() + ); + } + #[test] + fn numerical_boundaries() { + assert_eq!(java_min(0.0, -0.0).to_bits(), (-0.0f64).to_bits()); + assert_eq!(java_max(0.0, -0.0).to_bits(), 0.0f64.to_bits()); + assert_eq!(Vec3::new(-0.0, 0.0, 0.0).normalize(), Vec3::ZERO); + assert_ne!(Vec3::new(-0.0, 0.0, 0.0), Vec3::ZERO); + let b = Aabb::block(BlockPos::new(i32::MAX, 0, 0)); + assert_eq!(b.min(Axis::X), i32::MIN as f64); + assert_eq!(b.max(Axis::X), i32::MAX as f64); + assert!(Aabb::new(Vec3::new(f64::NAN, 0.0, 0.0), Vec3::new(1.0, 1.0, 1.0)).has_nan()); + } +} diff --git a/crates/horizon-core/src/geometry/movement.rs b/crates/horizon-core/src/geometry/movement.rs new file mode 100644 index 000000000..e89c77ba0 --- /dev/null +++ b/crates/horizon-core/src/geometry/movement.rs @@ -0,0 +1,208 @@ +//! Entity geometry helpers operating on an already selected collider list. +use super::{Aabb, Axis, Vec3, VoxelShape}; + +/// BlockGetter's floor-height decision for caller-selected collision shapes. +/// The lower block is queried lazily only if the current shape is empty. +pub fn block_floor_height<'s>(shape: &VoxelShape, below: impl FnOnce() -> &'s VoxelShape) -> f64 { + if !shape.is_empty() { + return shape.max(Axis::Y); + } + let height = below().max(Axis::Y); + if height >= 1.0 { + height - 1.0 + } else { + f64::NEG_INFINITY + } +} + +/// Bounds used once by Entity.collide to select entity collisions. The same +/// entity list is reused for both subsequent block/world-border queries. +pub fn entity_collision_bounds(movement: Vec3, aabb: Aabb, max_step: f32) -> Aabb { + aabb.expand_towards(movement) + .expand_towards(Vec3::new(0.0, max_step as f64, 0.0)) +} + +/// Resolve Entity.collide's initial movement and complete step-up decision. +/// +/// `collect` supplies vanilla-equivalent colliders for each requested bound, +/// including the previously selected entity shapes, applicable world border, +/// and context-dependent block shapes in vanilla order. It is called for the +/// initial movement (unless its squared length is zero), then at most once +/// more if stepping is eligible. Entity collision selection and movement's +/// grounding/velocity/inside-block side effects belong to the caller. +pub fn resolve_step_movement<'s>( + movement: Vec3, + aabb: Aabb, + max_step: f32, + on_ground: bool, + mut collect: impl FnMut(Aabb) -> Vec<&'s VoxelShape>, +) -> Vec3 { + let resolved = if movement.length_squared() == 0.0 { + movement + } else { + let shapes = collect(aabb.expand_towards(movement)); + resolve_shape_movement(movement, aabb, &shapes) + }; + let landed = movement.y != resolved.y && movement.y < 0.0; + if max_step > 0.0 + && (landed || on_ground) + && (movement.x != resolved.x || movement.z != resolved.z) + { + let step_box = if landed { + aabb.move_by(Vec3::new(0.0, resolved.y, 0.0)) + } else { + aabb + }; + let mut query = step_box.expand_towards(Vec3::new(movement.x, max_step as f64, movement.z)); + if !landed { + query = query.expand_towards(Vec3::new(0.0, -(1.0e-5_f32 as f64), 0.0)); + } + let shapes = collect(query); + for height in candidate_step_heights(step_box, &shapes, max_step, resolved.y as f32) { + let candidate = resolve_shape_movement( + Vec3::new(movement.x, height as f64, movement.z), + step_box, + &shapes, + ); + if candidate.horizontal_distance_squared() > resolved.horizontal_distance_squared() { + return candidate.subtract(Vec3::new( + 0.0, + aabb.min(Axis::Y) - step_box.min(Axis::Y), + 0.0, + )); + } + } + } + resolved +} + +/// Resolve vanilla's Y-first, magnitude-dependent horizontal axis ordering. +/// +/// The caller must supply vanilla-equivalent block/entity/world-border shapes. +/// This helper does not collect shapes, step up, set grounded flags, modify +/// velocity, or apply inside-block effects. +pub fn resolve_shape_movement(movement: Vec3, aabb: Aabb, shapes: &[&VoxelShape]) -> Vec3 { + if shapes.is_empty() { + return movement; + } + let mut result = [0.0; 3]; + for axis in Axis::step_order(movement) { + let amount = movement.component(axis); + if amount == 0.0 { + continue; + } + let moved = aabb.move_by(Vec3::new(result[0], result[1], result[2])); + result[axis as usize] = + VoxelShape::collide_all(axis, moved, shapes.iter().copied(), amount); + } + Vec3::new(result[0], result[1], result[2]) +} + +/// Candidate heights from Entity.collectCandidateStepUpHeights, including its +/// float narrowing, signed-zero set identity, current-Y exclusion and sorting. +/// Used by the step-up decision after collecting the appropriate world shapes. +pub fn candidate_step_heights( + aabb: Aabb, + shapes: &[&VoxelShape], + max_step: f32, + current_y: f32, +) -> Vec { + let mut heights = Vec::::with_capacity(4); + for shape in shapes { + for coordinate in shape.coordinates(Axis::Y) { + let height = (*coordinate - aabb.min(Axis::Y)) as f32; + if height < 0.0 || height == current_y { + continue; + } + if height > max_step { + break; + } + // FloatArraySet uses Float.floatToIntBits, so NaNs compare equal + // while positive and negative zero remain separate members. + let height = if height.is_nan() { f32::NAN } else { height }; + if !heights.iter().any(|old| old.to_bits() == height.to_bits()) { + heights.push(height); + } + } + } + heights.sort_unstable_by(f32::total_cmp); + heights +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::position::BlockPos; + #[test] + fn movement_slides_after_a_wall_collision() { + let wall = VoxelShape::block(); + let b = Aabb::new(Vec3::new(-0.6, 0.0, 0.2), Vec3::new(-0.2, 1.8, 0.8)); + let requested = Vec3::new(1.0, 0.0, 0.1); + assert_eq!( + resolve_shape_movement(requested, b, &[&wall]), + Vec3::new(0.2, 0.0, 0.1) + ); + assert_eq!( + resolve_shape_movement(Vec3::new(-0.0, -0.0, -0.0), b, &[]), + Vec3::new(-0.0, -0.0, -0.0) + ); + assert_eq!( + resolve_shape_movement(Vec3::new(-0.0, -0.0, -0.0), b, &[&wall]), + Vec3::ZERO + ); + } + #[test] + fn step_heights_deduplicate_and_exclude_current_y() { + let shape = VoxelShape::from_cube([1, 2, 1], &[true, true]).unwrap(); + let b = Aabb::block(BlockPos::default()); + assert_eq!( + candidate_step_heights(b, &[&shape, &shape], 0.6, 0.0), + vec![0.5] + ); + assert_eq!( + candidate_step_heights(b, &[&shape], 1.0, 0.5), + vec![0.0, 1.0] + ); + } + + #[test] + fn stepping_requeries_and_clears_a_half_block() { + let ledge = VoxelShape::from_box(Aabb::new(Vec3::ZERO, Vec3::new(1.0, 0.5, 1.0))).unwrap(); + let b = Aabb::new(Vec3::new(-0.6, 0.0, 0.2), Vec3::new(-0.2, 1.8, 0.8)); + let requested = Vec3::new(1.0, 0.0, 0.0); + let mut queries = Vec::new(); + let result = resolve_step_movement(requested, b, 0.6, true, |query| { + queries.push(query); + vec![&ledge] + }); + assert_eq!(result, Vec3::new(1.0, 0.5, 0.0)); + assert_eq!(queries.len(), 2); + assert_eq!(queries[0], b.expand_towards(requested)); + assert_eq!(queries[1].min(Axis::Y), -(1.0e-5_f32 as f64)); + assert_eq!( + resolve_step_movement(requested, b, 0.6, false, |_| vec![&ledge]), + Vec3::new(0.2, 0.0, 0.0) + ); + } + + #[test] + fn squared_length_underflow_skips_collection_and_keeps_signed_zero() { + let b = Aabb::block(BlockPos::default()); + let requested = Vec3::new(-0.0, 1e-200, -0.0); + assert_eq!( + resolve_step_movement(requested, b, 0.6, true, |_| panic!("unexpected query")), + requested + ); + } + #[test] + fn floor_height_defers_the_lower_lookup_until_empty() { + let empty = VoxelShape::empty(); + let block = VoxelShape::block(); + assert_eq!( + block_floor_height(&block, || panic!("unnecessary lower lookup")), + 1.0 + ); + assert_eq!(block_floor_height(&empty, || &block), 0.0); + assert_eq!(block_floor_height(&empty, || &empty), f64::NEG_INFINITY); + } +} diff --git a/crates/horizon-core/src/geometry/shape.rs b/crates/horizon-core/src/geometry/shape.rs new file mode 100644 index 000000000..62593ebc6 --- /dev/null +++ b/crates/horizon-core/src/geometry/shape.rs @@ -0,0 +1,551 @@ +use super::{ + Aabb, Axis, BlockHit, COLLISION_EPSILON, Direction, Vec3, clamp, floor_i32, java_max, java_min, +}; +use crate::position::BlockPos; +use std::fmt; +use std::sync::{Arc, OnceLock}; +mod create; +mod face; +mod join; +pub use join::ShapeOp; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ShapeError { + InvalidCoordinates, + InvalidOccupancy, + TooLarge, + UnboundedBoolean, + InvalidBounds, +} +impl fmt::Display for ShapeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "invalid voxel shape: {self:?}") + } +} +impl std::error::Error for ShapeError {} + +/// Immutable discrete occupancy with exact double coordinate boundaries. +/// +/// Greedy boxes are calculated once and reused for ray and proximity queries. +/// Cube shapes retain vanilla's arithmetic cell lookup instead of replacing it +/// with a binary search over coordinates (which differs at rounding boundaries). +#[derive(Clone, Debug)] +pub struct VoxelShape { + identity: Arc, + coords: Arc<[Vec; 3]>, + sizes: [usize; 3], + occupancy: Arc<[u64]>, + cube: bool, + coordinate_cubes: [bool; 3], + boxes: Arc>, + bounds: Option, + discrete_min: [i32; 3], + discrete_max: [i32; 3], +} + +type FaceCache = [OnceLock>; 6]; +#[derive(Debug, Default)] +struct ShapeIdentity { + faces: OnceLock>, +} + +impl VoxelShape { + pub fn from_grid(coords: [Vec; 3], occupied: &[bool]) -> Result { + Self::build(coords, occupied, false, [false; 3]) + } + pub fn from_cube(sizes: [usize; 3], occupied: &[bool]) -> Result { + if sizes.contains(&0) { + return Err(ShapeError::InvalidCoordinates); + } + let volume = volume(sizes)?; + if occupied.len() != volume { + return Err(ShapeError::InvalidOccupancy); + } + let coords = sizes.map(|size| (0..=size).map(|i| i as f64 / size as f64).collect()); + Self::build(coords, occupied, true, [true; 3]) + } + fn build( + coords: [Vec; 3], + occupied: &[bool], + cube: bool, + coordinate_cubes: [bool; 3], + ) -> Result { + if coords.iter().any(|c| { + c.is_empty() + || c.len() > 1_048_577 + || c.iter().any(|v| v.is_nan()) + || c.windows(2).any(|p| p[0] >= p[1]) + }) { + return Err(ShapeError::InvalidCoordinates); + } + let sizes = std::array::from_fn(|i| coords[i].len() - 1); + let count = volume(sizes)?; + if count != occupied.len() { + return Err(ShapeError::InvalidOccupancy); + } + let mut occupancy = vec![0; count.div_ceil(64)]; + let mut discrete_min = sizes.map(|v| v as i32); + let mut discrete_max = [0; 3]; + for (i, full) in occupied.iter().enumerate() { + if *full { + occupancy[i / 64] |= 1 << (i % 64); + let position = [ + (i / (sizes[1] * sizes[2])) as i32, + (i / sizes[2] % sizes[1]) as i32, + (i % sizes[2]) as i32, + ]; + for axis in 0..3 { + discrete_min[axis] = discrete_min[axis].min(position[axis]); + discrete_max[axis] = discrete_max[axis].max(position[axis] + 1); + } + } + } + let mut shape = Self { + identity: Arc::new(ShapeIdentity::default()), + coords: Arc::new(coords), + sizes, + occupancy: occupancy.into(), + cube, + coordinate_cubes, + boxes: Arc::new(Vec::new()), + bounds: None, + discrete_min, + discrete_max, + }; + shape.boxes = Arc::new(shape.decompose()); + shape.bounds = shape.boxes.iter().copied().reduce(Aabb::union_bounds); + Ok(shape) + } + pub fn empty() -> Self { + static EMPTY: OnceLock = OnceLock::new(); + EMPTY + .get_or_init(|| { + Self::from_grid([vec![0.0], vec![0.0], vec![0.0]], &[]).expect("valid empty grid") + }) + .clone() + } + pub fn block() -> Self { + static BLOCK: OnceLock = OnceLock::new(); + BLOCK + .get_or_init(|| Self::from_cube([1, 1, 1], &[true]).expect("valid unit cube")) + .clone() + } + pub fn is_empty(&self) -> bool { + self.bounds.is_none() + } + pub fn bounds(&self) -> Option { + self.bounds + } + pub fn boxes(&self) -> &[Aabb] { + &self.boxes + } + pub fn coordinates(&self, axis: Axis) -> &[f64] { + &self.coords[axis as usize] + } + pub fn sizes(&self) -> [usize; 3] { + self.sizes + } + pub fn is_cube(&self) -> bool { + self.cube + } + /// Clones and operations returning an existing immutable shape preserve its + /// identity. Separately constructed grids remain distinct even if equal. + pub fn same_identity(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.identity, &other.identity) + } + /// A separately constructed shape with the same immutable grid. Storage is + /// shared, while identity-sensitive vanilla join shortcuts remain distinct. + pub fn fresh_identity(&self) -> Self { + let mut shape = self.clone(); + shape.identity = Arc::new(ShapeIdentity::default()); + shape + } + pub fn cube_coordinate_axes(&self) -> [bool; 3] { + self.coordinate_cubes + } + /// An array shape can contain CubePointRange axes after a partial cube + /// merge. Preserve that metadata for subsequent Boolean operations. + pub fn from_mixed_grid( + coords: [Vec; 3], + occupied: &[bool], + coordinate_cubes: [bool; 3], + ) -> Result { + for i in 0..3 { + if coordinate_cubes[i] { + let size = coords[i].len().saturating_sub(1); + if size == 0 + || coords[i] + .iter() + .enumerate() + .any(|(j, v)| v.to_bits() != (j as f64 / size as f64).to_bits()) + { + return Err(ShapeError::InvalidCoordinates); + } + } + } + Self::build(coords, occupied, false, coordinate_cubes) + } + pub fn min(&self, axis: Axis) -> f64 { + let i = axis as usize; + let index = self.discrete_min[i]; + if index >= self.sizes[i] as i32 { + f64::INFINITY + } else { + self.coords[i][index as usize] + } + } + pub fn max(&self, axis: Axis) -> f64 { + let i = axis as usize; + let index = self.discrete_max[i]; + if index <= 0 { + f64::NEG_INFINITY + } else { + self.coords[i][index as usize] + } + } + /// Discrete extrema are separate from occupancy: a quantized empty shape + /// can retain nonempty axis ranges, and empty joins retain Java sentinels. + pub fn discrete_bounds(&self) -> ([i32; 3], [i32; 3]) { + (self.discrete_min, self.discrete_max) + } + /// Import reference extrema. Nonempty shapes must match their occupancy; + /// empty shapes admit bounded ranges or the empty-join sentinel triple. + pub fn with_discrete_bounds( + mut self, + min: [i32; 3], + max: [i32; 3], + ) -> Result { + let in_range = (0..3).all(|i| { + min[i] >= 0 + && min[i] <= self.sizes[i] as i32 + && max[i] >= 0 + && max[i] <= self.sizes[i] as i32 + }); + let join_sentinel = min == [i32::MAX; 3] && max == [i32::MIN + 1; 3]; + if (!in_range && !join_sentinel) + || (!self.is_empty() && (min != self.discrete_min || max != self.discrete_max)) + { + return Err(ShapeError::InvalidBounds); + } + if min != self.discrete_min || max != self.discrete_max { + self.identity = Arc::new(ShapeIdentity::default()); + } + self.discrete_min = min; + self.discrete_max = max; + Ok(self) + } + /// Minimum occupied coordinate along an axis at the two cyclic + /// perpendicular coordinates; an empty/outside column yields +infinity. + pub fn min_at(&self, axis: Axis, first: f64, second: f64) -> f64 { + let mut position = self.column_position(axis, first, second); + for i in 0..self.sizes[axis as usize] { + position[axis as usize] = i as i32; + if self.is_full(position[0], position[1], position[2]) { + return self.coords[axis as usize][i]; + } + } + f64::INFINITY + } + /// Maximum occupied coordinate at the same cyclic column; an empty/outside + /// column yields -infinity. The maximum is the cell's upper face. + pub fn max_at(&self, axis: Axis, first: f64, second: f64) -> f64 { + let mut position = self.column_position(axis, first, second); + for i in (0..self.sizes[axis as usize]).rev() { + position[axis as usize] = i as i32; + if self.is_full(position[0], position[1], position[2]) { + return self.coords[axis as usize][i + 1]; + } + } + f64::NEG_INFINITY + } + fn column_position(&self, axis: Axis, first: f64, second: f64) -> [i32; 3] { + let a = (axis as usize + 1) % 3; + let b = (axis as usize + 2) % 3; + let mut position = [0; 3]; + position[a] = self.find_index(Axis::ALL[a], first); + position[b] = self.find_index(Axis::ALL[b], second); + position + } + /// Vanilla movement converts cube coordinates to an array shape, even for + /// a zero offset. Keep this distinction for subsequent cell lookups. + pub fn moved(&self, offset: Vec3) -> Self { + if self.is_empty() { + return Self::empty(); + } + let mut result = self.clone(); + result.identity = Arc::new(ShapeIdentity::default()); + result.cube = false; + result.coordinate_cubes = [false; 3]; + let mut coords = (*self.coords).clone(); + for axis in Axis::ALL { + for value in &mut coords[axis as usize] { + *value += offset.component(axis); + } + } + result.coords = Arc::new(coords); + result.boxes = Arc::new(result.decompose()); + result.bounds = self.bounds.map(|bounds| bounds.move_by(offset)); + result + } + pub fn is_full(&self, x: i32, y: i32, z: i32) -> bool { + if x < 0 + || y < 0 + || z < 0 + || x as usize >= self.sizes[0] + || y as usize >= self.sizes[1] + || z as usize >= self.sizes[2] + { + return false; + } + full( + &self.occupancy, + index(self.sizes, x as usize, y as usize, z as usize), + ) + } + pub fn find_index(&self, axis: Axis, value: f64) -> i32 { + let i = axis as usize; + if self.cube { + return floor_i32(clamp( + value * self.sizes[i] as f64, + -1.0, + self.sizes[i] as f64, + )); + } + // Upper-bound search, including the final outside cell index. + let coords = &self.coords[i]; + let mut start = 0; + let mut end = coords.len(); + while start < end { + let middle = (start + end) / 2; + if value < coords[middle] { + end = middle; + } else { + start = middle + 1; + } + } + start as i32 - 1 + } + pub fn collide(&self, axis: Axis, aabb: Aabb, amount: f64) -> f64 { + if self.is_empty() { + return amount; + } + if amount.abs() < COLLISION_EPSILON { + return 0.0; + } + let i = axis as usize; + let p = Axis::ALL[(i + 1) % 3]; + let q = Axis::ALL[(i + 2) % 3]; + let p_start = self.find_index(p, aabb.min(p) + COLLISION_EPSILON).max(0); + let p_end = (self.find_index(p, aabb.max(p) - COLLISION_EPSILON) + 1) + .min(self.sizes[p as usize] as i32); + let q_start = self.find_index(q, aabb.min(q) + COLLISION_EPSILON).max(0); + let q_end = (self.find_index(q, aabb.max(q) - COLLISION_EPSILON) + 1) + .min(self.sizes[q as usize] as i32); + let occupied_layer = |layer| { + (p_start..p_end).any(|u| { + (q_start..q_end).any(|v| { + let mut cell = [0; 3]; + cell[i] = layer; + cell[p as usize] = u; + cell[q as usize] = v; + self.is_full(cell[0], cell[1], cell[2]) + }) + }) + }; + if amount > 0.0 { + let start = self.find_index(axis, aabb.max(axis) - COLLISION_EPSILON) + 1; + for layer in start..self.sizes[i] as i32 { + if occupied_layer(layer) { + let distance = self.coords[i][layer as usize] - aabb.max(axis); + return if distance >= -COLLISION_EPSILON { + java_min(amount, distance) + } else { + amount + }; + } + } + } else if amount < 0.0 { + let start = self.find_index(axis, aabb.min(axis) + COLLISION_EPSILON); + for layer in (0..start).rev() { + if occupied_layer(layer) { + let distance = self.coords[i][layer as usize + 1] - aabb.min(axis); + return if distance <= COLLISION_EPSILON { + java_max(amount, distance) + } else { + amount + }; + } + } + } + amount + } + pub fn collide_all<'a>( + axis: Axis, + aabb: Aabb, + shapes: impl IntoIterator, + mut amount: f64, + ) -> f64 { + for shape in shapes { + if amount.abs() < COLLISION_EPSILON { + return 0.0; + } + amount = shape.collide(axis, aabb, amount); + } + amount + } + pub fn clip(&self, start: Vec3, end: Vec3, block: BlockPos) -> Option { + if self.is_empty() { + return None; + } + let delta = end.subtract(start); + if delta.length_squared() < COLLISION_EPSILON { + return None; + } + let nudged = start.add_vector(delta.scale(0.001)); + let x = self.find_index(Axis::X, nudged.x - block.x as f64); + let y = self.find_index(Axis::Y, nudged.y - block.y as f64); + let z = self.find_index(Axis::Z, nudged.z - block.z as f64); + if self.is_full(x, y, z) { + Some(BlockHit { + location: nudged, + direction: Direction::approximate_nearest(delta).opposite(), + block, + inside: true, + }) + } else { + Aabb::clip_boxes(self.boxes.iter().copied(), start, end, block) + } + } + pub fn closest_point(&self, point: Vec3) -> Option { + let mut best = None; + for aabb in self.boxes.iter() { + let candidate = Vec3::new( + clamp(point.x, aabb.min(Axis::X), aabb.max(Axis::X)), + clamp(point.y, aabb.min(Axis::Y), aabb.max(Axis::Y)), + clamp(point.z, aabb.min(Axis::Z), aabb.max(Axis::Z)), + ); + if best + .is_none_or(|old| point.distance_squared(candidate) < point.distance_squared(old)) + { + best = Some(candidate); + } + } + best + } + fn decompose(&self) -> Vec { + let mut remaining = self.occupancy.to_vec(); + let mut boxes = Vec::new(); + let [nx, ny, nz] = self.sizes; + for y in 0..ny { + for x in 0..nx { + let mut run = None; + for z in 0..=nz { + if z < nz && full(&remaining, index(self.sizes, x, y, z)) { + if run.is_none() { + run = Some(z); + } + continue; + } + let Some(z_start) = run.take() else { continue }; + clear_strip(&mut remaining, self.sizes, x, y, z_start, z); + let mut x_end = x + 1; + while x_end < nx && strip_full(&remaining, self.sizes, x_end, y, z_start, z) { + clear_strip(&mut remaining, self.sizes, x_end, y, z_start, z); + x_end += 1; + } + let mut y_end = y + 1; + while y_end < ny + && (x..x_end) + .all(|u| strip_full(&remaining, self.sizes, u, y_end, z_start, z)) + { + for u in x..x_end { + clear_strip(&mut remaining, self.sizes, u, y_end, z_start, z); + } + y_end += 1; + } + boxes.push(Aabb::new( + Vec3::new( + self.coords[0][x], + self.coords[1][y], + self.coords[2][z_start], + ), + Vec3::new( + self.coords[0][x_end], + self.coords[1][y_end], + self.coords[2][z], + ), + )); + } + } + } + boxes + } +} + +fn volume(sizes: [usize; 3]) -> Result { + let count = sizes + .into_iter() + .try_fold(1usize, usize::checked_mul) + .ok_or(ShapeError::TooLarge)?; + if count > 1_048_576 { + Err(ShapeError::TooLarge) + } else { + Ok(count) + } +} +fn index(sizes: [usize; 3], x: usize, y: usize, z: usize) -> usize { + (x * sizes[1] + y) * sizes[2] + z +} +fn full(bits: &[u64], i: usize) -> bool { + bits[i / 64] & (1 << (i % 64)) != 0 +} +fn strip_full(bits: &[u64], sizes: [usize; 3], x: usize, y: usize, min: usize, max: usize) -> bool { + (min..max).all(|z| full(bits, index(sizes, x, y, z))) +} +fn clear_strip(bits: &mut [u64], sizes: [usize; 3], x: usize, y: usize, min: usize, max: usize) { + for z in min..max { + let i = index(sizes, x, y, z); + bits[i / 64] &= !(1 << (i % 64)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn stop_at_obstacle_and_reuse_boxes() { + let shape = VoxelShape::block(); + let player = Aabb::new(Vec3::new(-0.6, 0.0, 0.2), Vec3::new(-0.2, 1.8, 0.8)); + assert_eq!(shape.collide(Axis::X, player, 1.0), 0.2); + assert_eq!(shape.collide(Axis::Z, player, 1.0), 1.0); + assert_eq!(shape.boxes().len(), 1); + assert!( + shape + .clip( + Vec3::new(0.5, 0.5, 0.5), + Vec3::new(2.0, 0.5, 0.5), + BlockPos::default() + ) + .unwrap() + .inside + ); + assert_eq!( + VoxelShape::empty().collide(Axis::X, player, -0.0).to_bits(), + (-0.0f64).to_bits() + ); + } + #[test] + fn sparse_stair_decomposition() { + let shape = VoxelShape::from_cube( + [2, 2, 2], + &[true, true, false, false, true, true, true, true], + ) + .unwrap(); + assert_eq!(shape.boxes().len(), 2); + assert_eq!( + shape.closest_point(Vec3::new(0.1, 0.9, 0.5)), + Some(Vec3::new(0.1, 0.5, 0.5)) + ); + assert!(VoxelShape::from_grid(std::array::from_fn(|_| vec![0.0, 1.0]), &[]).is_err()); + } +} diff --git a/crates/horizon-core/src/geometry/shape/create.rs b/crates/horizon-core/src/geometry/shape/create.rs new file mode 100644 index 000000000..312e030b3 --- /dev/null +++ b/crates/horizon-core/src/geometry/shape/create.rs @@ -0,0 +1,147 @@ +use super::{ShapeError, ShapeOp, VoxelShape}; +use crate::geometry::{Aabb, Axis, COLLISION_EPSILON}; + +impl VoxelShape { + /// Shapes.create(AABB): thin-box rejection and up to 1/8 cube quantization. + pub fn from_box(aabb: Aabb) -> Result { + if aabb.has_nan() { + return Err(ShapeError::InvalidCoordinates); + } + if Axis::ALL + .into_iter() + .any(|axis| aabb.max(axis) - aabb.min(axis) < COLLISION_EPSILON) + { + return Ok(Self::empty()); + } + let bits = Axis::ALL.map(|axis| find_bits(aabb.min(axis), aabb.max(axis))); + if bits.iter().any(Option::is_none) { + return Self::from_grid( + Axis::ALL.map(|axis| vec![aabb.min(axis), aabb.max(axis)]), + &[true], + ); + } + let bits = bits.map(Option::unwrap); + if bits == [0, 0, 0] { + return Ok(Self::block()); + } + let sizes = bits.map(|bits| 1usize << bits); + let lo = std::array::from_fn::<_, 3, _>(|i| { + round_small(aabb.min(Axis::ALL[i]) * sizes[i] as f64) as usize + }); + let hi = std::array::from_fn::<_, 3, _>(|i| { + round_small(aabb.max(Axis::ALL[i]) * sizes[i] as f64) as usize + }); + let mut occupied = Vec::with_capacity(sizes[0] * sizes[1] * sizes[2]); + for x in 0..sizes[0] { + for y in 0..sizes[1] { + for z in 0..sizes[2] { + occupied.push( + x >= lo[0] + && x < hi[0] + && y >= lo[1] + && y < hi[1] + && z >= lo[2] + && z < hi[2], + ); + } + } + } + Self::from_cube(sizes, &occupied)? + .with_discrete_bounds(lo.map(|v| v as i32), hi.map(|v| v as i32)) + } + /// VoxelShape.optimize, reconstructing greedy boxes in vanilla order. + pub fn optimized(&self) -> Result { + let mut result = Self::empty(); + for aabb in self.boxes.iter() { + let part = Self::from_box(*aabb)?; + result = result.join_unoptimized(&part, ShapeOp::OR)?; + } + Ok(result) + } + pub fn join(&self, other: &Self, operation: ShapeOp) -> Result { + self.join_unoptimized(other, operation)?.optimized() + } +} +fn find_bits(min: f64, max: f64) -> Option { + if min < -COLLISION_EPSILON || max > 1.0000001 { + return None; + } + for bits in 0..=3 { + let size = (1usize << bits) as f64; + let lo = min * size; + let hi = max * size; + if (lo - round_small(lo) as f64).abs() < COLLISION_EPSILON * size + && (hi - round_small(hi) as f64).abs() < COLLISION_EPSILON * size + { + return Some(bits); + } + } + None +} +// Values reach this helper only in the small range admitted by find_bits. +// Avoid floor(value + 0.5): addition can round a value just below a tie upward. +fn round_small(value: f64) -> i64 { + let lower = value.floor(); + (if value - lower >= 0.5 { + lower + 1.0 + } else { + lower + }) as i64 +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::geometry::Vec3; + #[test] + fn quantization_thin_boxes_and_shared_block_identity() { + let full = VoxelShape::from_box(Aabb::new(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0))).unwrap(); + assert!(full.same_identity(&VoxelShape::block())); + let slab = VoxelShape::from_box(Aabb::new(Vec3::ZERO, Vec3::new(1.0, 0.5, 1.0))).unwrap(); + assert!(slab.is_cube()); + assert_eq!(slab.sizes(), [1, 2, 1]); + assert_eq!(slab.max(Axis::Y), 0.5); + let thin = VoxelShape::from_box(Aabb::new(Vec3::ZERO, Vec3::new(1e-8, 1.0, 1.0))).unwrap(); + assert!(thin.same_identity(&VoxelShape::empty())); + assert_eq!(round_small(f64::from_bits(0.5f64.to_bits() - 1)), 0); + } + #[test] + fn optimization_restores_composite_shapes() { + let a = VoxelShape::from_box(Aabb::new(Vec3::ZERO, Vec3::new(1.0, 0.5, 1.0))).unwrap(); + let b = VoxelShape::from_box(Aabb::new( + Vec3::new(0.5, 0.5, 0.0), + Vec3::new(1.0, 1.0, 1.0), + )) + .unwrap(); + let combined = a.join(&b, ShapeOp::OR).unwrap(); + assert_eq!(combined.boxes().len(), 2); + assert_eq!(combined.max(Axis::Y), 1.0); + assert!( + !combined + .join_is_not_empty(&a.join_unoptimized(&b, ShapeOp::OR).unwrap(), ShapeOp::XOR) + .unwrap() + ); + } + #[test] + fn quantized_empty_boxes_keep_independent_axis_extrema() { + let shape = VoxelShape::from_box(Aabb::new( + crate::geometry::Vec3::new(1e-8, 0.875, -1e-8), + crate::geometry::Vec3::new(0.12500001, 1.0, 9e-8), + )) + .unwrap(); + assert!(shape.is_empty()); + assert_eq!(shape.min(Axis::Y), 0.875); + assert_eq!(shape.max(Axis::Y), 1.0); + assert_eq!(shape.max(Axis::Z), f64::NEG_INFINITY); + assert_eq!( + crate::geometry::block_floor_height(&VoxelShape::empty(), || &shape), + 0.0 + ); + assert!( + shape + .optimized() + .unwrap() + .same_identity(&VoxelShape::empty()) + ); + } +} diff --git a/crates/horizon-core/src/geometry/shape/face.rs b/crates/horizon-core/src/geometry/shape/face.rs new file mode 100644 index 000000000..06a0f95ef --- /dev/null +++ b/crates/horizon-core/src/geometry/shape/face.rs @@ -0,0 +1,123 @@ +use super::{ShapeError, VoxelShape, volume}; +use crate::geometry::{Aabb, Axis, COLLISION_EPSILON, Direction, Vec3}; + +impl VoxelShape { + /// Native face selection samples just inside the unit-block boundary. The + /// result preserves identity on empty/cube-like axes and caches other faces. + pub fn face_shape(&self, direction: Direction) -> Result { + let (axis, _) = face_axis(direction); + if self.is_empty() || self.cube_like_along(axis) { + return Ok(self.clone()); + } + self.identity + .faces + .get_or_init(|| Box::new(std::array::from_fn(|_| std::sync::OnceLock::new()))) + [direction as usize] + .get_or_init(|| self.calculate_face(direction)) + .clone() + } + fn cube_like_along(&self, axis: Axis) -> bool { + let coords = self.coordinates(axis); + coords.len() == 2 + && coords[0].abs() <= COLLISION_EPSILON + && (coords[1] - 1.0).abs() <= COLLISION_EPSILON + } + fn calculate_face(&self, direction: Direction) -> Result { + let (axis, positive) = face_axis(direction); + let a = axis as usize; + let index = self.find_index( + axis, + if positive { + 0.9999999 + } else { + COLLISION_EPSILON + }, + ); + let mut starts = [0; 3]; + starts[a] = index; + let mut ends = self.sizes.map(|v| v as i32); + ends[a] = index + 1; + // SubShape extrema clamp the parent bounds; they are not recomputed + // from the selected occupancy. Sparse slices can therefore be nonempty + // by native metadata even when their decomposition contains no boxes. + let min = + std::array::from_fn(|i| self.discrete_min[i].clamp(starts[i], ends[i]) - starts[i]); + let max = + std::array::from_fn(|i| self.discrete_max[i].clamp(starts[i], ends[i]) - starts[i]); + if (0..3).any(|i| min[i] >= max[i]) { + return Ok(Self::empty()); + } + let mut coords = (*self.coords).clone(); + coords[a] = vec![0.0, 1.0]; + if (0..3).all(|i| { + coords[i].len() == 2 + && coords[i][0].abs() <= COLLISION_EPSILON + && (coords[i][1] - 1.0).abs() <= COLLISION_EPSILON + }) { + return Ok(Self::block()); + } + let sizes = std::array::from_fn(|i| coords[i].len() - 1); + let mut occupied = Vec::with_capacity(volume(sizes)?); + for x in 0..sizes[0] { + for y in 0..sizes[1] { + for z in 0..sizes[2] { + let mut p = [x as i32, y as i32, z as i32]; + p[a] = index; + occupied.push(self.is_full(p[0], p[1], p[2])); + } + } + } + let mut cubes = self.coordinate_cubes; + cubes[a] = true; + let mut result = Self::build(coords, &occupied, false, cubes)?; + result.discrete_min = min; + result.discrete_max = max; + result.bounds = Some(Aabb::new( + Vec3::new( + result.min(Axis::X), + result.min(Axis::Y), + result.min(Axis::Z), + ), + Vec3::new( + result.max(Axis::X), + result.max(Axis::Y), + result.max(Axis::Z), + ), + )); + Ok(result) + } +} +fn face_axis(direction: Direction) -> (Axis, bool) { + match direction { + Direction::Down => (Axis::Y, false), + Direction::Up => (Axis::Y, true), + Direction::North => (Axis::Z, false), + Direction::South => (Axis::Z, true), + Direction::West => (Axis::X, false), + Direction::East => (Axis::X, true), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + #[test] + fn face_cache_is_lazy_shared_and_does_not_retain_parent() { + let shape = VoxelShape::from_cube( + [2, 2, 2], + &[true, false, false, false, false, false, false, false], + ) + .unwrap(); + assert!(shape.identity.faces.get().is_none()); + let weak = Arc::downgrade(&shape.identity); + let face = shape.face_shape(Direction::Down).unwrap(); + assert!(!face.same_identity(&shape)); + assert!(face.same_identity(&shape.clone().face_shape(Direction::Down).unwrap())); + assert!(shape.fresh_identity().identity.faces.get().is_none()); + assert!(shape.moved(Vec3::ZERO).identity.faces.get().is_none()); + drop(shape); + assert!(weak.upgrade().is_none()); + assert!(!face.is_empty()); + } +} diff --git a/crates/horizon-core/src/geometry/shape/join.rs b/crates/horizon-core/src/geometry/shape/join.rs new file mode 100644 index 000000000..57c981e65 --- /dev/null +++ b/crates/horizon-core/src/geometry/shape/join.rs @@ -0,0 +1,363 @@ +use super::{ShapeError, VoxelShape, volume}; +use crate::geometry::{Axis, COLLISION_EPSILON}; + +/// A four-bit truth table, indexed as (first << 1) | second. +/// True for two empty cells would describe an unbounded volume, which vanilla +/// rejects for shape joins. Typed errors preserve that rejection here. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ShapeOp(u8); +impl ShapeOp { + pub const FALSE: Self = Self(0); + pub const AND: Self = Self(8); + pub const OR: Self = Self(14); + pub const XOR: Self = Self(6); + pub const ONLY_FIRST: Self = Self(4); + pub const ONLY_SECOND: Self = Self(2); + pub const FIRST: Self = Self(12); + pub const SECOND: Self = Self(10); + pub const fn from_truth_table(bits: u8) -> Self { + Self(bits & 15) + } + pub const fn apply(self, first: bool, second: bool) -> bool { + self.0 & (1 << ((first as u8) * 2 + second as u8)) != 0 + } + fn validate(self) -> Result<(), ShapeError> { + if self.apply(false, false) { + Err(ShapeError::UnboundedBoolean) + } else { + Ok(()) + } + } +} + +struct Merger { + coords: Vec, + first: Vec, + second: Vec, + cube_range: bool, + discrete_cube: bool, +} + +impl VoxelShape { + /// Shapes.joinUnoptimized, preserving merged coordinates and cube metadata. + pub fn join_unoptimized(&self, other: &Self, operation: ShapeOp) -> Result { + operation.validate()?; + if self.same_identity(other) { + return Ok(if operation.apply(true, true) { + self.clone() + } else { + Self::empty() + }); + } + let only_first = operation.apply(true, false); + let only_second = operation.apply(false, true); + if self.is_empty() { + return Ok(if only_second { + other.clone() + } else { + Self::empty() + }); + } + if other.is_empty() { + return Ok(if only_first { + self.clone() + } else { + Self::empty() + }); + } + let mergers = self.mergers(other, only_first, only_second)?; + let sizes = std::array::from_fn(|i| mergers[i].coords.len() - 1); + let count = volume(sizes)?; + let mut occupied = Vec::with_capacity(count); + for x in 0..sizes[0] { + for y in 0..sizes[1] { + for z in 0..sizes[2] { + let a = self.is_full( + mergers[0].first[x], + mergers[1].first[y], + mergers[2].first[z], + ); + let b = other.is_full( + mergers[0].second[x], + mergers[1].second[y], + mergers[2].second[z], + ); + occupied.push(operation.apply(a, b)); + } + } + } + let [x, y, z] = mergers; + let coordinate_cubes = [x.cube_range, y.cube_range, z.cube_range]; + let cube = x.discrete_cube && y.discrete_cube && z.discrete_cube; + let shape = Self::build( + [x.coords, y.coords, z.coords], + &occupied, + cube, + coordinate_cubes, + )?; + if shape.is_empty() { + shape.with_discrete_bounds([i32::MAX; 3], [i32::MIN + 1; 3]) + } else { + Ok(shape) + } + } + /// Shapes.joinIsNotEmpty without allocating the result occupancy or boxes. + pub fn join_is_not_empty(&self, other: &Self, operation: ShapeOp) -> Result { + operation.validate()?; + let a_empty = self.is_empty(); + let b_empty = other.is_empty(); + if a_empty || b_empty { + return Ok(operation.apply(!a_empty, !b_empty)); + } + if self.same_identity(other) { + return Ok(operation.apply(true, true)); + } + let only_first = operation.apply(true, false); + let only_second = operation.apply(false, true); + for axis in Axis::ALL { + if self.max(axis) < other.min(axis) - COLLISION_EPSILON + || other.max(axis) < self.min(axis) - COLLISION_EPSILON + { + return Ok(only_first || only_second); + } + } + let mergers = self.mergers(other, only_first, only_second)?; + let sizes = std::array::from_fn(|i| mergers[i].coords.len() - 1); + volume(sizes)?; + for x in 0..sizes[0] { + for y in 0..sizes[1] { + for z in 0..sizes[2] { + if operation.apply( + self.is_full( + mergers[0].first[x], + mergers[1].first[y], + mergers[2].first[z], + ), + other.is_full( + mergers[0].second[x], + mergers[1].second[y], + mergers[2].second[z], + ), + ) { + return Ok(true); + } + } + } + } + Ok(false) + } + fn mergers( + &self, + other: &Self, + only_first: bool, + only_second: bool, + ) -> Result<[Merger; 3], ShapeError> { + let x = merge( + 1, + &self.coords[0], + &other.coords[0], + self.coordinate_cubes[0], + other.coordinate_cubes[0], + only_first, + only_second, + )?; + let y = merge( + x.coords.len() - 1, + &self.coords[1], + &other.coords[1], + self.coordinate_cubes[1], + other.coordinate_cubes[1], + only_first, + only_second, + )?; + let multiplier = (x.coords.len() - 1) + .checked_mul(y.coords.len() - 1) + .ok_or(ShapeError::TooLarge)?; + let z = merge( + multiplier, + &self.coords[2], + &other.coords[2], + self.coordinate_cubes[2], + other.coordinate_cubes[2], + only_first, + only_second, + )?; + Ok([x, y, z]) + } +} + +#[allow(clippy::too_many_arguments)] // Mirrors the coordinate-merger selection inputs. +fn merge( + multiplier: usize, + a: &[f64], + b: &[f64], + a_cube: bool, + b_cube: bool, + only_first: bool, + only_second: bool, +) -> Result { + let na = a.len() - 1; + let nb = b.len() - 1; + if a_cube && b_cube { + let gcd = gcd(na, nb); + let lcm = (na / gcd).checked_mul(nb).ok_or(ShapeError::TooLarge)?; + if multiplier + .checked_mul(lcm) + .is_some_and(|volume| volume <= 256) + { + return Ok(Merger { + coords: (0..=lcm).map(|i| i as f64 / lcm as f64).collect(), + first: (0..lcm).map(|i| (i / (nb / gcd)) as i32).collect(), + second: (0..lcm).map(|i| (i / (na / gcd)) as i32).collect(), + cube_range: true, + discrete_cube: true, + }); + } + } + if a[na] < b[0] - COLLISION_EPSILON { + return Ok(disjoint(a, b, false)); + } + if b[nb] < a[0] - COLLISION_EPSILON { + return Ok(disjoint(b, a, true)); + } + // Primitive DoubleArrayList equality treats the two signed zeros equally. + if a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a == b) { + return Ok(Merger { + coords: a.to_vec(), + first: (0..na).map(|i| i as i32).collect(), + second: (0..na).map(|i| i as i32).collect(), + cube_range: a_cube, + discrete_cube: false, + }); + } + let mut coords = Vec::with_capacity(a.len() + b.len()); + let mut first = Vec::with_capacity(coords.capacity()); + let mut second = Vec::with_capacity(coords.capacity()); + let (mut i, mut j) = (0usize, 0usize); + let mut last = f64::NAN; + while i < a.len() || j < b.len() { + let a_end = i == a.len(); + let b_end = j == b.len(); + let choose_a = !a_end && (b_end || a[i] < b[j] + COLLISION_EPSILON); + if choose_a { + i += 1; + if !only_first && (j == 0 || b_end) { + continue; + } + } else { + j += 1; + if !only_second && (i == 0 || a_end) { + continue; + } + } + let ai = i as i32 - 1; + let bj = j as i32 - 1; + let value = if choose_a { a[i - 1] } else { b[j - 1] }; + if !matches!( + last.partial_cmp(&(value - COLLISION_EPSILON)), + Some(std::cmp::Ordering::Greater | std::cmp::Ordering::Equal) + ) { + coords.push(value); + first.push(ai); + second.push(bj); + last = value; + } else { + let n = coords.len() - 1; + first[n] = ai; + second[n] = bj; + } + } + if coords.len() <= 1 { + coords = vec![0.0]; + first.clear(); + second.clear(); + } else { + first.pop(); + second.pop(); + } + Ok(Merger { + coords, + first, + second, + cube_range: false, + discrete_cube: false, + }) +} +fn disjoint(lower: &[f64], upper: &[f64], swap: bool) -> Merger { + let nl = lower.len(); + let nu = upper.len(); + let mut first = Vec::with_capacity(nl + nu - 1); + let mut second = Vec::with_capacity(nl + nu - 1); + for i in 0..nl { + first.push(i as i32); + second.push(-1); + } + for i in 0..nu - 1 { + first.push(nl as i32 - 1); + second.push(i as i32); + } + if swap { + std::mem::swap(&mut first, &mut second); + } + Merger { + coords: lower.iter().chain(upper).copied().collect(), + first, + second, + cube_range: false, + discrete_cube: false, + } +} +fn gcd(mut a: usize, mut b: usize) -> usize { + while b != 0 { + let r = a % b; + a = b; + b = r; + } + a +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::geometry::Vec3; + #[test] + fn signed_zero_list_equality_preserves_first_coordinates() { + let a = VoxelShape::from_grid([vec![0.0, 1.0], vec![0.0, 1.0], vec![0.0, 1.0]], &[true]) + .unwrap(); + let b = VoxelShape::from_grid([vec![-0.0, 1.0], vec![0.0, 1.0], vec![0.0, 1.0]], &[true]) + .unwrap(); + let joined = a.join_unoptimized(&b, ShapeOp::FALSE).unwrap(); + assert!(joined.is_empty()); + assert_eq!(joined.coordinates(Axis::X)[0].to_bits(), 0.0f64.to_bits()); + assert_eq!(joined.coordinates(Axis::X).len(), 2); + } + #[test] + fn returned_shapes_preserve_alias_identity() { + let a = VoxelShape::block().moved(Vec3::new(2.0, 0.0, 0.0)); + let alias = VoxelShape::empty() + .join_unoptimized(&a, ShapeOp::OR) + .unwrap(); + assert!(a.same_identity(&alias)); + let result = a.join_unoptimized(&alias, ShapeOp::FALSE).unwrap(); + assert!(result.same_identity(&VoxelShape::empty())); + assert_eq!(result.coordinates(Axis::X), &[0.0]); + assert!(!a.same_identity(&a.moved(Vec3::ZERO))); + } + #[test] + fn unions_intersections_difference_and_rejection() { + let a = VoxelShape::block(); + let b = a.moved(Vec3::new(0.5, 0.0, 0.0)); + let union = a.join_unoptimized(&b, ShapeOp::OR).unwrap(); + assert_eq!(union.max(Axis::X), 1.5); + let intersection = a.join_unoptimized(&b, ShapeOp::AND).unwrap(); + assert_eq!(intersection.min(Axis::X), 0.5); + assert_eq!(intersection.max(Axis::X), 1.0); + let difference = a.join_unoptimized(&b, ShapeOp::ONLY_FIRST).unwrap(); + assert_eq!(difference.max(Axis::X), 0.5); + assert!(!a.join_is_not_empty(&a, ShapeOp::XOR).unwrap()); + assert!( + a.join_unoptimized(&b, ShapeOp::from_truth_table(1)) + .is_err() + ); + } +} diff --git a/crates/horizon-core/src/geometry/sweep.rs b/crates/horizon-core/src/geometry/sweep.rs new file mode 100644 index 000000000..e90ee5634 --- /dev/null +++ b/crates/horizon-core/src/geometry/sweep.rs @@ -0,0 +1,224 @@ +//! BlockGetter.forEachBlockIntersectedBetween's ordered movement-path visits. +use super::{Aabb, TraversalError, Vec3, clamp, floor_i32}; +use crate::position::BlockPos; +use std::collections::HashSet; + +struct Sweep<'v, V> { + visitor: &'v mut V, + visited: HashSet, + work: usize, + limit: usize, +} +impl bool> Sweep<'_, V> { + fn spend(&mut self) -> Result<(), TraversalError> { + if self.work == self.limit { + return Err(TraversalError::VisitLimit); + } + self.work += 1; + Ok(()) + } + fn visit( + &mut self, + positions: impl Iterator, + step: i32, + deduplicate: bool, + ) -> Result { + for pos in positions { + self.spend()?; + if deduplicate && !self.visited.insert(pos.pack()) { + continue; + } + if !(self.visitor)(pos, step) { + return Ok(false); + } + if !deduplicate { + self.visited.insert(pos.pack()); + } + } + Ok(true) + } +} + +/// Visit blocks and step indices for a moving box, stopping if the callback +/// returns false. `final_box` is the box at `end`, not at `start`. +/// +/// Only finite inputs/computed geometry and positive Java-int-sized block boxes +/// are supported. `max_work` limits iterator candidates and ray steps, including +/// suppressed duplicate visits. Prior callbacks remain applied on an error. +/// Block/entity effects and their state transitions are separate from visitation. +pub fn sweep_intersected_blocks( + start: Vec3, + end: Vec3, + final_box: Aabb, + max_work: usize, + mut visitor: impl FnMut(BlockPos, i32) -> bool, +) -> Result { + if !start.is_finite() + || !end.is_finite() + || !final_box.min_position().is_finite() + || !final_box.max_position().is_finite() + { + return Err(TraversalError::NonFinite); + } + let movement = end.subtract(start); + if !movement.is_finite() { + return Err(TraversalError::NonFinite); + } + if movement.length_squared() < (1.0e-5_f32 * 1.0e-5_f32) as f64 { + let blocks = + BlockPos::between_closed_box(final_box).map_err(|_| TraversalError::InvalidBounds)?; + // This branch has no deduplication in vanilla. Avoid allocating a set + // or copying visited positions for stationary/tiny movements. + for (work, pos) in blocks.enumerate() { + if work == max_work { + return Err(TraversalError::VisitLimit); + } + if !visitor(pos, 0) { + return Ok(false); + } + } + return Ok(true); + } + let mut sweep = Sweep { + visitor: &mut visitor, + visited: HashSet::new(), + work: 0, + limit: max_work, + }; + let initial_box = final_box.move_by(movement.scale(-1.0)); + if !initial_box.min_position().is_finite() || !initial_box.max_position().is_finite() { + return Err(TraversalError::NonFinite); + } + let initial = BlockPos::between_box_corners_in_direction(initial_box, movement) + .map_err(|_| TraversalError::InvalidBounds)?; + if !sweep.visit(initial, 0, false)? { + return Ok(false); + } + let size = final_box.size().components(); + let corner = furthest_corner(movement); + let center = final_box.center().components(); + let finish = Vec3::new( + center[0] + size[0] * 0.5 * corner[0] as f64, + center[1] + size[1] * 0.5 * corner[1] as f64, + center[2] + size[2] * 0.5 * corner[2] as f64, + ); + let origin = finish.subtract(movement); + if !origin.is_finite() || !finish.is_finite() || size.iter().any(|v| !v.is_finite()) { + return Err(TraversalError::NonFinite); + } + let mut position = origin.components().map(floor_i32); + let delta = movement.components(); + let sign = delta.map(|v| { + if v == 0.0 { + 0i32 + } else if v > 0.0 { + 1 + } else { + -1 + } + }); + let increment = std::array::from_fn::<_, 3, _>(|i| { + if sign[i] == 0 { + f64::MAX + } else { + sign[i] as f64 / delta[i] + } + }); + let mut boundary = std::array::from_fn::<_, 3, _>(|i| { + let value = origin.components()[i]; + let fraction = value - (value.floor() as i64) as f64; + increment[i] + * if sign[i] > 0 { + 1.0 - fraction + } else { + fraction + } + }); + let mut step = 0i32; + while boundary.iter().any(|v| *v <= 1.0) { + sweep.spend()?; + let axis = if boundary[0] < boundary[1] { + if boundary[0] < boundary[2] { 0 } else { 2 } + } else if boundary[1] < boundary[2] { + 1 + } else { + 2 + }; + position[axis] = position[axis].wrapping_add(sign[axis]); + boundary[axis] += increment[axis]; + let pos = BlockPos::new(position[0], position[1], position[2]); + // The static Java clip takes raw endpoints, including wrapped +1 ints. + let block_box = Aabb { + min: Vec3::from_block(pos), + max: Vec3::from_block(pos.offset(1, 1, 1)), + }; + let Some(point) = block_box.clip(origin, finish) else { + continue; + }; + step = step.wrapping_add(1); + let clamped = std::array::from_fn::<_, 3, _>(|i| { + clamp( + point.components()[i], + position[i] as f64 + 1.0e-5_f32 as f64, + (position[i] as f64 + 1.0) - 1.0e-5_f32 as f64, + ) + }); + let opposite = + std::array::from_fn::<_, 3, _>(|i| floor_i32(clamped[i] - size[i] * corner[i] as f64)); + let blocks = BlockPos::between_corners_in_direction( + pos, + BlockPos::new(opposite[0], opposite[1], opposite[2]), + movement, + ) + .map_err(|_| TraversalError::InvalidBounds)?; + if !sweep.visit(blocks, step, true)? { + return Ok(false); + } + } + let final_blocks = BlockPos::between_box_corners_in_direction(final_box, movement) + .map_err(|_| TraversalError::InvalidBounds)?; + sweep.visit(final_blocks, step.wrapping_add(1), true) +} + +fn furthest_corner(movement: Vec3) -> [i32; 3] { + let abs = [ + Vec3::new(1.0, 0.0, 0.0).dot(movement).abs(), + Vec3::new(0.0, 1.0, 0.0).dot(movement).abs(), + Vec3::new(0.0, 0.0, 1.0).dot(movement).abs(), + ]; + let [x, y, z] = movement.components().map(|v| if v >= 0.0 { 1 } else { -1 }); + if abs[0] <= abs[1] && abs[0] <= abs[2] { + [-x, -z, y] + } else if abs[1] <= abs[2] { + [z, -y, -x] + } else { + [-y, x, -z] + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn tiny_movement_includes_maximum_faces_and_stops_immediately() { + let box_ = Aabb::unit_cube(Vec3::ZERO); + let mut visits = Vec::new(); + assert_eq!( + sweep_intersected_blocks(Vec3::ZERO, Vec3::ZERO, box_, 20, |p, step| { + visits.push((p, step)); + true + }), + Ok(true) + ); + assert_eq!(visits.len(), 8); + assert!(visits.iter().all(|(_, step)| *step == 0)); + assert_eq!( + sweep_intersected_blocks(Vec3::ZERO, Vec3::ZERO, box_, 20, |_, _| false), + Ok(false) + ); + assert_eq!( + sweep_intersected_blocks(Vec3::ZERO, Vec3::ZERO, box_, 1, |_, _| true), + Err(TraversalError::VisitLimit) + ); + } +} diff --git a/crates/horizon-core/src/geometry/traversal.rs b/crates/horizon-core/src/geometry/traversal.rs new file mode 100644 index 000000000..6dee29f6e --- /dev/null +++ b/crates/horizon-core/src/geometry/traversal.rs @@ -0,0 +1,155 @@ +//! Ordered block visits for a finite ray, as in BlockGetter.traverseBlocks. +use super::{Vec3, floor_i32}; +use crate::position::BlockPos; +use std::fmt; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TraversalError { + NonFinite, + VisitLimit, + InvalidBounds, +} +impl fmt::Display for TraversalError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "block traversal failed: {self:?}") + } +} +impl std::error::Error for TraversalError {} + +/// Visit blocks in vanilla ray order until the visitor returns Some, or the +/// segment is exhausted. `None` corresponds to vanilla's miss callback. +/// +/// Non-finite geometry and exceeding the caller's visit budget return typed +/// errors. Previously invoked callbacks are not rolled back on a budget error. +pub fn traverse_blocks( + start: Vec3, + end: Vec3, + max_visits: usize, + mut visitor: impl FnMut(BlockPos) -> Option, +) -> Result, TraversalError> { + if !start.is_finite() || !end.is_finite() { + return Err(TraversalError::NonFinite); + } + if start == end { + return Ok(None); + } + let finish = end.lerp(start, -1e-7); + let origin = start.lerp(end, -1e-7); + let delta = origin.vector_to(finish).components(); + if !origin.is_finite() || !finish.is_finite() || delta.iter().any(|v| !v.is_finite()) { + return Err(TraversalError::NonFinite); + } + let mut position = origin.components().map(floor_i32); + let sign = delta.map(|v| { + if v == 0.0 { + 0i32 + } else if v > 0.0 { + 1 + } else { + -1 + } + }); + let step = std::array::from_fn::<_, 3, _>(|i| { + if sign[i] == 0 { + f64::MAX + } else { + sign[i] as f64 / delta[i] + } + }); + let mut boundary = std::array::from_fn::<_, 3, _>(|i| { + let value = origin.components()[i]; + let fraction = value - (value.floor() as i64) as f64; + step[i] + * if sign[i] > 0 { + 1.0 - fraction + } else { + fraction + } + }); + let mut visited = 0; + loop { + if visited == max_visits { + return Err(TraversalError::VisitLimit); + } + visited += 1; + if let Some(result) = visitor(BlockPos::new(position[0], position[1], position[2])) { + return Ok(Some(result)); + } + if !(boundary[0] <= 1.0 || boundary[1] <= 1.0 || boundary[2] <= 1.0) { + return Ok(None); + } + // Strict comparisons give Z priority on a three-way corner tie. + let axis = if boundary[0] < boundary[1] { + if boundary[0] < boundary[2] { 0 } else { 2 } + } else if boundary[1] < boundary[2] { + 1 + } else { + 2 + }; + position[axis] = position[axis].wrapping_add(sign[axis]); + boundary[axis] += step[axis]; + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn corner_order_and_early_exit() { + let mut visited = Vec::new(); + assert_eq!( + traverse_blocks::<()>( + Vec3::new(0.5, 0.5, 0.5), + Vec3::new(1.5, 1.5, 1.5), + 10, + |pos| { + visited.push(pos); + None + } + ), + Ok(None) + ); + assert_eq!( + visited, + vec![ + BlockPos::new(0, 0, 0), + BlockPos::new(0, 0, 1), + BlockPos::new(0, 1, 1), + BlockPos::new(1, 1, 1) + ] + ); + let result = traverse_blocks( + Vec3::new(0.5, 0.5, 0.5), + Vec3::new(1.5, 1.5, 1.5), + 10, + |pos| (pos.z == 1).then_some(pos), + ); + assert_eq!(result, Ok(Some(BlockPos::new(0, 0, 1)))); + } + #[test] + fn miss_zero_identity_and_budget_errors() { + let mut count = 0; + assert_eq!( + traverse_blocks::<()>(Vec3::ZERO, Vec3::ZERO, 0, |_| panic!( + "no visits for equal endpoints" + )), + Ok(None) + ); + assert_eq!( + traverse_blocks::<()>(Vec3::new(-0.0, 0.0, 0.0), Vec3::ZERO, 10, |_| { + count += 1; + None + }), + Ok(None) + ); + assert_eq!(count, 4); + assert_eq!( + traverse_blocks::<()>(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0), 1, |_| None), + Err(TraversalError::VisitLimit) + ); + assert_eq!( + traverse_blocks::<()>(Vec3::ZERO, Vec3::new(f64::NAN, 1.0, 1.0), 1, |_| None), + Err(TraversalError::NonFinite) + ); + } +} diff --git a/crates/horizon-core/src/geometry/trig.rs b/crates/horizon-core/src/geometry/trig.rs new file mode 100644 index 000000000..988f05177 --- /dev/null +++ b/crates/horizon-core/src/geometry/trig.rs @@ -0,0 +1,38 @@ +//! Vanilla's quantized float sine table with Java double-to-long indexing. +use std::sync::OnceLock; + +pub const DEG_TO_RAD: f32 = f32::from_bits(0x3c8e_fa35); +pub const RAD_TO_DEG: f32 = f32::from_bits(0x4265_2ee0); +const SCALE: f64 = 10430.378350470453; +static SINE: OnceLock> = OnceLock::new(); + +/// Generated from the 26.3 table formula, with no bundled vanilla artifact. +/// Differential validation checks all 65,536 entries on the tested platform. +pub fn sine_table() -> &'static [f32] { + SINE.get_or_init(|| { + (0..65536) + .map(|i| (i as f64 / SCALE).sin() as f32) + .collect::>() + .into_boxed_slice() + }) +} +pub fn sin(angle: f64) -> f32 { + sine_table()[((angle * SCALE) as i64 & 65535) as usize] +} +pub fn cos(angle: f64) -> f32 { + sine_table()[((angle * SCALE + 16384.0) as i64 & 65535) as usize] +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn long_narrowing_and_quadrants() { + assert_eq!(sin(0.0).to_bits(), 0.0f32.to_bits()); + assert_eq!(sin(f64::NAN), sin(0.0)); + assert_eq!(sin(f64::INFINITY), sine_table()[65535]); + assert_eq!(sin(f64::NEG_INFINITY), sine_table()[0]); + assert_eq!(cos(0.0), 1.0); + assert_eq!(sin(std::f64::consts::FRAC_PI_2), 1.0); + } +} diff --git a/crates/horizon-core/src/lib.rs b/crates/horizon-core/src/lib.rs new file mode 100644 index 000000000..19c75bc60 --- /dev/null +++ b/crates/horizon-core/src/lib.rs @@ -0,0 +1,17 @@ +//! Horizon's initial simulation primitives, targeting Minecraft Java Edition 26.3. +//! +//! This is not a playable game. Differential checks cover only the operations +//! listed in docs/rust-parity.md; the rest of vanilla remains unimplemented. +#![forbid(unsafe_code)] + +pub mod biome; +pub mod carving; +pub mod density; +pub mod geometry; +pub mod noise; +pub mod position; +pub mod random; +pub mod storage; +pub mod ticks; + +pub const VANILLA_VERSION: &str = "26.3"; diff --git a/crates/horizon-core/src/noise/mod.rs b/crates/horizon-core/src/noise/mod.rs new file mode 100644 index 000000000..cb255fbe5 --- /dev/null +++ b/crates/horizon-core/src/noise/mod.rs @@ -0,0 +1,289 @@ +//! Base noise samplers for the pinned 26.3 target. +//! +//! Coordinates use double precision; Perlin interpolation and its derivatives +//! use single precision. Keep operation order: algebraic rearrangement changes +//! world generation. Complete density graphs and terrain generation remain absent. +mod normal; +mod perlin; +mod simplex; +mod stack; +mod volume; + +pub use normal::{ + NoiseBuildError, NormalNoise, NormalNoiseBuilder, Normalization, OctaveInfo, create_legacy_fbm, +}; +pub use perlin::{PerlinNoise, SmearedPerlinNoise}; +pub use simplex::SimplexNoise; +pub use stack::{Noise, NoiseLayer, NoiseStack, NoiseStackBuilder}; +pub use volume::{DensityError, DensityVolume}; + +use crate::random::RandomSource; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct NanRange; +impl std::fmt::Display for NanRange { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("noise interval bounds cannot include NaN") + } +} +impl std::error::Error for NanRange {} + +/// The immutable offsets and permutation table shared by gradient samplers. +#[derive(Clone, Debug)] +pub struct GradientTable { + offsets: [f64; 3], + permutations: [u8; 256], +} + +impl GradientTable { + pub fn new(random: &mut impl RandomSource, offset_scale: f64) -> Self { + // Zero scale still consumes all three draws. + let offsets = std::array::from_fn(|_| random.next_double() * offset_scale); + let mut permutations = std::array::from_fn(|i| i as u8); + for i in 0..256 { + let other = i + random.next_int_bound((256 - i) as i32).unwrap() as usize; + permutations.swap(i, other); + } + Self { + offsets, + permutations, + } + } + + pub fn offsets(&self) -> &[f64; 3] { + &self.offsets + } + pub fn permutations(&self) -> &[u8; 256] { + &self.permutations + } + + fn permute(&self, index: i32) -> i32 { + i32::from(self.permutations[(index & 255) as usize]) + } + + fn gradient(&self, index: i32) -> [i32; 3] { + GRADIENTS[(self.permute(index) & 15) as usize] + } +} + +// Perlin's 16-direction table includes four repeated directions. Simplex uses +// the first twelve directions, selecting them with remainder instead of masking. +const GRADIENTS: [[i32; 3]; 16] = [ + [1, 1, 0], + [-1, 1, 0], + [1, -1, 0], + [-1, -1, 0], + [1, 0, 1], + [-1, 0, 1], + [1, 0, -1], + [-1, 0, -1], + [0, 1, 1], + [0, -1, 1], + [0, 1, -1], + [0, -1, -1], + [1, 1, 0], + [0, -1, 1], + [-1, 1, 0], + [0, -1, -1], +]; + +fn dot(gradient: [i32; 3], point: [f32; 3]) -> f32 { + gradient[0] as f32 * point[0] + gradient[1] as f32 * point[1] + gradient[2] as f32 * point[2] +} + +/// Vanilla's periodic coordinate reduction with the normal Far Lands flag off. +/// The fast-path boundary is the double immediately below 2^24. +pub fn wrap(value: f64) -> f64 { + let half = f64::from_bits(16_777_216.0_f64.to_bits() - 1); + if value >= -half && value < half { + value + } else { + value - (value / 33_554_432.0 + 0.5).floor() * 33_554_432.0 + } +} + +fn smoothstep(value: f32) -> f32 { + value * value * value * (value * (value * 6.0 - 15.0) + 10.0) +} +fn smoothstep_derivative(value: f32) -> f32 { + 30.0 * value * value * (value - 1.0) * (value - 1.0) +} +fn lerp(delta: f32, start: f32, end: f32) -> f32 { + start + delta * (end - start) +} +fn lerp2(a: f32, b: f32, values: [f32; 4]) -> f32 { + lerp( + b, + lerp(a, values[0], values[1]), + lerp(a, values[2], values[3]), + ) +} +fn lerp3(fade: [f32; 3], values: [f32; 8]) -> f32 { + lerp( + fade[2], + lerp2(fade[0], fade[1], values[..4].try_into().unwrap()), + lerp2(fade[0], fade[1], values[4..].try_into().unwrap()), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{geometry::Axis, random::LegacyRandom}; + + #[test] + fn vanilla_seed_zero_samples_and_derivatives() { + // Values captured by the original adapter from the pinned server JAR. + let mut random = LegacyRandom::new(0); + let noise = PerlinNoise::new(&mut random); + assert_eq!(random.next_long(), -6_819_959_017_335_327_829); + let mut derivative = [0.0; 3]; + assert_eq!( + noise + .noise_with_derivative(0.0, 0.0, 0.0, &mut derivative) + .to_bits(), + 3_183_733_582 + ); + assert_eq!( + derivative.map(f32::to_bits), + [3_189_117_465, 3_214_556_526, 1_017_326_887] + ); + let mut random = LegacyRandom::new(0); + let simplex = SimplexNoise::with_skipped_offsets(&mut random, true); + assert_eq!(simplex.table().offsets(), &[0.0; 3]); + assert_eq!(simplex.table().permutations(), noise.table().permutations()); + assert_eq!(random.next_long(), -6_819_959_017_335_327_829); + assert_eq!(simplex.get2(0.25, 0.75).to_bits(), 3_146_180_247); + assert_eq!(simplex.get3(0.25, 0.5, 0.75).to_bits(), 1_062_011_824); + assert!(simplex.get3(f64::NAN, 0.0, 0.0).is_nan()); + assert_eq!( + SmearedPerlinNoise::new(&mut random, f64::NAN).range(), + Err(NanRange) + ); + } + + #[test] + fn bulk_accumulation_preserves_tail_and_rejects_short_buffers_before_writes() { + let noise = PerlinNoise::new(&mut LegacyRandom::new(0)); + let volume = DensityVolume::new([1; 3], [0; 3], [1; 3]).unwrap(); + let mut random = LegacyRandom::new(0); + let mut values = + std::array::from_fn::<_, 5, _>(|_| f32::from_bits(random.next_int() as u32)); + let tail = values[1..].iter().map(|v| v.to_bits()).collect::>(); + noise + .add_to_volume(&mut values, volume, 1.0, 1.0, 1.0) + .unwrap(); + assert_eq!(values[0].to_bits(), 3_184_062_705); + assert_eq!( + values[1..].iter().map(|v| v.to_bits()).collect::>(), + tail + ); + let before = values.map(f32::to_bits); + let too_large = DensityVolume::new([2; 3], [0; 3], [1; 3]).unwrap(); + assert_eq!( + noise.add_to_volume(&mut values, too_large, 1.0, 1.0, 1.0), + Err(DensityError::BufferTooShort) + ); + assert_eq!(values.map(f32::to_bits), before); + } + + #[test] + fn density_dimensions_are_bounded_and_coordinates_wrap() { + assert_eq!( + DensityVolume::new([0, 1, 1], [0; 3], [1; 3]), + Err(DensityError::NonpositiveDimensions) + ); + assert_eq!( + DensityVolume::new([1; 3], [0; 3], [1, 0, 1]), + Err(DensityError::NonpositiveSteps) + ); + assert_eq!( + DensityVolume::new([i32::MAX; 3], [0; 3], [1; 3]), + Err(DensityError::VolumeTooLarge) + ); + let volume = DensityVolume::new([2, 3, 4], [i32::MAX, 0, -1], [2, 4, 8]).unwrap(); + assert_eq!(volume.block(Axis::X, 1), Some(i32::MIN + 1)); + assert_eq!(volume.block(Axis::X, 2), None); + assert_eq!(volume.index([1, 2, 3]), Some(23)); + assert_eq!(volume.index([1, 3, 3]), None); + } + + #[test] + fn normal_noise_reference_values_and_legacy_failure_draws() { + let mut builder = NormalNoise::builder(); + builder.set_base_octave(-3); + assert_eq!( + builder.set_amplitude_modifier(-1, 0.0).unwrap_err(), + NoiseBuildError::ModifierIndex + ); + builder.set_octave_count(3).unwrap(); + builder.set_amplitude_modifier(1, 0.0).unwrap(); + assert_eq!( + builder.set_octave_count(4).unwrap_err(), + NoiseBuildError::CountAfterModifiers + ); + let definition = builder.build().unwrap(); + assert_eq!( + definition.normalization_factor().to_bits(), + 4_607_442_513_526_237_848 + ); + assert_eq!( + definition + .octaves() + .iter() + .map(|o| o.octave_index) + .collect::>(), + [-3, -1] + ); + let mut random = LegacyRandom::new(0); + let modern = definition.create(&mut random).unwrap(); + assert_eq!(modern.get3(0.0, 0.0, 0.0).to_bits(), 1_042_650_710); + assert_eq!(random.next_long(), -6_688_467_811_848_818_630); + let mut random = LegacyRandom::new(0); + let legacy = definition + .create_for_legacy_nether_biome(&mut random) + .unwrap(); + assert_eq!(legacy.get3(0.0, 0.0, 0.0).to_bits(), 3_199_632_936); + assert_eq!(random.next_long(), 4_966_550_093_728_345_520); + let mut empty = NormalNoise::builder(); + empty.set_base_octave(2).set_octave_count(0).unwrap(); + let mut random = LegacyRandom::new(0); + assert_eq!( + empty + .build() + .unwrap() + .create_for_legacy_nether_biome(&mut random) + .unwrap_err(), + NoiseBuildError::PositiveLegacyOctaves + ); + assert_eq!(random.next_long(), -6_819_959_017_335_327_829); + let mut random = LegacyRandom::new(0); + assert_eq!( + create_legacy_fbm(&mut random, i32::MIN, &[1.0]).unwrap_err(), + NoiseBuildError::LegacyWorkLimit + ); + assert_eq!(random.next_long(), LegacyRandom::new(0).next_long()); + } + + #[test] + fn stack_snapshots_share_layers_and_preserve_zero_amplitude_semantics() { + use std::sync::Arc; + let sampler: Arc = Arc::new(PerlinNoise::new(&mut LegacyRandom::new(0))); + let mut builder = NoiseStack::builder(); + builder.add(Arc::clone(&sampler), 1.0, 0.0); + let zero = builder.build().unwrap(); + builder.add(Arc::clone(&sampler), 2.0, 1.0); + assert_eq!(zero.layers().len(), 1); + assert!(Arc::ptr_eq(zero.get_layer(0).unwrap(), &sampler)); + assert!(zero.get_layer(1).is_none()); + let mut flattened = NoiseStack::builder(); + flattened.add_stack(&zero, 1.0, f32::INFINITY); + assert_eq!(flattened.build().unwrap_err(), NanRange); + let nested = NoiseStack::builder() + .add(Arc::new(zero), 1.0, f32::INFINITY) + .build() + .unwrap(); + assert_eq!(nested.range().unwrap(), [0.0; 2]); + assert!(nested.get3(1.0, 2.0, 3.0).is_nan()); + } +} diff --git a/crates/horizon-core/src/noise/normal.rs b/crates/horizon-core/src/noise/normal.rs new file mode 100644 index 000000000..1a0b8b853 --- /dev/null +++ b/crates/horizon-core/src/noise/normal.rs @@ -0,0 +1,387 @@ +use super::{NanRange, NoiseStack, PerlinNoise}; +use crate::random::{PositionalRandom, RandomSource}; +use std::sync::Arc; + +/// An allocation bound for the builder API (the vanilla data codec allows 32). +const MAX_BUILDER_OCTAVES: i32 = 4096; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NoiseBuildError { + NegativeOctaveCount, + TooManyOctaves, + CountAfterModifiers, + ModifierIndex, + EmptyAmplitudes, + NanRange, + InvertedRange, + MissingNoiseLevels, + PositiveLegacyOctaves, + LegacyWorkLimit, +} +impl std::fmt::Display for NoiseBuildError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::NegativeOctaveCount => "octave count cannot be negative", + Self::TooManyOctaves => "octave count exceeds the 4096-layer allocation bound", + Self::CountAfterModifiers => { + "cannot change octave count after setting amplitude modifiers" + } + Self::ModifierIndex => "amplitude modifier index is outside the octave range", + Self::EmptyAmplitudes => "at least one amplitude is required", + Self::NanRange => "noise interval bounds cannot include NaN", + Self::InvertedRange => "noise interval lower bound exceeds its upper bound", + Self::MissingNoiseLevels => "legacy initializer could not create all nonzero octaves", + Self::PositiveLegacyOctaves => "positive legacy octaves are disabled", + Self::LegacyWorkLimit => "legacy initializer exceeds the 4096-octave work bound", + }) + } +} +impl std::error::Error for NoiseBuildError {} +impl From for NoiseBuildError { + fn from(_: NanRange) -> Self { + Self::NanRange + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Normalization { + Enabled, + Disabled, + Legacy, +} + +#[derive(Clone, Copy, Debug)] +pub struct OctaveInfo { + pub octave_index: i32, + pub frequency: f64, + pub amplitude: f64, +} +impl OctaveInfo { + pub fn seed(&self) -> String { + format!("octave_{}", self.octave_index) + } +} + +#[derive(Clone, Debug)] +pub struct NormalNoise { + parameters: NormalNoiseBuilder, + octaves: Vec, + normalization_factor: f64, + range: [f32; 2], +} +impl NormalNoise { + pub fn builder() -> NormalNoiseBuilder { + NormalNoiseBuilder::default() + } + pub fn octaves(&self) -> &[OctaveInfo] { + &self.octaves + } + pub fn normalization_factor(&self) -> f64 { + self.normalization_factor + } + pub fn range(&self) -> [f32; 2] { + self.range + } + + pub fn create(&self, random: &mut impl RandomSource) -> Result { + // Even an empty stack consumes both positional forks. + let first = random.fork_positional(); + let second = random.fork_positional(); + let mut builder = NoiseStack::builder(); + for octave in &self.octaves { + let name = octave.seed(); + let a = PerlinNoise::new(&mut first.from_hash_of(&name)); + let b = PerlinNoise::new(&mut second.from_hash_of(&name)); + let amplitude = (self.normalization_factor * octave.amplitude) as f32; + builder.add(Arc::new(a), octave.frequency, amplitude); + builder.add( + Arc::new(b), + octave.frequency * 1.018_126_888_217_522_7, + amplitude, + ); + } + Ok(builder.build()?) + } + + pub fn create_for_legacy_nether_biome( + &self, + random: &mut impl RandomSource, + ) -> Result { + let defaults; + let modifiers = if self.parameters.modifiers.is_empty() { + defaults = vec![1.0; self.parameters.octave_count as usize]; + &defaults + } else { + &self.parameters.modifiers + }; + let first = create_legacy_fbm(random, self.parameters.base_octave, modifiers)?; + let second = create_legacy_fbm(random, self.parameters.base_octave, modifiers)?; + let amplitude = (self.normalization_factor * self.parameters.base_amplitude) as f32; + Ok(NoiseStack::builder() + .add_stack(&first, 1.0, amplitude) + .add_stack(&second, 1.018_126_888_217_522_7, amplitude) + .build()?) + } + + pub fn create_parity(base_octave: i32, amplitudes: &[f64]) -> Result { + if amplitudes.is_empty() { + return Err(NoiseBuildError::EmptyAmplitudes); + } + if amplitudes.len() > MAX_BUILDER_OCTAVES as usize { + return Err(NoiseBuildError::TooManyOctaves); + } + let count = amplitudes.len() as i32; + let octaves = build_octaves(base_octave, 1.0, count, true, amplitudes); + let factor = normalization_factor(sum_abs(&octaves), &octaves); + let base_amplitude = if factor == 0.0 { + 1.0 + } else { + parity_factor(1.0, count, amplitudes) / factor + }; + NormalNoiseBuilder { + base_octave, + base_amplitude, + octave_count: count, + normalization: Normalization::Enabled, + modifiers: amplitudes.to_vec(), + } + .build() + } +} + +#[derive(Clone, Debug)] +pub struct NormalNoiseBuilder { + base_amplitude: f64, + base_octave: i32, + octave_count: i32, + normalization: Normalization, + modifiers: Vec, +} +impl Default for NormalNoiseBuilder { + fn default() -> Self { + Self { + base_amplitude: 1.0, + base_octave: 0, + octave_count: 1, + normalization: Normalization::Enabled, + modifiers: Vec::new(), + } + } +} +impl NormalNoiseBuilder { + pub fn set_base_amplitude(&mut self, amplitude: f64) -> &mut Self { + self.base_amplitude = amplitude; + self + } + pub fn set_base_octave(&mut self, octave: i32) -> &mut Self { + self.base_octave = octave; + self + } + pub fn set_normalization(&mut self, normalization: Normalization) -> &mut Self { + self.normalization = normalization; + self + } + pub fn set_octave_count(&mut self, count: i32) -> Result<&mut Self, NoiseBuildError> { + if !self.modifiers.is_empty() { + return Err(NoiseBuildError::CountAfterModifiers); + } + self.octave_count = count; + Ok(self) + } + pub fn set_amplitude_modifier( + &mut self, + index: i32, + value: f64, + ) -> Result<&mut Self, NoiseBuildError> { + if index < 0 || index >= self.octave_count { + return Err(NoiseBuildError::ModifierIndex); + } + if self.octave_count > MAX_BUILDER_OCTAVES { + return Err(NoiseBuildError::TooManyOctaves); + } + if self.modifiers.is_empty() { + self.modifiers.resize(self.octave_count as usize, 1.0); + } + self.modifiers[index as usize] = value; + Ok(self) + } + pub fn build(&self) -> Result { + if self.octave_count < 0 { + return Err(NoiseBuildError::NegativeOctaveCount); + } + if self.octave_count > MAX_BUILDER_OCTAVES { + return Err(NoiseBuildError::TooManyOctaves); + } + let octaves = build_octaves( + self.base_octave, + self.base_amplitude, + self.octave_count, + self.normalization != Normalization::Disabled, + &self.modifiers, + ); + let mut sum = sum_abs(&octaves); + let mut factor = normalization_factor(sum, &octaves); + if self.normalization == Normalization::Legacy && factor != 0.0 { + let legacy = parity_factor(self.base_amplitude, self.octave_count, &self.modifiers); + sum *= legacy / factor; + factor = legacy; + } + let bound = (sum * (1.0 / 3.0) * 6.0) as f32; + if bound.is_nan() { + return Err(NoiseBuildError::NanRange); + } + if bound < 0.0 { + return Err(NoiseBuildError::InvertedRange); + } + Ok(NormalNoise { + parameters: self.clone(), + octaves, + normalization_factor: factor, + range: [-bound, bound], + }) + } +} + +/// The legacy initializer consumes the caller's stream in reverse octave order. +/// Missing and zero-amplitude octaves consume exactly 262 integer draws. +/// Requests outside the documented allocation/work bounds fail before drawing. +pub fn create_legacy_fbm( + random: &mut impl RandomSource, + base_octave: i32, + amplitudes: &[f64], +) -> Result { + if amplitudes.len() > MAX_BUILDER_OCTAVES as usize { + return Err(NoiseBuildError::TooManyOctaves); + } + let zero_index = base_octave.wrapping_neg(); + if zero_index.wrapping_sub(1) >= MAX_BUILDER_OCTAVES { + return Err(NoiseBuildError::LegacyWorkLimit); + } + let count = amplitudes.len() as i32; + let mut levels = vec![None; amplitudes.len()]; + let zero_noise = PerlinNoise::new(random); + if zero_index >= 0 && zero_index < count && amplitudes[zero_index as usize] != 0.0 { + levels[zero_index as usize] = Some(zero_noise); + } + for index in (0..zero_index).rev() { + if index < count && amplitudes[index as usize] != 0.0 { + levels[index as usize] = Some(PerlinNoise::new(random)); + } else { + random.consume_count(262); + } + } + if levels.iter().filter(|v| v.is_some()).count() + != amplitudes.iter().filter(|v| **v != 0.0).count() + { + return Err(NoiseBuildError::MissingNoiseLevels); + } + if zero_index < count - 1 { + return Err(NoiseBuildError::PositiveLegacyOctaves); + } + let mut frequency = power_of_two(zero_index.wrapping_neg()); + let mut amplitude = power_of_two(count - 1) / (power_of_two(count) - 1.0); + let mut builder = NoiseStack::builder(); + for (index, noise) in levels.into_iter().enumerate() { + if let Some(noise) = noise { + builder.add( + Arc::new(noise), + frequency, + (amplitude * amplitudes[index]) as f32, + ); + } + frequency *= 2.0; + amplitude /= 2.0; + } + Ok(builder.build()?) +} + +fn modifier(modifiers: &[f64], index: usize) -> f64 { + if modifiers.is_empty() { + 1.0 + } else { + modifiers[index] + } +} + +fn build_octaves( + base: i32, + amplitude: f64, + count: i32, + normalize: bool, + modifiers: &[f64], +) -> Vec { + let mut frequency = power_of_two(base); + let mut amplitude = amplitude; + if normalize { + amplitude *= power_of_two(count - 1) / (power_of_two(count) - 1.0); + } + let mut result = Vec::with_capacity(count as usize); + for index in 0..count { + let multiplier = modifier(modifiers, index as usize); + if multiplier != 0.0 { + result.push(OctaveInfo { + octave_index: base.wrapping_add(index), + frequency, + amplitude: amplitude * multiplier, + }); + } + frequency *= 2.0; + amplitude *= 0.5; + } + result +} + +// Math.pow(2, integer), including exact subnormal powers and saturation, without +// a platform libm approximation. Frequencies subsequently double iteratively. +fn power_of_two(exponent: i32) -> f64 { + match exponent { + ..=-1075 => 0.0, + -1074..=-1023 => f64::from_bits(1_u64 << (exponent + 1074)), + -1022..=1023 => f64::from_bits(((exponent + 1023) as u64) << 52), + _ => f64::INFINITY, + } +} + +fn sum_abs(octaves: &[OctaveInfo]) -> f64 { + // Sequential DoubleStream.sum uses compensated summation and an uncorrected + // sum to recover infinity when compensation arithmetic produces NaN. + let (mut sum, mut correction, mut simple) = (0.0, 0.0, 0.0); + for octave in octaves { + let value = octave.amplitude.abs(); + let adjusted = value - correction; + let next = sum + adjusted; + correction = (next - sum) - adjusted; + sum = next; + simple += value; + } + let result = sum - correction; + if result.is_nan() && simple.is_infinite() { + simple + } else { + result + } +} +fn normalization_factor(sum: f64, octaves: &[OctaveInfo]) -> f64 { + let mut variance = 0.0; + for octave in octaves { + let deviation = 0.270_224_783_124_521_1 * octave.amplitude.abs(); + variance += deviation * deviation; + } + let deviation = variance.sqrt(); + if deviation == 0.0 { + 0.0 + } else { + (sum * (1.0 / 3.0)) / (deviation * 2.0_f64.sqrt()) + } +} +fn parity_factor(base_amplitude: f64, count: i32, modifiers: &[f64]) -> f64 { + let (mut first, mut last) = (i32::MAX, i32::MIN); + for index in 0..count { + if modifier(modifiers, index as usize) != 0.0 { + first = first.min(index); + last = last.max(index); + } + } + let distance = last.wrapping_sub(first).wrapping_add(1); + base_amplitude * 0.5 * (1.0 / 3.0) / (0.1 * (1.0 + 1.0 / f64::from(distance))) +} diff --git a/crates/horizon-core/src/noise/perlin.rs b/crates/horizon-core/src/noise/perlin.rs new file mode 100644 index 000000000..101ded427 --- /dev/null +++ b/crates/horizon-core/src/noise/perlin.rs @@ -0,0 +1,273 @@ +use super::{ + DensityError, DensityVolume, GradientTable, dot, lerp2, lerp3, smoothstep, + smoothstep_derivative, wrap, +}; +use crate::{geometry::floor_i32, random::RandomSource}; + +#[derive(Clone, Debug)] +pub struct PerlinNoise { + table: GradientTable, +} + +impl PerlinNoise { + pub fn new(random: &mut impl RandomSource) -> Self { + Self { + table: GradientTable::new(random, 256.0), + } + } + pub fn table(&self) -> &GradientTable { + &self.table + } + pub fn range(&self) -> [f32; 2] { + [-2.0, 2.0] + } + pub fn get2(&self, x: f64, z: f64) -> f32 { + self.get3(wrap(x), 0.0, wrap(z)) + } + pub fn get3(&self, x: f64, y: f64, z: f64) -> f32 { + let (cell, relative) = self.coordinates([x, y, z]); + let point = relative.map(|v| v as f32); + self.sample(cell, point, point[1]) + } + + fn coordinates(&self, point: [f64; 3]) -> ([i32; 3], [f64; 3]) { + let shifted: [f64; 3] = std::array::from_fn(|i| wrap(point[i]) + self.table.offsets[i]); + let cell = shifted.map(floor_i32); + ( + cell, + std::array::from_fn(|i| shifted[i] - f64::from(cell[i])), + ) + } + + fn gradients(&self, cell: [i32; 3]) -> [[i32; 3]; 8] { + let p = self.table.permute(cell[0]); + let q = self.table.permute(cell[0].wrapping_add(1)); + let lower = self.table.permute(p.wrapping_add(cell[1])); + let upper = self.table.permute(p.wrapping_add(cell[1]).wrapping_add(1)); + let lower_x = self.table.permute(q.wrapping_add(cell[1])); + let upper_x = self.table.permute(q.wrapping_add(cell[1]).wrapping_add(1)); + let rows = [ + lower, lower_x, upper, upper_x, lower, lower_x, upper, upper_x, + ]; + std::array::from_fn(|i| { + self.table + .gradient(rows[i].wrapping_add(cell[2]).wrapping_add((i / 4) as i32)) + }) + } + + fn corner_values(gradients: [[i32; 3]; 8], point: [f32; 3]) -> [f32; 8] { + std::array::from_fn(|i| { + dot( + gradients[i], + [ + point[0] - (i & 1) as f32, + point[1] - ((i >> 1) & 1) as f32, + point[2] - ((i >> 2) & 1) as f32, + ], + ) + }) + } + + fn sample(&self, cell: [i32; 3], point: [f32; 3], interpolation_y: f32) -> f32 { + let values = Self::corner_values(self.gradients(cell), point); + lerp3( + [ + smoothstep(point[0]), + smoothstep(interpolation_y), + smoothstep(point[2]), + ], + values, + ) + } + + /// Returns the sampled value and adds its gradient into the supplied array. + pub fn noise_with_derivative(&self, x: f64, y: f64, z: f64, derivative: &mut [f32; 3]) -> f32 { + let (cell, relative) = self.coordinates([x, y, z]); + let point = relative.map(|v| v as f32); + let gradients = self.gradients(cell); + let values = Self::corner_values(gradients, point); + let fade = point.map(smoothstep); + let gradient = + std::array::from_fn::<_, 3, _>(|axis| lerp3(fade, gradients.map(|g| g[axis] as f32))); + let changes = [ + lerp2( + fade[1], + fade[2], + [ + values[1] - values[0], + values[3] - values[2], + values[5] - values[4], + values[7] - values[6], + ], + ), + lerp2( + fade[2], + fade[0], + [ + values[2] - values[0], + values[6] - values[4], + values[3] - values[1], + values[7] - values[5], + ], + ), + lerp2( + fade[0], + fade[1], + [ + values[4] - values[0], + values[5] - values[1], + values[6] - values[2], + values[7] - values[3], + ], + ), + ]; + for axis in 0..3 { + derivative[axis] += gradient[axis] + smoothstep_derivative(point[axis]) * changes[axis]; + } + lerp3(fade, values) + } + + /// Adds a scaled volume using vanilla's cached X/Z dot products and Y loop. + /// Extra buffer elements are untouched; short buffers are rejected up front. + pub fn add_to_volume( + &self, + buffer: &mut [f32], + volume: DensityVolume, + xz_scale: f64, + y_scale: f64, + amplitude: f32, + ) -> Result<(), DensityError> { + self.add_volume(buffer, volume, xz_scale, y_scale, amplitude, None) + } + + fn add_volume( + &self, + buffer: &mut [f32], + volume: DensityVolume, + xz_scale: f64, + y_scale: f64, + amplitude: f32, + fudge_y_scale: Option, + ) -> Result<(), DensityError> { + if buffer.len() < volume.size() { + return Err(DensityError::BufferTooShort); + } + let [size_x, size_y, size_z] = volume.sizes(); + let mut index = 0; + for z in 0..size_z { + let shifted_z = + wrap(f64::from(volume.coordinate(2, z)) * xz_scale) + self.table.offsets[2]; + let cell_z = floor_i32(shifted_z); + let dz = (shifted_z - f64::from(cell_z)) as f32; + let fade_z = smoothstep(dz); + for x in 0..size_x { + let shifted_x = + wrap(f64::from(volume.coordinate(0, x)) * xz_scale) + self.table.offsets[0]; + let cell_x = floor_i32(shifted_x); + let dx = (shifted_x - f64::from(cell_x)) as f32; + let fade_x = smoothstep(dx); + let mut previous_y = i32::MIN; + let mut xz_dots = [0.0_f32; 8]; + let mut y_gradients = [0.0_f32; 8]; + for y in 0..size_y { + let input_y = f64::from(volume.coordinate(1, y)) * y_scale; + let shifted_y = wrap(input_y) + self.table.offsets[1]; + let cell_y = floor_i32(shifted_y); + let dy = shifted_y - f64::from(cell_y); + let fade_y = smoothstep(dy as f32); + if previous_y != cell_y { + let gradients = self.gradients([cell_x, cell_y, cell_z]); + for i in 0..8 { + xz_dots[i] = gradients[i][0] as f32 * (dx - (i & 1) as f32) + + gradients[i][2] as f32 * (dz - ((i >> 2) & 1) as f32); + y_gradients[i] = gradients[i][1] as f32; + } + previous_y = cell_y; + } + let dy = match fudge_y_scale { + Some(scale) => (dy - compute_fudge_y(input_y, dy, scale)) as f32, + None => dy as f32, + }; + let values = std::array::from_fn(|i| { + xz_dots[i] + y_gradients[i] * (dy - ((i >> 1) & 1) as f32) + }); + buffer[index] += amplitude * lerp3([fade_x, fade_y, fade_z], values); + index += 1; + } + } + } + Ok(()) + } +} + +#[derive(Clone, Debug)] +pub struct SmearedPerlinNoise { + base: PerlinNoise, + fudge_y_scale: f64, +} + +impl SmearedPerlinNoise { + pub fn new(random: &mut impl RandomSource, fudge_y_scale: f64) -> Self { + Self { + base: PerlinNoise::new(random), + fudge_y_scale, + } + } + pub fn table(&self) -> &GradientTable { + self.base.table() + } + pub fn range(&self) -> Result<[f32; 2], super::NanRange> { + let bound = (self.fudge_y_scale.abs() + 2.0) as f32; + if bound.is_nan() { + Err(super::NanRange) + } else { + Ok([-bound, bound]) + } + } + pub fn get2(&self, x: f64, z: f64) -> f32 { + self.get3(wrap(x), 0.0, wrap(z)) + } + pub fn get3(&self, x: f64, y: f64, z: f64) -> f32 { + let (cell, relative) = self.base.coordinates([x, y, z]); + let fudge = compute_fudge_y(y, relative[1], self.fudge_y_scale); + self.base.sample( + cell, + [ + relative[0] as f32, + (relative[1] - fudge) as f32, + relative[2] as f32, + ], + relative[1] as f32, + ) + } + // This inherited method samples the unsmeared field, just as vanilla does. + pub fn noise_with_derivative(&self, x: f64, y: f64, z: f64, derivative: &mut [f32; 3]) -> f32 { + self.base.noise_with_derivative(x, y, z, derivative) + } + pub fn add_to_volume( + &self, + buffer: &mut [f32], + volume: DensityVolume, + xz_scale: f64, + y_scale: f64, + amplitude: f32, + ) -> Result<(), DensityError> { + self.base.add_volume( + buffer, + volume, + xz_scale, + y_scale, + amplitude, + Some(self.fudge_y_scale), + ) + } +} + +fn compute_fudge_y(input_y: f64, relative_y: f64, scale: f64) -> f64 { + let limited_y = if input_y >= 0.0 && input_y < relative_y { + input_y + } else { + relative_y + }; + f64::from(floor_i32(limited_y / scale + f64::from(1e-7_f32))) * scale +} diff --git a/crates/horizon-core/src/noise/simplex.rs b/crates/horizon-core/src/noise/simplex.rs new file mode 100644 index 000000000..8dcb56f85 --- /dev/null +++ b/crates/horizon-core/src/noise/simplex.rs @@ -0,0 +1,121 @@ +use super::{GRADIENTS, GradientTable}; +use crate::{geometry::floor_i32, random::RandomSource}; + +#[derive(Clone, Debug)] +pub struct SimplexNoise { + table: GradientTable, +} + +impl SimplexNoise { + pub fn new(random: &mut impl RandomSource) -> Self { + Self::with_skipped_offsets(random, false) + } + pub fn with_skipped_offsets(random: &mut impl RandomSource, skip_offsets: bool) -> Self { + Self { + table: GradientTable::new(random, if skip_offsets { 0.0 } else { 256.0 }), + } + } + pub fn table(&self) -> &GradientTable { + &self.table + } + pub fn range(&self) -> [f32; 2] { + [-2.0, 2.0] + } + + fn corner(gradient: usize, point: [f64; 3], radius: f64) -> f64 { + let attenuation = radius - point[0] * point[0] - point[1] * point[1] - point[2] * point[2]; + // Negative attenuation contributes zero; NaN follows the arithmetic path. + if attenuation < 0.0 { + 0.0 + } else { + let squared = attenuation * attenuation; + let g = GRADIENTS[gradient]; + squared + * squared + * (f64::from(g[0]) * point[0] + + f64::from(g[1]) * point[1] + + f64::from(g[2]) * point[2]) + } + } + + pub fn get2(&self, x: f64, y: f64) -> f32 { + let x = x + self.table.offsets[0]; + let y = y + self.table.offsets[1]; + let root3 = 3.0_f64.sqrt(); + let skew = 0.5 * (root3 - 1.0); + let unskew = (3.0 - root3) / 6.0; + let shift = (x + y) * skew; + let i = floor_i32(x + shift); + let j = floor_i32(y + shift); + let shift = f64::from(i.wrapping_add(j)) * unskew; + let dx = x - (f64::from(i) - shift); + let dy = y - (f64::from(j) - shift); + let (a, b) = if dx > dy { (1, 0) } else { (0, 1) }; + let i = i & 255; + let j = j & 255; + let grad = |a, b| (self.table.permute(i + a + self.table.permute(j + b)) % 12) as usize; + let first = Self::corner(grad(0, 0), [dx, dy, 0.0], 0.5); + let second = Self::corner( + grad(a, b), + [dx - f64::from(a) + unskew, dy - f64::from(b) + unskew, 0.0], + 0.5, + ); + let third = Self::corner( + grad(1, 1), + [dx - 1.0 + 2.0 * unskew, dy - 1.0 + 2.0 * unskew, 0.0], + 0.5, + ); + (70.0 * (first + second + third)) as f32 + } + + pub fn get3(&self, x: f64, y: f64, z: f64) -> f32 { + let shifted = [ + x + self.table.offsets[0], + y + self.table.offsets[1], + z + self.table.offsets[2], + ]; + let skew = (shifted[0] + shifted[1] + shifted[2]) * (1.0 / 3.0); + let cell = shifted.map(|v| floor_i32(v + skew)); + let unskew = f64::from(cell[0].wrapping_add(cell[1]).wrapping_add(cell[2])) * (1.0 / 6.0); + let point: [f64; 3] = std::array::from_fn(|i| shifted[i] - (f64::from(cell[i]) - unskew)); + let [x, y, z] = point; + let (a, b) = if x >= y { + if y >= z { + ([1, 0, 0], [1, 1, 0]) + } else if x >= z { + ([1, 0, 0], [1, 0, 1]) + } else { + ([0, 0, 1], [1, 0, 1]) + } + } else if y < z { + ([0, 0, 1], [0, 1, 1]) + } else if x < z { + ([0, 1, 0], [0, 1, 1]) + } else { + ([0, 1, 0], [1, 1, 0]) + }; + let cell = cell.map(|v| v & 255); + let grad = |delta: [i32; 3]| { + (self.table.permute( + cell[0] + + delta[0] + + self + .table + .permute(cell[1] + delta[1] + self.table.permute(cell[2] + delta[2])), + ) % 12) as usize + }; + let first = Self::corner(grad([0; 3]), point, 0.6); + let second = Self::corner( + grad(a), + std::array::from_fn(|i| point[i] - f64::from(a[i]) + (1.0 / 6.0)), + 0.6, + ); + let third = Self::corner( + grad(b), + std::array::from_fn(|i| point[i] - f64::from(b[i]) + (1.0 / 3.0)), + 0.6, + ); + let fourth = Self::corner(grad([1; 3]), point.map(|v| v - 1.0 + 0.5), 0.6); + (32.0 * (first + second + third + fourth)) as f32 + } +} diff --git a/crates/horizon-core/src/noise/stack.rs b/crates/horizon-core/src/noise/stack.rs new file mode 100644 index 000000000..9cfe093d5 --- /dev/null +++ b/crates/horizon-core/src/noise/stack.rs @@ -0,0 +1,233 @@ +use super::{DensityError, DensityVolume, NanRange, PerlinNoise, SimplexNoise, SmearedPerlinNoise}; +use std::sync::Arc; + +/// Immutable noise sampling. Implementations may override the default scalar +/// volume traversal when vanilla has a distinct bulk arithmetic path. +pub trait Noise: std::fmt::Debug + Send + Sync { + fn range(&self) -> Result<[f32; 2], NanRange>; + fn get2(&self, x: f64, z: f64) -> f32; + fn get3(&self, x: f64, y: f64, z: f64) -> f32; + fn add_to_volume( + &self, + buffer: &mut [f32], + volume: DensityVolume, + xz_scale: f64, + y_scale: f64, + amplitude: f32, + ) -> Result<(), DensityError> { + if buffer.len() < volume.size() { + return Err(DensityError::BufferTooShort); + } + let [sx, sy, sz] = volume.sizes(); + let mut index = 0; + for z in 0..sz { + let z = f64::from(volume.coordinate(2, z)) * xz_scale; + for x in 0..sx { + let x = f64::from(volume.coordinate(0, x)) * xz_scale; + for y in 0..sy { + let y = f64::from(volume.coordinate(1, y)) * y_scale; + buffer[index] += amplitude * self.get3(x, y, z); + index += 1; + } + } + } + Ok(()) + } +} + +impl Noise for PerlinNoise { + fn range(&self) -> Result<[f32; 2], NanRange> { + Ok(PerlinNoise::range(self)) + } + fn get2(&self, x: f64, z: f64) -> f32 { + PerlinNoise::get2(self, x, z) + } + fn get3(&self, x: f64, y: f64, z: f64) -> f32 { + PerlinNoise::get3(self, x, y, z) + } + fn add_to_volume( + &self, + buffer: &mut [f32], + volume: DensityVolume, + xz_scale: f64, + y_scale: f64, + amplitude: f32, + ) -> Result<(), DensityError> { + PerlinNoise::add_to_volume(self, buffer, volume, xz_scale, y_scale, amplitude) + } +} +impl Noise for SmearedPerlinNoise { + fn range(&self) -> Result<[f32; 2], NanRange> { + SmearedPerlinNoise::range(self) + } + fn get2(&self, x: f64, z: f64) -> f32 { + SmearedPerlinNoise::get2(self, x, z) + } + fn get3(&self, x: f64, y: f64, z: f64) -> f32 { + SmearedPerlinNoise::get3(self, x, y, z) + } + fn add_to_volume( + &self, + buffer: &mut [f32], + volume: DensityVolume, + xz_scale: f64, + y_scale: f64, + amplitude: f32, + ) -> Result<(), DensityError> { + SmearedPerlinNoise::add_to_volume(self, buffer, volume, xz_scale, y_scale, amplitude) + } +} +impl Noise for SimplexNoise { + fn range(&self) -> Result<[f32; 2], NanRange> { + Ok(SimplexNoise::range(self)) + } + fn get2(&self, x: f64, z: f64) -> f32 { + SimplexNoise::get2(self, x, z) + } + fn get3(&self, x: f64, y: f64, z: f64) -> f32 { + SimplexNoise::get3(self, x, y, z) + } +} + +#[derive(Clone, Debug)] +pub struct NoiseLayer { + pub noise: Arc, + pub frequency: f64, + pub amplitude: f32, +} + +#[derive(Clone, Debug)] +pub struct NoiseStack { + layers: Vec, + range: [f32; 2], +} + +impl NoiseStack { + pub fn builder() -> NoiseStackBuilder { + NoiseStackBuilder::default() + } + pub fn layers(&self) -> &[NoiseLayer] { + &self.layers + } + pub fn get_layer(&self, index: usize) -> Option<&Arc> { + self.layers.get(index).map(|layer| &layer.noise) + } +} +impl Noise for NoiseStack { + fn range(&self) -> Result<[f32; 2], NanRange> { + Ok(self.range) + } + fn get2(&self, x: f64, z: f64) -> f32 { + let mut value = 0.0; + for layer in &self.layers { + value += layer.amplitude * layer.noise.get2(x * layer.frequency, z * layer.frequency); + } + value + } + fn get3(&self, x: f64, y: f64, z: f64) -> f32 { + let mut value = 0.0; + for layer in &self.layers { + value += layer.amplitude + * layer.noise.get3( + x * layer.frequency, + y * layer.frequency, + z * layer.frequency, + ); + } + value + } + fn add_to_volume( + &self, + buffer: &mut [f32], + volume: DensityVolume, + xz_scale: f64, + y_scale: f64, + amplitude: f32, + ) -> Result<(), DensityError> { + if buffer.len() < volume.size() { + return Err(DensityError::BufferTooShort); + } + for layer in &self.layers { + layer.noise.add_to_volume( + buffer, + volume, + xz_scale * layer.frequency, + y_scale * layer.frequency, + amplitude * layer.amplitude, + )?; + } + Ok(()) + } +} + +#[derive(Clone, Debug, Default)] +pub struct NoiseStackBuilder { + layers: Vec, +} +impl NoiseStackBuilder { + pub fn add(&mut self, noise: Arc, frequency: f64, amplitude: f32) -> &mut Self { + self.layers.push(NoiseLayer { + noise, + frequency, + amplitude, + }); + self + } + /// Flattening rescales each existing layer before subsequent sampling. + pub fn add_stack(&mut self, stack: &NoiseStack, frequency: f64, amplitude: f32) -> &mut Self { + self.layers + .extend(stack.layers.iter().map(|layer| NoiseLayer { + noise: Arc::clone(&layer.noise), + frequency: layer.frequency * frequency, + amplitude: layer.amplitude * amplitude, + })); + self + } + pub fn build(&self) -> Result { + let mut range = [0.0; 2]; + for layer in &self.layers { + let bounds = layer.noise.range()?; + if layer.amplitude.is_nan() { + return Err(NanRange); + } + let scaled = if bounds[0].is_nan() || bounds[1].is_nan() { + [f32::NAN; 2] + } else { + // Interval.mulBound defines zero times infinity as positive zero. + let product = |v: f32| { + if v == 0.0 || layer.amplitude == 0.0 { + 0.0 + } else { + v * layer.amplitude + } + }; + let a = product(bounds[0]); + let b = product(bounds[1]); + if a < b { + [a, b] + } else if a > b { + [b, a] + } else if a == 0.0 { + [ + f32::from_bits(a.to_bits() | b.to_bits()), + f32::from_bits(a.to_bits() & b.to_bits()), + ] + } else { + [a, b] + } + }; + range = [range[0] + scaled[0], range[1] + scaled[1]]; + if range[0].is_nan() || range[1].is_nan() { + range = [f32::NAN; 2]; + } + // Interval.of interns [0,1], including a supplied negative zero. + if range[0] == 0.0 && range[1] == 1.0 { + range[0] = 0.0; + } + } + Ok(NoiseStack { + layers: self.layers.clone(), + range, + }) + } +} diff --git a/crates/horizon-core/src/noise/volume.rs b/crates/horizon-core/src/noise/volume.rs new file mode 100644 index 000000000..d0362ee1b --- /dev/null +++ b/crates/horizon-core/src/noise/volume.rs @@ -0,0 +1,94 @@ +use crate::geometry::Axis; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DensityError { + NonpositiveDimensions, + NonpositiveSteps, + VolumeTooLarge, + BufferTooShort, +} +impl std::fmt::Display for DensityError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::NonpositiveDimensions => "density dimensions must be positive", + Self::NonpositiveSteps => "density coordinate steps must be positive", + Self::VolumeTooLarge => "density volume exceeds the Java array index domain", + Self::BufferTooShort => "density buffer is smaller than its volume", + }) + } +} +impl std::error::Error for DensityError {} + +/// A bounded strided density volume. The flat layout is Z, X, Y (Y innermost). +/// Block coordinate multiplication and addition retain Java's i32 wrapping. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DensityVolume { + sizes: [usize; 3], + minimum: [i32; 3], + steps: [i32; 3], + size: usize, +} +impl DensityVolume { + pub fn new(sizes: [i32; 3], minimum: [i32; 3], steps: [i32; 3]) -> Result { + if sizes.iter().any(|v| *v <= 0) { + return Err(DensityError::NonpositiveDimensions); + } + if steps.iter().any(|v| *v <= 0) { + return Err(DensityError::NonpositiveSteps); + } + let sizes = sizes.map(|v| v as usize); + let size = sizes + .into_iter() + .try_fold(1_usize, |n, v| n.checked_mul(v)) + .filter(|n| *n <= i32::MAX as usize) + .ok_or(DensityError::VolumeTooLarge)?; + Ok(Self { + sizes, + minimum, + steps, + size, + }) + } + pub fn sizes(self) -> [usize; 3] { + self.sizes + } + pub fn minimum(self) -> [i32; 3] { + self.minimum + } + pub fn steps(self) -> [i32; 3] { + self.steps + } + pub fn size(self) -> usize { + self.size + } + pub fn maximum(self) -> [i32; 3] { + std::array::from_fn(|axis| self.coordinate(axis, self.sizes[axis]).wrapping_sub(1)) + } + pub fn index(self, position: [usize; 3]) -> Option { + if (0..3).any(|i| position[i] >= self.sizes[i]) { + return None; + } + Some(position[1] + (position[0] + position[2] * self.sizes[0]) * self.sizes[1]) + } + pub fn block(self, axis: Axis, index: usize) -> Option { + let axis = axis as usize; + (index < self.sizes[axis]).then(|| self.coordinate(axis, index)) + } + /// Find an exact lattice sample, retaining Java's wrapped subtraction and + /// extent multiplication. Coordinates between samples are cache misses. + pub fn index_of_block(self, position: [i32; 3]) -> Option { + let relative: [i32; 3] = std::array::from_fn(|i| position[i].wrapping_sub(self.minimum[i])); + for (axis, value) in relative.iter().enumerate() { + let extent = (self.sizes[axis] as i32).wrapping_mul(self.steps[axis]); + if *value < 0 || *value >= extent || *value % self.steps[axis] != 0 { + return None; + } + } + self.index(std::array::from_fn(|i| { + (relative[i] / self.steps[i]) as usize + })) + } + pub(super) fn coordinate(self, axis: usize, index: usize) -> i32 { + self.minimum[axis].wrapping_add((index as i32).wrapping_mul(self.steps[axis])) + } +} diff --git a/crates/horizon-core/src/position.rs b/crates/horizon-core/src/position.rs new file mode 100644 index 000000000..2c657ca41 --- /dev/null +++ b/crates/horizon-core/src/position.rs @@ -0,0 +1,184 @@ +//! Integer coordinates and vanilla's packed position formats. +mod iter; +pub use iter::{BlockBoxIter, BlockIterationTooLarge}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct BlockPos { + pub x: i32, + pub y: i32, + pub z: i32, +} + +impl BlockPos { + pub const fn new(x: i32, y: i32, z: i32) -> Self { + Self { x, y, z } + } + + /// Values outside the signed 26/12/26-bit ranges are truncated as in vanilla. + pub const fn pack(self) -> i64 { + (((self.x as u64 & 0x3ff_ffff) << 38) + | ((self.z as u64 & 0x3ff_ffff) << 12) + | (self.y as u64 & 0xfff)) as i64 + } + + pub const fn unpack(value: i64) -> Self { + Self::new( + (value >> 38) as i32, + (value << 52 >> 52) as i32, + (value << 26 >> 38) as i32, + ) + } + + pub const fn offset(self, dx: i32, dy: i32, dz: i32) -> Self { + Self::new( + self.x.wrapping_add(dx), + self.y.wrapping_add(dy), + self.z.wrapping_add(dz), + ) + } + + pub const fn section(self) -> SectionPos { + // Arithmetic shift floors negative coordinates; integer / 16 does not. + SectionPos::new(self.x >> 4, self.y >> 4, self.z >> 4) + } + + pub const fn chunk(self) -> ChunkPos { + ChunkPos::new(self.x >> 4, self.z >> 4) + } + + /// Section update packet coordinate: X in bits 8..11, Z in 4..7, Y in 0..3. + pub const fn section_relative(self) -> u16 { + (((self.x & 15) << 8) | ((self.z & 15) << 4) | (self.y & 15)) as u16 + } + + /// Block-state container index. This is a different layout from packets. + pub const fn section_index(self) -> usize { + (((self.y & 15) << 8) | ((self.z & 15) << 4) | (self.x & 15)) as usize + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct SectionPos { + pub x: i32, + pub y: i32, + pub z: i32, +} + +impl SectionPos { + pub const fn new(x: i32, y: i32, z: i32) -> Self { + Self { x, y, z } + } + + pub const fn pack(self) -> i64 { + (((self.x as u64 & 0x3f_ffff) << 42) + | ((self.z as u64 & 0x3f_ffff) << 20) + | (self.y as u64 & 0xf_ffff)) as i64 + } + + pub const fn unpack(value: i64) -> Self { + Self::new( + (value >> 42) as i32, + (value << 44 >> 44) as i32, + (value << 22 >> 42) as i32, + ) + } + + pub const fn relative_to_block(self, relative: u16) -> BlockPos { + BlockPos::new( + self.x + .wrapping_shl(4) + .wrapping_add(((relative >> 8) & 15) as i32), + self.y.wrapping_shl(4).wrapping_add((relative & 15) as i32), + self.z + .wrapping_shl(4) + .wrapping_add(((relative >> 4) & 15) as i32), + ) + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct ChunkPos { + pub x: i32, + pub z: i32, +} + +impl ChunkPos { + pub const fn new(x: i32, z: i32) -> Self { + Self { x, z } + } + + pub const fn pack(self) -> i64 { + ((self.x as u32 as u64) | ((self.z as u32 as u64) << 32)) as i64 + } + + pub const fn unpack(value: i64) -> Self { + Self::new(value as i32, (value >> 32) as i32) + } + + pub const fn region(self) -> Self { + Self::new(self.x >> 5, self.z >> 5) + } + + pub const fn region_local(self) -> (u8, u8) { + ((self.x & 31) as u8, (self.z & 31) as u8) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn negative_boundaries_use_floor_division() { + for (block, section, local) in [ + (-17, -2, 15), + (-16, -1, 0), + (-1, -1, 15), + (0, 0, 0), + (16, 1, 0), + ] { + let p = BlockPos::new(block, block, block); + assert_eq!(p.section(), SectionPos::new(section, section, section)); + assert_eq!(p.section_relative(), local * 0x111); + assert_eq!(p.section().relative_to_block(p.section_relative()), p); + } + assert_eq!(ChunkPos::new(-1, -33).region(), ChunkPos::new(-1, -2)); + assert_eq!(ChunkPos::new(-1, -33).region_local(), (31, 31)); + } + + #[test] + fn coordinate_formats_are_distinct_and_bijective_in_range() { + let mut packet_indices = [false; 4096]; + let mut storage_indices = [false; 4096]; + for y in 0..16 { + for z in 0..16 { + for x in 0..16 { + let p = BlockPos::new(x, y, z); + packet_indices[p.section_relative() as usize] = true; + storage_indices[p.section_index()] = true; + assert_eq!( + SectionPos::default().relative_to_block(p.section_relative()), + p + ); + } + } + } + assert!(packet_indices.into_iter().all(|x| x)); + assert!(storage_indices.into_iter().all(|x| x)); + assert_ne!( + BlockPos::new(1, 2, 3).section_relative() as usize, + BlockPos::new(1, 2, 3).section_index() + ); + } + + #[test] + fn packed_signed_limits_and_java_overflow() { + let block = BlockPos::new(-33_554_432, -2048, 33_554_431); + assert_eq!(BlockPos::unpack(block.pack()), block); + let section = SectionPos::new(-2_097_152, -524_288, 2_097_151); + assert_eq!(SectionPos::unpack(section.pack()), section); + let chunk = ChunkPos::new(i32::MIN, i32::MAX); + assert_eq!(ChunkPos::unpack(chunk.pack()), chunk); + assert_eq!(BlockPos::new(i32::MAX, 0, 0).offset(1, 0, 0).x, i32::MIN); + } +} diff --git a/crates/horizon-core/src/position/iter.rs b/crates/horizon-core/src/position/iter.rs new file mode 100644 index 000000000..980df68c6 --- /dev/null +++ b/crates/horizon-core/src/position/iter.rs @@ -0,0 +1,159 @@ +//! Inclusive block boxes in vanilla's fixed and movement-dependent visit orders. +use super::BlockPos; +use crate::geometry::{Aabb, Axis, Vec3, floor_i32}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BlockIterationTooLarge; +impl std::fmt::Display for BlockIterationTooLarge { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("block box exceeds the positive Java-int iteration domain") + } +} +impl std::error::Error for BlockIterationTooLarge {} + +/// Value iterator; each position is independent of later cursor updates. +/// +/// Bounds are inclusive, including an AABB's floored maximum face. Boxes whose +/// true volume exceeds i32::MAX are rejected instead of reproducing Java's +/// overflowed counts. A caller can lazily limit a supported box with `take`. +#[derive(Clone, Debug)] +pub struct BlockBoxIter { + start: [i32; 3], + steps: [i32; 3], + sizes: [usize; 3], + // Innermost axis first. + axes: [Axis; 3], + index: usize, + count: usize, +} +impl BlockBoxIter { + fn new( + a: BlockPos, + b: BlockPos, + direction: Option, + ) -> Result { + let a = [a.x, a.y, a.z]; + let b = [b.x, b.y, b.z]; + let min = std::array::from_fn::<_, 3, _>(|i| a[i].min(b[i])); + let max = std::array::from_fn::<_, 3, _>(|i| a[i].max(b[i])); + let sizes = std::array::from_fn::<_, 3, _>(|i| (max[i] as i64 - min[i] as i64 + 1) as u64); + let count = sizes + .into_iter() + .try_fold(1u64, |total, size| { + total.checked_mul(size).filter(|v| *v <= i32::MAX as u64) + }) + .ok_or(BlockIterationTooLarge)?; + let mut start = min; + let mut steps = [1; 3]; + let axes = if let Some(direction) = direction { + for axis in Axis::ALL { + let i = axis as usize; + // NaN takes the negative direction in Java's dcmpl branch. + let forward = direction.component(axis) >= 0.0; + if !forward { + start[i] = max[i]; + steps[i] = -1; + } + } + let [first, second, third] = Axis::step_order(direction); + [third, second, first] + } else { + [Axis::X, Axis::Y, Axis::Z] + }; + Ok(Self { + start, + steps, + sizes: sizes.map(|v| v as usize), + axes, + index: 0, + count: count as usize, + }) + } +} +impl Iterator for BlockBoxIter { + type Item = BlockPos; + fn next(&mut self) -> Option { + if self.index == self.count { + return None; + } + let mut index = self.index; + let mut point = self.start; + for axis in self.axes { + let i = axis as usize; + let offset = index % self.sizes[i]; + index /= self.sizes[i]; + point[i] = point[i].wrapping_add(self.steps[i].wrapping_mul(offset as i32)); + } + self.index += 1; + Some(BlockPos::new(point[0], point[1], point[2])) + } + fn size_hint(&self) -> (usize, Option) { + let remaining = self.count - self.index; + (remaining, Some(remaining)) + } +} +impl ExactSizeIterator for BlockBoxIter {} +impl std::iter::FusedIterator for BlockBoxIter {} + +impl BlockPos { + pub fn containing(point: Vec3) -> Self { + Self::new(floor_i32(point.x), floor_i32(point.y), floor_i32(point.z)) + } + pub fn between_closed(a: Self, b: Self) -> Result { + BlockBoxIter::new(a, b, None) + } + pub fn between_closed_box(b: Aabb) -> Result { + Self::between_closed( + Self::containing(b.min_position()), + Self::containing(b.max_position()), + ) + } + pub fn between_corners_in_direction( + a: Self, + b: Self, + direction: Vec3, + ) -> Result { + BlockBoxIter::new(a, b, Some(direction)) + } + pub fn between_box_corners_in_direction( + b: Aabb, + direction: Vec3, + ) -> Result { + Self::between_corners_in_direction( + Self::containing(b.min_position()), + Self::containing(b.max_position()), + direction, + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn ordering_inclusive_faces_and_value_independence() { + let a = BlockPos::new(-1, 0, 0); + let b = BlockPos::new(0, 1, 0); + assert_eq!( + BlockPos::between_closed(b, a).unwrap().collect::>(), + vec![a, BlockPos::new(0, 0, 0), BlockPos::new(-1, 1, 0), b] + ); + assert_eq!( + BlockPos::between_corners_in_direction(a, b, Vec3::new(-1.0, 0.0, 0.0)) + .unwrap() + .collect::>(), + vec![BlockPos::new(0, 0, 0), a, b, BlockPos::new(-1, 1, 0)] + ); + assert_eq!( + BlockPos::between_closed_box(Aabb::unit_cube(Vec3::ZERO)) + .unwrap() + .len(), + 8 + ); + assert_eq!( + BlockPos::between_closed(BlockPos::new(i32::MIN, 0, 0), BlockPos::new(i32::MAX, 0, 0)) + .unwrap_err(), + BlockIterationTooLarge + ); + } +} diff --git a/crates/horizon-core/src/random.rs b/crates/horizon-core/src/random.rs new file mode 100644 index 000000000..309d48124 --- /dev/null +++ b/crates/horizon-core/src/random.rs @@ -0,0 +1,263 @@ +//! Vanilla's two seeded random streams. No platform/default Rust RNG is used. +mod hash; +mod positional; +mod worldgen; +pub use hash::{seed_from_hash, seed_from_hash_utf16}; +pub use positional::{ + LegacyPositionalRandom, PositionalRandom, XoroshiroPositionalRandom, java_string_hash, + position_seed, +}; +pub use worldgen::{WorldgenPositional, WorldgenRandom, WorldgenSource, slime_chunk_random}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InvalidBound; + +impl std::fmt::Display for InvalidBound { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("bound must be positive") + } +} + +impl std::error::Error for InvalidBound {} + +pub trait RandomSource: Sized { + type Positional: PositionalRandom; + fn set_seed(&mut self, seed: i64); + fn next_int(&mut self) -> i32; + fn next_int_bound(&mut self, bound: i32) -> Result; + fn next_long(&mut self) -> i64; + fn next_boolean(&mut self) -> bool; + fn next_float(&mut self) -> f32; + fn next_double(&mut self) -> f64; + fn fork_positional(&mut self) -> Self::Positional; + fn fork(&mut self) -> Self + where + Self: Sized; + + fn consume_count(&mut self, count: i32) { + for _ in 0..count { + self.next_int(); + } + } + fn next_int_between_inclusive(&mut self, min: i32, max: i32) -> Result { + self.next_int_bound(max.wrapping_sub(min).wrapping_add(1)) + .map(|v| v.wrapping_add(min)) + } + fn next_int_between(&mut self, origin: i32, bound: i32) -> Result { + if origin >= bound { + return Err(InvalidBound); + } + self.next_int_bound(bound.wrapping_sub(origin)) + .map(|v| v.wrapping_add(origin)) + } + fn triangle(&mut self, mean: f64, deviation: f64) -> f64 { + mean + deviation * (self.next_double() - self.next_double()) + } + fn triangle_float(&mut self, mean: f32, deviation: f32) -> f32 { + mean + deviation * (self.next_float() - self.next_float()) + } +} + +#[derive(Clone, Debug)] +pub struct LegacyRandom { + state: u64, +} + +impl LegacyRandom { + const MULTIPLIER: u64 = 0x5_deec_e66d; + const MASK: u64 = (1 << 48) - 1; + + pub fn new(seed: i64) -> Self { + Self { + state: (seed as u64 ^ Self::MULTIPLIER) & Self::MASK, + } + } + + fn bits(&mut self, count: u32) -> i32 { + self.state = self.state.wrapping_mul(Self::MULTIPLIER).wrapping_add(11) & Self::MASK; + (self.state >> (48 - count)) as i32 + } +} + +impl RandomSource for LegacyRandom { + type Positional = LegacyPositionalRandom; + fn fork_positional(&mut self) -> Self::Positional { + LegacyPositionalRandom::new(self.next_long()) + } + fn set_seed(&mut self, seed: i64) { + *self = Self::new(seed); + } + + fn next_int(&mut self) -> i32 { + self.bits(32) + } + + fn next_int_bound(&mut self, bound: i32) -> Result { + if bound <= 0 { + return Err(InvalidBound); + } + if bound & (bound - 1) == 0 { + return Ok(((i64::from(bound) * i64::from(self.bits(31))) >> 31) as i32); + } + loop { + let bits = self.bits(31); + let value = bits % bound; + // Java's signed overflow is part of the rejection rule. + if bits.wrapping_sub(value).wrapping_add(bound - 1) >= 0 { + return Ok(value); + } + } + } + + fn next_long(&mut self) -> i64 { + let high = i64::from(self.bits(32)) << 32; + // Java sign-extends the low int before addition; concatenation differs. + high.wrapping_add(i64::from(self.bits(32))) + } + + fn next_boolean(&mut self) -> bool { + self.bits(1) != 0 + } + fn next_float(&mut self) -> f32 { + self.bits(24) as f32 * (1.0 / 16_777_216.0) + } + fn next_double(&mut self) -> f64 { + let value = (i64::from(self.bits(26)) << 27) + i64::from(self.bits(27)); + value as f64 * (1.0 / 9_007_199_254_740_992.0) + } + + fn fork(&mut self) -> Self { + Self::new(self.next_long()) + } +} + +#[derive(Clone, Debug)] +pub struct XoroshiroRandom { + lo: u64, + hi: u64, +} + +impl XoroshiroRandom { + const GOLDEN_RATIO: u64 = 0x9e37_79b9_7f4a_7c15; + const SILVER_RATIO: u64 = 0x6a09_e667_f3bc_c909; + + pub fn new(seed: i64) -> Self { + let lo = seed as u64 ^ Self::SILVER_RATIO; + Self::from_state( + mix_stafford13(lo), + mix_stafford13(lo.wrapping_add(Self::GOLDEN_RATIO)), + ) + } + + pub fn from_state(lo: u64, hi: u64) -> Self { + if lo | hi == 0 { + Self { + lo: Self::GOLDEN_RATIO, + hi: Self::SILVER_RATIO, + } + } else { + Self { lo, hi } + } + } +} + +impl RandomSource for XoroshiroRandom { + type Positional = XoroshiroPositionalRandom; + fn fork_positional(&mut self) -> Self::Positional { + let lo = self.next_long() as u64; + let hi = self.next_long() as u64; + XoroshiroPositionalRandom::new(lo, hi) + } + fn set_seed(&mut self, seed: i64) { + *self = Self::new(seed); + } + fn next_int(&mut self) -> i32 { + self.next_long() as i32 + } + + fn next_int_bound(&mut self, bound: i32) -> Result { + if bound <= 0 { + return Err(InvalidBound); + } + let bound = bound as u32; + let threshold = bound.wrapping_neg() % bound; + loop { + let product = u64::from(self.next_int() as u32) * u64::from(bound); + if product as u32 >= threshold { + return Ok((product >> 32) as i32); + } + } + } + + fn next_long(&mut self) -> i64 { + let lo = self.lo; + let hi = self.hi ^ lo; + let result = lo.wrapping_add(self.hi).rotate_left(17).wrapping_add(lo); + self.lo = lo.rotate_left(49) ^ hi ^ (hi << 21); + self.hi = hi.rotate_left(28); + result as i64 + } + + fn next_boolean(&mut self) -> bool { + self.next_long() & 1 != 0 + } + fn next_float(&mut self) -> f32 { + ((self.next_long() as u64) >> 40) as f32 * (1.0 / 16_777_216.0) + } + fn next_double(&mut self) -> f64 { + ((self.next_long() as u64) >> 11) as f64 * (1.0 / 9_007_199_254_740_992.0) + } + fn fork(&mut self) -> Self { + let lo = self.next_long() as u64; + let hi = self.next_long() as u64; + Self::from_state(lo, hi) + } +} + +pub const fn mix_stafford13(mut value: u64) -> u64 { + value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + value ^ (value >> 31) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn legacy_jdk_sequence_and_sign_extended_low_word() { + let mut rng = LegacyRandom::new(0); + assert_eq!(rng.next_int(), -1_155_484_576); + assert_eq!(rng.next_int(), -723_955_400); + assert_eq!(LegacyRandom::new(0).next_long(), -4_962_768_465_676_381_896); + } + + fn invalid_bounds_do_not_consume_state(mut rng: R) { + let mut reference = rng.clone(); + for bound in [0, -1, i32::MIN] { + assert_eq!(rng.next_int_bound(bound), Err(InvalidBound)); + } + rng.consume_count(-1); + assert_eq!(rng.next_long(), reference.next_long()); + } + + #[test] + fn invalid_inputs_preserve_both_streams() { + invalid_bounds_do_not_consume_state(LegacyRandom::new(0)); + invalid_bounds_do_not_consume_state(XoroshiroRandom::new(0)); + } + + #[test] + fn zero_state_fallback_and_reseed() { + let mut a = XoroshiroRandom::from_state(0, 0); + let mut b = XoroshiroRandom::from_state( + XoroshiroRandom::GOLDEN_RATIO, + XoroshiroRandom::SILVER_RATIO, + ); + for _ in 0..100 { + assert_eq!(a.next_long(), b.next_long()); + } + a.set_seed(-1); + assert_eq!(a.next_long(), XoroshiroRandom::new(-1).next_long()); + } +} diff --git a/crates/horizon-core/src/random/hash.rs b/crates/horizon-core/src/random/hash.rs new file mode 100644 index 000000000..15cd50174 --- /dev/null +++ b/crates/horizon-core/src/random/hash.rs @@ -0,0 +1,157 @@ +//! Original MD5 implementation for vanilla's deterministic name-derived seeds. +//! Integer algorithm and vectors: https://www.rfc-editor.org/rfc/rfc1321 +//! This is an internal seed transform, not an authentication API. +const K: [u32; 64] = [ + 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391, +]; +const SHIFT: [[u32; 4]; 4] = [ + [7, 12, 17, 22], + [5, 9, 14, 20], + [4, 11, 16, 23], + [6, 10, 15, 21], +]; +struct Md5 { + state: [u32; 4], + buffer: [u8; 64], + used: usize, + bytes: u64, +} +impl Md5 { + fn new() -> Self { + Self { + state: [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476], + buffer: [0; 64], + used: 0, + bytes: 0, + } + } + fn block(&mut self, block: &[u8; 64]) { + let words = std::array::from_fn::<_, 16, _>(|i| { + u32::from_le_bytes(block[i * 4..i * 4 + 4].try_into().unwrap()) + }); + let [mut a, mut b, mut c, mut d] = self.state; + for (i, constant) in K.iter().enumerate() { + let (mix, index) = match i / 16 { + 0 => ((b & c) | (!b & d), i), + 1 => ((d & b) | (!d & c), (5 * i + 1) % 16), + 2 => (b ^ c ^ d, (3 * i + 5) % 16), + _ => (c ^ (b | !d), (7 * i) % 16), + }; + let next = b.wrapping_add( + a.wrapping_add(mix) + .wrapping_add(*constant) + .wrapping_add(words[index]) + .rotate_left(SHIFT[i / 16][i % 4]), + ); + a = d; + d = c; + c = b; + b = next; + } + for (old, value) in self.state.iter_mut().zip([a, b, c, d]) { + *old = old.wrapping_add(value); + } + } + fn update(&mut self, mut input: &[u8]) { + self.bytes = self.bytes.wrapping_add(input.len() as u64); + if self.used != 0 { + let count = (64 - self.used).min(input.len()); + self.buffer[self.used..self.used + count].copy_from_slice(&input[..count]); + self.used += count; + input = &input[count..]; + if self.used != 64 { + return; + } + let block = self.buffer; + self.block(&block); + self.used = 0; + } + while input.len() >= 64 { + self.block(input[..64].try_into().unwrap()); + input = &input[64..]; + } + self.buffer[..input.len()].copy_from_slice(input); + self.used = input.len(); + } + fn finish(mut self) -> [u8; 16] { + let length = self.bytes.wrapping_mul(8).to_le_bytes(); + let count = if self.used < 56 { + 56 - self.used + } else { + 120 - self.used + }; + let mut padding = [0; 64]; + padding[0] = 0x80; + self.update(&padding[..count]); + self.update(&length); + std::array::from_fn(|i| self.state[i / 4].to_le_bytes()[i % 4]) + } +} +fn seed(digest: [u8; 16]) -> [u64; 2] { + [ + u64::from_be_bytes(digest[..8].try_into().unwrap()), + u64::from_be_bytes(digest[8..].try_into().unwrap()), + ] +} +pub fn seed_from_hash(name: &str) -> [u64; 2] { + let mut digest = Md5::new(); + digest.update(name.as_bytes()); + seed(digest.finish()) +} +pub fn seed_from_hash_utf16(name: &[u16]) -> [u64; 2] { + let mut digest = Md5::new(); + for point in char::decode_utf16(name.iter().copied()) { + let mut bytes = [0; 4]; + // Java UTF-8 encoding replaces each malformed surrogate with '?'. + digest.update(point.unwrap_or('?').encode_utf8(&mut bytes).as_bytes()); + } + seed(digest.finish()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn rfc_vectors_and_streaming_padding_boundaries() { + for (input, expected) in [ + ("", "d41d8cd98f00b204e9800998ecf8427e"), + ("a", "0cc175b9c0f1b6a831c399e269772661"), + ("abc", "900150983cd24fb0d6963f7d28e17f72"), + ("message digest", "f96b697d7cb7938d525a2f31aaf161d0"), + ( + "abcdefghijklmnopqrstuvwxyz", + "c3fcd3d76192e4007dfb496cca67e13b", + ), + ( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", + "d174ab98d277d9f5a5611c2c9f419d9f", + ), + ( + "12345678901234567890123456789012345678901234567890123456789012345678901234567890", + "57edf4a22be3c955ac49da2e2107b67a", + ), + ] { + let mut digest = Md5::new(); + for chunk in input.as_bytes().chunks(3) { + digest.update(chunk); + } + let actual: String = digest.finish().iter().map(|v| format!("{v:02x}")).collect(); + assert_eq!(actual, expected); + } + assert_eq!( + seed_from_hash_utf16(&[0xd800, 0x61, 0xdc00]), + seed_from_hash("?a?") + ); + assert_eq!( + seed_from_hash_utf16(&[0xd83d, 0xde00]), + seed_from_hash("😀") + ); + } +} diff --git a/crates/horizon-core/src/random/positional.rs b/crates/horizon-core/src/random/positional.rs new file mode 100644 index 000000000..e7d629185 --- /dev/null +++ b/crates/horizon-core/src/random/positional.rs @@ -0,0 +1,79 @@ +use super::{LegacyRandom, RandomSource, XoroshiroRandom, seed_from_hash, seed_from_hash_utf16}; +use crate::position::BlockPos; + +#[allow(clippy::wrong_self_convention)] // These are seeded factories, matching Java's fromSeed/fromHashOf. +pub trait PositionalRandom { + type Source: RandomSource; + fn at(&self, position: BlockPos) -> Self::Source; + fn from_seed(&self, seed: i64) -> Self::Source; + fn from_hash_of(&self, name: &str) -> Self::Source; + fn from_hash_of_utf16(&self, name: &[u16]) -> Self::Source; +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct LegacyPositionalRandom { + seed: i64, +} +impl LegacyPositionalRandom { + pub const fn new(seed: i64) -> Self { + Self { seed } + } +} +impl PositionalRandom for LegacyPositionalRandom { + type Source = LegacyRandom; + fn at(&self, position: BlockPos) -> Self::Source { + LegacyRandom::new(position_seed(position) ^ self.seed) + } + fn from_seed(&self, seed: i64) -> Self::Source { + LegacyRandom::new(seed) + } + fn from_hash_of(&self, name: &str) -> Self::Source { + LegacyRandom::new(java_string_hash(name.encode_utf16()) as i64 ^ self.seed) + } + fn from_hash_of_utf16(&self, name: &[u16]) -> Self::Source { + LegacyRandom::new(java_string_hash(name.iter().copied()) as i64 ^ self.seed) + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct XoroshiroPositionalRandom { + lo: u64, + hi: u64, +} +impl XoroshiroPositionalRandom { + pub const fn new(lo: u64, hi: u64) -> Self { + Self { lo, hi } + } +} +impl PositionalRandom for XoroshiroPositionalRandom { + type Source = XoroshiroRandom; + fn at(&self, position: BlockPos) -> Self::Source { + XoroshiroRandom::from_state(position_seed(position) as u64 ^ self.lo, self.hi) + } + fn from_seed(&self, seed: i64) -> Self::Source { + XoroshiroRandom::from_state(seed as u64 ^ self.lo, seed as u64 ^ self.hi) + } + fn from_hash_of(&self, name: &str) -> Self::Source { + let [lo, hi] = seed_from_hash(name); + XoroshiroRandom::from_state(lo ^ self.lo, hi ^ self.hi) + } + fn from_hash_of_utf16(&self, name: &[u16]) -> Self::Source { + let [lo, hi] = seed_from_hash_utf16(name); + XoroshiroRandom::from_state(lo ^ self.lo, hi ^ self.hi) + } +} +pub fn java_string_hash(name: impl IntoIterator) -> i32 { + name.into_iter().fold(0i32, |hash, unit| { + hash.wrapping_mul(31).wrapping_add(unit as i32) + }) +} +/// Mth.getSeed's signed Java arithmetic, including the initial int product. +pub const fn position_seed(position: BlockPos) -> i64 { + let mixed = position.x.wrapping_mul(3_129_871) as i64 + ^ (position.z as i64).wrapping_mul(116_129_781) + ^ position.y as i64; + mixed + .wrapping_mul(mixed) + .wrapping_mul(42_317_861) + .wrapping_add(mixed.wrapping_mul(11)) + >> 16 +} diff --git a/crates/horizon-core/src/random/worldgen.rs b/crates/horizon-core/src/random/worldgen.rs new file mode 100644 index 000000000..70c88b0e2 --- /dev/null +++ b/crates/horizon-core/src/random/worldgen.rs @@ -0,0 +1,190 @@ +//! Legacy bit-sampling adapter used by vanilla's world-generation random stream. +use super::{InvalidBound, LegacyRandom, PositionalRandom, RandomSource, XoroshiroRandom}; +use crate::position::BlockPos; + +mod sealed { + pub trait Sealed {} +} +pub trait WorldgenSource: RandomSource + sealed::Sealed { + #[doc(hidden)] + fn worldgen_bits(&mut self, count: i32) -> i32; +} +impl sealed::Sealed for LegacyRandom {} +impl WorldgenSource for LegacyRandom { + fn worldgen_bits(&mut self, count: i32) -> i32 { + self.state = self.state.wrapping_mul(Self::MULTIPLIER).wrapping_add(11) & Self::MASK; + self.state.wrapping_shr(48_i32.wrapping_sub(count) as u32) as i32 + } +} +impl sealed::Sealed for XoroshiroRandom {} +impl WorldgenSource for XoroshiroRandom { + fn worldgen_bits(&mut self, count: i32) -> i32 { + (self.next_long() as u64).wrapping_shr(64_i32.wrapping_sub(count) as u32) as i32 + } +} + +#[derive(Clone, Debug)] +pub struct WorldgenRandom { + source: R, + count: i32, + wrapped: bool, +} +impl WorldgenRandom { + pub fn new(source: R) -> Self { + Self { + source, + count: 0, + wrapped: true, + } + } + fn plain(source: R) -> Self { + Self { + source, + count: 0, + wrapped: false, + } + } + pub fn count(&self) -> i32 { + self.count + } + pub fn next_bits(&mut self, bits: i32) -> i32 { + if self.wrapped { + self.count = self.count.wrapping_add(1); + } + self.source.worldgen_bits(bits) + } + pub fn set_decoration_seed(&mut self, seed: i64, x: i32, z: i32) -> i64 { + self.set_seed(seed); + let a = self.next_long() | 1; + let b = self.next_long() | 1; + let mixed = (x as i64) + .wrapping_mul(a) + .wrapping_add((z as i64).wrapping_mul(b)) + ^ seed; + self.set_seed(mixed); + mixed + } + pub fn set_feature_seed(&mut self, seed: i64, index: i32, step: i32) { + self.set_seed( + seed.wrapping_add(index as i64) + .wrapping_add(step.wrapping_mul(10000) as i64), + ); + } + pub fn set_large_feature_seed(&mut self, seed: i64, x: i32, z: i32) { + self.set_seed(seed); + let a = self.next_long(); + let b = self.next_long(); + self.set_seed((x as i64).wrapping_mul(a) ^ (z as i64).wrapping_mul(b) ^ seed); + } + pub fn set_large_feature_with_salt(&mut self, seed: i64, x: i32, z: i32, salt: i32) { + self.set_seed( + (x as i64) + .wrapping_mul(341873128712) + .wrapping_add((z as i64).wrapping_mul(132897987541)) + .wrapping_add(seed) + .wrapping_add(salt as i64), + ); + } +} +impl sealed::Sealed for WorldgenRandom {} +impl WorldgenSource for WorldgenRandom { + fn worldgen_bits(&mut self, count: i32) -> i32 { + self.next_bits(count) + } +} +impl RandomSource for WorldgenRandom { + type Positional = WorldgenPositional; + fn set_seed(&mut self, seed: i64) { + self.source.set_seed(seed); + } + fn next_int(&mut self) -> i32 { + if self.wrapped { + self.next_bits(32) + } else { + self.source.next_int() + } + } + fn next_int_bound(&mut self, bound: i32) -> Result { + if !self.wrapped { + return self.source.next_int_bound(bound); + } + if bound <= 0 { + return Err(InvalidBound); + } + if bound & (bound - 1) == 0 { + return Ok(((bound as i64 * self.next_bits(31) as i64) >> 31) as i32); + } + loop { + let bits = self.next_bits(31); + let value = bits % bound; + if bits.wrapping_sub(value).wrapping_add(bound - 1) >= 0 { + return Ok(value); + } + } + } + fn next_long(&mut self) -> i64 { + if !self.wrapped { + return self.source.next_long(); + } + let high = (self.next_bits(32) as i64) << 32; + high.wrapping_add(self.next_bits(32) as i64) + } + fn next_boolean(&mut self) -> bool { + if self.wrapped { + self.next_bits(1) != 0 + } else { + self.source.next_boolean() + } + } + fn next_float(&mut self) -> f32 { + if self.wrapped { + self.next_bits(24) as f32 * (1.0 / 16777216.0) + } else { + self.source.next_float() + } + } + fn next_double(&mut self) -> f64 { + if !self.wrapped { + return self.source.next_double(); + } + let bits = ((self.next_bits(26) as i64) << 27) + self.next_bits(27) as i64; + bits as f64 * (1.0 / 9007199254740992.0) + } + /// Native forks return the underlying source, not another bit adapter. + /// The returned value keeps that behavior through a transparent variant. + fn fork(&mut self) -> Self { + Self::plain(self.source.fork()) + } + fn fork_positional(&mut self) -> Self::Positional { + WorldgenPositional(self.source.fork_positional()) + } +} +#[derive(Clone, Debug)] +pub struct WorldgenPositional(P); +impl PositionalRandom for WorldgenPositional

+where + P::Source: WorldgenSource, +{ + type Source = WorldgenRandom; + fn at(&self, position: BlockPos) -> Self::Source { + WorldgenRandom::plain(self.0.at(position)) + } + fn from_seed(&self, seed: i64) -> Self::Source { + WorldgenRandom::plain(self.0.from_seed(seed)) + } + fn from_hash_of(&self, name: &str) -> Self::Source { + WorldgenRandom::plain(self.0.from_hash_of(name)) + } + fn from_hash_of_utf16(&self, name: &[u16]) -> Self::Source { + WorldgenRandom::plain(self.0.from_hash_of_utf16(name)) + } +} +pub fn slime_chunk_random(x: i32, z: i32, seed: i64, salt: i64) -> LegacyRandom { + let mixed = seed + .wrapping_add(x.wrapping_mul(x).wrapping_mul(4987142) as i64) + .wrapping_add(x.wrapping_mul(5947611) as i64) + .wrapping_add((z.wrapping_mul(z) as i64).wrapping_mul(4392871)) + .wrapping_add(z.wrapping_mul(389711) as i64) + ^ salt; + LegacyRandom::new(mixed) +} diff --git a/crates/horizon-core/src/storage.rs b/crates/horizon-core/src/storage.rs new file mode 100644 index 000000000..61f8c505f --- /dev/null +++ b/crates/horizon-core/src/storage.rs @@ -0,0 +1,172 @@ +//! Palette indices packed into padded 64-bit words, not a continuous bitstream. + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum StorageError { + InvalidBits(u8), + InvalidLength { expected: usize, actual: usize }, + OutOfBounds { index: usize, len: usize }, + ValueTooLarge(u32), +} + +impl std::fmt::Display for StorageError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{self:?}") + } +} + +impl std::error::Error for StorageError {} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PackedStorage { + bits: u8, + len: usize, + per_word: usize, + mask: u64, + words: Vec, +} + +impl PackedStorage { + pub fn new(bits: u8, len: usize) -> Result { + let per_word = Self::per_word(bits)?; + Self::from_words(bits, len, vec![0; len.div_ceil(per_word)]) + } + + /// Retains padding and unused tail bits from input, as the Java long[] does. + pub fn from_words(bits: u8, len: usize, words: Vec) -> Result { + let per_word = Self::per_word(bits)?; + let expected = len.div_ceil(per_word); + if words.len() != expected { + return Err(StorageError::InvalidLength { + expected, + actual: words.len(), + }); + } + Ok(Self { + bits, + len, + per_word, + mask: (1_u64 << bits) - 1, + words, + }) + } + + fn per_word(bits: u8) -> Result { + if !(1..=32).contains(&bits) { + return Err(StorageError::InvalidBits(bits)); + } + Ok(64 / usize::from(bits)) + } + + pub fn bits(&self) -> u8 { + self.bits + } + pub fn len(&self) -> usize { + self.len + } + pub fn is_empty(&self) -> bool { + self.len == 0 + } + pub fn words(&self) -> &[u64] { + &self.words + } + + fn location(&self, index: usize) -> Result<(usize, usize), StorageError> { + if index >= self.len { + return Err(StorageError::OutOfBounds { + index, + len: self.len, + }); + } + Ok(( + index / self.per_word, + (index % self.per_word) * usize::from(self.bits), + )) + } + + pub fn get(&self, index: usize) -> Result { + let (word, shift) = self.location(index)?; + Ok(((self.words[word] >> shift) & self.mask) as u32) + } + + /// Validation fails before mutation. Writes accept nonnegative Java ints; + /// imported 32-bit words may still decode to any u32 bit pattern. + pub fn set(&mut self, index: usize, value: u32) -> Result { + let (word, shift) = self.location(index)?; + if u64::from(value) > self.mask || value > i32::MAX as u32 { + return Err(StorageError::ValueTooLarge(value)); + } + let old = ((self.words[word] >> shift) & self.mask) as u32; + self.words[word] = (self.words[word] & !(self.mask << shift)) | (u64::from(value) << shift); + Ok(old) + } + + /// Vanilla's doubling fill also writes padding and unused tail slots. + pub fn fill(&mut self, value: u32) -> Result<(), StorageError> { + if u64::from(value) > self.mask || value > i32::MAX as u32 { + return Err(StorageError::ValueTooLarge(value)); + } + let mut word = u64::from(value); + let mut shift = u32::from(self.bits); + while shift < 64 { + word |= word << shift; + shift *= 2; + } + self.words.fill(word); + Ok(()) + } + + pub fn unpack(&self) -> Vec { + let mut values = Vec::with_capacity(self.len); + for &word in &self.words { + for slot in 0..self.per_word.min(self.len - values.len()) { + values.push(((word >> (slot * usize::from(self.bits))) & self.mask) as u32); + } + } + values + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn padded_words_never_split_entries() { + let mut storage = PackedStorage::new(5, 13).unwrap(); + assert_eq!(storage.words().len(), 2); + storage.set(11, 31).unwrap(); + storage.set(12, 7).unwrap(); + assert_eq!(storage.words(), &[31 << 55, 7]); + } + + #[test] + fn all_widths_survive_overwrites_and_unpack() { + for bits in 1..=32 { + let mut storage = PackedStorage::new(bits, 4096).unwrap(); + let mut expected = vec![0; 4096]; + for pass in 0..3 { + for (i, item) in expected.iter_mut().enumerate() { + let value = ((i as u64 * 7 + pass) & storage.mask) as u32; + assert_eq!(storage.set(i, value).unwrap(), *item); + *item = value; + } + assert_eq!(storage.unpack(), expected); + } + } + } + + #[test] + fn imported_padding_is_preserved_and_invalid_writes_are_atomic() { + let mut storage = PackedStorage::from_words(5, 1, vec![u64::MAX]).unwrap(); + assert_eq!(storage.set(0, 0).unwrap(), 31); + assert_eq!(storage.words(), &[u64::MAX << 5]); + let unchanged = storage.clone(); + assert!(storage.set(1, 0).is_err()); + assert!(storage.set(0, 32).is_err()); + assert_eq!(storage, unchanged); + assert!(PackedStorage::new(0, 1).is_err()); + assert!(PackedStorage::new(33, 1).is_err()); + assert!(PackedStorage::from_words(5, 13, vec![0]).is_err()); + assert!(PackedStorage::new(1, 0).unwrap().unpack().is_empty()); + } +} diff --git a/crates/horizon-core/src/ticks/heap.rs b/crates/horizon-core/src/ticks/heap.rs new file mode 100644 index 000000000..262105392 --- /dev/null +++ b/crates/horizon-core/src/ticks/heap.rs @@ -0,0 +1,101 @@ +//! Array heap with the pinned JDK PriorityQueue's equal-key and iterator-removal +//! behavior. Equal comparator keys are observable in saved and loaded ticks. +use std::{cmp::Ordering, collections::VecDeque}; + +#[derive(Clone, Debug)] +pub(super) struct Heap { + pub(super) values: Vec, +} +impl Default for Heap { + fn default() -> Self { + Self { values: Vec::new() } + } +} +impl Heap { + pub(super) fn peek(&self) -> Option { + self.values.first().copied() + } + pub(super) fn push(&mut self, value: T, compare: impl Fn(T, T) -> Ordering) { + self.values.push(value); + self.up(self.values.len() - 1, value, &compare); + } + fn up(&mut self, mut index: usize, value: T, compare: &impl Fn(T, T) -> Ordering) -> usize { + while index > 0 { + let parent = (index - 1) / 2; + if compare(value, self.values[parent]) != Ordering::Less { + break; + } + self.values[index] = self.values[parent]; + index = parent; + } + self.values[index] = value; + index + } + fn down(&mut self, mut index: usize, value: T, compare: &impl Fn(T, T) -> Ordering) -> usize { + let half = self.values.len() / 2; + while index < half { + let mut child = index * 2 + 1; + let right = child + 1; + if right < self.values.len() + && compare(self.values[child], self.values[right]) == Ordering::Greater + { + child = right; + } + if compare(value, self.values[child]) != Ordering::Greater { + break; + } + self.values[index] = self.values[child]; + index = child; + } + self.values[index] = value; + index + } + pub(super) fn pop(&mut self, compare: impl Fn(T, T) -> Ordering) -> Option { + let first = self.peek()?; + let last = self.values.pop().unwrap(); + if !self.values.is_empty() { + self.down(0, last, &compare); + } + Some(first) + } + fn remove_at(&mut self, index: usize, compare: &impl Fn(T, T) -> Ordering) -> Option { + let last = self.values.pop().unwrap(); + if index == self.values.len() { + return None; + } + if self.down(index, last, compare) == index && self.up(index, last, compare) != index { + Some(last) + } else { + None + } + } + pub(super) fn remove_if( + &mut self, + mut predicate: impl FnMut(T) -> bool, + compare: impl Fn(T, T) -> Ordering, + ) { + let mut cursor = 0; + let mut moved = VecDeque::new(); + while cursor < self.values.len() { + let value = self.values[cursor]; + cursor += 1; + if predicate(value) { + if let Some(value) = self.remove_at(cursor - 1, &compare) { + moved.push_back(value); + } else { + cursor -= 1; + } + } + } + while let Some(value) = moved.pop_front() { + if predicate(value) { + let index = self + .values + .iter() + .position(|&candidate| candidate == value) + .unwrap(); + self.remove_at(index, &compare); + } + } + } +} diff --git a/crates/horizon-core/src/ticks/index.rs b/crates/horizon-core/src/ticks/index.rs new file mode 100644 index 000000000..6f88cf701 --- /dev/null +++ b/crates/horizon-core/src/ticks/index.rs @@ -0,0 +1,159 @@ +//! Deadline index whose traversal matches the pinned fastutil long map. Heap +//! insertion order decides exact ties between chunk heads after save loading. +#[derive(Clone, Debug)] +pub(super) struct DeadlineIndex { + keys: Vec, + values: Vec, + zero: bool, + size: usize, +} +fn mix(key: i64) -> usize { + let mut value = (key as u64).wrapping_mul(0x9e3779b97f4a7c15); + value ^= value >> 32; + (value ^ (value >> 16)) as usize +} +impl Default for DeadlineIndex { + fn default() -> Self { + Self { + keys: vec![0; 33], + values: vec![0; 33], + zero: false, + size: 0, + } + } +} +impl DeadlineIndex { + fn capacity(&self) -> usize { + self.keys.len() - 1 + } + fn find(&self, key: i64) -> usize { + if key == 0 { + return self.capacity(); + } + let mask = self.capacity() - 1; + let mut slot = mix(key) & mask; + while self.keys[slot] != 0 && self.keys[slot] != key { + slot = (slot + 1) & mask; + } + slot + } + pub(super) fn put(&mut self, key: i64, value: i64) { + let slot = self.find(key); + let exists = if key == 0 { + self.zero + } else { + self.keys[slot] != 0 + }; + self.values[slot] = value; + if exists { + return; + } + self.keys[slot] = key; + if key == 0 { + self.zero = true; + } + let old_size = self.size; + self.size += 1; + if old_size >= self.capacity() * 3 / 4 { + self.rehash(self.capacity() * 2); + } + } + fn rehash(&mut self, capacity: usize) { + let old_keys = std::mem::replace(&mut self.keys, vec![0; capacity + 1]); + let old_values = std::mem::replace(&mut self.values, vec![0; capacity + 1]); + for slot in (0..old_keys.len() - 1).rev() { + if old_keys[slot] == 0 { + continue; + } + let destination = self.find(old_keys[slot]); + self.keys[destination] = old_keys[slot]; + self.values[destination] = old_values[slot]; + } + self.values[capacity] = *old_values.last().unwrap(); + } + fn shift_keys(&mut self, mut hole: usize, wrapped: &mut Vec) { + let mask = self.capacity() - 1; + loop { + let mut slot = (hole + 1) & mask; + loop { + let key = self.keys[slot]; + if key == 0 { + self.keys[hole] = 0; + return; + } + let home = mix(key) & mask; + let crosses = if hole <= slot { + hole >= home || home > slot + } else { + hole >= home && home > slot + }; + if crosses { + break; + } + slot = (slot + 1) & mask; + } + if slot < hole { + wrapped.push(self.keys[slot]); + } + self.keys[hole] = self.keys[slot]; + self.values[hole] = self.values[slot]; + hole = slot; + } + } + pub(super) fn remove(&mut self, key: i64) { + let slot = self.find(key); + if key == 0 { + if !self.zero { + return; + } + self.zero = false; + } else { + if self.keys[slot] == 0 { + return; + } + self.shift_keys(slot, &mut Vec::new()); + } + self.size -= 1; + if self.capacity() > 32 && self.size < self.capacity() * 3 / 16 { + self.rehash(self.capacity() / 2); + } + } + /// Visit in vanilla iterator order. The callback updates the deadline and + /// returns true to remove the entry. Regular iterator removal does not shrink. + pub(super) fn visit(&mut self, mut action: impl FnMut(i64, &mut i64) -> bool) { + let mut remaining = self.size; + let mut position = self.capacity() as isize; + let mut wrapped = Vec::new(); + let mut zero = self.zero; + while remaining > 0 { + remaining -= 1; + let slot = if zero { + zero = false; + self.capacity() + } else { + loop { + position -= 1; + if position < 0 { + break self.find(wrapped[(-position - 1) as usize]); + } + if self.keys[position as usize] != 0 { + break position as usize; + } + } + }; + let key = self.keys[slot]; + if !action(key, &mut self.values[slot]) { + continue; + } + if slot == self.capacity() { + self.zero = false; + self.size -= 1; + } else if position >= 0 { + self.shift_keys(slot, &mut wrapped); + self.size -= 1; + } else { + self.remove(key); + } + } + } +} diff --git a/crates/horizon-core/src/ticks/mod.rs b/crates/horizon-core/src/ticks/mod.rs new file mode 100644 index 000000000..38fcef4db --- /dev/null +++ b/crates/horizon-core/src/ticks/mod.rs @@ -0,0 +1,638 @@ +//! Scheduled block/fluid tick machinery for Java Edition 26.3. Type IDs identify +//! registry-owned types; each block/fluid registry uses its own LevelTicks. +mod heap; +mod index; +use crate::position::{BlockPos, ChunkPos}; +use heap::Heap; +use index::DeadlineIndex; +use std::{ + cmp::Ordering, + collections::{HashMap, HashSet, VecDeque}, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct TickTypeId(pub u32); + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +#[repr(i8)] +pub enum TickPriority { + ExtremelyHigh = -3, + VeryHigh = -2, + High = -1, + #[default] + Normal = 0, + Low = 1, + VeryLow = 2, + ExtremelyLow = 3, +} +impl TickPriority { + pub const fn by_value(value: i32) -> Self { + match value { + i32::MIN..=-3 => Self::ExtremelyHigh, + -2 => Self::VeryHigh, + -1 => Self::High, + 0 => Self::Normal, + 1 => Self::Low, + 2 => Self::VeryLow, + 3..=i32::MAX => Self::ExtremelyLow, + } + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ScheduledTick { + pub kind: TickTypeId, + pub pos: BlockPos, + pub trigger_tick: i64, + pub priority: TickPriority, + pub sub_tick_order: i64, +} +impl ScheduledTick { + pub fn drain_cmp(self, other: Self) -> Ordering { + self.trigger_tick + .cmp(&other.trigger_tick) + .then_with(|| self.intra_cmp(other)) + } + pub fn intra_cmp(self, other: Self) -> Ordering { + self.priority + .cmp(&other.priority) + .then_with(|| self.sub_tick_order.cmp(&other.sub_tick_order)) + } + pub fn saved(self, game_time: i64) -> SavedTick { + SavedTick { + kind: self.kind, + pos: self.pos, + delay: self.trigger_tick.wrapping_sub(game_time) as i32, + priority: self.priority, + } + } + fn key(self) -> (TickTypeId, BlockPos) { + (self.kind, self.pos) + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SavedTick { + pub kind: TickTypeId, + pub pos: BlockPos, + pub delay: i32, + pub priority: TickPriority, +} +impl SavedTick { + pub fn unpack(self, game_time: i64, sub_tick_order: i64) -> ScheduledTick { + ScheduledTick { + kind: self.kind, + pos: self.pos, + trigger_tick: game_time.wrapping_add(i64::from(self.delay)), + priority: self.priority, + sub_tick_order, + } + } +} + +#[derive(Clone, Debug, Default)] +pub struct ChunkTicks { + queue: Heap, + pending: Option>, + positions: HashSet<(TickTypeId, BlockPos)>, +} +impl ChunkTicks { + pub fn from_saved(ticks: Vec) -> Self { + Self { + positions: ticks.iter().map(|t| (t.kind, t.pos)).collect(), + pending: Some(ticks), + ..Self::default() + } + } + pub fn peek(&self) -> Option { + self.queue.peek() + } + pub fn poll(&mut self) -> Option { + let tick = self.queue.pop(ScheduledTick::drain_cmp)?; + self.positions.remove(&tick.key()); + Some(tick) + } + /// First schedule wins for a type/position, irrespective of timing/priority. + pub fn schedule(&mut self, tick: ScheduledTick) -> bool { + if !self.positions.insert(tick.key()) { + return false; + } + self.queue.push(tick, ScheduledTick::drain_cmp); + true + } + pub fn has_scheduled(&self, pos: BlockPos, kind: TickTypeId) -> bool { + self.positions.contains(&(kind, pos)) + } + pub fn count(&self) -> usize { + self.queue.values.len() + self.pending.as_ref().map_or(0, Vec::len) + } + /// Heap traversal order, as exposed by vanilla getAll, rather than sorted order. + pub fn queued(&self) -> &[ScheduledTick] { + &self.queue.values + } + pub fn remove_if(&mut self, mut predicate: impl FnMut(ScheduledTick) -> bool) { + self.queue.remove_if( + |tick| { + if !predicate(tick) { + return false; + } + self.positions.remove(&tick.key()); + true + }, + ScheduledTick::drain_cmp, + ); + } + pub fn pack(&self, game_time: i64) -> Vec { + let mut saved = self.pending.clone().unwrap_or_default(); + let mut queued = self.queue.values.clone(); + queued.sort_by_key(|t| t.sub_tick_order); + saved.extend(queued.into_iter().map(|t| t.saved(game_time))); + saved + } + pub fn unpack(&mut self, game_time: i64) { + if let Some(pending) = self.pending.take() { + let mut order = (pending.len() as i32).wrapping_neg() as i64; + for saved in pending { + // Vanilla does not deduplicate a saved list during unpack. + self.queue + .push(saved.unpack(game_time, order), ScheduledTick::drain_cmp); + order = order.wrapping_add(1); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn tick(kind: u32, x: i32, time: i64, priority: i32, order: i64) -> ScheduledTick { + ScheduledTick { + kind: TickTypeId(kind), + pos: BlockPos::new(x, 64, 0), + trigger_tick: time, + priority: TickPriority::by_value(priority), + sub_tick_order: order, + } + } + fn level() -> LevelTicks { + let mut level = LevelTicks::default(); + for x in -1..=2 { + level + .add_chunk(ChunkPos::new(x, 0), ChunkTicks::default()) + .unwrap(); + } + level + } + #[test] + fn due_chunks_compete_by_priority_not_trigger_time() { + let mut level = level(); + for tick in [ + tick(0, 0, 1, 3, 10), + tick(1, 1, 2, -3, 11), + tick(2, 16, 3, 0, 12), + ] { + assert_eq!(level.schedule(tick), ScheduleResult::Added); + } + assert_eq!( + level.schedule(tick(0, 0, -100, -3, -10)), + ScheduleResult::Duplicate + ); + let mut ran = Vec::new(); + level + .tick(10, 10, |_| true, |_, tick| ran.push(tick.kind.0)) + .unwrap(); + assert_eq!(ran, [2, 0, 1]); + assert_eq!(level.count(), 0); + } + #[test] + fn callback_scheduling_waits_until_the_next_collection() { + let mut level = level(); + let original = tick(0, 0, 0, 0, 0); + level.schedule(original); + let mut ran = 0; + level + .tick( + 0, + 100, + |_| true, + |level, tick| { + ran += 1; + assert!(!level.will_tick_this_tick(tick.pos, tick.kind)); + assert_eq!(level.schedule(tick), ScheduleResult::Added); + assert!(level.has_scheduled(tick.pos, tick.kind)); + }, + ) + .unwrap(); + assert_eq!(ran, 1); + assert_eq!(level.count(), 1); + level.tick(0, 100, |_| true, |_, _| ran += 1).unwrap(); + assert_eq!(ran, 2); + assert_eq!(level.count(), 0); + } + #[test] + fn pending_ticks_keep_list_order_and_java_time_overflow() { + let a = tick(0, 0, i64::MAX, -9, 10).saved(i64::MIN); + assert_eq!(a.delay, -1); + let b = SavedTick { + delay: 1, + kind: TickTypeId(1), + ..a + }; + let mut chunk = ChunkTicks::from_saved(vec![a, b, a]); + assert_eq!(chunk.count(), 3); + assert!(chunk.peek().is_none()); + assert!(!chunk.schedule(tick(0, 0, 100, 0, 0))); + chunk.unpack(i64::MAX); + assert_eq!(chunk.count(), 3); + assert_eq!(chunk.poll().unwrap().trigger_tick, i64::MIN); + assert_eq!(chunk.poll().unwrap().sub_tick_order, -3); + assert_eq!(chunk.poll().unwrap().sub_tick_order, -1); + chunk.unpack(0); + assert_eq!(chunk.count(), 0); + } + #[test] + fn disabled_and_removed_chunks_retain_their_queue() { + let mut level = level(); + level.schedule(tick(0, 0, 0, 0, 0)); + level + .tick(10, 10, |_| false, |_, _| panic!("disabled chunk ran")) + .unwrap(); + let chunk = level.remove_chunk(ChunkPos::new(0, 0)).unwrap(); + assert_eq!(chunk.count(), 1); + assert_eq!( + level.schedule(tick(1, 0, 0, 0, 0)), + ScheduleResult::MissingChunk + ); + level.add_chunk(ChunkPos::new(0, 0), chunk).unwrap(); + let mut ran = Vec::new(); + level + .tick(10, 1, |_| true, |_, tick| ran.push(tick)) + .unwrap(); + assert_eq!(ran, [tick(0, 0, 0, 0, 0)]); + } + #[test] + fn collection_guards_and_membership_survive_area_mutation() { + let mut level = level(); + level.schedule(tick(0, 0, 0, 0, 0)); + level.schedule(tick(1, 1, 0, 0, 1)); + level.begin_tick(0, 10, |_| true).unwrap(); + assert_eq!( + level.begin_tick(0, 10, |_| true), + Err(TickError::AlreadyCollecting) + ); + assert_eq!(level.finish_tick(), Err(TickError::TicksRemain)); + assert_eq!(level.next_tick().unwrap().unwrap().kind, TickTypeId(0)); + let probe = BlockPos::new(1, 64, 0); + assert!(level.will_tick_this_tick(probe, TickTypeId(1))); + level.clear_area(TickArea::new(probe, probe)); + // Preserve vanilla's stale lazily built set until cleanup. + assert!(level.will_tick_this_tick(probe, TickTypeId(1))); + assert!(level.next_tick().unwrap().is_none()); + level.finish_tick().unwrap(); + assert!(!level.will_tick_this_tick(probe, TickTypeId(1))); + assert_eq!(level.next_tick(), Err(TickError::NotCollecting)); + } + #[test] + fn copying_active_ticks_preserves_relative_order_and_wraps() { + let mut level = level(); + level.schedule(tick(0, 0, 0, 0, i64::MAX - 1)); + level.schedule(tick(1, 1, 0, 0, i64::MAX)); + level.begin_tick(0, 10, |_| true).unwrap(); + level.next_tick().unwrap(); + level.copy_area( + TickArea::new(BlockPos::new(0, 64, 0), BlockPos::new(1, 64, 0)), + BlockPos::new(16, 0, 0), + ); + let copied = level.chunk(ChunkPos::new(1, 0)).unwrap().queued(); + assert_eq!(copied.len(), 2); + assert_eq!(copied[0].sub_tick_order, i64::MIN); + assert_eq!(copied[1].sub_tick_order, i64::MIN + 1); + while level.next_tick().unwrap().is_some() {} + level.finish_tick().unwrap(); + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TickArea { + pub min: BlockPos, + pub max: BlockPos, +} +impl TickArea { + pub fn new(a: BlockPos, b: BlockPos) -> Self { + Self { + min: BlockPos::new(a.x.min(b.x), a.y.min(b.y), a.z.min(b.z)), + max: BlockPos::new(a.x.max(b.x), a.y.max(b.y), a.z.max(b.z)), + } + } + pub fn contains(self, pos: BlockPos) -> bool { + (self.min.x..=self.max.x).contains(&pos.x) + && (self.min.y..=self.max.y).contains(&pos.y) + && (self.min.z..=self.max.z).contains(&pos.z) + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ScheduleResult { + Added, + Duplicate, + MissingChunk, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TickError { + AlreadyCollecting, + NotCollecting, + TicksRemain, + ChunkAlreadyAdded, + WrongChunk, +} +impl std::fmt::Display for TickError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "scheduled tick invariant: {self:?}") + } +} +impl std::error::Error for TickError {} + +#[derive(Default)] +pub struct LevelTicks { + chunks: HashMap, + deadlines: DeadlineIndex, + containers_to_tick: Heap, + to_run: VecDeque, + already_run: Vec, + to_run_set: HashSet<(TickTypeId, BlockPos)>, + collecting: bool, +} +impl LevelTicks { + pub fn add_chunk(&mut self, pos: ChunkPos, ticks: ChunkTicks) -> Result<(), TickError> { + let key = pos.pack(); + if self.chunks.contains_key(&key) { + return Err(TickError::ChunkAlreadyAdded); + } + if ticks.queue.values.iter().any(|t| t.pos.chunk() != pos) + || ticks + .pending + .as_ref() + .is_some_and(|p| p.iter().any(|t| t.pos.chunk() != pos)) + { + return Err(TickError::WrongChunk); + } + if let Some(tick) = ticks.peek() { + self.deadlines.put(key, tick.trigger_tick); + } + self.chunks.insert(key, ticks); + Ok(()) + } + pub fn remove_chunk(&mut self, pos: ChunkPos) -> Option { + self.deadlines.remove(pos.pack()); + self.chunks.remove(&pos.pack()) + } + pub fn chunk(&self, pos: ChunkPos) -> Option<&ChunkTicks> { + self.chunks.get(&pos.pack()) + } + pub fn unpack_chunk(&mut self, pos: ChunkPos, game_time: i64) { + if let Some(chunk) = self.chunks.get_mut(&pos.pack()) { + chunk.unpack(game_time); + if let Some(tick) = chunk.peek() { + self.deadlines.put(pos.pack(), tick.trigger_tick); + } + } + } + pub fn schedule(&mut self, tick: ScheduledTick) -> ScheduleResult { + let key = tick.pos.chunk().pack(); + let Some(chunk) = self.chunks.get_mut(&key) else { + return ScheduleResult::MissingChunk; + }; + if !chunk.schedule(tick) { + return ScheduleResult::Duplicate; + } + if chunk.peek() == Some(tick) { + self.deadlines.put(key, tick.trigger_tick); + } + ScheduleResult::Added + } + pub fn has_scheduled(&self, pos: BlockPos, kind: TickTypeId) -> bool { + self.chunk(pos.chunk()) + .is_some_and(|c| c.has_scheduled(pos, kind)) + } + pub fn will_tick_this_tick(&mut self, pos: BlockPos, kind: TickTypeId) -> bool { + if self.to_run_set.is_empty() && !self.to_run.is_empty() { + self.to_run_set.extend(self.to_run.iter().map(|t| t.key())); + } + self.to_run_set.contains(&(kind, pos)) + } + pub fn count(&self) -> usize { + self.chunks.values().map(ChunkTicks::count).sum() + } + pub fn begin_tick( + &mut self, + game_time: i64, + maximum: i32, + mut can_tick: impl FnMut(ChunkPos) -> bool, + ) -> Result<(), TickError> { + if self.collecting { + return Err(TickError::AlreadyCollecting); + } + self.collecting = true; + let mut containers = std::mem::take(&mut self.containers_to_tick); + let chunks = &mut self.chunks; + let compare = |a: i64, b: i64| { + chunks[&a] + .peek() + .unwrap() + .intra_cmp(chunks[&b].peek().unwrap()) + }; + self.deadlines.visit(|key, deadline| { + if *deadline > game_time { + return false; + } + let Some(head) = chunks.get(&key).and_then(ChunkTicks::peek) else { + return true; + }; + if head.trigger_tick > game_time { + *deadline = head.trigger_tick; + return false; + } + if !can_tick(ChunkPos::unpack(key)) { + return false; + } + containers.push(key, compare); + true + }); + let maximum = maximum.max(0) as usize; + while self.to_run.len() < maximum { + let Some(key) = containers.pop(|a, b| { + self.chunks[&a] + .peek() + .unwrap() + .intra_cmp(self.chunks[&b].peek().unwrap()) + }) else { + break; + }; + let chunk = self.chunks.get_mut(&key).unwrap(); + self.to_run.push_back(chunk.poll().unwrap()); + let competing = containers.peek().and_then(|key| self.chunks[&key].peek()); + let chunk = self.chunks.get_mut(&key).unwrap(); + while self.to_run.len() < maximum { + let Some(head) = chunk.peek() else { + break; + }; + if head.trigger_tick > game_time + || competing.is_some_and(|other| head.intra_cmp(other) == Ordering::Greater) + { + break; + } + self.to_run.push_back(chunk.poll().unwrap()); + } + if let Some(head) = chunk.peek() { + if head.trigger_tick <= game_time && self.to_run.len() < maximum { + containers.push(key, |a, b| { + self.chunks[&a] + .peek() + .unwrap() + .intra_cmp(self.chunks[&b].peek().unwrap()) + }); + } else { + self.deadlines.put(key, head.trigger_tick); + } + } + } + for &key in &containers.values { + self.deadlines + .put(key, self.chunks[&key].peek().unwrap().trigger_tick); + } + containers.values.clear(); + self.containers_to_tick = containers; + Ok(()) + } + /// Pop immediately before invoking block/fluid behavior. The current tick is + /// already-run, absent from will_tick, and available to area copying. + pub fn next_tick(&mut self) -> Result, TickError> { + if !self.collecting { + return Err(TickError::NotCollecting); + } + let Some(tick) = self.to_run.pop_front() else { + return Ok(None); + }; + if !self.to_run_set.is_empty() { + self.to_run_set.remove(&tick.key()); + } + self.already_run.push(tick); + Ok(Some(tick)) + } + pub fn finish_tick(&mut self) -> Result<(), TickError> { + if !self.collecting { + return Err(TickError::NotCollecting); + } + if !self.to_run.is_empty() { + return Err(TickError::TicksRemain); + } + self.already_run.clear(); + self.to_run_set.clear(); + self.collecting = false; + Ok(()) + } + pub fn tick( + &mut self, + game_time: i64, + maximum: i32, + can_tick: impl FnMut(ChunkPos) -> bool, + mut run: impl FnMut(&mut Self, ScheduledTick), + ) -> Result<(), TickError> { + self.begin_tick(game_time, maximum, can_tick)?; + while let Some(tick) = self.next_tick()? { + run(self, tick); + } + self.finish_tick() + } + fn chunks_in_area(&self, area: TickArea) -> Vec { + let min = area.min.chunk(); + let max = area.max.chunk(); + if min.x > max.x || min.z > max.z { + return Vec::new(); + } + let width = (i64::from(max.x) - i64::from(min.x) + 1) as u64; + let depth = (i64::from(max.z) - i64::from(min.z) + 1) as u64; + // Small edits should probe their grid rather than scan every loaded chunk. + // Large empty areas should visit loaded chunks rather than the empty grid. + if width * depth <= self.chunks.len() as u64 { + let mut keys = Vec::new(); + for x in min.x..=max.x { + for z in min.z..=max.z { + let key = ChunkPos::new(x, z).pack(); + if self.chunks.contains_key(&key) { + keys.push(key); + } + } + } + return keys; + } + let mut keys: Vec<_> = self + .chunks + .keys() + .copied() + .filter(|key| { + let pos = ChunkPos::unpack(*key); + (min.x..=max.x).contains(&pos.x) && (min.z..=max.z).contains(&pos.z) + }) + .collect(); + keys.sort_by_key(|key| { + let p = ChunkPos::unpack(*key); + (p.x, p.z) + }); + keys + } + pub fn clear_area(&mut self, area: TickArea) { + for key in self.chunks_in_area(area) { + let chunk = self.chunks.get_mut(&key).unwrap(); + let old = chunk.peek(); + chunk.remove_if(|tick| area.contains(tick.pos)); + if chunk.peek() != old { + if let Some(tick) = chunk.peek() { + self.deadlines.put(key, tick.trigger_tick); + } else { + self.deadlines.remove(key); + } + } + } + self.already_run.retain(|tick| !area.contains(tick.pos)); + self.to_run.retain(|tick| !area.contains(tick.pos)); + // Vanilla clearArea leaves its lazily computed membership set intact. + } + fn area_ticks(&self, area: TickArea) -> Vec { + let mut ticks: Vec<_> = self + .already_run + .iter() + .chain(self.to_run.iter()) + .copied() + .filter(|t| area.contains(t.pos)) + .collect(); + for key in self.chunks_in_area(area) { + ticks.extend( + self.chunks[&key] + .queued() + .iter() + .copied() + .filter(|t| area.contains(t.pos)), + ); + } + ticks + } + fn schedule_copy(&mut self, ticks: Vec, offset: BlockPos) { + let Some(min) = ticks.iter().map(|t| t.sub_tick_order).min() else { + return; + }; + let max = ticks.iter().map(|t| t.sub_tick_order).max().unwrap(); + for mut tick in ticks { + tick.pos = tick.pos.offset(offset.x, offset.y, offset.z); + tick.sub_tick_order = tick + .sub_tick_order + .wrapping_sub(min) + .wrapping_add(max) + .wrapping_add(1); + self.schedule(tick); + } + } + pub fn copy_area(&mut self, area: TickArea, offset: BlockPos) { + self.schedule_copy(self.area_ticks(area), offset); + } + pub fn copy_area_from(&mut self, source: &Self, area: TickArea, offset: BlockPos) { + self.schedule_copy(source.area_ticks(area), offset); + } +} diff --git a/crates/horizon-core/tests/carving_bounds.rs b/crates/horizon-core/tests/carving_bounds.rs new file mode 100644 index 000000000..0eae83caa --- /dev/null +++ b/crates/horizon-core/tests/carving_bounds.rs @@ -0,0 +1,58 @@ +use horizon_core::carving::{CarvingMask, CarvingMaskError}; + +#[test] +fn invalid_bounds_and_growth_fail_without_changing_existing_cells() { + for (min, max) in [(0, -1), (0, 4064), (i32::MIN, i32::MAX)] { + assert!(matches!( + CarvingMask::new(min, max), + Err(CarvingMaskError::InvalidBounds) + )); + } + let mut mask = CarvingMask::new(-64, 319).unwrap(); + mask.carve(0, -64, 0).unwrap(); + mask.carve(15, 319, 15).unwrap(); + let previous: Vec<_> = mask.columns().collect(); + assert_eq!(mask.carve(0, -65, 0), Err(CarvingMaskError::NegativeIndex)); + assert_eq!( + mask.carve(0, (1 << 24) - 64, 0), + Err(CarvingMaskError::Capacity) + ); + assert_eq!(mask.columns().collect::>(), previous); +} + +#[test] +fn shared_candidate_budget_counts_skipped_cells_and_stops_before_the_next_callback() { + use horizon_core::{ + carving::{CarveError, carve_ellipsoid_with_budget}, + position::ChunkPos, + }; + let mut mask = CarvingMask::new(0, 15).unwrap(); + let mut remaining = 2; + let mut calls = 0; + let result = carve_ellipsoid_with_budget( + ChunkPos::new(0, 0), + [8., 8., 8.], + 4., + 4., + &mut mask, + |_, _| { + calls += 1; + true + }, + &mut remaining, + ); + assert_eq!(result, Err(CarveError::IterationLimit)); + assert_eq!(calls, 2); + assert_eq!(remaining, 0); + assert!(mask.is_empty()); + let result = carve_ellipsoid_with_budget( + ChunkPos::new(0, 0), + [1000., 8., 1000.], + 1., + 1., + &mut mask, + |_, _| panic!("culled shape queried its predicate"), + &mut remaining, + ); + assert!(result.is_ok()); +} diff --git a/crates/horizon-core/tests/density_world_fields.rs b/crates/horizon-core/tests/density_world_fields.rs new file mode 100644 index 000000000..7bc9ed6dd --- /dev/null +++ b/crates/horizon-core/tests/density_world_fields.rs @@ -0,0 +1,202 @@ +use horizon_core::{ + density::{ + BlendDensitySampler, CachingDensitySampler, ConstantSampler, ContextBoundSampler, + DensityBlender, DensitySampler, SampleError, SamplerContext, WorldField, WorldFields, + graph::{DensityCompiler, DensityGraph, GraphNode}, + }, + noise::DensityVolume, +}; +use std::sync::{Arc, Mutex}; + +#[derive(Debug)] +struct SpatialBlender { + calls: Mutex>>, +} +impl DensityBlender for SpatialBlender { + fn is_empty(&self) -> bool { + self.calls.lock().unwrap().push(None); + false + } + fn blend_density(&self, [x, y, z]: [i32; 3], input: f32) -> f32 { + self.calls.lock().unwrap().push(Some([x, y, z])); + input + (x * 100 + y * 10 + z) as f32 + } +} + +#[test] +fn fields_resolve_through_the_same_context_and_replace_cached_values() { + let alpha: Arc = Arc::new(ContextBoundSampler::new(WorldField::BlendAlpha)); + let beard = ContextBoundSampler::new(WorldField::Beardifier); + let fields = WorldFields::default() + .with_field(WorldField::Beardifier, alpha) + .with_field(WorldField::BlendAlpha, Arc::new(ConstantSampler(0.25))); + let mut context = SamplerContext::cached().with_world_fields(fields); + let cached = CachingDensitySampler::new(0, Arc::new(beard)).unwrap(); + assert_eq!(cached.sample_value(&mut context, [0; 3]).unwrap(), 0.25); + context = context.with_world_fields( + WorldFields::default().with_field(WorldField::Beardifier, Arc::new(ConstantSampler(0.75))), + ); + assert_eq!(cached.sample_value(&mut context, [0; 3]).unwrap(), 0.75); +} + +#[test] +fn absent_fields_use_vanilla_defaults_including_buffer_tails() { + let volume = DensityVolume::new([1; 3], [0; 3], [1; 3]).unwrap(); + let mut context = SamplerContext::default(); + for (field, expected) in [ + (WorldField::BlendAlpha, 1.0), + (WorldField::BlendOffset, 0.0), + (WorldField::Beardifier, 0.0), + ] { + let mut buffer = [9.0; 3]; + ContextBoundSampler::new(field) + .sample_volume(&mut context, &mut buffer, volume) + .unwrap(); + assert_eq!(buffer, [expected; 3]); + } +} + +#[test] +fn blending_visits_z_x_y_and_preserves_the_input_tail() { + let blender = Arc::new(SpatialBlender { + calls: Mutex::new(Vec::new()), + }); + let mut context = SamplerContext::default() + .with_world_fields(WorldFields::default().with_blender(blender.clone())); + let sampler = BlendDensitySampler { + input: Arc::new(ConstantSampler(0.5)), + }; + let volume = DensityVolume::new([2; 3], [1, 2, 3], [2, 3, 4]).unwrap(); + let mut buffer = [9.0; 10]; + sampler + .sample_volume(&mut context, &mut buffer, volume) + .unwrap(); + assert_eq!( + *blender.calls.lock().unwrap(), + vec![ + None, + Some([1, 2, 3]), + Some([1, 5, 3]), + Some([3, 2, 3]), + Some([3, 5, 3]), + Some([1, 2, 7]), + Some([1, 5, 7]), + Some([3, 2, 7]), + Some([3, 5, 7]) + ] + ); + assert_eq!( + buffer, + [ + 123.5, 153.5, 323.5, 353.5, 127.5, 157.5, 327.5, 357.5, 0.5, 0.5 + ] + ); +} + +#[derive(Debug)] +struct FailedInput; +impl DensitySampler for FailedInput { + fn sample_value(&self, _: &mut SamplerContext, _: [i32; 3]) -> Result { + Err(SampleError::ZeroGradientPeriod) + } + fn sample_volume( + &self, + _: &mut SamplerContext, + buffer: &mut [f32], + _: DensityVolume, + ) -> Result<(), SampleError> { + buffer[0] = 0.25; + Err(SampleError::ZeroGradientPeriod) + } +} +#[test] +fn failed_input_prevents_blender_lookup_and_preserves_partial_writes() { + let blender = Arc::new(SpatialBlender { + calls: Mutex::new(Vec::new()), + }); + let mut context = SamplerContext::default() + .with_world_fields(WorldFields::default().with_blender(blender.clone())); + let sampler = BlendDensitySampler { + input: Arc::new(FailedInput), + }; + assert!(sampler.sample_value(&mut context, [0; 3]).is_err()); + let mut buffer = [9.0; 2]; + assert!( + sampler + .sample_volume( + &mut context, + &mut buffer, + DensityVolume::new([1; 3], [0; 3], [1; 3]).unwrap() + ) + .is_err() + ); + assert_eq!(buffer, [0.25, 9.0]); + assert!(blender.calls.lock().unwrap().is_empty()); +} + +#[test] +fn blending_range_and_axes_follow_input_even_for_spatial_providers() { + let mut graph = DensityGraph::default(); + let constant = graph.insert(GraphNode::Constant(0.5)).unwrap(); + let root = graph.insert(GraphNode::BlendDensity(constant)).unwrap(); + assert_eq!(graph.domain_axes(root).unwrap(), 0); + assert_eq!(graph.range(root).unwrap(), graph.range(constant).unwrap()); + let mut compiler = DensityCompiler::new(graph); + let raw = compiler.compile_raw(root).unwrap(); + let optimized = compiler.get_sampler(root).unwrap(); + let blender = Arc::new(SpatialBlender { + calls: Mutex::new(Vec::new()), + }); + let mut context = + SamplerContext::default().with_world_fields(WorldFields::default().with_blender(blender)); + assert_eq!(raw.sample_value(&mut context, [1, 2, 3]).unwrap(), 123.5); + assert_eq!( + optimized.sample_value(&mut context, [1, 2, 3]).unwrap(), + 0.5 + ); +} + +#[test] +fn named_reference_identity_differs_from_direct_value_equality() { + let mut graph = DensityGraph::new(); + let value = graph.insert(GraphNode::Constant(-0.0)).unwrap(); + let direct = graph + .insert(GraphNode::Reference { + input: value, + holder: None, + }) + .unwrap(); + let a = graph + .register_function("minecraft:a".into(), value) + .unwrap(); + let b = graph + .register_function("minecraft:b".into(), value) + .unwrap(); + assert!(!graph.java_equals(a, b).unwrap()); + assert!(!graph.java_equals(a, direct).unwrap()); + assert_eq!(graph.function("minecraft:a"), Some(a)); + assert!( + graph + .register_function("minecraft:a".into(), value) + .is_err() + ); + let exponent = graph.insert(GraphNode::Constant(0.5)).unwrap(); + let power = graph + .insert(GraphNode::Power { base: a, exponent }) + .unwrap(); + let mut compiler = DensityCompiler::new(graph); + let raw = compiler.compile_raw(power).unwrap(); + let optimized = compiler.get_sampler(power).unwrap(); + let mut context = SamplerContext::default(); + assert_eq!( + raw.sample_value(&mut context, [0; 3]).unwrap().to_bits(), + 0x8000_0000 + ); + assert_eq!( + optimized + .sample_value(&mut context, [0; 3]) + .unwrap() + .to_bits(), + 0 + ); +} diff --git a/crates/horizon-world/Cargo.toml b/crates/horizon-world/Cargo.toml new file mode 100644 index 000000000..4c8c4f43a --- /dev/null +++ b/crates/horizon-world/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "horizon-world" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version.workspace = true +description = "Horizon vanilla world data, NBT, regions and chunk storage" + +[dependencies] +serde_json = { version = "1.0.151", features = ["raw_value"] } +horizon-core = { path = "../horizon-core" } +flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } +lz4_flex = { version = "0.14", default-features = false, features = ["std", "safe-encode", "safe-decode", "checked-decode"] } +xxhash-rust = { version = "0.8.19", features = ["xxh32"] } + +[[bin]] +name = "horizon-world" +path = "src/main.rs" + +[[bin]] +name = "horizon-worldgen-parity" +path = "src/bin/worldgen_parity.rs" diff --git a/crates/horizon-world/examples/anchor_fixture.rs b/crates/horizon-world/examples/anchor_fixture.rs new file mode 100644 index 000000000..c6c15e65e --- /dev/null +++ b/crates/horizon-world/examples/anchor_fixture.rs @@ -0,0 +1,71 @@ +//! Original comparison transport for generation bounds and vertical anchors. +use horizon_world::worldgen::anchor::{VerticalAnchor, WorldGenerationContext}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn anchor( + a: VerticalAnchor, + context: WorldGenerationContext, + out: &mut impl Write, +) -> io::Result<()> { + writeln!( + out, + "anchor {} {}", + a.resolve(context), + a.to_json().unwrap_or_else(|_| "error".to_owned()) + ) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let [min, height, sea] = std::array::from_fn(|i| f["context"][i].as_i64().unwrap() as i32); + let context = if let Some(g) = f.get("generator") { + WorldGenerationContext::with_generator( + min, + height, + g[0].as_i64().unwrap() as i32, + g[1].as_i64().unwrap() as i32, + g[2].as_i64().unwrap() as i32, + ) + } else { + WorldGenerationContext::new(min, height, sea) + }; + writeln!( + out, + "context {} {} {}", + context.min_y, context.height, context.sea_level + )?; + for a in [ + VerticalAnchor::BOTTOM, + VerticalAnchor::TOP, + VerticalAnchor::SEA_LEVEL, + ] { + anchor(a, context, &mut out)?; + } + for e in f["values"].as_array().unwrap() { + let v = e.as_i64().unwrap() as i32; + for a in [ + VerticalAnchor::Absolute(v), + VerticalAnchor::AboveBottom(v), + VerticalAnchor::BelowTop(v), + VerticalAnchor::RelativeToSeaLevel(v), + ] { + anchor(a, context, &mut out)?; + } + } + for e in f["json"].as_array().unwrap() { + match VerticalAnchor::from_json(e.as_str().unwrap()) { + Ok(a) => anchor(a, context, &mut out)?, + Err(_) => writeln!(out, "error")?, + } + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/examples/basic_feature_fixture.rs b/crates/horizon-world/examples/basic_feature_fixture.rs new file mode 100644 index 000000000..f8ec7f53c --- /dev/null +++ b/crates/horizon-world/examples/basic_feature_fixture.rs @@ -0,0 +1,175 @@ +//! Feature world transport retaining ordered mutations and partial failures. +use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; +use horizon_world::{ + heightmap::HeightmapType, + registry::BlockStateId, + worldgen::{ + anchor::WorldGenerationContext, + feature::{BasicFeature, FeatureBlocks, FeatureWorld}, + placement::{FeaturePlacer, PlacementContext, PlacementModifier, PlacementQueryError}, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + io::{self, Write}, + path::Path, +}; +struct World<'a, W> { + states: BTreeMap<[i32; 3], BlockStateId>, + blocks: [BlockStateId; 5], + calls: i32, + fail: i32, + reject: i32, + out: &'a mut W, +} +impl PlacementContext for World<'_, W> { + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new(-64, 384, 63) + } + fn min_y(&mut self) -> Result { + Ok(-64) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + Err(PlacementQueryError::Unavailable) + } +} +impl FeatureWorld for World<'_, W> { + type Error = io::Error; + fn block(&mut self, p: [i32; 3]) -> Result { + let call = self.calls; + self.calls += 1; + writeln!(self.out, "get {} {} {}", p[0], p[1], p[2])?; + if call == self.fail { + return Err(io::Error::other("world failure")); + } + let hash = p[0] + .wrapping_mul(31) + .wrapping_add(p[1].wrapping_mul(7)) + .wrapping_add(p[2].wrapping_mul(17)) + .rem_euclid(5) as usize; + let state = self.states.get(&p).copied().unwrap_or(self.blocks[hash]); + writeln!(self.out, "state {}", state.0)?; + Ok(state) + } + fn set_block( + &mut self, + p: [i32; 3], + state: BlockStateId, + flags: i32, + ) -> Result { + let call = self.calls; + self.calls += 1; + writeln!( + self.out, + "set {} {} {} {} {flags}", + p[0], p[1], p[2], state.0 + )?; + if call == self.fail { + return Err(io::Error::other("world failure")); + } + let result = self.reject == 0 || call % self.reject != 0; + if result { + self.states.insert(p, state); + } + writeln!(self.out, "written {result}")?; + Ok(result) + } +} +fn fixture( + f: &Value, + mut random: impl RandomSource, + blocks: [BlockStateId; 5], + out: &mut impl Write, +) -> Result<(), Box> { + let decoded = BasicFeature::from_json(f["definition"].as_str().unwrap()).and_then(|feature| { + let modifiers = f + .get("placement") + .map(|v| { + v.as_array() + .unwrap() + .iter() + .map(|v| PlacementModifier::from_json(&v.to_string())) + .collect::, _>>() + }) + .transpose()?; + Ok((feature, modifiers)) + }); + match decoded { + Err(_) => writeln!(out, "decode error")?, + Ok((feature, modifiers)) => { + writeln!(out, "decode ok")?; + let mut world = World { + states: BTreeMap::new(), + blocks, + calls: 0, + fail: f["fail"].as_i64().unwrap() as i32, + reject: f["reject"].as_i64().unwrap() as i32, + out, + }; + let blocks = FeatureBlocks { + air: blocks[0], + stone: blocks[1], + cobblestone: blocks[2], + end_stone: blocks[3], + obsidian: blocks[4], + }; + let p = &f["origin"]; + let origin = [ + p[0].as_i64().unwrap() as i32, + p[1].as_i64().unwrap() as i32, + p[2].as_i64().unwrap() as i32, + ]; + let mut placer = FeaturePlacer::new(); + for _ in 0..f["repeats"].as_u64().unwrap() { + world.calls = 0; + let result = if let Some(modifiers) = &modifiers { + placer + .place_with_context( + modifiers, + &mut world, + &mut random, + origin, + |world, random, position| { + feature.place(world, random, position, blocks) + }, + ) + .map_err(|_| ()) + } else { + feature + .place(&mut world, &mut random, origin, blocks) + .map_err(|_| ()) + }; + match result { + Ok(value) => writeln!(world.out, "place {value}")?, + Err(_) => writeln!(world.out, "place error")?, + } + writeln!(world.out, "next {}", random.next_long())?; + for (p, state) in &world.states { + writeln!(world.out, "stored {} {} {} {}", p[0], p[1], p[2], state.0)?; + } + writeln!(world.out, "end")?; + } + } + } + writeln!(out, "tail {}", random.next_long())?; + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let ids: [u32; 5] = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let blocks = ids.map(BlockStateId); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, LegacyRandom::new(seed), blocks, &mut out)?; + } else { + fixture(&f, XoroshiroRandom::new(seed), blocks, &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/biome_chunk_fixture.rs b/crates/horizon-world/examples/biome_chunk_fixture.rs new file mode 100644 index 000000000..4adbd0a1f --- /dev/null +++ b/crates/horizon-world/examples/biome_chunk_fixture.rs @@ -0,0 +1,62 @@ +//! Original transport for native chunk biome fill order and failure state. +use horizon_core::position::ChunkPos; +use horizon_world::worldgen::biome_chunk::BiomeChunk; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let height = n(&f["height"]); + let mut chunk = BiomeChunk::new( + ChunkPos::new(n(&f["cx"]), n(&f["cz"])), + n(&f["min"]), + height, + n(&f["default"]), + )?; + for op in f["ops"].as_array().unwrap() { + let mut calls = 0; + let result = chunk.fill(n(&op[3]), n(&op[4]), |[x, y, z]| { + writeln!(out, "resolve {x} {y} {z}").unwrap(); + let previous = calls; + calls += 1; + if previous == n(&op[2]) { + return Err(()); + } + Ok(x.wrapping_mul(31) + .wrapping_add(y.wrapping_mul(7)) + .wrapping_add(z.wrapping_mul(17)) + .wrapping_add(n(&op[0])) + .rem_euclid(n(&op[1]))) + }); + writeln!( + out, + "fill {} {calls}", + if result.is_ok() { "ok" } else { "error" } + )?; + for index in 0..height as usize / 16 { + writeln!(out, "section {index}")?; + for row in chunk.section(index).unwrap().chunks(4) { + writeln!(out, "biomes {} {} {} {}", row[0], row[1], row[2], row[3])?; + } + } + for q in f["queries"].as_array().unwrap() { + writeln!( + out, + "query {}", + chunk.noise_biome([n(&q[0]), n(&q[1]), n(&q[2])]) + )?; + } + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/biome_generation_fixture.rs b/crates/horizon-world/examples/biome_generation_fixture.rs new file mode 100644 index 000000000..4c41b7ca5 --- /dev/null +++ b/crates/horizon-world/examples/biome_generation_fixture.rs @@ -0,0 +1,106 @@ +//! Chunk biome generation from bundled climate routers and imported preset tables. +use horizon_core::{ + biome::{BiomeZoom, obfuscate_seed}, + density::{SamplerContext, graph::DensityCompiler}, + position::{BlockPos, ChunkPos}, +}; +use horizon_world::worldgen::{ + biome_chunk::BiomeChunk, + biome_source::{BiomeSet, BiomeSourceDefinition}, + density::DensityRegistry, + router::{NoiseRouter, RouterField}, +}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + io::{self, Write}, + path::Path, +}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("registries.json"))?)?; + let noises: BTreeMap = serde_json::from_value(bundle["noises"].clone())?; + let densities: BTreeMap = serde_json::from_value(bundle["densities"].clone())?; + let presets: BTreeMap = serde_json::from_value(bundle["presets"].clone())?; + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let settings: Value = serde_json::from_str( + bundle["settings"][f["setting"].as_str().unwrap()] + .as_str() + .unwrap(), + )?; + let mut definitions = DensityRegistry::from_json(&noises, &densities)?; + let router = + NoiseRouter::from_json(&settings["noise_router"].to_string(), &mut definitions)?; + let seed = f["seed"].as_i64().unwrap(); + let mut compiler = DensityCompiler::new_seeded( + definitions.into_graph(), + seed, + f["legacy"].as_bool().unwrap(), + ); + let climate = router.compile_climate(&mut compiler)?; + let definition = match f["source"].as_str().unwrap_or("multi") { + "fixed" => BiomeSourceDefinition::Fixed("minecraft:plains".into()), + "checkerboard" => BiomeSourceDefinition::Checkerboard { + biomes: BiomeSet::Direct(vec![ + "minecraft:plains".into(), + "minecraft:the_end".into(), + "minecraft:nether_wastes".into(), + ]), + scale: n(&f["scale"]), + }, + "end" => BiomeSourceDefinition::End, + "multi" => BiomeSourceDefinition::Preset { + name: f["preset"].as_str().unwrap().into(), + inline: false, + }, + _ => panic!("unknown source"), + }; + let source = definition.resolve(&presets)?; + let erosion = compiler.get_sampler(router.function(RouterField::Erosion))?; + let mut resolver = source.resolver(&climate, erosion.as_ref()); + let (cx, cz, min, height) = (n(&f["cx"]), n(&f["cz"]), n(&f["min"]), n(&f["height"])); + let mut chunk = BiomeChunk::new( + ChunkPos::new(cx, cz), + min, + height, + "minecraft:plains".to_owned(), + )?; + for repeat in 0..n(&f["repeats"]) { + let mut context = SamplerContext::cached(); + let volume = resolver.prepare_volume( + &mut context, + [cx.wrapping_shl(4) >> 2, min >> 2, cz.wrapping_shl(4) >> 2], + [4, height >> 2, 4], + )?; + chunk.fill(n(&f["write_min"]), n(&f["write_max"]), |quart| { + resolver + .sample_prepared(&mut context, volume.as_ref(), quart) + .map(str::to_owned) + })?; + writeln!(out, "fill {repeat}")?; + for section in 0..height as usize / 16 { + writeln!(out, "section {section}")?; + for name in chunk.section(section).unwrap() { + writeln!(out, "biome {name}")?; + } + } + let zoom = BiomeZoom::new(obfuscate_seed(seed)); + for q in f["queries"].as_array().unwrap() { + let block = BlockPos::new(n(&q[0]), n(&q[1]), n(&q[2])); + writeln!( + out, + "query {}", + chunk.noise_biome(zoom.quart_at_block(block)) + )?; + } + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/biome_placement_fixture.rs b/crates/horizon-world/examples/biome_placement_fixture.rs new file mode 100644 index 000000000..a412b9924 --- /dev/null +++ b/crates/horizon-world/examples/biome_placement_fixture.rs @@ -0,0 +1,175 @@ +use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom, XoroshiroRandom}; +use horizon_world::{ + heightmap::HeightmapType, + worldgen::{ + anchor::WorldGenerationContext, + feature_sort::FeatureIdentity, + placement::{FeaturePlacer, PlacementContext, PlacementModifier, PlacementQueryError}, + }, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +struct World<'a, W> { + out: &'a mut W, + f: &'a Value, + queries: i32, + calls: i32, +} +impl PlacementContext for World<'_, W> { + fn top_feature(&self) -> Option { + self.f["top"] + .as_bool() + .unwrap() + .then_some(FeatureIdentity(42)) + } + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new(-64, 384, 63) + } + fn min_y(&mut self) -> Result { + Ok(-64) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + Err(PlacementQueryError::Unavailable) + } + fn biome_allows_feature( + &mut self, + p: [i32; 3], + feature: FeatureIdentity, + ) -> Result { + assert_eq!(feature, FeatureIdentity(42)); + let error = |e: io::Error| PlacementQueryError::Failed(e.to_string()); + writeln!(self.out, "biome {} {} {}", p[0], p[1], p[2]).map_err(error)?; + let call = self.queries; + self.queries += 1; + if call == n(&self.f["query_fail"]) { + return Err(PlacementQueryError::Unavailable); + } + let index = p[0] + .wrapping_mul(31) + .wrapping_add(p[1].wrapping_mul(7)) + .wrapping_add(p[2].wrapping_mul(17)) + .rem_euclid(2) as usize; + writeln!(self.out, "selected {index}").map_err(error)?; + writeln!(self.out, "settings {index}").map_err(error)?; + let call = self.queries; + self.queries += 1; + if call == n(&self.f["query_fail"]) { + return Err(PlacementQueryError::Unavailable); + } + Ok(matches!(n(&self.f["membership"][index]), 1 | 2)) + } +} +fn feature( + world: &mut World<'_, W>, + random: &mut impl RandomSource, + p: [i32; 3], +) -> Result { + writeln!(world.out, "feature {} {} {}", p[0], p[1], p[2]).map_err(|_| ())?; + if world.f["draw"].as_bool().unwrap() { + writeln!(world.out, "draw {}", random.next_long()).map_err(|_| ())?; + } + let call = world.calls; + world.calls += 1; + if call == n(&world.f["feature_fail"]) { + return Err(()); + } + if world.f["nested"].as_bool().unwrap() { + return FeaturePlacer::new() + .place_with_context(&[PlacementModifier::Biome], world, random, p, feature) + .map_err(|_| ()); + } + Ok(n(&world.f["return_mode"]) == 0 + || (n(&world.f["return_mode"]) == 2 + && p[0].wrapping_add(p[1]).wrapping_add(p[2]).rem_euclid(2) == 0)) +} +fn fixture( + f: &Value, + mut random: impl RandomSource, + out: &mut impl Write, +) -> Result<(), Box> { + let modifiers = f["placement"] + .as_array() + .unwrap() + .iter() + .map(|v| PlacementModifier::from_json(&v.to_string())) + .collect::, _>>()?; + let origin = std::array::from_fn(|i| n(&f["origin"][i])); + let mut world = World { + out, + f, + queries: 0, + calls: 0, + }; + let mut placer = FeaturePlacer::new(); + for _ in 0..3 { + world.queries = 0; + world.calls = 0; + let result = if f["direct"].as_bool().unwrap() { + // Direct modifier callbacks share their query world through a local + // emitted-position list; this corpus uses only the unit biome filter. + let mut positions = Vec::new(); + let result = modifiers[0].modify_in(&mut world, &mut random, origin, |_, p| { + positions.push(p); + Ok::<_, ()>(()) + }); + result.map_err(|_| ()).and_then(|()| { + for p in positions { + feature(&mut world, &mut random, p)?; + } + Ok(true) + }) + } else if f["top"].as_bool().unwrap() { + placer + .place_with_biome_check( + &modifiers, + &mut world, + &mut random, + origin, + FeatureIdentity(42), + feature, + ) + .map_err(|_| ()) + } else { + placer + .place_with_context(&modifiers, &mut world, &mut random, origin, feature) + .map_err(|_| ()) + }; + match result { + Ok(value) => writeln!(world.out, "place {value}")?, + Err(()) => writeln!(world.out, "place error")?, + } + writeln!(world.out, "next {}", random.next_long())?; + } + writeln!(world.out, "tail {}", random.next_long())?; + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + match ( + f["legacy"].as_bool().unwrap(), + f["worldgen"].as_bool().unwrap(), + ) { + (true, false) => fixture(&f, LegacyRandom::new(seed), &mut out)?, + (true, true) => fixture(&f, WorldgenRandom::new(LegacyRandom::new(seed)), &mut out)?, + (false, false) => fixture(&f, XoroshiroRandom::new(seed), &mut out)?, + (false, true) => fixture( + &f, + WorldgenRandom::new(XoroshiroRandom::new(seed)), + &mut out, + )?, + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/biome_source_codec_fixture.rs b/crates/horizon-world/examples/biome_source_codec_fixture.rs new file mode 100644 index 000000000..d45dcdd3a --- /dev/null +++ b/crates/horizon-world/examples/biome_source_codec_fixture.rs @@ -0,0 +1,79 @@ +//! Registry-aware codec transport for biome-source definitions. +use horizon_core::density::{ConstantSampler, SamplerContext}; +use horizon_world::worldgen::{ + biome_source::BiomeSourceCatalog, climate::ClimateSampler, tags::TagDefinitions, +}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + io::{self, Write}, + path::Path, + sync::Arc, +}; +fn normalized(value: Value) -> Value { + match value { + Value::Number(n) => { + serde_json::json!({"float64_bits":format!("{:016x}",n.as_f64().unwrap().to_bits())}) + } + Value::Array(values) => Value::Array(values.into_iter().map(normalized).collect()), + Value::Object(values) => Value::Object( + values + .into_iter() + .map(|(k, v)| (k, normalized(v))) + .collect(), + ), + value => value, + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let read = |name: &str| -> Result, Box> { + Ok(serde_json::from_str(&fs::read_to_string( + dir.join(format!("{name}.json")), + )?)?) + }; + let biomes: BTreeSet<_> = read("biomes")?.into_keys().collect(); + let presets = read("presets")?; + let mut tags = TagDefinitions::default(); + for (name, raw) in read("biome_tags")? { + tags.apply_json(&name, "vanilla", &raw)?; + } + let tags = tags.build(|name, _| biomes.contains(name).then(|| name.to_owned()))?; + assert!(tags.missing.is_empty()); + let catalog = BiomeSourceCatalog::new(&biomes, &tags.tags, &presets.keys().cloned().collect())?; + let positions: Vec<[i32; 3]> = + serde_json::from_str(&fs::read_to_string(dir.join("positions.json"))?)?; + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for json in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let definition = match catalog.decode(json) { + Ok(v) => v, + Err(_) => { + writeln!(out, "codec error")?; + continue; + } + }; + let encoded = catalog.encode(&definition)?; + writeln!(out, "codec {}", normalized(serde_json::from_str(&encoded)?))?; + let source = definition.resolve(&presets)?; + writeln!( + out, + "possible {}", + serde_json::to_string(&source.possible_biomes())? + )?; + let climate = + ClimateSampler::new(std::array::from_fn(|_| Arc::new(ConstantSampler(0.)) as _)); + let erosion = ConstantSampler(0.); + let mut resolver = source.resolver(&climate, &erosion); + let mut context = SamplerContext::cached(); + for &pos in &positions { + writeln!( + out, + "biome {}", + resolver.sample(&mut context, pos).unwrap_or("error") + )?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/biome_source_fixture.rs b/crates/horizon-world/examples/biome_source_fixture.rs new file mode 100644 index 000000000..cbf262a7c --- /dev/null +++ b/crates/horizon-world/examples/biome_source_fixture.rs @@ -0,0 +1,79 @@ +//! Original transport for fixed, checkerboard and End biome-source queries. +use horizon_core::density::{DensitySampler, SampleError, SamplerContext}; +use horizon_world::worldgen::biome_source::{ + CheckerboardBiomeSource, EndBiomeSource, FixedBiomeSource, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, + sync::{Arc, Mutex}, +}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +#[derive(Debug)] +struct Erosion { + value: f32, + fail: bool, + trace: Arc>>, +} +impl DensitySampler for Erosion { + fn sample_value(&self, _: &mut SamplerContext, pos: [i32; 3]) -> Result { + self.trace.lock().unwrap().push(pos); + if self.fail { + Err(SampleError::RecursiveCache) + } else { + Ok(self.value) + } + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let kind = f["kind"].as_str().unwrap(); + let fixed = FixedBiomeSource { biome: 7 }; + let checker = CheckerboardBiomeSource::new( + f["biomes"] + .as_array() + .map(|v| v.iter().map(n).collect()) + .unwrap_or_default(), + f["scale"].as_i64().unwrap_or(0) as i32, + )?; + let end = EndBiomeSource { + center: 0, + highlands: 1, + midlands: 2, + islands: 3, + barrens: 4, + }; + let trace = Arc::new(Mutex::new(Vec::new())); + let erosion = Erosion { + value: f32::from_bits(u32::from_str_radix(f["bits"].as_str().unwrap_or("0"), 16)?), + fail: f["fail"].as_bool().unwrap_or(false), + trace: trace.clone(), + }; + let mut context = SamplerContext::cached(); + for pos in f["positions"].as_array().unwrap() { + let q = [n(&pos[0]), n(&pos[1]), n(&pos[2])]; + let value = match kind { + "fixed" => Some(*fixed.noise_biome(q)), + "checkerboard" => checker.noise_biome(q).ok().copied(), + "end" => end.noise_biome(q, &erosion, &mut context).ok().copied(), + _ => panic!("invalid source"), + }; + for [x, y, z] in trace.lock().unwrap().drain(..) { + writeln!(out, "sample {x} {y} {z}")?; + } + match value { + Some(id) => writeln!(out, "biome {id}")?, + None => writeln!(out, "error")?, + } + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/biome_temperature_fixture.rs b/crates/horizon-world/examples/biome_temperature_fixture.rs new file mode 100644 index 000000000..86b1393ce --- /dev/null +++ b/crates/horizon-world/examples/biome_temperature_fixture.rs @@ -0,0 +1,119 @@ +//! Original comparison transport for biome temperatures and ordered caches. +use horizon_core::position::BlockPos; +use horizon_world::worldgen::biome_temperature::{ + BiomeTemperature, BiomeTemperatureSettings, Precipitation, TemperatureModifier, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn bits(value: f32) -> u32 { + if value.is_nan() { + 0x7fc00000 + } else { + value.to_bits() + } +} +fn operations(worker: &mut BiomeTemperature, ops: &Value, out: &mut impl Write) -> io::Result<()> { + for op in ops.as_array().unwrap() { + match op[0].as_str().unwrap() { + "query" => { + let p = BlockPos::new( + op[1].as_i64().unwrap() as i32, + op[2].as_i64().unwrap() as i32, + op[3].as_i64().unwrap() as i32, + ); + let sea = op[4].as_i64().unwrap() as i32; + writeln!( + out, + "adjusted {:x}", + bits(worker.settings().height_adjusted(p, sea)) + )?; + writeln!(out, "cached {:x}", bits(worker.temperature(p, sea)))?; + let warm = worker.warm_enough_to_rain(p, sea); + let cold = worker.cold_enough_to_snow(p, sea); + let melt = worker.should_melt_frozen_ocean_iceberg_slightly(p, sea); + let precipitation = match worker.precipitation_at(p, sea) { + Precipitation::None => "NONE", + Precipitation::Rain => "RAIN", + Precipitation::Snow => "SNOW", + }; + writeln!(out, "weather {warm} {cold} {melt} {precipitation}")?; + } + "fill" => { + for i in 0..op[1].as_i64().unwrap() as i32 { + let p = BlockPos::new( + (op[2].as_i64().unwrap() as i32).wrapping_add(i), + i & 255, + i.wrapping_mul(31), + ); + writeln!( + out, + "fill {:x}", + bits(worker.temperature(p, op[3].as_i64().unwrap() as i32)) + )?; + } + } + "dump" => { + writeln!(out, "cache {}", worker.cached_temperatures().len())?; + for (key, value) in worker.cached_temperatures() { + writeln!(out, "{:x} {:x}", key as u64, bits(value))?; + } + } + "thread" => operations(&mut BiomeTemperature::new(worker.settings()), &op[1], out)?, + _ => panic!("unknown operation"), + } + } + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let settings = if let Some(json) = f.get("json") { + match BiomeTemperatureSettings::from_json(json.as_str().unwrap()) { + Ok(value) => value, + Err(_) => { + writeln!(out, "decode error")?; + continue; + } + } + } else { + BiomeTemperatureSettings { + base_temperature: f32::from_bits(u32::from_str_radix( + f["base"].as_str().unwrap(), + 16, + )?), + downfall: f32::from_bits(u32::from_str_radix( + f.get("downfall").and_then(Value::as_str).unwrap_or("0"), + 16, + )?), + modifier: if f["modifier"].as_str().unwrap() == "FROZEN" { + TemperatureModifier::Frozen + } else { + TemperatureModifier::None + }, + has_precipitation: f["precipitation"].as_bool().unwrap(), + } + }; + writeln!( + out, + "settings {} {:x} {} {:x}", + settings.has_precipitation, + bits(settings.base_temperature), + if settings.modifier == TemperatureModifier::Frozen { + "FROZEN" + } else { + "NONE" + }, + bits(settings.downfall) + )?; + operations(&mut BiomeTemperature::new(settings), &f["ops"], &mut out)?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/examples/block_properties_fixture.rs b/crates/horizon-world/examples/block_properties_fixture.rs new file mode 100644 index 000000000..35aef48e9 --- /dev/null +++ b/crates/horizon-world/examples/block_properties_fixture.rs @@ -0,0 +1,142 @@ +use horizon_core::geometry::{Aabb, Axis, ShapeOp, Vec3, VoxelShape}; +use horizon_world::{ + block_properties::{BlockDefinitionProperties, BlockPropertiesRegistry, BlockProperty}, + collision::CachedCollisionRegistry, + nbt::{self, Limits, Tag}, + registry::{BlockRegistry, BlockStateId}, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn bbox(v: &Value) -> Aabb { + let v = v + .as_array() + .unwrap() + .iter() + .map(|v| f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap())) + .collect::>(); + Aabb::new(Vec3::new(v[0], v[1], v[2]), Vec3::new(v[3], v[4], v[5])) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let read = |name: &str| -> Result> { + Ok( + nbt::read_named(&fs::read(dir.join(name))?, Limits::default())? + .0 + .tag, + ) + }; + let registry = BlockRegistry::from_nbt(&read("block-registry.nbt")?)?; + let collisions = CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, ®istry)?; + let data = read("block-properties.nbt")?; + let properties = BlockPropertiesRegistry::from_nbt(&data, &collisions)?; + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + let solid = properties.bind(BlockProperty::Solid); + let replaceable = properties.bind(BlockProperty::Replaceable); + for id in 0..registry.len() { + let state = BlockStateId(id as u32); + let definition = properties + .definition(®istry.state(state).unwrap().name) + .unwrap(); + let s = properties.property(state, BlockProperty::Solid)?; + let r = properties.property(state, BlockProperty::Replaceable)?; + assert_eq!(s, solid.contains(state)); + assert_eq!(r, replaceable.contains(state)); + writeln!( + out, + "state {id} {} {} {r} {s}", + definition.force_solid_on, definition.force_solid_off + )?; + writeln!( + out, + "render {} {} {}", + properties.property(state, BlockProperty::Liquid)?, + definition.can_occlude, + properties.property(state, BlockProperty::SolidRender)? + )?; + assert_eq!( + properties.property(state, BlockProperty::Liquid)?, + properties.bind(BlockProperty::Liquid).contains(state) + ); + assert_eq!( + properties.property(state, BlockProperty::SolidRender)?, + properties.bind(BlockProperty::SolidRender).contains(state) + ); + match collisions.cached_shape(state)? { + None => writeln!(out, "cache none")?, + Some(shape) => match shape.bounds() { + None => writeln!(out, "cache empty")?, + Some(b) => { + let v = [ + b.min(Axis::X), + b.min(Axis::Y), + b.min(Axis::Z), + b.max(Axis::X), + b.max(Axis::Y), + b.max(Axis::Z), + ] + .map(f64::to_bits); + writeln!( + out, + "cache {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", + v[0], v[1], v[2], v[3], v[4], v[5] + )?; + } + }, + } + } + assert!( + properties + .property(BlockStateId(registry.len() as u32), BlockProperty::Solid) + .is_err() + ); + for (name, value) in [ + ("DataVersion", Tag::Int(0)), + ("states", Tag::List(vec![])), + ("blocks", Tag::compound([] as [(&str, Tag); 0])), + ("occlusion", Tag::compound([] as [(&str, Tag); 0])), + ] { + let mut bad = data.clone(); + *bad.get_mut(name).unwrap() = value; + assert!(BlockPropertiesRegistry::from_nbt(&bad, &collisions).is_err()); + } + for flags in [-1, 32] { + let mut bad = data.clone(); + *bad.get_mut("blocks") + .unwrap() + .get_mut("minecraft:stone") + .unwrap() = Tag::Byte(flags); + assert!(BlockPropertiesRegistry::from_nbt(&bad, &collisions).is_err()); + } + let mut bad = data.clone(); + let Some(Tag::List(states)) = bad.get_mut("states") else { + unreachable!() + }; + states.swap(0, 1); + assert!(BlockPropertiesRegistry::from_nbt(&bad, &collisions).is_err()); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let mut shape = VoxelShape::empty(); + for v in f["shape"].as_array().unwrap() { + shape = shape.join(&VoxelShape::from_box(bbox(v))?, ShapeOp::OR)?; + } + let properties = BlockDefinitionProperties { + force_solid_on: f["on"].as_bool().unwrap(), + force_solid_off: f["off"].as_bool().unwrap(), + replaceable: false, + liquid: false, + can_occlude: f["occludes"].as_bool().unwrap(), + }; + writeln!( + out, + "solid {}", + properties.calculate_solid(f["cached"].as_bool().unwrap().then_some(&shape)) + )?; + writeln!(out, "render {}", properties.calculate_solid_render(&shape)?)?; + } + Ok(()) +} diff --git a/crates/horizon-world/examples/block_state_codec_fixture.rs b/crates/horizon-world/examples/block_state_codec_fixture.rs new file mode 100644 index 000000000..d0632ae86 --- /dev/null +++ b/crates/horizon-world/examples/block_state_codec_fixture.rs @@ -0,0 +1,70 @@ +//! Original JSON block-state codec comparison transport. +use horizon_world::{ + DATA_VERSION, + nbt::Tag, + registry::{BlockRegistry, BlockStateId, BlockStateJsonCodec}, +}; +use serde_json::Value; +use std::{ + collections::BTreeSet, + fs, + io::{self, Write}, + path::Path, +}; +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", tag(&facts["states"])), + ("defaults", tag(&facts["defaults"])), + ]))?; + let integers: BTreeSet<_> = facts["integers"] + .as_array() + .unwrap() + .iter() + .map(|v| { + ( + v[0].as_str().unwrap().to_owned(), + v[1].as_str().unwrap().to_owned(), + ) + }) + .collect(); + let codec = BlockStateJsonCodec::new(®istry, integers)?; + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for i in 0..registry.len() { + let id = BlockStateId(i as u32); + writeln!( + out, + "state {i} {} {}", + codec.encode(id, false)?, + codec.encode(id, true)? + )?; + } + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let input: Value = serde_json::from_str(line)?; + match codec.decode(input[1].as_str().unwrap(), input[0].as_bool().unwrap()) { + Err(_) => writeln!(out, "decode error")?, + Ok(id) => writeln!( + out, + "decode {} {} {}", + id.0, + codec.encode(id, false)?, + codec.encode(id, true)? + )?, + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/block_support_fixture.rs b/crates/horizon-world/examples/block_support_fixture.rs new file mode 100644 index 000000000..9c43d5798 --- /dev/null +++ b/crates/horizon-world/examples/block_support_fixture.rs @@ -0,0 +1,69 @@ +use horizon_core::geometry::Direction; +use horizon_world::{ + block_support::{CachedBlockSupportRegistry, SupportType}, + nbt::{self, Limits, Tag}, + registry::{BlockRegistry, BlockStateId}, +}; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let read = |name: &str| -> Result> { + Ok( + nbt::read_named(&fs::read(dir.join(name))?, Limits::default())? + .0 + .tag, + ) + }; + let registry = BlockRegistry::from_nbt(&read("block-registry.nbt")?)?; + let tag = read("cached-support.nbt")?; + let support = CachedBlockSupportRegistry::from_nbt(&tag, ®istry)?; + assert_eq!(registry.len(), 35723); + assert_eq!(support.cached_state_count(), 35524); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for id in 0..registry.len() { + let state = BlockStateId(id as u32); + if support.cached_shape(state)?.is_none() { + writeln!(out, "state {id} uncached")?; + for d in Direction::ALL { + assert!( + support + .is_face_sturdy(state, d, SupportType::Full)? + .is_none() + ); + } + continue; + } + writeln!(out, "state {id} cached")?; + for d in Direction::ALL { + write!(out, "support {}", d as u8)?; + for t in [SupportType::Full, SupportType::Center, SupportType::Rigid] { + write!(out, " {}", support.is_face_sturdy(state, d, t)?.unwrap())?; + } + writeln!( + out, + " {}", + support + .is_face_sturdy(state, d, SupportType::Full)? + .unwrap() + )?; + } + } + let mut bad = tag.clone(); + *bad.get_mut("Kind").unwrap() = Tag::String("collision".into()); + assert!(CachedBlockSupportRegistry::from_nbt(&bad, ®istry).is_err()); + assert!( + support + .is_face_sturdy( + BlockStateId(registry.len() as u32), + Direction::Down, + SupportType::Full + ) + .is_err() + ); + Ok(()) +} diff --git a/crates/horizon-world/examples/block_survival_fixture.rs b/crates/horizon-world/examples/block_survival_fixture.rs new file mode 100644 index 000000000..e062eb8da --- /dev/null +++ b/crates/horizon-world/examples/block_survival_fixture.rs @@ -0,0 +1,279 @@ +use horizon_core::geometry::VoxelShape; +use horizon_world::{ + block_collision::{BlockCollisionRegistry, DynamicCollisionWorld, ShulkerCollisionState}, + block_properties::BlockPropertiesRegistry, + block_support::BlockSupportRegistry, + block_survival::{BlockSurvivalRegistry, SurvivalDefinitions, SurvivalRule, SurvivalWorld}, + collision::CachedCollisionRegistry, + dynamic_support::DynamicSupportWorld, + fluid::{FluidKind, FluidState, FluidStateTable}, + nbt::{self, Limits, Tag}, + registry::{BlockRegistry, BlockStateId}, + worldgen::tags::TagDefinitions, +}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + io::{self, BufRead, Write}, + path::Path, + sync::Arc, +}; +struct World<'a, W> { + out: &'a mut W, + neighbors: Vec, + fluids: &'a FluidStateTable, + fluid_states: Vec, + fluid_calls: i32, + fluid_fail: i32, + entity: &'a str, + shulker: ShulkerCollisionState, + reads: i32, + lights: i32, + light_fail: i32, + brightness: i32, + entities: i32, + fail: i32, + entity_fail: i32, +} +impl World<'_, W> { + fn entity(&mut self, p: [i32; 3]) -> io::Result<()> { + writeln!(self.out, "entity {} {} {}", p[0], p[1], p[2])?; + let old = self.entities; + self.entities += 1; + if old == self.entity_fail { + return Err(io::Error::other("injected entity query failure")); + } + Ok(()) + } +} +impl DynamicSupportWorld for World<'_, W> { + type Error = io::Error; + fn shulker_is_closed(&mut self, p: [i32; 3]) -> io::Result> { + self.entity(p)?; + Ok(match self.entity { + "none" => None, + "closed" => Some(true), + "opened" => Some(false), + _ => unreachable!(), + }) + } + fn moving_piston_shape(&mut self, p: [i32; 3]) -> io::Result> { + self.entity(p)?; + Ok(None) + } +} +impl DynamicCollisionWorld for World<'_, W> { + fn shulker_collision_state( + &mut self, + p: [i32; 3], + ) -> io::Result> { + self.entity(p)?; + Ok((self.entity != "none").then_some(self.shulker)) + } +} +impl SurvivalWorld for World<'_, W> { + fn fluid_state(&mut self, p: [i32; 3]) -> io::Result { + writeln!(self.out, "fluid {} {} {}", p[0], p[1], p[2])?; + let old = self.fluid_calls; + self.fluid_calls += 1; + if old == self.fluid_fail { + return Err(io::Error::other("injected fluid query failure")); + } + self.fluids + .get(self.fluid_states[old as usize % self.fluid_states.len()]) + .ok_or_else(|| io::Error::other("unknown fixture fluid state")) + } + fn raw_brightness(&mut self, p: [i32; 3], sky_darken: i32) -> io::Result { + writeln!(self.out, "light {} {} {} {sky_darken}", p[0], p[1], p[2])?; + let old = self.lights; + self.lights += 1; + if old == self.light_fail { + return Err(io::Error::other("injected light query failure")); + } + Ok(self.brightness) + } + fn block_state(&mut self, p: [i32; 3]) -> io::Result { + writeln!(self.out, "read {} {} {}", p[0], p[1], p[2])?; + let old = self.reads; + self.reads += 1; + if old == self.fail { + return Err(io::Error::other("injected block query failure")); + } + Ok(self.neighbors[old as usize % self.neighbors.len()]) + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let read = |name: &str| -> Result> { + Ok( + nbt::read_named(&fs::read(dir.join(name))?, Limits::default())? + .0 + .tag, + ) + }; + let registry = BlockRegistry::from_nbt(&read("block-registry.nbt")?)?; + let collisions = CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, ®istry)?; + let properties = + BlockPropertiesRegistry::from_nbt(&read("block-properties.nbt")?, &collisions)?; + let support = Arc::new(BlockSupportRegistry::from_nbt( + &read("cached-support.nbt")?, + ®istry, + )?); + let resources: BTreeMap = + serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; + let mut tags = TagDefinitions::default(); + for (name, text) in resources { + tags.apply_json(&name, "vanilla", &text)?; + } + let tags = tags.build(|name, _| registry.default_state(name).map(|_| name.to_owned()))?; + assert!(tags.missing.is_empty()); + let definitions: BTreeMap = + serde_json::from_str(&fs::read_to_string(dir.join("survival-rules.json"))?)?; + let definitions = definitions + .into_iter() + .map(|(name, rule)| { + use SurvivalRule::*; + let rule = match rule.as_str() { + value if value.starts_with("TagBelow:") => TagBelow(value[9..].to_owned()), + "CactusFlower" => CactusFlower, + "Seagrass" => Seagrass, + "BubbleColumn" => BubbleColumn, + "RedstoneWire" => RedstoneWire, + "DoublePlant" => DoublePlant, + "Door" => Door, + "BigDripleaf" => BigDripleaf, + "BigDripleafStem" => BigDripleafStem, + "Farmland" => Farmland, + "Cocoa" => Cocoa, + "Crop" => Crop, + "GrowingPlant" => GrowingPlant, + "MangrovePropagule" => MangrovePropagule, + "Speleothem" => Speleothem, + "Scaffolding" => Scaffolding, + "PistonHead" => PistonHead, + "ChorusPlant" => ChorusPlant, + "ChorusFlower" => ChorusFlower, + "PitcherCrop" => PitcherCrop, + "Multiface" => Multiface, + "Vine" => Vine, + "HangingMoss" => HangingMoss, + "SnowLayer" => SnowLayer, + "SeaPickle" => SeaPickle, + "Fire" => Fire, + "Cactus" => Cactus, + "Path" => Path, + "Mushroom" => Mushroom, + "Bell" => Bell, + "SugarCane" => SugarCane, + "LilyPad" => LilyPad, + "Frogspawn" => Frogspawn, + "SporeBlossom" => SporeBlossom, + "SmallDripleaf" => SmallDripleaf, + "TallSeagrass" => TallSeagrass, + "Always" => Always, + "SolidBelow" => SolidBelow, + "SolidBehind" => SolidBehind, + "NonAirBelow" => NonAirBelow, + "MossCarpet" => MossCarpet, + "CenterBelow" => CenterBelow, + "Lantern" => Lantern, + "FullAbove" => FullAbove, + "FullBehind" => FullBehind, + "RigidOrCenterBelow" => RigidOrCenterBelow, + "RigidBelow" => RigidBelow, + "FullBelow" => FullBelow, + "CenterAbove" => CenterAbove, + "FaceAttached" => FaceAttached, + "SupportsBamboo" => SupportsBamboo, + _ => panic!("unknown rule {rule}"), + }; + (name, rule) + }) + .collect(); + let fluid_resources: BTreeMap = + serde_json::from_str(&fs::read_to_string(dir.join("fluid-tags.json"))?)?; + let mut fluid_tags = TagDefinitions::default(); + for (name, text) in fluid_resources { + fluid_tags.apply_json(&name, "vanilla", &text)?; + } + let fluid_tags = + fluid_tags.build(|name, _| FluidKind::from_name(name).map(|_| name.to_owned()))?; + assert!(fluid_tags.missing.is_empty()); + let fluids = FluidStateTable::new(®istry)?; + let collision = Arc::new(BlockCollisionRegistry::new(Arc::new(collisions))?); + let extra: Value = serde_json::from_str(&fs::read_to_string( + dir.join("survival-extra-definitions.json"), + )?)?; + let definitions = SurvivalDefinitions { + rules: definitions, + ignition_odds: serde_json::from_value(extra["ignition_odds"].clone())?, + fence_gates: serde_json::from_value(extra["fence_gates"].clone())?, + }; + let survival = BlockSurvivalRegistry::new( + ®istry, + &properties, + support, + collision, + &definitions, + &tags.tags, + &fluid_tags.tags, + )?; + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in io::BufReader::new(fs::File::open(dir.join("inputs.txt"))?).lines() { + let f: Value = serde_json::from_str(&line?)?; + let mut world = World { + out: &mut out, + fluids: &fluids, + fluid_states: f + .get("fluid_states") + .unwrap_or(&f["neighbors"]) + .as_array() + .unwrap() + .iter() + .map(|v| BlockStateId(v.as_u64().unwrap() as u32)) + .collect(), + fluid_calls: 0, + fluid_fail: f["fluid_fail"].as_i64().unwrap_or(-1) as i32, + neighbors: f["neighbors"] + .as_array() + .unwrap() + .iter() + .map(|v| BlockStateId(v.as_u64().unwrap() as u32)) + .collect(), + entity: f["entity"].as_str().unwrap(), + shulker: ShulkerCollisionState { + previous_progress: f.get("shulker_progress").map_or(0.0, |v| { + f32::from_bits(u32::from_str_radix(v[0].as_str().unwrap(), 16).unwrap()) + }), + progress: f.get("shulker_progress").map_or(0.0, |v| { + f32::from_bits(u32::from_str_radix(v[1].as_str().unwrap(), 16).unwrap()) + }), + }, + reads: 0, + lights: 0, + brightness: f["brightness"].as_i64().unwrap_or(15) as i32, + light_fail: f["light_fail"].as_i64().unwrap_or(-1) as i32, + entities: 0, + fail: f["fail"].as_i64().unwrap() as i32, + entity_fail: f["entity_fail"].as_i64().unwrap() as i32, + }; + let p = std::array::from_fn(|i| f["position"][i].as_i64().unwrap() as i32); + match survival.can_survive( + &mut world, + BlockStateId(f["state"].as_u64().unwrap() as u32), + p, + ) { + Ok(value) => writeln!(world.out, "survive {value}")?, + Err(_) => writeln!(world.out, "survive error")?, + } + writeln!( + world.out, + "counts {} {} {} {}", + world.reads, world.entities, world.lights, world.fluid_calls + )?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/examples/bulk_section_fixture.rs b/crates/horizon-world/examples/bulk_section_fixture.rs new file mode 100644 index 000000000..b9be692a7 --- /dev/null +++ b/crates/horizon-world/examples/bulk_section_fixture.rs @@ -0,0 +1,209 @@ +use horizon_world::worldgen::{ + anchor::WorldGenerationContext, bulk_section::TerrainBulkAccess, feature_region::TerrainRegion, +}; +// Feature chains against a resident multi-chunk region. +use horizon_core::position::ChunkPos; +use horizon_world::{ + DATA_VERSION, + heightmap::{HeightmapState, HeightmapType}, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + worldgen::{ + tags::TagDefinitions, + terrain::{PreLightChunkStage, TerrainBlockStates, TerrainChunk}, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeSet, + fs, + io::{self, Write}, + path::Path, +}; +#[derive(Clone, Copy)] +struct State { + air: bool, + air_block: bool, + fluid: bool, + motion: bool, + no_leaves: bool, +} +impl HeightmapState for State { + fn is_air(self) -> bool { + self.air + } + fn is_air_block(self) -> bool { + self.air_block + } + fn has_fluid(self) -> bool { + self.fluid + } + fn blocks_motion_in_heightmap(self) -> bool { + self.motion + } + fn blocks_motion_in_heightmap_no_leaves(self) -> bool { + self.no_leaves + } +} +struct Properties<'a>(&'a [State]); +impl TerrainBlockStates for Properties<'_> { + type State = State; + fn heightmap_state(&self, id: BlockStateId) -> State { + self.0[id.0 as usize] + } +} +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + _ => panic!("unsupported registry fixture value"), + } +} +fn fixture( + f: &Value, + registry: &BlockRegistry, + states: &[State], + out: &mut impl Write, +) -> Result<(), Box> { + let minimum = n(&f["min"]); + let height = n(&f["height"]); + let mut chunks = Vec::new(); + for p in f["chunks"].as_array().unwrap() { + let mut chunk = TerrainChunk::new( + ChunkPos::new(n(&p[0]), n(&p[1])), + minimum, + height, + registry, + Properties(states), + )?; + chunk.set_generation_stage(PreLightChunkStage::Terrain); + if f["prime"].as_bool().unwrap() { + chunk.prime_heightmaps(&HeightmapType::ALL)?; + } + chunks.push(chunk); + } + let mut region = TerrainRegion::new(chunks, WorldGenerationContext::new(minimum, height, 0))?; + let mut bulk = TerrainBulkAccess::new(&mut region)?; + for op in f["ops"].as_array().unwrap() { + if op[0].as_str() == Some("reset") { + drop(bulk); + bulk = TerrainBulkAccess::new(&mut region)?; + writeln!(out, "reset")?; + writeln!(out, "cache 0")?; + continue; + } + let result = (|| -> Result<(), Box> { + match op[0].as_str().unwrap() { + "height" => { + let kind = HeightmapType::ALL + .into_iter() + .find(|k| k.name() == op[1].as_str().unwrap()) + .unwrap(); + writeln!(out, "height {}", bulk.height(kind, n(&op[2]), n(&op[3]))?)?; + } + kind => { + let p = [n(&op[1]), n(&op[2]), n(&op[3])]; + match kind { + "get" => writeln!(out, "get {}", bulk.block(p)?.0)?, + "world" => writeln!(out, "world {}", bulk.world_block(p)?.0)?, + "has" => writeln!(out, "has {}", bulk.has_section(p)?)?, + "set" => match bulk.set_block(p, BlockStateId(n(&op[4]) as u32))? { + Some(old) => writeln!(out, "set {}", old.0)?, + None => writeln!(out, "set none")?, + }, + _ => panic!("unknown operation"), + } + } + } + Ok(()) + })(); + if result.is_err() { + writeln!(out, "error")?; + } + writeln!(out, "cache {}", bulk.acquired_section_count())?; + } + drop(bulk); + for chunk in region.chunks() { + writeln!(out, "chunk {} {}", chunk.position().x, chunk.position().z)?; + for kind in HeightmapType::ALL { + if let Some(map) = chunk.heightmap(kind) { + writeln!(out, "map {}", kind.name())?; + for word in map.raw_data() { + writeln!(out, "{word:x}")?; + } + } else { + writeln!(out, "missing {}", kind.name())?; + } + } + for i in 0..height / 16 { + writeln!(out, "section {i}")?; + for index in 0..4096 { + writeln!(out, "{}", chunk.section(i as usize).unwrap().get(index)?.0)?; + } + } + } + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List( + facts["states"] + .as_array() + .unwrap() + .iter() + .map(|s| tag(&s[4])) + .collect(), + ), + ), + ("defaults", tag(&facts["defaults"])), + ]))?; + let mut definitions = TagDefinitions::default(); + for (name, text) in bundle.as_object().unwrap() { + definitions.apply_json(name, "vanilla", text.as_str().unwrap())?; + } + let built = definitions.build(|id, _| facts["defaults"].get(id).map(|_| id.to_owned()))?; + assert!(built.missing.is_empty()); + let motion: BTreeSet<_> = built.tags["minecraft:blocks_motion_in_heightmap"] + .iter() + .map(String::as_str) + .collect(); + let no_leaves: BTreeSet<_> = built.tags["minecraft:blocks_motion_in_heightmap_no_leaves"] + .iter() + .map(String::as_str) + .collect(); + let states: Vec<_> = facts["states"] + .as_array() + .unwrap() + .iter() + .map(|a| { + let name = a[0].as_str().unwrap(); + State { + air: a[1].as_bool().unwrap(), + air_block: name == "minecraft:air", + fluid: a[2].as_bool().unwrap(), + motion: motion.contains(name), + no_leaves: no_leaves.contains(name), + } + }) + .collect(); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + fixture(&serde_json::from_str(line)?, ®istry, &states, &mut out)?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/examples/canyon_carver_fixture.rs b/crates/horizon-world/examples/canyon_carver_fixture.rs new file mode 100644 index 000000000..023ffa356 --- /dev/null +++ b/crates/horizon-world/examples/canyon_carver_fixture.rs @@ -0,0 +1,99 @@ +//! Transport for decoded canyon paths, ordered mask writes and RNG continuation. +use horizon_core::{ + carving::{CarverOutput, CarvingMask}, + position::ChunkPos, + random::{LegacyRandom, RandomSource, XoroshiroRandom}, +}; +use horizon_world::worldgen::{anchor::WorldGenerationContext, carver::CanyonCarver}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +struct Output<'a, W: Write> { + mask: &'a mut CarvingMask, + out: &'a mut W, + calls: i32, + fail: i32, +} +impl CarverOutput for Output<'_, W> { + type Error = (); + fn min_y(&self) -> i32 { + self.mask.min_y() + } + fn max_y(&self) -> i32 { + self.mask.max_y() + } + fn carve(&mut self, x: i32, y: i32, z: i32) -> Result<(), ()> { + writeln!(self.out, "cell {x} {y} {z}").unwrap(); + let previous = self.calls; + self.calls += 1; + if previous == self.fail { + return Err(()); + } + self.mask.carve(x, y, z).unwrap(); + Ok(()) + } +} +fn fixture( + f: &Value, + mut random: impl RandomSource, + out: &mut impl Write, +) -> Result<(), Box> { + let c = &f["context"]; + let context = WorldGenerationContext::new(n(&c[0]), n(&c[1]), n(&c[2])); + match CanyonCarver::from_json(f["definition"].as_str().unwrap()) { + Ok(carver) => { + writeln!(out, "decode ok")?; + let mut mask = CarvingMask::new(context.min_y + 1, context.min_y + context.height - 8)?; + let target = ChunkPos::new(n(&f["target"][0]), n(&f["target"][1])); + let origin = ChunkPos::new(n(&f["origin"][0]), n(&f["origin"][1])); + for _ in 0..n(&f["repeats"]) { + writeln!(out, "start {}", carver.is_start_chunk(&mut random))?; + let mut output = Output { + mask: &mut mask, + out, + calls: 0, + fail: n(&f["fail"]), + }; + let result = carver.carve(context, &mut random, target, origin, &mut output); + let calls = output.calls; + writeln!( + out, + "carve {} {calls}", + match result { + Ok(true) => "true", + Ok(false) => "false", + Err(_) => "error", + } + )?; + for c in mask.columns() { + writeln!(out, "column {} {} {} {}", c.x, c.z, c.min_y, c.max_y)?; + } + writeln!(out, "next {}", random.next_long())?; + } + } + Err(_) => writeln!(out, "decode error")?, + } + writeln!(out, "tail {}", random.next_long())?; + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, LegacyRandom::new(seed), &mut out)?; + } else { + fixture(&f, XoroshiroRandom::new(seed), &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/carving_geometry_fixture.rs b/crates/horizon-world/examples/carving_geometry_fixture.rs new file mode 100644 index 000000000..1f0ce0ea2 --- /dev/null +++ b/crates/horizon-world/examples/carving_geometry_fixture.rs @@ -0,0 +1,119 @@ +//! Transport for shared cave/canyon geometry and ordered output failures. +use horizon_core::{ + carving::{CarverOutput, CarvingMask, can_reach, carve_ellipsoid}, + position::ChunkPos, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +fn d(v: &Value) -> f64 { + f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} +fn bits(v: f64) -> u64 { + if v.is_nan() { + 0x7ff8000000000000 + } else { + v.to_bits() + } +} +struct Output<'a> { + mask: &'a mut CarvingMask, + trace: &'a std::cell::RefCell>, + calls: i32, + fail: i32, +} +impl CarverOutput for Output<'_> { + type Error = (); + fn min_y(&self) -> i32 { + self.mask.min_y() + } + fn max_y(&self) -> i32 { + self.mask.max_y() + } + fn carve(&mut self, x: i32, y: i32, z: i32) -> Result<(), ()> { + self.trace.borrow_mut().push(format!("cell {x} {y} {z}")); + let previous = self.calls; + self.calls += 1; + if previous == self.fail { + return Err(()); + } + self.mask.carve(x, y, z).unwrap(); + Ok(()) + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let chunk = ChunkPos::new(n(&f["chunk"][0]), n(&f["chunk"][1])); + let mut mask = CarvingMask::new(n(&f["min"]), n(&f["max"]))?; + for e in f["ellipsoids"].as_array().unwrap() { + let trace = std::cell::RefCell::new(Vec::new()); + let mut output = Output { + mask: &mut mask, + trace: &trace, + calls: 0, + fail: n(&e["fail"]), + }; + let result = carve_ellipsoid( + chunk, + [d(&e["center"][0]), d(&e["center"][1]), d(&e["center"][2])], + d(&e["horizontal"]), + d(&e["vertical"]), + &mut output, + |[x, y, z], by| { + let skip = match n(&e["skip"]) { + 0 => x * x + y * y + z * z >= 1., + 1 => y <= -0.7 || x * x + y * y + z * z >= 1., + 2 => by.rem_euclid(3) == 0, + _ => false, + }; + trace.borrow_mut().push(format!( + "skip {:x} {:x} {:x} {by} {skip}", + bits(x), + bits(y), + bits(z) + )); + skip + }, + ); + let calls = output.calls; + for event in trace.into_inner() { + writeln!(out, "{event}")?; + } + writeln!( + out, + "ellipsoid {} {calls}", + if result.is_ok() { "ok" } else { "error" } + )?; + for c in mask.columns() { + writeln!(out, "column {} {} {} {}", c.x, c.z, c.min_y, c.max_y)?; + } + } + } + for line in fs::read_to_string(dir.join("reach.txt"))?.lines() { + let q: Value = serde_json::from_str(line)?; + let thickness = f32::from_bits(u32::from_str_radix(q[6].as_str().unwrap(), 16)?); + writeln!( + out, + "reach {}", + can_reach( + ChunkPos::new(n(&q[0]), n(&q[1])), + d(&q[2]), + d(&q[3]), + n(&q[4]), + n(&q[5]), + thickness + ) + )?; + } + Ok(()) +} diff --git a/crates/horizon-world/examples/carving_mask_fixture.rs b/crates/horizon-world/examples/carving_mask_fixture.rs new file mode 100644 index 000000000..c7675ce47 --- /dev/null +++ b/crates/horizon-world/examples/carving_mask_fixture.rs @@ -0,0 +1,76 @@ +//! Transport for native carving-mask traversal and callback mutation behavior. +use horizon_core::carving::CarvingMask; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let mut mask = CarvingMask::new(n(&f["min"]), n(&f["max"]))?; + writeln!(out, "mask {} {}", mask.min_y(), mask.max_y())?; + for op in f["ops"].as_array().unwrap() { + match op["kind"].as_str().unwrap() { + "carve" => { + let q = &op["pos"]; + let ok = mask.carve(n(&q[0]), n(&q[1]), n(&q[2])).is_ok(); + writeln!(out, "carve {}", if ok { "ok" } else { "error" })?; + } + "fill" => { + let b = &op["box"]; + let mut calls = 0; + for x in n(&b[0])..=n(&b[1]) { + for z in n(&b[4])..=n(&b[5]) { + for y in n(&b[2])..=n(&b[3]) { + mask.carve(x, y, z)?; + calls += 1; + } + } + } + writeln!(out, "fill {calls}")?; + } + "visit" => { + let mut calls = 0; + let result = mask.try_visit_mut(|mask, c| { + writeln!(out, "column {} {} {} {}", c.x, c.z, c.min_y, c.max_y).unwrap(); + let previous = calls; + calls += 1; + if let Some(points) = op["add"].get(previous.to_string()) { + for q in points.as_array().unwrap() { + let ok = mask.carve(n(&q[0]), n(&q[1]), n(&q[2])).is_ok(); + writeln!(out, "add {}", if ok { "ok" } else { "error" }).unwrap(); + } + } + if previous == n(&op["fail"]) { + Err(()) + } else { + Ok(()) + } + }); + writeln!( + out, + "visit {} {calls}", + if result.is_ok() { "ok" } else { "error" } + )?; + } + "read" => { + for c in mask.columns() { + writeln!(out, "column {} {} {} {}", c.x, c.z, c.min_y, c.max_y)?; + } + writeln!(out, "read")?; + } + _ => unreachable!(), + } + writeln!(out, "empty {}", mask.is_empty())?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/cave_carver_fixture.rs b/crates/horizon-world/examples/cave_carver_fixture.rs new file mode 100644 index 000000000..ad0d37612 --- /dev/null +++ b/crates/horizon-world/examples/cave_carver_fixture.rs @@ -0,0 +1,99 @@ +//! Transport for decoded cave paths, ordered mask writes and RNG continuation. +use horizon_core::{ + carving::{CarverOutput, CarvingMask}, + position::ChunkPos, + random::{LegacyRandom, RandomSource, XoroshiroRandom}, +}; +use horizon_world::worldgen::{anchor::WorldGenerationContext, carver::CaveCarver}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +struct Output<'a, W: Write> { + mask: &'a mut CarvingMask, + out: &'a mut W, + calls: i32, + fail: i32, +} +impl CarverOutput for Output<'_, W> { + type Error = (); + fn min_y(&self) -> i32 { + self.mask.min_y() + } + fn max_y(&self) -> i32 { + self.mask.max_y() + } + fn carve(&mut self, x: i32, y: i32, z: i32) -> Result<(), ()> { + writeln!(self.out, "cell {x} {y} {z}").unwrap(); + let previous = self.calls; + self.calls += 1; + if previous == self.fail { + return Err(()); + } + self.mask.carve(x, y, z).unwrap(); + Ok(()) + } +} +fn fixture( + f: &Value, + mut random: impl RandomSource, + out: &mut impl Write, +) -> Result<(), Box> { + let c = &f["context"]; + let context = WorldGenerationContext::new(n(&c[0]), n(&c[1]), n(&c[2])); + match CaveCarver::from_json(f["definition"].as_str().unwrap()) { + Ok(carver) => { + writeln!(out, "decode ok")?; + let mut mask = CarvingMask::new(context.min_y + 1, context.min_y + context.height - 8)?; + let target = ChunkPos::new(n(&f["target"][0]), n(&f["target"][1])); + let origin = ChunkPos::new(n(&f["origin"][0]), n(&f["origin"][1])); + for _ in 0..n(&f["repeats"]) { + writeln!(out, "start {}", carver.is_start_chunk(&mut random))?; + let mut output = Output { + mask: &mut mask, + out, + calls: 0, + fail: n(&f["fail"]), + }; + let result = carver.carve(context, &mut random, target, origin, &mut output); + let calls = output.calls; + writeln!( + out, + "carve {} {calls}", + match result { + Ok(true) => "true", + Ok(false) => "false", + Err(_) => "error", + } + )?; + for c in mask.columns() { + writeln!(out, "column {} {} {} {}", c.x, c.z, c.min_y, c.max_y)?; + } + writeln!(out, "next {}", random.next_long())?; + } + } + Err(_) => writeln!(out, "decode error")?, + } + writeln!(out, "tail {}", random.next_long())?; + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, LegacyRandom::new(seed), &mut out)?; + } else { + fixture(&f, XoroshiroRandom::new(seed), &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/chunk_stage_fixture.rs b/crates/horizon-world/examples/chunk_stage_fixture.rs new file mode 100644 index 000000000..874b84f5f --- /dev/null +++ b/crates/horizon-world/examples/chunk_stage_fixture.rs @@ -0,0 +1,212 @@ +//! Test transport for pre-light ProtoChunk writes and stage heightmap transitions. +use horizon_core::position::ChunkPos; +use horizon_world::{ + DATA_VERSION, + heightmap::{HeightmapState, HeightmapType}, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + worldgen::{ + tags::TagDefinitions, + terrain::{PreLightChunkStage, TerrainBlockStates, TerrainChunk}, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeSet, + fs, + io::{self, Write}, + path::Path, +}; +#[derive(Clone, Copy)] +struct State { + air: bool, + air_block: bool, + fluid: bool, + motion: bool, + no_leaves: bool, +} +impl HeightmapState for State { + fn is_air(self) -> bool { + self.air + } + fn is_air_block(self) -> bool { + self.air_block + } + fn has_fluid(self) -> bool { + self.fluid + } + fn blocks_motion_in_heightmap(self) -> bool { + self.motion + } + fn blocks_motion_in_heightmap_no_leaves(self) -> bool { + self.no_leaves + } +} +struct Properties<'a>(&'a [State]); +impl TerrainBlockStates for Properties<'_> { + type State = State; + fn heightmap_state(&self, id: BlockStateId) -> State { + self.0[id.0 as usize] + } +} +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + _ => panic!("unsupported registry fixture value"), + } +} +fn fixture( + f: &Value, + registry: &BlockRegistry, + states: &[State], + out: &mut impl Write, +) -> Result<(), Box> { + let mut chunk = TerrainChunk::new( + ChunkPos::new(n(&f["chunk"][0]), n(&f["chunk"][1])), + n(&f["min"]), + n(&f["height"]), + registry, + Properties(states), + )?; + writeln!( + out, + "chunk {} {} {} {}", + n(&f["chunk"][0]), + n(&f["chunk"][1]), + chunk.min_y(), + chunk.height() + )?; + for op in f["ops"].as_array().unwrap() { + match op[0].as_str().unwrap() { + "stage" => { + let stage = PreLightChunkStage::ALL + .into_iter() + .find(|s| s.name() == op[1].as_str().unwrap()) + .unwrap(); + chunk.set_generation_stage(stage); + writeln!(out, "stage {}", chunk.generation_stage().name())?; + } + "set" => { + let previous = chunk.set_block_worldgen( + n(&op[1]), + n(&op[2]), + n(&op[3]), + BlockStateId(n(&op[4]) as u32), + )?; + writeln!(out, "set {}", previous.0)?; + } + "get" => writeln!( + out, + "get {}", + chunk.block(n(&op[1]), n(&op[2]), n(&op[3])).0 + )?, + "prime" => { + let kinds: Vec<_> = HeightmapType::ALL + .into_iter() + .enumerate() + .filter_map(|(i, k)| (n(&op[1]) & (1 << i) != 0).then_some(k)) + .collect(); + chunk.prime_heightmaps(&kinds)?; + writeln!(out, "prime {}", n(&op[1]))?; + } + "query" => { + for kind in HeightmapType::ALL { + if let Some(map) = chunk.heightmap(kind) { + writeln!( + out, + "height {} {}", + kind.name(), + map.first_available(n(&op[1]) & 15, n(&op[2]) & 15)? + )?; + } else { + writeln!(out, "missing {}", kind.name())?; + } + } + } + "dump" => { + for kind in HeightmapType::ALL { + if let Some(map) = chunk.heightmap(kind) { + writeln!(out, "map {}", kind.name())?; + for word in map.raw_data() { + writeln!(out, "{word:x}")?; + } + } else { + writeln!(out, "missing {}", kind.name())?; + } + } + for i in 0..chunk.height() / 16 { + writeln!(out, "section {i}")?; + for index in 0..4096 { + writeln!(out, "{}", chunk.section(i as usize).unwrap().get(index)?.0)?; + } + } + } + _ => panic!("unknown operation"), + } + } + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List( + facts["states"] + .as_array() + .unwrap() + .iter() + .map(|s| tag(&s[4])) + .collect(), + ), + ), + ("defaults", tag(&facts["defaults"])), + ]))?; + let mut definitions = TagDefinitions::default(); + for (name, text) in bundle.as_object().unwrap() { + definitions.apply_json(name, "vanilla", text.as_str().unwrap())?; + } + let built = definitions.build(|id, _| facts["defaults"].get(id).map(|_| id.to_owned()))?; + assert!(built.missing.is_empty()); + let motion: BTreeSet<_> = built.tags["minecraft:blocks_motion_in_heightmap"] + .iter() + .map(String::as_str) + .collect(); + let no_leaves: BTreeSet<_> = built.tags["minecraft:blocks_motion_in_heightmap_no_leaves"] + .iter() + .map(String::as_str) + .collect(); + let states: Vec<_> = facts["states"] + .as_array() + .unwrap() + .iter() + .map(|a| { + let name = a[0].as_str().unwrap(); + State { + air: a[1].as_bool().unwrap(), + air_block: name == "minecraft:air", + fluid: a[2].as_bool().unwrap(), + motion: motion.contains(name), + no_leaves: no_leaves.contains(name), + } + }) + .collect(); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + fixture(&serde_json::from_str(line)?, ®istry, &states, &mut out)?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/examples/collision_fixture.rs b/crates/horizon-world/examples/collision_fixture.rs new file mode 100644 index 000000000..95c7ad73c --- /dev/null +++ b/crates/horizon-world/examples/collision_fixture.rs @@ -0,0 +1,199 @@ +//! Queries imported cached shapes through resident section state IDs. +use horizon_core::{ + geometry::{Aabb, Axis, Vec3}, + position::BlockPos, +}; +use horizon_world::{ + chunk::BlockSection, + collision::CachedCollisionRegistry, + nbt::{self, Limits, Tag}, + registry::{BlockRegistry, BlockStateId}, +}; +use std::{ + error::Error, + fs, + io::{BufRead, Write}, + path::PathBuf, +}; + +fn bits(value: f64) -> u64 { + if value.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + value.to_bits() + } +} +fn values( + out: &mut impl Write, + label: &str, + numbers: impl IntoIterator, +) -> std::io::Result<()> { + write!(out, "{label}")?; + for value in numbers { + write!(out, " {:016x}", bits(value))?; + } + writeln!(out) +} +fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> std::io::Result<()> { + values( + out, + label, + b.min_position() + .components() + .into_iter() + .chain(b.max_position().components()), + ) +} +struct Input<'a>(std::str::SplitWhitespace<'a>); +impl Input<'_> { + fn integer(&mut self) -> i32 { + self.0.next().unwrap().parse().unwrap() + } + fn number(&mut self) -> f64 { + f64::from_bits(u64::from_str_radix(self.0.next().unwrap(), 16).unwrap()) + } + fn vector(&mut self) -> Vec3 { + Vec3::new(self.number(), self.number(), self.number()) + } +} +fn main() -> Result<(), Box> { + let base = PathBuf::from( + std::env::args() + .nth(1) + .ok_or("fixture directory required")?, + ); + let (registry_root, _) = nbt::read_named( + &fs::read(base.join("block-registry.nbt"))?, + Limits::default(), + )?; + let registry = BlockRegistry::from_nbt(®istry_root.tag)?; + let (root, _) = nbt::read_named( + &fs::read(base.join("cached-collision.nbt"))?, + Limits::default(), + )?; + let collisions = CachedCollisionRegistry::from_nbt(&root.tag, ®istry)?; + let mut section = BlockSection::uniform(BlockStateId(0), ®istry)?; + let mut out = std::io::BufWriter::new(fs::File::create(base.join("rust.txt"))?); + let mut identities = std::collections::HashMap::new(); + for id in 0..registry.len() { + let index = id % 4096; + section.set(index, BlockStateId(id as u32))?; + match collisions.section_shape(§ion, index)? { + None => writeln!(out, "state {id} uncached")?, + Some(shape) => { + writeln!(out, "state {id} cached {}", shape.boxes().len())?; + let count = identities.len(); + let identity = *identities.entry(std::ptr::from_ref(shape)).or_insert(count); + writeln!(out, "identity {identity}")?; + let flags = shape.cube_coordinate_axes(); + writeln!( + out, + "cube {} {}", + u8::from(shape.is_cube()), + u8::from(flags[0]) + 2 * u8::from(flags[1]) + 4 * u8::from(flags[2]) + )?; + values( + &mut out, + "axis-extrema", + Axis::ALL + .map(|axis| shape.min(axis)) + .into_iter() + .chain(Axis::ALL.map(|axis| shape.max(axis))), + )?; + if let Some(b) = shape.bounds() { + box_values(&mut out, "bounds", b)?; + } else { + writeln!(out, "bounds none")?; + } + for b in shape.boxes() { + box_values(&mut out, "part", *b)?; + } + } + } + } + let other_registry = BlockRegistry::from_nbt(®istry_root.tag)?; + let other_section = BlockSection::uniform(BlockStateId(0), &other_registry)?; + assert!(collisions.section_shape(&other_section, 0).is_err()); + assert!( + collisions + .cached_shape(BlockStateId(registry.len() as u32)) + .is_err() + ); + assert!(collisions.section_shape(§ion, 4096).is_err()); + // Import failures must not create a usable partial collision registry. + let mut corrupt = root.tag.clone(); + *corrupt.get_mut("DataVersion").unwrap() = Tag::Int(0); + assert!(CachedCollisionRegistry::from_nbt(&corrupt, ®istry).is_err()); + let mut corrupt = root.tag.clone(); + let Some(Tag::IntArray(mapping)) = corrupt.get_mut("cached_shapes") else { + unreachable!() + }; + mapping[0] = -2; + assert!(CachedCollisionRegistry::from_nbt(&corrupt, ®istry).is_err()); + let mut corrupt = root.tag.clone(); + let Some(Tag::List(states)) = corrupt.get_mut("states") else { + unreachable!() + }; + states.swap(0, 1); + assert!(CachedCollisionRegistry::from_nbt(&corrupt, ®istry).is_err()); + let mut count = 0; + for line in std::io::BufReader::new(fs::File::open(base.join("inputs.txt"))?).lines() { + let line = line?; + let mut input = Input(line.split_whitespace()); + let id = input.integer(); + let block = BlockPos::new(input.integer(), input.integer(), input.integer()); + let b = Aabb::new(input.vector(), input.vector()); + let start = input.vector(); + let end = input.vector(); + let point = input.vector(); + let amount = input.number(); + section.set(count % 4096, BlockStateId(id as u32))?; + let shape = collisions + .section_shape(§ion, count % 4096)? + .ok_or("query used uncached state")?; + let moved = shape.moved(Vec3::from_block(block)); + values( + &mut out, + "collide", + Axis::ALL.map(|axis| moved.collide(axis, b, amount)), + )?; + if let Some(h) = shape.clip(start, end, block) { + writeln!( + out, + "hit {} {} {:016x} {:016x} {:016x}", + h.direction as u8, + u8::from(h.inside), + bits(h.location.x), + bits(h.location.y), + bits(h.location.z) + )?; + } else { + writeln!(out, "hit none")?; + } + if let Some(p) = moved.closest_point(point) { + values(&mut out, "closest", p.components())?; + } else { + writeln!(out, "closest none")?; + } + writeln!( + out, + "index {} {} {}", + moved.find_index(Axis::X, point.x), + moved.find_index(Axis::Y, point.y), + moved.find_index(Axis::Z, point.z) + )?; + assert!(input.0.next().is_none()); + count += 1; + } + out.flush()?; + println!( + "HORIZON_COLLISION_RESULT {{\"registry_states\":{},\"cached_states\":{},\"uncached_states\":{},\"unique_shapes\":{},\"unique_grids\":{},\"queries\":{}}}", + registry.len(), + collisions.cached_state_count(), + registry.len() - collisions.cached_state_count(), + collisions.shape_count(), + collisions.unique_grid_count(), + count + ); + Ok(()) +} diff --git a/crates/horizon-world/examples/decoration_fixture.rs b/crates/horizon-world/examples/decoration_fixture.rs new file mode 100644 index 000000000..57c33d24b --- /dev/null +++ b/crates/horizon-world/examples/decoration_fixture.rs @@ -0,0 +1,211 @@ +use horizon_core::{position::ChunkPos, random::RandomSource}; +use horizon_world::{ + heightmap::HeightmapType, + worldgen::{ + anchor::WorldGenerationContext, + decoration::{DecorationBiome, DecorationWorld, FeatureDecorationPlan}, + feature_sort::FeatureIdentity, + placement::{PlacementContext, PlacementModifier, PlacementQueryError}, + }, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +struct World<'a, W> { + f: &'a Value, + out: &'a mut W, + biomes: &'a [Vec>], + calls: i32, + queries: i32, + notifications: i32, + chunks_read: i32, +} +impl DecorationWorld for World<'_, W> { + type Error = (); + fn min_section_y(&mut self) -> Result { + Ok(n(&self.f["min"]) >> 4) + } + fn chunk_biomes(&mut self, chunk: ChunkPos) -> Result, ()> { + writeln!(self.out, "chunk {} {}", chunk.x, chunk.z).map_err(|_| ())?; + let call = self.chunks_read; + self.chunks_read += 1; + if call == n(&self.f["chunk_fail"]) { + return Err(()); + } + let dx = chunk.x.wrapping_sub(n(&self.f["cx"])); + let dz = chunk.z.wrapping_sub(n(&self.f["cz"])); + let values = self.f["palettes"][((dz + 1) * 3 + dx + 1) as usize] + .as_array() + .unwrap(); + // The native fixture fills every quart cell from this repeating sequence. + // Only cells actually present in the chunk count as resident biomes. + Ok((0..n(&self.f["height"]) * 4) + .map(|i| DecorationBiome(n(&values[i as usize % values.len()]) as u32)) + .collect()) + } + fn set_currently_generating(&mut self, feature: Option) -> Result<(), ()> { + match feature { + Some(id) => writeln!( + self.out, + "generating ResourceKey[minecraft:worldgen/placed_feature / horizon:f{}]", + id.0 + ), + None => writeln!(self.out, "generating none"), + } + .map_err(|_| ())?; + let call = self.notifications; + self.notifications += 1; + if call == n(&self.f["notify_fail"]) { + Err(()) + } else { + Ok(()) + } + } +} +impl PlacementContext for World<'_, W> { + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new(-64, 384, 63) + } + fn min_y(&mut self) -> Result { + Ok(n(&self.f["min"])) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + Err(PlacementQueryError::Unavailable) + } + fn biome_allows_feature( + &mut self, + p: [i32; 3], + feature: FeatureIdentity, + ) -> Result { + let index = p[0] + .wrapping_mul(31) + .wrapping_add(p[1].wrapping_mul(7)) + .wrapping_add(p[2].wrapping_mul(17)) + .wrapping_add(n(&self.f["biome_offset"])) + .rem_euclid(self.biomes.len() as i32 + 1) as usize; + writeln!(self.out, "biome {} {} {} {}", p[0], p[1], p[2], index) + .map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + let call = self.queries; + self.queries += 1; + if call == n(&self.f["query_fail"]) { + return Err(PlacementQueryError::Unavailable); + } + Ok(self + .biomes + .get(index) + .is_some_and(|steps| steps.iter().flatten().any(|id| *id == feature))) + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let biomes = f["biomes"] + .as_array() + .unwrap() + .iter() + .map(|b| { + b.as_array() + .unwrap() + .iter() + .map(|s| { + s.as_array() + .unwrap() + .iter() + .map(|id| FeatureIdentity(n(id) as u32)) + .collect::>() + }) + .collect::>() + }) + .collect::>(); + let plan = FeatureDecorationPlan::new( + biomes + .iter() + .enumerate() + .map(|(i, b)| (DecorationBiome(i as u32), b.clone())) + .collect(), + ); + let Ok(plan) = plan else { + writeln!(out, "plan error")?; + continue; + }; + writeln!(out, "plan ok")?; + let placements = f["placements"] + .as_array() + .unwrap() + .iter() + .map(|p| { + p.as_array() + .unwrap() + .iter() + .map(|m| PlacementModifier::from_json(&m.to_string())) + .collect::, _>>() + }) + .collect::, _>>()?; + let mut world = World { + f: &f, + out: &mut out, + biomes: &biomes, + calls: 0, + queries: 0, + notifications: 0, + chunks_read: 0, + }; + for _ in 0..2 { + world.calls = 0; + world.queries = 0; + world.notifications = 0; + world.chunks_read = 0; + let result = plan.decorate_features( + &mut world, + ChunkPos::new(n(&f["cx"]), n(&f["cz"])), + f["seed"].as_i64().unwrap(), + |w, placer, rng, id, origin| { + placer + .place_with_biome_check( + &placements[id.0 as usize], + w, + rng, + origin, + id, + |w, r, p| { + writeln!(w.out, "feature {} {} {} {}", id.0, p[0], p[1], p[2]) + .map_err(|_| ())?; + writeln!( + w.out, + "draw {} {} {:x} {:x}", + r.next_long(), + r.next_int_bound(17).unwrap(), + r.next_float().to_bits(), + r.next_double().to_bits() + ) + .map_err(|_| ())?; + let call = w.calls; + w.calls += 1; + if call == n(&w.f["feature_fail"]) { + return Err(()); + } + Ok(n(&w.f["return_mode"]) == 0 + || (n(&w.f["return_mode"]) == 2 && id.0 % 2 == 0)) + }, + ) + .map_err(|_| ()) + }, + ); + writeln!( + world.out, + "decorate {}", + if result.is_ok() { "ok" } else { "error" } + )?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/decoration_region_fixture.rs b/crates/horizon-world/examples/decoration_region_fixture.rs new file mode 100644 index 000000000..db1fb4206 --- /dev/null +++ b/crates/horizon-world/examples/decoration_region_fixture.rs @@ -0,0 +1,304 @@ +#[path = "support/decoration_storage.rs"] +mod storage; +use horizon_core::{ + biome::obfuscate_seed, + position::{BlockPos, ChunkPos}, +}; +use horizon_world::{ + heightmap::HeightmapType, + registry::{BlockRegistry, BlockStateId}, + worldgen::{ + anchor::WorldGenerationContext, + biome_chunk::{BiomeChunk, BiomeRegion}, + biome_predicate::BiomePredicateBindings, + block_feature::FeatureBlockBindings, + decoration::{DecorationBiome, DecorationWorld, FeatureDecorationPlan}, + feature::{FeatureBlocks, FeatureWorld}, + feature_graph::FeatureDefinition, + feature_region::TerrainRegion, + feature_sort::FeatureIdentity, + placement::{LayerBlock, PlacementContext, PlacementModifier, PlacementQueryError}, + terrain::{PreLightChunkStage, TerrainChunk}, + }, +}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + io::{self, Write}, + path::Path, + sync::Arc, +}; +use storage::{Properties, State}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +struct World<'a, W> { + out: &'a mut W, + f: &'a Value, + region: TerrainRegion<'a, Properties<'a>>, + biomes: BiomeRegion, + settings: Vec>>, + writes: i32, +} +impl DecorationWorld for World<'_, W> { + type Error = (); + fn min_section_y(&mut self) -> Result { + Ok(n(&self.f["min"]) >> 4) + } + fn chunk_biomes(&mut self, p: ChunkPos) -> Result, ()> { + writeln!(self.out, "chunk {} {}", p.x, p.z).map_err(|_| ())?; + self.biomes.present_in_chunk(p).map_err(|_| ()) + } + fn set_currently_generating(&mut self, feature: Option) -> Result<(), ()> { + match feature { + Some(id) => writeln!( + self.out, + "generating ResourceKey[minecraft:worldgen/placed_feature / horizon:f{}]", + id.0 + ), + None => writeln!(self.out, "generating none"), + } + .map_err(|_| ()) + } +} +impl FeatureWorld for World<'_, W> { + type Error = (); + fn block(&mut self, p: [i32; 3]) -> Result { + self.region.block(p).map_err(|_| ()) + } + fn set_block(&mut self, p: [i32; 3], state: BlockStateId, flags: i32) -> Result { + writeln!( + self.out, + "write {} {} {} {} {flags}", + p[0], p[1], p[2], state.0 + ) + .map_err(|_| ())?; + let call = self.writes; + self.writes += 1; + if call == n(&self.f["write_fail"]) { + return Err(()); + } + let reject = n(&self.f["reject"]); + let result = reject == 0 || call % reject != 0; + if result { + self.region.set_block_worldgen(p, state).map_err(|_| ())?; + } + writeln!(self.out, "written {result}").map_err(|_| ())?; + Ok(result) + } +} +impl PlacementContext for World<'_, W> { + fn biome_identity(&mut self, p: [i32; 3]) -> Result { + let id = *self + .region + .biome_at(&self.biomes, BlockPos::new(p[0], p[1], p[2])) + .map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + writeln!(self.out, "biome {} {} {} {}", p[0], p[1], p[2], id.0) + .map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + Ok(id) + } + fn generation(&self) -> WorldGenerationContext { + self.region.generation() + } + fn min_y(&mut self) -> Result { + self.region.min_y() + } + fn max_y(&mut self) -> Result { + self.region.max_y() + } + fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result { + self.region.height(kind, x, z) + } + fn layer_block(&mut self, p: [i32; 3]) -> Result { + self.region.layer_block(p) + } + fn biome_allows_feature( + &mut self, + p: [i32; 3], + feature: FeatureIdentity, + ) -> Result { + let id = self.biome_identity(p)?; + Ok(self + .settings + .get(id.0 as usize) + .is_some_and(|b| b.iter().flatten().any(|v| *v == feature))) + } +} +fn fixture( + f: &Value, + registry: &BlockRegistry, + states: &[State], + out: &mut impl Write, +) -> Result<(), Box> { + let settings = f["biomes"] + .as_array() + .unwrap() + .iter() + .map(|b| { + b.as_array() + .unwrap() + .iter() + .map(|s| { + s.as_array() + .unwrap() + .iter() + .map(|id| FeatureIdentity(n(id) as u32)) + .collect::>() + }) + .collect::>() + }) + .collect::>(); + let plan = FeatureDecorationPlan::new( + settings + .iter() + .enumerate() + .map(|(i, b)| (DecorationBiome(i as u32), b.clone())) + .collect(), + )?; + writeln!(out, "plan ok")?; + let names = (0..=settings.len()) + .map(|i| (format!("horizon:b{i}"), DecorationBiome(i as u32))) + .collect::>(); + let biomes = Arc::new(BiomePredicateBindings::new(&names, &BTreeMap::new())?); + let bindings = FeatureBlockBindings::new(registry, BTreeSet::new())?.with_biomes(biomes); + let features = f["features"] + .as_array() + .unwrap() + .iter() + .map(|v| FeatureDefinition::from_json_with_blocks(&v.to_string(), &bindings)) + .collect::, _>>()?; + let placements = f["placements"] + .as_array() + .unwrap() + .iter() + .map(|p| { + p.as_array() + .unwrap() + .iter() + .map(|m| PlacementModifier::from_json_with_blocks(&m.to_string(), &bindings)) + .collect::, _>>() + }) + .collect::, _>>()?; + let blocks = FeatureBlocks::from_registry(registry)?; + let min = n(&f["min"]); + let height = n(&f["height"]); + let cp = ChunkPos::new(n(&f["cx"]), n(&f["cz"])); + let stage = PreLightChunkStage::ALL + .into_iter() + .find(|s| s.name() == f["stage"].as_str().unwrap()) + .unwrap(); + let mut chunks = Vec::new(); + let mut biome_chunks = Vec::new(); + for dz in -1..=1 { + for dx in -1..=1 { + let p = ChunkPos::new(cp.x + dx, cp.z + dz); + let mut chunk = TerrainChunk::new(p, min, height, registry, Properties(states))?; + chunk.set_generation_stage(stage); + for x in 0..16 { + for z in 0..16 { + chunk.set_block_worldgen( + (p.x << 4) + x, + -56, + (p.z << 4) + z, + registry.default_state("minecraft:stone").unwrap(), + )?; + if (x + z) % 3 != 0 { + chunk.set_block_worldgen( + (p.x << 4) + x, + -48, + (p.z << 4) + z, + registry.default_state("minecraft:dirt").unwrap(), + )?; + } + } + } + chunks.push(chunk); + let values = f["palettes"][((dz + 1) * 3 + dx + 1) as usize] + .as_array() + .unwrap(); + let mut biomes = + BiomeChunk::new(p, min, height, DecorationBiome(settings.len() as u32))?; + biomes.fill(min, min + height - 1, |[x, y, z]| { + let index = ((y - (min >> 2)) * 16 + (z & 3) * 4 + (x & 3)) + .rem_euclid(values.len() as i32) as usize; + Ok::<_, std::convert::Infallible>(DecorationBiome(n(&values[index]) as u32)) + })?; + biome_chunks.push(biomes); + } + } + let mut world = World { + out, + f, + region: TerrainRegion::new(chunks, WorldGenerationContext::new(-64, 384, 63))?, + biomes: BiomeRegion::new(biome_chunks, obfuscate_seed(f["seed"].as_i64().unwrap()))?, + settings, + writes: 0, + }; + for _ in 0..2 { + world.writes = 0; + let result = plan.decorate_features( + &mut world, + cp, + f["seed"].as_i64().unwrap(), + |w, placer, rng, id, origin| { + placer + .place_with_biome_check( + &placements[id.0 as usize], + w, + rng, + origin, + id, + |w, r, p| features[id.0 as usize].place(w, r, p, blocks), + ) + .map_err(|_| ()) + }, + ); + writeln!( + world.out, + "decorate {}", + if result.is_ok() { "ok" } else { "error" } + )?; + for [x, z] in [[0, 0], [15, 15], [16, 16], [-1, -1]] { + for kind in HeightmapType::ALL { + writeln!( + world.out, + "height {} {x} {z} {}", + kind.name(), + world.region.height(kind, x, z)? + )?; + } + } + } + for chunk in world.region.chunks() { + let p = chunk.position(); + writeln!(world.out, "stored {} {}", p.x, p.z)?; + for kind in HeightmapType::ALL { + if let Some(map) = chunk.heightmap(kind) { + writeln!(world.out, "map {}", kind.name())?; + for word in map.raw_data() { + writeln!(world.out, "{word:x}")?; + } + } else { + writeln!(world.out, "missing {}", kind.name())?; + } + } + for i in 0..height as usize / 16 { + writeln!(world.out, "section {i}")?; + for index in 0..4096 { + writeln!(world.out, "{}", chunk.section(i).unwrap().get(index)?.0)?; + } + } + } + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let (registry, states) = storage::load(dir)?; + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + fixture(&serde_json::from_str(line)?, ®istry, &states, &mut out)?; + } + Ok(()) +} diff --git a/crates/horizon-world/examples/dynamic_support_fixture.rs b/crates/horizon-world/examples/dynamic_support_fixture.rs new file mode 100644 index 000000000..a321f97d0 --- /dev/null +++ b/crates/horizon-world/examples/dynamic_support_fixture.rs @@ -0,0 +1,252 @@ +use horizon_core::geometry::{Aabb, Axis, Direction, VoxelShape}; +use horizon_world::{ + block_collision::{DynamicCollisionWorld, ShulkerCollisionState}, + block_support::SupportType, + chunk::BlockState, + collision::CachedCollisionRegistry, + dynamic_support::{DynamicSupport, DynamicSupportWorld}, + nbt::{self, Limits, Tag}, + piston_shape::{MovingPistonState, PistonBlockBindings, PistonCollisionWorld}, + registry::{BlockRegistry, BlockStateId}, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn values( + out: &mut impl Write, + label: &str, + values: impl IntoIterator, +) -> io::Result<()> { + write!(out, "{label}")?; + for v in values { + let bits = if v.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + v.to_bits() + }; + write!(out, " {bits:016x}")?; + } + writeln!(out) +} +fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { + values( + out, + label, + [ + b.min(Axis::X), + b.min(Axis::Y), + b.min(Axis::Z), + b.max(Axis::X), + b.max(Axis::Y), + b.max(Axis::Z), + ], + ) +} +fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { + writeln!( + out, + "shape {} {} {}", + shape.is_empty(), + shape.boxes().len(), + shape.is_cube() + )?; + for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { + values(out, name, shape.coordinates(axis).iter().copied())?; + } + let axes = shape.cube_coordinate_axes(); + writeln!( + out, + "axes {}", + u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) + )?; + values( + out, + "extrema", + Axis::ALL + .map(|a| shape.min(a)) + .into_iter() + .chain(Axis::ALL.map(|a| shape.max(a))), + )?; + match shape.bounds() { + Some(b) => box_values(out, "bounds", b)?, + None => writeln!(out, "bounds none")?, + } + for b in shape.boxes() { + box_values(out, "box", *b)?; + } + Ok(()) +} +struct World<'a, W> { + collisions: &'a CachedCollisionRegistry<'a>, + pistons: &'a PistonBlockBindings<'a>, + dynamic: &'a [Option], + active: Option, + noclip: Option, + out: &'a mut W, + entity: &'a str, + shulker: ShulkerCollisionState, + fail: i32, + calls: i32, +} +impl World<'_, W> { + fn query(&mut self, p: [i32; 3]) -> io::Result<()> { + writeln!(self.out, "entity {} {} {}", p[0], p[1], p[2])?; + let count = self.calls; + self.calls += 1; + if count == self.fail { + return Err(io::Error::other("injected block entity failure")); + } + Ok(()) + } +} +impl DynamicSupportWorld for World<'_, W> { + type Error = io::Error; + fn shulker_is_closed(&mut self, p: [i32; 3]) -> io::Result> { + self.query(p)?; + Ok(match self.entity { + "none" | "other" | "piston" => None, + "closed" => Some(true), + _ => Some(false), + }) + } + fn moving_piston_shape(&mut self, p: [i32; 3]) -> io::Result> { + self.query(p)?; + match self.active { + None => Ok(None), + Some(active) => { + let bindings = self.pistons; + bindings + .collision_shape(self, p, active, self.noclip) + .map(Some) + .map_err(io::Error::other) + } + } + } +} +impl DynamicCollisionWorld for World<'_, W> { + fn shulker_collision_state( + &mut self, + p: [i32; 3], + ) -> io::Result> { + self.query(p)?; + Ok(match self.entity { + "none" | "other" | "piston" => None, + _ => Some(self.shulker), + }) + } +} +impl PistonCollisionWorld for World<'_, W> { + type Error = io::Error; + fn collision_shape(&mut self, state: BlockStateId, p: [i32; 3]) -> io::Result { + if let Some(shape) = self.collisions.cached_shape(state)? { + return Ok(shape.clone()); + } + self.dynamic[state.0 as usize] + .as_ref() + .expect("known empty-context dynamic collision") + .clone() + .collision_shape(self, p) + .map_err(io::Error::other) + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts.json"))?)?; + let states = facts["states"] + .as_array() + .unwrap() + .iter() + .map(|value| BlockState { + name: value["id"].as_str().unwrap().to_owned(), + properties: value + .get("properties") + .and_then(Value::as_object) + .map(|p| { + p.iter() + .map(|(k, v)| (k.clone(), v.as_str().unwrap().to_owned())) + .collect() + }) + .unwrap_or_default(), + }) + .collect::>(); + let read = |name: &str| -> Result> { + Ok( + nbt::read_named(&fs::read(dir.join(name))?, Limits::default())? + .0 + .tag, + ) + }; + let registry = BlockRegistry::from_nbt(&read("block-registry.nbt")?)?; + let collisions = CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, ®istry)?; + let pistons = PistonBlockBindings::new(®istry)?; + let dynamic = states + .iter() + .map(DynamicSupport::from_state) + .collect::>>()?; + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let support = DynamicSupport::from_state(&states[f["state"].as_u64().unwrap() as usize])? + .ok_or("missing dynamic support selection")?; + let p = std::array::from_fn(|i| f["position"][i].as_i64().unwrap() as i32); + values(&mut out, "offset", support.offset(p).components())?; + let active = f.get("piston").map(|v| MovingPistonState { + moved_state: BlockStateId(v["state"].as_u64().unwrap() as u32), + direction: Direction::ALL[v["direction"].as_u64().unwrap() as usize], + extending: v["extending"].as_bool().unwrap(), + source: v["source"].as_bool().unwrap(), + progress: f32::from_bits( + u32::from_str_radix(v["progress"].as_str().unwrap(), 16).unwrap(), + ), + previous_progress: 0.0, + }); + let clip = f + .get("piston") + .map(|v| v["noclip"].as_i64().unwrap()) + .unwrap_or(-1); + let mut world = World { + collisions: &collisions, + pistons: &pistons, + dynamic: &dynamic, + active, + noclip: (clip >= 0).then(|| Direction::ALL[clip as usize]), + out: &mut out, + entity: f["entity"].as_str().unwrap(), + shulker: ShulkerCollisionState { + previous_progress: f.get("shulker_progress").map_or(0.0, |v| { + f32::from_bits(u32::from_str_radix(v[0].as_str().unwrap(), 16).unwrap()) + }), + progress: f.get("shulker_progress").map_or(0.0, |v| { + f32::from_bits(u32::from_str_radix(v[1].as_str().unwrap(), 16).unwrap()) + }), + }, + calls: 0, + fail: f["fail"].as_i64().unwrap() as i32, + }; + match if f.get("collision").and_then(Value::as_bool).unwrap_or(false) { + support.collision_shape(&mut world, p) + } else { + support.shape(&mut world, p) + } { + Ok(shape) => emit(world.out, &shape)?, + Err(_) => writeln!(world.out, "shape error")?, + } + for direction in Direction::ALL { + for (i, kind) in [SupportType::Full, SupportType::Center, SupportType::Rigid] + .into_iter() + .enumerate() + { + match support.is_face_sturdy(&mut world, p, direction, kind) { + Ok(value) => writeln!(world.out, "support {} {i} {value}", direction as u8)?, + Err(_) => writeln!(world.out, "support {} {i} error", direction as u8)?, + } + } + } + writeln!(world.out, "queries {}", world.calls)?; + } + Ok(()) +} diff --git a/crates/horizon-world/examples/entity_obstruction_fixture.rs b/crates/horizon-world/examples/entity_obstruction_fixture.rs new file mode 100644 index 000000000..ef8f0acc8 --- /dev/null +++ b/crates/horizon-world/examples/entity_obstruction_fixture.rs @@ -0,0 +1,115 @@ +use horizon_core::geometry::{Aabb, Axis, ShapeOp, Vec3, VoxelShape}; +use horizon_world::entity_obstruction::{ + EntityIdentity, EntityObstructionWorld, ObstructionEntity, is_unobstructed, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +struct World<'a, W> { + entities: Vec, + out: &'a mut W, + fail: bool, + calls: usize, +} +impl EntityObstructionWorld for World<'_, W> { + type Error = io::Error; + fn obstruction_candidates( + &mut self, + excluded: Option, + bounds: Aabb, + ) -> io::Result> { + let values = [ + bounds.min(Axis::X), + bounds.min(Axis::Y), + bounds.min(Axis::Z), + bounds.max(Axis::X), + bounds.max(Axis::Y), + bounds.max(Axis::Z), + ] + .map(f64::to_bits); + writeln!( + self.out, + "query {} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", + excluded.map(|id| id.0 as i64).unwrap_or(-1), + values[0], + values[1], + values[2], + values[3], + values[4], + values[5] + )?; + self.calls += 1; + if self.fail { + return Err(io::Error::other("injected entity query failure")); + } + let selected = self + .entities + .iter() + .filter(|e| Some(e.identity) != excluded && e.bounds.intersects(bounds) && !e.spectator) + .copied() + .collect::>(); + for entity in &selected { + writeln!(self.out, "picked {}", entity.identity.0)?; + } + Ok(selected) + } +} +fn bbox(v: &Value) -> Aabb { + let values = v + .as_array() + .unwrap() + .iter() + .map(|v| f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap())) + .collect::>(); + Aabb::new( + Vec3::new(values[0], values[1], values[2]), + Vec3::new(values[3], values[4], values[5]), + ) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let mut entities = Vec::::new(); + for value in f["entities"].as_array().unwrap() { + let identity = EntityIdentity(entities.len() as u64 + 1); + let parent = value["parent"].as_i64().unwrap(); + let root_vehicle = if parent < 0 { + identity + } else { + entities[parent as usize].root_vehicle + }; + entities.push(ObstructionEntity { + identity, + root_vehicle, + bounds: bbox(&value["box"]), + spectator: value["spectator"].as_bool().unwrap(), + removed: value["removed"].as_bool().unwrap(), + blocks_building: value["building"].as_bool().unwrap(), + }); + } + let mut shape = VoxelShape::empty(); + for value in f["shape"].as_array().unwrap() { + shape = shape.join(&VoxelShape::from_box(bbox(value))?, ShapeOp::OR)?; + } + let excluded = f["exclude"].as_i64().unwrap(); + let excluded = (excluded >= 0).then(|| entities[excluded as usize]); + let mut world = World { + entities, + out: &mut out, + fail: f["fail"].as_bool().unwrap(), + calls: 0, + }; + match is_unobstructed(&mut world, excluded.as_ref(), &shape) { + Ok(value) => writeln!(world.out, "clear {value}")?, + Err(_) => writeln!(world.out, "clear error")?, + } + writeln!(world.out, "queries {}", world.calls)?; + } + Ok(()) +} diff --git a/crates/horizon-world/examples/face_support_fixture.rs b/crates/horizon-world/examples/face_support_fixture.rs new file mode 100644 index 000000000..e6bee0e7a --- /dev/null +++ b/crates/horizon-world/examples/face_support_fixture.rs @@ -0,0 +1,147 @@ +use horizon_core::geometry::{Aabb, Axis, Direction, ShapeOp, Vec3, VoxelShape}; +use horizon_world::block_support::SupportType; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn numbers(v: &Value) -> Vec { + v.as_array() + .unwrap() + .iter() + .map(|v| f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap())) + .collect() +} +fn values( + out: &mut impl Write, + label: &str, + values: impl IntoIterator, +) -> io::Result<()> { + write!(out, "{label}")?; + for v in values { + let bits = if v.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + v.to_bits() + }; + write!(out, " {bits:016x}")?; + } + writeln!(out) +} +fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { + values( + out, + label, + [ + b.min(Axis::X), + b.min(Axis::Y), + b.min(Axis::Z), + b.max(Axis::X), + b.max(Axis::Y), + b.max(Axis::Z), + ], + ) +} +fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { + writeln!( + out, + "shape {} {} {}", + shape.is_empty(), + shape.boxes().len(), + shape.is_cube() + )?; + for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { + values(out, name, shape.coordinates(axis).iter().copied())?; + } + let axes = shape.cube_coordinate_axes(); + writeln!( + out, + "axes {}", + u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) + )?; + values( + out, + "extrema", + Axis::ALL + .map(|a| shape.min(a)) + .into_iter() + .chain(Axis::ALL.map(|a| shape.max(a))), + )?; + match shape.bounds() { + Some(b) => box_values(out, "bounds", b)?, + None => writeln!(out, "bounds none")?, + } + for b in shape.boxes() { + box_values(out, "box", *b)?; + } + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let mut shape = if f.get("coords").is_some() { + let coords = std::array::from_fn(|i| numbers(&f["coords"][i])); + let occupied = f["occupied"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_bool().unwrap()) + .collect::>(); + if f["cube"].as_bool().unwrap() { + VoxelShape::from_cube(coords.map(|v| v.len() - 1), &occupied)? + } else { + VoxelShape::from_grid(coords, &occupied)? + } + } else { + let mut s = VoxelShape::empty(); + for v in f["boxes"].as_array().unwrap() { + let v = numbers(v); + s = s.join( + &VoxelShape::from_box(Aabb::new( + Vec3::new(v[0], v[1], v[2]), + Vec3::new(v[3], v[4], v[5]), + ))?, + ShapeOp::OR, + )?; + } + s + }; + if let Some(v) = f.get("move") { + let v = numbers(v); + shape = shape.moved(Vec3::new(v[0], v[1], v[2])); + } + for direction in Direction::ALL { + let face = shape.face_shape(direction)?; + writeln!( + out, + "face {} {} {}", + direction as u8, + face.same_identity(&shape), + face.same_identity(&shape.face_shape(direction)?) + )?; + emit(&mut out, &face)?; + writeln!( + out, + "support {} {} {} 3", + SupportType::Full.is_supporting(&shape, direction)?, + SupportType::Center.is_supporting(&shape, direction)?, + SupportType::Rigid.is_supporting(&shape, direction)? + )?; + for nested in Direction::ALL { + let second = face.face_shape(nested)?; + writeln!( + out, + "nested {} {}", + nested as u8, + second.same_identity(&face) + )?; + emit(&mut out, &second)?; + } + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/feature_catalog_fixture.rs b/crates/horizon-world/examples/feature_catalog_fixture.rs new file mode 100644 index 000000000..c12b9c1a0 --- /dev/null +++ b/crates/horizon-world/examples/feature_catalog_fixture.rs @@ -0,0 +1,276 @@ +//! Feature world transport retaining ordered mutations and partial failures. +use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom, XoroshiroRandom}; +use horizon_world::{ + DATA_VERSION, + heightmap::HeightmapType, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + worldgen::{ + anchor::WorldGenerationContext, + block_feature::FeatureBlockBindings, + feature::{FeatureBlocks, FeatureWorld}, + feature_catalog::FeatureCatalog, + feature_graph::FeatureDefinition, + placement::{FeaturePlacer, PlacementContext, PlacementModifier, PlacementQueryError}, + tags::TagDefinitions, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + io::{self, Write}, + path::Path, +}; +struct World<'a, W> { + states: BTreeMap<[i32; 3], BlockStateId>, + blocks: [BlockStateId; 5], + calls: i32, + fail: i32, + reject: i32, + out: &'a mut W, +} +impl PlacementContext for World<'_, W> { + fn block_state(&mut self, position: [i32; 3]) -> Result { + self.block(position) + .map_err(|e| PlacementQueryError::Failed(e.to_string())) + } + fn max_y(&mut self) -> Result { + Ok(319) + } + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new(-64, 384, 63) + } + fn min_y(&mut self) -> Result { + Ok(-64) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + Err(PlacementQueryError::Unavailable) + } +} +impl FeatureWorld for World<'_, W> { + type Error = io::Error; + fn block(&mut self, p: [i32; 3]) -> Result { + let call = self.calls; + self.calls += 1; + writeln!(self.out, "get {} {} {}", p[0], p[1], p[2])?; + if call == self.fail { + return Err(io::Error::other("world failure")); + } + let hash = p[0] + .wrapping_mul(31) + .wrapping_add(p[1].wrapping_mul(7)) + .wrapping_add(p[2].wrapping_mul(17)) + .rem_euclid(5) as usize; + let state = self.states.get(&p).copied().unwrap_or(self.blocks[hash]); + writeln!(self.out, "state {}", state.0)?; + Ok(state) + } + fn set_block( + &mut self, + p: [i32; 3], + state: BlockStateId, + flags: i32, + ) -> Result { + let call = self.calls; + self.calls += 1; + writeln!( + self.out, + "set {} {} {} {} {flags}", + p[0], p[1], p[2], state.0 + )?; + if call == self.fail { + return Err(io::Error::other("world failure")); + } + let result = self.reject == 0 || call % self.reject != 0; + if result { + self.states.insert(p, state); + } + writeln!(self.out, "written {result}")?; + Ok(result) + } +} +fn fixture( + f: &Value, + catalog: &FeatureCatalog, + bindings: &FeatureBlockBindings<'_>, + mut random: impl RandomSource, + blocks: [BlockStateId; 5], + out: &mut impl Write, +) -> Result<(), Box> { + let root = if f["placed_root"].as_bool().unwrap_or(false) { + catalog + .placed_feature_with_blocks(f["definition"].as_str().unwrap(), bindings) + .map(|placed| FeatureDefinition::Sequence(vec![placed])) + } else { + catalog.feature_with_blocks(f["definition"].as_str().unwrap(), bindings) + }; + let decoded = root.and_then(|feature| { + let modifiers = f + .get("placement") + .map(|v| { + v.as_array() + .unwrap() + .iter() + .map(|v| PlacementModifier::from_json_with_blocks(&v.to_string(), bindings)) + .collect::, _>>() + }) + .transpose()?; + Ok((feature, modifiers)) + }); + match decoded { + Err(_) => writeln!(out, "decode error")?, + Ok((feature, modifiers)) => { + writeln!(out, "decode ok")?; + let mut world = World { + states: BTreeMap::new(), + blocks, + calls: 0, + fail: f["fail"].as_i64().unwrap() as i32, + reject: f["reject"].as_i64().unwrap() as i32, + out, + }; + let blocks = FeatureBlocks { + air: blocks[0], + stone: blocks[1], + cobblestone: blocks[2], + end_stone: blocks[3], + obsidian: blocks[4], + }; + let p = &f["origin"]; + let origin = [ + p[0].as_i64().unwrap() as i32, + p[1].as_i64().unwrap() as i32, + p[2].as_i64().unwrap() as i32, + ]; + let mut placer = FeaturePlacer::new(); + for _ in 0..f["repeats"].as_u64().unwrap() { + world.calls = 0; + let result = if let Some(modifiers) = &modifiers { + placer + .place_with_context( + modifiers, + &mut world, + &mut random, + origin, + |world, random, position| { + feature.place(world, random, position, blocks) + }, + ) + .map_err(|_| ()) + } else { + feature + .place(&mut world, &mut random, origin, blocks) + .map_err(|_| ()) + }; + match result { + Ok(value) => writeln!(world.out, "place {value}")?, + Err(_) => writeln!(world.out, "place error")?, + } + writeln!(world.out, "next {}", random.next_long())?; + for (p, state) in &world.states { + writeln!(world.out, "stored {} {} {} {}", p[0], p[1], p[2], state.0)?; + } + writeln!(world.out, "end")?; + } + } + } + writeln!(out, "tail {}", random.next_long())?; + Ok(()) +} +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let resources: Value = serde_json::from_str(&fs::read_to_string(dir.join("catalog.json"))?)?; + let definitions = |name: &str| { + resources[name] + .as_object() + .unwrap() + .iter() + .map(|(k, v)| (k.clone(), v.as_str().unwrap().to_owned())) + .collect() + }; + let mut tags = TagDefinitions::default(); + for (name, value) in resources["tags"].as_object().unwrap() { + tags.apply_json(name, "fixture", value.as_str().unwrap())?; + } + let catalog = + FeatureCatalog::from_resources(&definitions("features"), &definitions("placed"), &tags)?; + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", tag(&facts["states"])), + ("defaults", tag(&facts["defaults"])), + ]))?; + let integers = facts["integers"] + .as_array() + .unwrap() + .iter() + .map(|v| { + ( + v[0].as_str().unwrap().to_owned(), + v[1].as_str().unwrap().to_owned(), + ) + }) + .collect(); + let bindings = FeatureBlockBindings::new(®istry, integers)?; + let blocks = ["air", "stone", "cobblestone", "end_stone", "obsidian"].map(|name| { + registry + .default_state(&format!("minecraft:{name}")) + .unwrap() + }); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + match ( + f["legacy"].as_bool().unwrap(), + f["worldgen"].as_bool().unwrap(), + ) { + (true, false) => fixture( + &f, + &catalog, + &bindings, + LegacyRandom::new(seed), + blocks, + &mut out, + )?, + (true, true) => fixture( + &f, + &catalog, + &bindings, + WorldgenRandom::new(LegacyRandom::new(seed)), + blocks, + &mut out, + )?, + (false, false) => fixture( + &f, + &catalog, + &bindings, + XoroshiroRandom::new(seed), + blocks, + &mut out, + )?, + (false, true) => fixture( + &f, + &catalog, + &bindings, + WorldgenRandom::new(XoroshiroRandom::new(seed)), + blocks, + &mut out, + )?, + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/feature_graph_fixture.rs b/crates/horizon-world/examples/feature_graph_fixture.rs new file mode 100644 index 000000000..fae5b6e2e --- /dev/null +++ b/crates/horizon-world/examples/feature_graph_fixture.rs @@ -0,0 +1,180 @@ +//! Feature world transport retaining ordered mutations and partial failures. +use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; +use horizon_world::{ + heightmap::HeightmapType, + registry::BlockStateId, + worldgen::{ + anchor::WorldGenerationContext, + feature::{FeatureBlocks, FeatureWorld}, + feature_graph::FeatureDefinition, + placement::{FeaturePlacer, PlacementContext, PlacementModifier, PlacementQueryError}, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + io::{self, Write}, + path::Path, +}; +struct World<'a, W> { + states: BTreeMap<[i32; 3], BlockStateId>, + blocks: [BlockStateId; 5], + calls: i32, + fail: i32, + reject: i32, + out: &'a mut W, +} +impl PlacementContext for World<'_, W> { + fn max_y(&mut self) -> Result { + Ok(319) + } + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new(-64, 384, 63) + } + fn min_y(&mut self) -> Result { + Ok(-64) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + Err(PlacementQueryError::Unavailable) + } +} +impl FeatureWorld for World<'_, W> { + type Error = io::Error; + fn block(&mut self, p: [i32; 3]) -> Result { + let call = self.calls; + self.calls += 1; + writeln!(self.out, "get {} {} {}", p[0], p[1], p[2])?; + if call == self.fail { + return Err(io::Error::other("world failure")); + } + let hash = p[0] + .wrapping_mul(31) + .wrapping_add(p[1].wrapping_mul(7)) + .wrapping_add(p[2].wrapping_mul(17)) + .rem_euclid(5) as usize; + let state = self.states.get(&p).copied().unwrap_or(self.blocks[hash]); + writeln!(self.out, "state {}", state.0)?; + Ok(state) + } + fn set_block( + &mut self, + p: [i32; 3], + state: BlockStateId, + flags: i32, + ) -> Result { + let call = self.calls; + self.calls += 1; + writeln!( + self.out, + "set {} {} {} {} {flags}", + p[0], p[1], p[2], state.0 + )?; + if call == self.fail { + return Err(io::Error::other("world failure")); + } + let result = self.reject == 0 || call % self.reject != 0; + if result { + self.states.insert(p, state); + } + writeln!(self.out, "written {result}")?; + Ok(result) + } +} +fn fixture( + f: &Value, + mut random: impl RandomSource, + blocks: [BlockStateId; 5], + out: &mut impl Write, +) -> Result<(), Box> { + let decoded = + FeatureDefinition::from_json(f["definition"].as_str().unwrap()).and_then(|feature| { + let modifiers = f + .get("placement") + .map(|v| { + v.as_array() + .unwrap() + .iter() + .map(|v| PlacementModifier::from_json(&v.to_string())) + .collect::, _>>() + }) + .transpose()?; + Ok((feature, modifiers)) + }); + match decoded { + Err(_) => writeln!(out, "decode error")?, + Ok((feature, modifiers)) => { + writeln!(out, "decode ok")?; + let mut world = World { + states: BTreeMap::new(), + blocks, + calls: 0, + fail: f["fail"].as_i64().unwrap() as i32, + reject: f["reject"].as_i64().unwrap() as i32, + out, + }; + let blocks = FeatureBlocks { + air: blocks[0], + stone: blocks[1], + cobblestone: blocks[2], + end_stone: blocks[3], + obsidian: blocks[4], + }; + let p = &f["origin"]; + let origin = [ + p[0].as_i64().unwrap() as i32, + p[1].as_i64().unwrap() as i32, + p[2].as_i64().unwrap() as i32, + ]; + let mut placer = FeaturePlacer::new(); + for _ in 0..f["repeats"].as_u64().unwrap() { + world.calls = 0; + let result = if let Some(modifiers) = &modifiers { + placer + .place_with_context( + modifiers, + &mut world, + &mut random, + origin, + |world, random, position| { + feature.place(world, random, position, blocks) + }, + ) + .map_err(|_| ()) + } else { + feature + .place(&mut world, &mut random, origin, blocks) + .map_err(|_| ()) + }; + match result { + Ok(value) => writeln!(world.out, "place {value}")?, + Err(_) => writeln!(world.out, "place error")?, + } + writeln!(world.out, "next {}", random.next_long())?; + for (p, state) in &world.states { + writeln!(world.out, "stored {} {} {} {}", p[0], p[1], p[2], state.0)?; + } + writeln!(world.out, "end")?; + } + } + } + writeln!(out, "tail {}", random.next_long())?; + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let ids: [u32; 5] = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let blocks = ids.map(BlockStateId); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, LegacyRandom::new(seed), blocks, &mut out)?; + } else { + fixture(&f, XoroshiroRandom::new(seed), blocks, &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/feature_placement_fixture.rs b/crates/horizon-world/examples/feature_placement_fixture.rs new file mode 100644 index 000000000..c7500fa4f --- /dev/null +++ b/crates/horizon-world/examples/feature_placement_fixture.rs @@ -0,0 +1,91 @@ +//! Transport for native modifier chains and a feature callback sharing the RNG. +#[path = "support/placement_queries.rs"] +mod queries; +use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; +use horizon_world::worldgen::{ + anchor::WorldGenerationContext, + placement::{FeaturePlacer, PlacementModifier}, +}; +use serde_json::Value; +use std::cell::RefCell; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +fn fixture( + f: &Value, + mut random: impl RandomSource, + out: &mut impl Write, +) -> Result<(), Box> { + let c = &f["context"]; + let context = WorldGenerationContext::new(n(&c[0]), n(&c[1]), n(&c[2])); + let out = RefCell::new(out); + let mut context = queries::Queries::new(f, context, &out); + let modifiers = f["modifiers"] + .as_array() + .unwrap() + .iter() + .map(|v| PlacementModifier::from_json(&v.to_string())) + .collect::, _>>(); + match modifiers { + Err(_) => writeln!(out.borrow_mut(), "decode error")?, + Ok(modifiers) => { + writeln!(out.borrow_mut(), "decode ok")?; + let mut placer = FeaturePlacer::new(); + for p in f["positions"].as_array().unwrap() { + let mut count = 0; + let fail = n(&f["fail"]); + let draw = f["draw"].as_bool().unwrap(); + let mode = n(&f["result"]); + let result = placer.place_in( + &modifiers, + &mut context, + &mut random, + [n(&p[0]), n(&p[1]), n(&p[2])], + |random, p| { + let previous = count; + count += 1; + if previous == fail { + return Err(io::Error::other("feature failure")); + } + writeln!(out.borrow_mut(), "feature {} {} {}", p[0], p[1], p[2])?; + let mut value = i64::from(p[0].wrapping_add(p[1]).wrapping_add(p[2])); + if draw { + value = random.next_long(); + writeln!(out.borrow_mut(), "consumer {value}")?; + } + let result = mode == 1 || (mode == 2 && value & 1 == 0); + writeln!(out.borrow_mut(), "result {result}")?; + Ok(result) + }, + ); + match result { + Ok(result) => writeln!(out.borrow_mut(), "place {result}")?, + Err(_) => writeln!(out.borrow_mut(), "place error")?, + } + writeln!(out.borrow_mut(), "next {}", random.next_long())?; + } + } + } + writeln!(out.borrow_mut(), "tail {}", random.next_long())?; + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, LegacyRandom::new(seed), &mut out)?; + } else { + fixture(&f, XoroshiroRandom::new(seed), &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/feature_region_fixture.rs b/crates/horizon-world/examples/feature_region_fixture.rs new file mode 100644 index 000000000..2b3918be3 --- /dev/null +++ b/crates/horizon-world/examples/feature_region_fixture.rs @@ -0,0 +1,294 @@ +use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom, XoroshiroRandom}; +use horizon_world::worldgen::{ + anchor::WorldGenerationContext, + block_feature::FeatureBlockBindings, + feature::FeatureBlocks, + feature_graph::FeatureDefinition, + feature_region::{RegionError, TerrainFeatureAccess, TerrainRegion}, + placement::{FeaturePlacer, PlacementContext, PlacementModifier}, + terrain::TerrainError, +}; +// Feature chains against a resident multi-chunk region. +use horizon_core::position::ChunkPos; +use horizon_world::{ + DATA_VERSION, + heightmap::{HeightmapState, HeightmapType}, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + worldgen::{ + tags::TagDefinitions, + terrain::{PreLightChunkStage, TerrainBlockStates, TerrainChunk}, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeSet, + fs, + io::{self, Write}, + path::Path, +}; +#[derive(Clone, Copy)] +struct State { + air: bool, + air_block: bool, + fluid: bool, + motion: bool, + no_leaves: bool, +} +impl HeightmapState for State { + fn is_air(self) -> bool { + self.air + } + fn is_air_block(self) -> bool { + self.air_block + } + fn has_fluid(self) -> bool { + self.fluid + } + fn blocks_motion_in_heightmap(self) -> bool { + self.motion + } + fn blocks_motion_in_heightmap_no_leaves(self) -> bool { + self.no_leaves + } +} +struct Properties<'a>(&'a [State]); +impl TerrainBlockStates for Properties<'_> { + type State = State; + fn heightmap_state(&self, id: BlockStateId) -> State { + self.0[id.0 as usize] + } +} +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + _ => panic!("unsupported registry fixture value"), + } +} +fn fixture( + f: &Value, + registry: &BlockRegistry, + states: &[State], + out: &mut impl Write, +) -> Result<(), Box> { + let seed = f["seed"].as_i64().unwrap(); + match ( + f["legacy"].as_bool().unwrap(), + f["worldgen"].as_bool().unwrap(), + ) { + (true, false) => run(f, registry, states, out, LegacyRandom::new(seed)), + (true, true) => run( + f, + registry, + states, + out, + WorldgenRandom::new(LegacyRandom::new(seed)), + ), + (false, false) => run(f, registry, states, out, XoroshiroRandom::new(seed)), + (false, true) => run( + f, + registry, + states, + out, + WorldgenRandom::new(XoroshiroRandom::new(seed)), + ), + } +} +fn run( + f: &Value, + registry: &BlockRegistry, + states: &[State], + out: &mut impl Write, + mut random: impl RandomSource, +) -> Result<(), Box> { + let stage = PreLightChunkStage::ALL + .into_iter() + .find(|s| s.name() == f["stage"].as_str().unwrap()) + .unwrap(); + let mut chunks = Vec::new(); + for cx in -1..=1 { + for cz in -1..=1 { + let mut chunk = + TerrainChunk::new(ChunkPos::new(cx, cz), -64, 64, registry, Properties(states))?; + chunk.set_generation_stage(stage); + for x in 0..16 { + for z in 0..16 { + chunk.set_block_worldgen( + (cx << 4) + x, + -56, + (cz << 4) + z, + registry.default_state("minecraft:stone").unwrap(), + )?; + if (x + z) % 3 != 0 { + chunk.set_block_worldgen( + (cx << 4) + x, + -48, + (cz << 4) + z, + registry.default_state("minecraft:dirt").unwrap(), + )?; + } + } + } + chunks.push(chunk); + } + } + let mut region = TerrainRegion::new(chunks, WorldGenerationContext::new(-64, 64, 0))?; + let blocks = FeatureBlocks::from_registry(registry)?; + // These configured fixture states use compact names and an enum property; + // no integer-property parsing is requested by this region corpus. + let bindings = FeatureBlockBindings::new(registry, BTreeSet::new())?; + let features = f["features"] + .as_array() + .unwrap() + .iter() + .map(|v| FeatureDefinition::from_json_with_blocks(&v.to_string(), &bindings)) + .collect::, _>>()?; + let modifiers = f["placement"] + .as_array() + .unwrap() + .iter() + .map(|v| PlacementModifier::from_json(&v.to_string())) + .collect::, _>>()?; + let mut placer = FeaturePlacer::new(); + let fail = n(&f["fail"]); + let reject = n(&f["reject"]); + for repeat in 0..2 { + for feature in &features { + let mut calls = 0; + let result = { + let write = |region: &mut TerrainRegion<'_, Properties<'_>>, + p: [i32; 3], + state: BlockStateId, + flags: i32| + -> Result { + writeln!(out, "write {} {} {} {} {flags}", p[0], p[1], p[2], state.0) + .map_err(TerrainError::from)?; + let call = calls; + calls += 1; + if call == fail { + return Err(TerrainError::Storage(io::Error::other( + "injected write failure", + )) + .into()); + } + let result = reject == 0 || call % reject != 0; + if result { + region.set_block_worldgen(p, state)?; + } + writeln!(out, "written {result}").map_err(TerrainError::from)?; + Ok(result) + }; + let mut world = TerrainFeatureAccess::new(&mut region, write); + placer.place_with_context( + &modifiers, + &mut world, + &mut random, + [15, -40, 15], + |world, random, p| feature.place(world, random, p, blocks), + ) + }; + match result { + Ok(result) => writeln!(out, "place {result}")?, + Err(_) => writeln!(out, "place error")?, + } + writeln!(out, "next {}", random.next_long())?; + for [x, z] in [[0, 0], [15, 15], [16, 16], [-1, -1]] { + for kind in HeightmapType::ALL { + writeln!( + out, + "height {} {x} {z} {}", + kind.name(), + region.height(kind, x, z)? + )?; + } + } + } + writeln!(out, "repeat {repeat}")?; + } + for chunk in region.chunks() { + let p = chunk.position(); + writeln!(out, "chunk {} {}", p.x, p.z)?; + for kind in HeightmapType::ALL { + if let Some(map) = chunk.heightmap(kind) { + writeln!(out, "map {}", kind.name())?; + for word in map.raw_data() { + writeln!(out, "{word:x}")?; + } + } else { + writeln!(out, "missing {}", kind.name())?; + } + } + for i in 0..4 { + writeln!(out, "section {i}")?; + for index in 0..4096 { + writeln!(out, "{}", chunk.section(i).unwrap().get(index)?.0)?; + } + } + } + writeln!(out, "tail {}", random.next_long())?; + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List( + facts["states"] + .as_array() + .unwrap() + .iter() + .map(|s| tag(&s[4])) + .collect(), + ), + ), + ("defaults", tag(&facts["defaults"])), + ]))?; + let mut definitions = TagDefinitions::default(); + for (name, text) in bundle.as_object().unwrap() { + definitions.apply_json(name, "vanilla", text.as_str().unwrap())?; + } + let built = definitions.build(|id, _| facts["defaults"].get(id).map(|_| id.to_owned()))?; + assert!(built.missing.is_empty()); + let motion: BTreeSet<_> = built.tags["minecraft:blocks_motion_in_heightmap"] + .iter() + .map(String::as_str) + .collect(); + let no_leaves: BTreeSet<_> = built.tags["minecraft:blocks_motion_in_heightmap_no_leaves"] + .iter() + .map(String::as_str) + .collect(); + let states: Vec<_> = facts["states"] + .as_array() + .unwrap() + .iter() + .map(|a| { + let name = a[0].as_str().unwrap(); + State { + air: a[1].as_bool().unwrap(), + air_block: name == "minecraft:air", + fluid: a[2].as_bool().unwrap(), + motion: motion.contains(name), + no_leaves: no_leaves.contains(name), + } + }) + .collect(); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + fixture(&serde_json::from_str(line)?, ®istry, &states, &mut out)?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/examples/feature_sort_fixture.rs b/crates/horizon-world/examples/feature_sort_fixture.rs new file mode 100644 index 000000000..6e645601c --- /dev/null +++ b/crates/horizon-world/examples/feature_sort_fixture.rs @@ -0,0 +1,50 @@ +use horizon_world::worldgen::feature_sort::{ + FeatureIdentity, FeatureSortError, build_features_per_step, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let biomes: Vec>> = serde_json::from_value(f["biomes"].clone())?; + let biomes = biomes + .into_iter() + .map(|steps| { + steps + .into_iter() + .map(|step| step.into_iter().map(FeatureIdentity).collect()) + .collect() + }) + .collect::>(); + match build_features_per_step(&biomes) { + Err(FeatureSortError::Cycle) => writeln!(out, "cycle")?, + Err(error) => return Err(error.into()), + Ok(steps) => { + writeln!(out, "steps {}", steps.len())?; + for (index, step) in steps.iter().enumerate() { + writeln!(out, "step {index} {}", step.features().len())?; + for feature in step.features() { + writeln!(out, "feature {}", feature.0)?; + } + for id in f["queries"].as_array().unwrap() { + let id = FeatureIdentity(id.as_u64().unwrap() as u32); + writeln!( + out, + "index {} {}", + id.0, + step.index(id).map_or(-1, |i| i as i32) + )?; + } + } + } + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/fill_layer_fixture.rs b/crates/horizon-world/examples/fill_layer_fixture.rs new file mode 100644 index 000000000..d10cd2b72 --- /dev/null +++ b/crates/horizon-world/examples/fill_layer_fixture.rs @@ -0,0 +1,195 @@ +//! Feature world transport retaining ordered mutations and partial failures. +use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; +use horizon_world::{ + DATA_VERSION, + heightmap::HeightmapType, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + worldgen::{ + anchor::WorldGenerationContext, + block_feature::{FeatureBlockBindings, FillLayerFeature}, + feature::FeatureWorld, + placement::{PlacementContext, PlacementQueryError}, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + io::{self, Write}, + path::Path, +}; +struct World<'a, W> { + states: BTreeMap<[i32; 3], BlockStateId>, + blocks: Vec, + minimum: i32, + calls: i32, + fail: i32, + reject: i32, + out: &'a mut W, +} +impl PlacementContext for World<'_, W> { + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new(self.minimum, 384, 63) + } + fn min_y(&mut self) -> Result { + writeln!(self.out, "min").map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + let call = self.calls; + self.calls += 1; + if call == self.fail { + return Err(PlacementQueryError::Failed("minimum query failure".into())); + } + writeln!(self.out, "minimum {}", self.minimum) + .map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + Ok(self.minimum) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + Err(PlacementQueryError::Unavailable) + } +} +impl FeatureWorld for World<'_, W> { + type Error = io::Error; + fn block(&mut self, p: [i32; 3]) -> Result { + let call = self.calls; + self.calls += 1; + writeln!(self.out, "get {} {} {}", p[0], p[1], p[2])?; + if call == self.fail { + return Err(io::Error::other("world failure")); + } + let hash = p[0] + .wrapping_mul(31) + .wrapping_add(p[1].wrapping_mul(7)) + .wrapping_add(p[2].wrapping_mul(17)) + .rem_euclid(7) as usize; + let state = self.states.get(&p).copied().unwrap_or(self.blocks[hash]); + writeln!(self.out, "state {}", state.0)?; + Ok(state) + } + fn set_block( + &mut self, + p: [i32; 3], + state: BlockStateId, + flags: i32, + ) -> Result { + let call = self.calls; + self.calls += 1; + writeln!( + self.out, + "set {} {} {} {} {flags}", + p[0], p[1], p[2], state.0 + )?; + if call == self.fail { + return Err(io::Error::other("world failure")); + } + let result = self.reject == 0 || call % self.reject != 0; + if result { + self.states.insert(p, state); + } + writeln!(self.out, "written {result}")?; + Ok(result) + } +} +fn fixture( + f: &Value, + mut random: impl RandomSource, + blocks: &[BlockStateId], + bindings: &FeatureBlockBindings<'_>, + out: &mut impl Write, +) -> Result<(), Box> { + let decoded = FillLayerFeature::from_json(f["definition"].as_str().unwrap(), bindings); + match decoded { + Err(_) => writeln!(out, "decode error")?, + Ok(feature) => { + writeln!(out, "decode ok")?; + let mut world = World { + states: BTreeMap::new(), + blocks: blocks.to_vec(), + minimum: f["world_min"].as_i64().unwrap() as i32, + calls: 0, + fail: f["fail"].as_i64().unwrap() as i32, + reject: f["reject"].as_i64().unwrap() as i32, + out, + }; + let p = &f["origin"]; + let origin = [ + p[0].as_i64().unwrap() as i32, + p[1].as_i64().unwrap() as i32, + p[2].as_i64().unwrap() as i32, + ]; + for _ in 0..f["repeats"].as_u64().unwrap() { + world.calls = 0; + let result = feature.place(&mut world, origin); + match result { + Ok(value) => writeln!(world.out, "place {value}")?, + Err(_) => writeln!(world.out, "place error")?, + } + writeln!(world.out, "next {}", random.next_long())?; + for (p, state) in &world.states { + writeln!(world.out, "stored {} {} {} {}", p[0], p[1], p[2], state.0)?; + } + writeln!(world.out, "end")?; + } + } + } + writeln!(out, "tail {}", random.next_long())?; + Ok(()) +} +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", tag(&facts["states"])), + ("defaults", tag(&facts["defaults"])), + ]))?; + let integers = facts["integers"] + .as_array() + .unwrap() + .iter() + .map(|v| { + ( + v[0].as_str().unwrap().to_owned(), + v[1].as_str().unwrap().to_owned(), + ) + }) + .collect(); + let bindings = FeatureBlockBindings::new(®istry, integers)?; + let blocks: Vec<_> = [ + "air", + "cave_air", + "void_air", + "stone", + "water", + "oak_leaves", + "dirt", + ] + .map(|name| { + registry + .default_state(&format!("minecraft:{name}")) + .unwrap() + }) + .to_vec(); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, LegacyRandom::new(seed), &blocks, &bindings, &mut out)?; + } else { + fixture(&f, XoroshiroRandom::new(seed), &blocks, &bindings, &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/fluid_fixture.rs b/crates/horizon-world/examples/fluid_fixture.rs new file mode 100644 index 000000000..e874077eb --- /dev/null +++ b/crates/horizon-world/examples/fluid_fixture.rs @@ -0,0 +1,121 @@ +use horizon_world::{ + DATA_VERSION, + fluid::{FluidBlockBindings, FluidHeightWorld, FluidKind, FluidState, FluidStateTable}, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +struct World<'a, W> { + out: &'a mut W, + above: FluidState, + sturdy: bool, + calls: i32, + fail: i32, +} +impl World<'_, W> { + fn query(&mut self, kind: &str, p: [i32; 3]) -> io::Result<()> { + writeln!(self.out, "{kind} {} {} {}", p[0], p[1], p[2])?; + let call = self.calls; + self.calls += 1; + if call == self.fail { + Err(io::Error::other("injected fluid query failure")) + } else { + Ok(()) + } + } +} +impl FluidHeightWorld for World<'_, W> { + type Error = io::Error; + fn fluid(&mut self, p: [i32; 3]) -> io::Result { + self.query("fluid", p)?; + Ok(self.above) + } + fn sturdy_down(&mut self, p: [i32; 3]) -> io::Result { + self.query("block", p)?; + Ok(self.sturdy) + } +} +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", tag(&facts["states"])), + ("defaults", tag(&facts["defaults"])), + ]))?; + let fluids = FluidStateTable::new(®istry)?; + let blocks = FluidBlockBindings::new(®istry)?; + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for first in FluidKind::ALL { + for second in FluidKind::ALL { + writeln!( + out, + "family {} {} {}", + first.name(), + second.name(), + first.same_family(second) + )?; + } + } + for i in 0..registry.len() { + let fluid = fluids.get(BlockStateId(i as u32)).unwrap(); + writeln!( + out, + "state {i} {} {} {} {} {} {} {}", + fluid.kind().name(), + fluid.amount(), + fluid.falling(), + fluid.is_full(), + fluid.is_source(), + fluid.own_height().to_bits(), + blocks.block(fluid).0 + )?; + } + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let fluid = fluids + .get(BlockStateId(f["state"].as_u64().unwrap() as u32)) + .unwrap(); + let above = fluids + .get(BlockStateId(f["above"].as_u64().unwrap() as u32)) + .unwrap(); + let p = std::array::from_fn(|i| f["position"][i].as_i64().unwrap() as i32); + let mut world = World { + out: &mut out, + above, + sturdy: f["sturdy"].as_bool().unwrap(), + calls: 0, + fail: f["fail"].as_i64().unwrap() as i32, + }; + for camera in [false, true] { + let result = if camera { + fluid.camera_height_at(&mut world, p) + } else { + fluid.height_at(&mut world, p) + }; + match result { + Ok(value) => writeln!(world.out, "height {}", value.to_bits())?, + Err(_) => writeln!(world.out, "height error")?, + } + } + writeln!(world.out, "calls {}", world.calls)?; + } + Ok(()) +} diff --git a/crates/horizon-world/examples/height_provider_fixture.rs b/crates/horizon-world/examples/height_provider_fixture.rs new file mode 100644 index 000000000..7ada87a18 --- /dev/null +++ b/crates/horizon-world/examples/height_provider_fixture.rs @@ -0,0 +1,50 @@ +//! Transport for anchored provider samples and subsequent random state. +use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; +use horizon_world::worldgen::{anchor::WorldGenerationContext, height_provider::HeightProvider}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +fn fixture( + f: &Value, + mut random: impl RandomSource, + out: &mut impl Write, +) -> Result<(), Box> { + let c = &f["context"]; + let context = WorldGenerationContext::new(n(&c[0]), n(&c[1]), n(&c[2])); + match HeightProvider::from_json(f["definition"].as_str().unwrap()) { + Ok(provider) => { + writeln!(out, "decode ok")?; + for _ in 0..f["samples"].as_u64().unwrap() { + match provider.sample(&mut random, context) { + Ok(value) => writeln!(out, "sample {value}")?, + Err(_) => writeln!(out, "sample error")?, + } + writeln!(out, "next {}", random.next_long())?; + } + } + Err(_) => writeln!(out, "decode error")?, + } + writeln!(out, "tail {}", random.next_long())?; + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, LegacyRandom::new(seed), &mut out)?; + } else { + fixture(&f, XoroshiroRandom::new(seed), &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/heightmap_fixture.rs b/crates/horizon-world/examples/heightmap_fixture.rs new file mode 100644 index 000000000..35d7bc5c2 --- /dev/null +++ b/crates/horizon-world/examples/heightmap_fixture.rs @@ -0,0 +1,253 @@ +//! Original differential-test transport. State air/fluid facts are private inputs; +//! tag predicates are resolved by the Rust loader, not imported oracle results. +use horizon_world::heightmap::{Heightmap, HeightmapChunk, HeightmapState, HeightmapType}; +use horizon_world::worldgen::tags::TagDefinitions; +use serde_json::Value; +use std::{ + cell::RefCell, + collections::BTreeSet, + fs, + io::{self, Write}, + path::Path, +}; + +#[derive(Clone, Copy)] +struct State { + air: bool, + air_block: bool, + fluid: bool, + motion: bool, + no_leaves: bool, +} +impl HeightmapState for State { + fn is_air(self) -> bool { + self.air + } + fn is_air_block(self) -> bool { + self.air_block + } + fn has_fluid(self) -> bool { + self.fluid + } + fn blocks_motion_in_heightmap(self) -> bool { + self.motion + } + fn blocks_motion_in_heightmap_no_leaves(self) -> bool { + self.no_leaves + } +} +struct Chunk<'a> { + min: i32, + height: i32, + blocks: Vec, + counts: Vec, + states: &'a [State], + air: usize, + void_air: usize, + trace: bool, + reads: RefCell>, +} +impl Chunk<'_> { + fn index(&self, x: i32, y: i32, z: i32) -> usize { + ((y - self.min) * 256 + (z & 15) * 16 + (x & 15)) as usize + } + fn write(&mut self, x: i32, y: i32, z: i32, id: usize) { + let index = self.index(x, y, z); + let old = self.blocks[index]; + self.counts[((y - self.min) >> 4) as usize] += + i32::from(!self.states[id].air) - i32::from(!self.states[old].air); + self.blocks[index] = id; + } +} +impl HeightmapChunk for Chunk<'_> { + type State = State; + fn min_y(&self) -> i32 { + self.min + } + fn height(&self) -> i32 { + self.height + } + fn highest_section_y(&self) -> i32 { + self.counts + .iter() + .rposition(|&n| n != 0) + .map_or(self.min, |i| self.min + i as i32 * 16) + } + fn block_state(&self, x: i32, y: i32, z: i32) -> State { + let id = if y < self.min || y >= self.min + self.height { + self.void_air + } else if self.counts[((y - self.min) >> 4) as usize] == 0 { + self.air + } else { + self.blocks[self.index(x, y, z)] + }; + if self.trace { + self.reads + .borrow_mut() + .push(format!("read {x} {y} {z} {id}")); + } + self.states[id] + } +} +fn num(value: &Value) -> i32 { + value.as_i64().unwrap() as i32 +} +fn fixture( + input: Value, + states: &[State], + defaults: &Value, + out: &mut impl Write, +) -> io::Result<()> { + let min = num(&input["min"]); + let height = num(&input["height"]); + let air = num(&defaults["minecraft:air"]) as usize; + let mut chunk = Chunk { + min, + height, + blocks: vec![air; (height * 256) as usize], + counts: vec![0; (height / 16) as usize], + states, + air, + void_air: num(&defaults["minecraft:void_air"]) as usize, + trace: input["trace"].as_bool().unwrap(), + reads: RefCell::default(), + }; + writeln!(out, "chunk {min} {height}")?; + for a in input["initial"].as_array().unwrap() { + chunk.write(num(&a[0]), num(&a[1]), num(&a[2]), num(&a[3]) as usize); + } + let mut maps = HeightmapType::ALL.map(|kind| Heightmap::new(kind, min, height).unwrap()); + for a in input["ops"].as_array().unwrap() { + match a[0].as_str().unwrap() { + "set" | "update" => { + let (x, y, z, id) = (num(&a[1]), num(&a[2]), num(&a[3]), num(&a[4]) as usize); + let mask = if a[0] == "set" { + chunk.write(x, y, z, id); + num(&a[5]) + } else { + 1 << num(&a[5]) + }; + for (t, map) in maps.iter_mut().enumerate() { + if mask & (1 << t) != 0 { + match map.update(&chunk, x, y, z, states[id]) { + Ok(changed) => writeln!(out, "update {t} {changed}")?, + Err(_) => writeln!(out, "update {t} error")?, + } + } + } + } + "prime" => { + let mask = num(&a[1]); + let mut selected: Vec<_> = maps + .iter_mut() + .enumerate() + .filter_map(|(t, map)| (mask & (1 << t) != 0).then_some(map)) + .collect(); + Heightmap::prime(&chunk, &mut selected).unwrap(); + writeln!(out, "prime {mask}")?; + } + "raw" => { + let t = num(&a[1]) as usize; + let words: Vec<_> = a[2] + .as_array() + .unwrap() + .iter() + .map(|word| u64::from_str_radix(word.as_str().unwrap(), 16).unwrap()) + .collect(); + maps[t].set_raw_data(&chunk, &words).unwrap(); + writeln!(out, "raw {t}")?; + } + "query" => { + let (x, z) = (num(&a[1]), num(&a[2])); + for (t, map) in maps.iter().enumerate() { + match map.first_available(x, z) { + Ok(first) => writeln!( + out, + "height {t} {x} {z} {first} {}", + map.highest_taken(x, z).unwrap() + )?, + Err(_) => writeln!(out, "height {t} {x} {z} error")?, + } + } + } + "dump" => { + writeln!(out, "highest_section {}", chunk.highest_section_y())?; + for (t, map) in maps.iter().enumerate() { + writeln!(out, "words {t} {}", map.raw_data().len())?; + for word in map.raw_data() { + writeln!(out, "{word:x}")?; + } + } + } + _ => panic!("unknown fixture operation"), + } + for read in chunk.reads.borrow_mut().drain(..) { + writeln!(out, "{read}")?; + } + } + Ok(()) +} +fn main() -> Result<(), Box> { + let directory = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&directory); + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let tags: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; + let mut definitions = TagDefinitions::default(); + for (name, text) in tags.as_object().unwrap() { + definitions.apply_json(name, "vanilla", text.as_str().unwrap())?; + } + let built = definitions.build(|id, _| facts["defaults"].get(id).map(|_| id.to_owned()))?; + assert!(built.missing.is_empty()); + let motion: BTreeSet<_> = built.tags["minecraft:blocks_motion_in_heightmap"] + .iter() + .map(String::as_str) + .collect(); + let no_leaves: BTreeSet<_> = built.tags["minecraft:blocks_motion_in_heightmap_no_leaves"] + .iter() + .map(String::as_str) + .collect(); + let states: Vec<_> = facts["states"] + .as_array() + .unwrap() + .iter() + .map(|a| { + let name = a[0].as_str().unwrap(); + State { + air: a[1].as_bool().unwrap(), + air_block: name == "minecraft:air", + fluid: a[2].as_bool().unwrap(), + motion: motion.contains(name), + no_leaves: no_leaves.contains(name), + } + }) + .collect(); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for (t, kind) in HeightmapType::ALL.iter().enumerate() { + writeln!( + out, + "type {t} {} {} {}", + kind.name(), + kind.send_to_client(), + kind.keep_after_worldgen() + )?; + } + for (id, &state) in states.iter().enumerate() { + let mask = HeightmapType::ALL + .iter() + .enumerate() + .fold(0, |mask, (t, kind)| { + mask | if kind.is_opaque(state) { 1 << t } else { 0 } + }); + writeln!(out, "predicate {id} {mask}")?; + } + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + fixture( + serde_json::from_str(line)?, + &states, + &facts["defaults"], + &mut out, + )?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/examples/material_condition_fixture.rs b/crates/horizon-world/examples/material_condition_fixture.rs new file mode 100644 index 000000000..0cbb03168 --- /dev/null +++ b/crates/horizon-world/examples/material_condition_fixture.rs @@ -0,0 +1,735 @@ +//! Original comparison transport for material conditions and cache behavior. +use horizon_core::{ + density::{ConstantSampler, DensitySampler, SampleError, SamplerContext}, + noise::{DensityVolume, NanRange, Noise}, + position::BlockPos, + random::{LegacyRandom, PositionalRandom, RandomSource, XoroshiroRandom}, +}; +use horizon_world::worldgen::{ + anchor::{VerticalAnchor, WorldGenerationContext}, + biome_temperature::{BiomeTemperature, BiomeTemperatureSettings}, + decode_noise, + density::DensityRegistry, + material_condition::{ + MaterialCondition, MaterialConditionRegistry, MaterialConditions, MaterialDensitySources, + MaterialNoiseSources, MaterialRule, MaterialRuleError, MaterialRuleLibrary, + MaterialSurfaceQueries, + }, + material_surface::{ClayBandBlocks, MaterialSurface}, + tags::TagDefinitions, +}; +use horizon_world::{ + DATA_VERSION, + nbt::Tag, + registry::{BlockRegistry, BlockStateId, BlockStateJsonCodec}, +}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + io::{self, Write}, + path::Path, + sync::{Arc, Mutex}, +}; +// Canonicalize numeric values as double bits, avoiding differences in JSON +// number formatting while preserving every encoded int32/double value. +fn encoded(value: &MaterialCondition) -> String { + let Ok(text) = value.to_json() else { + return "error".to_owned(); + }; + let bytes = text.as_bytes(); + let mut transformed = Vec::new(); + let mut i = 0; + let mut quoted = false; + let mut escaped = false; + while i < bytes.len() { + if !quoted { + let special = [ + ("-Infinity", 0xfff0000000000000u64), + ("Infinity", 0x7ff0000000000000), + ("NaN", 0x7ff8000000000000), + ] + .into_iter() + .find(|(token, _)| bytes[i..].starts_with(token.as_bytes())); + if let Some((token, bits)) = special { + transformed.extend_from_slice(format!("\"number:{bits:x}\"").as_bytes()); + i += token.len(); + continue; + } + } + let c = bytes[i]; + transformed.push(c); + i += 1; + if escaped { + escaped = false; + } else if quoted && c == b'\\' { + escaped = true; + } else if c == b'"' { + quoted = !quoted; + } + } + fn normalize(value: &mut Value) { + match value { + Value::Number(n) => { + let v = n.as_f64().unwrap(); + *value = Value::String(format!("number:{:x}", v.to_bits())); + } + Value::Array(a) => a.iter_mut().for_each(normalize), + Value::Object(o) => o.values_mut().for_each(normalize), + _ => {} + } + } + let mut value: Value = serde_json::from_slice(&transformed).unwrap(); + normalize(&mut value); + serde_json::to_string(&value).unwrap() +} +fn anchor(v: &Value) -> VerticalAnchor { + let n = v[1].as_i64().unwrap() as i32; + match v[0].as_u64().unwrap() { + 0 => VerticalAnchor::Absolute(n), + 1 => VerticalAnchor::AboveBottom(n), + 2 => VerticalAnchor::BelowTop(n), + 3 => VerticalAnchor::RelativeToSeaLevel(n), + _ => panic!("unknown anchor"), + } +} +fn condition(v: &Value, registry: &MaterialConditionRegistry) -> MaterialCondition { + match v[0].as_str().unwrap() { + "json" => registry.decode(v[1].as_str().unwrap()).unwrap(), + "noise" => MaterialCondition::NoiseThreshold { + noise: v[1].as_str().unwrap().to_owned(), + min: f64::from_bits(u64::from_str_radix(v[2].as_str().unwrap(), 16).unwrap()), + max: f64::from_bits(u64::from_str_radix(v[3].as_str().unwrap(), 16).unwrap()), + is_3d: v[4].as_bool().unwrap(), + }, + "temperature" => MaterialCondition::Temperature, + "above" => MaterialCondition::AbovePreliminarySurface, + "biome" => MaterialCondition::Biome( + v[1].as_array() + .unwrap() + .iter() + .map(|name| name.as_str().unwrap().to_owned()) + .collect(), + ), + "hole" => MaterialCondition::Hole, + "steep" => MaterialCondition::Steep, + "y" => MaterialCondition::YAbove { + anchor: anchor(&v[1]), + surface_depth_multiplier: v[2].as_i64().unwrap() as i32, + add_stone_depth: v[3].as_bool().unwrap(), + }, + "water" => MaterialCondition::Water { + offset: v[1].as_i64().unwrap() as i32, + surface_depth_multiplier: v[2].as_i64().unwrap() as i32, + add_stone_depth: v[3].as_bool().unwrap(), + }, + "stone" => MaterialCondition::StoneDepth { + offset: v[1].as_i64().unwrap() as i32, + add_surface_depth: v[2].as_bool().unwrap(), + secondary_depth_range: v[3].as_i64().unwrap() as i32, + ceiling: v[4].as_bool().unwrap(), + }, + "gradient" => MaterialCondition::VerticalGradient { + random_name: v[1].as_str().unwrap().to_owned(), + true_at_and_below: anchor(&v[2]), + false_at_and_above: anchor(&v[3]), + }, + "not" => MaterialCondition::Not(Box::new(condition(&v[1], registry))), + _ => panic!("unknown condition"), + } +} +#[derive(Default, Debug)] +struct Inputs { + depth: i32, + secondary: f32, + queries: Vec, + biome: Option, + density: f32, + density_remaining: i32, + ore_values: [f32; 3], + ore_remaining: [i32; 3], +} +#[derive(Debug)] +struct TracedDensity { + inputs: Arc>, + channel: Option, +} +impl TracedDensity { + fn label(&self) -> String { + self.channel + .map(|i| format!("ore {i}")) + .unwrap_or_else(|| "density".to_owned()) + } +} +impl DensitySampler for TracedDensity { + fn sample_value(&self, _: &mut SamplerContext, position: [i32; 3]) -> Result { + let [x, y, z] = position; + let mut inputs = self.inputs.lock().unwrap(); + inputs + .queries + .push(format!("{} query {x} {y} {z}", self.label())); + let remaining = match self.channel { + Some(i) => &mut inputs.ore_remaining[i], + None => &mut inputs.density_remaining, + }; + if *remaining == 0 { + return Err(SampleError::SurfaceSearchOverflow); + } + if *remaining > 0 { + *remaining -= 1; + } + Ok(self + .channel + .map(|i| inputs.ore_values[i]) + .unwrap_or(inputs.density)) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + let [sx, sy, sz] = volume.sizes(); + let [x, y, z] = volume.minimum(); + let [dx, dy, dz] = volume.steps(); + self.inputs.lock().unwrap().queries.push(format!( + "{} volume {sx} {sy} {sz} {x} {y} {z} {dx} {dy} {dz}", + self.label() + )); + for iz in 0..sz { + for ix in 0..sx { + for iy in 0..sy { + buffer[iy + (ix + iz * sx) * sy] = self.sample_value( + context, + [ + x.wrapping_add((ix as i32).wrapping_mul(dx)), + y.wrapping_add((iy as i32).wrapping_mul(dy)), + z.wrapping_add((iz as i32).wrapping_mul(dz)), + ], + )?; + } + } + } + Ok(()) + } +} +struct Surface { + inputs: Arc>, + noises: MaterialNoiseSources>, + real_noise: bool, + biomes: Arc>>, + possible: Option>, +} +#[derive(Debug)] +struct TracedNoise { + name: String, + inputs: Arc>, +} +impl Noise for TracedNoise { + fn range(&self) -> Result<[f32; 2], NanRange> { + Ok([f32::NEG_INFINITY, f32::INFINITY]) + } + fn get2(&self, _: f64, _: f64) -> f32 { + panic!("unexpected 2D noise call") + } + fn get3(&self, x: f64, y: f64, z: f64) -> f32 { + let mut inputs = self.inputs.lock().unwrap(); + inputs.queries.push(format!( + "noise query {} {} {} {}", + self.name, x as i32, y as i32, z as i32 + )); + inputs.secondary + } +} +impl MaterialSurfaceQueries for Surface

{ + fn possible_biomes(&self) -> Option> { + self.possible.clone() + } + fn biome(&mut self, p: BlockPos) -> Result>, MaterialRuleError> { + let mut inputs = self.inputs.lock().unwrap(); + inputs + .queries + .push(format!("biome query {} {} {}", p.x, p.y, p.z)); + if inputs.biome.as_deref() == Some("#throw") { + return Err(MaterialRuleError::BiomeQueryFailed); + } + Ok(inputs.biome.as_deref().map(Arc::from)) + } + fn cold_enough_to_snow( + &mut self, + name: &str, + p: BlockPos, + sea: i32, + ) -> Result { + Ok(self + .biomes + .lock() + .unwrap() + .get_mut(name) + .ok_or(MaterialRuleError::MissingBiome)? + .cold_enough_to_snow(p, sea)) + } + fn bind_noise( + &mut self, + name: &str, + ) -> Result, horizon_world::worldgen::DecodeError> { + let real = self.noises.bind_noise(name)?; + if self.real_noise { + Ok(real) + } else { + Ok(Arc::new(TracedNoise { + name: name.to_owned(), + inputs: self.inputs.clone(), + })) + } + } + fn band(&mut self, position: BlockPos) -> Result { + self.noises.band(position) + } + fn surface_depth(&mut self, _: i32, _: i32) -> i32 { + self.inputs.lock().unwrap().depth + } + fn surface_secondary(&mut self, x: i32, z: i32) -> f64 { + let mut i = self.inputs.lock().unwrap(); + i.queries.push(format!("secondary query {x} {z}")); + f64::from(i.secondary) + } +} +fn rule( + v: &Value, + registry: &MaterialConditionRegistry, + inputs: &Arc>, +) -> MaterialRule { + match v[0].as_str().unwrap() { + "block" => MaterialRule::Block(BlockStateId(v[1].as_u64().unwrap() as u32)), + "band" => MaterialRule::Bandlands, + "ore" => MaterialRule::OreVein { + ore: BlockStateId(7), + raw_ore: BlockStateId(8), + filler: BlockStateId(9), + raw_ore_chance: f32::from_bits( + u32::from_str_radix(v[1].as_str().unwrap(), 16).unwrap(), + ), + density: Arc::new(TracedDensity { + inputs: inputs.clone(), + channel: Some(0), + }), + richness: Arc::new(TracedDensity { + inputs: inputs.clone(), + channel: Some(1), + }), + filler_gap: Arc::new(TracedDensity { + inputs: inputs.clone(), + channel: Some(2), + }), + }, + "if" => MaterialRule::Condition { + if_true: condition(&v[1], registry), + then_run: Box::new(rule(&v[2], registry, inputs)), + }, + "sequence" => MaterialRule::Sequence( + v[1].as_array() + .unwrap() + .iter() + .map(|v| rule(v, registry, inputs)) + .collect(), + ), + _ => panic!("unknown rule"), + } +} +fn queries(inputs: &Mutex, out: &mut impl Write) -> io::Result<()> { + for query in inputs.lock().unwrap().queries.drain(..) { + writeln!(out, "{query}")?; + } + Ok(()) +} +struct RuleData { + blocks: BlockRegistry, + integers: BTreeSet<(String, String)>, + densities: BTreeMap, + definitions: BTreeMap, +} +fn metadata_tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(metadata_tag).collect()), + Value::Object(o) => Tag::Compound( + o.iter() + .map(|(k, v)| (k.as_str().into(), metadata_tag(v))) + .collect(), + ), + _ => panic!("invalid registry metadata"), + } +} +impl RuleData { + fn library( + &self, + f: &Value, + conditions: &MaterialConditionRegistry, + noises: &BTreeMap, + query: Option<&str>, + ) -> Result> { + let mut definitions = self.definitions.clone(); + if let Some(query) = query { + definitions.insert("horizon:query".to_owned(), query.to_owned()); + } + let blocks = BlockStateJsonCodec::new(&self.blocks, self.integers.clone())?; + let densities = DensityRegistry::from_json(noises, &self.densities)?; + Ok(MaterialRuleLibrary::from_json( + &definitions, + conditions, + &blocks, + densities, + f["seed"].as_i64().unwrap(), + f["legacy"].as_bool().unwrap(), + )?) + } +} +fn fixture( + f: &Value, + registry: &MaterialConditionRegistry, + noises: &BTreeMap, + biomes: Arc>>, + rules_data: Option<&RuleData>, + mut random: R, + out: &mut impl Write, +) -> Result<(), Box> +where + R::Positional: Clone, +{ + let [min, height, sea] = std::array::from_fn(|i| f["context"][i].as_i64().unwrap() as i32); + let generation = WorldGenerationContext::new(min, height, sea); + let inputs = Arc::new(Mutex::new(Inputs { + biome: Some("minecraft:plains".to_owned()), + density_remaining: -1, + ore_values: f + .get("ore_values") + .map(|v| { + std::array::from_fn(|i| { + f32::from_bits(u32::from_str_radix(v[i].as_str().unwrap(), 16).unwrap()) + }) + }) + .unwrap_or([1.0, 1.0, -1.0]), + ore_remaining: [-1; 3], + ..Inputs::default() + })); + let root = random.fork_positional(); + let mut samplers: Vec> = Vec::new(); + for name in ["clay_bands_offset", "surface", "surface_secondary"] { + let id = format!("minecraft:{name}"); + samplers.push(Arc::new( + decode_noise(&noises[&id])?.create(&mut root.from_hash_of(&id))?, + )); + } + let mut library = rules_data + .map(|data| data.library(f, registry, noises, None)) + .transpose()?; + if let Some(data) = rules_data { + if let Some(values) = f.get("library_json") { + for value in values.as_array().unwrap() { + let result = data.library(f, registry, noises, Some(value.as_str().unwrap())); + writeln!( + out, + "rule decode {}", + if result.is_ok() { "ok" } else { "error" } + )?; + } + } + } + let block_id = |name: &str, fallback| { + rules_data + .map(|data| { + data.blocks + .default_state(&format!("minecraft:{name}")) + .unwrap() + }) + .unwrap_or(BlockStateId(fallback)) + }; + let blocks = ClayBandBlocks { + terracotta: block_id("terracotta", 0), + orange: block_id("orange_terracotta", 1), + yellow: block_id("yellow_terracotta", 2), + brown: block_id("brown_terracotta", 3), + red: block_id("red_terracotta", 4), + white: block_id("white_terracotta", 5), + light_gray: block_id("light_gray_terracotta", 6), + }; + let surface = MaterialSurface::new( + root.clone(), + blocks, + samplers[0].clone(), + samplers[1].clone(), + samplers[2].clone(), + ); + let sources = MaterialNoiseSources::from_json(root.clone(), surface, noises)?; + let surface = Surface { + inputs: inputs.clone(), + noises: sources, + real_noise: f["real_noise"].as_bool().unwrap_or(false), + biomes, + possible: f.get("possible_biomes").filter(|v| !v.is_null()).map(|v| { + v.as_array() + .unwrap() + .iter() + .map(|v| v.as_str().unwrap().to_owned()) + .collect() + }), + }; + let dims: [i32; 9] = f + .get("volume") + .map(|v| std::array::from_fn(|i| v[i].as_i64().unwrap() as i32)) + .unwrap_or([16, 1, 16, 0, 0, 0, 1, 1, 1]); + let expected = DensityVolume::new( + dims[..3].try_into().unwrap(), + dims[3..6].try_into().unwrap(), + dims[6..].try_into().unwrap(), + )?; + let surface = MaterialDensitySources::new( + surface, + expected, + if library.is_some() { + Arc::new(ConstantSampler(0.0)) + } else { + Arc::new(TracedDensity { + inputs: inputs.clone(), + channel: None, + }) + }, + if library.is_some() { + SamplerContext::cached() + } else { + SamplerContext::default() + }, + )?; + let mut worker = MaterialConditions::::new(generation, root, surface); + let mut count = 0; + for c in f["conditions"].as_array().unwrap() { + let value = condition(c, registry); + writeln!(out, "runtime {}", encoded(&value))?; + worker.add(value)?; + count += 1; + } + if let Some(values) = f.get("json") { + for value in values.as_array().unwrap() { + match registry.decode(value.as_str().unwrap()) { + Err(_) => writeln!(out, "decode error")?, + Ok(condition) => { + writeln!(out, "decode {}", encoded(&condition))?; + match worker.add(condition) { + Ok(_) => count += 1, + Err(_) => writeln!(out, "compile error")?, + } + } + } + } + } + let mut rule_count = 0; + if let Some(values) = f.get("rules") { + for value in values.as_array().unwrap() { + worker.add_rule(rule(value, registry, &inputs))?; + queries(&inputs, out)?; + rule_count += 1; + } + } + if let Some(library) = &mut library { + for name in f["library_rules"].as_array().unwrap() { + worker.add_rule(library.rule(name.as_str().unwrap())?)?; + queries(&inputs, out)?; + rule_count += 1; + } + } + for op in f["ops"].as_array().unwrap() { + match op[0].as_str().unwrap() { + "ore_input" => { + let mut i = inputs.lock().unwrap(); + let channel = op[1].as_u64().unwrap() as usize; + i.ore_values[channel] = + f32::from_bits(u32::from_str_radix(op[2].as_str().unwrap(), 16)?); + i.ore_remaining[channel] = op[3].as_i64().unwrap() as i32; + } + "density" => { + let mut i = inputs.lock().unwrap(); + i.density = f32::from_bits(u32::from_str_radix(op[1].as_str().unwrap(), 16)?); + i.density_remaining = op[2].as_i64().unwrap() as i32; + } + "minimum" => { + let value = worker.minimum_surface_level(); + queries(&inputs, out)?; + match value { + Ok(v) => writeln!(out, "minimum {v}")?, + Err(_) => writeln!(out, "minimum error")?, + } + } + "biome" => inputs.lock().unwrap().biome = op[1].as_str().map(str::to_owned), + "rule" => { + let result = worker.add_rule(rule(&op[1], registry, &inputs)); + queries(&inputs, out)?; + match result { + Ok(index) => { + rule_count += 1; + writeln!(out, "rule added {index}")?; + } + Err(_) => writeln!(out, "rule compile error")?, + } + } + "apply" => { + let position = BlockPos::new( + op[1].as_i64().unwrap() as i32, + op[2].as_i64().unwrap() as i32, + op[3].as_i64().unwrap() as i32, + ); + for index in 0..rule_count { + let result = worker.try_apply(index, position); + queries(&inputs, out)?; + match result { + Ok(Some(block)) => writeln!(out, "rule {index} {}", block.0)?, + Ok(None) => writeln!(out, "rule {index} none")?, + Err(_) => writeln!(out, "rule {index} error")?, + } + } + } + "input" => { + let mut i = inputs.lock().unwrap(); + i.depth = op[1].as_i64().unwrap() as i32; + i.secondary = f32::from_bits(u32::from_str_radix(op[2].as_str().unwrap(), 16)?); + } + "xz" => worker.update_xz( + op[1].as_i64().unwrap() as i32, + op[2].as_i64().unwrap() as i32, + op[3].as_i64().unwrap() as i32, + op[4].as_i64().unwrap() as i32, + ), + "y" => worker.update_y( + op[1].as_i64().unwrap() as i32, + op[2].as_i64().unwrap() as i32, + op[3].as_i64().unwrap() as i32, + op[4].as_i64().unwrap() as i32, + ), + "add" => { + let index = worker.add(condition(&op[1], registry))?; + writeln!(out, "added {index}")?; + count += 1; + } + "eval" => { + let indices = if op.as_array().unwrap().len() == 1 { + (0..count).collect() + } else { + op[1] + .as_array() + .unwrap() + .iter() + .map(|i| i.as_u64().unwrap() as usize) + .collect::>() + }; + for index in indices { + let result = worker.test(index); + queries(&inputs, out)?; + match result { + Ok(value) => writeln!(out, "eval {index} {value}")?, + Err(_) => writeln!(out, "eval {index} error")?, + } + } + } + "secondary" => { + let value = worker.surface_secondary(); + queries(&inputs, out)?; + let bits = if value.is_nan() { + 0x7ff8000000000000 + } else { + value.to_bits() + }; + writeln!(out, "secondary {bits:x}")?; + } + _ => panic!("unknown operation"), + } + } + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + let definitions = serde_json::from_str(&fs::read_to_string(dir.join("conditions.json"))?)?; + let biome_definitions: BTreeMap = + serde_json::from_str(&fs::read_to_string(dir.join("biomes.json"))?)?; + let mut temperatures = BTreeMap::new(); + for (name, json) in &biome_definitions { + temperatures.insert( + name.clone(), + BiomeTemperature::new(BiomeTemperatureSettings::from_json(json)?), + ); + } + let biomes = Arc::new(Mutex::new(temperatures)); + let tag_json: BTreeMap = + serde_json::from_str(&fs::read_to_string(dir.join("biome_tags.json"))?)?; + let mut tag_definitions = TagDefinitions::default(); + for (name, json) in tag_json { + tag_definitions.apply_json(&name, "vanilla", &json)?; + } + let tags = tag_definitions + .build(|id, _required| biome_definitions.contains_key(id).then(|| id.to_owned()))?; + assert!(tags.missing.is_empty()); + let registry = MaterialConditionRegistry::from_json_with_biome_tags( + &definitions, + &biome_definitions.keys().cloned().collect(), + &tags.tags, + )?; + let noises = serde_json::from_str(&fs::read_to_string(dir.join("noises.json"))?)?; + let rules_data = if dir.join("rules.json").exists() { + let facts: Value = + serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + Some(RuleData { + blocks: BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", metadata_tag(&facts["states"])), + ("defaults", metadata_tag(&facts["defaults"])), + ]))?, + integers: facts["integers"] + .as_array() + .unwrap() + .iter() + .map(|v| { + ( + v[0].as_str().unwrap().to_owned(), + v[1].as_str().unwrap().to_owned(), + ) + }) + .collect(), + densities: serde_json::from_str(&fs::read_to_string(dir.join("densities.json"))?)?, + definitions: serde_json::from_str(&fs::read_to_string(dir.join("rules.json"))?)?, + }) + } else { + None + }; + for (name, value) in registry.entries() { + writeln!(out, "registry {name} {}", encoded(value))?; + } + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture( + &f, + ®istry, + &noises, + biomes.clone(), + rules_data.as_ref(), + LegacyRandom::new(seed), + &mut out, + )? + } else { + fixture( + &f, + ®istry, + &noises, + biomes.clone(), + rules_data.as_ref(), + XoroshiroRandom::new(seed), + &mut out, + )? + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/examples/material_extension_fixture.rs b/crates/horizon-world/examples/material_extension_fixture.rs new file mode 100644 index 000000000..a48943723 --- /dev/null +++ b/crates/horizon-world/examples/material_extension_fixture.rs @@ -0,0 +1,208 @@ +//! Original column-extension comparison transport. +use horizon_core::{ + noise::{NanRange, Noise}, + random::{LegacyRandom, PositionalRandom, RandomSource, XoroshiroRandom}, +}; +use horizon_world::{ + registry::BlockStateId, + worldgen::{ + biome_temperature::{BiomeTemperature, BiomeTemperatureSettings}, + decode_noise, + material_extensions::{ + ExtensionBlocks, ExtensionNoises, MaterialColumn, MaterialExtensions, + }, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + io::{self, Write}, + path::Path, + sync::{Arc, Mutex}, +}; +const NAMES: [&str; 6] = [ + "badlands_surface", + "badlands_pillar", + "badlands_pillar_roof", + "iceberg_surface", + "iceberg_pillar", + "iceberg_pillar_roof", +]; +#[derive(Debug)] +struct TracedNoise { + name: &'static str, + real: Arc, + constant: Option, + trace: Arc>>, +} +impl Noise for TracedNoise { + fn range(&self) -> Result<[f32; 2], NanRange> { + Ok([f32::NEG_INFINITY, f32::INFINITY]) + } + fn get2(&self, _: f64, _: f64) -> f32 { + panic!("unexpected 2D noise query") + } + fn get3(&self, x: f64, y: f64, z: f64) -> f32 { + self.trace.lock().unwrap().push(format!( + "noise {} {:x} {:x} {:x}", + self.name, + x.to_bits(), + y.to_bits(), + z.to_bits() + )); + self.constant.unwrap_or_else(|| self.real.get3(x, y, z)) + } +} +struct Column { + min: i32, + values: Vec, + remaining: i32, + trace: Arc>>, +} +impl Column { + fn index(&self, y: i32) -> Option { + let i = i64::from(y) - i64::from(self.min); + (i >= 0 && i < self.values.len() as i64).then_some(i as usize) + } +} +impl MaterialColumn for Column { + type Error = io::Error; + fn block(&mut self, y: i32) -> io::Result { + if self.remaining == 0 { + self.trace.lock().unwrap().push(format!("read error {y}")); + return Err(io::Error::other("fixture read limit")); + } + self.remaining -= 1; + let id = self + .index(y) + .map(|i| self.values[i]) + .unwrap_or(BlockStateId(2)); + self.trace + .lock() + .unwrap() + .push(format!("read {y} {}", id.0)); + Ok(id) + } + fn set_block(&mut self, y: i32, state: BlockStateId) -> io::Result<()> { + self.trace + .lock() + .unwrap() + .push(format!("write {y} {}", state.0)); + if let Some(i) = self.index(y) { + self.values[i] = state; + } + Ok(()) + } + fn is_air(&self, state: BlockStateId) -> bool { + state.0 <= 2 + } + fn same_block(&self, a: BlockStateId, b: BlockStateId) -> bool { + let kind = |id: BlockStateId| match id.0 { + 5 => 4, + 9 => 8, + other => other, + }; + kind(a) == kind(b) + } +} +fn fixture( + f: &Value, + noises: &BTreeMap, + biomes: &BTreeMap, + mut random: R, + out: &mut impl Write, +) -> Result<(), Box> +where + R::Positional: Clone, +{ + let root = random.fork_positional(); + let trace = Arc::new(Mutex::new(Vec::new())); + let mut sources = Vec::>::new(); + for (i, name) in NAMES.iter().enumerate() { + let id = format!("minecraft:{name}"); + sources.push(Arc::new(TracedNoise { + name, + real: Arc::new(decode_noise(&noises[&id])?.create(&mut root.from_hash_of(&id))?), + constant: f + .get("noise_bits") + .map(|v| f32::from_bits(u32::from_str_radix(v[i].as_str().unwrap(), 16).unwrap())), + trace: trace.clone(), + })); + } + let system = MaterialExtensions::new( + root, + ExtensionBlocks { + default: BlockStateId(f["default"].as_u64().unwrap() as u32), + water: BlockStateId(4), + packed_ice: BlockStateId(7), + snow: BlockStateId(6), + }, + ExtensionNoises { + badlands_surface: sources[0].clone(), + badlands_pillar: sources[1].clone(), + badlands_roof: sources[2].clone(), + iceberg_surface: sources[3].clone(), + iceberg_pillar: sources[4].clone(), + iceberg_roof: sources[5].clone(), + }, + f["sea"].as_i64().unwrap() as i32, + ); + let mut biome = BiomeTemperature::new(BiomeTemperatureSettings::from_json( + &biomes[f["biome"].as_str().unwrap()], + )?); + let mut column = Column { + min: f["min"].as_i64().unwrap() as i32, + values: f["initial"] + .as_array() + .unwrap() + .iter() + .map(|v| BlockStateId(v.as_u64().unwrap() as u32)) + .collect(), + remaining: 0, + trace: trace.clone(), + }; + for op in f["ops"].as_array().unwrap() { + column.remaining = f["limit"].as_i64().unwrap() as i32; + let x = op[1].as_i64().unwrap() as i32; + let z = op[2].as_i64().unwrap() as i32; + let surface = op[3].as_i64().unwrap() as i32; + let minimum = op[4].as_i64().unwrap() as i32; + let result = match op[0].as_str().unwrap() { + "badlands" => system.eroded_badlands(&mut column, x, z, surface, minimum), + "frozen" => system.frozen_ocean(&mut column, &mut biome, [x, z], surface, minimum), + _ => panic!("unknown extension"), + }; + for event in trace.lock().unwrap().drain(..) { + writeln!(out, "{event}")?; + } + writeln!( + out, + "result {}", + if result.is_ok() { "ok" } else { "error" } + )?; + write!(out, "column")?; + for id in &column.values { + write!(out, " {}", id.0)?; + } + writeln!(out)?; + } + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let noises = serde_json::from_str(&fs::read_to_string(dir.join("noises.json"))?)?; + let biomes = serde_json::from_str(&fs::read_to_string(dir.join("biomes.json"))?)?; + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, &noises, &biomes, LegacyRandom::new(seed), &mut out)?; + } else { + fixture(&f, &noises, &biomes, XoroshiroRandom::new(seed), &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/material_stage_fixture.rs b/crates/horizon-world/examples/material_stage_fixture.rs new file mode 100644 index 000000000..6682b04b7 --- /dev/null +++ b/crates/horizon-world/examples/material_stage_fixture.rs @@ -0,0 +1,838 @@ +//! Original transport for complete surface-stage chunk comparison. +use horizon_core::{ + biome::{BiomeZoom, obfuscate_seed}, + carving::CarvingMask, + density::{ConstantSampler, SamplerContext}, + noise::{DensityVolume, Noise}, + position::{BlockPos, ChunkPos}, + random::{LegacyRandom, PositionalRandom, RandomSource, XoroshiroRandom}, +}; +use horizon_world::{ + DATA_VERSION, + heightmap::{HeightmapState, HeightmapType}, + nbt::Tag, + registry::{BlockRegistry, BlockStateId, BlockStateJsonCodec}, + worldgen::{ + DecodeError, + anchor::WorldGenerationContext, + aquifer::{ + AquiferConfig, AquiferError, DisabledAquifer, GlobalFluidPicker, NoiseBasedAquifer, + RegistryAquiferBlockStates, + }, + biome_chunk::BiomeChunk, + biome_source::{BiomeSourceCatalog, BiomeSourceResolver}, + biome_temperature::{BiomeTemperature, BiomeTemperatureSettings}, + carver::{CarverCatalog, WorldCarver, generate_carving_mask}, + carving::{CarvingBlocks, apply_carving_mask}, + decode_noise, + density::DensityRegistry, + material_condition::{ + MaterialConditionRegistry, MaterialNoiseSources, MaterialRuleError, + MaterialRuleLibrary, MaterialSurfaceQueries, + }, + material_extensions::{ExtensionBlocks, ExtensionNoises, MaterialExtensions}, + material_stage::{SurfaceInputs, TopMaterialInputs, build_surface, top_material}, + material_surface::{ClayBandBlocks, MaterialSurface}, + router::{NoiseRouter, RouterField}, + tags::TagDefinitions, + terrain::{TerrainAquifer, TerrainBlockStates, TerrainChunk, fill_noise}, + }, +}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + io::{self, Write}, + path::Path, + sync::{Arc, Mutex}, +}; +#[derive(Clone, Copy)] +struct State { + air: bool, + air_block: bool, + fluid: bool, + motion: bool, + no_leaves: bool, +} +impl HeightmapState for State { + fn is_air(self) -> bool { + self.air + } + fn is_air_block(self) -> bool { + self.air_block + } + fn has_fluid(self) -> bool { + self.fluid + } + fn blocks_motion_in_heightmap(self) -> bool { + self.motion + } + fn blocks_motion_in_heightmap_no_leaves(self) -> bool { + self.no_leaves + } +} +struct Properties<'a>(&'a [State]); +impl TerrainBlockStates for Properties<'_> { + type State = State; + fn heightmap_state(&self, id: BlockStateId) -> State { + self.0[id.0 as usize] + } +} +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(o) => { + Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +type BiomeNeighborhood = BTreeMap<(i32, i32), BiomeChunk>>; +type Temperatures = Arc>>; +struct Surface { + noises: MaterialNoiseSources>, + choices: Vec>, + zoom: Option, + neighborhood: Option, + possible: Option>, + temperatures: Temperatures, + trace: Arc>>, +} +impl MaterialSurfaceQueries for Surface

{ + fn surface_depth(&mut self, x: i32, z: i32) -> i32 { + self.noises.surface_depth(x, z) + } + fn surface_secondary(&mut self, x: i32, z: i32) -> f64 { + self.noises.surface_secondary(x, z) + } + fn band(&mut self, p: BlockPos) -> Result { + self.noises.band(p) + } + fn bind_noise(&mut self, name: &str) -> Result, DecodeError> { + self.noises.bind_noise(name) + } + fn possible_biomes(&self) -> Option> { + self.possible.clone() + } + fn biome(&mut self, p: BlockPos) -> Result>, MaterialRuleError> { + let [x, y, z] = self + .zoom + .map_or([p.x, p.y, p.z], |zoom| zoom.quart_at_block(p)); + let hash = x + .wrapping_mul(31) + .wrapping_add(y.wrapping_mul(7)) + .wrapping_add(z.wrapping_mul(17)); + let name = if let Some(chunks) = &self.neighborhood { + chunks + .get(&(x >> 2, z >> 2)) + .ok_or(MaterialRuleError::MissingBiome)? + .noise_biome([x, y, z]) + .clone() + } else { + self.choices[hash.rem_euclid(self.choices.len() as i32) as usize].clone() + }; + if self.zoom.is_some() { + self.trace + .lock() + .unwrap() + .push(format!("quart {x} {y} {z} {name}")); + } + self.trace + .lock() + .unwrap() + .push(format!("biome {} {} {} {name}", p.x, p.y, p.z)); + Ok(Some(name)) + } + fn cold_enough_to_snow( + &mut self, + name: &str, + p: BlockPos, + sea: i32, + ) -> Result { + Ok(self + .temperatures + .lock() + .unwrap() + .get_mut(name) + .unwrap() + .cold_enough_to_snow(p, sea)) + } + fn melts_frozen_ocean( + &mut self, + name: &str, + p: BlockPos, + sea: i32, + ) -> Result { + Ok(self + .temperatures + .lock() + .unwrap() + .get_mut(name) + .unwrap() + .should_melt_frozen_ocean_iceberg_slightly(p, sea)) + } +} +struct Data { + registry: BlockRegistry, + integers: BTreeSet<(String, String)>, + properties: Vec, + carving_blocks: CarvingBlocks, + biome_carvers: BTreeMap>>, + conditions: MaterialConditionRegistry, + noises: BTreeMap, + densities: BTreeMap, + rules: BTreeMap, + presets: BTreeMap, + source_catalog: BiomeSourceCatalog, + temperatures: Temperatures, +} +fn biome_neighborhood( + f: &Value, + resolver: Option<&mut BiomeSourceResolver<'_>>, + out: &mut impl Write, +) -> Result, Box> { + let Some(resolver) = resolver else { + return Ok(None); + }; + let (cx, cz, min, height) = (n(&f["cx"]), n(&f["cz"]), n(&f["min"]), n(&f["height"])); + let mut chunks = BTreeMap::new(); + for dx in -1..=1 { + for dz in -1..=1 { + let (x, z) = (cx.wrapping_add(dx), cz.wrapping_add(dz)); + let mut chunk = BiomeChunk::new( + ChunkPos::new(x, z), + min, + height, + Arc::::from("minecraft:plains"), + )?; + let mut context = SamplerContext::cached(); + let volume = resolver.prepare_volume( + &mut context, + [x.wrapping_shl(4) >> 2, min >> 2, z.wrapping_shl(4) >> 2], + [4, height >> 2, 4], + )?; + chunk.fill(min, min + height - 1, |quart| { + resolver + .sample_prepared(&mut context, volume.as_ref(), quart) + .map(Arc::from) + })?; + writeln!(out, "biomechunk {x} {z}")?; + for section in 0..height as usize / 16 { + for name in chunk.section(section).unwrap() { + writeln!(out, "stored {name}")?; + } + } + chunks.insert((x, z), chunk); + } + } + Ok(Some(chunks)) +} +fn fixture( + f: &Value, + data: &Data, + mut random: R, + out: &mut impl Write, +) -> Result<(), Box> +where + R::Positional: Clone, +{ + let root = random.fork_positional(); + let seed = f["seed"].as_i64().unwrap(); + let legacy = f["legacy"].as_bool().unwrap(); + let codec = BlockStateJsonCodec::new(&data.registry, data.integers.clone())?; + let mut densities = DensityRegistry::from_json(&data.noises, &data.densities)?; + let router = f + .get("router") + .map(|value| NoiseRouter::from_json(&value.to_string(), &mut densities)) + .transpose()?; + let aquifers = f + .get("aquifers") + .filter(|value| !value.is_null()) + .map(|value| AquiferConfig::from_json(&value.to_string(), &mut densities)) + .transpose()?; + let mut library = MaterialRuleLibrary::from_json( + &data.rules, + &data.conditions, + &codec, + densities, + seed, + legacy, + )?; + let router = router + .map(|value| library.compile_router(value)) + .transpose()?; + let aquifers = aquifers + .map(|value| library.compile_aquifer(value)) + .transpose()?; + let rule = library.rule(f["rule"].as_str().unwrap())?; + let preliminary = if let Some(ref router) = router { + router.get(RouterField::ChunkSurfaceLevel).clone() + } else if let Some(name) = f["preliminary"].as_str() { + library.named_density(name)? + } else { + Arc::new(ConstantSampler(f["preliminary"].as_f64().unwrap() as f32)) + }; + let source = f + .get("biome_source_json") + .map(|json| { + data.source_catalog + .decode(&json.to_string())? + .resolve(&data.presets) + }) + .transpose()?; + let climate = router.as_ref().map(|r| r.climate_sampler()); + let mut biome_resolver = source.as_ref().map(|source| { + source.resolver( + climate.as_ref().unwrap(), + router.as_ref().unwrap().get(RouterField::Erosion).as_ref(), + ) + }); + let neighborhood = biome_neighborhood(f, biome_resolver.as_mut(), out)?; + let sampler = |name: &str| -> Result, DecodeError> { + let id = format!("minecraft:{name}"); + Ok(Arc::new( + decode_noise(&data.noises[&id])?.create(&mut root.from_hash_of(&id))?, + )) + }; + let surface = MaterialSurface::new( + root.clone(), + ClayBandBlocks::from_registry(&data.registry).unwrap(), + sampler("clay_bands_offset")?, + sampler("surface")?, + sampler("surface_secondary")?, + ); + let trace = Arc::new(Mutex::new(Vec::new())); + let mut surface = Surface { + noises: MaterialNoiseSources::from_json(root.clone(), surface, &data.noises)?, + neighborhood, + zoom: f["biome_zoom"] + .as_bool() + .unwrap_or(false) + .then(|| BiomeZoom::new(obfuscate_seed(seed))), + choices: f["biome_choices"] + .as_array() + .unwrap() + .iter() + .map(|v| Arc::from(v.as_str().unwrap())) + .collect(), + possible: f["possible"] + .as_array() + .map(|v| v.iter().map(|v| v.as_str().unwrap().to_owned()).collect()), + temperatures: data.temperatures.clone(), + trace: trace.clone(), + }; + let extensions = MaterialExtensions::new( + root.clone(), + ExtensionBlocks { + default: BlockStateId(f["default"].as_u64().unwrap() as u32), + water: data.registry.default_state("minecraft:water").unwrap(), + packed_ice: data.registry.default_state("minecraft:packed_ice").unwrap(), + snow: data.registry.default_state("minecraft:snow_block").unwrap(), + }, + ExtensionNoises { + badlands_surface: sampler("badlands_surface")?, + badlands_pillar: sampler("badlands_pillar")?, + badlands_roof: sampler("badlands_pillar_roof")?, + iceberg_surface: sampler("iceberg_surface")?, + iceberg_pillar: sampler("iceberg_pillar")?, + iceberg_roof: sampler("iceberg_pillar_roof")?, + }, + n(&f["sea"]), + ); + let (cx, cz, min, height) = (n(&f["cx"]), n(&f["cz"]), n(&f["min"]), n(&f["height"])); + let mut chunk = TerrainChunk::new( + ChunkPos::new(cx, cz), + min, + height, + &data.registry, + Properties(&data.properties), + )?; + for span in f["initial"].as_array().unwrap() { + for y in n(&span[1])..=n(&span[3]) { + chunk.set_block_raw( + n(&span[0]), + y, + n(&span[2]), + BlockStateId(span[4].as_u64().unwrap() as u32), + )?; + } + } + if f["prime"].as_bool().unwrap() { + chunk.prime_heightmaps(&[HeightmapType::WorldSurfaceWg, HeightmapType::OceanFloorWg])?; + } + let mut context = SamplerContext::cached(); + let volume = DensityVolume::new( + [16, n(&f["noise_height"]), 16], + [cx.wrapping_shl(4), n(&f["noise_min"]), cz.wrapping_shl(4)], + [1; 3], + )?; + let air = data.registry.default_state("minecraft:air").unwrap(); + let picker = GlobalFluidPicker::new( + n(&f["sea"]), + f.get("fluid").map_or_else( + || data.registry.default_state("minecraft:water").unwrap(), + |v| BlockStateId(v.as_u64().unwrap() as u32), + ), + data.registry.default_state("minecraft:lava").unwrap(), + air, + ); + let mut aquifer: Box = if let Some(samplers) = aquifers { + Box::new(NoiseBasedAquifer::new( + samplers, + picker, + root.from_hash_of("minecraft:aquifer").fork_positional(), + RegistryAquiferBlockStates::new(&data.registry)?, + volume, + &mut context, + )?) + } else { + Box::new(DisabledAquifer::new(picker, air)) + }; + if let Some(ref router) = router { + fill_noise( + &mut chunk, + volume, + router.get(RouterField::FinalDensity).as_ref(), + &mut context, + aquifer.as_mut(), + BlockStateId(f["default"].as_u64().unwrap() as u32), + )?; + writeln!(out, "terrain {}", aquifer.should_schedule_fluid_update())?; + dump(&mut chunk, height, out)?; + } + for repeat in 0..n(&f["repeats"]) { + let inputs = SurfaceInputs:: { + generation: WorldGenerationContext::new(min, height, n(&f["sea"])), + noise_volume: volume, + root: root.clone(), + surface: &mut surface, + preliminary_surface: preliminary.clone(), + density_context: &mut context, + write_min_y: n(&f["write_min"]), + write_max_y: n(&f["write_max"]), + }; + let result = build_surface(&mut chunk, rule.clone(), inputs, &extensions); + for event in trace.lock().unwrap().drain(..) { + writeln!(out, "{event}")?; + } + writeln!( + out, + "surface {repeat} {}", + if result.is_ok() { "ok" } else { "error" } + )?; + if let Err(error) = result { + eprintln!("surface failure: {error}"); + } + dump(&mut chunk, height, out)?; + } + for query in f["top_queries"].as_array().unwrap() { + let position = BlockPos::new(n(&query[0]), n(&query[1]), n(&query[2])); + let result = top_material( + &mut chunk, + rule.clone(), + TopMaterialInputs:: { + generation: WorldGenerationContext::new(min, height, n(&f["sea"])), + root: root.clone(), + surface: &mut surface, + preliminary_surface: preliminary.clone(), + density_context: &mut context, + }, + position, + query[3].as_bool().unwrap(), + ); + for event in trace.lock().unwrap().drain(..) { + writeln!(out, "{event}")?; + } + match result { + Ok(Some(state)) => writeln!(out, "top {}", state.0)?, + Ok(None) => writeln!(out, "top none")?, + Err(error) => { + writeln!(out, "top error")?; + eprintln!("top failure: {error}"); + } + } + } + if let Some(resolver) = biome_resolver.as_mut() { + let mut biome_context = SamplerContext::default(); + let generation = WorldGenerationContext::new(min, height, n(&f["sea"])); + let generated = + generate_carving_mask(seed, ChunkPos::new(cx, cz), generation, false, |origin| { + let quart = [ + origin.x.wrapping_shl(4) >> 2, + 0, + origin.z.wrapping_shl(4) >> 2, + ]; + let name = raw_biome(resolver, &mut biome_context, quart, &trace)?; + data.biome_carvers + .get(name.as_ref()) + .map(Vec::as_slice) + .ok_or(MaterialRuleError::MissingBiome) + })?; + let mut traced = TracedAquifer { + inner: aquifer.as_mut(), + trace: trace.clone(), + }; + let result = if generated.is_empty() { + Ok(()) + } else { + apply_carving_mask( + &mut chunk, + &generated, + rule.clone(), + TopMaterialInputs:: { + generation, + root: root.clone(), + surface: CarverSurface { + surface: &mut surface, + resolver, + context: &mut biome_context, + zoom: BiomeZoom::new(obfuscate_seed(seed)), + trace: trace.clone(), + }, + preliminary_surface: preliminary.clone(), + density_context: &mut context, + }, + &mut traced, + &data.carving_blocks, + |_| true, + ) + }; + for event in trace.lock().unwrap().drain(..) { + writeln!(out, "{event}")?; + } + writeln!( + out, + "generatedcarving {}", + if result.is_ok() { "ok" } else { "error" } + )?; + if let Err(error) = result { + eprintln!("generated carving failure: {error}"); + } + dump(&mut chunk, height, out)?; + } + let carving = &f["carving"]; + for q in carving["initial"].as_array().unwrap() { + chunk.set_block_worldgen( + n(&q[0]), + n(&q[1]), + n(&q[2]), + BlockStateId(q[3].as_u64().unwrap() as u32), + )?; + } + let mut mask = CarvingMask::new(min + 1, min + height - 8)?; + for q in carving["spans"].as_array().unwrap() { + for y in n(&q[2])..=n(&q[3]) { + mask.carve(n(&q[0]), y, n(&q[1]))?; + } + } + let mut traced = TracedAquifer { + inner: aquifer.as_mut(), + trace: trace.clone(), + }; + for mode in carving["filters"].as_array().unwrap() { + let mode = n(mode); + let result = apply_carving_mask( + &mut chunk, + &mask, + rule.clone(), + TopMaterialInputs:: { + generation: WorldGenerationContext::new(min, height, n(&f["sea"])), + root: root.clone(), + surface: &mut surface, + preliminary_surface: preliminary.clone(), + density_context: &mut context, + }, + &mut traced, + &data.carving_blocks, + |[x, y, z]| { + if mode == 0 { + return true; + } + let keep = mode == 1 + && x.wrapping_mul(31) + .wrapping_add(y.wrapping_mul(7)) + .wrapping_add(z.wrapping_mul(17)) + .rem_euclid(5) + != 0; + trace + .lock() + .unwrap() + .push(format!("filter {x} {y} {z} {keep}")); + keep + }, + ); + for event in trace.lock().unwrap().drain(..) { + writeln!(out, "{event}")?; + } + writeln!( + out, + "carving {mode} {}", + if result.is_ok() { "ok" } else { "error" } + )?; + if let Err(error) = result { + eprintln!("carving failure: {error}"); + } + dump(&mut chunk, height, out)?; + } + Ok(()) +} +fn raw_biome( + resolver: &mut BiomeSourceResolver<'_>, + context: &mut SamplerContext, + [x, y, z]: [i32; 3], + trace: &Arc>>, +) -> Result, MaterialRuleError> { + let name = resolver + .sample(context, [x, y, z]) + .map_err(|_| MaterialRuleError::BiomeQueryFailed)?; + trace + .lock() + .unwrap() + .push(format!("rawquart {x} {y} {z} {name}")); + Ok(Arc::from(name)) +} +struct CarverSurface<'a, 'b, P: PositionalRandom> { + surface: &'a mut Surface

, + resolver: &'a mut BiomeSourceResolver<'b>, + context: &'a mut SamplerContext, + zoom: BiomeZoom, + trace: Arc>>, +} +impl MaterialSurfaceQueries for CarverSurface<'_, '_, P> { + fn surface_depth(&mut self, x: i32, z: i32) -> i32 { + self.surface.surface_depth(x, z) + } + fn surface_secondary(&mut self, x: i32, z: i32) -> f64 { + self.surface.surface_secondary(x, z) + } + fn band(&mut self, p: BlockPos) -> Result { + self.surface.band(p) + } + fn bind_noise(&mut self, name: &str) -> Result, DecodeError> { + self.surface.bind_noise(name) + } + fn biome(&mut self, p: BlockPos) -> Result>, MaterialRuleError> { + raw_biome( + self.resolver, + self.context, + self.zoom.quart_at_block(p), + &self.trace, + ) + .map(Some) + } + fn cold_enough_to_snow( + &mut self, + name: &str, + p: BlockPos, + sea: i32, + ) -> Result { + self.surface.cold_enough_to_snow(name, p, sea) + } + fn melts_frozen_ocean( + &mut self, + name: &str, + p: BlockPos, + sea: i32, + ) -> Result { + self.surface.melts_frozen_ocean(name, p, sea) + } +} +struct TracedAquifer<'a> { + inner: &'a mut dyn TerrainAquifer, + trace: Arc>>, +} +impl TerrainAquifer for TracedAquifer<'_> { + fn compute_substance( + &mut self, + context: &mut SamplerContext, + [x, y, z]: [i32; 3], + density: f64, + ) -> Result, AquiferError> { + self.trace + .lock() + .unwrap() + .push(format!("aquifer {x} {y} {z} {:x}", density.to_bits())); + let result = self.inner.compute_substance(context, [x, y, z], density)?; + self.trace.lock().unwrap().push(format!( + "substance {}", + result.map_or_else(|| "none".to_owned(), |v| v.0.to_string()) + )); + Ok(result) + } + fn should_schedule_fluid_update(&self) -> bool { + let result = self.inner.should_schedule_fluid_update(); + self.trace + .lock() + .unwrap() + .push(format!("fluid_schedule {result}")); + result + } +} +fn dump( + chunk: &mut TerrainChunk<'_, B>, + height: i32, + out: &mut impl Write, +) -> Result<(), Box> { + for section in 0..height as usize / 16 { + writeln!(out, "section {section}")?; + let data = chunk.section(section).unwrap(); + for y in 0..16 { + for z in 0..16 { + write!(out, "blocks")?; + for x in 0..16 { + write!(out, " {}", data.get((y << 8) | (z << 4) | x)?.0)?; + } + writeln!(out)?; + } + } + } + for kind in [HeightmapType::WorldSurfaceWg, HeightmapType::OceanFloorWg] { + writeln!(out, "heightmap {}", kind.name())?; + for word in chunk.ensure_heightmap(kind).raw_data() { + writeln!(out, "{word:x}")?; + } + } + for (section, offsets) in chunk.postprocessing().iter().enumerate() { + writeln!(out, "post {section} {}", offsets.len())?; + for offset in offsets { + writeln!(out, "{offset}")?; + } + } + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let read = |name: &str| -> Result, Box> { + Ok(serde_json::from_str(&fs::read_to_string( + dir.join(format!("{name}.json")), + )?)?) + }; + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List( + facts["states"] + .as_array() + .unwrap() + .iter() + .map(|v| tag(&v[4])) + .collect(), + ), + ), + ("defaults", tag(&facts["defaults"])), + ]))?; + let biomes = read("biomes")?; + let mut temperatures = BTreeMap::new(); + for (name, raw) in &biomes { + temperatures.insert( + name.clone(), + BiomeTemperature::new(BiomeTemperatureSettings::from_json(raw)?), + ); + } + let mut biome_tags = TagDefinitions::default(); + for (name, raw) in read("biome_tags")? { + biome_tags.apply_json(&name, "vanilla", &raw)?; + } + let biome_tags = biome_tags.build(|id, _| biomes.contains_key(id).then(|| id.to_owned()))?; + assert!(biome_tags.missing.is_empty()); + let conditions = MaterialConditionRegistry::from_json_with_biome_tags( + &read("conditions")?, + &biomes.keys().cloned().collect(), + &biome_tags.tags, + )?; + let mut block_tags = TagDefinitions::default(); + for (name, raw) in read("block_tags")? { + block_tags.apply_json(&name, "vanilla", &raw)?; + } + let block_tags = block_tags.build(|id, _| facts["defaults"].get(id).map(|_| id.to_owned()))?; + assert!(block_tags.missing.is_empty()); + let motion: BTreeSet<_> = block_tags.tags["minecraft:blocks_motion_in_heightmap"] + .iter() + .map(String::as_str) + .collect(); + let no_leaves: BTreeSet<_> = block_tags.tags["minecraft:blocks_motion_in_heightmap_no_leaves"] + .iter() + .map(String::as_str) + .collect(); + let properties = facts["states"] + .as_array() + .unwrap() + .iter() + .map(|v| { + let name = v[0].as_str().unwrap(); + State { + air: v[1].as_bool().unwrap(), + air_block: name == "minecraft:air", + fluid: v[2].as_bool().unwrap(), + motion: motion.contains(name), + no_leaves: no_leaves.contains(name), + } + }) + .collect(); + let integers = facts["integers"] + .as_array() + .unwrap() + .iter() + .map(|v| { + ( + v[0].as_str().unwrap().to_owned(), + v[1].as_str().unwrap().to_owned(), + ) + }) + .collect(); + let presets = read("presets")?; + let source_catalog = BiomeSourceCatalog::new( + &biomes.keys().cloned().collect(), + &biome_tags.tags, + &presets.keys().cloned().collect(), + )?; + let carving_blocks = CarvingBlocks::from_registry( + ®istry, + &block_tags.tags["minecraft:uncarvable"] + .iter() + .cloned() + .collect(), + )?; + let carvers = CarverCatalog::from_json(&read("carvers")?)?; + let mut biome_carvers = BTreeMap::new(); + for (name, json) in &biomes { + let value: Value = serde_json::from_str(json)?; + biome_carvers.insert( + name.clone(), + carvers.decode_set(&value["carvers"].to_string())?, + ); + } + let data = Data { + biome_carvers, + carving_blocks, + registry, + integers, + properties, + conditions, + noises: read("noises")?, + densities: read("densities")?, + rules: read("rules")?, + presets, + source_catalog, + temperatures: Arc::new(Mutex::new(temperatures)), + }; + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, &data, LegacyRandom::new(seed), &mut out)?; + } else { + fixture(&f, &data, XoroshiroRandom::new(seed), &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/material_surface_fixture.rs b/crates/horizon-world/examples/material_surface_fixture.rs new file mode 100644 index 000000000..c7cb93bbd --- /dev/null +++ b/crates/horizon-world/examples/material_surface_fixture.rs @@ -0,0 +1,137 @@ +//! Original comparison transport for terracotta bands and surface queries. +use horizon_core::{ + noise::{NanRange, Noise}, + random::{LegacyRandom, PositionalRandom, RandomSource, XoroshiroRandom}, +}; +use horizon_world::{ + registry::BlockStateId, + worldgen::{ + decode_noise, + material_surface::{ClayBandBlocks, ClayBands, MaterialSurface}, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + io::{self, Write}, + path::Path, + sync::Arc, +}; +#[derive(Debug)] +struct ConstantNoise(f32); +impl Noise for ConstantNoise { + fn range(&self) -> Result<[f32; 2], NanRange> { + Ok([f32::NEG_INFINITY, f32::INFINITY]) + } + fn get2(&self, _: f64, _: f64) -> f32 { + panic!("unexpected 2d noise query") + } + fn get3(&self, _: f64, y: f64, _: f64) -> f32 { + assert_eq!(y, 0.); + self.0 + } +} +fn blocks() -> ClayBandBlocks { + ClayBandBlocks { + terracotta: BlockStateId(0), + orange: BlockStateId(1), + yellow: BlockStateId(2), + brown: BlockStateId(3), + red: BlockStateId(4), + white: BlockStateId(5), + light_gray: BlockStateId(6), + } +} +fn fixture( + f: &Value, + mut direct: R, + root: R::Positional, + noises: &BTreeMap, + out: &mut impl Write, +) -> Result<(), Box> { + if f["child"].as_bool().unwrap() { + direct = direct + .fork_positional() + .from_hash_of("minecraft:clay_bands"); + } + direct.consume_count(f["consume"].as_i64().unwrap() as i32); + let bands = ClayBands::generate(&mut direct, blocks()); + writeln!(out, "bands {}", bands.states().len())?; + for state in bands.states() { + writeln!(out, "{}", state.0)?; + } + writeln!(out, "next {} {}", direct.next_long(), direct.next_int())?; + let mut samplers: Vec> = Vec::new(); + for (i, name) in ["clay_bands_offset", "surface", "surface_secondary"] + .iter() + .enumerate() + { + let sampler: Arc = if let Some(bits) = f["overrides"][i].as_str() { + Arc::new(ConstantNoise(f32::from_bits(u32::from_str_radix( + bits, 16, + )?))) + } else { + let id = format!("minecraft:{name}"); + Arc::new(decode_noise(&noises[&id])?.create(&mut root.from_hash_of(&id))?) + }; + samplers.push(sampler); + } + let surface = MaterialSurface::new( + root, + blocks(), + samplers[0].clone(), + samplers[1].clone(), + samplers[2].clone(), + ); + writeln!(out, "system bands")?; + for state in surface.bands().states() { + writeln!(out, "{}", state.0)?; + } + for p in f["points"].as_array().unwrap() { + let [x, y, z] = std::array::from_fn(|i| p[i].as_i64().unwrap() as i32); + match surface.band([x, y, z]) { + Some(state) => writeln!(out, "band {}", state.0)?, + None => writeln!(out, "band error")?, + } + writeln!(out, "depth {}", surface.surface_depth(x, z))?; + let value = surface.surface_secondary(x, z); + let bits = if value.is_nan() { + 0x7ff8000000000000 + } else { + value.to_bits() + }; + writeln!(out, "secondary {bits:x}")?; + } + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private directory"); + let dir = Path::new(&arg); + let noises: BTreeMap = + serde_json::from_str(&fs::read_to_string(dir.join("noises.json"))?)?; + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture( + &f, + LegacyRandom::new(seed), + LegacyRandom::new(seed).fork_positional(), + &noises, + &mut out, + )?; + } else { + fixture( + &f, + XoroshiroRandom::new(seed), + XoroshiroRandom::new(seed).fork_positional(), + &noises, + &mut out, + )?; + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/examples/piston_shape_fixture.rs b/crates/horizon-world/examples/piston_shape_fixture.rs new file mode 100644 index 000000000..06c62803b --- /dev/null +++ b/crates/horizon-world/examples/piston_shape_fixture.rs @@ -0,0 +1,190 @@ +use horizon_core::geometry::{Aabb, Axis, Direction, VoxelShape}; +use horizon_world::{ + collision::CachedCollisionRegistry, + dynamic_support::{DynamicSupport, DynamicSupportWorld}, + nbt::{self, Limits, Tag}, + piston_shape::{MovingPistonState, PistonBlockBindings, PistonCollisionWorld}, + registry::{BlockRegistry, BlockStateId}, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn values( + out: &mut impl Write, + label: &str, + values: impl IntoIterator, +) -> io::Result<()> { + write!(out, "{label}")?; + for v in values { + let bits = if v.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + v.to_bits() + }; + write!(out, " {bits:016x}")?; + } + writeln!(out) +} +fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { + values( + out, + label, + [ + b.min(Axis::X), + b.min(Axis::Y), + b.min(Axis::Z), + b.max(Axis::X), + b.max(Axis::Y), + b.max(Axis::Z), + ], + ) +} +fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { + writeln!( + out, + "shape {} {} {}", + shape.is_empty(), + shape.boxes().len(), + shape.is_cube() + )?; + for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { + values(out, name, shape.coordinates(axis).iter().copied())?; + } + let axes = shape.cube_coordinate_axes(); + writeln!( + out, + "axes {}", + u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) + )?; + values( + out, + "extrema", + Axis::ALL + .map(|a| shape.min(a)) + .into_iter() + .chain(Axis::ALL.map(|a| shape.max(a))), + )?; + match shape.bounds() { + Some(b) => box_values(out, "bounds", b)?, + None => writeln!(out, "bounds none")?, + } + for b in shape.boxes() { + box_values(out, "box", *b)?; + } + Ok(()) +} +struct World<'a, 'r, W> { + collisions: &'a CachedCollisionRegistry<'r>, + dynamic: &'a [Option], + out: &'a mut W, + fail: i32, + calls: i32, +} +impl World<'_, '_, W> { + fn query(&mut self, p: [i32; 3]) -> io::Result<()> { + writeln!(self.out, "entity {} {} {}", p[0], p[1], p[2])?; + let count = self.calls; + self.calls += 1; + if count == self.fail { + Err(io::Error::other("injected block entity failure")) + } else { + Ok(()) + } + } +} +impl DynamicSupportWorld for World<'_, '_, W> { + type Error = io::Error; + fn shulker_is_closed(&mut self, p: [i32; 3]) -> io::Result> { + self.query(p)?; + Ok(None) + } + fn moving_piston_shape(&mut self, p: [i32; 3]) -> io::Result> { + self.query(p)?; + Ok(None) + } +} +impl PistonCollisionWorld for World<'_, '_, W> { + type Error = io::Error; + fn collision_shape(&mut self, state: BlockStateId, p: [i32; 3]) -> io::Result { + if let Some(shape) = self.collisions.cached_shape(state)? { + return Ok(shape.clone()); + } + let dynamic = self.dynamic[state.0 as usize] + .as_ref() + .expect("known empty-context dynamic collision") + .clone(); + dynamic.shape(self, p).map_err(io::Error::other) + } +} +fn number(v: &Value) -> f32 { + f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} +fn float_bits(v: f32) -> u32 { + if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let read = |name: &str| -> Result> { + Ok( + nbt::read_named(&fs::read(dir.join(name))?, Limits::default())? + .0 + .tag, + ) + }; + let registry = BlockRegistry::from_nbt(&read("block-registry.nbt")?)?; + let collisions = CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, ®istry)?; + let bindings = PistonBlockBindings::new(®istry)?; + let dynamic = (0..registry.len()) + .map(|id| DynamicSupport::from_state(registry.state(BlockStateId(id as u32)).unwrap())) + .collect::>>()?; + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let p = std::array::from_fn(|i| f["position"][i].as_i64().unwrap() as i32); + let piston = MovingPistonState { + moved_state: BlockStateId(f["state"].as_u64().unwrap() as u32), + direction: Direction::ALL[f["direction"].as_u64().unwrap() as usize], + extending: f["extending"].as_bool().unwrap(), + source: f["source"].as_bool().unwrap(), + progress: number(&f["progress"]), + previous_progress: number(&f["previous"]), + }; + let partial = number(&f["partial"]); + let offset = piston.interpolated_offset(partial).map(float_bits); + writeln!( + out, + "motion {} {:08x} {:08x} {:08x} {:08x}", + piston.movement_direction() as u8, + float_bits(piston.interpolated_progress(partial)), + offset[0], + offset[1], + offset[2] + )?; + writeln!( + out, + "related {}", + bindings.collision_related_state(piston)?.0 + )?; + let mut world = World { + collisions: &collisions, + dynamic: &dynamic, + out: &mut out, + fail: f["fail"].as_i64().unwrap() as i32, + calls: 0, + }; + let clip = f["noclip"].as_i64().unwrap(); + let noclip = (clip >= 0).then(|| Direction::ALL[clip as usize]); + if !f["kinematic"].as_bool().unwrap() { + match bindings.collision_shape(&mut world, p, piston, noclip) { + Ok(shape) => emit(world.out, &shape)?, + Err(_) => writeln!(world.out, "shape error")?, + } + } + writeln!(world.out, "queries {}", world.calls)?; + } + Ok(()) +} diff --git a/crates/horizon-world/examples/placement_fixture.rs b/crates/horizon-world/examples/placement_fixture.rs new file mode 100644 index 000000000..b3e6c4747 --- /dev/null +++ b/crates/horizon-world/examples/placement_fixture.rs @@ -0,0 +1,84 @@ +//! Transport for placement decoding, emissions, failures and random state. +#[path = "support/placement_queries.rs"] +mod queries; +use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; +use horizon_world::worldgen::{anchor::WorldGenerationContext, placement::PlacementModifier}; +use serde_json::Value; +use std::cell::RefCell; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +fn fixture( + f: &Value, + mut random: impl RandomSource, + out: &mut impl Write, +) -> Result<(), Box> { + let c = &f["context"]; + let context = WorldGenerationContext::new(n(&c[0]), n(&c[1]), n(&c[2])); + let out = RefCell::new(out); + let mut context = queries::Queries::new(f, context, &out); + match PlacementModifier::from_json(f["definition"].as_str().unwrap()) { + Err(_) => writeln!(out.borrow_mut(), "decode error")?, + Ok(modifier) => { + writeln!(out.borrow_mut(), "decode ok")?; + for p in f["positions"].as_array().unwrap() { + if f["count_only"].as_bool().unwrap_or(false) { + match modifier.repetitions(&mut random, [n(&p[0]), n(&p[1]), n(&p[2])]) { + Ok(Some(count)) => writeln!(out.borrow_mut(), "count {count}")?, + _ => writeln!(out.borrow_mut(), "count error")?, + } + writeln!(out.borrow_mut(), "next {}", random.next_long())?; + continue; + } + let mut count = 0; + let fail = n(&f["fail"]); + let draw = f["draw"].as_bool().unwrap(); + let result = modifier.modify_in( + &mut context, + &mut random, + [n(&p[0]), n(&p[1]), n(&p[2])], + |random, p| { + let previous = count; + count += 1; + if previous == fail { + return Err(io::Error::other("consumer failure")); + } + writeln!(out.borrow_mut(), "position {} {} {}", p[0], p[1], p[2])?; + if draw { + writeln!(out.borrow_mut(), "consumer {}", random.next_long())?; + } + Ok(()) + }, + ); + writeln!( + out.borrow_mut(), + "modify {}", + if result.is_ok() { "ok" } else { "error" } + )?; + writeln!(out.borrow_mut(), "next {}", random.next_long())?; + } + } + } + writeln!(out.borrow_mut(), "tail {}", random.next_long())?; + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, LegacyRandom::new(seed), &mut out)?; + } else { + fixture(&f, XoroshiroRandom::new(seed), &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/replace_block_fixture.rs b/crates/horizon-world/examples/replace_block_fixture.rs new file mode 100644 index 000000000..7a8d00363 --- /dev/null +++ b/crates/horizon-world/examples/replace_block_fixture.rs @@ -0,0 +1,204 @@ +//! Feature world transport retaining ordered mutations and partial failures. +use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; +use horizon_world::{ + DATA_VERSION, + heightmap::HeightmapType, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + worldgen::{ + anchor::WorldGenerationContext, + block_feature::{FeatureBlockBindings, ReplaceBlockFeature}, + feature::FeatureWorld, + placement::{PlacementContext, PlacementQueryError}, + tags::TagDefinitions, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + io::{self, Write}, + path::Path, +}; +struct World<'a, W> { + states: BTreeMap<[i32; 3], BlockStateId>, + blocks: Vec, + minimum: i32, + calls: i32, + fail: i32, + reject: i32, + out: &'a mut W, +} +impl PlacementContext for World<'_, W> { + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new(self.minimum, 384, 63) + } + fn min_y(&mut self) -> Result { + writeln!(self.out, "min").map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + let call = self.calls; + self.calls += 1; + if call == self.fail { + return Err(PlacementQueryError::Failed("minimum query failure".into())); + } + writeln!(self.out, "minimum {}", self.minimum) + .map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + Ok(self.minimum) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + Err(PlacementQueryError::Unavailable) + } +} +impl FeatureWorld for World<'_, W> { + type Error = io::Error; + fn block(&mut self, p: [i32; 3]) -> Result { + let call = self.calls; + self.calls += 1; + writeln!(self.out, "get {} {} {}", p[0], p[1], p[2])?; + if call == self.fail { + return Err(io::Error::other("world failure")); + } + let hash = p[0] + .wrapping_mul(31) + .wrapping_add(p[1].wrapping_mul(7)) + .wrapping_add(p[2].wrapping_mul(17)) + .rem_euclid(7) as usize; + let state = self.states.get(&p).copied().unwrap_or(self.blocks[hash]); + writeln!(self.out, "state {}", state.0)?; + Ok(state) + } + fn set_block( + &mut self, + p: [i32; 3], + state: BlockStateId, + flags: i32, + ) -> Result { + let call = self.calls; + self.calls += 1; + writeln!( + self.out, + "set {} {} {} {} {flags}", + p[0], p[1], p[2], state.0 + )?; + if call == self.fail { + return Err(io::Error::other("world failure")); + } + let result = self.reject == 0 || call % self.reject != 0; + if result { + self.states.insert(p, state); + } + writeln!(self.out, "written {result}")?; + Ok(result) + } +} +fn fixture( + f: &Value, + mut random: impl RandomSource, + blocks: &[BlockStateId], + bindings: &FeatureBlockBindings<'_>, + out: &mut impl Write, +) -> Result<(), Box> { + let decoded = ReplaceBlockFeature::from_json(f["definition"].as_str().unwrap(), bindings); + match decoded { + Err(_) => writeln!(out, "decode error")?, + Ok(feature) => { + writeln!(out, "decode ok")?; + let mut world = World { + states: BTreeMap::new(), + blocks: blocks.to_vec(), + minimum: f["world_min"].as_i64().unwrap() as i32, + calls: 0, + fail: f["fail"].as_i64().unwrap() as i32, + reject: f["reject"].as_i64().unwrap() as i32, + out, + }; + let p = &f["origin"]; + let origin = [ + p[0].as_i64().unwrap() as i32, + p[1].as_i64().unwrap() as i32, + p[2].as_i64().unwrap() as i32, + ]; + for _ in 0..f["repeats"].as_u64().unwrap() { + world.calls = 0; + let result = feature.place(&mut world, &mut random, origin); + match result { + Ok(value) => writeln!(world.out, "place {value}")?, + Err(_) => writeln!(world.out, "place error")?, + } + writeln!(world.out, "next {}", random.next_long())?; + for (p, state) in &world.states { + writeln!(world.out, "stored {} {} {} {}", p[0], p[1], p[2], state.0)?; + } + writeln!(world.out, "end")?; + } + } + } + writeln!(out, "tail {}", random.next_long())?; + Ok(()) +} +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", tag(&facts["states"])), + ("defaults", tag(&facts["defaults"])), + ]))?; + let integers = facts["integers"] + .as_array() + .unwrap() + .iter() + .map(|v| { + ( + v[0].as_str().unwrap().to_owned(), + v[1].as_str().unwrap().to_owned(), + ) + }) + .collect(); + let resources: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; + let mut definitions = TagDefinitions::default(); + for (name, text) in resources.as_object().unwrap() { + definitions.apply_json(name, "vanilla", text.as_str().unwrap())?; + } + let built = + definitions.build(|name, _| registry.default_state(name).map(|_| name.to_owned()))?; + assert!(built.missing.is_empty()); + let bindings = FeatureBlockBindings::with_tags(®istry, integers, &built.tags)?; + let blocks: Vec<_> = [ + "air", + "cave_air", + "void_air", + "stone", + "water", + "oak_leaves", + "dirt", + ] + .map(|name| { + registry + .default_state(&format!("minecraft:{name}")) + .unwrap() + }) + .to_vec(); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, LegacyRandom::new(seed), &blocks, &bindings, &mut out)?; + } else { + fixture(&f, XoroshiroRandom::new(seed), &blocks, &bindings, &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/rule_test_fixture.rs b/crates/horizon-world/examples/rule_test_fixture.rs new file mode 100644 index 000000000..31fa4c436 --- /dev/null +++ b/crates/horizon-world/examples/rule_test_fixture.rs @@ -0,0 +1,95 @@ +//! Differential transport for replacement rules over pinned block identities. +use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; +use horizon_world::{ + DATA_VERSION, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + worldgen::{block_feature::FeatureBlockBindings, rule_test::RuleTest, tags::TagDefinitions}, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn fixture( + f: &Value, + bindings: &FeatureBlockBindings<'_>, + mut random: impl RandomSource, + out: &mut impl Write, +) -> Result<(), Box> { + match RuleTest::from_json(f["definition"].as_str().unwrap(), bindings) { + Err(_) => writeln!(out, "decode error")?, + Ok(rule) => { + writeln!(out, "decode ok")?; + let mut index = 0; + let heights = f["heights"].as_array().unwrap(); + for _ in 0..f["repeats"].as_u64().unwrap() { + for state in f["states"].as_array().unwrap() { + let y = heights[index % heights.len()].as_i64().unwrap() as i32; + index += 1; + let result = rule.test( + BlockStateId(state.as_u64().unwrap() as u32), + [17, y, -33], + &mut random, + ); + writeln!(out, "test {result} {}", random.next_long())?; + } + } + } + } + writeln!(out, "tail {}", random.next_long())?; + Ok(()) +} +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", tag(&facts["states"])), + ("defaults", tag(&facts["defaults"])), + ]))?; + let integers = facts["integers"] + .as_array() + .unwrap() + .iter() + .map(|v| { + ( + v[0].as_str().unwrap().to_owned(), + v[1].as_str().unwrap().to_owned(), + ) + }) + .collect(); + let resources: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; + let mut definitions = TagDefinitions::default(); + for (name, text) in resources.as_object().unwrap() { + definitions.apply_json(name, "vanilla", text.as_str().unwrap())?; + } + let built = + definitions.build(|name, _| registry.default_state(name).map(|_| name.to_owned()))?; + assert!(built.missing.is_empty()); + let bindings = FeatureBlockBindings::with_tags(®istry, integers, &built.tags)?; + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, &bindings, LegacyRandom::new(seed), &mut out)?; + } else { + fixture(&f, &bindings, XoroshiroRandom::new(seed), &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/scattered_ore_fixture.rs b/crates/horizon-world/examples/scattered_ore_fixture.rs new file mode 100644 index 000000000..bc9dd9200 --- /dev/null +++ b/crates/horizon-world/examples/scattered_ore_fixture.rs @@ -0,0 +1,228 @@ +//! Feature world transport retaining ordered mutations and partial failures. +use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; +use horizon_world::{ + DATA_VERSION, + heightmap::HeightmapType, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + worldgen::{ + anchor::WorldGenerationContext, + block_feature::FeatureBlockBindings, + feature::FeatureWorld, + ore_feature::ScatteredOreFeature, + placement::{PlacementContext, PlacementQueryError}, + tags::TagDefinitions, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + io::{self, Write}, + path::Path, +}; +struct World<'a, W> { + states: BTreeMap<[i32; 3], BlockStateId>, + blocks: Vec, + minimum: i32, + mode: usize, + center: [i32; 3], + calls: i32, + fail: i32, + reject: i32, + out: &'a mut W, +} +impl PlacementContext for World<'_, W> { + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new(self.minimum, 384, 63) + } + fn min_y(&mut self) -> Result { + writeln!(self.out, "min").map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + let call = self.calls; + self.calls += 1; + if call == self.fail { + return Err(PlacementQueryError::Failed("minimum query failure".into())); + } + writeln!(self.out, "minimum {}", self.minimum) + .map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + Ok(self.minimum) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + Err(PlacementQueryError::Unavailable) + } +} +impl FeatureWorld for World<'_, W> { + type Error = io::Error; + fn block(&mut self, p: [i32; 3]) -> Result { + let call = self.calls; + self.calls += 1; + writeln!(self.out, "get {} {} {}", p[0], p[1], p[2])?; + if call == self.fail { + return Err(io::Error::other("world failure")); + } + let hash = p[0] + .wrapping_mul(31) + .wrapping_add(p[1].wrapping_mul(7)) + .wrapping_add(p[2].wrapping_mul(17)) + .rem_euclid(7) as usize; + let mut fallback = if self.mode == 0 { + self.blocks[hash] + } else { + self.blocks[3] + }; + if self.mode >= 2 { + let delta = [ + [0, -1, 0], + [0, 1, 0], + [0, 0, -1], + [0, 0, 1], + [-1, 0, 0], + [1, 0, 0], + ][self.mode - 2]; + let adjacent = std::array::from_fn(|i| self.center[i].wrapping_add(delta[i])); + if p == adjacent { + fallback = self.blocks[1]; + } + } + let state = self.states.get(&p).copied().unwrap_or(fallback); + writeln!(self.out, "state {}", state.0)?; + Ok(state) + } + fn set_block( + &mut self, + p: [i32; 3], + state: BlockStateId, + flags: i32, + ) -> Result { + let call = self.calls; + self.calls += 1; + writeln!( + self.out, + "set {} {} {} {} {flags}", + p[0], p[1], p[2], state.0 + )?; + if call == self.fail { + return Err(io::Error::other("world failure")); + } + let result = self.reject == 0 || call % self.reject != 0; + if result { + self.states.insert(p, state); + } + writeln!(self.out, "written {result}")?; + Ok(result) + } +} +fn fixture( + f: &Value, + mut random: impl RandomSource, + blocks: &[BlockStateId], + bindings: &FeatureBlockBindings<'_>, + out: &mut impl Write, +) -> Result<(), Box> { + let decoded = ScatteredOreFeature::from_json(f["definition"].as_str().unwrap(), bindings); + match decoded { + Err(_) => writeln!(out, "decode error")?, + Ok(feature) => { + writeln!(out, "decode ok")?; + let mut world = World { + states: BTreeMap::new(), + blocks: blocks.to_vec(), + minimum: f["world_min"].as_i64().unwrap() as i32, + mode: f["mode"].as_u64().unwrap() as usize, + center: std::array::from_fn(|i| f["origin"][i].as_i64().unwrap() as i32), + calls: 0, + fail: f["fail"].as_i64().unwrap() as i32, + reject: f["reject"].as_i64().unwrap() as i32, + out, + }; + let p = &f["origin"]; + let origin = [ + p[0].as_i64().unwrap() as i32, + p[1].as_i64().unwrap() as i32, + p[2].as_i64().unwrap() as i32, + ]; + for _ in 0..f["repeats"].as_u64().unwrap() { + world.calls = 0; + let result = feature.place(&mut world, &mut random, origin); + match result { + Ok(value) => writeln!(world.out, "place {value}")?, + Err(_) => writeln!(world.out, "place error")?, + } + writeln!(world.out, "next {}", random.next_long())?; + for (p, state) in &world.states { + writeln!(world.out, "stored {} {} {} {}", p[0], p[1], p[2], state.0)?; + } + writeln!(world.out, "end")?; + } + } + } + writeln!(out, "tail {}", random.next_long())?; + Ok(()) +} +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", tag(&facts["states"])), + ("defaults", tag(&facts["defaults"])), + ]))?; + let integers = facts["integers"] + .as_array() + .unwrap() + .iter() + .map(|v| { + ( + v[0].as_str().unwrap().to_owned(), + v[1].as_str().unwrap().to_owned(), + ) + }) + .collect(); + let resources: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; + let mut definitions = TagDefinitions::default(); + for (name, text) in resources.as_object().unwrap() { + definitions.apply_json(name, "vanilla", text.as_str().unwrap())?; + } + let built = + definitions.build(|name, _| registry.default_state(name).map(|_| name.to_owned()))?; + assert!(built.missing.is_empty()); + let bindings = FeatureBlockBindings::with_tags(®istry, integers, &built.tags)?; + let blocks: Vec<_> = [ + "air", + "cave_air", + "void_air", + "stone", + "water", + "oak_leaves", + "dirt", + ] + .map(|name| { + registry + .default_state(&format!("minecraft:{name}")) + .unwrap() + }) + .to_vec(); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, LegacyRandom::new(seed), &blocks, &bindings, &mut out)?; + } else { + fixture(&f, XoroshiroRandom::new(seed), &blocks, &bindings, &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/state_provider_fixture.rs b/crates/horizon-world/examples/state_provider_fixture.rs new file mode 100644 index 000000000..e8a8f9f5a --- /dev/null +++ b/crates/horizon-world/examples/state_provider_fixture.rs @@ -0,0 +1,540 @@ +use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom, XoroshiroRandom}; +use horizon_world::{ + DATA_VERSION, + block_collision::{BlockCollisionRegistry, DynamicCollisionWorld, ShulkerCollisionState}, + block_support::{BlockSupportRegistry, SupportType}, + block_survival::{BlockSurvivalRegistry, SurvivalDefinitions, SurvivalRule, SurvivalWorld}, + fluid::{FluidKind, FluidStateTable}, + heightmap::HeightmapType, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + worldgen::{ + anchor::WorldGenerationContext, + biome::BiomeId, + biome_predicate::BiomePredicateBindings, + feature::FeatureWorld, + placement::{PlacementContext, PlacementQueryError}, + state_provider::{StateProviderBindings, StateProviderCatalog}, + tags::TagDefinitions, + }, +}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + io::{self, Write}, + path::Path, + sync::Arc, +}; +struct World<'a, W> { + support: &'a BlockSupportRegistry<'a>, + survival: &'a BlockSurvivalRegistry<'a>, + out: &'a mut W, + fallback: BlockStateId, + biome: BiomeId, + unobstructed: bool, + brightness: i32, + tags: &'a BTreeMap>, + calls: i32, + fail: i32, + queries: i32, + query_fail: i32, + bounds: [i32; 3], +} +impl FeatureWorld for World<'_, W> { + type Error = (); + fn block(&mut self, p: [i32; 3]) -> Result { + writeln!(self.out, "read {} {} {}", p[0], p[1], p[2]).map_err(|_| ())?; + let call = self.calls; + self.calls += 1; + if call == self.fail { + Err(()) + } else { + Ok(self.fallback) + } + } + fn set_block(&mut self, _: [i32; 3], _: BlockStateId, _: i32) -> Result { + panic!("providers must not write blocks") + } +} +impl World<'_, W> { + fn query(&mut self, name: &str, value: i32) -> Result { + writeln!(self.out, "{name}").map_err(|_| PlacementQueryError::Unavailable)?; + let call = self.queries; + self.queries += 1; + if call == self.query_fail { + Err(PlacementQueryError::Unavailable) + } else { + Ok(value) + } + } +} +impl horizon_world::dynamic_support::DynamicSupportWorld for World<'_, W> { + type Error = PlacementQueryError; + fn shulker_is_closed(&mut self, p: [i32; 3]) -> Result, Self::Error> { + self.query(&format!("entity {} {} {}", p[0], p[1], p[2]), 0)?; + Ok(None) + } + fn moving_piston_shape( + &mut self, + p: [i32; 3], + ) -> Result, Self::Error> { + self.query(&format!("entity {} {} {}", p[0], p[1], p[2]), 0)?; + Ok(None) + } +} +impl DynamicCollisionWorld for World<'_, W> { + fn shulker_collision_state( + &mut self, + p: [i32; 3], + ) -> Result, Self::Error> { + self.query(&format!("entity {} {} {}", p[0], p[1], p[2]), 0)?; + Ok(None) + } +} +impl SurvivalWorld for World<'_, W> { + fn fluid_state( + &mut self, + p: [i32; 3], + ) -> Result { + self.query(&format!("fluid {} {} {}", p[0], p[1], p[2]), 0)?; + horizon_world::fluid::FluidState::from_block( + self.support.registry().state(self.fallback).unwrap(), + ) + .map_err(|_| PlacementQueryError::Unavailable) + } + fn raw_brightness(&mut self, p: [i32; 3], sky_darken: i32) -> Result { + self.query( + &format!("light {} {} {} {sky_darken}", p[0], p[1], p[2]), + self.brightness, + ) + } + fn block_state(&mut self, position: [i32; 3]) -> Result { + self.block(position) + .map_err(|_| PlacementQueryError::Unavailable) + } +} +impl PlacementContext for World<'_, W> { + fn block_survives( + &mut self, + state: BlockStateId, + position: [i32; 3], + ) -> Result { + let survival = self.survival; + survival + .can_survive(self, state, position) + .map_err(|_| PlacementQueryError::Unavailable) + } + fn face_sturdy( + &mut self, + p: [i32; 3], + direction: horizon_core::geometry::Direction, + ) -> Result { + let state = self + .block(p) + .map_err(|_| PlacementQueryError::Unavailable)?; + let support = self.support; + support + .is_face_sturdy(self, state, p, direction, SupportType::Full) + .map_err(|_| PlacementQueryError::Unavailable) + } + + fn unobstructed_block(&mut self, p: [i32; 3]) -> Result { + let min = p.map(f64::from); + let max = min.map(|v| v + 1.0); + let label = format!( + "clear {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", + min[0].to_bits(), + min[1].to_bits(), + min[2].to_bits(), + max[0].to_bits(), + max[1].to_bits(), + max[2].to_bits() + ); + self.query(&label, i32::from(self.unobstructed)) + .map(|value| value != 0) + } + fn biome_identity(&mut self, p: [i32; 3]) -> Result { + self.query( + &format!("biome {} {} {}", p[0], p[1], p[2]), + self.biome.0 as i32, + ) + .map(|id| BiomeId(id as u32)) + } + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext { + min_y: self.bounds[0], + height: self.bounds[1], + sea_level: self.bounds[2], + } + } + fn predicate_generation(&mut self) -> Result { + let min_y = self.min_y()?; + let height = self.query("height", self.bounds[1])?; + let sea_level = self.query("sea", self.bounds[2])?; + Ok(WorldGenerationContext { + min_y, + height, + sea_level, + }) + } + fn block_state(&mut self, position: [i32; 3]) -> Result { + self.block(position) + .map_err(|_| PlacementQueryError::Unavailable) + } + fn block_matches_tag( + &mut self, + position: [i32; 3], + tag: &str, + ) -> Result { + let state = self + .block(position) + .map_err(|_| PlacementQueryError::Unavailable)?; + Ok(self + .tags + .get(tag) + .is_some_and(|states| states.contains(&state))) + } + fn min_y(&mut self) -> Result { + self.query("min", self.bounds[0]) + } + fn max_y(&mut self) -> Result { + Ok(self + .min_y()? + .wrapping_add(self.query("height", self.bounds[1])?) + .wrapping_sub(1)) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + Err(PlacementQueryError::Unavailable) + } +} +fn fixture( + f: &Value, + bindings: &StateProviderBindings<'_>, + catalog: &StateProviderCatalog, + tags: &BTreeMap>, + support: (&BlockSupportRegistry<'_>, &BlockSurvivalRegistry<'_>), + mut random: impl RandomSource, + out: &mut impl Write, +) -> Result<(), Box> { + let json = f["definition"].as_str().unwrap(); + let decoded = if f["holder"].as_bool().unwrap_or(false) { + catalog.provider(json, bindings) + } else if f["typed"].as_bool().unwrap() { + catalog.typed_provider(json, bindings) + } else { + catalog.direct_provider(json, bindings) + }; + match decoded { + Err(_) => writeln!(out, "decode error")?, + Ok(provider) => { + writeln!(out, "decode ok")?; + let mut world = World { + support: support.0, + survival: support.1, + out, + tags, + fallback: BlockStateId(0), + biome: BiomeId(0), + unobstructed: f["unobstructed"].as_bool().unwrap_or(true), + brightness: f["brightness"].as_i64().unwrap_or(15) as i32, + calls: 0, + queries: 0, + query_fail: f["query_fail"].as_i64().unwrap_or(-1) as i32, + bounds: f + .get("bounds") + .map(|v| std::array::from_fn(|i| v[i].as_i64().unwrap() as i32)) + .unwrap_or([-64, 384, 63]), + fail: f["fail"].as_i64().unwrap() as i32, + }; + let mut position_index = 0usize; + let mut sample_index = 0usize; + for repeat in 0..f["repeats"].as_i64().unwrap() as i32 { + for state in f["states"].as_array().unwrap() { + world.fallback = BlockStateId(state.as_u64().unwrap() as u32); + world.biome = f + .get("biomes") + .map(|values| { + let values = values.as_array().unwrap(); + BiomeId(values[sample_index % values.len()].as_u64().unwrap() as u32) + }) + .unwrap_or(BiomeId(0)); + sample_index += 1; + let p = if let Some(positions) = f.get("positions") { + let positions = positions.as_array().unwrap(); + let p = &positions[position_index % positions.len()]; + position_index += 1; + std::array::from_fn(|i| p[i].as_i64().unwrap() as i32) + } else { + [17, repeat - 64, -33] + }; + for optional in [false, true] { + let result = if optional { + provider.get_optional_state(&mut world, &mut random, p) + } else { + provider.get_state(&mut world, &mut random, p).map(Some) + }; + match result { + Ok(Some(state)) => writeln!(world.out, "state {}", state.0)?, + Ok(None) => writeln!(world.out, "state none")?, + Err(_) => writeln!(world.out, "state error")?, + } + writeln!(world.out, "next {}", random.next_long())?; + } + } + } + } + } + writeln!(out, "tail {}", random.next_long())?; + Ok(()) +} +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", tag(&facts["states"])), + ("defaults", tag(&facts["defaults"])), + ]))?; + let integers = facts["integers"] + .as_array() + .unwrap() + .iter() + .map(|v| { + ( + v[0].as_str().unwrap().to_owned(), + v[1].as_str().unwrap().to_owned(), + ) + }) + .collect(); + let resources: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; + let mut definitions = TagDefinitions::default(); + for (name, text) in resources.as_object().unwrap() { + definitions.apply_json(name, "vanilla", text.as_str().unwrap())?; + } + let built = + definitions.build(|name, _| registry.default_state(name).map(|_| name.to_owned()))?; + assert!(built.missing.is_empty()); + let tag_states: BTreeMap> = built + .tags + .iter() + .map(|(tag, names)| { + let states = (0..registry.len()) + .map(|i| BlockStateId(i as u32)) + .filter(|id| names.contains(®istry.state(*id).unwrap().name)) + .collect(); + (tag.clone(), states) + }) + .collect(); + let fluid_resources: BTreeMap = + serde_json::from_str(&fs::read_to_string(dir.join("fluid-tags.json"))?)?; + let mut fluid_tags = TagDefinitions::default(); + for (name, text) in fluid_resources { + fluid_tags.apply_json(&name, "vanilla", &text)?; + } + let fluid_tags = + fluid_tags.build(|name, _| FluidKind::from_name(name).map(|_| name.to_owned()))?; + assert!(fluid_tags.missing.is_empty()); + let biome_resources: BTreeMap = + serde_json::from_str(&fs::read_to_string(dir.join("biomes.json"))?)?; + let biome_names: BTreeMap = biome_resources + .keys() + .enumerate() + .map(|(i, name)| (name.clone(), BiomeId(i as u32))) + .collect(); + let biome_tags: BTreeMap = + serde_json::from_str(&fs::read_to_string(dir.join("biome_tags.json"))?)?; + let mut definitions = TagDefinitions::default(); + for (name, text) in biome_tags { + definitions.apply_json(&name, "vanilla", &text)?; + } + let biome_tags = + definitions.build(|name, _| biome_names.contains_key(name).then(|| name.to_owned()))?; + assert!(biome_tags.missing.is_empty()); + let biomes = Arc::new(BiomePredicateBindings::new(&biome_names, &biome_tags.tags)?); + let collision_tag = horizon_world::nbt::read_named( + &fs::read(dir.join("cached-collision.nbt"))?, + horizon_world::nbt::Limits::default(), + )? + .0 + .tag; + let collision = + horizon_world::collision::CachedCollisionRegistry::from_nbt(&collision_tag, ®istry)?; + let properties_tag = horizon_world::nbt::read_named( + &fs::read(dir.join("block-properties.nbt"))?, + horizon_world::nbt::Limits::default(), + )? + .0 + .tag; + let properties = horizon_world::block_properties::BlockPropertiesRegistry::from_nbt( + &properties_tag, + &collision, + )?; + let support_tag = horizon_world::nbt::read_named( + &fs::read(dir.join("cached-support.nbt"))?, + horizon_world::nbt::Limits::default(), + )? + .0 + .tag; + let support = Arc::new(BlockSupportRegistry::from_nbt(&support_tag, ®istry)?); + let survival_definitions: BTreeMap = + serde_json::from_str(&fs::read_to_string(dir.join("survival-rules.json"))?)?; + let survival_definitions = survival_definitions + .into_iter() + .map(|(name, rule)| { + use SurvivalRule::*; + let rule = match rule.as_str() { + value if value.starts_with("TagBelow:") => TagBelow(value[9..].to_owned()), + "CactusFlower" => CactusFlower, + "Seagrass" => Seagrass, + "BubbleColumn" => BubbleColumn, + "RedstoneWire" => RedstoneWire, + "DoublePlant" => DoublePlant, + "Door" => Door, + "BigDripleaf" => BigDripleaf, + "BigDripleafStem" => BigDripleafStem, + "Farmland" => Farmland, + "Cocoa" => Cocoa, + "Crop" => Crop, + "GrowingPlant" => GrowingPlant, + "MangrovePropagule" => MangrovePropagule, + "Speleothem" => Speleothem, + "Scaffolding" => Scaffolding, + "PistonHead" => PistonHead, + "ChorusPlant" => ChorusPlant, + "ChorusFlower" => ChorusFlower, + "PitcherCrop" => PitcherCrop, + "Multiface" => Multiface, + "Vine" => Vine, + "HangingMoss" => HangingMoss, + "SnowLayer" => SnowLayer, + "SeaPickle" => SeaPickle, + "Fire" => Fire, + "Cactus" => Cactus, + "Path" => Path, + "Mushroom" => Mushroom, + "Bell" => Bell, + "SugarCane" => SugarCane, + "LilyPad" => LilyPad, + "Frogspawn" => Frogspawn, + "SporeBlossom" => SporeBlossom, + "SmallDripleaf" => SmallDripleaf, + "TallSeagrass" => TallSeagrass, + "Always" => Always, + "SolidBelow" => SolidBelow, + "SolidBehind" => SolidBehind, + "NonAirBelow" => NonAirBelow, + "MossCarpet" => MossCarpet, + "CenterBelow" => CenterBelow, + "Lantern" => Lantern, + "FullAbove" => FullAbove, + "FullBehind" => FullBehind, + "RigidOrCenterBelow" => RigidOrCenterBelow, + "RigidBelow" => RigidBelow, + "FullBelow" => FullBelow, + "CenterAbove" => CenterAbove, + "FaceAttached" => FaceAttached, + "SupportsBamboo" => SupportsBamboo, + _ => panic!("unknown survival rule {rule}"), + }; + (name, rule) + }) + .collect(); + let collision = Arc::new(BlockCollisionRegistry::new(Arc::new(collision))?); + let extra: Value = serde_json::from_str(&fs::read_to_string( + dir.join("survival-extra-definitions.json"), + )?)?; + let survival_definitions = SurvivalDefinitions { + rules: survival_definitions, + ignition_odds: serde_json::from_value(extra["ignition_odds"].clone())?, + fence_gates: serde_json::from_value(extra["fence_gates"].clone())?, + }; + let survival = BlockSurvivalRegistry::new( + ®istry, + &properties, + Arc::clone(&support), + collision, + &survival_definitions, + &built.tags, + &fluid_tags.tags, + )?; + let bindings = StateProviderBindings::new(®istry, integers, &built.tags)? + .with_block_properties(&properties)? + .with_fluid_tags(&fluid_tags.tags)? + .with_biomes(biomes); + let resources: BTreeMap = + serde_json::from_str(&fs::read_to_string(dir.join("catalog.json"))?)?; + let catalog = StateProviderCatalog::from_resources(&resources)?; + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + let fluids = FluidStateTable::new(®istry)?; + for i in 0..registry.len() { + let fluid = fluids.get(BlockStateId(i as u32)).unwrap(); + writeln!( + out, + "fluid {i} {} {} {} {} {}", + fluid.kind().name(), + fluid.amount(), + fluid.falling(), + fluid.is_source(), + fluid.own_height().to_bits() + )?; + } + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + match ( + f["legacy"].as_bool().unwrap(), + f["worldgen"].as_bool().unwrap(), + ) { + (true, false) => fixture( + &f, + &bindings, + &catalog, + &tag_states, + (&support, &survival), + LegacyRandom::new(seed), + &mut out, + )?, + (false, false) => fixture( + &f, + &bindings, + &catalog, + &tag_states, + (&support, &survival), + XoroshiroRandom::new(seed), + &mut out, + )?, + (true, true) => fixture( + &f, + &bindings, + &catalog, + &tag_states, + (&support, &survival), + WorldgenRandom::new(LegacyRandom::new(seed)), + &mut out, + )?, + (false, true) => fixture( + &f, + &bindings, + &catalog, + &tag_states, + (&support, &survival), + WorldgenRandom::new(XoroshiroRandom::new(seed)), + &mut out, + )?, + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/structure_density_fixture.rs b/crates/horizon-world/examples/structure_density_fixture.rs new file mode 100644 index 000000000..55ef66f83 --- /dev/null +++ b/crates/horizon-world/examples/structure_density_fixture.rs @@ -0,0 +1,97 @@ +//! Original JSON transport for structure-density comparison. +use horizon_core::{ + density::{ + Beardifier, DensitySampler, JigsawJunction, RigidPiece, SamplerContext, StructureBounds, + TerrainAdjustment, + }, + noise::DensityVolume, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, +}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +fn bounds(v: &Value) -> Option { + if v.is_null() { + None + } else { + StructureBounds::new( + std::array::from_fn(|i| n(&v[i])), + std::array::from_fn(|i| n(&v[i + 3])), + ) + } +} +fn bits(value: f32) -> u32 { + if value.is_nan() { + 0x7fc00000 + } else { + value.to_bits() + } +} +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + let mut out = io::BufWriter::new(fs::File::create(&args[2])?); + for line in fs::read_to_string(&args[1])?.lines() { + let f: Value = serde_json::from_str(line)?; + let pieces = f["pieces"] + .as_array() + .unwrap() + .iter() + .map(|a| RigidPiece { + bounds: bounds(&a[0]).unwrap(), + adjustment: match a[1].as_str().unwrap() { + "NONE" => TerrainAdjustment::None, + "BURY" => TerrainAdjustment::Bury, + "BEARD_THIN" => TerrainAdjustment::BeardThin, + "BEARD_BOX" => TerrainAdjustment::BeardBox, + "ENCAPSULATE" => TerrainAdjustment::Encapsulate, + _ => panic!("unknown adjustment"), + }, + ground_level_delta: n(&a[2]), + }) + .collect(); + let junctions = f["junctions"] + .as_array() + .unwrap() + .iter() + .map(|a| JigsawJunction { + source_x: n(&a[0]), + source_ground_y: n(&a[1]), + source_z: n(&a[2]), + }) + .collect(); + let sampler = Beardifier::new(pieces, junctions, bounds(&f["affected"])); + let mut context = SamplerContext::default(); + writeln!( + out, + "beardifier {} {}", + f["pieces"].as_array().unwrap().len(), + f["junctions"].as_array().unwrap().len() + )?; + for p in f["points"].as_array().unwrap() { + writeln!( + out, + "value {:x}", + bits(sampler.sample_value(&mut context, std::array::from_fn(|i| n(&p[i])))?) + )?; + } + for a in f["volumes"].as_array().unwrap() { + let volume = DensityVolume::new( + std::array::from_fn(|i| n(&a[i])), + std::array::from_fn(|i| n(&a[i + 3])), + std::array::from_fn(|i| n(&a[i + 6])), + )?; + let mut buffer = vec![-123.5; volume.size() + n(&a[9]) as usize]; + sampler.sample_volume(&mut context, &mut buffer, volume)?; + writeln!(out, "volume {}", buffer.len())?; + for value in buffer { + writeln!(out, "{:x}", bits(value))?; + } + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/examples/support/decoration_storage.rs b/crates/horizon-world/examples/support/decoration_storage.rs new file mode 100644 index 000000000..43afdc1fc --- /dev/null +++ b/crates/horizon-world/examples/support/decoration_storage.rs @@ -0,0 +1,101 @@ +use horizon_world::{ + DATA_VERSION, + heightmap::HeightmapState, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + worldgen::{tags::TagDefinitions, terrain::TerrainBlockStates}, +}; +use serde_json::Value; +use std::{collections::BTreeSet, fs, path::Path}; +#[derive(Clone, Copy)] +pub struct State { + air: bool, + air_block: bool, + fluid: bool, + motion: bool, + no_leaves: bool, +} +impl HeightmapState for State { + fn is_air(self) -> bool { + self.air + } + fn is_air_block(self) -> bool { + self.air_block + } + fn has_fluid(self) -> bool { + self.fluid + } + fn blocks_motion_in_heightmap(self) -> bool { + self.motion + } + fn blocks_motion_in_heightmap_no_leaves(self) -> bool { + self.no_leaves + } +} +pub struct Properties<'a>(pub &'a [State]); +impl TerrainBlockStates for Properties<'_> { + type State = State; + fn heightmap_state(&self, id: BlockStateId) -> State { + self.0[id.0 as usize] + } +} +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + _ => panic!("unsupported registry fixture value"), + } +} +pub fn load(dir: &Path) -> Result<(BlockRegistry, Vec), Box> { + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List( + facts["states"] + .as_array() + .unwrap() + .iter() + .map(|s| tag(&s[4])) + .collect(), + ), + ), + ("defaults", tag(&facts["defaults"])), + ]))?; + let mut definitions = TagDefinitions::default(); + for (name, text) in bundle.as_object().unwrap() { + definitions.apply_json(name, "vanilla", text.as_str().unwrap())?; + } + let built = definitions.build(|id, _| facts["defaults"].get(id).map(|_| id.to_owned()))?; + assert!(built.missing.is_empty()); + let motion: BTreeSet<_> = built.tags["minecraft:blocks_motion_in_heightmap"] + .iter() + .map(String::as_str) + .collect(); + let no_leaves: BTreeSet<_> = built.tags["minecraft:blocks_motion_in_heightmap_no_leaves"] + .iter() + .map(String::as_str) + .collect(); + let states: Vec<_> = facts["states"] + .as_array() + .unwrap() + .iter() + .map(|a| { + let name = a[0].as_str().unwrap(); + State { + air: a[1].as_bool().unwrap(), + air_block: name == "minecraft:air", + fluid: a[2].as_bool().unwrap(), + motion: motion.contains(name), + no_leaves: no_leaves.contains(name), + } + }) + .collect(); + Ok((registry, states)) +} diff --git a/crates/horizon-world/examples/support/placement_queries.rs b/crates/horizon-world/examples/support/placement_queries.rs new file mode 100644 index 000000000..eacb36cd6 --- /dev/null +++ b/crates/horizon-world/examples/support/placement_queries.rs @@ -0,0 +1,149 @@ +use horizon_world::{ + heightmap::HeightmapType, + worldgen::{ + anchor::WorldGenerationContext, + placement::{LayerBlock, PlacementContext, PlacementQueryError}, + }, +}; +use serde_json::Value; +use std::{cell::RefCell, io::Write}; +pub struct Queries<'a, W> { + generation: WorldGenerationContext, + world_min: i32, + height_base: i32, + mode: i32, + layer_world: bool, + fail: i32, + calls: i32, + out: &'a RefCell, +} +impl<'a, W: Write> Queries<'a, W> { + pub fn new(f: &Value, generation: WorldGenerationContext, out: &'a RefCell) -> Self { + let height_base = generation.min_y; + let world_min = f["world_min"] + .as_i64() + .map(|v| v as i32) + .unwrap_or(generation.min_y); + let generation = WorldGenerationContext::new( + generation.min_y.max(world_min), + generation.height, + generation.sea_level, + ); + Self { + generation, + world_min, + height_base, + layer_world: f["layer_world"].as_bool().unwrap_or(false), + mode: f["height_mode"].as_i64().unwrap_or(0) as i32, + fail: f["query_fail"].as_i64().unwrap_or(-1) as i32, + calls: 0, + out, + } + } +} +impl PlacementContext for Queries<'_, W> { + fn max_y(&mut self) -> Result { + Ok(self + .world_min + .wrapping_add(self.generation.height) + .wrapping_sub(1)) + } + fn inside_build_height(&mut self, [x, y, z]: [i32; 3]) -> Result { + writeln!(self.out.borrow_mut(), "inside {x} {y} {z}") + .map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + let call = self.calls; + self.calls += 1; + if call == self.fail { + return Err(PlacementQueryError::Failed("bounds query failure".into())); + } + let result = y >= self.world_min && y <= self.max_y()?; + writeln!(self.out.borrow_mut(), "bounds_result {result}") + .map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + Ok(result) + } + fn outside_build_height(&mut self, y: i32) -> Result { + writeln!(self.out.borrow_mut(), "outside {y}") + .map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + let call = self.calls; + self.calls += 1; + if call == self.fail { + return Err(PlacementQueryError::Failed("bounds query failure".into())); + } + let result = y < self.world_min || y > self.max_y()?; + writeln!(self.out.borrow_mut(), "bounds_result {result}") + .map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + Ok(result) + } + fn layer_block(&mut self, [x, y, z]: [i32; 3]) -> Result { + let mut out = self.out.borrow_mut(); + writeln!(out, "block {x} {y} {z}") + .map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + let call = self.calls; + self.calls += 1; + if call == self.fail { + return Err(PlacementQueryError::Failed("block query failure".into())); + } + let names = [ + "bedrock", + "stone", + "air", + "water", + "dirt", + "cave_air", + "lava", + "bubble_column", + "void_air", + "grass_block", + "air", + "water", + ]; + let index = if y <= self.height_base { + 0 + } else { + y.wrapping_sub(self.height_base) + .wrapping_add(x.wrapping_mul(31).wrapping_add(z.wrapping_mul(17)) & 3) + .rem_euclid(12) as usize + }; + writeln!(out, "block_result minecraft:{}", names[index]) + .map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + Ok(match index { + 0 => LayerBlock::Bedrock, + 1 | 4 | 7 | 9 => LayerBlock::Ground, + _ => LayerBlock::Empty, + }) + } + fn generation(&self) -> WorldGenerationContext { + self.generation + } + fn min_y(&mut self) -> Result { + Ok(self.world_min) + } + fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result { + let mut out = self.out.borrow_mut(); + writeln!(out, "height {} {x} {z}", kind.name()) + .map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + let call = self.calls; + self.calls += 1; + if call == self.fail { + return Err(PlacementQueryError::Failed("height query failure".into())); + } + let min = self.height_base; + let result = if self.layer_world { + min.wrapping_add(24).wrapping_add((x ^ z) & 3) + } else if self.mode == 0 { + min.wrapping_add( + x.wrapping_mul(31) + .wrapping_add(z.wrapping_mul(17)) + .wrapping_add((kind as i32) * 7) + .rem_euclid(129), + ) + .wrapping_sub(64) + } else { + [i32::MIN, i32::MAX, 0, -1, min, min.wrapping_add(1)] + [(kind as usize + ((x ^ z) & 3) as usize) % 6] + }; + writeln!(out, "height_result {result}") + .map_err(|e| PlacementQueryError::Failed(e.to_string()))?; + Ok(result) + } +} diff --git a/crates/horizon-world/examples/terrain_fixture.rs b/crates/horizon-world/examples/terrain_fixture.rs new file mode 100644 index 000000000..09868a340 --- /dev/null +++ b/crates/horizon-world/examples/terrain_fixture.rs @@ -0,0 +1,303 @@ +//! Test transport for registry-backed noise-stage filling against vanilla doFill. +use horizon_core::{ + density::{ + Beardifier, JigsawJunction, RigidPiece, SamplerContext, StructureBounds, TerrainAdjustment, + WorldField, WorldFields, graph::DensityCompiler, + }, + noise::DensityVolume, + position::ChunkPos, + random::{LegacyRandom, PositionalRandom, RandomSource, XoroshiroRandom}, +}; +use horizon_world::{ + DATA_VERSION, + heightmap::{HeightmapState, HeightmapType}, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + worldgen::{ + aquifer::{ + AquiferConfig, DisabledAquifer, GlobalFluidPicker, NoiseBasedAquifer, + RegistryAquiferBlockStates, + }, + density::DensityRegistry, + router::{NoiseRouter, RouterField}, + tags::TagDefinitions, + terrain::{TerrainAquifer, TerrainBlockStates, TerrainChunk, fill_noise}, + }, +}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + io::{self, Write}, + path::Path, + sync::Arc, +}; +#[derive(Clone, Copy)] +struct State { + air: bool, + air_block: bool, + fluid: bool, + motion: bool, + no_leaves: bool, +} +impl HeightmapState for State { + fn is_air(self) -> bool { + self.air + } + fn is_air_block(self) -> bool { + self.air_block + } + fn has_fluid(self) -> bool { + self.fluid + } + fn blocks_motion_in_heightmap(self) -> bool { + self.motion + } + fn blocks_motion_in_heightmap_no_leaves(self) -> bool { + self.no_leaves + } +} +struct Properties<'a>(&'a [State]); +impl TerrainBlockStates for Properties<'_> { + type State = State; + fn heightmap_state(&self, id: BlockStateId) -> State { + self.0[id.0 as usize] + } +} +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + _ => panic!("unsupported registry fixture value"), + } +} +fn structure(v: &Value) -> Beardifier { + let bounds = |v: &Value| { + StructureBounds::new( + std::array::from_fn(|i| n(&v[i])), + std::array::from_fn(|i| n(&v[i + 3])), + ) + .unwrap() + }; + let pieces = v["pieces"] + .as_array() + .unwrap() + .iter() + .map(|a| RigidPiece { + bounds: bounds(&a[0]), + ground_level_delta: n(&a[2]), + adjustment: match a[1].as_str().unwrap() { + "NONE" => TerrainAdjustment::None, + "BURY" => TerrainAdjustment::Bury, + "BEARD_THIN" => TerrainAdjustment::BeardThin, + "BEARD_BOX" => TerrainAdjustment::BeardBox, + "ENCAPSULATE" => TerrainAdjustment::Encapsulate, + _ => panic!("unknown adjustment"), + }, + }) + .collect(); + let junctions = v["junctions"] + .as_array() + .unwrap() + .iter() + .map(|a| JigsawJunction { + source_x: n(&a[0]), + source_ground_y: n(&a[1]), + source_z: n(&a[2]), + }) + .collect(); + Beardifier::new(pieces, junctions, Some(bounds(&v["affected"]))) +} +fn fixture( + f: Value, + registry: &BlockRegistry, + states: &[State], + bundle: &Value, + out: &mut impl Write, +) -> Result<(), Box> { + let min = n(&f["min"]); + let height = n(&f["height"]); + let cx = n(&f["cx"]); + let cz = n(&f["cz"]); + let seed = f["seed"].as_i64().unwrap(); + let legacy = f["legacy"].as_bool().unwrap(); + let volume = DensityVolume::new( + [16, n(&f["noise_height"]), 16], + [cx.wrapping_shl(4), n(&f["noise_min"]), cz.wrapping_shl(4)], + [1; 3], + )?; + let mut chunk = TerrainChunk::new( + ChunkPos { x: cx, z: cz }, + min, + height, + registry, + Properties(states), + )?; + for a in f["initial"].as_array().unwrap() { + chunk.set_block_raw(n(&a[0]), n(&a[1]), n(&a[2]), BlockStateId(n(&a[3]) as u32))?; + } + let noises: BTreeMap = serde_json::from_value(bundle["noises"].clone())?; + let densities: BTreeMap = serde_json::from_value(bundle["densities"].clone())?; + let mut definitions = DensityRegistry::from_json(&noises, &densities)?; + let router = NoiseRouter::from_json(&f["router"].to_string(), &mut definitions)?; + let config = if f["aquifers"].is_null() { + None + } else { + Some(AquiferConfig::from_json( + &f["aquifers"].to_string(), + &mut definitions, + )?) + }; + let mut compiler = DensityCompiler::new_seeded(definitions.into_graph(), seed, legacy); + let mut context = SamplerContext::cached(); + if let Some(source) = f.get("structure") { + context = context.with_world_fields( + WorldFields::default().with_field(WorldField::Beardifier, Arc::new(structure(source))), + ); + } + let air = registry.default_state("minecraft:air").unwrap(); + let picker = GlobalFluidPicker::new( + n(&f["sea"]), + BlockStateId(n(&f["fluid"]) as u32), + registry.default_state("minecraft:lava").unwrap(), + air, + ); + let mut aquifer: Box = if let Some(config) = config { + let samplers = config.compile(&mut compiler)?; + let blocks = RegistryAquiferBlockStates::new(registry)?; + if legacy { + let random = LegacyRandom::new(seed) + .fork_positional() + .from_hash_of("minecraft:aquifer") + .fork_positional(); + Box::new(NoiseBasedAquifer::new( + samplers, + picker, + random, + blocks, + volume, + &mut context, + )?) + } else { + let random = XoroshiroRandom::new(seed) + .fork_positional() + .from_hash_of("minecraft:aquifer") + .fork_positional(); + Box::new(NoiseBasedAquifer::new( + samplers, + picker, + random, + blocks, + volume, + &mut context, + )?) + } + } else { + Box::new(DisabledAquifer::new(picker, air)) + }; + let density = compiler.get_sampler(router.function(RouterField::FinalDensity))?; + writeln!(out, "chunk {cx} {cz} {min} {height}")?; + for repeat in 0..n(&f["repeats"]) { + fill_noise( + &mut chunk, + volume, + density.as_ref(), + &mut context, + aquifer.as_mut(), + BlockStateId(n(&f["block"]) as u32), + )?; + writeln!( + out, + "fill {repeat} {}", + aquifer.should_schedule_fluid_update() + )?; + for section in 0..(height / 16) as usize { + writeln!(out, "section {section}")?; + for index in 0..4096 { + writeln!(out, "{}", chunk.section(section).unwrap().get(index)?.0)?; + } + } + for kind in [HeightmapType::OceanFloorWg, HeightmapType::WorldSurfaceWg] { + writeln!(out, "heightmap {}", kind.name())?; + for word in chunk.heightmap(kind).unwrap().raw_data() { + writeln!(out, "{word:x}")?; + } + } + for (section, list) in chunk.postprocessing().iter().enumerate() { + writeln!(out, "post {section} {}", list.len())?; + for offset in list { + writeln!(out, "{offset}")?; + } + } + } + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; + let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("registries.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List( + facts["states"] + .as_array() + .unwrap() + .iter() + .map(|s| tag(&s[4])) + .collect(), + ), + ), + ("defaults", tag(&facts["defaults"])), + ]))?; + let mut definitions = TagDefinitions::default(); + for (name, text) in bundle["tags"].as_object().unwrap() { + definitions.apply_json(name, "vanilla", text.as_str().unwrap())?; + } + let built = definitions.build(|id, _| facts["defaults"].get(id).map(|_| id.to_owned()))?; + assert!(built.missing.is_empty()); + let motion: BTreeSet<_> = built.tags["minecraft:blocks_motion_in_heightmap"] + .iter() + .map(String::as_str) + .collect(); + let no_leaves: BTreeSet<_> = built.tags["minecraft:blocks_motion_in_heightmap_no_leaves"] + .iter() + .map(String::as_str) + .collect(); + let states: Vec<_> = facts["states"] + .as_array() + .unwrap() + .iter() + .map(|a| { + let name = a[0].as_str().unwrap(); + State { + air: a[1].as_bool().unwrap(), + air_block: name == "minecraft:air", + fluid: a[2].as_bool().unwrap(), + motion: motion.contains(name), + no_leaves: no_leaves.contains(name), + } + }) + .collect(); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + fixture( + serde_json::from_str(line)?, + ®istry, + &states, + &bundle, + &mut out, + )?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/examples/tick_fixture.rs b/crates/horizon-world/examples/tick_fixture.rs new file mode 100644 index 000000000..7b5bfa8ed --- /dev/null +++ b/crates/horizon-world/examples/tick_fixture.rs @@ -0,0 +1,71 @@ +//! Process vanilla saved block/fluid ticks through Horizon's storage and queues. +use horizon_core::{ + position::ChunkPos, + ticks::{ScheduledTick, TickPriority, TickTypeId}, +}; +use horizon_world::{ + chunk::ChunkData, + compression::Compression, + nbt::{self, Limits, Tag}, + region::{ChunkRecord, RegionFile, RegionWriter}, + tick_data::TickKind, +}; +use std::{collections::BTreeMap, error::Error, fs, path::PathBuf}; +fn main() -> Result<(), Box> { + let base = PathBuf::from( + std::env::args() + .nth(1) + .ok_or("expected fixture directory")?, + ); + let bytes = fs::read(base.join("ticks-input.nbt"))?; + let (root, used) = nbt::read_named(&bytes, Limits::default())?; + assert_eq!(used, bytes.len()); + let mut chunk = ChunkData::new(root)?; + for (kind, ids_field, time) in [ + (TickKind::Block, "block_ids", 1000), + (TickKind::Fluid, "fluid_ids", i64::MAX - 8), + ] { + let Some(Tag::Compound(entries)) = chunk.root().tag.get(ids_field) else { + return Err("missing type IDs".into()); + }; + let mut ids = BTreeMap::new(); + let mut names = BTreeMap::new(); + for (name, id) in entries { + let Tag::Int(id) = id else { + return Err("invalid ID".into()); + }; + let name = name.to_string()?; + ids.insert(name.clone(), TickTypeId(*id as u32)); + names.insert(TickTypeId(*id as u32), name); + } + let mut ticks = chunk.saved_ticks(kind, |name| ids.get(name).copied())?; + assert!(ticks.peek().is_none()); + assert_eq!(ticks.count(), 251); + ticks.unpack(time); + if let Some(first) = ticks.poll() { + assert!(ticks.schedule(ScheduledTick { + trigger_tick: time.wrapping_add(123), + priority: TickPriority::High, + sub_tick_order: 77, + ..first + })); + } + let saved = ticks.pack(time); + chunk.set_saved_ticks(kind, &saved, |id| names.get(&id).cloned())?; + } + let root = chunk.into_nbt(); + fs::write( + base.join("ticks-output.nbt"), + nbt::write_named(&root, Limits::default())?, + )?; + let path = base.join("tick-region/r.0.0.mca"); + let record = ChunkRecord::from_nbt(&root, Compression::Zlib, 123, Limits::default())?; + let mut writer = RegionWriter::create(&path)?; + writer.write(ChunkPos::new(0, 0), &record)?; + writer.finish()?; + let record = RegionFile::open(path)? + .read(ChunkPos::new(0, 0))? + .ok_or("missing region chunk")?; + assert_eq!(record.nbt(Limits::default())?, root); + Ok(()) +} diff --git a/crates/horizon-world/examples/value_provider_fixture.rs b/crates/horizon-world/examples/value_provider_fixture.rs new file mode 100644 index 000000000..be7bf8afe --- /dev/null +++ b/crates/horizon-world/examples/value_provider_fixture.rs @@ -0,0 +1,68 @@ +//! Transport for decoded scalar provider samples and subsequent random state. +use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; +use horizon_world::worldgen::value_provider::{FloatProvider, IntProvider}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn bits(value: f32) -> u32 { + if value.is_nan() { + 0x7fc00000 + } else { + value.to_bits() + } +} +fn fixture( + f: &Value, + mut random: impl RandomSource, + out: &mut impl Write, +) -> Result<(), Box> { + let json = f["definition"].as_str().unwrap(); + match f["kind"].as_str().unwrap() { + "float" => match FloatProvider::from_json(json) { + Ok(provider) => { + let [min, max] = provider.bounds(); + writeln!(out, "float {:x} {:x}", bits(min), bits(max))?; + for _ in 0..f["samples"].as_u64().unwrap() { + writeln!(out, "sample {:x}", bits(provider.sample(&mut random)))?; + writeln!(out, "next {}", random.next_long())?; + } + } + Err(_) => writeln!(out, "decode error")?, + }, + "int" => match IntProvider::from_json(json) { + Ok(provider) => { + let [min, max] = provider.bounds(); + writeln!(out, "int {min} {max}")?; + for _ in 0..f["samples"].as_u64().unwrap() { + match provider.sample(&mut random) { + Ok(value) => writeln!(out, "sample {value}")?, + Err(_) => writeln!(out, "sample error")?, + } + writeln!(out, "next {}", random.next_long())?; + } + } + Err(_) => writeln!(out, "decode error")?, + }, + _ => unreachable!(), + } + writeln!(out, "tail {}", random.next_long())?; + Ok(()) +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, LegacyRandom::new(seed), &mut out)?; + } else { + fixture(&f, XoroshiroRandom::new(seed), &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/world_fixture.rs b/crates/horizon-world/examples/world_fixture.rs new file mode 100644 index 000000000..d972643cc --- /dev/null +++ b/crates/horizon-world/examples/world_fixture.rs @@ -0,0 +1,154 @@ +//! Exercises world primitives using local vanilla-generated fixtures. +use horizon_world::{ + chunk::{BlockSection, BlockState, PalettedContainer}, + nbt::{self, JavaString, Limits, NamedTag, Tag}, + registry::{BlockRegistry, BlockStateId}, +}; +use std::{error::Error, fs, path::PathBuf}; + +fn main() -> Result<(), Box> { + let base = PathBuf::from( + std::env::args() + .nth(1) + .ok_or("expected fixture directory")?, + ); + let output = base.join("rust/palettes"); + fs::create_dir_all(&output)?; + for entry in fs::read_dir(base.join("palettes"))? { + let entry = entry?; + let filename = entry + .file_name() + .into_string() + .map_err(|_| "invalid filename")?; + let biome = filename.starts_with("biome-"); + let count: usize = filename + .split_once('-') + .unwrap() + .1 + .trim_end_matches(".nbt") + .parse()?; + let len = if biome { 64 } else { 4096 }; + let (root, _) = nbt::read_named(&fs::read(entry.path())?, Limits::default())?; + let mut palette = PalettedContainer::from_nbt(&root.tag, len, if biome { 1 } else { 4 })?; + for i in 0..len { + assert_eq!( + palette.get(i)?, + &Tag::String(JavaString::from(format!("state{}", i % count).as_str())) + ); + } + palette.set(len - 1, Tag::String(JavaString::from("state4096")))?; + for kind in ["edited", "compact"] { + if kind == "compact" { + palette.compact()?; + } + let root = NamedTag { + name: root.name.clone(), + tag: palette.to_nbt(), + }; + fs::write( + output.join(format!("{kind}-{filename}")), + nbt::write_named(&root, Limits::default())?, + )?; + } + } + let (registry_root, _) = nbt::read_named( + &fs::read(base.join("block-registry.nbt"))?, + Limits::default(), + )?; + let registry = BlockRegistry::from_nbt(®istry_root.tag)?; + let Some(Tag::List(states)) = registry_root.tag.get("states") else { + return Err("missing states".into()); + }; + for (i, tag) in states.iter().enumerate() { + let state = BlockState::from_nbt(tag)?; + assert_eq!(registry.id(&state), Some(BlockStateId(i as u32))); + assert_eq!(registry.state(BlockStateId(i as u32)), Some(&state)); + assert_eq!(registry.resolve(&state)?, BlockStateId(i as u32)); + let descriptor = BlockState { + name: state.name.clone(), + properties: Default::default(), + }; + assert_eq!( + registry.resolve(&descriptor)?, + registry.default_state(&state.name).unwrap() + ); + } + fs::write( + base.join("rust/block-registry.nbt"), + nbt::write_named(®istry_root, Limits::default())?, + )?; + let mut section = BlockSection::uniform(BlockStateId(0), ®istry)?; + for i in 0..4096 { + section.set(i, BlockStateId(((i * 7) % registry.len()) as u32))?; + } + assert_eq!(section.bits(), 12); + let root = NamedTag { + name: "".into(), + tag: section.to_nbt()?, + }; + fs::write( + base.join("rust/runtime-section.nbt"), + nbt::write_named(&root, Limits::default())?, + )?; + let loaded = BlockSection::from_nbt(&root.tag, ®istry)?; + for i in 0..4096 { + assert_eq!(loaded.get(i)?, section.get(i)?); + } + assert!(section.set(4096, BlockStateId(0)).is_err()); + assert!(section.set(0, BlockStateId(registry.len() as u32)).is_err()); + // Rotate every registered state through one slot to exercise slot reuse. + for i in 0..registry.len() { + section.set(0, BlockStateId(i as u32))?; + } + for i in 1..4096 { + assert_eq!( + section.get(i)?, + BlockStateId(((i * 7) % registry.len()) as u32) + ); + } + for i in 0..4096 { + section.set(i, BlockStateId(0))?; + } + assert_eq!(section.bits(), 0); + // Mixed replacement, sharing, and compaction must preserve every block. + let mut expected = vec![BlockStateId(0); 4096]; + let mut random = 0x31415926u64; + for step in 0..100_000 { + random = random.wrapping_mul(6364136223846793005).wrapping_add(1); + let index = (random >> 32) as usize % 4096; + let state = BlockStateId(if step % 3 == 0 { + 0 + } else { + (random >> 16) as u32 % registry.len() as u32 + }); + assert_eq!(section.set(index, state)?, expected[index]); + expected[index] = state; + if step % 8192 == 0 { + section.compact()?; + for (index, state) in expected.iter().enumerate() { + assert_eq!(section.get(index)?, *state); + } + } + } + let mutated = NamedTag { + name: "".into(), + tag: section.to_nbt()?, + }; + fs::write( + base.join("rust/runtime-mutated.nbt"), + nbt::write_named(&mutated, Limits::default())?, + )?; + let loaded = BlockSection::from_nbt(&mutated.tag, ®istry)?; + for (index, state) in expected.iter().enumerate() { + assert_eq!(loaded.get(index)?, *state); + section.set(index, BlockStateId(0))?; + } + section.compact()?; + assert_eq!(section.bits(), 0); + assert!(section.to_nbt()?.get("data").is_none()); + println!( + "Rust registry: {} states and default-state resolutions checked", + registry.len() + ); + Ok(()) +} diff --git a/crates/horizon-world/examples/worldgen_random_fixture.rs b/crates/horizon-world/examples/worldgen_random_fixture.rs new file mode 100644 index 000000000..1cf37b1f9 --- /dev/null +++ b/crates/horizon-world/examples/worldgen_random_fixture.rs @@ -0,0 +1,134 @@ +use horizon_core::{ + position::BlockPos, + random::{ + LegacyRandom, PositionalRandom, RandomSource, WorldgenRandom, WorldgenSource, + XoroshiroRandom, slime_chunk_random, + }, +}; +use serde_json::Value; +use std::{ + fs, + io::{self, Write}, + path::Path, +}; +fn n(v: &Value) -> i32 { + v.as_i64().unwrap() as i32 +} +fn l(v: &Value) -> i64 { + v.as_i64().unwrap() +} +fn fixture(f: &Value, source: impl WorldgenSource, out: &mut impl Write) -> io::Result<()> { + let mut root = WorldgenRandom::new(source); + let mut child = None; + for op in f["ops"].as_array().unwrap() { + match op[0].as_str().unwrap() { + "root" => { + child = None; + writeln!(out, "root")?; + } + "bits" => writeln!(out, "bits {}", root.next_bits(n(&op[1])))?, + "decoration" => writeln!( + out, + "decoration {}", + root.set_decoration_seed(l(&op[1]), n(&op[2]), n(&op[3])) + )?, + "feature" => { + root.set_feature_seed(l(&op[1]), n(&op[2]), n(&op[3])); + writeln!(out, "feature")?; + } + "large" => { + root.set_large_feature_seed(l(&op[1]), n(&op[2]), n(&op[3])); + writeln!(out, "large")?; + } + "salt" => { + root.set_large_feature_with_salt(l(&op[1]), n(&op[2]), n(&op[3]), n(&op[4])); + writeln!(out, "salt")?; + } + "slime" => { + let mut r = slime_chunk_random(n(&op[1]), n(&op[2]), l(&op[3]), l(&op[4])); + writeln!( + out, + "slime {} {}", + r.next_long(), + r.next_int_bound(10).unwrap() + )?; + } + kind => { + let random = child.as_mut().unwrap_or(&mut root); + match kind { + "int" => writeln!(out, "int {}", random.next_int())?, + "long" => writeln!(out, "long {}", random.next_long())?, + "bool" => writeln!(out, "bool {}", random.next_boolean())?, + "float" => writeln!(out, "float {:x}", random.next_float().to_bits())?, + "double" => writeln!(out, "double {:x}", random.next_double().to_bits())?, + "bound" => match random.next_int_bound(n(&op[1])) { + Ok(v) => writeln!(out, "bound {v}")?, + Err(_) => writeln!(out, "bound error")?, + }, + "seed" => { + random.set_seed(l(&op[1])); + writeln!(out, "seed")?; + } + "consume" => { + random.consume_count(n(&op[1])); + writeln!(out, "consume")?; + } + "fork" => { + child = Some(random.fork()); + writeln!(out, "fork")?; + } + "pos" => { + child = Some(random.fork_positional().at(BlockPos::new( + n(&op[1]), + n(&op[2]), + n(&op[3]), + ))); + writeln!(out, "pos")?; + } + "pos_seed" => { + child = Some(random.fork_positional().from_seed(l(&op[1]))); + writeln!(out, "pos_seed")?; + } + "pos_hash" => { + let units = op[1] + .as_array() + .unwrap() + .iter() + .map(|v| n(v) as u16) + .collect::>(); + child = Some(random.fork_positional().from_hash_of_utf16(&units)); + writeln!(out, "pos_hash")?; + } + _ => panic!("unknown operation"), + } + } + } + writeln!(out, "count {}", root.count())?; + } + writeln!(out, "tail {}", root.next_long())?; + writeln!(out, "count {}", root.count())?; + Ok(()) +} +fn layers(f: &Value, mut source: impl WorldgenSource, out: &mut impl Write) -> io::Result<()> { + source.consume_count(n(&f["warmup"])); + match n(&f["layers"]) { + 1 => fixture(f, source, out), + 2 => fixture(f, WorldgenRandom::new(source), out), + 3 => fixture(f, WorldgenRandom::new(WorldgenRandom::new(source)), out), + _ => panic!("unsupported layer count"), + } +} +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(line)?; + if f["legacy"].as_bool().unwrap() { + layers(&f, LegacyRandom::new(l(&f["seed"])), &mut out)?; + } else { + layers(&f, XoroshiroRandom::new(l(&f["seed"])), &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/src/bin/worldgen_parity.rs b/crates/horizon-world/src/bin/worldgen_parity.rs new file mode 100644 index 000000000..eaf585023 --- /dev/null +++ b/crates/horizon-world/src/bin/worldgen_parity.rs @@ -0,0 +1,915 @@ +//! Original transport for version-specific JSON decoding comparisons. +use horizon_core::{ + density::{ + SamplerContext, + graph::{DensityCompiler, FunctionId}, + }, + noise::DensityVolume, + noise::{Noise, NormalNoise}, + random::{LegacyRandom, RandomSource, XoroshiroRandom}, +}; +use horizon_world::worldgen::{ + decode_noise, + density::DensityRegistry, + router::{NoiseRouter, RouterField}, +}; +use std::io::{self, BufRead, Write}; + +fn bits(value: f32) -> u32 { + if value.is_nan() { + 0x7fc0_0000 + } else { + value.to_bits() + } +} +fn probe( + noise: &NormalNoise, + random: &mut impl RandomSource, + nether: bool, + out: &mut impl Write, +) -> Result<(), Box> { + let sampler = match if nether { + noise.create_for_legacy_nether_biome(random) + } else { + noise.create(random) + } { + Ok(sampler) => sampler, + Err(_) => { + writeln!(out, "sample error {}", random.next_long())?; + return Ok(()); + } + }; + for [x, y, z] in [ + [0., 0., 0.], + [-17.25, 64.125, 32.5], + [30e6, -64., -30e6], + [1.25, -0.5, -3.75], + [33554432., -2048., -33554433.], + ] { + writeln!( + out, + "query {} {}", + bits(sampler.get2(x, z)), + bits(sampler.get3(x, y, z)) + )?; + } + writeln!(out, "parent {}", random.next_long())?; + Ok(()) +} +fn registry_probe( + path: &str, + seed: i64, + legacy: bool, + optimized: bool, + out: &mut impl Write, +) -> Result<(), Box> { + let bundle: std::collections::BTreeMap> = + serde_json::from_str(&std::fs::read_to_string(path)?)?; + let registry = DensityRegistry::from_json(&bundle["noises"], &bundle["densities"])?; + let entries: Vec<_> = registry + .entries() + .map(|(name, id)| (name.to_owned(), id)) + .collect(); + let mut compiler = DensityCompiler::new_seeded(registry.into_graph(), seed, legacy); + writeln!(out, "registry {}", entries.len())?; + for (name, id) in entries { + sample_root( + &mut compiler, + id, + &name, + optimized, + false, + &mut SamplerContext::cached(), + out, + )?; + } + Ok(()) +} +fn sample_root( + compiler: &mut DensityCompiler, + id: FunctionId, + name: &str, + optimized: bool, + router: bool, + context: &mut SamplerContext, + out: &mut impl Write, +) -> Result<(), Box> { + let range = compiler.graph().range(id)?; + writeln!( + out, + "entry {name} {} {} {}", + bits(range.min()), + bits(range.max()), + compiler.graph().domain_axes(id)? + )?; + let sampler = match if optimized { + compiler.get_sampler(id) + } else { + compiler.compile_raw(id) + } { + Ok(sampler) => sampler, + Err(_) => { + writeln!(out, "compile error")?; + return Ok(()); + } + }; + writeln!(out, "compile ok {}", compiler.cache_count())?; + for position in [ + [0, 0, 0], + [-17, -64, 32], + [30000000, 319, -30000000], + [1, -1, -1], + ] { + writeln!( + out, + "density {}", + bits(sampler.sample_value(context, position)?) + )?; + } + let mut volumes = vec![ + ([2, 9, 2], [-17, -64, 32], [1, 1, 1]), + ([2, 9, 2], [-16, -64, 32], [4, 8, 4]), + ]; + if router { + volumes.push(([3, 1, 2], [-17, 0, 32], [4, 1, 4])); + } + for (extents, minimum, steps) in volumes { + let volume = DensityVolume::new(extents, minimum, steps)?; + let mut buffer = vec![0.; volume.size()]; + for _ in 0..2 { + let result = sampler.sample_volume(context, &mut buffer, volume); + writeln!( + out, + "volume {}", + if result.is_ok() { "ok" } else { "error" } + )?; + for value in &buffer { + writeln!(out, "cell {}", bits(*value))?; + } + } + } + Ok(()) +} +fn router_probe( + path: &str, + setting: &str, + seed: i64, + legacy: bool, + optimized: bool, + out: &mut impl Write, +) -> Result<(), Box> { + let bundle: std::collections::BTreeMap> = + serde_json::from_str(&std::fs::read_to_string(path)?)?; + let mut registry = DensityRegistry::from_json(&bundle["noises"], &bundle["densities"])?; + let settings: std::collections::BTreeMap> = + serde_json::from_str(&bundle["settings"][setting])?; + let router = NoiseRouter::from_json(settings["noise_router"].get(), &mut registry)?; + let mut compiler = DensityCompiler::new_seeded(registry.into_graph(), seed, legacy); + let mut context = SamplerContext::cached(); + writeln!(out, "router {setting} 8")?; + for field in RouterField::ALL { + sample_root( + &mut compiler, + router.function(field), + field.name(), + optimized, + true, + &mut context, + out, + )?; + } + let climate = router.compile_climate(&mut compiler)?; + writeln!(out, "climate caches {}", compiler.cache_count())?; + for position in [ + [0, 0, 0], + [-5, -16, 8], + [7500000, 79, -7500000], + [i32::MIN, i32::MAX, -1], + [536870912, -536870913, 17], + [-4, 0, 8], + ] { + write!(out, "climate")?; + for value in climate.sample(&mut context, position)?.parameters() { + write!(out, " {value}")?; + } + writeln!(out)?; + } + for (preset, json) in &bundle["presets"] { + let source = + horizon_world::worldgen::biome::MultiNoiseBiomeSource::from_quantized_json(json)?; + writeln!( + out, + "biomes {preset} {}", + source.parameters().entries().len() + )?; + let mut resolver = source.resolver(&climate); + for position in [ + [0, 0, 0], + [-5, -16, 8], + [7500000, 79, -7500000], + [i32::MIN, i32::MAX, -1], + [536870912, -536870913, 17], + [-4, 0, 8], + ] { + writeln!(out, "biome {}", resolver.sample(&mut context, position)?)?; + } + for (minimum, extents) in [ + ([-5, -16, 8], [3, 4, 2]), + ([-4, -16, 8], [3, 4, 2]), + ([i32::MAX - 1, i32::MIN, -1], [2, 2, 2]), + ] { + let volume = resolver.prepare_volume(&mut context, minimum, extents)?; + let mut positions = Vec::new(); + for z in 0..extents[2] { + for x in 0..extents[0] { + for y in 0..extents[1] { + positions.push([ + minimum[0].wrapping_add(x), + minimum[1].wrapping_add(y), + minimum[2].wrapping_add(z), + ]); + } + } + } + for position in positions + .iter() + .chain(positions.iter().rev()) + .chain(positions.iter().take(3)) + { + writeln!( + out, + "biomecell {}", + resolver.sample_prepared(&volume, *position)? + )?; + } + } + } + Ok(()) +} +fn index_probe( + branching: usize, + json: &str, + out: &mut impl Write, +) -> Result<(), Box> { + use horizon_world::worldgen::climate::{ClimateIndex, Parameter, ParameterPoint, TargetPoint}; + let input: serde_json::Value = serde_json::from_str(json)?; + let mut entries = Vec::new(); + for (id, entry) in input["entries"] + .as_array() + .ok_or("entries")? + .iter() + .enumerate() + { + let coords = entry["coordinates"].as_array().ok_or("coordinates")?; + let mut coordinates = [Parameter::new(0, 0); 6]; + for (coordinate, value) in coordinates.iter_mut().zip(coords) { + *coordinate = Parameter::new( + value[0].as_i64().ok_or("minimum")?, + value[1].as_i64().ok_or("maximum")?, + ); + } + entries.push(( + ParameterPoint { + coordinates, + offset: entry["offset"].as_i64().ok_or("offset")?, + }, + id, + )); + } + let index = match ClimateIndex::with_branching(entries, branching) { + Ok(index) => index, + Err(_) => { + writeln!(out, "index error")?; + return Ok(()); + } + }; + writeln!(out, "index ok {}", index.entries().len())?; + for id in index.leaf_order() { + writeln!(out, "leaf {id}")?; + } + let mut cached = index.searcher(); + for target in input["targets"].as_array().ok_or("targets")? { + let values = target.as_array().ok_or("target")?; + let point = TargetPoint { + temperature: values[0].as_i64().ok_or("temperature")?, + humidity: values[1].as_i64().ok_or("humidity")?, + continentalness: values[2].as_i64().ok_or("continentalness")?, + erosion: values[3].as_i64().ok_or("erosion")?, + depth: values[4].as_i64().ok_or("depth")?, + weirdness: values[5].as_i64().ok_or("weirdness")?, + }; + let brute = index.brute_force(point); + writeln!( + out, + "brute {brute} {}", + index.entries()[*brute].0.fitness(point) + )?; + for (label, result) in [ + ("cached", cached.find(point)), + ("fresh", index.searcher().find(point)), + ] { + match result { + Ok(id) => writeln!( + out, + "{label} {id} {}", + index.entries()[*id].0.fitness(point) + )?, + Err(_) => writeln!(out, "{label} error")?, + } + } + } + Ok(()) +} +fn settings_probe( + settings: horizon_world::worldgen::settings::NoiseSettings, + out: &mut impl Write, +) -> Result<(), Box> { + writeln!(out, "settings {} {}", settings.min_y, settings.height)?; + for (minimum, height) in [ + (-64, 384), + (0, 128), + (-2032, 4064), + (17, 15), + (2048, 16), + (i32::MAX, 1), + (i32::MIN, i32::MAX), + ] { + let clamped = settings.clamp_to_height(minimum, height); + writeln!(out, "clamped {} {}", clamped.min_y, clamped.height)?; + } + Ok(()) +} +fn aquifer_probe(line: &str, out: &mut impl Write) -> Result<(), Box> { + use horizon_world::{ + registry::BlockStateId, + worldgen::aquifer::{DisabledAquifer, FluidPicker, FluidStatus, GlobalFluidPicker}, + }; + use std::sync::atomic::{AtomicUsize, Ordering}; + #[derive(Debug)] + struct Counted { + picker: GlobalFluidPicker, + calls: AtomicUsize, + } + impl FluidPicker for Counted { + fn compute(&self, position: [i32; 3]) -> FluidStatus { + self.calls.fetch_add(1, Ordering::Relaxed); + self.picker.compute(position) + } + } + let args: Vec<_> = line.split_whitespace().collect(); + let sea = args[1].parse::()?; + let fluid = BlockStateId(args[2].parse::()?); + let position = [args[3].parse()?, args[4].parse()?, args[5].parse()?]; + let density = f64::from_bits(u64::from_str_radix(args[6], 16)?); + // Local labels correspond to actual reference default block states. They + // exercise identity-based selection independently of numeric registry IDs. + let picker = GlobalFluidPicker::new(sea, fluid, BlockStateId(1), BlockStateId(2)); + let status = picker.compute(position); + writeln!( + out, + "fluid {} {} {}", + status.level, + status.state.0, + status.at(position[1], BlockStateId(2)).0 + )?; + let counted = Counted { + picker, + calls: AtomicUsize::new(0), + }; + let aquifer = DisabledAquifer::new(&counted, BlockStateId(2)); + let substance = aquifer.compute_substance(position, density); + let label = substance.map_or_else(|| "default_solid".to_string(), |id| id.0.to_string()); + writeln!( + out, + "substance {label} {} {}", + aquifer.should_schedule_fluid_update(), + counted.calls.load(Ordering::Relaxed) + )?; + Ok(()) +} +fn noise_aquifer_probe(line: &str, out: &mut impl Write) -> Result<(), Box> { + use horizon_core::{ + density::{ConstantSampler, DensitySampler, SampleError}, + random::PositionalRandom, + }; + use horizon_world::{ + registry::BlockStateId, + worldgen::aquifer::{ + AquiferBlockStates, AquiferConfig, AquiferField, AquiferSamplers, FluidPicker, + FluidStatus, GlobalFluidPicker, NoiseBasedAquifer, + }, + }; + use std::sync::{Arc, Mutex}; + #[derive(Debug)] + struct Traced { + sampler: Arc, + field: usize, + events: Arc>>, + calls: Mutex, + fail: Option, + } + impl Traced { + fn enter(&self, event: String) -> Result<(), SampleError> { + self.events.lock().unwrap().push(event); + let mut calls = self.calls.lock().unwrap(); + *calls += 1; + if self.fail == Some(*calls) { + self.events + .lock() + .unwrap() + .push(format!("sample failure {}", self.field)); + Err(SampleError::ZeroGradientPeriod) + } else { + Ok(()) + } + } + } + impl DensitySampler for Traced { + fn sample_value( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + self.enter(format!( + "sample {} value {} {} {}", + self.field, position[0], position[1], position[2] + ))?; + let result = self.sampler.sample_value(context, position); + self.events.lock().unwrap().push(match result { + Ok(value) => format!("value {}", bits(value)), + Err(_) => "value error".into(), + }); + result + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + let size = volume.sizes(); + let min = volume.minimum(); + let steps = volume.steps(); + self.enter(format!( + "sample {} volume {} {} {} {} {} {} {} {} {}", + self.field, + size[0], + size[1], + size[2], + min[0], + min[1], + min[2], + steps[0], + steps[1], + steps[2] + ))?; + let result = self.sampler.sample_volume(context, buffer, volume); + let mut events = self.events.lock().unwrap(); + events.push(format!( + "sample volume {}", + if result.is_ok() { "ok" } else { "error" } + )); + events.extend( + buffer + .iter() + .map(|value| format!("sample cell {}", bits(*value))), + ); + result + } + } + #[derive(Debug)] + struct Picker { + inner: GlobalFluidPicker, + events: Arc>>, + } + impl FluidPicker for Picker { + fn compute(&self, position: [i32; 3]) -> FluidStatus { + let status = self.inner.compute(position); + self.events.lock().unwrap().push(format!( + "pick {} {} {} {} {}", + position[0], position[1], position[2], status.level, status.state.0 + )); + status + } + } + struct Blocks; + impl AquiferBlockStates for Blocks { + fn air(&self) -> BlockStateId { + BlockStateId(2) + } + fn lava(&self) -> BlockStateId { + BlockStateId(1) + } + fn is_air(&self, s: BlockStateId) -> bool { + matches!(s.0, 2 | 4 | 5) + } + fn is_lava(&self, s: BlockStateId) -> bool { + matches!(s.0, 1 | 7) + } + fn is_water(&self, s: BlockStateId) -> bool { + matches!(s.0, 0 | 6) + } + } + fn flush(events: &Mutex>, out: &mut impl Write) -> io::Result<()> { + for event in events.lock().unwrap().drain(..) { + writeln!(out, "{event}")?; + } + Ok(()) + } + fn run( + samplers: AquiferSamplers, + picker: Picker, + random: F, + volume: DensityVolume, + queries: &serde_json::Value, + events: Arc>>, + out: &mut impl Write, + ) -> Result<(), Box> { + let mut context = SamplerContext::cached(); + let created = + NoiseBasedAquifer::new(samplers, picker, random, Blocks, volume, &mut context); + flush(&events, out)?; + let mut aquifer = match created { + Ok(value) => value, + Err(_) => { + writeln!(out, "aquifer create error")?; + return Ok(()); + } + }; + writeln!(out, "aquifer ready {}", aquifer.skip_sampling_above_y())?; + for query in queries.as_array().ok_or("queries")? { + let position = [ + query[0].as_i64().ok_or("x")? as i32, + query[1].as_i64().ok_or("y")? as i32, + query[2].as_i64().ok_or("z")? as i32, + ]; + let density = f64::from_bits(u64::from_str_radix( + query[3].as_str().ok_or("density")?, + 16, + )?); + let result = aquifer.compute_substance(&mut context, position, density); + flush(&events, out)?; + let result = match result { + Ok(Some(state)) => state.0.to_string(), + Ok(None) => "default_solid".into(), + Err(_) => "error".into(), + }; + writeln!( + out, + "aquifer result {result} {}", + aquifer.should_schedule_fluid_update() + )?; + } + for (index, (location, status)) in aquifer.cached_cells().enumerate() { + let status = status.map_or("none".into(), |s| format!("{} {}", s.level, s.state.0)); + writeln!(out, "aquifer cell {index} {location} {status}")?; + } + let mut surfaces: Vec<_> = aquifer.cached_surfaces().collect(); + surfaces.sort_by_key(|entry| entry.0); + for (key, value) in surfaces { + writeln!(out, "aquifer surface {key} {value}")?; + } + Ok(()) + } + let fields: Vec<_> = line.splitn(6, ' ').collect(); + let seed: i64 = fields[1].parse()?; + let legacy = fields[2] == "1"; + let bundle: std::collections::BTreeMap> = + serde_json::from_str(&std::fs::read_to_string(fields[3])?)?; + let fixture: serde_json::Value = serde_json::from_str(fields[5])?; + let mut registry = DensityRegistry::from_json(&bundle["noises"], &bundle["densities"])?; + let settings: std::collections::BTreeMap> = + serde_json::from_str(&bundle["settings"][fields[4]])?; + let config_text = fixture + .get("config") + .map(|c| c.as_str().ok_or("config string")) + .transpose()? + .unwrap_or_else(|| settings.get("aquifers").map_or("null", |v| v.get())); + let config = match AquiferConfig::from_json(config_text, &mut registry) { + Ok(config) => config, + Err(_) => { + writeln!(out, "aquifer config error")?; + return Ok(()); + } + }; + let mut compiler = DensityCompiler::new_seeded(registry.into_graph(), seed, legacy); + let samplers = match config.compile(&mut compiler) { + Ok(s) => s, + Err(_) => { + writeln!(out, "aquifer compile error")?; + return Ok(()); + } + }; + writeln!(out, "aquifer compile ok {}", compiler.cache_count())?; + let events = Arc::new(Mutex::new(Vec::new())); + let mut traced = Vec::new(); + for field in AquiferField::ALL { + let i = field as usize; + let sampler = if let Some(value) = fixture + .get("overrides") + .and_then(|v| v.get(i)) + .and_then(|v| v.as_str()) + { + Arc::new(ConstantSampler(f32::from_bits(u32::from_str_radix( + value, 16, + )?))) as Arc + } else { + samplers.get(field).clone() + }; + let fail = fixture + .get("fail") + .filter(|f| f[0].as_u64() == Some(i as u64)) + .and_then(|f| f[1].as_u64()) + .map(|n| n as usize); + traced.push(Arc::new(Traced { + sampler, + field: i, + events: events.clone(), + calls: Mutex::new(0), + fail, + }) as Arc); + } + let samplers = AquiferSamplers::new(traced.try_into().unwrap()); + let array = |name: &str| -> Result<[i32; 3], Box> { + Ok(std::array::from_fn(|i| { + fixture[name][i].as_i64().unwrap() as i32 + })) + }; + let volume = DensityVolume::new(array("sizes")?, array("minimum")?, array("steps")?)?; + let picker = Picker { + inner: GlobalFluidPicker::new( + fixture["sea"].as_i64().ok_or("sea")? as i32, + BlockStateId(fixture["fluid"].as_u64().ok_or("fluid")? as u32), + BlockStateId(1), + BlockStateId(2), + ), + events: events.clone(), + }; + if legacy { + let random = LegacyRandom::new(seed) + .fork_positional() + .from_hash_of("minecraft:aquifer") + .fork_positional(); + run( + samplers, + picker, + random, + volume, + &fixture["queries"], + events, + out, + ) + } else { + let random = XoroshiroRandom::new(seed) + .fork_positional() + .from_hash_of("minecraft:aquifer") + .fork_positional(); + run( + samplers, + picker, + random, + volume, + &fixture["queries"], + events, + out, + ) + } +} + +fn tags_probe( + fixture: &serde_json::Value, + out: &mut impl Write, +) -> Result<(), Box> { + use horizon_world::worldgen::tags::TagDefinitions; + writeln!( + out, + "tags resources {}", + fixture["files"].as_array().ok_or("files")?.len() + )?; + let mut definitions = TagDefinitions::default(); + for file in fixture["files"].as_array().ok_or("files")? { + let name = file[0].as_str().ok_or("name")?; + let source = file[1].as_str().ok_or("source")?; + if definitions + .apply_json(name, source, file[2].as_str().ok_or("json")?) + .is_err() + { + // Fixture names are valid. Codec errors can introduce empty tags. + let canonical = definitions + .definitions() + .keys() + .find(|key| key.as_str() == name || key.as_str() == format!("minecraft:{name}")) + .ok_or("tag name")?; + writeln!(out, "tag resource error {canonical} {source}")?; + } + } + let mut trace = Vec::new(); + let result = definitions.build(|id, required| { + trace.push(format!("tag lookup {id} {required}")); + fixture["elements"] + .get(id) + .and_then(|v| v.as_str()) + .map(str::to_owned) + })?; + for event in trace { + writeln!(out, "{event}")?; + } + writeln!(out, "tags built {}", result.tags.len())?; + for (name, values) in result.tags { + writeln!(out, "tag members {name} {}", values.len())?; + for value in values { + writeln!(out, "tag member {value}")?; + } + } + for name in result.missing.keys() { + writeln!(out, "tag missing {name}")?; + } + Ok(()) +} +fn tag_registry_probe(path: &str, out: &mut impl Write) -> Result<(), Box> { + let bundle: std::collections::BTreeMap> = + serde_json::from_str(&std::fs::read_to_string(path)?)?; + let files: Vec<_> = bundle["tags"] + .iter() + .map(|(name, json)| serde_json::json!([name, "vanilla", json])) + .collect(); + tags_probe( + &serde_json::json!({"files":files,"elements":bundle["block_elements"]}), + out, + ) +} + +fn main() -> Result<(), Box> { + let mut out = io::BufWriter::new(io::stdout().lock()); + for line in io::stdin().lock().lines() { + let line = line?; + let mut args = line.splitn(5, ' '); + let command = args.next().ok_or("command")?; + if command == "tag_entry" { + match horizon_world::worldgen::tags::TagEntry::from_json( + line.strip_prefix("tag_entry ").ok_or("entry")?, + ) { + Ok(e) => writeln!(out, "tag entry {}", e.display())?, + Err(_) => writeln!(out, "tag entry error")?, + } + continue; + } + if command == "tag_file" { + match horizon_world::worldgen::tags::TagFile::from_json( + line.strip_prefix("tag_file ").ok_or("file")?, + ) { + Ok(file) => { + writeln!(out, "tag file {} {}", file.replace, file.entries.len())?; + for e in file.entries { + writeln!(out, "tag entry {}", e.display())?; + } + } + Err(_) => writeln!(out, "tag file error")?, + } + continue; + } + if command == "tag_registry" { + tag_registry_probe( + line.strip_prefix("tag_registry ").ok_or("registry")?, + &mut out, + )?; + continue; + } + if command == "tags" { + tags_probe( + &serde_json::from_str(line.strip_prefix("tags ").ok_or("tags")?)?, + &mut out, + )?; + continue; + } + if command == "noise_aquifer" { + noise_aquifer_probe(&line, &mut out)?; + continue; + } + if command == "aquifer" { + aquifer_probe(&line, &mut out)?; + continue; + } + if command == "noise_settings" { + match horizon_world::worldgen::settings::NoiseSettings::from_json( + line.strip_prefix("noise_settings ") + .ok_or("settings json")?, + ) { + Ok(settings) => settings_probe(settings, &mut out)?, + Err(_) => writeln!(out, "settings error")?, + } + continue; + } + if command == "settings_create" { + let values: Vec = line + .split_whitespace() + .skip(1) + .map(str::parse) + .collect::>()?; + match horizon_world::worldgen::settings::NoiseSettings::create(values[0], values[1]) { + Ok(settings) => settings_probe(settings, &mut out)?, + Err(_) => writeln!(out, "settings error")?, + } + continue; + } + if command == "climate_parameter" { + match horizon_world::worldgen::climate::decode_parameter( + line.strip_prefix("climate_parameter ") + .ok_or("parameter json")?, + ) { + Ok(p) => writeln!(out, "parameter {} {}", p.min, p.max)?, + Err(_) => writeln!(out, "parameter error")?, + } + continue; + } + if command == "climate_point" { + match horizon_world::worldgen::climate::decode_parameter_point( + line.strip_prefix("climate_point ").ok_or("point json")?, + ) { + Ok(p) => { + write!(out, "parameterpoint")?; + for coordinate in p.coordinates { + write!(out, " {} {}", coordinate.min, coordinate.max)?; + } + writeln!(out, " {}", p.offset)?; + } + Err(_) => writeln!(out, "parameterpoint error")?, + } + continue; + } + if command == "index" { + let mut args = line.splitn(3, ' '); + args.next(); + let branching = args.next().ok_or("branching")?.parse::()?; + index_probe(branching, args.next().ok_or("index json")?, &mut out)?; + continue; + } + if command == "quantize" { + let mut values = line.split_whitespace().skip(1); + write!(out, "quantized")?; + for _ in 0..6 { + let value = f32::from_bits(u32::from_str_radix(values.next().ok_or("float")?, 16)?); + write!( + out, + " {}", + horizon_world::worldgen::climate::quantize(value) + )?; + } + writeln!(out)?; + let value = values.next().ok_or("long")?.parse::()?; + writeln!( + out, + "unquantized {}", + bits(horizon_world::worldgen::climate::unquantize(value)) + )?; + continue; + } + let seed = args.next().ok_or("seed")?.parse::()?; + let legacy = args.next().ok_or("stream")? == "1"; + let nether = args.next().ok_or("nether")? == "1"; + let json = args.next().ok_or("json")?; + if command == "router" { + let (path, setting) = json.split_once(' ').ok_or("router setting")?; + router_probe(path, setting, seed, legacy, nether, &mut out)?; + continue; + } + if command == "registry" { + registry_probe(json, seed, legacy, nether, &mut out)?; + continue; + } + if command != "noise" { + return Err("unknown command".into()); + } + let noise = match decode_noise(json) { + Ok(noise) => noise, + Err(_) => { + writeln!(out, "decode error")?; + continue; + } + }; + let [min, max] = noise.range(); + writeln!( + out, + "decode {} {} {} {}", + noise.octaves().len(), + noise.normalization_factor().to_bits(), + bits(min), + bits(max) + )?; + for octave in noise.octaves() { + writeln!( + out, + "octave {} {} {}", + octave.octave_index, + octave.frequency.to_bits(), + octave.amplitude.to_bits() + )?; + } + if legacy { + probe(&noise, &mut LegacyRandom::new(seed), nether, &mut out)?; + } else { + probe(&noise, &mut XoroshiroRandom::new(seed), nether, &mut out)?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/src/block_collision.rs b/crates/horizon-world/src/block_collision.rs new file mode 100644 index 000000000..965e63512 --- /dev/null +++ b/crates/horizon-world/src/block_collision.rs @@ -0,0 +1,112 @@ +//! No-entity-context block collision queries over cached and dynamic definitions. +//! Entity movement contexts select different shapes and are separate queries. +use crate::{ + collision::CachedCollisionRegistry, + dynamic_support::{DynamicSupport, DynamicSupportError, DynamicSupportWorld}, + registry::{BlockRegistry, BlockStateId}, +}; +use horizon_core::geometry::{Aabb, Direction, Vec3, VoxelShape}; +use std::{collections::HashMap, io, sync::Arc}; + +#[derive(Clone, Copy, Debug)] +pub struct ShulkerCollisionState { + pub previous_progress: f32, + pub progress: f32, +} +impl ShulkerCollisionState { + pub fn bounding_box(self, direction: Direction) -> Aabb { + // Native getProgress(1) retains this interpolation, including rounding. + let progress = 0.5f32 * (self.previous_progress + (self.progress - self.previous_progress)); + let maximum = if progress.is_nan() { + progress + } else { + (-1.0f32).max(progress) + } as f64; + let minimum = if progress.is_nan() { + progress + } else { + (-1.0f32).min(progress) + } as f64; + let [x, y, z] = direction.normal(); + Aabb::new(Vec3::new(-0.5, 0.0, -0.5), Vec3::new(0.5, 1.0, 0.5)) + .expand_towards(Vec3::new( + f64::from(x) * maximum, + f64::from(y) * maximum, + f64::from(z) * maximum, + )) + .contract(Vec3::new( + f64::from(-x) * (1.0 + minimum), + f64::from(-y) * (1.0 + minimum), + f64::from(-z) * (1.0 + minimum), + )) + .move_by(Vec3::new(0.5, 0.0, 0.5)) + } +} + +pub trait DynamicCollisionWorld: DynamicSupportWorld { + /// One block-entity lookup. None denotes absence or another entity type. + fn shulker_collision_state( + &mut self, + position: [i32; 3], + ) -> Result, Self::Error>; +} + +#[derive(Debug)] +pub enum CollisionQueryError { + Data(io::Error), + Dynamic(DynamicSupportError), + Unsupported(BlockStateId), +} +impl std::fmt::Display for CollisionQueryError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Data(error) => error.fmt(f), + Self::Dynamic(error) => error.fmt(f), + Self::Unsupported(state) => write!(f, "unsupported block collision state {}", state.0), + } + } +} +impl std::error::Error for CollisionQueryError {} + +pub struct BlockCollisionRegistry<'r> { + cached: Arc>, + dynamic: HashMap, +} +impl<'r> BlockCollisionRegistry<'r> { + pub fn new(cached: Arc>) -> io::Result { + let mut dynamic = HashMap::new(); + for index in 0..cached.registry().len() { + let id = BlockStateId(index as u32); + if cached.cached_shape(id)?.is_none() { + if let Some(rule) = + DynamicSupport::from_state(cached.registry().state(id).unwrap())? + { + dynamic.insert(id, rule); + } + } + } + Ok(Self { cached, dynamic }) + } + pub fn registry(&self) -> &'r BlockRegistry { + self.cached.registry() + } + pub fn collision_shape( + &self, + world: &mut W, + state: BlockStateId, + position: [i32; 3], + ) -> Result> { + if let Some(shape) = self + .cached + .cached_shape(state) + .map_err(CollisionQueryError::Data)? + { + return Ok(shape.clone()); + } + self.dynamic + .get(&state) + .ok_or(CollisionQueryError::Unsupported(state))? + .collision_shape(world, position) + .map_err(CollisionQueryError::Dynamic) + } +} diff --git a/crates/horizon-world/src/block_properties.rs b/crates/horizon-world/src/block_properties.rs new file mode 100644 index 000000000..4ec7498bc --- /dev/null +++ b/crates/horizon-world/src/block_properties.rs @@ -0,0 +1,171 @@ +//! Immutable block-definition flags and legacy solidity calculated from cached +//! collision shapes. Replacement with an item/fluid context is separate behavior. +use crate::{ + DATA_VERSION, + chunk::BlockState, + collision::CachedCollisionRegistry, + compression::invalid, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, +}; +use horizon_core::geometry::{ShapeError, ShapeOp, VoxelShape}; +use std::{collections::BTreeMap, io, sync::Arc}; + +#[derive(Clone, Copy, Debug)] +pub struct BlockDefinitionProperties { + pub force_solid_on: bool, + pub force_solid_off: bool, + pub replaceable: bool, + pub liquid: bool, + pub can_occlude: bool, +} +impl BlockDefinitionProperties { + pub fn calculate_solid_render(self, occlusion: &VoxelShape) -> Result { + Ok(self.can_occlude && !occlusion.join_is_not_empty(&VoxelShape::block(), ShapeOp::XOR)?) + } + + /// Force-on wins even if both definition flags are set. A missing cache + /// counts as non-solid; it is distinct from a missing collision implementation. + pub fn calculate_solid(self, cached_shape: Option<&VoxelShape>) -> bool { + if self.force_solid_on { + return true; + } + if self.force_solid_off { + return false; + } + cached_shape + .and_then(VoxelShape::bounds) + .is_some_and(|bounds| { + bounds.average_size() >= 0.7291666666666666 || bounds.size().y >= 1.0 + }) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BlockProperty { + Solid, + Replaceable, + Liquid, + SolidRender, +} +impl BlockProperty { + fn mask(self) -> u8 { + match self { + Self::Solid => 1, + Self::Replaceable => 2, + Self::Liquid => 4, + Self::SolidRender => 8, + } + } +} +/// An immutable property selection, shared by decoded block predicates. +#[derive(Clone, Debug)] +pub struct BoundBlockProperty { + states: Arc<[u8]>, + property: BlockProperty, +} +impl BoundBlockProperty { + pub fn contains(&self, id: BlockStateId) -> bool { + self.states + .get(id.0 as usize) + .is_some_and(|flags| flags & self.property.mask() != 0) + } +} + +pub struct BlockPropertiesRegistry<'r> { + registry: &'r BlockRegistry, + definitions: BTreeMap, + states: Arc<[u8]>, +} +impl<'r> BlockPropertiesRegistry<'r> { + pub fn from_nbt(tag: &Tag, collisions: &CachedCollisionRegistry<'r>) -> io::Result { + let registry = collisions.registry(); + if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) { + return Err(invalid("block properties DataVersion mismatch")); + } + let Some(Tag::List(states)) = tag.get("states") else { + return Err(invalid("missing block property state identities")); + }; + if states.len() != registry.len() { + return Err(invalid("block property registry size mismatch")); + } + for (id, state) in states.iter().enumerate() { + if registry.state(BlockStateId(id as u32)) != Some(&BlockState::from_nbt(state)?) { + return Err(invalid("block property state identities differ")); + } + } + let Some(Tag::Compound(blocks)) = tag.get("blocks") else { + return Err(invalid("missing block definition properties")); + }; + let mut definitions = BTreeMap::new(); + for (name, flags) in blocks { + let name = name.to_string().map_err(|e| invalid(e.to_string()))?; + let Tag::Byte(flags @ 0..=31) = flags else { + return Err(invalid("invalid block definition flags")); + }; + if registry.default_state(&name).is_none() { + return Err(invalid("unknown block definition properties")); + } + definitions.insert( + name, + BlockDefinitionProperties { + force_solid_on: flags & 1 != 0, + force_solid_off: flags & 2 != 0, + replaceable: flags & 4 != 0, + liquid: flags & 8 != 0, + can_occlude: flags & 16 != 0, + }, + ); + } + let occlusion = CachedCollisionRegistry::from_nbt( + tag.get("occlusion") + .ok_or_else(|| invalid("missing block occlusion shapes"))?, + registry, + )?; + let mut result = Vec::with_capacity(registry.len()); + for id in 0..registry.len() { + let id = BlockStateId(id as u32); + let state = registry.state(id).unwrap(); + let properties = definitions + .get(&state.name) + .ok_or_else(|| invalid("missing block definition properties"))?; + result.push( + u8::from(properties.calculate_solid(collisions.cached_shape(id)?)) + | (u8::from(properties.replaceable) << 1) + | (u8::from(properties.liquid) << 2) + | (u8::from( + properties + .calculate_solid_render( + occlusion + .cached_shape(id)? + .ok_or_else(|| invalid("missing block occlusion shape"))?, + ) + .map_err(|error| invalid(error.to_string()))?, + ) << 3), + ); + } + Ok(Self { + registry, + definitions, + states: result.into(), + }) + } + pub fn registry(&self) -> &'r BlockRegistry { + self.registry + } + pub fn definition(&self, name: &str) -> Option { + self.definitions.get(name).copied() + } + pub fn property(&self, id: BlockStateId, property: BlockProperty) -> io::Result { + self.states + .get(id.0 as usize) + .map(|flags| flags & property.mask() != 0) + .ok_or_else(|| invalid("block property state outside registry")) + } + pub fn bind(&self, property: BlockProperty) -> BoundBlockProperty { + BoundBlockProperty { + states: Arc::clone(&self.states), + property, + } + } +} diff --git a/crates/horizon-world/src/block_support.rs b/crates/horizon-world/src/block_support.rs new file mode 100644 index 000000000..2c7a9aecc --- /dev/null +++ b/crates/horizon-world/src/block_support.rs @@ -0,0 +1,221 @@ +//! Native support tests over an already-selected block support shape. Selecting +//! that shape from block/world/entity behavior is the caller's responsibility. +use horizon_core::geometry::{Aabb, Direction, ShapeError, ShapeOp, Vec3, VoxelShape}; +use std::sync::OnceLock; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SupportType { + Full, + Center, + Rigid, +} +impl SupportType { + pub fn is_supporting( + self, + shape: &VoxelShape, + direction: Direction, + ) -> Result { + let face = shape.face_shape(direction)?; + let (required, operation) = match self { + Self::Full => (VoxelShape::block(), ShapeOp::XOR), + Self::Center => { + static CENTER: OnceLock = OnceLock::new(); + ( + CENTER + .get_or_init(|| { + VoxelShape::from_box(Aabb::new( + Vec3::new(0.4375, 0.0, 0.4375), + Vec3::new(0.5625, 0.625, 0.5625), + )) + .expect("valid support shape") + }) + .clone(), + ShapeOp::ONLY_SECOND, + ) + } + Self::Rigid => { + static RIGID: OnceLock = OnceLock::new(); + ( + RIGID + .get_or_init(|| { + VoxelShape::block() + .join( + &VoxelShape::from_box(Aabb::new( + Vec3::new(0.125, 0.0, 0.125), + Vec3::new(0.875, 1.0, 0.875), + )) + .expect("valid support inset"), + ShapeOp::ONLY_FIRST, + ) + .expect("valid support ring") + }) + .clone(), + ShapeOp::ONLY_SECOND, + ) + } + }; + Ok(!face.join_is_not_empty(&required, operation)?) + } +} + +use crate::{ + collision::CachedCollisionRegistry, + compression::invalid, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, +}; +use std::{collections::HashMap, io}; +/// Cached branch of BlockState.isFaceSturdy. Dynamic support-shape selection +/// stays explicit as None, even when a context-free approximation looks obvious. +pub struct CachedBlockSupportRegistry<'r> { + shapes: CachedCollisionRegistry<'r>, + states: Vec>, +} +impl<'r> CachedBlockSupportRegistry<'r> { + pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result { + if tag.get("Kind") != Some(&Tag::String("block_support".into())) { + return Err(invalid("wrong cached support data kind")); + } + let shapes = CachedCollisionRegistry::from_nbt(tag, registry)?; + let mut cache = HashMap::new(); + let mut states = Vec::with_capacity(registry.len()); + for id in 0..registry.len() { + let Some(shape) = shapes.cached_shape(BlockStateId(id as u32))? else { + states.push(None); + continue; + }; + let identity = std::ptr::from_ref(shape); + let flags = if let Some(flags) = cache.get(&identity) { + *flags + } else { + let mut flags = [0; 3]; + for (i, support) in [SupportType::Full, SupportType::Center, SupportType::Rigid] + .into_iter() + .enumerate() + { + for direction in Direction::ALL { + if support + .is_supporting(shape, direction) + .map_err(|e| invalid(e.to_string()))? + { + flags[i] |= 1 << direction as u8; + } + } + } + cache.insert(identity, flags); + flags + }; + states.push(Some(flags)); + } + Ok(Self { shapes, states }) + } + pub fn registry(&self) -> &'r BlockRegistry { + self.shapes.registry() + } + pub fn cached_state_count(&self) -> usize { + self.shapes.cached_state_count() + } + pub fn cached_shape(&self, state: BlockStateId) -> io::Result> { + self.shapes.cached_shape(state) + } + pub fn is_face_sturdy( + &self, + state: BlockStateId, + direction: Direction, + support: SupportType, + ) -> io::Result> { + let flags = self + .states + .get(state.0 as usize) + .ok_or_else(|| invalid("support state outside registry"))?; + Ok(flags.map(|flags| { + flags[match support { + SupportType::Full => 0, + SupportType::Center => 1, + SupportType::Rigid => 2, + }] & (1 << direction as u8) + != 0 + })) + } +} + +use crate::dynamic_support::{DynamicSupport, DynamicSupportError, DynamicSupportWorld}; +/// Unified cached/dynamic support dispatch. Block-entity queries remain owned by +/// the world, including the moving-piston entity's collision calculation. +pub struct BlockSupportRegistry<'r> { + cached: CachedBlockSupportRegistry<'r>, + dynamic: HashMap, +} +#[derive(Debug)] +pub enum SupportQueryError { + Data(io::Error), + Dynamic(DynamicSupportError), + Unsupported(BlockStateId), +} +impl std::fmt::Display for SupportQueryError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Data(e) => e.fmt(f), + Self::Dynamic(e) => e.fmt(f), + Self::Unsupported(state) => write!(f, "unsupported block support state {}", state.0), + } + } +} +impl std::error::Error for SupportQueryError {} +impl<'r> BlockSupportRegistry<'r> { + pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result { + let cached = CachedBlockSupportRegistry::from_nbt(tag, registry)?; + let mut dynamic = HashMap::new(); + for id in 0..registry.len() { + let id = BlockStateId(id as u32); + if cached.cached_shape(id)?.is_none() { + if let Some(behavior) = DynamicSupport::from_state(registry.state(id).unwrap())? { + dynamic.insert(id, behavior); + } + } + } + Ok(Self { cached, dynamic }) + } + pub fn registry(&self) -> &'r BlockRegistry { + self.cached.registry() + } + pub fn support_shape( + &self, + world: &mut W, + state: BlockStateId, + position: [i32; 3], + ) -> Result> { + if let Some(shape) = self + .cached + .cached_shape(state) + .map_err(SupportQueryError::Data)? + { + return Ok(shape.clone()); + } + self.dynamic + .get(&state) + .ok_or(SupportQueryError::Unsupported(state))? + .shape(world, position) + .map_err(SupportQueryError::Dynamic) + } + pub fn is_face_sturdy( + &self, + world: &mut W, + state: BlockStateId, + position: [i32; 3], + direction: Direction, + support: SupportType, + ) -> Result> { + if let Some(result) = self + .cached + .is_face_sturdy(state, direction, support) + .map_err(SupportQueryError::Data)? + { + return Ok(result); + } + self.dynamic + .get(&state) + .ok_or(SupportQueryError::Unsupported(state))? + .is_face_sturdy(world, position, direction, support) + .map_err(SupportQueryError::Dynamic) + } +} diff --git a/crates/horizon-world/src/block_survival.rs b/crates/horizon-world/src/block_survival.rs new file mode 100644 index 000000000..0140729a2 --- /dev/null +++ b/crates/horizon-world/src/block_survival.rs @@ -0,0 +1,1215 @@ +//! Initial block-survival rules over version-bound definitions and world queries. +//! Unsupported definitions remain explicit; survival is not inferred from shape. +use crate::{ + block_collision::{BlockCollisionRegistry, CollisionQueryError, DynamicCollisionWorld}, + block_properties::{BlockPropertiesRegistry, BlockProperty, BoundBlockProperty}, + block_support::{BlockSupportRegistry, SupportQueryError, SupportType}, + compression::invalid, + fluid::{FluidKind, FluidState}, + registry::{BlockRegistry, BlockStateId}, +}; +use horizon_core::geometry::Direction; +use std::{ + collections::{BTreeMap, BTreeSet}, + io, + sync::Arc, +}; +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SurvivalRule { + Fire, + Cactus, + Path, + Mushroom, + Multiface, + Vine, + HangingMoss, + SnowLayer, + SeaPickle, + Bell, + GrowingPlant, + MangrovePropagule, + Speleothem, + Scaffolding, + PistonHead, + ChorusPlant, + ChorusFlower, + PitcherCrop, + SugarCane, + LilyPad, + Frogspawn, + SporeBlossom, + SmallDripleaf, + TallSeagrass, + BigDripleaf, + BigDripleafStem, + Farmland, + Cocoa, + Crop, + DoublePlant, + Door, + TagBelow(String), + CactusFlower, + Seagrass, + BubbleColumn, + RedstoneWire, + Always, + SolidBelow, + SolidBehind, + NonAirBelow, + MossCarpet, + CenterBelow, + Lantern, + FullAbove, + FullBehind, + RigidOrCenterBelow, + RigidBelow, + FullBelow, + CenterAbove, + FaceAttached, + SupportsBamboo, +} +/// Version-specific definition inputs, independent of evaluated survival results. +#[derive(Clone, Debug, Default)] +pub struct SurvivalDefinitions { + pub rules: BTreeMap, + pub ignition_odds: BTreeMap, + pub fence_gates: BTreeSet, +} +#[derive(Clone, Copy)] +enum Rule { + Fire, + Cactus, + Path, + Mushroom, + Multiface(u8), + Vine(u8), + HangingMoss, + SnowLayer, + SeaPickle, + GrowingPlant { + head: BlockStateId, + body: BlockStateId, + direction: Direction, + kelp: bool, + }, + MangrovePropagule(bool), + Speleothem(Direction), + Scaffolding, + PistonHead { + direction: Direction, + sticky: bool, + }, + ChorusPlant, + ChorusFlower, + PitcherCrop(bool), + SugarCane, + LilyPad, + Frogspawn, + SporeBlossom, + SmallDripleaf(bool), + TallSeagrass(bool), + BigDripleaf, + BigDripleafStem, + Farmland, + Cocoa(Direction), + Crop, + DoublePlant(bool), + Door(bool), + TagBelow(usize), + CactusFlower, + Seagrass, + BubbleColumn, + RedstoneWire, + Always, + Solid(Direction), + NonAirBelow, + MossCarpet(bool), + Support { + face: Direction, + kind: SupportType, + center_restriction: bool, + }, + RigidOrCenterBelow, + SupportsBamboo, +} +pub trait SurvivalWorld: DynamicCollisionWorld { + fn fluid_state(&mut self, position: [i32; 3]) -> Result; + fn raw_brightness(&mut self, position: [i32; 3], sky_darken: i32) -> Result; + fn block_state(&mut self, position: [i32; 3]) -> Result; +} +#[derive(Debug)] +pub enum SurvivalError { + World(E), + Support(SupportQueryError), + Collision(CollisionQueryError), + Registry(io::Error), + Unsupported(BlockStateId), +} +impl std::fmt::Display for SurvivalError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::World(e) => e.fmt(f), + Self::Support(e) => e.fmt(f), + Self::Collision(e) => e.fmt(f), + Self::Registry(e) => e.fmt(f), + Self::Unsupported(id) => write!(f, "unsupported block survival state {}", id.0), + } + } +} +impl std::error::Error for SurvivalError {} +pub struct BlockSurvivalRegistry<'r> { + registry: &'r BlockRegistry, + support: Arc>, + collision: Arc>, + solid: BoundBlockProperty, + liquid: BoundBlockProperty, + solid_render: BoundBlockProperty, + flammable: BTreeSet, + fence_gates: BTreeSet, + cactus_support: BTreeSet, + mushroom_light_override: BTreeSet, + rules: Vec>, + unstable_bottom_center: BTreeSet, + supports_bamboo: BTreeSet, + bound_tags: Vec>, + cactus_flower: BTreeSet, + no_seagrass: BTreeSet, + vegetation: BTreeSet, + dripleaf: BTreeSet, + maintains_farmland: BTreeSet, + cocoa: BTreeSet, + crops: BTreeSet, + no_snow: BTreeSet, + snow_override: BTreeSet, + mangrove: BTreeSet, + hanging_mangrove: BTreeSet, + no_kelp: BTreeSet, + chorus_plant: BTreeSet, + chorus_flower: BTreeSet, + lily_pad: BTreeSet, + frogspawn: BTreeSet, + small_dripleaf: BTreeSet, + sugar_cane: BTreeSet, + sugar_cane_adjacent: BTreeSet, + fluid_tags: [u8; 5], + bubble_up: BTreeSet, + bubble_down: BTreeSet, +} +impl<'r> BlockSurvivalRegistry<'r> { + pub fn new( + registry: &'r BlockRegistry, + properties: &BlockPropertiesRegistry<'r>, + support: Arc>, + collision: Arc>, + definitions: &SurvivalDefinitions, + tags: &BTreeMap>, + fluid_tags: &BTreeMap>, + ) -> io::Result { + if !std::ptr::eq(registry, properties.registry()) + || !std::ptr::eq(registry, support.registry()) + || !std::ptr::eq(registry, collision.registry()) + { + return Err(invalid("survival inputs use different registries")); + } + for name in definitions + .rules + .keys() + .chain(definitions.ignition_odds.keys()) + .chain(definitions.fence_gates.iter()) + { + if registry.default_state(name).is_none() { + return Err(invalid("unknown block survival definition")); + } + } + let mut rules = Vec::with_capacity(registry.len()); + let mut tag_names = Vec::::new(); + let mut tag_indices = BTreeMap::::new(); + for id in 0..registry.len() { + let state = registry.state(BlockStateId(id as u32)).unwrap(); + let Some(rule) = definitions.rules.get(&state.name) else { + rules.push(None); + continue; + }; + let property = |name: &str| { + state + .properties + .get(name) + .map(String::as_str) + .ok_or_else(|| invalid("missing survival property")) + }; + let facing = || -> io::Result { + match property("facing")? { + "down" => Ok(Direction::Down), + "up" => Ok(Direction::Up), + "north" => Ok(Direction::North), + "south" => Ok(Direction::South), + "west" => Ok(Direction::West), + "east" => Ok(Direction::East), + _ => Err(invalid("invalid survival facing")), + } + }; + let boolean = |name: &str| -> io::Result { + match property(name)? { + "true" => Ok(true), + "false" => Ok(false), + _ => Err(invalid("invalid survival boolean")), + } + }; + let upper_half = || -> io::Result { + match property("half")? { + "upper" => Ok(true), + "lower" => Ok(false), + _ => Err(invalid("invalid survival half")), + } + }; + let full = |face| Rule::Support { + face, + kind: SupportType::Full, + center_restriction: false, + }; + let faces = || -> io::Result { + let mut mask = 0; + for direction in Direction::ALL { + if state.properties.contains_key(direction_name(direction)) + && boolean(direction_name(direction))? + { + mask |= 1 << direction as u8; + } + } + Ok(mask) + }; + rules.push(Some(match rule { + SurvivalRule::Fire => Rule::Fire, + SurvivalRule::Cactus => Rule::Cactus, + SurvivalRule::Path => Rule::Path, + SurvivalRule::Mushroom => Rule::Mushroom, + SurvivalRule::Multiface => Rule::Multiface(faces()?), + SurvivalRule::Vine => Rule::Vine(faces()?), + SurvivalRule::HangingMoss => Rule::HangingMoss, + SurvivalRule::SnowLayer => Rule::SnowLayer, + SurvivalRule::SeaPickle => Rule::SeaPickle, + SurvivalRule::Bell => { + let (face, kind, center_restriction) = match property("attachment")? { + "floor" => (Direction::Up, SupportType::Full, false), + "ceiling" => (Direction::Down, SupportType::Center, true), + "single_wall" | "double_wall" => { + (facing()?.opposite(), SupportType::Full, false) + } + _ => return Err(invalid("invalid bell attachment")), + }; + Rule::Support { + face, + kind, + center_restriction, + } + } + SurvivalRule::GrowingPlant => { + let (head, body, direction, kelp) = match state.name.as_str() { + "minecraft:kelp" | "minecraft:kelp_plant" => ( + "minecraft:kelp", + "minecraft:kelp_plant", + Direction::Up, + true, + ), + "minecraft:cave_vines" | "minecraft:cave_vines_plant" => ( + "minecraft:cave_vines", + "minecraft:cave_vines_plant", + Direction::Down, + false, + ), + "minecraft:twisting_vines" | "minecraft:twisting_vines_plant" => ( + "minecraft:twisting_vines", + "minecraft:twisting_vines_plant", + Direction::Up, + false, + ), + "minecraft:weeping_vines" | "minecraft:weeping_vines_plant" => ( + "minecraft:weeping_vines", + "minecraft:weeping_vines_plant", + Direction::Down, + false, + ), + _ => return Err(invalid("unknown growing plant family")), + }; + Rule::GrowingPlant { + head: registry + .default_state(head) + .ok_or_else(|| invalid("missing growing plant head"))?, + body: registry + .default_state(body) + .ok_or_else(|| invalid("missing growing plant body"))?, + direction, + kelp, + } + } + SurvivalRule::MangrovePropagule => Rule::MangrovePropagule(boolean("hanging")?), + SurvivalRule::Speleothem => { + Rule::Speleothem(match property("vertical_direction")? { + "up" => Direction::Up, + "down" => Direction::Down, + _ => return Err(invalid("invalid speleothem direction")), + }) + } + SurvivalRule::Scaffolding => Rule::Scaffolding, + SurvivalRule::PistonHead => Rule::PistonHead { + direction: facing()?, + sticky: match property("type")? { + "normal" => false, + "sticky" => true, + _ => return Err(invalid("invalid piston head type")), + }, + }, + SurvivalRule::ChorusPlant => Rule::ChorusPlant, + SurvivalRule::ChorusFlower => Rule::ChorusFlower, + SurvivalRule::PitcherCrop => Rule::PitcherCrop(upper_half()?), + SurvivalRule::SugarCane => Rule::SugarCane, + SurvivalRule::LilyPad => Rule::LilyPad, + SurvivalRule::Frogspawn => Rule::Frogspawn, + SurvivalRule::SporeBlossom => Rule::SporeBlossom, + SurvivalRule::SmallDripleaf => Rule::SmallDripleaf(upper_half()?), + SurvivalRule::TallSeagrass => Rule::TallSeagrass(upper_half()?), + SurvivalRule::BigDripleaf => Rule::BigDripleaf, + SurvivalRule::BigDripleafStem => Rule::BigDripleafStem, + SurvivalRule::Farmland => Rule::Farmland, + SurvivalRule::Cocoa => Rule::Cocoa(facing()?), + SurvivalRule::Crop => Rule::Crop, + SurvivalRule::DoublePlant => Rule::DoublePlant(upper_half()?), + SurvivalRule::Door => Rule::Door(upper_half()?), + SurvivalRule::TagBelow(name) => { + Rule::TagBelow(*tag_indices.entry(name.clone()).or_insert_with(|| { + let index = tag_names.len(); + tag_names.push(name.clone()); + index + })) + } + SurvivalRule::CactusFlower => Rule::CactusFlower, + SurvivalRule::Seagrass => Rule::Seagrass, + SurvivalRule::BubbleColumn => Rule::BubbleColumn, + SurvivalRule::RedstoneWire => Rule::RedstoneWire, + SurvivalRule::Always => Rule::Always, + SurvivalRule::SolidBelow => Rule::Solid(Direction::Down), + SurvivalRule::SolidBehind => Rule::Solid(facing()?.opposite()), + SurvivalRule::NonAirBelow => Rule::NonAirBelow, + SurvivalRule::MossCarpet => Rule::MossCarpet(boolean("bottom")?), + SurvivalRule::CenterBelow => Rule::Support { + face: Direction::Up, + kind: SupportType::Center, + center_restriction: true, + }, + SurvivalRule::Lantern => Rule::Support { + face: if boolean("hanging")? { + Direction::Down + } else { + Direction::Up + }, + kind: SupportType::Center, + center_restriction: true, + }, + SurvivalRule::FullAbove => full(Direction::Down), + SurvivalRule::FullBehind => full(facing()?), + SurvivalRule::RigidOrCenterBelow => Rule::RigidOrCenterBelow, + SurvivalRule::RigidBelow => Rule::Support { + face: Direction::Up, + kind: SupportType::Rigid, + center_restriction: false, + }, + SurvivalRule::FullBelow => full(Direction::Up), + SurvivalRule::CenterAbove => Rule::Support { + face: Direction::Down, + kind: SupportType::Center, + center_restriction: false, + }, + SurvivalRule::FaceAttached => full(match property("face")? { + "floor" => Direction::Up, + "ceiling" => Direction::Down, + "wall" => facing()?, + _ => return Err(invalid("invalid attachment face")), + }), + SurvivalRule::SupportsBamboo => Rule::SupportsBamboo, + })); + } + let tag_states = |name: &str| -> io::Result> { + let names = tags + .get(name) + .into_iter() + .flatten() + .collect::>(); + for name in &names { + if registry.default_state(name).is_none() { + return Err(invalid("unknown survival tag member")); + } + } + Ok((0..registry.len()) + .map(|i| BlockStateId(i as u32)) + .filter(|id| names.contains(®istry.state(*id).unwrap().name)) + .collect()) + }; + let fluid_tag = |name: &str| -> io::Result { + fluid_tags + .get(name) + .into_iter() + .flatten() + .try_fold(0, |mask, name| { + Ok(mask + | FluidKind::from_name(name) + .ok_or_else(|| invalid("unknown survival fluid tag member"))? + .mask()) + }) + }; + Ok(Self { + registry, + support, + collision, + solid: properties.bind(BlockProperty::Solid), + liquid: properties.bind(BlockProperty::Liquid), + solid_render: properties.bind(BlockProperty::SolidRender), + flammable: (0..registry.len()) + .map(|i| BlockStateId(i as u32)) + .filter(|id| { + let state = registry.state(*id).unwrap(); + definitions + .ignition_odds + .get(&state.name) + .is_some_and(|value| *value > 0) + && !state + .properties + .get("waterlogged") + .is_some_and(|value| value == "true") + }) + .collect(), + fence_gates: (0..registry.len()) + .map(|i| BlockStateId(i as u32)) + .filter(|id| { + definitions + .fence_gates + .contains(®istry.state(*id).unwrap().name) + }) + .collect(), + cactus_support: tag_states("minecraft:supports_cactus")?, + mushroom_light_override: tag_states("minecraft:overrides_mushroom_light_requirement")?, + rules, + unstable_bottom_center: tag_states("minecraft:unstable_bottom_center")?, + supports_bamboo: tag_states("minecraft:supports_bamboo")?, + bound_tags: tag_names + .iter() + .map(|name| tag_states(name)) + .collect::>()?, + cactus_flower: tag_states("minecraft:support_override_cactus_flower")?, + no_seagrass: tag_states("minecraft:cannot_support_seagrass")?, + vegetation: tag_states("minecraft:supports_vegetation")?, + dripleaf: tag_states("minecraft:supports_big_dripleaf")?, + maintains_farmland: tag_states("minecraft:maintains_farmland")?, + cocoa: tag_states("minecraft:supports_cocoa")?, + crops: tag_states("minecraft:supports_crops")?, + no_snow: tag_states("minecraft:cannot_support_snow_layer")?, + snow_override: tag_states("minecraft:support_override_snow_layer")?, + mangrove: tag_states("minecraft:supports_mangrove_propagule")?, + hanging_mangrove: tag_states("minecraft:supports_hanging_mangrove_propagule")?, + no_kelp: tag_states("minecraft:cannot_support_kelp")?, + chorus_plant: tag_states("minecraft:supports_chorus_plant")?, + chorus_flower: tag_states("minecraft:supports_chorus_flower")?, + lily_pad: tag_states("minecraft:supports_lily_pad")?, + frogspawn: tag_states("minecraft:supports_frogspawn")?, + small_dripleaf: tag_states("minecraft:supports_small_dripleaf")?, + sugar_cane: tag_states("minecraft:supports_sugar_cane")?, + sugar_cane_adjacent: tag_states("minecraft:supports_sugar_cane_adjacently")?, + fluid_tags: [ + fluid_tag("minecraft:water")?, + fluid_tag("minecraft:supports_lily_pad")?, + fluid_tag("minecraft:supports_frogspawn")?, + fluid_tag("minecraft:supports_sugar_cane_adjacently")?, + fluid_tag("minecraft:lava")?, + ], + bubble_up: tag_states("minecraft:enables_bubble_column_push_up")?, + bubble_down: tag_states("minecraft:enables_bubble_column_drag_down")?, + }) + } + pub fn supported_states(&self) -> usize { + self.rules.iter().filter(|r| r.is_some()).count() + } + pub fn supports_state(&self, state: BlockStateId) -> bool { + self.rules + .get(state.0 as usize) + .is_some_and(Option::is_some) + } + fn read( + &self, + world: &mut W, + position: [i32; 3], + ) -> Result> { + let state = world.block_state(position).map_err(SurvivalError::World)?; + if self.registry.state(state).is_none() { + return Err(SurvivalError::Registry(invalid( + "world survival state outside registry", + ))); + } + Ok(state) + } + fn support( + &self, + world: &mut W, + position: [i32; 3], + face: Direction, + kind: SupportType, + center_restriction: bool, + ) -> Result> { + let state = self.read(world, position)?; + if center_restriction + && face == Direction::Down + && self.unstable_bottom_center.contains(&state) + { + return Ok(false); + } + self.support + .is_face_sturdy(world, state, position, face, kind) + .map_err(SurvivalError::Support) + } + fn is_air(&self, state: BlockStateId) -> bool { + matches!( + self.registry.state(state).unwrap().name.as_str(), + "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air" + ) + } + fn face_property(&self, state: BlockStateId, direction: Direction) -> bool { + self.registry + .state(state) + .unwrap() + .properties + .get(direction_name(direction)) + .is_some_and(|value| value == "true") + } + fn can_attach( + &self, + world: &mut W, + neighbor: BlockStateId, + at: [i32; 3], + direction: Direction, + ) -> Result> { + let face = direction.opposite(); + if self + .support + .is_face_sturdy(world, neighbor, at, face, SupportType::Full) + .map_err(SurvivalError::Support)? + { + return Ok(true); + } + let shape = self + .collision + .collision_shape(world, neighbor, at) + .map_err(SurvivalError::Collision)?; + SupportType::Full + .is_supporting(&shape, face) + .map_err(|error| SurvivalError::Registry(invalid(error.to_string()))) + } + fn is_named(&self, state: BlockStateId, name: &str) -> bool { + self.registry.state(state).unwrap().name == name + } + fn same_block(&self, first: BlockStateId, second: BlockStateId) -> bool { + self.registry.state(first).unwrap().name == self.registry.state(second).unwrap().name + } + fn scaffold_distance(&self, state: BlockStateId) -> io::Result> { + if !self.is_named(state, "minecraft:scaffolding") { + return Ok(None); + } + self.registry + .state(state) + .unwrap() + .properties + .get("distance") + .and_then(|v| v.parse::().ok()) + .filter(|v| (0..=7).contains(v)) + .map(Some) + .ok_or_else(|| invalid("invalid scaffolding distance")) + } + fn is_lower_half(&self, below: BlockStateId, candidate: BlockStateId) -> bool { + let neighbor = self.registry.state(below).unwrap(); + neighbor.name == self.registry.state(candidate).unwrap().name + && neighbor + .properties + .get("half") + .is_some_and(|v| v == "lower") + } + fn fluid_matches(&self, tag: usize, fluid: FluidState) -> bool { + self.fluid_tags[tag] & fluid.kind().mask() != 0 + } + pub fn can_survive( + &self, + world: &mut W, + state: BlockStateId, + position: [i32; 3], + ) -> Result> { + let rule = self + .rules + .get(state.0 as usize) + .ok_or_else(|| SurvivalError::Registry(invalid("survival candidate outside registry")))? + .ok_or(SurvivalError::Unsupported(state))?; + match rule { + Rule::Fire => { + let below = relative(position, Direction::Down); + let neighbor = self.read(world, below)?; + if self + .support + .is_face_sturdy(world, neighbor, below, Direction::Up, SupportType::Full) + .map_err(SurvivalError::Support)? + { + return Ok(true); + } + for direction in Direction::ALL { + let neighbor = self.read(world, relative(position, direction))?; + if self.flammable.contains(&neighbor) { + return Ok(true); + } + } + Ok(false) + } + Rule::Cactus => { + for direction in [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ] { + let at = relative(position, direction); + let neighbor = self.read(world, at)?; + if self.solid.contains(neighbor) + || self + .fluid_matches(4, world.fluid_state(at).map_err(SurvivalError::World)?) + { + return Ok(false); + } + } + let neighbor = self.read(world, relative(position, Direction::Down))?; + if !self.same_block(neighbor, state) && !self.cactus_support.contains(&neighbor) { + return Ok(false); + } + let above = self.read(world, relative(position, Direction::Up))?; + Ok(!self.liquid.contains(above)) + } + Rule::Path => { + let above = self.read(world, relative(position, Direction::Up))?; + Ok(!self.solid.contains(above) || self.fence_gates.contains(&above)) + } + Rule::Mushroom => { + let below = self.read(world, relative(position, Direction::Down))?; + if self.mushroom_light_override.contains(&below) { + return Ok(true); + } + Ok(world + .raw_brightness(position, 0) + .map_err(SurvivalError::World)? + < 13 + && self.solid_render.contains(below)) + } + Rule::Multiface(faces) => { + for direction in Direction::ALL { + if faces & (1 << direction as u8) != 0 { + let at = relative(position, direction); + let neighbor = self.read(world, at)?; + if !self.can_attach(world, neighbor, at, direction)? { + return Ok(false); + } + } + } + Ok(faces != 0) + } + Rule::HangingMoss => { + let at = relative(position, Direction::Up); + let neighbor = self.read(world, at)?; + Ok(self.can_attach(world, neighbor, at, Direction::Up)? + || self.same_block(neighbor, state)) + } + Rule::Vine(faces) => { + let above = relative(position, Direction::Up); + let mut any = false; + let mut cached_above = None; + if faces & (1 << Direction::Up as u8) != 0 { + let neighbor = self.read(world, above)?; + // getUpdatedState passes DOWN here, unlike canSupportAtFace. + any = self.can_attach(world, neighbor, above, Direction::Down)?; + } + for direction in [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ] { + if faces & (1 << direction as u8) == 0 { + continue; + } + let at = relative(position, direction); + let neighbor = self.read(world, at)?; + let mut valid = self.can_attach(world, neighbor, at, direction)?; + if !valid { + let neighbor = self.read(world, above)?; + valid = self.same_block(neighbor, state) + && self.face_property(neighbor, direction); + } + if !valid { + let neighbor = match cached_above { + Some(neighbor) => neighbor, + None => { + let neighbor = self.read(world, above)?; + cached_above = Some(neighbor); + neighbor + } + }; + valid = self.same_block(neighbor, state) + && self.face_property(neighbor, direction); + } + any |= valid; + } + Ok(any) + } + Rule::SnowLayer => { + let at = relative(position, Direction::Down); + let neighbor = self.read(world, at)?; + if self.no_snow.contains(&neighbor) { + return Ok(false); + } + if self.snow_override.contains(&neighbor) { + return Ok(true); + } + let shape = self + .collision + .collision_shape(world, neighbor, at) + .map_err(SurvivalError::Collision)?; + Ok(SupportType::Full + .is_supporting(&shape, Direction::Up) + .map_err(|error| SurvivalError::Registry(invalid(error.to_string())))? + || (self.same_block(neighbor, state) + && self + .registry + .state(neighbor) + .unwrap() + .properties + .get("layers") + .is_some_and(|value| value == "8"))) + } + Rule::SeaPickle => { + let at = relative(position, Direction::Down); + let neighbor = self.read(world, at)?; + let shape = self + .collision + .collision_shape(world, neighbor, at) + .map_err(SurvivalError::Collision)?; + Ok(!shape + .face_shape(Direction::Up) + .map_err(|error| SurvivalError::Registry(invalid(error.to_string())))? + .is_empty() + || self + .support + .is_face_sturdy(world, neighbor, at, Direction::Up, SupportType::Full) + .map_err(SurvivalError::Support)?) + } + Rule::GrowingPlant { + head, + body, + direction, + kelp, + } => { + let at = relative(position, direction.opposite()); + let neighbor = self.read(world, at)?; + if kelp && self.no_kelp.contains(&neighbor) { + return Ok(false); + } + Ok(self.same_block(neighbor, head) + || self.same_block(neighbor, body) + || self + .support + .is_face_sturdy(world, neighbor, at, direction, SupportType::Full) + .map_err(SurvivalError::Support)?) + } + Rule::MangrovePropagule(hanging) => { + let neighbor = self.read( + world, + relative( + position, + if hanging { + Direction::Up + } else { + Direction::Down + }, + ), + )?; + Ok(if hanging { + self.hanging_mangrove.contains(&neighbor) + } else { + self.mangrove.contains(&neighbor) + }) + } + Rule::Speleothem(direction) => { + let at = relative(position, direction.opposite()); + let neighbor = self.read(world, at)?; + Ok(self + .support + .is_face_sturdy(world, neighbor, at, direction, SupportType::Full) + .map_err(SurvivalError::Support)? + || (self.same_block(neighbor, state) + && self + .registry + .state(neighbor) + .unwrap() + .properties + .get("vertical_direction") + == self + .registry + .state(state) + .unwrap() + .properties + .get("vertical_direction"))) + } + Rule::Scaffolding => { + let below = relative(position, Direction::Down); + let neighbor = self.read(world, below)?; + let mut distance = if let Some(distance) = self + .scaffold_distance(neighbor) + .map_err(SurvivalError::Registry)? + { + distance + } else { + if self + .support + .is_face_sturdy(world, neighbor, below, Direction::Up, SupportType::Full) + .map_err(SurvivalError::Support)? + { + return Ok(true); + } + 7 + }; + for direction in [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ] { + let neighbor = self.read(world, relative(position, direction))?; + if let Some(adjacent) = self + .scaffold_distance(neighbor) + .map_err(SurvivalError::Registry)? + { + distance = distance.min(adjacent + 1); + if distance == 1 { + break; + } + } + } + Ok(distance < 7) + } + Rule::PistonHead { direction, sticky } => { + let neighbor = self.read(world, relative(position, direction.opposite()))?; + let definition = self.registry.state(neighbor).unwrap(); + let base = if sticky { + "minecraft:sticky_piston" + } else { + "minecraft:piston" + }; + Ok(((definition.name == base + && definition + .properties + .get("extended") + .is_some_and(|v| v == "true")) + || definition.name == "minecraft:moving_piston") + && definition.properties.get("facing") + == self.registry.state(state).unwrap().properties.get("facing")) + } + Rule::ChorusPlant => { + let below = self.read(world, relative(position, Direction::Down))?; + let above = self.read(world, relative(position, Direction::Up))?; + let crowded = !self.is_air(above) && !self.is_air(below); + for direction in [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ] { + let at = relative(position, direction); + let neighbor = self.read(world, at)?; + if self.same_block(neighbor, state) { + if crowded { + return Ok(false); + } + let support = self.read(world, relative(at, Direction::Down))?; + if self.same_block(support, state) || self.chorus_plant.contains(&support) { + return Ok(true); + } + } + } + Ok(self.same_block(below, state) || self.chorus_plant.contains(&below)) + } + Rule::ChorusFlower => { + let below = self.read(world, relative(position, Direction::Down))?; + if self.is_named(below, "minecraft:chorus_plant") + || self.chorus_flower.contains(&below) + { + return Ok(true); + } + if !self.is_air(below) { + return Ok(false); + } + let mut found = false; + for direction in [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ] { + let neighbor = self.read(world, relative(position, direction))?; + if self.is_named(neighbor, "minecraft:chorus_plant") { + if found { + return Ok(false); + } + found = true; + } else if !self.is_air(neighbor) { + return Ok(false); + } + } + Ok(found) + } + Rule::PitcherCrop(upper) => { + if !upper + && world + .raw_brightness(position, 0) + .map_err(SurvivalError::World)? + < 8 + { + return Ok(false); + } + let below = self.read(world, relative(position, Direction::Down))?; + Ok(if upper { + self.is_lower_half(below, state) + } else { + self.crops.contains(&below) + }) + } + Rule::SugarCane => { + let below = relative(position, Direction::Down); + let neighbor = self.read(world, below)?; + if self.registry.state(neighbor).unwrap().name + == self.registry.state(state).unwrap().name + { + return Ok(true); + } + if !self.sugar_cane.contains(&neighbor) { + return Ok(false); + } + for direction in [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ] { + let at = relative(below, direction); + let adjacent = self.read(world, at)?; + let fluid = world.fluid_state(at).map_err(SurvivalError::World)?; + if self.fluid_matches(3, fluid) || self.sugar_cane_adjacent.contains(&adjacent) + { + return Ok(true); + } + } + Ok(false) + } + Rule::LilyPad => { + let below = relative(position, Direction::Down); + let neighbor = self.read(world, below)?; + let fluid_below = world.fluid_state(below).map_err(SurvivalError::World)?; + let fluid_here = world.fluid_state(position).map_err(SurvivalError::World)?; + Ok( + (self.fluid_matches(1, fluid_below) || self.lily_pad.contains(&neighbor)) + && fluid_here.kind() == FluidKind::Empty, + ) + } + Rule::Frogspawn => { + let below = relative(position, Direction::Down); + let fluid_below = world.fluid_state(below).map_err(SurvivalError::World)?; + let fluid_here = world.fluid_state(position).map_err(SurvivalError::World)?; + Ok((self.fluid_matches(2, fluid_below) + || self.frogspawn.contains(&self.read(world, below)?)) + && fluid_here.kind() == FluidKind::Empty) + } + Rule::SporeBlossom => Ok(self.support( + world, + relative(position, Direction::Up), + Direction::Down, + SupportType::Center, + true, + )? && !self.fluid_matches( + 0, + world.fluid_state(position).map_err(SurvivalError::World)?, + )), + Rule::SmallDripleaf(upper) => { + let neighbor = self.read(world, relative(position, Direction::Down))?; + if upper { + return Ok(self.is_lower_half(neighbor, state)); + } + Ok(self.small_dripleaf.contains(&neighbor) + || (world + .fluid_state(position) + .map_err(SurvivalError::World)? + .kind() + == FluidKind::Water + && self.vegetation.contains(&neighbor))) + } + Rule::TallSeagrass(upper) => { + let below = relative(position, Direction::Down); + if upper { + return Ok(self.is_lower_half(self.read(world, below)?, state)); + } + let fluid = world.fluid_state(position).map_err(SurvivalError::World)?; + let neighbor = self.read(world, below)?; + Ok(self + .support + .is_face_sturdy(world, neighbor, below, Direction::Up, SupportType::Full) + .map_err(SurvivalError::Support)? + && !self.no_seagrass.contains(&neighbor) + && self.fluid_matches(0, fluid) + && fluid.is_full()) + } + Rule::BigDripleaf => { + let below = self.read(world, relative(position, Direction::Down))?; + Ok(matches!( + self.registry.state(below).unwrap().name.as_str(), + "minecraft:big_dripleaf" | "minecraft:big_dripleaf_stem" + ) || self.dripleaf.contains(&below)) + } + Rule::BigDripleafStem => { + let below = self.read(world, relative(position, Direction::Down))?; + let above = self.read(world, relative(position, Direction::Up))?; + Ok( + (self.registry.state(below).unwrap().name == "minecraft:big_dripleaf_stem" + || self.dripleaf.contains(&below)) + && matches!( + self.registry.state(above).unwrap().name.as_str(), + "minecraft:big_dripleaf" | "minecraft:big_dripleaf_stem" + ), + ) + } + Rule::Farmland => { + let above = relative(position, Direction::Up); + Ok(!self.solid.contains(self.read(world, above)?) + || self.maintains_farmland.contains(&self.read(world, above)?)) + } + Rule::Cocoa(direction) => Ok(self + .cocoa + .contains(&self.read(world, relative(position, direction))?)), + Rule::Crop => Ok(world + .raw_brightness(position, 0) + .map_err(SurvivalError::World)? + >= 8 + && self + .crops + .contains(&self.read(world, relative(position, Direction::Down))?)), + Rule::DoublePlant(upper) => { + let below = self.read(world, relative(position, Direction::Down))?; + if !upper { + return Ok(self.vegetation.contains(&below)); + } + let neighbor = self.registry.state(below).unwrap(); + Ok(neighbor.name == self.registry.state(state).unwrap().name + && neighbor + .properties + .get("half") + .is_some_and(|v| v == "lower")) + } + Rule::Door(upper) => { + let below = relative(position, Direction::Down); + let neighbor = self.read(world, below)?; + if upper { + return Ok(self.registry.state(neighbor).unwrap().name + == self.registry.state(state).unwrap().name); + } + self.support + .is_face_sturdy(world, neighbor, below, Direction::Up, SupportType::Full) + .map_err(SurvivalError::Support) + } + Rule::TagBelow(index) => Ok(self.bound_tags[index] + .contains(&self.read(world, relative(position, Direction::Down))?)), + Rule::CactusFlower => { + let below = relative(position, Direction::Down); + self.read(world, below)?; + let neighbor = self.read(world, below)?; + Ok(self.cactus_flower.contains(&neighbor) + || self + .support + .is_face_sturdy(world, neighbor, below, Direction::Up, SupportType::Center) + .map_err(SurvivalError::Support)?) + } + Rule::Seagrass => { + let below = relative(position, Direction::Down); + let neighbor = self.read(world, below)?; + Ok(self + .support + .is_face_sturdy(world, neighbor, below, Direction::Up, SupportType::Full) + .map_err(SurvivalError::Support)? + && !self.no_seagrass.contains(&neighbor)) + } + Rule::BubbleColumn => { + let below = self.read(world, relative(position, Direction::Down))?; + Ok(self.registry.state(below).unwrap().name + == self.registry.state(state).unwrap().name + || self.bubble_up.contains(&below) + || self.bubble_down.contains(&below)) + } + Rule::RedstoneWire => { + let below = relative(position, Direction::Down); + let neighbor = self.read(world, below)?; + Ok(self + .support + .is_face_sturdy(world, neighbor, below, Direction::Up, SupportType::Full) + .map_err(SurvivalError::Support)? + || self.registry.state(neighbor).unwrap().name == "minecraft:hopper") + } + Rule::Always => Ok(true), + Rule::Solid(direction) => Ok(self + .solid + .contains(self.read(world, relative(position, direction))?)), + Rule::NonAirBelow => { + Ok(!self.is_air(self.read(world, relative(position, Direction::Down))?)) + } + Rule::MossCarpet(base) => { + let below = self.read(world, relative(position, Direction::Down))?; + if base { + return Ok(!self.is_air(below)); + } + let below = self.registry.state(below).unwrap(); + Ok(below.name == self.registry.state(state).unwrap().name + && below.properties.get("bottom").is_some_and(|v| v == "true")) + } + Rule::Support { + face, + kind, + center_restriction, + } => self.support( + world, + relative(position, face.opposite()), + face, + kind, + center_restriction, + ), + Rule::RigidOrCenterBelow => { + let below = relative(position, Direction::Down); + Ok( + self.support(world, below, Direction::Up, SupportType::Rigid, false)? + || self.support(world, below, Direction::Up, SupportType::Center, true)?, + ) + } + Rule::SupportsBamboo => Ok(self + .supports_bamboo + .contains(&self.read(world, relative(position, Direction::Down))?)), + } + } +} +fn relative(position: [i32; 3], direction: Direction) -> [i32; 3] { + let normal = direction.normal(); + std::array::from_fn(|i| position[i].wrapping_add(normal[i])) +} + +fn direction_name(direction: Direction) -> &'static str { + match direction { + Direction::Down => "down", + Direction::Up => "up", + Direction::North => "north", + Direction::South => "south", + Direction::West => "west", + Direction::East => "east", + } +} diff --git a/crates/horizon-world/src/chunk.rs b/crates/horizon-world/src/chunk.rs new file mode 100644 index 000000000..600113b32 --- /dev/null +++ b/crates/horizon-world/src/chunk.rs @@ -0,0 +1,556 @@ +//! Saved section palettes and storage-level chunk access. Changes here do not +//! run block behavior, lighting, heightmaps, neighbor updates or scheduled ticks. +use crate::{ + DATA_VERSION, + compression::invalid, + nbt::{Compound, JavaString, NamedTag, Tag}, + registry::{BlockRegistry, BlockStateId}, + tick_data::{self, TickKind}, +}; +use horizon_core::{ + position::{BlockPos, ChunkPos}, + storage::PackedStorage, + ticks::{ChunkTicks, SavedTick, TickTypeId}, +}; +use std::{collections::BTreeMap, io}; + +fn key(value: &str) -> JavaString { + JavaString::from(value) +} +fn bits_for_palette(len: usize, min: u8) -> u8 { + if len <= 1 { + 0 + } else { + ((usize::BITS - (len - 1).leading_zeros()) as u8).max(min) + } +} + +#[derive(Clone, Debug)] +pub struct PalettedContainer { + palette: Vec, + storage: Option, + entries: usize, + min_bits: u8, + extra: Compound, +} +impl PalettedContainer { + pub fn uniform(value: Tag, entries: usize, min_bits: u8) -> io::Result { + if entries == 0 || !(1..=32).contains(&min_bits) { + return Err(invalid("invalid palette dimensions")); + } + if matches!(value, Tag::End) { + return Err(invalid("End cannot be a palette entry")); + } + Ok(Self { + palette: vec![value], + storage: None, + entries, + min_bits, + extra: Compound::new(), + }) + } + + pub fn from_nbt(tag: &Tag, entries: usize, min_bits: u8) -> io::Result { + let Tag::Compound(map) = tag else { + return Err(invalid("palette container is not a compound")); + }; + let Some(Tag::List(palette)) = map.get(&key("palette")) else { + return Err(invalid("missing palette list")); + }; + let first = palette.first().ok_or_else(|| invalid("empty palette"))?; + let mut result = Self::uniform(first.clone(), entries, min_bits)?; + if palette.len() > i32::MAX as usize || palette.iter().any(|t| matches!(t, Tag::End)) { + return Err(invalid("invalid palette")); + } + result.palette = palette.clone(); + let bits = bits_for_palette(palette.len(), min_bits); + if bits > 0 { + let Some(Tag::LongArray(words)) = map.get(&key("data")) else { + return Err(invalid("nonuniform palette is missing data")); + }; + let storage = + PackedStorage::from_words(bits, entries, words.iter().map(|&w| w as u64).collect()) + .map_err(|e| invalid(e.to_string()))?; + for index in 0..entries { + if storage.get(index).unwrap() as usize >= palette.len() { + return Err(invalid("palette index outside palette")); + } + } + result.storage = Some(storage); + } + result.extra = map.clone(); + result.extra.remove(&key("palette")); + result.extra.remove(&key("data")); + Ok(result) + } + + pub fn bits(&self) -> u8 { + self.storage.as_ref().map_or(0, PackedStorage::bits) + } + pub fn palette_len(&self) -> usize { + self.palette.len() + } + pub fn get(&self, index: usize) -> io::Result<&Tag> { + if index >= self.entries { + return Err(invalid("section index out of bounds")); + } + let palette_index = self.storage.as_ref().map_or(0, |s| s.get(index).unwrap()) as usize; + Ok(&self.palette[palette_index]) + } + + pub fn set(&mut self, index: usize, value: Tag) -> io::Result { + let old = self.get(index)?.clone(); + if matches!(value, Tag::End) { + return Err(invalid("End cannot be a palette entry")); + } + let id = if let Some(id) = self.palette.iter().position(|v| *v == value) { + id + } else { + if self.palette.len() >= i32::MAX as usize { + return Err(invalid("palette too large")); + } + let next_bits = bits_for_palette(self.palette.len() + 1, self.min_bits); + if next_bits != self.bits() { + let mut next = PackedStorage::new(next_bits, self.entries) + .map_err(|e| invalid(e.to_string()))?; + if let Some(previous) = &self.storage { + for i in 0..self.entries { + next.set(i, previous.get(i).unwrap()).unwrap(); + } + } + self.storage = Some(next); + } + self.palette.push(value); + self.palette.len() - 1 + }; + if let Some(storage) = &mut self.storage { + storage + .set(index, id as u32) + .map_err(|e| invalid(e.to_string()))?; + } + Ok(old) + } + + /// Rebuild a minimal palette in first-use order, preserving every entry. + pub fn compact(&mut self) -> io::Result<()> { + let values = (0..self.entries) + .map(|i| self.get(i).cloned()) + .collect::>>()?; + let mut compact = Self::uniform(values[0].clone(), self.entries, self.min_bits)?; + for (i, value) in values.into_iter().enumerate() { + compact.set(i, value)?; + } + compact.extra = std::mem::take(&mut self.extra); + *self = compact; + Ok(()) + } + + pub fn to_nbt(&self) -> Tag { + let mut map = self.extra.clone(); + map.insert(key("palette"), Tag::List(self.palette.clone())); + if let Some(storage) = &self.storage { + map.insert( + key("data"), + Tag::LongArray(storage.words().iter().map(|&v| v as i64).collect()), + ); + } + Tag::Compound(map) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct BlockState { + pub name: String, + pub properties: BTreeMap, +} +impl BlockState { + pub fn to_nbt(&self) -> Tag { + let mut map = Compound::new(); + map.insert(key("id"), Tag::String(key(&self.name))); + if !self.properties.is_empty() { + map.insert( + key("properties"), + Tag::Compound( + self.properties + .iter() + .map(|(k, v)| (key(k), Tag::String(key(v)))) + .collect(), + ), + ); + } + Tag::Compound(map) + } + pub fn from_nbt(tag: &Tag) -> io::Result { + if let Tag::String(name) = tag { + return Ok(Self { + name: name.to_string().map_err(|e| invalid(e.to_string()))?, + properties: BTreeMap::new(), + }); + } + let Some(Tag::String(name)) = tag.get("id") else { + return Err(invalid("block state is missing id")); + }; + let mut properties = BTreeMap::new(); + if let Some(tag) = tag.get("properties") { + let Tag::Compound(map) = tag else { + return Err(invalid("block properties are not a compound")); + }; + for (k, v) in map { + let Tag::String(v) = v else { + return Err(invalid("block property is not a string")); + }; + properties.insert( + k.to_string().map_err(|e| invalid(e.to_string()))?, + v.to_string().map_err(|e| invalid(e.to_string()))?, + ); + } + } + Ok(Self { + name: name.to_string().map_err(|e| invalid(e.to_string()))?, + properties, + }) + } +} + +#[derive(Clone, Debug)] +pub struct ChunkData { + root: NamedTag, + position: ChunkPos, +} +impl ChunkData { + pub fn new(root: NamedTag) -> io::Result { + let Some(Tag::Int(x)) = root.tag.get("xPos") else { + return Err(invalid("chunk is missing xPos")); + }; + let Some(Tag::Int(z)) = root.tag.get("zPos") else { + return Err(invalid("chunk is missing zPos")); + }; + let position = ChunkPos::new(*x, *z); + let Some(Tag::Int(version)) = root.tag.get("DataVersion") else { + return Err(invalid("chunk is missing DataVersion")); + }; + if *version != DATA_VERSION { + return Err(invalid(format!( + "expected DataVersion {DATA_VERSION}, got {version}; data fixing is not implemented" + ))); + } + let Some(Tag::List(sections)) = root.tag.get("sections") else { + return Err(invalid("chunk is missing sections")); + }; + let mut seen = std::collections::BTreeSet::new(); + for section in sections { + let Some(Tag::Byte(y)) = section.get("Y") else { + return Err(invalid("section is missing byte Y")); + }; + if !seen.insert(*y) { + return Err(invalid("duplicate section Y")); + } + } + Ok(Self { root, position }) + } + pub fn position(&self) -> ChunkPos { + self.position + } + pub fn into_nbt(self) -> NamedTag { + self.root + } + pub fn root(&self) -> &NamedTag { + &self.root + } + + pub fn saved_ticks( + &self, + kind: TickKind, + resolve: impl FnMut(&str) -> Option, + ) -> io::Result { + let Some(tag) = self.root.tag.get(kind.field()) else { + return Ok(ChunkTicks::default()); + }; + let mut ticks = tick_data::read_list(tag, resolve)?; + ticks.retain(|tick| tick.pos.chunk() == self.position); + Ok(ChunkTicks::from_saved(ticks)) + } + + pub fn set_saved_ticks( + &mut self, + kind: TickKind, + ticks: &[SavedTick], + name: impl FnMut(TickTypeId) -> Option, + ) -> io::Result<()> { + if ticks.iter().any(|tick| tick.pos.chunk() != self.position) { + return Err(invalid("saved tick is outside this chunk")); + } + let tag = tick_data::write_list(ticks, name)?; + let Tag::Compound(map) = &mut self.root.tag else { + unreachable!() + }; + map.insert(key(kind.field()), tag); + Ok(()) + } + + fn section_index(&self, block: BlockPos) -> io::Result> { + if block.chunk() != self.position { + return Err(invalid("block is outside this chunk")); + } + let section_y = i8::try_from(block.y >> 4) + .map_err(|_| invalid("block height outside saved section range"))?; + let Tag::List(sections) = self.root.tag.get("sections").unwrap() else { + unreachable!() + }; + Ok(sections + .iter() + .position(|s| s.get("Y") == Some(&Tag::Byte(section_y)))) + } + + pub fn block(&self, block: BlockPos) -> io::Result> { + let Some(index) = self.section_index(block)? else { + return Ok(None); + }; + let Tag::List(sections) = self.root.tag.get("sections").unwrap() else { + unreachable!() + }; + let Some(container) = sections[index].get("block_states") else { + return Ok(None); + }; + let palette = PalettedContainer::from_nbt(container, 4096, 4)?; + Ok(Some(BlockState::from_nbt( + palette.get(block.section_index())?, + )?)) + } + + pub fn load_block_section<'r>( + &self, + block: BlockPos, + registry: &'r BlockRegistry, + ) -> io::Result>> { + let Some(index) = self.section_index(block)? else { + return Ok(None); + }; + let Tag::List(sections) = self.root.tag.get("sections").unwrap() else { + unreachable!() + }; + sections[index] + .get("block_states") + .map(|tag| BlockSection::from_nbt(tag, registry)) + .transpose() + } + + /// Storage-only mutation. The caller must arrange simulation-derived updates + /// before treating this as a gameplay block placement. + pub fn set_block_data(&mut self, block: BlockPos, state: BlockState) -> io::Result { + let index = self + .section_index(block)? + .ok_or_else(|| invalid("section is not present"))?; + let Tag::List(sections) = self.root.tag.get_mut("sections").unwrap() else { + unreachable!() + }; + let container = sections[index] + .get_mut("block_states") + .ok_or_else(|| invalid("section has no block-state data"))?; + let mut palette = PalettedContainer::from_nbt(container, 4096, 4)?; + let old = BlockState::from_nbt(palette.get(block.section_index())?)?; + palette.set(block.section_index(), state.to_nbt())?; + *container = palette.to_nbt(); + Ok(old) + } +} + +/// Resident section: 4,096 blocks stored as numeric palette entries. Uniform +/// sections have no word array; property strings live in the shared registry. +pub struct BlockSection<'r> { + palette: Vec, + local_ids: std::collections::HashMap, + counts: Vec, + free: Vec, + storage: Option, + registry: &'r BlockRegistry, + extra: Compound, +} +impl<'r> BlockSection<'r> { + pub fn registry(&self) -> &'r BlockRegistry { + self.registry + } + pub fn uniform(state: BlockStateId, registry: &'r BlockRegistry) -> io::Result { + if registry.state(state).is_none() { + return Err(invalid("state ID outside registry")); + } + Ok(Self { + palette: vec![state], + local_ids: [(state, 0)].into(), + counts: vec![4096], + free: Vec::new(), + storage: None, + registry, + extra: Compound::new(), + }) + } + pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result { + let container = PalettedContainer::from_nbt(tag, 4096, 4)?; + let resolved = container + .palette + .iter() + .map(|tag| registry.resolve(&BlockState::from_nbt(tag)?)) + .collect::>>()?; + let first_index = container.storage.as_ref().map_or(0, |s| s.get(0).unwrap()) as usize; + let mut section = Self::uniform(resolved[first_index], registry)?; + for index in 0..4096 { + let id = container + .storage + .as_ref() + .map_or(0, |s| s.get(index).unwrap()) as usize; + section.set(index, resolved[id])?; + } + section.extra = container.extra; + Ok(section) + } + pub fn bits(&self) -> u8 { + self.storage.as_ref().map_or(0, PackedStorage::bits) + } + pub fn get(&self, index: usize) -> io::Result { + if index >= 4096 { + return Err(invalid("section index out of bounds")); + } + let id = self.storage.as_ref().map_or(0, |s| s.get(index).unwrap()); + Ok(self.palette[id as usize]) + } + pub fn set(&mut self, index: usize, state: BlockStateId) -> io::Result { + let old = self.get(index)?; + if state.0 as usize >= self.registry.len() { + return Err(invalid("state ID outside registry")); + } + if old == state { + return Ok(old); + } + let old_id = self.local_ids[&old]; + if self.counts[old_id as usize] == 1 && !self.local_ids.contains_key(&state) { + // Replacing the last occurrence can reuse its slot without repacking. + self.palette[old_id as usize] = state; + self.local_ids.remove(&old); + self.local_ids.insert(state, old_id); + return Ok(old); + } + let id = if let Some(id) = self.local_ids.get(&state) { + *id + } else if let Some(id) = self.free.pop() { + self.palette[id as usize] = state; + self.local_ids.insert(state, id); + id + } else { + let id = self.palette.len() as u32; + let next_bits = bits_for_palette(self.palette.len() + 1, 4); + if next_bits != self.bits() { + let mut storage = + PackedStorage::new(next_bits, 4096).map_err(|e| invalid(e.to_string()))?; + if let Some(old) = &self.storage { + for i in 0..4096 { + storage.set(i, old.get(i).unwrap()).unwrap(); + } + } + self.storage = Some(storage); + } + self.palette.push(state); + self.counts.push(0); + self.local_ids.insert(state, id); + id + }; + self.storage + .as_mut() + .unwrap() + .set(index, id) + .map_err(|e| invalid(e.to_string()))?; + self.counts[old_id as usize] -= 1; + self.counts[id as usize] += 1; + if self.counts[old_id as usize] == 0 { + self.local_ids.remove(&old); + self.free.push(old_id); + } + if self.counts[id as usize] == 4096 { + self.palette = vec![state]; + self.local_ids = [(state, 0)].into(); + self.counts = vec![4096]; + self.free.clear(); + self.storage = None; + } + Ok(old) + } + pub fn compact(&mut self) -> io::Result<()> { + let values: Vec<_> = (0..4096).map(|i| self.get(i).unwrap()).collect(); + self.palette.clear(); + self.local_ids.clear(); + self.counts.clear(); + self.free.clear(); + for state in &values { + if !self.local_ids.contains_key(state) { + self.local_ids.insert(*state, self.palette.len() as u32); + self.palette.push(*state); + self.counts.push(0); + } + self.counts[self.local_ids[state] as usize] += 1; + } + let bits = bits_for_palette(self.palette.len(), 4); + self.storage = if bits == 0 { + None + } else { + let mut storage = PackedStorage::new(bits, 4096).map_err(|e| invalid(e.to_string()))?; + for (i, state) in values.iter().enumerate() { + storage.set(i, self.local_ids[state]).unwrap(); + } + Some(storage) + }; + Ok(()) + } + pub fn to_nbt(&self) -> io::Result { + let mut map = self.extra.clone(); + let palette = self + .palette + .iter() + .map(|id| { + self.registry + .state(*id) + .map(BlockState::to_nbt) + .ok_or_else(|| invalid("state ID outside registry")) + }) + .collect::>>()?; + map.insert(key("palette"), Tag::List(palette)); + if let Some(storage) = &self.storage { + map.insert( + key("data"), + Tag::LongArray(storage.words().iter().map(|&w| w as i64).collect()), + ); + } + Ok(Tag::Compound(map)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn palette_grows_across_word_widths_and_compacts_to_uniform() { + let mut palette = PalettedContainer::uniform(Tag::Int(0), 4096, 4).unwrap(); + for i in 0..4096 { + palette.set(i, Tag::Int(i as i32)).unwrap(); + } + assert_eq!(palette.bits(), 12); + let mut loaded = PalettedContainer::from_nbt(&palette.to_nbt(), 4096, 4).unwrap(); + for i in 0..4096 { + assert_eq!(loaded.get(i).unwrap(), &Tag::Int(i as i32)); + loaded.set(i, Tag::Int(7)).unwrap(); + } + loaded.compact().unwrap(); + assert_eq!(loaded.bits(), 0); + assert_eq!(loaded.palette_len(), 1); + assert!(loaded.to_nbt().get("data").is_none()); + assert_eq!(loaded.get(4095).unwrap(), &Tag::Int(7)); + } + #[test] + fn invalid_palette_data_fails_before_access() { + let mut tag = Tag::compound([("palette", Tag::List(vec![Tag::Int(0), Tag::Int(1)]))]); + assert!(PalettedContainer::from_nbt(&tag, 4096, 4).is_err()); + let Tag::Compound(map) = &mut tag else { + unreachable!() + }; + map.insert(key("data"), Tag::LongArray(vec![-1; 256])); + assert!(PalettedContainer::from_nbt(&tag, 4096, 4).is_err()); + } +} diff --git a/crates/horizon-world/src/collision.rs b/crates/horizon-world/src/collision.rs new file mode 100644 index 000000000..b5e27c11b --- /dev/null +++ b/crates/horizon-world/src/collision.rs @@ -0,0 +1,190 @@ +//! Version-pinned cached block collision data, without entity-context behavior. +//! +//! Java's no-context BlockState.getCollisionShape uses its cache when present. +//! The overload taking CollisionContext always calls block behavior instead. +//! This module covers the cached branch only; uncached states remain explicit. +use crate::{ + DATA_VERSION, + chunk::{BlockSection, BlockState}, + compression::invalid, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, +}; +use horizon_core::geometry::{Axis, VoxelShape}; +use std::{collections::HashMap, io}; + +#[derive(PartialEq, Eq, Hash)] +struct GridKey { + coords: [Vec; 3], + occupied: Vec, + cube: bool, + axes: u8, + min: [i32; 3], + max: [i32; 3], +} + +pub struct CachedCollisionRegistry<'r> { + registry: &'r BlockRegistry, + shapes: Vec, + state_shapes: Vec, + grid_count: usize, +} +impl<'r> CachedCollisionRegistry<'r> { + pub fn registry(&self) -> &'r BlockRegistry { + self.registry + } + pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result { + if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) { + return Err(invalid("collision DataVersion mismatch")); + } + let Some(Tag::List(states)) = tag.get("states") else { + return Err(invalid("missing collision state identities")); + }; + if states.len() != registry.len() { + return Err(invalid("collision registry size mismatch")); + } + for (id, state) in states.iter().enumerate() { + if registry.state(BlockStateId(id as u32)) != Some(&BlockState::from_nbt(state)?) { + return Err(invalid("collision state identities differ")); + } + } + let Some(Tag::List(entries)) = tag.get("shapes") else { + return Err(invalid("missing collision shapes")); + }; + if entries.len() > registry.len() { + return Err(invalid("too many cached collision shapes")); + } + let mut shapes = Vec::with_capacity(entries.len()); + let mut grids = HashMap::::new(); + for entry in entries { + let mut coords: [Vec; 3] = std::array::from_fn(|_| Vec::new()); + for (i, axis) in ["x", "y", "z"].into_iter().enumerate() { + let Some(Tag::LongArray(bits)) = entry.get(axis) else { + return Err(invalid("missing collision coordinates")); + }; + coords[i] = bits.iter().map(|b| f64::from_bits(*b as u64)).collect(); + } + let Some(Tag::ByteArray(bits)) = entry.get("occupied") else { + return Err(invalid("missing collision occupancy")); + }; + if bits.iter().any(|b| *b != 0 && *b != 1) { + return Err(invalid("invalid collision occupancy")); + } + let occupied = bits.iter().map(|b| *b != 0).collect::>(); + let Some(Tag::Byte(cube_axes)) = entry.get("cube_axes") else { + return Err(invalid("missing cube-coordinate metadata")); + }; + if *cube_axes < 0 || *cube_axes > 7 { + return Err(invalid("invalid cube-coordinate metadata")); + } + let coordinate_cubes = [cube_axes & 1 != 0, cube_axes & 2 != 0, cube_axes & 4 != 0]; + let discrete_bounds = |name| -> io::Result<[i32; 3]> { + let Some(Tag::IntArray(values)) = entry.get(name) else { + return Err(invalid("missing collision discrete extrema")); + }; + values + .as_slice() + .try_into() + .map_err(|_| invalid("invalid collision discrete extrema length")) + }; + let min = discrete_bounds("discrete_min")?; + let max = discrete_bounds("discrete_max")?; + let cube = match entry.get("cube") { + Some(Tag::Byte(0)) => false, + Some(Tag::Byte(1)) => true, + _ => return Err(invalid("invalid collision cube flag")), + }; + let key = GridKey { + coords: std::array::from_fn(|i| coords[i].iter().map(|v| v.to_bits()).collect()), + occupied: bits.clone(), + cube, + axes: *cube_axes as u8, + min, + max, + }; + if let Some(existing) = grids.get(&key) { + shapes.push(existing.fresh_identity()); + continue; + } + let shape = match entry.get("cube") { + Some(Tag::Byte(0)) => { + VoxelShape::from_mixed_grid(coords, &occupied, coordinate_cubes) + } + Some(Tag::Byte(1)) => { + if *cube_axes != 7 { + return Err(invalid("cube shape has array-coordinate metadata")); + } + let sizes = std::array::from_fn(|i| coords[i].len().saturating_sub(1)); + let shape = VoxelShape::from_cube(sizes, &occupied) + .map_err(|e| invalid(e.to_string()))?; + for axis in Axis::ALL { + if shape + .coordinates(axis) + .iter() + .map(|v| v.to_bits()) + .ne(coords[axis as usize].iter().map(|v| v.to_bits())) + { + return Err(invalid("cube collision coordinates differ")); + } + } + Ok(shape) + } + _ => return Err(invalid("invalid collision cube flag")), + } + .map_err(|e| invalid(e.to_string()))?; + let shape = shape + .with_discrete_bounds(min, max) + .map_err(|e| invalid(e.to_string()))?; + grids.insert(key, shape.clone()); + shapes.push(shape); + } + let Some(Tag::IntArray(state_shapes)) = tag.get("cached_shapes") else { + return Err(invalid("missing cached shape mapping")); + }; + if state_shapes.len() != registry.len() + || state_shapes + .iter() + .any(|id| *id < -1 || *id >= shapes.len() as i32) + { + return Err(invalid("invalid cached shape mapping")); + } + Ok(Self { + registry, + shapes, + state_shapes: state_shapes.clone(), + grid_count: grids.len(), + }) + } + pub fn shape_count(&self) -> usize { + self.shapes.len() + } + pub fn unique_grid_count(&self) -> usize { + self.grid_count + } + pub fn cached_state_count(&self) -> usize { + self.state_shapes.iter().filter(|id| **id >= 0).count() + } + /// None means vanilla must call block behavior for this state. It does not + /// mean air, an empty shape, or permission to ignore a collision. + pub fn cached_shape(&self, state: BlockStateId) -> io::Result> { + let id = *self + .state_shapes + .get(state.0 as usize) + .ok_or_else(|| invalid("collision state outside registry"))?; + Ok(if id < 0 { + None + } else { + Some(&self.shapes[id as usize]) + }) + } + pub fn section_shape( + &self, + section: &BlockSection<'_>, + index: usize, + ) -> io::Result> { + if !std::ptr::eq(section.registry(), self.registry) { + return Err(invalid("section uses a different collision registry")); + } + self.cached_shape(section.get(index)?) + } +} diff --git a/crates/horizon-world/src/compression.rs b/crates/horizon-world/src/compression.rs new file mode 100644 index 000000000..0bdfb6091 --- /dev/null +++ b/crates/horizon-world/src/compression.rs @@ -0,0 +1,227 @@ +//! Region codecs, including lz4-java's block framing (not the LZ4 frame format). +use flate2::{Compression as Level, Decompress, FlushDecompress, Status}; +use std::io::{self, Read, Write}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum Compression { + Gzip = 1, + Zlib = 2, + None = 3, + Lz4 = 4, +} + +pub(crate) fn invalid(message: impl Into) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message.into()) +} + +impl TryFrom for Compression { + type Error = io::Error; + fn try_from(value: u8) -> io::Result { + match value { + 1 => Ok(Self::Gzip), + 2 => Ok(Self::Zlib), + 3 => Ok(Self::None), + 4 => Ok(Self::Lz4), + _ => Err(invalid(format!( + "unsupported region compression ID {value}" + ))), + } + } +} + +impl Compression { + pub fn decode(self, bytes: &[u8], max_output: usize) -> io::Result> { + match self { + Self::None => { + if bytes.len() > max_output { + return Err(invalid("decompression limit exceeded")); + } + Ok(bytes.to_vec()) + } + Self::Gzip => { + let decoder = flate2::read::MultiGzDecoder::new(bytes); + let mut output = Vec::new(); + decoder + .take((max_output as u64).saturating_add(1)) + .read_to_end(&mut output)?; + if output.len() > max_output { + return Err(invalid("decompression limit exceeded")); + } + Ok(output) + } + Self::Zlib => { + let mut decoder = Decompress::new(true); + let mut output = Vec::new(); + let mut block = [0; 8192]; + loop { + let before_in = decoder.total_in(); + let before_out = decoder.total_out(); + let status = decoder + .decompress( + &bytes[before_in as usize..], + &mut block, + FlushDecompress::None, + ) + .map_err(|e| invalid(e.to_string()))?; + let produced = (decoder.total_out() - before_out) as usize; + if produced > max_output.saturating_sub(output.len()) { + return Err(invalid("decompression limit exceeded")); + } + output.extend_from_slice(&block[..produced]); + if status == Status::StreamEnd { + return Ok(output); + } + if decoder.total_in() == before_in && produced == 0 { + return Err(invalid("truncated zlib stream")); + } + } + } + Self::Lz4 => decode_lz4(bytes, max_output), + } + } + + pub fn encode(self, bytes: &[u8]) -> io::Result> { + match self { + Self::None => Ok(bytes.to_vec()), + Self::Gzip => { + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), Level::default()); + encoder.write_all(bytes)?; + encoder.finish() + } + Self::Zlib => { + let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), Level::default()); + encoder.write_all(bytes)?; + encoder.finish() + } + Self::Lz4 => Ok(encode_lz4(bytes)), + } + } +} + +const MAGIC: &[u8; 8] = b"LZ4Block"; +fn checksum(bytes: &[u8]) -> u32 { + // The Checksum adapter used by the pinned Java library masks to 28 bits. + xxhash_rust::xxh32::xxh32(bytes, 0x9747_b28c) & 0x0fff_ffff +} + +fn decode_lz4(mut bytes: &[u8], max_output: usize) -> io::Result> { + let mut output = Vec::new(); + loop { + let header = bytes + .get(..21) + .ok_or_else(|| invalid("truncated LZ4 header"))?; + if &header[..8] != MAGIC { + return Err(invalid("invalid LZ4 block magic")); + } + let method = header[8] & 0xf0; + if !matches!(method, 0x10 | 0x20) { + return Err(invalid("invalid LZ4 block method")); + } + let compressed = u32::from_le_bytes(header[9..13].try_into().unwrap()) as usize; + let raw = u32::from_le_bytes(header[13..17].try_into().unwrap()) as usize; + let expected = u32::from_le_bytes(header[17..21].try_into().unwrap()); + if raw > (1 << (10 + (header[8] & 15))) + || (raw == 0) != (compressed == 0) + || (method == 0x10 && raw != compressed) + { + return Err(invalid("invalid LZ4 block lengths")); + } + bytes = &bytes[21..]; + if raw == 0 { + if expected != 0 { + return Err(invalid("invalid LZ4 terminator checksum")); + } + return Ok(output); + } + if raw > max_output.saturating_sub(output.len()) { + return Err(invalid("decompression limit exceeded")); + } + let block = bytes + .get(..compressed) + .ok_or_else(|| invalid("truncated LZ4 payload"))?; + let start = output.len(); + if method == 0x10 { + output.extend_from_slice(block); + } else { + output.resize(start + raw, 0); + let actual = lz4_flex::block::decompress_into(block, &mut output[start..]) + .map_err(|e| invalid(e.to_string()))?; + if actual != raw { + return Err(invalid("LZ4 decoded length mismatch")); + } + } + if checksum(&output[start..]) != expected { + return Err(invalid("LZ4 checksum mismatch")); + } + bytes = &bytes[compressed..]; + } +} + +fn encode_lz4(bytes: &[u8]) -> Vec { + let mut output = Vec::new(); + for block in bytes.chunks(65536) { + let compressed = lz4_flex::block::compress(block); + let (token, payload) = if compressed.len() < block.len() { + (0x26, compressed.as_slice()) + } else { + (0x16, block) + }; + output.extend_from_slice(MAGIC); + output.push(token); + output.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + output.extend_from_slice(&(block.len() as u32).to_le_bytes()); + output.extend_from_slice(&checksum(block).to_le_bytes()); + output.extend_from_slice(payload); + } + output.extend_from_slice(MAGIC); + output.push(0x16); + output.extend_from_slice(&[0; 12]); + output +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn all_codecs_roundtrip_and_enforce_limits() { + for codec in [ + Compression::Gzip, + Compression::Zlib, + Compression::None, + Compression::Lz4, + ] { + for bytes in [ + vec![], + vec![0; 131073], + (0..262144).map(|i| (i * 37) as u8).collect(), + ] { + let encoded = codec.encode(&bytes).unwrap(); + assert_eq!(codec.decode(&encoded, bytes.len()).unwrap(), bytes); + if !bytes.is_empty() { + assert!(codec.decode(&encoded, bytes.len() - 1).is_err()); + } + if codec != Compression::None { + assert!( + codec + .decode(&encoded[..encoded.len() - 1], bytes.len()) + .is_err() + ); + } + } + } + } + #[test] + fn checksums_reject_corruption() { + for codec in [Compression::Gzip, Compression::Zlib, Compression::Lz4] { + let mut encoded = codec.encode(b"Horizon world data").unwrap(); + let i = if codec == Compression::Lz4 { + 17 + } else { + encoded.len() - 5 + }; + encoded[i] ^= 1; + assert!(codec.decode(&encoded, 1000).is_err()); + } + } +} diff --git a/crates/horizon-world/src/dynamic_support.rs b/crates/horizon-world/src/dynamic_support.rs new file mode 100644 index 000000000..835ac4817 --- /dev/null +++ b/crates/horizon-world/src/dynamic_support.rs @@ -0,0 +1,251 @@ +//! Uncached support-shape selection. Block entities are queried through snapshots; +//! their lifecycle and active moving-piston collision generation are separate. +use crate::{block_support::SupportType, chunk::BlockState, compression::invalid}; +use horizon_core::{ + geometry::{Aabb, Direction, ShapeError, ShapeOp, Vec3, VoxelShape}, + position::BlockPos, + random::position_seed, +}; +use std::{io, sync::OnceLock}; + +pub trait DynamicSupportWorld { + type Error; + /// None represents a missing block entity or a different block-entity type. + fn shulker_is_closed(&mut self, position: [i32; 3]) -> Result, Self::Error>; + /// Invoke the active moving-piston entity's collision calculation when it + /// exists. None represents a missing entity or a different entity type. + fn moving_piston_shape( + &mut self, + position: [i32; 3], + ) -> Result, Self::Error>; +} +#[derive(Debug)] +pub enum DynamicSupportError { + World(E), + Shape(ShapeError), +} +impl std::fmt::Display for DynamicSupportError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::World(e) => e.fmt(f), + Self::Shape(e) => e.fmt(f), + } + } +} +impl std::error::Error for DynamicSupportError {} +#[derive(Clone, Debug)] +pub struct DynamicSupport { + kind: Kind, +} +#[derive(Clone, Debug)] +enum Kind { + Bamboo, + Speleothem(usize), + Scaffolding, + PowderSnow, + Shulker(Direction), + MovingPiston, +} +impl DynamicSupport { + /// Select behavior from a validated registry descriptor. None requests a + /// different implementation (usually the immutable cached-support branch). + pub fn from_state(state: &BlockState) -> io::Result> { + let property = |name: &str| { + state + .properties + .get(name) + .map(String::as_str) + .ok_or_else(|| invalid("missing dynamic support property")) + }; + let kind = match state.name.as_str() { + "minecraft:bamboo" => Kind::Bamboo, + "minecraft:pointed_dripstone" | "minecraft:sulfur_spike" => { + let down = match property("vertical_direction")? { + "down" => true, + "up" => false, + _ => return Err(invalid("invalid speleothem direction")), + }; + let shape = match property("thickness")? { + "tip_merge" => 0, + "tip" => { + if down { + 2 + } else { + 1 + } + } + "frustum" => 3, + "middle" => 4, + "base" => 5, + _ => return Err(invalid("invalid speleothem thickness")), + }; + Kind::Speleothem(shape) + } + "minecraft:scaffolding" => Kind::Scaffolding, + "minecraft:powder_snow" => Kind::PowderSnow, + "minecraft:moving_piston" => Kind::MovingPiston, + name if shulker(name) => Kind::Shulker(match property("facing")? { + "down" => Direction::Down, + "up" => Direction::Up, + "north" => Direction::North, + "south" => Direction::South, + "west" => Direction::West, + "east" => Direction::East, + _ => return Err(invalid("invalid shulker facing")), + }), + _ => return Ok(None), + }; + Ok(Some(Self { kind })) + } + pub fn offset(&self, position: [i32; 3]) -> Vec3 { + let maximum = match self.kind { + Kind::Bamboo => 0.25f32, + Kind::Speleothem(_) => 0.125f32, + _ => return Vec3::ZERO, + }; + let seed = position_seed(BlockPos::new(position[0], 0, position[2])); + let component = |shift: u32| { + let fraction = ((seed >> shift) & 15i64) as f32 / 15.0f32; + ((f64::from(fraction) - 0.5) * 0.5).clamp(-f64::from(maximum), f64::from(maximum)) + }; + Vec3::new(component(0), 0.0, component(8)) + } + pub fn shape( + &self, + world: &mut W, + position: [i32; 3], + ) -> Result> { + Ok(match self.kind { + Kind::Bamboo => { + static SHAPE: OnceLock = OnceLock::new(); + SHAPE + .get_or_init(|| column(3.0, 0.0, 16.0)) + .moved(self.offset(position)) + } + Kind::Speleothem(index) => { + static SHAPES: OnceLock<[VoxelShape; 6]> = OnceLock::new(); + SHAPES.get_or_init(|| { + [ + column(6.0, 0.0, 16.0), + column(6.0, 0.0, 11.0), + column(6.0, 5.0, 16.0), + column(8.0, 0.0, 16.0), + column(10.0, 0.0, 16.0), + column(12.0, 0.0, 16.0), + ] + })[index] + .moved(self.offset(position)) + } + Kind::Scaffolding => { + static SHAPE: OnceLock = OnceLock::new(); + SHAPE + .get_or_init(|| { + let mut legs = VoxelShape::empty(); + for [x, z] in [[0.0, 0.0], [0.875, 0.0], [0.875, 0.875], [0.0, 0.875]] { + let leg = box_shape([x, 0.0, z], [x + 0.125, 1.0, z + 0.125]); + legs = legs.join(&leg, ShapeOp::OR).expect("bounded scaffold legs"); + } + column(16.0, 14.0, 16.0) + .join(&legs, ShapeOp::OR) + .expect("bounded scaffold support") + }) + .clone() + } + Kind::PowderSnow => VoxelShape::empty(), + Kind::Shulker(facing) => { + if world + .shulker_is_closed(position) + .map_err(DynamicSupportError::World)? + == Some(false) + { + static SHAPES: OnceLock<[VoxelShape; 6]> = OnceLock::new(); + SHAPES.get_or_init(|| { + Direction::ALL.map(|direction| { + let mut min = [0.0; 3]; + let mut max = [1.0; 3]; + for (i, n) in direction.normal().into_iter().enumerate() { + if n < 0 { + max[i] = 0.0625; + } else if n > 0 { + min[i] = 0.9375; + } + } + box_shape(min, max) + }) + })[facing.opposite() as usize] + .clone() + } else { + VoxelShape::block() + } + } + Kind::MovingPiston => world + .moving_piston_shape(position) + .map_err(DynamicSupportError::World)? + .unwrap_or_else(VoxelShape::empty), + }) + } + pub fn collision_shape( + &self, + world: &mut W, + position: [i32; 3], + ) -> Result> { + if let Kind::Shulker(direction) = self.kind { + return match world + .shulker_collision_state(position) + .map_err(DynamicSupportError::World)? + { + Some(snapshot) => VoxelShape::from_box(snapshot.bounding_box(direction)) + .map_err(DynamicSupportError::Shape), + None => Ok(VoxelShape::block()), + }; + } + // Empty collision context uses the stable scaffolding shape, empty + // powder snow, and the same bamboo/speleothem/piston geometry as support. + self.shape(world, position) + } + pub fn is_face_sturdy( + &self, + world: &mut W, + position: [i32; 3], + direction: Direction, + support: SupportType, + ) -> Result> { + support + .is_supporting(&self.shape(world, position)?, direction) + .map_err(DynamicSupportError::Shape) + } +} +fn box_shape(min: [f64; 3], max: [f64; 3]) -> VoxelShape { + VoxelShape::from_box(Aabb::new( + Vec3::new(min[0], min[1], min[2]), + Vec3::new(max[0], max[1], max[2]), + )) + .expect("bounded support shape") +} +fn column(width: f64, min_y: f64, max_y: f64) -> VoxelShape { + let min = (8.0 - width / 2.0) / 16.0; + let max = (8.0 + width / 2.0) / 16.0; + box_shape([min, min_y / 16.0, min], [max, max_y / 16.0, max]) +} +fn shulker(name: &str) -> bool { + matches!( + name, + "minecraft:shulker_box" + | "minecraft:white_shulker_box" + | "minecraft:orange_shulker_box" + | "minecraft:magenta_shulker_box" + | "minecraft:light_blue_shulker_box" + | "minecraft:yellow_shulker_box" + | "minecraft:lime_shulker_box" + | "minecraft:pink_shulker_box" + | "minecraft:gray_shulker_box" + | "minecraft:light_gray_shulker_box" + | "minecraft:cyan_shulker_box" + | "minecraft:purple_shulker_box" + | "minecraft:blue_shulker_box" + | "minecraft:brown_shulker_box" + | "minecraft:green_shulker_box" + | "minecraft:red_shulker_box" + | "minecraft:black_shulker_box" + ) +} diff --git a/crates/horizon-world/src/entity_obstruction.rs b/crates/horizon-world/src/entity_obstruction.rs new file mode 100644 index 000000000..89f7f586b --- /dev/null +++ b/crates/horizon-world/src/entity_obstruction.rs @@ -0,0 +1,89 @@ +//! Entity obstruction against a voxel shape. Entity storage, lifecycle and +//! vehicle-tree maintenance supply the immutable candidate snapshots here. +use horizon_core::geometry::{Aabb, ShapeError, ShapeOp, VoxelShape}; + +/// Object identity within the caller's entity snapshot, including its generation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EntityIdentity(pub u64); +#[derive(Clone, Copy, Debug)] +pub struct ObstructionEntity { + pub identity: EntityIdentity, + pub root_vehicle: EntityIdentity, + pub bounds: Aabb, + pub removed: bool, + pub spectator: bool, + pub blocks_building: bool, +} +pub trait EntityObstructionWorld { + type Error; + /// Preserve native query order. Implementations may return a broad-phase + /// superset: exclusion, spectator and exact AABB filters are enforced below. + fn obstruction_candidates( + &mut self, + excluded: Option, + bounds: Aabb, + ) -> Result, Self::Error>; +} +#[derive(Debug)] +pub enum ObstructionError { + World(E), + Shape(ShapeError), +} +impl std::fmt::Display for ObstructionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::World(e) => e.fmt(f), + Self::Shape(e) => e.fmt(f), + } + } +} +impl std::error::Error for ObstructionError {} + +pub fn is_unobstructed( + world: &mut W, + excluded: Option<&ObstructionEntity>, + shape: &VoxelShape, +) -> Result> { + let Some(bounds) = shape.bounds() else { + return Ok(true); + }; + let candidates = world + .obstruction_candidates(excluded.map(|e| e.identity), bounds) + .map_err(ObstructionError::World)?; + for entity in candidates { + if excluded.is_some_and(|e| e.identity == entity.identity) + || entity.spectator + || !entity.bounds.intersects(bounds) + { + continue; + } + if entity.removed + || !entity.blocks_building + || excluded.is_some_and(|e| e.root_vehicle == entity.root_vehicle) + { + continue; + } + let other = VoxelShape::from_box(entity.bounds).map_err(ObstructionError::Shape)?; + if shape + .join_is_not_empty(&other, ShapeOp::AND) + .map_err(ObstructionError::Shape)? + { + return Ok(false); + } + } + Ok(true) +} + +/// Entity obstruction for the unit cube used by the vanilla block predicate. +/// Translate the voxel shape in floating point: integer MAX + 1 must not wrap. +pub fn is_block_unobstructed( + world: &mut W, + position: [i32; 3], +) -> Result> { + let shape = VoxelShape::block().moved(horizon_core::geometry::Vec3::new( + f64::from(position[0]), + f64::from(position[1]), + f64::from(position[2]), + )); + is_unobstructed(world, None, &shape) +} diff --git a/crates/horizon-world/src/fluid.rs b/crates/horizon-world/src/fluid.rs new file mode 100644 index 000000000..f0472709c --- /dev/null +++ b/crates/horizon-world/src/fluid.rs @@ -0,0 +1,252 @@ +//! Fluid states carried by the pinned vanilla block-state registry. +//! Flow updates, spreading and entity interaction are separate simulation work. +use crate::{ + chunk::BlockState, + compression::invalid, + registry::{BlockRegistry, BlockStateId}, +}; +use std::io; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum FluidKind { + Empty, + FlowingWater, + Water, + FlowingLava, + Lava, +} +impl FluidKind { + pub const ALL: [Self; 5] = [ + Self::Empty, + Self::FlowingWater, + Self::Water, + Self::FlowingLava, + Self::Lava, + ]; + pub const fn name(self) -> &'static str { + match self { + Self::Empty => "minecraft:empty", + Self::FlowingWater => "minecraft:flowing_water", + Self::Water => "minecraft:water", + Self::FlowingLava => "minecraft:flowing_lava", + Self::Lava => "minecraft:lava", + } + } + pub fn from_name(name: &str) -> Option { + Self::ALL.into_iter().find(|kind| kind.name() == name) + } + pub const fn same_family(self, other: Self) -> bool { + matches!( + (self, other), + (Self::Empty, Self::Empty) + | ( + Self::Water | Self::FlowingWater, + Self::Water | Self::FlowingWater + ) + | ( + Self::Lava | Self::FlowingLava, + Self::Lava | Self::FlowingLava + ) + ) + } + pub const fn mask(self) -> u8 { + 1 << self as u8 + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FluidState { + kind: FluidKind, + amount: u8, + falling: bool, +} +impl FluidState { + pub const EMPTY: Self = Self { + kind: FluidKind::Empty, + amount: 0, + falling: false, + }; + pub const WATER: Self = Self { + kind: FluidKind::Water, + amount: 8, + falling: false, + }; + pub const fn kind(self) -> FluidKind { + self.kind + } + pub const fn amount(self) -> u8 { + self.amount + } + pub const fn falling(self) -> bool { + self.falling + } + pub const fn is_source(self) -> bool { + matches!(self.kind, FluidKind::Water | FluidKind::Lava) + } + pub const fn is_full(self) -> bool { + self.amount == 8 + } + pub fn height_at( + self, + world: &mut W, + position: [i32; 3], + ) -> Result { + if self.kind == FluidKind::Empty { + return Ok(0.0); + } + let above = [position[0], position[1].wrapping_add(1), position[2]]; + Ok(if self.kind.same_family(world.fluid(above)?.kind) { + 1.0 + } else { + self.own_height() + }) + } + pub fn camera_height_at( + self, + world: &mut W, + position: [i32; 3], + ) -> Result { + if self.is_source() { + let above = [position[0], position[1].wrapping_add(1), position[2]]; + if world.sturdy_down(above)? { + return Ok(1.0); + } + } + self.height_at(world, position) + } + pub fn own_height(self) -> f32 { + f32::from(self.amount) / 9.0 + } + pub fn from_block(state: &BlockState) -> io::Result { + let water = state.name == "minecraft:water"; + if water || state.name == "minecraft:lava" { + let level = state + .properties + .get("level") + .and_then(|v| v.parse::().ok()) + .filter(|v| *v <= 15) + .ok_or_else(|| invalid("invalid liquid block level"))?; + let kind = match (water, level == 0) { + (true, true) => FluidKind::Water, + (true, false) => FluidKind::FlowingWater, + (false, true) => FluidKind::Lava, + (false, false) => FluidKind::FlowingLava, + }; + return Ok(Self { + kind, + amount: if level == 0 || level >= 8 { + 8 + } else { + 8 - level + }, + falling: level >= 8, + }); + } + if matches!( + state.name.as_str(), + "minecraft:kelp" + | "minecraft:kelp_plant" + | "minecraft:seagrass" + | "minecraft:tall_seagrass" + | "minecraft:bubble_column" + ) { + return Ok(Self::WATER); + } + match state.properties.get("waterlogged").map(String::as_str) { + Some("true") => { + // The pinned copper-grate blocks use falling source water. + let falling = matches!( + state.name.as_str(), + "minecraft:copper_grate" + | "minecraft:exposed_copper_grate" + | "minecraft:weathered_copper_grate" + | "minecraft:oxidized_copper_grate" + | "minecraft:waxed_copper_grate" + | "minecraft:waxed_exposed_copper_grate" + | "minecraft:waxed_weathered_copper_grate" + | "minecraft:waxed_oxidized_copper_grate" + ); + Ok(Self { + falling, + ..Self::WATER + }) + } + None | Some("false") => Ok(Self::EMPTY), + _ => Err(invalid("invalid waterlogged block property")), + } + } +} +/// Queries required by fluid surface height and camera immersion. The caller +/// owns block shape/support behavior and world-query failures. +pub trait FluidHeightWorld { + type Error; + fn fluid(&mut self, position: [i32; 3]) -> Result; + fn sturdy_down(&mut self, position: [i32; 3]) -> Result; +} +#[derive(Debug)] +pub struct FluidStateTable(Vec); +impl FluidStateTable { + pub fn new(registry: &BlockRegistry) -> io::Result { + (0..registry.len()) + .map(|i| FluidState::from_block(registry.state(BlockStateId(i as u32)).unwrap())) + .collect::>>() + .map(Self) + } + pub fn get(&self, state: BlockStateId) -> Option { + self.0.get(state.0 as usize).copied() + } + pub fn matching_states(&self, mask: u8) -> impl Iterator + '_ { + self.0 + .iter() + .enumerate() + .filter(move |(_, state)| state.kind.mask() & mask != 0) + .map(|(i, _)| BlockStateId(i as u32)) + } +} + +/// Bound identities for converting fluid states into their legacy liquid blocks. +pub struct FluidBlockBindings { + air: BlockStateId, + water: [BlockStateId; 16], + lava: [BlockStateId; 16], +} +impl FluidBlockBindings { + pub fn new(registry: &BlockRegistry) -> io::Result { + let levels = |name: &str| -> io::Result<[BlockStateId; 16]> { + let default = registry + .default_state(name) + .ok_or_else(|| invalid("missing liquid block"))?; + let mut state = registry.state(default).unwrap().clone(); + let mut result = [default; 16]; + for (level, id) in result.iter_mut().enumerate() { + state.properties.insert("level".into(), level.to_string()); + *id = registry + .id(&state) + .ok_or_else(|| invalid("missing liquid block level"))?; + } + Ok(result) + }; + Ok(Self { + air: registry + .default_state("minecraft:air") + .ok_or_else(|| invalid("missing air block"))?, + water: levels("minecraft:water")?, + lava: levels("minecraft:lava")?, + }) + } + pub fn block(&self, state: FluidState) -> BlockStateId { + if state.kind == FluidKind::Empty { + return self.air; + } + let level = if state.is_source() { + 0 + } else { + 8 - state.amount.min(8) + if state.falling { 8 } else { 0 } + } as usize; + if state.kind.same_family(FluidKind::Water) { + self.water[level] + } else { + self.lava[level] + } + } +} diff --git a/crates/horizon-world/src/heightmap.rs b/crates/horizon-world/src/heightmap.rs new file mode 100644 index 000000000..4cc7df058 --- /dev/null +++ b/crates/horizon-world/src/heightmap.rs @@ -0,0 +1,249 @@ +//! Packed column heights and the six Java 26.3 heightmap predicates. +//! +//! Block behavior supplies air/fluid facts and resolved block-tag membership. +//! Heightmaps do not infer those facts from collision shapes or block names. +use horizon_core::storage::{PackedStorage, StorageError}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum HeightmapType { + WorldSurfaceWg, + WorldSurface, + OceanFloorWg, + OceanFloor, + MotionBlocking, + MotionBlockingNoLeaves, +} + +impl HeightmapType { + pub const ALL: [Self; 6] = [ + Self::WorldSurfaceWg, + Self::WorldSurface, + Self::OceanFloorWg, + Self::OceanFloor, + Self::MotionBlocking, + Self::MotionBlockingNoLeaves, + ]; + + pub fn name(self) -> &'static str { + match self { + Self::WorldSurfaceWg => "WORLD_SURFACE_WG", + Self::WorldSurface => "WORLD_SURFACE", + Self::OceanFloorWg => "OCEAN_FLOOR_WG", + Self::OceanFloor => "OCEAN_FLOOR", + Self::MotionBlocking => "MOTION_BLOCKING", + Self::MotionBlockingNoLeaves => "MOTION_BLOCKING_NO_LEAVES", + } + } + + pub fn send_to_client(self) -> bool { + matches!( + self, + Self::WorldSurface | Self::MotionBlocking | Self::MotionBlockingNoLeaves + ) + } + + pub fn keep_after_worldgen(self) -> bool { + !matches!(self, Self::WorldSurfaceWg | Self::OceanFloorWg) + } + + pub fn is_opaque(self, state: impl HeightmapState) -> bool { + match self { + Self::WorldSurfaceWg | Self::WorldSurface => !state.is_air(), + Self::OceanFloorWg | Self::OceanFloor => state.blocks_motion_in_heightmap(), + Self::MotionBlocking => state.blocks_motion_in_heightmap() || state.has_fluid(), + Self::MotionBlockingNoLeaves => { + state.blocks_motion_in_heightmap_no_leaves() || state.has_fluid() + } + } + } +} + +pub trait HeightmapState: Copy { + fn is_air(self) -> bool; + /// Exact AIR block identity, distinct from cave/void air. + fn is_air_block(self) -> bool; + fn has_fluid(self) -> bool; + fn blocks_motion_in_heightmap(self) -> bool; + fn blocks_motion_in_heightmap_no_leaves(self) -> bool; +} + +pub trait HeightmapChunk { + type State: HeightmapState; + fn min_y(&self) -> i32; + fn height(&self) -> i32; + fn highest_section_y(&self) -> i32; + fn block_state(&self, x: i32, y: i32, z: i32) -> Self::State; +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum HeightmapError { + InvalidBounds, + MismatchedChunk, + Storage(StorageError), +} +impl From for HeightmapError { + fn from(value: StorageError) -> Self { + Self::Storage(value) + } +} +impl std::fmt::Display for HeightmapError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{self:?}") + } +} +impl std::error::Error for HeightmapError {} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Heightmap { + kind: HeightmapType, + min_y: i32, + height: i32, + data: PackedStorage, +} + +impl Heightmap { + /// Bounded to the vanilla codec's positive, aligned vertical ranges. + pub fn new(kind: HeightmapType, min_y: i32, height: i32) -> Result { + if !(-2032..=2031).contains(&min_y) + || !(16..=4064).contains(&height) + || min_y % 16 != 0 + || height % 16 != 0 + || min_y + height > 2032 + { + return Err(HeightmapError::InvalidBounds); + } + let bits = (32 - (height as u32).leading_zeros()) as u8; + Ok(Self { + kind, + min_y, + height, + data: PackedStorage::new(bits, 256)?, + }) + } + + pub fn kind(&self) -> HeightmapType { + self.kind + } + pub fn raw_data(&self) -> &[u64] { + self.data.words() + } + + fn index(x: i32, z: i32) -> usize { + x.wrapping_add(z.wrapping_mul(16)) as usize + } + + pub fn first_available(&self, x: i32, z: i32) -> Result { + Ok((self.data.get(Self::index(x, z))? as i32).wrapping_add(self.min_y)) + } + + pub fn highest_taken(&self, x: i32, z: i32) -> Result { + Ok(self.first_available(x, z)?.wrapping_sub(1)) + } + + fn set_height(&mut self, x: i32, z: i32, y: i32) -> Result<(), HeightmapError> { + self.data + .set(Self::index(x, z), y.wrapping_sub(self.min_y) as u32)?; + Ok(()) + } + + fn check_chunk(&self, chunk: &impl HeightmapChunk) -> Result<(), HeightmapError> { + if chunk.min_y() != self.min_y || chunk.height() != self.height { + return Err(HeightmapError::MismatchedChunk); + } + Ok(()) + } + + /// The caller writes the new state to the chunk before updating its maps. + pub fn update( + &mut self, + chunk: &C, + x: i32, + y: i32, + z: i32, + state: C::State, + ) -> Result { + self.check_chunk(chunk)?; + let first = self.first_available(x, z)?; + if y <= first.wrapping_sub(2) { + return Ok(false); + } + if self.kind.is_opaque(state) { + if y >= first { + self.set_height(x, z, y.wrapping_add(1))?; + return Ok(true); + } + } else if y == first.wrapping_sub(1) { + let mut scan_y = y.wrapping_sub(1); + while scan_y >= self.min_y { + if self.kind.is_opaque(chunk.block_state(x, scan_y, z)) { + self.set_height(x, z, scan_y.wrapping_add(1))?; + return Ok(true); + } + scan_y -= 1; + } + self.set_height(x, z, self.min_y)?; + return Ok(true); + } + Ok(false) + } + + /// Matching lengths preserve all bits, including padding and unused slots. + /// A length mismatch primes this registered map from the chunk instead. + pub fn set_raw_data( + &mut self, + chunk: &impl HeightmapChunk, + words: &[u64], + ) -> Result<(), HeightmapError> { + self.check_chunk(chunk)?; + if words.len() == self.data.words().len() { + self.data = PackedStorage::from_words(self.data.bits(), 256, words.to_vec())?; + Ok(()) + } else { + Self::prime(chunk, &mut [self]) + } + } + + /// Preserves caller map order and scans X, then Z, then descending Y. + /// An unfound column retains its previous value, including during re-priming. + pub fn prime( + chunk: &impl HeightmapChunk, + maps: &mut [&mut Self], + ) -> Result<(), HeightmapError> { + if maps.is_empty() { + return Ok(()); + } + for map in maps.iter() { + map.check_chunk(chunk)?; + } + let upper = chunk.highest_section_y().wrapping_add(16); + let mut remaining = Vec::with_capacity(maps.len()); + for x in 0..16 { + for z in 0..16 { + remaining.clear(); + remaining.extend(0..maps.len()); + let mut y = upper.wrapping_sub(1); + while y >= chunk.min_y() { + let state = chunk.block_state(x, y, z); + if !state.is_air_block() { + let mut i = 0; + while i < remaining.len() { + let map = &mut maps[remaining[i]]; + if map.kind.is_opaque(state) { + map.set_height(x, z, y.wrapping_add(1))?; + remaining.remove(i); + } else { + i += 1; + } + } + if remaining.is_empty() { + break; + } + } + y -= 1; + } + } + } + Ok(()) + } +} diff --git a/crates/horizon-world/src/lib.rs b/crates/horizon-world/src/lib.rs new file mode 100644 index 000000000..f3cea7028 --- /dev/null +++ b/crates/horizon-world/src/lib.rs @@ -0,0 +1,22 @@ +//! Vanilla-compatible world data for Horizon. This crate does not run gameplay. +#![forbid(unsafe_code)] + +pub mod block_collision; +pub mod block_properties; +pub mod block_support; +pub mod block_survival; +pub mod chunk; +pub mod collision; +pub mod compression; +pub mod dynamic_support; +pub mod entity_obstruction; +pub mod fluid; +pub mod heightmap; +pub mod nbt; +pub mod piston_shape; +pub mod region; +pub mod registry; +pub mod tick_data; +pub mod worldgen; + +pub const DATA_VERSION: i32 = 5023; diff --git a/crates/horizon-world/src/main.rs b/crates/horizon-world/src/main.rs new file mode 100644 index 000000000..ff61c99dd --- /dev/null +++ b/crates/horizon-world/src/main.rs @@ -0,0 +1,197 @@ +use horizon_core::position::BlockPos; +use horizon_world::{ + chunk::{BlockState, ChunkData}, + compression::Compression, + nbt::{self, Limits}, + region::{ChunkRecord, RegionFile, RegionWriter}, +}; +use std::{ + collections::BTreeMap, + error::Error, + fs::{File, OpenOptions}, + io::{Read, Write}, + path::Path, +}; + +fn codec(name: &str) -> Result> { + match name { + "gzip" | "1" => Ok(Compression::Gzip), + "zlib" | "2" => Ok(Compression::Zlib), + "none" | "3" => Ok(Compression::None), + "lz4" | "4" => Ok(Compression::Lz4), + _ => Err(format!("unknown codec {name}; choose gzip, zlib, none or lz4").into()), + } +} + +fn read_bounded(path: &str) -> Result, Box> { + let max = Limits::default().max_bytes; + let mut bytes = Vec::new(); + File::open(path)? + .take((max + 1) as u64) + .read_to_end(&mut bytes)?; + if bytes.len() > max { + return Err("input exceeds 64 MiB limit".into()); + } + Ok(bytes) +} + +fn write_new(path: &str, bytes: &[u8]) -> Result<(), Box> { + let mut file = OpenOptions::new().write(true).create_new(true).open(path)?; + if let Err(error) = file.write_all(bytes).and_then(|_| file.sync_all()) { + drop(file); + let _ = std::fs::remove_file(path); + return Err(error.into()); + } + Ok(()) +} + +fn run(args: &[String]) -> Result<(), Box> { + let Some(command) = args.first().map(String::as_str) else { + return Err("use --help for commands".into()); + }; + match command { + "--help" | "-h" if args.len() == 1 => println!( + "Horizon world data tools — Java Edition 26.3\n\ + inspect \n\ + copy-region [gzip|zlib|none|lz4]\n\ + get-block \n\ + edit-block-data [property=value ...]\n\ + nbt-copy \n\ + nbt-network-copy \n\ + Existing output files are refused. edit-block-data changes saved block data only;\n\ + it does not run lighting, heightmaps, ticks or neighbor updates." + ), + "nbt-copy" | "nbt-network-copy" if args.len() == 5 => { + let bytes = + codec(&args[3])?.decode(&read_bounded(&args[1])?, Limits::default().max_bytes)?; + let encoded = if command == "nbt-copy" { + let (root, used) = nbt::read_named(&bytes, Limits::default())?; + if used != bytes.len() { + return Err("trailing bytes after NBT root".into()); + } + nbt::write_named(&root, Limits::default())? + } else { + let (root, used) = nbt::read_network(&bytes, Limits::default())?; + if used != bytes.len() { + return Err("trailing bytes after NBT root".into()); + } + nbt::write_network(&root, Limits::default())? + }; + write_new(&args[2], &codec(&args[4])?.encode(&encoded)?)?; + println!("Wrote {}", args[2]); + } + "inspect" if args.len() == 2 => { + let mut region = RegionFile::open(&args[1])?; + let chunks: Vec<_> = region.chunks().collect(); + println!( + "Horizon region {},{}: {} chunks", + region.position().x, + region.position().z, + chunks.len() + ); + for (pos, timestamp) in chunks { + let record = region.read(pos)?.unwrap(); + let root = record.nbt(Limits::default())?; + println!( + "chunk {},{} timestamp={} codec={:?} compressed={} root_type={}", + pos.x, + pos.z, + timestamp, + record.compression, + record.compressed.len(), + root.tag.id() + ); + } + } + "copy-region" if args.len() == 3 || args.len() == 4 => { + let mut region = RegionFile::open(&args[1])?; + if args.len() == 3 { + region.export(&args[2], &[])?; + } else { + let compression = codec(&args[3])?; + if horizon_world::region::position_from_path(Path::new(&args[2]))? + != region.position() + { + return Err("export region coordinates differ".into()); + } + let mut writer = RegionWriter::create(&args[2])?; + let positions: Vec<_> = region.chunks().map(|(p, _)| p).collect(); + for pos in positions { + let old = region.read(pos)?.unwrap(); + let record = ChunkRecord::from_nbt( + &old.nbt(Limits::default())?, + compression, + old.timestamp, + Limits::default(), + )?; + writer.write(pos, &record)?; + } + writer.finish()?; + } + println!("Wrote {}", args[2]); + } + "get-block" if args.len() == 5 => { + let block = BlockPos::new(args[2].parse()?, args[3].parse()?, args[4].parse()?); + let record = RegionFile::open(&args[1])? + .read(block.chunk())? + .ok_or("chunk is absent")?; + let chunk = ChunkData::new(record.nbt(Limits::default())?)?; + let state = chunk + .block(block)? + .ok_or("section has no block-state data")?; + print!("{}", state.name); + for (name, value) in state.properties { + print!(" {name}={value}"); + } + println!(); + } + "edit-block-data" if args.len() >= 7 => { + let block = BlockPos::new(args[3].parse()?, args[4].parse()?, args[5].parse()?); + let mut properties = BTreeMap::new(); + for arg in &args[7..] { + let (key, value) = arg.split_once('=').ok_or("expected property=value")?; + if key.is_empty() + || value.is_empty() + || properties + .insert(key.to_owned(), value.to_owned()) + .is_some() + { + return Err("invalid or duplicate block property".into()); + } + } + let mut region = RegionFile::open(&args[1])?; + let old = region.read(block.chunk())?.ok_or("chunk is absent")?; + let mut chunk = ChunkData::new(old.nbt(Limits::default())?)?; + chunk.set_block_data( + block, + BlockState { + name: args[6].clone(), + properties, + }, + )?; + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH)? + .as_secs() as u32; + let next = ChunkRecord::from_nbt( + &chunk.into_nbt(), + old.compression, + timestamp, + Limits::default(), + )?; + region.export(&args[2], &[(block.chunk(), Some(next))])?; + println!( + "Wrote saved block data to {}; simulation-derived data has not been updated.", + args[2] + ); + } + _ => return Err("invalid command or arguments; use --help".into()), + } + Ok(()) +} + +fn main() { + if let Err(error) = run(&std::env::args().skip(1).collect::>()) { + eprintln!("Horizon: {error}"); + std::process::exit(2); + } +} diff --git a/crates/horizon-world/src/nbt.rs b/crates/horizon-world/src/nbt.rs new file mode 100644 index 000000000..b271c6567 --- /dev/null +++ b/crates/horizon-world/src/nbt.rs @@ -0,0 +1,606 @@ +//! Java Edition NBT with lossless UTF-16 strings and 26.3 mixed-list wrappers. +use std::collections::BTreeMap; + +/// Java strings can contain unpaired surrogates, which Rust UTF-8 strings cannot. +#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct JavaString(pub Vec); + +impl From<&str> for JavaString { + fn from(value: &str) -> Self { + Self(value.encode_utf16().collect()) + } +} +impl JavaString { + pub fn to_string(&self) -> Result { + String::from_utf16(&self.0) + } + pub fn to_string_lossy(&self) -> String { + String::from_utf16_lossy(&self.0) + } +} + +pub type Compound = BTreeMap; + +/// Float and double variants hold their IEEE bit patterns. Java canonicalizes +/// NaNs on binary output. Loading, like vanilla's valueOf factories, normalizes +/// negative zero to positive zero. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Tag { + End, + Byte(i8), + Short(i16), + Int(i32), + Long(i64), + Float(u32), + Double(u64), + ByteArray(Vec), + String(JavaString), + List(Vec), + Compound(Compound), + IntArray(Vec), + LongArray(Vec), +} + +impl Tag { + pub fn id(&self) -> u8 { + match self { + Self::End => 0, + Self::Byte(_) => 1, + Self::Short(_) => 2, + Self::Int(_) => 3, + Self::Long(_) => 4, + Self::Float(_) => 5, + Self::Double(_) => 6, + Self::ByteArray(_) => 7, + Self::String(_) => 8, + Self::List(_) => 9, + Self::Compound(_) => 10, + Self::IntArray(_) => 11, + Self::LongArray(_) => 12, + } + } + pub fn get(&self, key: &str) -> Option<&Tag> { + match self { + Self::Compound(map) => map.get(&JavaString::from(key)), + _ => None, + } + } + pub fn get_mut(&mut self, key: &str) -> Option<&mut Tag> { + match self { + Self::Compound(map) => map.get_mut(&JavaString::from(key)), + _ => None, + } + } + pub fn compound(entries: impl IntoIterator, Tag)>) -> Self { + Self::Compound(entries.into_iter().map(|(k, v)| (k.into(), v)).collect()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NamedTag { + pub name: JavaString, + pub tag: Tag, +} + +#[derive(Clone, Copy, Debug)] +pub struct Limits { + pub max_bytes: usize, + pub max_nodes: usize, + pub max_depth: usize, +} +impl Default for Limits { + fn default() -> Self { + Self { + max_bytes: 64 * 1024 * 1024, + max_nodes: 1_000_000, + max_depth: 512, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Error { + pub offset: usize, + pub reason: &'static str, +} +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "NBT at byte {}: {}", self.offset, self.reason) + } +} +impl std::error::Error for Error {} + +struct Reader<'a> { + bytes: &'a [u8], + offset: usize, + limits: Limits, + nodes: usize, +} +impl<'a> Reader<'a> { + fn error(&self, reason: &'static str) -> Error { + Error { + offset: self.offset, + reason, + } + } + fn take(&mut self, len: usize) -> Result<&'a [u8], Error> { + let end = self + .offset + .checked_add(len) + .ok_or_else(|| self.error("length overflow"))?; + if end > self.limits.max_bytes { + return Err(self.error("byte limit exceeded")); + } + let value = self + .bytes + .get(self.offset..end) + .ok_or_else(|| self.error("truncated input"))?; + self.offset = end; + Ok(value) + } + fn number(&mut self) -> Result<[u8; N], Error> { + Ok(self.take(N)?.try_into().unwrap()) + } + fn byte(&mut self) -> Result { + Ok(self.take(1)?[0]) + } + fn count(&mut self, element_bytes: usize) -> Result { + let count = i32::from_be_bytes(self.number()?); + if count < 0 { + return Err(self.error("negative collection length")); + } + let count = count as usize; + let size = count + .checked_mul(element_bytes) + .ok_or_else(|| self.error("length overflow"))?; + if size > self.bytes.len().saturating_sub(self.offset) + || size > self.limits.max_bytes.saturating_sub(self.offset) + { + return Err(self.error("collection exceeds available bytes")); + } + Ok(count) + } + fn string(&mut self) -> Result { + let len = u16::from_be_bytes(self.number()?) as usize; + let bytes = self.take(len)?; + let mut units = Vec::with_capacity(len); + let mut i = 0; + while i < bytes.len() { + let b = bytes[i]; + let (unit, size) = match b { + 0..=127 => (u16::from(b), 1), + 192..=223 if i + 1 < len && bytes[i + 1] & 0xc0 == 0x80 => { + ((u16::from(b & 31) << 6) | u16::from(bytes[i + 1] & 63), 2) + } + 224..=239 + if i + 2 < len + && bytes[i + 1] & 0xc0 == 0x80 + && bytes[i + 2] & 0xc0 == 0x80 => + { + ( + (u16::from(b & 15) << 12) + | (u16::from(bytes[i + 1] & 63) << 6) + | u16::from(bytes[i + 2] & 63), + 3, + ) + } + _ => return Err(self.error("invalid Java modified UTF-8")), + }; + // Match DataInput.readUTF, including accepted overlong sequences. + units.push(unit); + i += size; + } + Ok(JavaString(units)) + } + fn payload(&mut self, id: u8, depth: usize) -> Result { + if self.nodes >= self.limits.max_nodes { + return Err(self.error("node limit exceeded")); + } + self.nodes += 1; + if matches!(id, 9 | 10) && depth >= self.limits.max_depth { + return Err(self.error("depth limit exceeded")); + } + Ok(match id { + 0 => Tag::End, + 1 => Tag::Byte(self.byte()? as i8), + 2 => Tag::Short(i16::from_be_bytes(self.number()?)), + 3 => Tag::Int(i32::from_be_bytes(self.number()?)), + 4 => Tag::Long(i64::from_be_bytes(self.number()?)), + 5 => { + let bits = u32::from_be_bytes(self.number()?); + Tag::Float(if f32::from_bits(bits) == 0.0 { 0 } else { bits }) + } + 6 => { + let bits = u64::from_be_bytes(self.number()?); + Tag::Double(if f64::from_bits(bits) == 0.0 { 0 } else { bits }) + } + 7 => { + let len = self.count(1)?; + Tag::ByteArray(self.take(len)?.to_vec()) + } + 8 => Tag::String(self.string()?), + 9 => { + let element_id = self.byte()?; + let len = self.count(0)?; + if len > 0 && (element_id == 0 || element_id > 12) { + return Err(self.error("invalid list element type")); + } + if len > self.limits.max_nodes.saturating_sub(self.nodes) { + return Err(self.error("node limit exceeded")); + } + // At least one byte per valid non-End payload; do not allocate from an unchecked count. + if len > self.bytes.len().saturating_sub(self.offset) { + return Err(self.error("truncated list")); + } + let mut values = Vec::with_capacity(len); + for _ in 0..len { + let mut value = self.payload(element_id, depth + 1)?; + if let Tag::Compound(map) = &mut value { + if map.len() == 1 && map.contains_key(&JavaString::default()) { + value = map.remove(&JavaString::default()).unwrap(); + } + } + values.push(value); + } + Tag::List(values) + } + 10 => { + let mut map = Compound::new(); + loop { + let id = self.byte()?; + if id == 0 { + break; + } + let name = self.string()?; + let value = self.payload(id, depth + 1)?; + map.insert(name, value); // Java maps retain the last duplicate key. + } + Tag::Compound(map) + } + 11 => { + let len = self.count(4)?; + let mut values = Vec::with_capacity(len); + for _ in 0..len { + values.push(i32::from_be_bytes(self.number()?)); + } + Tag::IntArray(values) + } + 12 => { + let len = self.count(8)?; + let mut values = Vec::with_capacity(len); + for _ in 0..len { + values.push(i64::from_be_bytes(self.number()?)); + } + Tag::LongArray(values) + } + _ => return Err(self.error("unknown tag type")), + }) + } +} + +/// Read a file root (type, modified-UTF name, payload), returning bytes consumed. +pub fn read_named(bytes: &[u8], limits: Limits) -> Result<(NamedTag, usize), Error> { + let mut reader = Reader { + bytes, + offset: 0, + limits, + nodes: 0, + }; + let id = reader.byte()?; + let name = if id == 0 { + JavaString::default() + } else { + reader.string()? + }; + let tag = reader.payload(id, 0)?; + Ok((NamedTag { name, tag }, reader.offset)) +} + +/// Read a network root (type and payload, without the file name field). +pub fn read_network(bytes: &[u8], limits: Limits) -> Result<(Tag, usize), Error> { + let mut reader = Reader { + bytes, + offset: 0, + limits, + nodes: 0, + }; + let id = reader.byte()?; + let tag = reader.payload(id, 0)?; + Ok((tag, reader.offset)) +} + +struct Writer { + bytes: Vec, + limits: Limits, + nodes: usize, +} +impl Writer { + fn error(&self, reason: &'static str) -> Error { + Error { + offset: self.bytes.len(), + reason, + } + } + fn put(&mut self, bytes: &[u8]) -> Result<(), Error> { + if bytes.len() > self.limits.max_bytes.saturating_sub(self.bytes.len()) { + return Err(self.error("byte limit exceeded")); + } + self.bytes.extend_from_slice(bytes); + Ok(()) + } + fn count(&mut self, len: usize) -> Result<(), Error> { + let len = i32::try_from(len).map_err(|_| self.error("collection too long"))?; + self.put(&len.to_be_bytes()) + } + fn string(&mut self, string: &JavaString) -> Result<(), Error> { + let len: usize = string + .0 + .iter() + .map(|&c| match c { + 1..=127 => 1, + 0..=2047 => 2, + _ => 3, + }) + .sum(); + let len = + u16::try_from(len).map_err(|_| self.error("modified UTF-8 exceeds 65535 bytes"))?; + self.put(&len.to_be_bytes())?; + for &c in &string.0 { + match c { + 1..=127 => self.put(&[c as u8])?, + 0..=2047 => self.put(&[0xc0 | (c >> 6) as u8, 0x80 | (c & 63) as u8])?, + _ => self.put(&[ + 0xe0 | (c >> 12) as u8, + 0x80 | ((c >> 6) & 63) as u8, + 0x80 | (c & 63) as u8, + ])?, + } + } + Ok(()) + } + fn payload(&mut self, tag: &Tag, depth: usize) -> Result<(), Error> { + if self.nodes >= self.limits.max_nodes { + return Err(self.error("node limit exceeded")); + } + self.nodes += 1; + if matches!(tag, Tag::List(_) | Tag::Compound(_)) && depth >= self.limits.max_depth { + return Err(self.error("depth limit exceeded")); + } + match tag { + Tag::End => {} + Tag::Byte(v) => self.put(&[*v as u8])?, + Tag::Short(v) => self.put(&v.to_be_bytes())?, + Tag::Int(v) => self.put(&v.to_be_bytes())?, + Tag::Long(v) => self.put(&v.to_be_bytes())?, + Tag::Float(v) => self.put( + &if f32::from_bits(*v).is_nan() { + 0x7fc0_0000_u32 + } else { + *v + } + .to_be_bytes(), + )?, + Tag::Double(v) => self.put( + &if f64::from_bits(*v).is_nan() { + 0x7ff8_0000_0000_0000_u64 + } else { + *v + } + .to_be_bytes(), + )?, + Tag::ByteArray(v) => { + self.count(v.len())?; + self.put(v)?; + } + Tag::String(v) => self.string(v)?, + Tag::List(values) => { + if values.iter().any(|v| matches!(v, Tag::End)) { + return Err(self.error("End cannot be a list element")); + } + let first = values.first().map_or(0, Tag::id); + let id = if values.iter().any(|v| v.id() != first) { + 10 + } else { + first + }; + self.put(&[id])?; + self.count(values.len())?; + for value in values { + let wrapper = matches!(value, Tag::Compound(c) if c.len() == 1 && c.contains_key(&JavaString::default())); + if id == 10 && (value.id() != 10 || wrapper) { + // Emit one synthetic compound layer without cloning the tree. + if depth + 1 >= self.limits.max_depth { + return Err(self.error("depth limit exceeded")); + } + if self.nodes >= self.limits.max_nodes { + return Err(self.error("node limit exceeded")); + } + self.nodes += 1; + self.put(&[value.id()])?; + self.string(&JavaString::default())?; + self.payload(value, depth + 2)?; + self.put(&[0])?; + } else { + self.payload(value, depth + 1)?; + } + } + } + Tag::Compound(values) => { + for (name, value) in values { + if matches!(value, Tag::End) { + return Err(self.error("End cannot be a named value")); + } + self.put(&[value.id()])?; + self.string(name)?; + self.payload(value, depth + 1)?; + } + self.put(&[0])?; + } + Tag::IntArray(v) => { + self.count(v.len())?; + for item in v { + self.put(&item.to_be_bytes())?; + } + } + Tag::LongArray(v) => { + self.count(v.len())?; + for item in v { + self.put(&item.to_be_bytes())?; + } + } + } + Ok(()) + } +} + +pub fn write_named(root: &NamedTag, limits: Limits) -> Result, Error> { + let mut writer = Writer { + bytes: Vec::new(), + limits, + nodes: 0, + }; + writer.put(&[root.tag.id()])?; + if root.tag.id() != 0 { + writer.string(&root.name)?; + } + writer.payload(&root.tag, 0)?; + Ok(writer.bytes) +} + +pub fn write_network(tag: &Tag, limits: Limits) -> Result, Error> { + let mut writer = Writer { + bytes: Vec::new(), + limits, + nodes: 0, + }; + writer.put(&[tag.id()])?; + writer.payload(tag, 0)?; + Ok(writer.bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn wire_node_budget_includes_mixed_list_wrappers() { + let tag = Tag::List(vec![Tag::Int(1), Tag::Byte(2)]); + let limits = Limits { + max_nodes: 5, + ..Limits::default() + }; + let bytes = write_network(&tag, limits).unwrap(); + assert_eq!(read_network(&bytes, limits).unwrap().0, tag); + let limits = Limits { + max_nodes: 4, + ..limits + }; + assert!(write_network(&tag, limits).is_err()); + assert!(read_network(&bytes, limits).is_err()); + } + #[test] + fn depth_boundary_and_every_truncated_prefix() { + let mut tag = Tag::Int(1); + for _ in 0..512 { + tag = Tag::List(vec![tag]); + } + let bytes = write_network(&tag, Limits::default()).unwrap(); + assert_eq!(read_network(&bytes, Limits::default()).unwrap().0, tag); + tag = Tag::List(vec![tag]); + assert!(write_network(&tag, Limits::default()).is_err()); + let deeper = write_network( + &tag, + Limits { + max_depth: 513, + ..Limits::default() + }, + ) + .unwrap(); + assert!(read_network(&deeper, Limits::default()).is_err()); + let short = Tag::compound([( + "list", + Tag::List(vec![Tag::Long(42), Tag::ByteArray(vec![1, 2, 3])]), + )]); + let bytes = write_network(&short, Limits::default()).unwrap(); + for end in 0..bytes.len() { + assert!(read_network(&bytes[..end], Limits::default()).is_err()); + } + } + #[test] + fn modified_utf_and_mixed_lists_preserve_java_values() { + let tag = Tag::List(vec![ + Tag::Int(3), + Tag::String(JavaString(vec![0, 0xd800, 0xdc00, 0xdfff])), + Tag::compound([("", Tag::Int(9))]), + Tag::compound([("x", Tag::Byte(1))]), + ]); + let data = write_network(&tag, Limits::default()).unwrap(); + assert_eq!(data[1], 10); + assert_eq!( + read_network(&data, Limits::default()).unwrap(), + (tag, data.len()) + ); + } + #[test] + fn malformed_lengths_truncation_limits_and_utf_are_rejected() { + for data in [ + &[7, 0xff, 0xff, 0xff, 0xff][..], + &[9, 0, 0, 0, 0, 1], + &[8, 0, 1, 0xc0], + &[13], + &[4, 0], + ] { + assert!(read_network(data, Limits::default()).is_err()); + } + let tag = Tag::List(vec![Tag::List(vec![Tag::Int(1)])]); + let bytes = write_network(&tag, Limits::default()).unwrap(); + assert!( + read_network( + &bytes, + Limits { + max_depth: 1, + ..Limits::default() + } + ) + .is_err() + ); + assert!( + read_network( + &bytes, + Limits { + max_nodes: 2, + ..Limits::default() + } + ) + .is_err() + ); + assert!( + read_network( + &bytes, + Limits { + max_bytes: bytes.len() - 1, + ..Limits::default() + } + ) + .is_err() + ); + assert!( + write_network(&Tag::String(JavaString(vec![0; 32768])), Limits::default()).is_err() + ); + } + #[test] + fn duplicate_keys_last_wins_and_nan_output_is_canonical() { + let bytes = [10, 1, 0, 1, b'x', 1, 1, 0, 1, b'x', 2, 0]; + assert_eq!( + read_network(&bytes, Limits::default()).unwrap().0.get("x"), + Some(&Tag::Byte(2)) + ); + assert_eq!( + write_network(&Tag::Float(0xff80_0001), Limits::default()).unwrap(), + [5, 0x7f, 0xc0, 0, 0] + ); + assert_eq!( + write_network(&Tag::Double((-0.0_f64).to_bits()), Limits::default()).unwrap()[1], + 0x80 + ); + } +} diff --git a/crates/horizon-world/src/piston_shape.rs b/crates/horizon-world/src/piston_shape.rs new file mode 100644 index 000000000..d14f8f301 --- /dev/null +++ b/crates/horizon-world/src/piston_shape.rs @@ -0,0 +1,196 @@ +//! Moving-piston collision selection and interpolation over immutable state IDs. +//! Tick progression, entity pushing and world mutation belong to the world loop. +use crate::{ + compression::invalid, + registry::{BlockRegistry, BlockStateId}, +}; +use horizon_core::geometry::{Direction, ShapeError, ShapeOp, Vec3, VoxelShape}; +use std::{collections::BTreeMap, io}; +#[derive(Clone, Copy, Debug)] +pub struct MovingPistonState { + pub moved_state: BlockStateId, + pub direction: Direction, + pub extending: bool, + pub source: bool, + pub progress: f32, + pub previous_progress: f32, +} +impl MovingPistonState { + pub fn movement_direction(self) -> Direction { + if self.extending { + self.direction + } else { + self.direction.opposite() + } + } + pub fn interpolated_progress(self, partial: f32) -> f32 { + let partial = if partial > 1.0 { 1.0 } else { partial }; + self.previous_progress + partial * (self.progress - self.previous_progress) + } + pub fn interpolated_offset(self, partial: f32) -> [f32; 3] { + self.offset(self.interpolated_progress(partial)) + } + fn offset(self, progress: f32) -> [f32; 3] { + let extended = if self.extending { + progress - 1.0 + } else { + 1.0 - progress + }; + self.direction.normal().map(|step| step as f32 * extended) + } +} +pub trait PistonCollisionWorld { + type Error; + /// The no-entity-context BlockState collision query at the supplied position. + fn collision_shape( + &mut self, + state: BlockStateId, + position: [i32; 3], + ) -> Result; +} +#[derive(Debug)] +pub enum PistonShapeError { + World(E), + Shape(ShapeError), + Registry(io::Error), +} +impl std::fmt::Display for PistonShapeError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::World(e) => e.fmt(f), + Self::Shape(e) => e.fmt(f), + Self::Registry(e) => e.fmt(f), + } + } +} +impl std::error::Error for PistonShapeError {} +struct Base { + extended: BlockStateId, + facing: Direction, + sticky: bool, +} +pub struct PistonBlockBindings<'r> { + registry: &'r BlockRegistry, + bases: BTreeMap, + heads: [[[BlockStateId; 2]; 6]; 2], +} +const DIRECTION_NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"]; +impl<'r> PistonBlockBindings<'r> { + pub fn new(registry: &'r BlockRegistry) -> io::Result { + let mut bases = BTreeMap::new(); + for id in 0..registry.len() { + let id = BlockStateId(id as u32); + let state = registry.state(id).unwrap(); + if !matches!( + state.name.as_str(), + "minecraft:piston" | "minecraft:sticky_piston" + ) { + continue; + } + let facing = state + .properties + .get("facing") + .and_then(|name| DIRECTION_NAMES.iter().position(|v| v == name)) + .ok_or_else(|| invalid("invalid piston facing"))?; + let mut extended = state.clone(); + extended.properties.insert("extended".into(), "true".into()); + bases.insert( + id, + Base { + extended: registry + .id(&extended) + .ok_or_else(|| invalid("missing extended piston state"))?, + facing: Direction::ALL[facing], + sticky: state.name == "minecraft:sticky_piston", + }, + ); + } + let default = registry + .default_state("minecraft:piston_head") + .and_then(|id| registry.state(id)) + .ok_or_else(|| invalid("missing piston head"))?; + let mut heads = [[[BlockStateId(0); 2]; 6]; 2]; + for (kind, type_heads) in heads.iter_mut().enumerate() { + for (direction, variants) in type_heads.iter_mut().enumerate() { + for (short, id) in variants.iter_mut().enumerate() { + let mut state = default.clone(); + state.properties.insert( + "type".into(), + if kind == 0 { "normal" } else { "sticky" }.into(), + ); + state + .properties + .insert("facing".into(), DIRECTION_NAMES[direction].into()); + state + .properties + .insert("short".into(), (short != 0).to_string()); + *id = registry + .id(&state) + .ok_or_else(|| invalid("missing piston head variant"))?; + } + } + } + Ok(Self { + registry, + bases, + heads, + }) + } + fn validate(&self, state: BlockStateId) -> io::Result<()> { + if self.registry.state(state).is_none() { + Err(invalid("piston moved state outside registry")) + } else { + Ok(()) + } + } + /// The collision-related state used by the native entity-pushing path. + /// Its sticky/short/facing rules differ from the entity's own collision head. + pub fn collision_related_state(&self, piston: MovingPistonState) -> io::Result { + self.validate(piston.moved_state)?; + if !piston.extending && piston.source { + if let Some(base) = self.bases.get(&piston.moved_state) { + return Ok(self.heads[usize::from(base.sticky)][base.facing as usize] + [usize::from(piston.progress > 0.25)]); + } + } + Ok(piston.moved_state) + } + pub fn collision_shape( + &self, + world: &mut W, + position: [i32; 3], + piston: MovingPistonState, + noclip: Option, + ) -> Result> { + self.validate(piston.moved_state) + .map_err(PistonShapeError::Registry)?; + let base = if !piston.extending && piston.source { + if let Some(base) = self.bases.get(&piston.moved_state) { + world + .collision_shape(base.extended, position) + .map_err(PistonShapeError::World)? + } else { + VoxelShape::empty() + } + } else { + VoxelShape::empty() + }; + // The stationary base is queried before this native noclip shortcut. + if piston.progress < 1.0 && noclip == Some(piston.movement_direction()) { + return Ok(base); + } + let state = if piston.source { + let short = piston.extending != (1.0f32 - piston.progress < 0.25f32); + self.heads[0][piston.direction as usize][usize::from(short)] + } else { + piston.moved_state + }; + let offset = piston.offset(piston.progress).map(f64::from); + let moving = world + .collision_shape(state, position) + .map_err(PistonShapeError::World)? + .moved(Vec3::new(offset[0], offset[1], offset[2])); + base.join(&moving, ShapeOp::OR) + .map_err(PistonShapeError::Shape) + } +} diff --git a/crates/horizon-world/src/region.rs b/crates/horizon-world/src/region.rs new file mode 100644 index 000000000..48b6e132e --- /dev/null +++ b/crates/horizon-world/src/region.rs @@ -0,0 +1,376 @@ +//! Anvil region reading and export to a new region. Existing files are never +//! overwritten. Use a separate directory for offline edits and copied .mcc data. +use crate::{ + compression::{Compression, invalid}, + nbt::{self, Limits, NamedTag}, +}; +use horizon_core::position::ChunkPos; +use std::{ + fs::{self, File, OpenOptions}, + io::{self, Read, Seek, SeekFrom, Write}, + path::{Path, PathBuf}, + sync::atomic::{AtomicU64, Ordering}, +}; + +const SECTOR: usize = 4096; +const HEADER: usize = SECTOR * 2; +const MAX_COMPRESSED: usize = 64 * 1024 * 1024; + +#[derive(Clone, Debug)] +pub struct ChunkRecord { + pub compression: Compression, + pub compressed: Vec, + pub timestamp: u32, +} +impl ChunkRecord { + pub fn from_nbt( + root: &NamedTag, + compression: Compression, + timestamp: u32, + limits: Limits, + ) -> io::Result { + let bytes = nbt::write_named(root, limits).map_err(|e| invalid(e.to_string()))?; + Ok(Self { + compression, + compressed: compression.encode(&bytes)?, + timestamp, + }) + } + pub fn nbt(&self, limits: Limits) -> io::Result { + let bytes = self + .compression + .decode(&self.compressed, limits.max_bytes)?; + let (root, used) = nbt::read_named(&bytes, limits).map_err(|e| invalid(e.to_string()))?; + if used != bytes.len() { + return Err(invalid("trailing bytes after region chunk NBT")); + } + Ok(root) + } +} + +pub struct RegionFile { + file: File, + path: PathBuf, + position: ChunkPos, + offsets: [u32; 1024], + timestamps: [u32; 1024], +} + +pub fn position_from_path(path: &Path) -> io::Result { + let name = path + .file_name() + .and_then(|s| s.to_str()) + .ok_or_else(|| invalid("invalid region filename"))?; + let parts: Vec<_> = name.split('.').collect(); + if parts.len() != 4 || parts[0] != "r" || parts[3] != "mca" { + return Err(invalid("expected r...mca")); + } + let x: i32 = parts[1] + .parse() + .map_err(|_| invalid("invalid region x coordinate"))?; + let z: i32 = parts[2] + .parse() + .map_err(|_| invalid("invalid region z coordinate"))?; + // Regions outside this range cannot be addressed with signed chunk coordinates. + if !(-67_108_864..=67_108_863).contains(&x) || !(-67_108_864..=67_108_863).contains(&z) { + return Err(invalid("region coordinate outside chunk coordinate range")); + } + Ok(ChunkPos::new(x, z)) +} + +fn slot(region: ChunkPos, chunk: ChunkPos) -> io::Result { + if chunk.region() != region { + return Err(invalid("chunk does not belong to this region")); + } + let (x, z) = chunk.region_local(); + Ok(usize::from(x) + usize::from(z) * 32) +} +fn position(region: ChunkPos, index: usize) -> ChunkPos { + ChunkPos::new( + region.x * 32 + (index % 32) as i32, + region.z * 32 + (index / 32) as i32, + ) +} +fn external_path(directory: &Path, chunk: ChunkPos) -> PathBuf { + directory.join(format!("c.{}.{}.mcc", chunk.x, chunk.z)) +} + +impl RegionFile { + pub fn position(&self) -> ChunkPos { + self.position + } + pub fn open(path: impl AsRef) -> io::Result { + let path = path.as_ref().to_owned(); + let position = position_from_path(&path)?; + let mut file = File::open(&path)?; + let len = file.metadata()?.len(); + if len < HEADER as u64 { + return Err(invalid("truncated region header")); + } + let mut header = [0; HEADER]; + file.read_exact(&mut header)?; + let mut offsets = [0; 1024]; + let mut timestamps = [0; 1024]; + let mut ranges = Vec::new(); + for i in 0..1024 { + offsets[i] = u32::from_be_bytes(header[i * 4..i * 4 + 4].try_into().unwrap()); + timestamps[i] = u32::from_be_bytes( + header[SECTOR + i * 4..SECTOR + i * 4 + 4] + .try_into() + .unwrap(), + ); + if offsets[i] == 0 { + continue; + } + let start = offsets[i] >> 8; + let count = offsets[i] & 255; + if start < 2 || count == 0 || u64::from(start + count) > len.div_ceil(SECTOR as u64) { + return Err(invalid(format!( + "invalid sector allocation at region slot {i}" + ))); + } + ranges.push((start, start + count)); + } + ranges.sort_unstable(); + if ranges.windows(2).any(|r| r[0].1 > r[1].0) { + return Err(invalid("overlapping region sector allocations")); + } + Ok(Self { + file, + path, + position, + offsets, + timestamps, + }) + } + + pub fn chunks(&self) -> impl Iterator + '_ { + self.offsets + .iter() + .enumerate() + .filter(|(_, value)| **value != 0) + .map(|(i, _)| (position(self.position, i), self.timestamps[i])) + } + + pub fn read(&mut self, chunk: ChunkPos) -> io::Result> { + let i = slot(self.position, chunk)?; + let offset = self.offsets[i]; + if offset == 0 { + return Ok(None); + } + self.file + .seek(SeekFrom::Start(u64::from(offset >> 8) * SECTOR as u64))?; + let mut header = [0; 5]; + self.file.read_exact(&mut header)?; + let len = u32::from_be_bytes(header[..4].try_into().unwrap()) as usize; + if len < 1 || len as u64 + 4 > (u64::from(offset & 255) * SECTOR as u64) { + return Err(invalid("invalid chunk payload length")); + } + let compression = Compression::try_from(header[4] & 127)?; + let compressed = if header[4] & 128 != 0 { + if len != 1 { + return Err(invalid("external chunk stub has inline data")); + } + let path = external_path(self.path.parent().unwrap_or(Path::new(".")), chunk); + let file = File::open(path)?; + let mut data = Vec::new(); + file.take((MAX_COMPRESSED + 1) as u64) + .read_to_end(&mut data)?; + if data.len() > MAX_COMPRESSED { + return Err(invalid("external chunk compressed limit exceeded")); + } + data + } else { + let mut data = vec![0; len - 1]; + self.file.read_exact(&mut data)?; + data + }; + Ok(Some(ChunkRecord { + compression, + compressed, + timestamp: self.timestamps[i], + })) + } + + /// Export all chunks, preserving untouched compressed bytes and timestamps. + /// Overrides are keyed by chunk position; None deletes a chunk in the export. + pub fn export( + &mut self, + destination: impl AsRef, + changes: &[(ChunkPos, Option)], + ) -> io::Result<()> { + let destination = destination.as_ref(); + if position_from_path(destination)? != self.position { + return Err(invalid("export region coordinates differ")); + } + let mut replacements = BTreeChanges::new(); + for (chunk, record) in changes { + let i = slot(self.position, *chunk)?; + if replacements.insert(i, record.as_ref()).is_some() { + return Err(invalid("duplicate chunk override")); + } + } + let mut writer = RegionWriter::create(destination)?; + for i in 0..1024 { + let chunk = position(self.position, i); + if let Some(record) = replacements.get(&i) { + if let Some(record) = record { + writer.write(chunk, record)?; + } + } else if let Some(record) = self.read(chunk)? { + writer.write(chunk, &record)?; + } + } + writer.finish() + } +} +type BTreeChanges<'a> = std::collections::BTreeMap>; + +static NEXT_TEMP: AtomicU64 = AtomicU64::new(0); + +/// Writes a complete new region to a temporary sibling, then publishes it with +/// an atomic, non-overwriting hard link. Drop rolls back unpublished files. +pub struct RegionWriter { + file: File, + temporary: PathBuf, + destination: PathBuf, + position: ChunkPos, + offsets: [u32; 1024], + timestamps: [u32; 1024], + next_sector: u32, + externals: Vec, + committed: bool, + failed: bool, +} +impl RegionWriter { + pub fn create(destination: impl AsRef) -> io::Result { + let destination = destination.as_ref().to_owned(); + let position = position_from_path(&destination)?; + if destination.try_exists()? { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "destination region already exists", + )); + } + let parent = destination + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + fs::create_dir_all(parent)?; + let (temporary, file) = loop { + let path = parent.join(format!( + ".horizon-{}-{}.tmp", + std::process::id(), + NEXT_TEMP.fetch_add(1, Ordering::Relaxed) + )); + match OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .open(&path) + { + Ok(file) => break (path, file), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + }; + let mut writer = Self { + file, + temporary, + destination, + position, + offsets: [0; 1024], + timestamps: [0; 1024], + next_sector: 2, + externals: Vec::new(), + committed: false, + failed: false, + }; + writer.file.write_all(&[0; HEADER])?; + Ok(writer) + } + + pub fn write(&mut self, chunk: ChunkPos, record: &ChunkRecord) -> io::Result<()> { + if self.failed { + return Err(invalid("region writer failed previously")); + } + let result = self.write_record(chunk, record); + if result.is_err() { + self.failed = true; + } + result + } + + fn write_record(&mut self, chunk: ChunkPos, record: &ChunkRecord) -> io::Result<()> { + let i = slot(self.position, chunk)?; + if self.offsets[i] != 0 { + return Err(invalid("chunk already written")); + } + if record.compressed.len() > MAX_COMPRESSED { + return Err(invalid("compressed chunk limit exceeded")); + } + let required = (record.compressed.len() + 5).div_ceil(SECTOR); + let external = required >= 256; + let sectors = if external { 1 } else { required as u32 }; + if self.next_sector + sectors > 0x100_0000 { + return Err(invalid("region sector address limit exceeded")); + } + if external { + let path = external_path(self.destination.parent().unwrap_or(Path::new(".")), chunk); + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&path)?; + self.externals.push(path); + file.write_all(&record.compressed)?; + file.sync_all()?; + } + self.file + .seek(SeekFrom::Start(u64::from(self.next_sector) * SECTOR as u64))?; + let len = if external { + 1 + } else { + record.compressed.len() as u32 + 1 + }; + self.file.write_all(&len.to_be_bytes())?; + self.file + .write_all(&[record.compression as u8 | if external { 128 } else { 0 }])?; + if !external { + self.file.write_all(&record.compressed)?; + } + self.offsets[i] = self.next_sector << 8 | sectors; + self.timestamps[i] = record.timestamp; + self.next_sector += sectors; + Ok(()) + } + + pub fn finish(mut self) -> io::Result<()> { + if self.failed { + return Err(invalid("cannot publish a failed region writer")); + } + self.file + .set_len(u64::from(self.next_sector) * SECTOR as u64)?; + self.file.seek(SeekFrom::Start(0))?; + for value in self.offsets { + self.file.write_all(&value.to_be_bytes())?; + } + for value in self.timestamps { + self.file.write_all(&value.to_be_bytes())?; + } + self.file.sync_all()?; + // Hard-link publication fails atomically if another writer won the name. + fs::hard_link(&self.temporary, &self.destination)?; + self.committed = true; + Ok(()) + } +} +impl Drop for RegionWriter { + fn drop(&mut self) { + let _ = fs::remove_file(&self.temporary); + if !self.committed { + for path in &self.externals { + let _ = fs::remove_file(path); + } + } + } +} diff --git a/crates/horizon-world/src/registry.rs b/crates/horizon-world/src/registry.rs new file mode 100644 index 000000000..d5e4acce6 --- /dev/null +++ b/crates/horizon-world/src/registry.rs @@ -0,0 +1,106 @@ +//! Runtime block-state IDs imported from a version-pinned registry data export. +//! This supplies identities and default properties, not block behavior. +mod json; +use crate::{DATA_VERSION, chunk::BlockState, compression::invalid, nbt::Tag}; +pub use json::BlockStateJsonCodec; +use std::{ + collections::{BTreeMap, BTreeSet}, + io, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct BlockStateId(pub u32); + +pub struct BlockRegistry { + states: Vec, + ids: BTreeMap, + defaults: BTreeMap, +} +impl BlockRegistry { + pub fn from_nbt(tag: &Tag) -> io::Result { + if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) { + return Err(invalid("block registry DataVersion mismatch")); + } + let Some(Tag::List(entries)) = tag.get("states") else { + return Err(invalid("missing registry states")); + }; + let Some(Tag::Compound(defaults)) = tag.get("defaults") else { + return Err(invalid("missing registry defaults")); + }; + if entries.is_empty() || entries.len() > i32::MAX as usize { + return Err(invalid("invalid registry size")); + } + let mut result = Self { + states: Vec::with_capacity(entries.len()), + ids: BTreeMap::new(), + defaults: BTreeMap::new(), + }; + for (i, entry) in entries.iter().enumerate() { + let state = BlockState::from_nbt(entry)?; + if result + .ids + .insert(state.clone(), BlockStateId(i as u32)) + .is_some() + { + return Err(invalid("duplicate block registry state")); + } + result.states.push(state); + } + for (name, id) in defaults { + let name = name.to_string().map_err(|e| invalid(e.to_string()))?; + let Tag::Int(id) = id else { + return Err(invalid("default state ID is not an int")); + }; + if *id < 0 + || result + .states + .get(*id as usize) + .is_none_or(|s| s.name != name) + { + return Err(invalid("invalid default block state ID")); + } + result.defaults.insert(name, BlockStateId(*id as u32)); + } + let names: BTreeSet<_> = result.states.iter().map(|s| &s.name).collect(); + if names.len() != result.defaults.len() + || names + .iter() + .any(|name| !result.defaults.contains_key(*name)) + { + return Err(invalid("registry is missing block defaults")); + } + Ok(result) + } + pub fn len(&self) -> usize { + self.states.len() + } + pub fn is_empty(&self) -> bool { + self.states.is_empty() + } + pub fn state(&self, id: BlockStateId) -> Option<&BlockState> { + self.states.get(id.0 as usize) + } + pub fn id(&self, state: &BlockState) -> Option { + self.ids.get(state).copied() + } + pub fn default_state(&self, name: &str) -> Option { + self.defaults.get(name).copied() + } + + /// Resolve a saved descriptor, supplying omitted default properties. Unlike + /// vanilla's lenient logging paths, invalid properties return a typed error. + pub fn resolve(&self, descriptor: &BlockState) -> io::Result { + let default = self + .default_state(&descriptor.name) + .ok_or_else(|| invalid("unknown block name"))?; + let mut state = self.state(default).unwrap().clone(); + for (key, value) in &descriptor.properties { + if !state.properties.contains_key(key) { + return Err(invalid("unknown block property")); + } + state.properties.insert(key.clone(), value.clone()); + } + self.id(&state) + .ok_or_else(|| invalid("invalid block property value")) + } +} diff --git a/crates/horizon-world/src/registry/json.rs b/crates/horizon-world/src/registry/json.rs new file mode 100644 index 000000000..664a7e1d9 --- /dev/null +++ b/crates/horizon-world/src/registry/json.rs @@ -0,0 +1,135 @@ +//! Java 26.3 compact/full block-state JSON codecs over a pinned registry. +use super::{BlockRegistry, BlockStateId}; +use crate::compression::invalid; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + io, +}; + +/// Property kinds accompany the imported state registry. Integer properties +/// parse Java decimal strings; enum and boolean properties use exact names. +pub struct BlockStateJsonCodec<'a> { + registry: &'a BlockRegistry, + integers: BTreeSet<(String, String)>, + counts: BTreeMap, +} +impl<'a> BlockStateJsonCodec<'a> { + pub fn new( + registry: &'a BlockRegistry, + integers: BTreeSet<(String, String)>, + ) -> io::Result { + for (block, property) in &integers { + let state = registry + .default_state(block) + .and_then(|id| registry.state(id)); + if !state.is_some_and(|state| state.properties.contains_key(property)) { + return Err(invalid("integer property is absent from block registry")); + } + } + let mut counts = BTreeMap::new(); + for state in ®istry.states { + *counts.entry(state.name.clone()).or_insert(0) += 1; + } + Ok(Self { + registry, + integers, + counts, + }) + } + /// `full` selects FULL_CODEC, which requires the object representation. + /// Invalid/missing properties keep their defaults, as vanilla's codec does. + pub fn decode(&self, json: &str, full: bool) -> io::Result { + let value: Value = serde_json::from_str(json).map_err(|e| invalid(e.to_string()))?; + let name = if !full && value.is_string() { + value.as_str() + } else { + value.get("id").and_then(Value::as_str) + } + .ok_or_else(|| invalid("missing block identifier"))?; + let (namespace, path) = name.split_once(':').unwrap_or(("minecraft", name)); + let name = format!( + "{}:{path}", + if namespace.is_empty() { + "minecraft" + } else { + namespace + } + ); + let default = self + .registry + .default_state(&name) + .ok_or_else(|| invalid("unknown block identifier"))?; + let mut state = self.registry.state(default).unwrap().clone(); + if let Some(properties) = value.get("properties").and_then(Value::as_object) { + for (key, raw) in properties { + if !state.properties.contains_key(key) { + continue; + } + let Some(value) = raw.as_str() else { + continue; + }; + let candidate = if self.integers.contains(&(name.clone(), key.clone())) { + let Some(value) = java_integer(value) else { + continue; + }; + value.to_string() + } else { + value.to_owned() + }; + let previous = state.properties.insert(key.clone(), candidate).unwrap(); + if self.registry.id(&state).is_none() { + state.properties.insert(key.clone(), previous); + } + } + } + self.registry + .id(&state) + .ok_or_else(|| invalid("block state is absent from registry")) + } + pub fn encode(&self, id: BlockStateId, full: bool) -> io::Result { + let state = self + .registry + .state(id) + .ok_or_else(|| invalid("unknown block state ID"))?; + let value = if !full && self.registry.default_state(&state.name) == Some(id) { + Value::String(state.name.clone()) + } else if self.counts[&state.name] == 1 { + serde_json::json!({"id":state.name}) + } else { + serde_json::json!({"id":state.name,"properties":state.properties}) + }; + serde_json::to_string(&value).map_err(|e| invalid(e.to_string())) + } +} + +fn java_integer(text: &str) -> Option { + let (negative, text) = if let Some(text) = text.strip_prefix('-') { + (true, text) + } else { + (false, text.strip_prefix('+').unwrap_or(text)) + }; + if text.is_empty() { + return None; + } + // BMP decimal digit runs accepted by Character.digit(char, 10) in JDK 25. + const ZEROES: [u32; 37] = [ + 0x30, 0x660, 0x6f0, 0x7c0, 0x966, 0x9e6, 0xa66, 0xae6, 0xb66, 0xbe6, 0xc66, 0xce6, 0xd66, + 0xde6, 0xe50, 0xed0, 0xf20, 0x1040, 0x1090, 0x17e0, 0x1810, 0x1946, 0x19d0, 0x1a80, 0x1a90, + 0x1b50, 0x1bb0, 0x1c40, 0x1c50, 0xa620, 0xa8d0, 0xa900, 0xa9d0, 0xa9f0, 0xaa50, 0xabf0, + 0xff10, + ]; + let mut value = 0i64; + for c in text.chars() { + let c = c as u32; + let zero = ZEROES + .iter() + .copied() + .find(|zero| c >= *zero && c < *zero + 10)?; + value = value * 10 + i64::from(c - zero); + if value > i64::from(i32::MAX) + i64::from(negative) { + return None; + } + } + Some(if negative { -value } else { value } as i32) +} diff --git a/crates/horizon-world/src/tick_data.rs b/crates/horizon-world/src/tick_data.rs new file mode 100644 index 000000000..e316f7a79 --- /dev/null +++ b/crates/horizon-world/src/tick_data.rs @@ -0,0 +1,81 @@ +//! Save-format bridge for scheduled block/fluid ticks. Registry identity is +//! supplied by the caller; this module does not implement either type's behavior. +use crate::{compression::invalid, nbt::Tag}; +use horizon_core::{ + position::BlockPos, + ticks::{SavedTick, TickPriority, TickTypeId}, +}; +use std::io; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TickKind { + Block, + Fluid, +} +impl TickKind { + pub const fn field(self) -> &'static str { + match self { + Self::Block => "block_ticks", + Self::Fluid => "fluid_ticks", + } + } +} + +pub fn read_list( + tag: &Tag, + mut resolve: impl FnMut(&str) -> Option, +) -> io::Result> { + let Tag::List(entries) = tag else { + return Err(invalid("saved ticks are not a list")); + }; + entries + .iter() + .map(|entry| { + let Some(Tag::String(name)) = entry.get("i") else { + return Err(invalid("saved tick is missing type name")); + }; + let name = name.to_string().map_err(|e| invalid(e.to_string()))?; + let kind = resolve(&name).ok_or_else(|| invalid("unknown saved tick type"))?; + let int = |key| { + // NbtOps/Codec.INT use Number.intValue, including narrowing + // longs and Java's saturating float conversion. + match entry.get(key) { + Some(Tag::Byte(v)) => Ok(i32::from(*v)), + Some(Tag::Short(v)) => Ok(i32::from(*v)), + Some(Tag::Int(v)) => Ok(*v), + Some(Tag::Long(v)) => Ok(*v as i32), + Some(Tag::Float(v)) => Ok(f32::from_bits(*v) as i32), + Some(Tag::Double(v)) => Ok(f64::from_bits(*v) as i32), + _ => Err(invalid(format!("saved tick is missing number {key}"))), + } + }; + Ok(SavedTick { + kind, + pos: BlockPos::new(int("x")?, int("y")?, int("z")?), + delay: int("t")?, + priority: TickPriority::by_value(int("p")?), + }) + }) + .collect() +} + +pub fn write_list( + ticks: &[SavedTick], + mut name: impl FnMut(TickTypeId) -> Option, +) -> io::Result { + let entries = ticks + .iter() + .map(|tick| { + let name = name(tick.kind).ok_or_else(|| invalid("unknown saved tick type ID"))?; + Ok(Tag::compound([ + ("i", Tag::String(name.as_str().into())), + ("x", Tag::Int(tick.pos.x)), + ("y", Tag::Int(tick.pos.y)), + ("z", Tag::Int(tick.pos.z)), + ("t", Tag::Int(tick.delay)), + ("p", Tag::Int(tick.priority as i32)), + ])) + }) + .collect::>>()?; + Ok(Tag::List(entries)) +} diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs new file mode 100644 index 000000000..8642bdc08 --- /dev/null +++ b/crates/horizon-world/src/worldgen.rs @@ -0,0 +1,258 @@ +//! Version-specific noise, density registry and terrain-router JSON decoding. +//! Complete terrain generation remains pending. +pub mod anchor; +pub mod aquifer; +pub mod biome; +pub mod biome_chunk; +pub mod biome_predicate; +pub mod biome_source; +pub mod biome_temperature; +pub mod block_feature; +pub mod block_predicate; +pub mod bulk_section; +pub mod carver; +pub mod carving; +pub mod climate; +pub mod decoration; +pub mod density; +pub mod feature; +pub mod feature_catalog; +pub mod feature_graph; +pub mod feature_region; +pub mod feature_sort; +pub mod fluid_predicate; +pub mod height_provider; +pub mod material_condition; +pub mod material_extensions; +pub mod material_stage; +pub mod material_surface; +pub mod ore_feature; +pub mod placement; +pub mod router; +pub mod rule_test; +pub mod settings; +pub mod state_provider; +pub mod tags; +pub mod terrain; +pub mod value_provider; +pub mod weighted; +use horizon_core::noise::{NoiseBuildError, NormalNoise, Normalization}; +use serde_json::value::RawValue; +use std::collections::BTreeMap; + +#[derive(Debug)] +pub enum DecodeError { + Json(serde_json::Error), + Field(&'static str), + Noise(NoiseBuildError), + Graph(horizon_core::density::graph::CompileError), + Sample(horizon_core::density::SampleError), + Registry(String), +} +impl std::fmt::Display for DecodeError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Json(error) => error.fmt(f), + Self::Field(field) => write!(f, "invalid world generation field: {field}"), + Self::Noise(error) => error.fmt(f), + Self::Graph(error) => error.fmt(f), + Self::Sample(error) => error.fmt(f), + Self::Registry(error) => f.write_str(error), + } + } +} +impl std::error::Error for DecodeError {} +impl From for DecodeError { + fn from(value: serde_json::Error) -> Self { + Self::Json(value) + } +} +impl From for DecodeError { + fn from(value: NoiseBuildError) -> Self { + Self::Noise(value) + } +} + +impl From for DecodeError { + fn from(value: horizon_core::density::graph::CompileError) -> Self { + Self::Graph(value) + } +} + +impl From for DecodeError { + fn from(value: horizon_core::density::SampleError) -> Self { + Self::Sample(value) + } +} + +type Object = BTreeMap>; +fn optional<'a>(object: &'a Object, name: &str) -> Option<&'a RawValue> { + object + .get(name) + .map(AsRef::as_ref) + .filter(|raw| raw.get() != "null") +} +fn required<'a>(object: &'a Object, name: &'static str) -> Result<&'a RawValue, DecodeError> { + optional(object, name).ok_or(DecodeError::Field(name)) +} +fn number_text(raw: &RawValue) -> Result<&str, DecodeError> { + let text = raw.get(); + if text.starts_with('-') || text.starts_with(|c: char| c.is_ascii_digit()) { + Ok(text) + } else { + Err(DecodeError::Field("number")) + } +} +fn double(raw: &RawValue) -> Result { + number_text(raw)? + .parse() + .map_err(|_| DecodeError::Field("number")) +} + +// Gson's lazily parsed numbers use BigDecimal.intValue for decimal/exponent +// forms: truncate toward zero, then retain the low 32 bits. Converting through +// f64 would both round large integers and saturate rather than wrap. +fn integer(raw: &RawValue) -> Result { + let text = number_text(raw)?; + let negative = text.starts_with('-'); + let text = text.strip_prefix('-').unwrap_or(text); + let (mantissa, exponent) = match text.split_once(['e', 'E']) { + Some((mantissa, exponent)) => ( + mantissa, + exponent + .parse::() + .map_err(|_| DecodeError::Field("integer exponent"))? as i64, + ), + None => (text, 0), + }; + let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, "")); + let digits = whole.bytes().chain(fraction.bytes()); + let length = whole.len() as i64 + exponent; + if length <= 0 { + return Ok(0); + } + let available = whole.len() as i64 + fraction.len() as i64; + let zeroes = (length - available).max(0); + if zeroes >= 32 { + return Ok(0); + } + let mut result = 0u32; + for digit in digits.take(length as usize) { + result = result + .wrapping_mul(10) + .wrapping_add(u32::from(digit - b'0')); + } + for _ in 0..zeroes { + result = result.wrapping_mul(10); + } + Ok(if negative { + result.wrapping_neg() + } else { + result + } as i32) +} +fn int_range(raw: &RawValue, name: &'static str, low: i32, high: i32) -> Result { + let value = integer(raw)?; + if (low..=high).contains(&value) { + Ok(value) + } else { + Err(DecodeError::Field(name)) + } +} +fn double_range( + raw: &RawValue, + name: &'static str, + low: f64, + high: f64, +) -> Result { + let value = double(raw)?; + if value.total_cmp(&low).is_ge() && value.total_cmp(&high).is_le() { + Ok(value) + } else { + Err(DecodeError::Field(name)) + } +} + +/// Decode Java Edition 26.3's direct normal-noise parameters from strict JSON. +/// Numeric tokens retain their decimal text; all rounding occurs at the target +/// numeric width. Unknown object fields are ignored, as in vanilla's codec. +pub fn decode_noise(json: &str) -> Result { + let object: Object = serde_json::from_str(json)?; + let base = int_range(required(&object, "base_octave")?, "base_octave", -32, 32)?; + let count = optional(&object, "octave_count") + .map(|raw| int_range(raw, "octave_count", 1, 32)) + .transpose()? + .unwrap_or(1); + let amplitude = optional(&object, "base_amplitude") + .map(|raw| double_range(raw, "base_amplitude", 1e-5f32 as f64, 1e6)) + .transpose()? + .unwrap_or(1.0); + let normalize = match optional(&object, "normalize") { + None => Normalization::Enabled, + Some(raw) => match raw.get() { + "true" => Normalization::Enabled, + "false" => Normalization::Disabled, + text if text.starts_with('"') && serde_json::from_str::(text)? == "legacy" => { + Normalization::Legacy + } + _ => return Err(DecodeError::Field("normalize")), + }, + }; + let modifiers: Vec> = optional(&object, "amplitude_modifiers") + .map(|raw| serde_json::from_str(raw.get())) + .transpose()? + .unwrap_or_default(); + if modifiers.len() > 32 || (!modifiers.is_empty() && modifiers.len() != count as usize) { + return Err(DecodeError::Field("amplitude_modifiers")); + } + let mut builder = NormalNoise::builder(); + builder + .set_base_octave(base) + .set_base_amplitude(amplitude) + .set_normalization(normalize); + builder.set_octave_count(count)?; + for (index, modifier) in modifiers.iter().enumerate() { + builder.set_amplitude_modifier( + index as i32, + double_range(modifier, "amplitude_modifiers", 0.0, 1e6)?, + )?; + } + Ok(builder.build()?) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn decimal_integers_wrap_without_floating_point_conversion() { + for (text, expected) in [ + ("4294967295", -1), + ("4294967296.5", 0), + ("-4294967297.9", -1), + ("1.9999999999999999999", 1), + ("12e1", 120), + ("123e-1", 12), + ("-123e-3", 0), + ("123e99", 0), + ] { + let raw: Box = serde_json::from_str(text).unwrap(); + assert_eq!(integer(&raw).unwrap(), expected, "{text}"); + } + } + #[test] + fn codec_defaults_and_empty_modifiers_match_explicit_parameters() { + let a = decode_noise(r#"{"base_octave":-7}"#).unwrap(); + let b = decode_noise(r#"{"base_octave":-7,"base_amplitude":1,"octave_count":1,"normalize":true,"amplitude_modifiers":[],"unknown":42}"#).unwrap(); + assert_eq!(a.range(), b.range()); + assert_eq!(a.normalization_factor(), b.normalization_factor()); + assert_eq!(a.octaves().len(), b.octaves().len()); + assert!(decode_noise(r#"{"base_octave":-7,"octave_count":0}"#).is_err()); + assert!(decode_noise(r#"{"base_octave":-7,"normalize":0}"#).is_err()); + assert!(decode_noise(r#"{"base_octave":-7,"amplitude_modifiers":[-0]}"#).is_err()); + assert!(decode_noise(r#"{"base_octave":-7,"amplitude_modifiers":[-0.0]}"#).is_err()); + assert!( + decode_noise(r#"{"base_octave":-7,"octave_count":2,"amplitude_modifiers":[1]}"#) + .is_err() + ); + } +} diff --git a/crates/horizon-world/src/worldgen/anchor.rs b/crates/horizon-world/src/worldgen/anchor.rs new file mode 100644 index 000000000..741a57dd0 --- /dev/null +++ b/crates/horizon-world/src/worldgen/anchor.rs @@ -0,0 +1,102 @@ +//! Vertical anchors and their generation bounds in Java Edition 26.3. +use super::{DecodeError, Object, int_range, required}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct WorldGenerationContext { + pub min_y: i32, + pub height: i32, + pub sea_level: i32, +} +impl WorldGenerationContext { + pub const fn new(min_y: i32, height: i32, sea_level: i32) -> Self { + Self { + min_y, + height, + sea_level, + } + } + + /// Vanilla combines the two minima and heights independently. This is + /// deliberately different from intersecting the two vertical intervals. + pub fn with_generator( + level_min: i32, + level_height: i32, + generator_min: i32, + generator_height: i32, + generator_sea_level: i32, + ) -> Self { + Self::new( + level_min.max(generator_min), + level_height.min(generator_height), + generator_sea_level, + ) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum VerticalAnchor { + Absolute(i32), + AboveBottom(i32), + BelowTop(i32), + RelativeToSeaLevel(i32), +} +impl VerticalAnchor { + pub const BOTTOM: Self = Self::AboveBottom(0); + pub const TOP: Self = Self::BelowTop(0); + pub const SEA_LEVEL: Self = Self::RelativeToSeaLevel(0); + + /// Runtime anchors accept every signed integer, with Java wrapping. + pub fn resolve(self, context: WorldGenerationContext) -> i32 { + match self { + Self::Absolute(y) => y, + Self::AboveBottom(offset) => context.min_y.wrapping_add(offset), + Self::BelowTop(offset) => context + .height + .wrapping_sub(1) + .wrapping_add(context.min_y) + .wrapping_sub(offset), + Self::RelativeToSeaLevel(offset) => context.sea_level.wrapping_add(offset), + } + } + + pub fn from_json(json: &str) -> Result { + let object: Object = serde_json::from_str(json)?; + let field = |name| { + required(&object, name) + .and_then(|raw| int_range(raw, name, -2032, 2031)) + .ok() + }; + // The codec nests exclusive alternatives. An ambiguous inner choice + // fails that branch, allowing a valid outer branch to succeed. + let exclusive = |left, right| match (left, right) { + (Some(value), None) | (None, Some(value)) => Some(value), + _ => None, + }; + exclusive( + field("absolute").map(Self::Absolute), + exclusive( + field("above_bottom").map(Self::AboveBottom), + exclusive( + field("below_top").map(Self::BelowTop), + field("relative_to_sea_level").map(Self::RelativeToSeaLevel), + ), + ), + ) + .ok_or(DecodeError::Field("vertical anchor")) + } + + /// Encode through the same field bounds as the vanilla codec. Constructed + /// runtime anchors can resolve successfully while failing this validation. + pub fn to_json(self) -> Result { + let (name, value) = match self { + Self::Absolute(y) => ("absolute", y), + Self::AboveBottom(offset) => ("above_bottom", offset), + Self::BelowTop(offset) => ("below_top", offset), + Self::RelativeToSeaLevel(offset) => ("relative_to_sea_level", offset), + }; + if !(-2032..=2031).contains(&value) { + return Err(DecodeError::Field("vertical anchor")); + } + Ok(format!("{{\"{name}\":{value}}}")) + } +} diff --git a/crates/horizon-world/src/worldgen/aquifer.rs b/crates/horizon-world/src/worldgen/aquifer.rs new file mode 100644 index 000000000..2b4f6e7c3 --- /dev/null +++ b/crates/horizon-world/src/worldgen/aquifer.rs @@ -0,0 +1,100 @@ +//! Global fluid selection and the 26.3 aquifer terrain paths. +mod config; +mod noise_based; +use crate::registry::BlockStateId; +pub use config::{AquiferConfig, AquiferField, AquiferSamplers}; +pub use noise_based::{ + AquiferBlockStates, AquiferError, NoiseBasedAquifer, RegistryAquiferBlockStates, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FluidStatus { + pub level: i32, + pub state: BlockStateId, +} +impl FluidStatus { + pub const fn at(self, y: i32, air: BlockStateId) -> BlockStateId { + if y < self.level { self.state } else { air } + } +} +pub trait FluidPicker: std::fmt::Debug + Send + Sync { + fn compute(&self, position: [i32; 3]) -> FluidStatus; +} +impl FluidPicker for &P { + fn compute(&self, position: [i32; 3]) -> FluidStatus { + P::compute(self, position) + } +} +/// State IDs must come from one immutable block registry. Default fluid can be +/// any registered block state; vanilla does not validate its material here. +#[derive(Clone, Copy, Debug)] +pub struct GlobalFluidPicker { + sea_level: i32, + default_fluid: BlockStateId, + lava: BlockStateId, + air: BlockStateId, + disabled: bool, +} +impl GlobalFluidPicker { + pub const fn new( + sea_level: i32, + default_fluid: BlockStateId, + lava: BlockStateId, + air: BlockStateId, + ) -> Self { + Self { + sea_level, + default_fluid, + lava, + air, + disabled: false, + } + } + /// Matches the vanilla developer flag. Regular gameplay keeps this false. + pub const fn with_disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } +} +impl FluidPicker for GlobalFluidPicker { + fn compute(&self, [_, y, _]: [i32; 3]) -> FluidStatus { + if self.disabled { + FluidStatus { + level: -4064, + state: self.air, + } + } else if y < (-54).min(self.sea_level) { + FluidStatus { + level: -54, + state: self.lava, + } + } else { + FluidStatus { + level: self.sea_level, + state: self.default_fluid, + } + } + } +} +#[derive(Debug)] +pub struct DisabledAquifer

{ + picker: P, + air: BlockStateId, +} +impl DisabledAquifer

{ + pub const fn new(picker: P, air: BlockStateId) -> Self { + Self { picker, air } + } + /// None selects the generator's default solid block. Java DCMPL treats NaN + /// as -1, so NaN and density <= zero call the picker; density > zero does not. + pub fn compute_substance(&self, position: [i32; 3], density: f64) -> Option { + if density > 0. { + None + } else { + Some(self.picker.compute(position).at(position[1], self.air)) + } + } + pub const fn should_schedule_fluid_update(&self) -> bool { + false + } +} diff --git a/crates/horizon-world/src/worldgen/aquifer/config.rs b/crates/horizon-world/src/worldgen/aquifer/config.rs new file mode 100644 index 000000000..984fe59e8 --- /dev/null +++ b/crates/horizon-world/src/worldgen/aquifer/config.rs @@ -0,0 +1,127 @@ +//! The six density roots in the 26.3 aquifer configuration. +use super::super::{DecodeError, Object, density::DensityRegistry, required}; +use horizon_core::density::{ + DensitySampler, + graph::{CompileError, DensityCompiler, FunctionId}, +}; +use std::sync::Arc; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(usize)] +pub enum AquiferField { + Barrier, + Floodedness, + Spread, + Lava, + Exclusion, + SurfaceLevel, +} +impl AquiferField { + pub const ALL: [Self; 6] = [ + Self::Barrier, + Self::Floodedness, + Self::Spread, + Self::Lava, + Self::Exclusion, + Self::SurfaceLevel, + ]; + pub const fn name(self) -> &'static str { + match self { + Self::Barrier => "barrier", + Self::Floodedness => "fluid_level_floodedness", + Self::Spread => "fluid_level_spread", + Self::Lava => "lava", + Self::Exclusion => "exclusion", + Self::SurfaceLevel => "surface_level", + } + } +} +#[derive(Clone, Copy, Debug)] +pub struct AquiferConfig { + functions: [FunctionId; 6], +} +impl AquiferConfig { + /// Decode all roots atomically into the caller's registry graph. + pub fn from_json(json: &str, registry: &mut DensityRegistry) -> Result { + let object: Object = serde_json::from_str(json)?; + let inputs = AquiferField::ALL + .iter() + .map(|f| required(&object, f.name()).map(|v| v.get())) + .collect::, _>>()?; + let functions = registry + .decode_functions(&inputs)? + .try_into() + .map_err(|_| DecodeError::Field("aquifer field count"))?; + Ok(Self { functions }) + } + pub fn function(self, field: AquiferField) -> FunctionId { + self.functions[field as usize] + } + /// Preserve vanilla's binding order and the shared compiler cache namespace. + pub fn compile(self, compiler: &mut DensityCompiler) -> Result { + let samplers = self + .functions + .iter() + .map(|id| compiler.get_sampler(*id)) + .collect::, _>>()? + .try_into() + .expect("six aquifer roots"); + Ok(AquiferSamplers { samplers }) + } +} +#[derive(Debug)] +pub struct AquiferSamplers { + samplers: [Arc; 6], +} +impl AquiferSamplers { + /// Bind already compiled roots in AquiferField::ALL order. + pub fn new(samplers: [Arc; 6]) -> Self { + Self { samplers } + } + pub fn get(&self, field: AquiferField) -> &Arc { + &self.samplers[field as usize] + } +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::density::{SamplerContext, graph::GraphNode}; + use std::collections::BTreeMap; + #[test] + fn bindings_share_named_cache_and_failed_decode_is_atomic() { + let mut registry = DensityRegistry::from_json(&BTreeMap::new(), &BTreeMap::from([("minecraft:shared".into(), r#"{"type":"cache","input":{"type":"gradient","axis":"x","from_coordinate":0,"to_coordinate":16,"from_value":0,"to_value":1}}"#.into())])).unwrap(); + let roots: BTreeMap<_, _> = AquiferField::ALL + .iter() + .map(|f| (f.name(), "minecraft:shared")) + .collect(); + let json = serde_json::to_string(&roots).unwrap(); + let expected = registry + .graph() + .clone() + .insert(GraphNode::Constant(123.)) + .unwrap(); + let invalid = json + .replace("\"barrier\":\"minecraft:shared\"", "\"barrier\":123") + .replace( + "\"surface_level\":\"minecraft:shared\"", + "\"surface_level\":{}", + ); + assert!(AquiferConfig::from_json(&invalid, &mut registry).is_err()); + assert_eq!(registry.decode_functions(&["123"]).unwrap()[0], expected); + let config = AquiferConfig::from_json(&json, &mut registry).unwrap(); + let mut compiler = DensityCompiler::new_seeded(registry.into_graph(), 0, false); + let samplers = config.compile(&mut compiler).unwrap(); + assert_eq!(compiler.cache_count(), 1); + let mut context = SamplerContext::cached(); + for field in AquiferField::ALL { + assert_eq!( + samplers + .get(field) + .sample_value(&mut context, [4, -54, 0]) + .unwrap(), + 0.25 + ); + } + } +} diff --git a/crates/horizon-world/src/worldgen/aquifer/noise_based.rs b/crates/horizon-world/src/worldgen/aquifer/noise_based.rs new file mode 100644 index 000000000..30181686b --- /dev/null +++ b/crates/horizon-world/src/worldgen/aquifer/noise_based.rs @@ -0,0 +1,578 @@ +//! Stateful 26.3 underground fluid and pressure selection. +use super::{AquiferField, AquiferSamplers, FluidPicker, FluidStatus}; +use crate::registry::{BlockRegistry, BlockStateId}; +use horizon_core::{ + density::{SampleError, SamplerContext}, + noise::{DensityError, DensityVolume}, + position::{BlockPos, ChunkPos}, + random::{PositionalRandom, RandomSource}, +}; +use std::collections::HashMap; + +const WAY_BELOW_MIN_Y: i32 = -32512; +const FLOWING_UPDATE_SIMILARITY: f64 = 1.0 - 44.0 / 25.0; +const SURFACE_OFFSETS: [[i32; 2]; 13] = [ + [0, 0], + [-2, -1], + [-1, -1], + [0, -1], + [1, -1], + [-3, 0], + [-2, 0], + [-1, 0], + [1, 0], + [-2, 1], + [-1, 1], + [0, 1], + [1, 1], +]; + +/// All IDs and block classifications must refer to the same immutable registry. +/// Lava/water tests classify the block, whereas default-lava equality tests the +/// exact state. Air tests include cave air and void air. +pub trait AquiferBlockStates { + fn air(&self) -> BlockStateId; + fn lava(&self) -> BlockStateId; + fn is_air(&self, state: BlockStateId) -> bool; + fn is_lava(&self, state: BlockStateId) -> bool; + fn is_water(&self, state: BlockStateId) -> bool; +} +pub struct RegistryAquiferBlockStates<'a> { + registry: &'a BlockRegistry, + air: BlockStateId, + lava: BlockStateId, +} +impl<'a> RegistryAquiferBlockStates<'a> { + pub fn new(registry: &'a BlockRegistry) -> Result { + Ok(Self { + registry, + air: registry + .default_state("minecraft:air") + .ok_or(AquiferError::MissingBlock)?, + lava: registry + .default_state("minecraft:lava") + .ok_or(AquiferError::MissingBlock)?, + }) + } + fn name(&self, state: BlockStateId) -> Option<&str> { + self.registry.state(state).map(|s| s.name.as_str()) + } +} +impl AquiferBlockStates for RegistryAquiferBlockStates<'_> { + fn air(&self) -> BlockStateId { + self.air + } + fn lava(&self) -> BlockStateId { + self.lava + } + fn is_air(&self, state: BlockStateId) -> bool { + matches!( + self.name(state), + Some("minecraft:air" | "minecraft:cave_air" | "minecraft:void_air") + ) + } + fn is_lava(&self, state: BlockStateId) -> bool { + self.name(state) == Some("minecraft:lava") + } + fn is_water(&self, state: BlockStateId) -> bool { + self.name(state) == Some("minecraft:water") + } +} +#[derive(Debug)] +pub enum AquiferError { + Sample(SampleError), + InvalidGrid, + OutsideGrid, + Allocation, + MissingBlock, +} +impl From for AquiferError { + fn from(value: SampleError) -> Self { + Self::Sample(value) + } +} +impl From for AquiferError { + fn from(value: DensityError) -> Self { + Self::Sample(value.into()) + } +} +impl std::fmt::Display for AquiferError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Sample(e) => e.fmt(f), + Self::InvalidGrid => f.write_str("aquifer grid is invalid or exceeds 16777216 cells"), + Self::OutsideGrid => f.write_str("aquifer query lies outside its grid"), + Self::Allocation => f.write_str("aquifer allocation failed"), + Self::MissingBlock => f.write_str("aquifer registry lacks default air or lava"), + } + } +} +impl std::error::Error for AquiferError {} + +pub struct NoiseBasedAquifer { + samplers: AquiferSamplers, + picker: P, + random: F, + blocks: B, + minimum: [i32; 3], + size_x: i32, + size_z: i32, + statuses: Vec>, + locations: Vec, + surfaces: HashMap, + skip_above_y: i32, + schedule: bool, +} +impl NoiseBasedAquifer { + /// The positional factory is the caller's aquifer factory, not the world's + /// unmodified factory. Every sampler uses the caller's shared context. + pub fn new( + samplers: AquiferSamplers, + picker: P, + random: F, + blocks: B, + volume: DensityVolume, + context: &mut SamplerContext, + ) -> Result { + let low = volume.minimum(); + let high = volume.maximum(); + let minimum = [ + low[0].wrapping_sub(5) >> 4, + low[1].wrapping_add(1).div_euclid(12).wrapping_sub(1), + low[2].wrapping_sub(5) >> 4, + ]; + let maximum = [ + (high[0].wrapping_sub(5) >> 4).wrapping_add(1), + high[1].wrapping_add(1).div_euclid(12).wrapping_add(1), + (high[2].wrapping_sub(5) >> 4).wrapping_add(1), + ]; + let sizes: [i32; 3] = + std::array::from_fn(|i| maximum[i].wrapping_sub(minimum[i]).wrapping_add(1)); + let count = sizes + .into_iter() + .try_fold(1usize, |n, s| { + if s > 0 { + n.checked_mul(s as usize) + } else { + None + } + }) + .filter(|n| *n <= 16_777_216) + .ok_or(AquiferError::InvalidGrid)?; + let mut statuses = Vec::new(); + statuses + .try_reserve_exact(count) + .map_err(|_| AquiferError::Allocation)?; + statuses.resize(count, None); + let mut locations = Vec::new(); + locations + .try_reserve_exact(count) + .map_err(|_| AquiferError::Allocation)?; + locations.resize(count, i64::MAX); + let mut result = Self { + samplers, + picker, + random, + blocks, + minimum, + size_x: sizes[0], + size_z: sizes[2], + statuses, + locations, + surfaces: HashMap::new(), + skip_above_y: 0, + schedule: false, + }; + let max_surface = result + .max_surface_level( + context, + [minimum[0].wrapping_shl(4), minimum[2].wrapping_shl(4)], + [ + maximum[0].wrapping_shl(4).wrapping_add(9), + maximum[2].wrapping_shl(4).wrapping_add(9), + ], + )? + .wrapping_add(8); + let skip_grid = max_surface.wrapping_add(12).div_euclid(12).wrapping_add(1); + result.skip_above_y = skip_grid.wrapping_mul(12).wrapping_add(11).wrapping_sub(1); + Ok(result) + } + /// Read-only diagnostic state; enumeration never populates a cache. + pub fn cached_cells(&self) -> impl Iterator)> + '_ { + self.locations + .iter() + .copied() + .zip(self.statuses.iter().copied()) + } + pub fn cached_surfaces(&self) -> impl Iterator + '_ { + self.surfaces.iter().map(|(key, value)| (*key, *value)) + } + pub fn should_schedule_fluid_update(&self) -> bool { + self.schedule + } + pub fn skip_sampling_above_y(&self) -> i32 { + self.skip_above_y + } + fn sample( + &self, + field: AquiferField, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + Ok(self.samplers.get(field).sample_value(context, position)? as f64) + } + fn surface_level( + &mut self, + context: &mut SamplerContext, + x: i32, + z: i32, + ) -> Result { + let x = (x >> 2).wrapping_shl(2); + let z = (z >> 2).wrapping_shl(2); + let key = ChunkPos::new(x, z).pack(); + if let Some(level) = self.surfaces.get(&key) { + return Ok(*level); + } + let level = self + .sample(AquiferField::SurfaceLevel, context, [x, 0, z])? + .floor() as i32; + self.surfaces.insert(key, level); + Ok(level) + } + fn max_surface_level( + &mut self, + context: &mut SamplerContext, + minimum: [i32; 2], + maximum: [i32; 2], + ) -> Result { + let low = minimum.map(|v| v >> 2); + let high = maximum.map(|v| v >> 2); + let sizes: [i32; 2] = std::array::from_fn(|i| high[i].wrapping_sub(low[i]).wrapping_add(1)); + let volume = DensityVolume::new( + [sizes[0], 1, sizes[1]], + [low[0].wrapping_shl(2), 0, low[1].wrapping_shl(2)], + [4, 1, 4], + )?; + if volume.size() > 2_097_152 { + return Err(AquiferError::InvalidGrid); + } + let mut buffer = Vec::new(); + buffer + .try_reserve_exact(volume.size()) + .map_err(|_| AquiferError::Allocation)?; + buffer.resize(volume.size(), 0.); + self.samplers + .get(AquiferField::SurfaceLevel) + .sample_volume(context, &mut buffer, volume)?; + self.surfaces + .try_reserve(volume.size()) + .map_err(|_| AquiferError::Allocation)?; + let mut maximum = i32::MIN; + let mut index = 0; + for z in 0..sizes[1] { + for x in 0..sizes[0] { + let value = (buffer[index] as f64).floor() as i32; + index += 1; + self.surfaces.insert( + ChunkPos::new( + low[0].wrapping_add(x).wrapping_shl(2), + low[1].wrapping_add(z).wrapping_shl(2), + ) + .pack(), + value, + ); + maximum = maximum.max(value); + } + } + Ok(maximum) + } + fn grid_index(&self, position: [i32; 3]) -> Result { + let relative: [i32; 3] = std::array::from_fn(|i| position[i].wrapping_sub(self.minimum[i])); + // Vanilla checks the final array index, rather than each coordinate. + let index = relative[1] + .wrapping_mul(self.size_z) + .wrapping_add(relative[2]) + .wrapping_mul(self.size_x) + .wrapping_add(relative[0]); + if index < 0 || index as usize >= self.locations.len() { + return Err(AquiferError::OutsideGrid); + } + Ok(index as usize) + } + fn status( + &mut self, + context: &mut SamplerContext, + index: usize, + ) -> Result { + if let Some(status) = self.statuses[index] { + return Ok(status); + } + let pos = BlockPos::unpack(self.locations[index]); + let status = self.compute_fluid(context, [pos.x, pos.y, pos.z])?; + self.statuses[index] = Some(status); + Ok(status) + } + fn compute_fluid( + &mut self, + context: &mut SamplerContext, + [x, y, z]: [i32; 3], + ) -> Result { + let global = self.picker.compute([x, y, z]); + let upper = y.wrapping_add(12); + let lower = y.wrapping_sub(12); + let mut minimum = i32::MAX; + let mut center_fluid = false; + for [dx, dz] in SURFACE_OFFSETS { + let sx = x.wrapping_add(dx.wrapping_mul(16)); + let sz = z.wrapping_add(dz.wrapping_mul(16)); + let surface = self.surface_level(context, sx, sz)?; + let adjusted = surface.wrapping_add(8); + let center = dx == 0 && dz == 0; + if center && lower > adjusted { + return Ok(global); + } + let above = upper > adjusted; + if above || center { + let status = self.picker.compute([sx, adjusted, sz]); + if !self.blocks.is_air(status.at(adjusted, self.blocks.air())) { + if center { + center_fluid = true; + } + if above { + return Ok(status); + } + } + } + minimum = minimum.min(surface); + } + let level = + self.compute_surface_level(context, [x, y, z], global, minimum, center_fluid)?; + let mut state = global.state; + if level <= -10 + && level != WAY_BELOW_MIN_Y + && state != self.blocks.lava() + && self + .sample( + AquiferField::Lava, + context, + [x.div_euclid(64), y.div_euclid(40), z.div_euclid(64)], + )? + .abs() + > 0.3 + { + state = self.blocks.lava(); + } + Ok(FluidStatus { level, state }) + } + fn compute_surface_level( + &self, + context: &mut SamplerContext, + position: [i32; 3], + global: FluidStatus, + minimum: i32, + center_fluid: bool, + ) -> Result { + let [x, y, z] = position; + let (dry, flooded) = if self.sample(AquiferField::Exclusion, context, position)? > 0. { + (-1., -1.) + } else { + let distance = minimum.wrapping_add(8).wrapping_sub(y); + let factor = if center_fluid { + let alpha = (distance as f64 - 0.) / (64. - 0.); + if alpha < 0. { + 1. + } else if alpha > 1. { + 0. + } else { + 1. + alpha * (0. - 1.) + } + } else { + 0. + }; + let value = self + .sample(AquiferField::Floodedness, context, position)? + .clamp(-1., 1.); + let alpha = (factor - 1.) / (0. - 1.); + let threshold_flooded = -0.3 + alpha * (0.8 - -0.3); + let threshold_dry = -0.8 + alpha * (0.4 - -0.8); + (value - threshold_dry, value - threshold_flooded) + }; + if flooded > 0. { + return Ok(global.level); + } + if dry > 0. { + let spread = self.samplers.get(AquiferField::Spread).sample_value( + context, + [x.div_euclid(16), y.div_euclid(40), z.div_euclid(16)], + )? * 10.; + let offset = ((spread as f64 / 3.).floor() as i32).wrapping_mul(3); + return Ok(minimum.min( + y.div_euclid(40) + .wrapping_mul(40) + .wrapping_add(20) + .wrapping_add(offset), + )); + } + Ok(WAY_BELOW_MIN_Y) + } + fn pressure( + &self, + context: &mut SamplerContext, + position: [i32; 3], + memo: &mut f64, + a: FluidStatus, + b: FluidStatus, + ) -> Result { + let y = position[1]; + let sa = a.at(y, self.blocks.air()); + let sb = b.at(y, self.blocks.air()); + if (self.blocks.is_lava(sa) && self.blocks.is_water(sb)) + || (self.blocks.is_water(sa) && self.blocks.is_lava(sb)) + { + return Ok(2.); + } + let gap = a.level.wrapping_sub(b.level).wrapping_abs(); + if gap == 0 { + return Ok(0.); + } + let midpoint = 0.5 * a.level.wrapping_add(b.level) as f64; + let dy = y as f64 + 0.5 - midpoint; + let edge = gap as f64 / 2. - dy.abs(); + let q = if dy > 0. { + let n = 0. + edge; + if n > 0. { n / 1.5 } else { n / 2.5 } + } else { + let n = 3. + edge; + if n > 0. { n / 3. } else { n / 10. } + }; + let barrier = if q < -2. || q > 2. { + 0. + } else { + if memo.is_nan() { + *memo = self.sample(AquiferField::Barrier, context, position)?; + } + *memo + }; + Ok(2. * (barrier + q)) + } + pub fn compute_substance( + &mut self, + context: &mut SamplerContext, + [x, y, z]: [i32; 3], + density: f64, + ) -> Result, AquiferError> { + if density > 0. { + self.schedule = false; + return Ok(None); + } + let global = self.picker.compute([x, y, z]); + if y > self.skip_above_y { + self.schedule = false; + return Ok(Some(global.at(y, self.blocks.air()))); + } + if self.blocks.is_lava(global.at(y, self.blocks.air())) { + self.schedule = false; + return Ok(Some(self.blocks.lava())); + } + let grid = [ + x.wrapping_sub(5) >> 4, + y.wrapping_add(1).div_euclid(12), + z.wrapping_sub(5) >> 4, + ]; + let mut distances = [i32::MAX; 4]; + let mut indices = [0usize; 4]; + for dx in 0..=1i32 { + for dy in -1..=1i32 { + for dz in 0..=1i32 { + let cell = [ + grid[0].wrapping_add(dx), + grid[1].wrapping_add(dy), + grid[2].wrapping_add(dz), + ]; + let index = self.grid_index(cell)?; + if self.locations[index] == i64::MAX { + let mut random = self.random.at(BlockPos::new(cell[0], cell[1], cell[2])); + let px = cell[0] + .wrapping_shl(4) + .wrapping_add(random.next_int_bound(10).expect("positive bound")); + let py = cell[1] + .wrapping_mul(12) + .wrapping_add(random.next_int_bound(9).expect("positive bound")); + let pz = cell[2] + .wrapping_shl(4) + .wrapping_add(random.next_int_bound(10).expect("positive bound")); + self.locations[index] = BlockPos::new(px, py, pz).pack(); + } + let point = BlockPos::unpack(self.locations[index]); + let ax = point.x.wrapping_sub(x); + let ay = point.y.wrapping_sub(y); + let az = point.z.wrapping_sub(z); + let distance = ax + .wrapping_mul(ax) + .wrapping_add(ay.wrapping_mul(ay)) + .wrapping_add(az.wrapping_mul(az)); + if let Some(slot) = distances.iter().position(|old| distance <= *old) { + for i in (slot + 1..4).rev() { + distances[i] = distances[i - 1]; + indices[i] = indices[i - 1]; + } + distances[slot] = distance; + indices[slot] = index; + } + } + } + } + let a = self.status(context, indices[0])?; + let s01 = similarity(distances[0], distances[1]); + let candidate = a.at(y, self.blocks.air()); + if s01 <= 0. { + self.schedule = if s01 >= FLOWING_UPDATE_SIMILARITY { + a != self.status(context, indices[1])? + } else { + false + }; + return Ok(Some(candidate)); + } + if self.blocks.is_water(candidate) + && self.blocks.is_lava( + self.picker + .compute([x, y.wrapping_sub(1), z]) + .at(y.wrapping_sub(1), self.blocks.air()), + ) + { + self.schedule = true; + return Ok(Some(candidate)); + } + let mut memo = f64::NAN; + let b = self.status(context, indices[1])?; + if density + s01 * self.pressure(context, [x, y, z], &mut memo, a, b)? > 0. { + self.schedule = false; + return Ok(None); + } + let c = self.status(context, indices[2])?; + let s02 = similarity(distances[0], distances[2]); + if s02 > 0. + && density + s01 * s02 * self.pressure(context, [x, y, z], &mut memo, a, c)? > 0. + { + self.schedule = false; + return Ok(None); + } + let s12 = similarity(distances[1], distances[2]); + if s12 > 0. + && density + s01 * s12 * self.pressure(context, [x, y, z], &mut memo, b, c)? > 0. + { + self.schedule = false; + return Ok(None); + } + self.schedule = a != b + || (s12 >= FLOWING_UPDATE_SIMILARITY && b != c) + || (s02 >= FLOWING_UPDATE_SIMILARITY && a != c) + || (s02 >= FLOWING_UPDATE_SIMILARITY + && similarity(distances[0], distances[3]) >= FLOWING_UPDATE_SIMILARITY + && a != self.status(context, indices[3])?); + Ok(Some(candidate)) + } +} +fn similarity(a: i32, b: i32) -> f64 { + 1. - b.wrapping_sub(a) as f64 / 25. +} diff --git a/crates/horizon-world/src/worldgen/biome.rs b/crates/horizon-world/src/worldgen/biome.rs new file mode 100644 index 000000000..7847d679b --- /dev/null +++ b/crates/horizon-world/src/worldgen/biome.rs @@ -0,0 +1,153 @@ +//! Multi-noise biome resolution over an imported immutable parameter table. +//! Vanilla biome JSON codecs and built-in preset builders remain separate work. +use super::{ + DecodeError, + climate::{ + ClimateIndex, ClimateSampler, ClimateSearch, ClimateVolume, IndexError, Parameter, + ParameterPoint, + }, + density::identifier, +}; +use horizon_core::density::{SampleError, SamplerContext}; + +/// Identity within an immutable biome registry snapshot. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct BiomeId(pub u32); + +#[derive(Debug)] +pub enum BiomeError { + Decode(DecodeError), + Index(IndexError), + Sample(SampleError), + OutsideVolume, +} +impl std::fmt::Display for BiomeError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Decode(e) => e.fmt(f), + Self::Index(e) => e.fmt(f), + Self::Sample(e) => e.fmt(f), + Self::OutsideVolume => f.write_str("biome query is outside the prepared quart volume"), + } + } +} +impl std::error::Error for BiomeError {} +impl From for BiomeError { + fn from(e: DecodeError) -> Self { + Self::Decode(e) + } +} +impl From for BiomeError { + fn from(e: IndexError) -> Self { + Self::Index(e) + } +} +impl From for BiomeError { + fn from(e: SampleError) -> Self { + Self::Sample(e) + } +} + +#[derive(Debug)] +pub struct MultiNoiseBiomeSource { + parameters: ClimateIndex, +} +impl MultiNoiseBiomeSource { + pub fn new(entries: Vec<(ParameterPoint, String)>) -> Result { + let entries = entries + .into_iter() + .map(|(point, name)| Ok((point, identifier(&name)?))) + .collect::>()?; + Ok(Self { + parameters: ClimateIndex::new(entries)?, + }) + } + /// Horizon's quantized import format, not the vanilla biome definition + /// codec: [{"coordinates":[[min,max]; six],"offset":long,"biome":id}]. + /// Built-in numeric tables stay private and are authenticated by the runner. + pub fn from_quantized_json(json: &str) -> Result { + let input: serde_json::Value = serde_json::from_str(json).map_err(DecodeError::from)?; + let mut entries = Vec::new(); + for entry in input + .as_array() + .ok_or(DecodeError::Field("biome parameter list"))? + { + let raw = entry["coordinates"] + .as_array() + .filter(|v| v.len() == 6) + .ok_or(DecodeError::Field("climate coordinates"))?; + let mut coordinates = [Parameter::new(0, 0); 6]; + for (coordinate, raw) in coordinates.iter_mut().zip(raw) { + let raw = raw + .as_array() + .filter(|v| v.len() == 2) + .ok_or(DecodeError::Field("climate interval"))?; + *coordinate = Parameter::new( + raw[0] + .as_i64() + .ok_or(DecodeError::Field("climate minimum"))?, + raw[1] + .as_i64() + .ok_or(DecodeError::Field("climate maximum"))?, + ); + } + let offset = entry["offset"] + .as_i64() + .ok_or(DecodeError::Field("climate offset"))?; + let biome = entry["biome"] + .as_str() + .ok_or(DecodeError::Field("biome identifier"))?; + entries.push(( + ParameterPoint { + coordinates, + offset, + }, + biome.to_owned(), + )); + } + Self::new(entries) + } + pub fn parameters(&self) -> &ClimateIndex { + &self.parameters + } + pub fn resolver<'a>(&'a self, climate: &'a ClimateSampler) -> BiomeResolver<'a> { + BiomeResolver { + climate, + search: self.parameters.searcher(), + } + } +} +#[derive(Debug)] +pub struct BiomeResolver<'a> { + climate: &'a ClimateSampler, + search: ClimateSearch<'a, String>, +} +impl<'a> BiomeResolver<'a> { + pub fn sample( + &mut self, + context: &mut SamplerContext, + quart: [i32; 3], + ) -> Result<&'a str, BiomeError> { + Ok(self + .search + .find(self.climate.sample(context, quart)?)? + .as_str()) + } + pub fn prepare_volume( + &self, + context: &mut SamplerContext, + minimum: [i32; 3], + extents: [i32; 3], + ) -> Result { + Ok(self.climate.sample_volume(context, minimum, extents)?) + } + /// Query order shares the same previous-leaf state as scalar resolution. + pub fn sample_prepared( + &mut self, + volume: &ClimateVolume, + quart: [i32; 3], + ) -> Result<&'a str, BiomeError> { + let target = volume.target(quart).ok_or(BiomeError::OutsideVolume)?; + Ok(self.search.find(target)?.as_str()) + } +} diff --git a/crates/horizon-world/src/worldgen/biome_chunk.rs b/crates/horizon-world/src/worldgen/biome_chunk.rs new file mode 100644 index 000000000..3d7e903f4 --- /dev/null +++ b/crates/horizon-world/src/worldgen/biome_chunk.rs @@ -0,0 +1,178 @@ +//! Quart-resolution biome storage and section-atomic noise-biome filling. +use crate::heightmap::{Heightmap, HeightmapError, HeightmapType}; +use horizon_core::{ + biome::BiomeZoom, + position::{BlockPos, ChunkPos}, +}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Clone, Debug)] +pub struct BiomeChunk { + position: ChunkPos, + min_y: i32, + height: i32, + sections: Vec<[T; 64]>, +} +#[derive(Debug, PartialEq, Eq)] +pub enum BiomeFillError { + InvalidBounds, + Resolve(E), +} +impl std::fmt::Display for BiomeFillError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::InvalidBounds => f.write_str("biome generation bounds are outside the chunk"), + Self::Resolve(error) => error.fmt(f), + } + } +} +impl std::error::Error for BiomeFillError {} +impl BiomeChunk { + /// A chunk's biome values use the same supported vertical bounds as terrain. + /// Each section stores a dense 4×4×4 array; palette/network codecs are separate. + pub fn new( + position: ChunkPos, + min_y: i32, + height: i32, + default: T, + ) -> Result { + Heightmap::new(HeightmapType::WorldSurfaceWg, min_y, height)?; + Ok(Self { + position, + min_y, + height, + sections: (0..height / 16) + .map(|_| std::array::from_fn(|_| default.clone())) + .collect(), + }) + } + pub fn section(&self, index: usize) -> Option<&[T; 64]> { + self.sections.get(index) + } + /// Vanilla clamps quart Y to the chunk and wraps X/Z to the local 4×4 grid. + /// The caller is responsible for selecting the chunk containing X/Z. + pub fn noise_biome(&self, quart: [i32; 3]) -> &T { + let bottom = self.min_y >> 2; + let y = quart[1].clamp(bottom, bottom + (self.height >> 2) - 1); + let section = ((y - bottom) >> 2) as usize; + &self.sections[section][index(quart[0], y, quart[2])] + } + /// Fill the sections intersecting inclusive generation bounds. Sections are + /// visited bottom to top; each resolver sees X/Y/Z loop order. A failed + /// section retains its previous values while earlier sections stay committed. + /// This does not decorate the resolver with blending or below-zero retrogen. + pub fn fill( + &mut self, + min_y: i32, + max_y: i32, + mut resolve: impl FnMut([i32; 3]) -> Result, + ) -> Result<(), BiomeFillError> { + if min_y < self.min_y || max_y >= self.min_y + self.height || min_y > max_y { + return Err(BiomeFillError::InvalidBounds); + } + let x = self.position.x.wrapping_shl(4) >> 2; + let z = self.position.z.wrapping_shl(4) >> 2; + for section_y in (min_y >> 4)..=(max_y >> 4) { + let section = (section_y - (self.min_y >> 4)) as usize; + let mut values = self.sections[section].clone(); + for dx in 0..4 { + for dy in 0..4 { + for dz in 0..4 { + let quart = [ + x.wrapping_add(dx), + section_y.wrapping_shl(2).wrapping_add(dy), + z.wrapping_add(dz), + ]; + values[index(dx, dy, dz)] = + resolve(quart).map_err(BiomeFillError::Resolve)?; + } + } + } + self.sections[section] = values; + } + Ok(()) + } +} +fn index(x: i32, y: i32, z: i32) -> usize { + (((y & 3) << 4) | ((z & 3) << 2) | (x & 3)) as usize +} + +/// Resident biome sections shared by decoration selection and block biome zoom. +/// The seed is already obfuscated, as for `BiomeZoom` and the client protocol. +pub struct BiomeRegion { + chunks: BTreeMap<(i32, i32), BiomeChunk>, + zoom: BiomeZoom, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BiomeRegionError { + InvalidChunks, + MissingChunk(ChunkPos), +} +impl std::fmt::Display for BiomeRegionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{self:?}") + } +} +impl std::error::Error for BiomeRegionError {} +impl BiomeRegion { + pub fn new(chunks: Vec>, obfuscated_seed: i64) -> Result { + if chunks.is_empty() || chunks.len() > 4096 { + return Err(BiomeRegionError::InvalidChunks); + } + let min = chunks[0].min_y; + let height = chunks[0].height; + let mut stored = BTreeMap::new(); + for chunk in chunks { + if chunk.min_y != min || chunk.height != height { + return Err(BiomeRegionError::InvalidChunks); + } + if stored + .insert((chunk.position.x, chunk.position.z), chunk) + .is_some() + { + return Err(BiomeRegionError::InvalidChunks); + } + } + Ok(Self { + chunks: stored, + zoom: BiomeZoom::new(obfuscated_seed), + }) + } + pub fn chunk(&self, p: ChunkPos) -> Result<&BiomeChunk, BiomeRegionError> { + self.chunks + .get(&(p.x, p.z)) + .ok_or(BiomeRegionError::MissingChunk(p)) + } + pub fn chunk_mut(&mut self, p: ChunkPos) -> Result<&mut BiomeChunk, BiomeRegionError> { + self.chunks + .get_mut(&(p.x, p.z)) + .ok_or(BiomeRegionError::MissingChunk(p)) + } + pub fn noise_biome(&self, quart: [i32; 3]) -> Result<&T, BiomeRegionError> { + Ok(self + .chunk(ChunkPos::new(quart[0] >> 2, quart[2] >> 2))? + .noise_biome(quart)) + } + pub fn biome(&self, block: BlockPos) -> Result<&T, BiomeRegionError> { + self.noise_biome(self.zoom.quart_at_block(block)) + } + pub fn quart_at_block(&self, block: BlockPos) -> [i32; 3] { + self.zoom.quart_at_block(block) + } + /// Distinct values currently stored anywhere in the chunk. The result is + /// sorted by biome identity; callers must not use this order as registry order. + pub fn present_in_chunk(&self, p: ChunkPos) -> Result, BiomeRegionError> + where + T: Ord, + { + Ok(self + .chunk(p)? + .sections + .iter() + .flatten() + .cloned() + .collect::>() + .into_iter() + .collect()) + } +} diff --git a/crates/horizon-world/src/worldgen/biome_predicate.rs b/crates/horizon-world/src/worldgen/biome_predicate.rs new file mode 100644 index 000000000..46554e1a9 --- /dev/null +++ b/crates/horizon-world/src/worldgen/biome_predicate.rs @@ -0,0 +1,81 @@ +//! Immutable biome identities and resolved holder sets for world predicates. +use super::{DecodeError, biome::BiomeId, density::identifier}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; +pub struct BiomePredicateBindings { + names: BTreeMap, + tags: BTreeMap>>, +} +impl BiomePredicateBindings { + /// IDs must belong to the same registry snapshot as the world's biome query. + pub fn new( + names: &BTreeMap, + tags: &BTreeMap>, + ) -> Result { + if names.len() > 8192 || tags.len() > 8192 { + return Err(DecodeError::Field("predicate biome registry size")); + } + let mut canonical = BTreeMap::new(); + let mut ids = BTreeSet::new(); + for (name, id) in names { + if canonical.insert(identifier(name)?, *id).is_some() || !ids.insert(*id) { + return Err(DecodeError::Field("duplicate predicate biome identity")); + } + } + let mut bound_tags = BTreeMap::new(); + for (name, entries) in tags { + if entries.len() > 8192 { + return Err(DecodeError::Field("predicate biome tag size")); + } + let values = entries + .iter() + .map(|entry| { + canonical + .get(&identifier(entry)?) + .copied() + .ok_or_else(|| DecodeError::Registry(format!("unknown biome {entry}"))) + }) + .collect::, _>>()?; + if bound_tags + .insert(super::tags::identifier(name)?, Arc::new(values)) + .is_some() + { + return Err(DecodeError::Field("duplicate predicate biome tag")); + } + } + Ok(Self { + names: canonical, + tags: bound_tags, + }) + } + pub fn resolve(&self, json: &str) -> Result>, DecodeError> { + if let Ok(name) = serde_json::from_str::(json) { + if let Some(tag) = name.strip_prefix('#') { + return self + .tags + .get(&super::tags::identifier(tag)?) + .cloned() + .ok_or_else(|| DecodeError::Registry(format!("unknown biome tag {tag}"))); + } + return Ok(Arc::new(BTreeSet::from([self.biome(&name)?]))); + } + let names: Vec = serde_json::from_str(json)?; + if names.len() > 8192 { + return Err(DecodeError::Field("predicate biome holder list")); + } + Ok(Arc::new( + names + .iter() + .map(|name| self.biome(name)) + .collect::>()?, + )) + } + fn biome(&self, name: &str) -> Result { + self.names + .get(&identifier(name)?) + .copied() + .ok_or_else(|| DecodeError::Registry(format!("unknown biome {name}"))) + } +} diff --git a/crates/horizon-world/src/worldgen/biome_source.rs b/crates/horizon-world/src/worldgen/biome_source.rs new file mode 100644 index 000000000..bb2cf8990 --- /dev/null +++ b/crates/horizon-world/src/worldgen/biome_source.rs @@ -0,0 +1,92 @@ +//! Fixed, checkerboard and End biome-source queries. Registry codecs are separate. +mod codec; +mod runtime; +pub use codec::{BiomeSet, BiomeSourceCatalog, BiomeSourceDefinition}; +use horizon_core::density::{DensitySampler, SampleError, SamplerContext}; +pub use runtime::{BiomeSourceError, BiomeSourceResolver, ResolvedBiomeSource}; + +#[derive(Clone, Debug)] +pub struct FixedBiomeSource { + pub biome: T, +} +impl FixedBiomeSource { + pub fn noise_biome(&self, _quart: [i32; 3]) -> &T { + &self.biome + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CheckerboardError { + TooManyBiomes, + EmptyBiomes, +} +impl std::fmt::Display for CheckerboardError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{self:?}") + } +} +impl std::error::Error for CheckerboardError {} +#[derive(Clone, Debug)] +pub struct CheckerboardBiomeSource { + biomes: Vec, + scale: i32, +} +impl CheckerboardBiomeSource { + /// Runtime scale is unrestricted, including Java's masked shift distances. + /// The vanilla JSON codec separately limits scale to 0..=62. + pub fn new(biomes: Vec, scale: i32) -> Result { + if biomes.len() > 8192 { + return Err(CheckerboardError::TooManyBiomes); + } + Ok(Self { biomes, scale }) + } + pub fn noise_biome(&self, quart: [i32; 3]) -> Result<&T, CheckerboardError> { + if self.biomes.is_empty() { + return Err(CheckerboardError::EmptyBiomes); + } + let shift = self.scale.wrapping_add(2) as u32; + let cell = quart[0] + .wrapping_shr(shift) + .wrapping_add(quart[2].wrapping_shr(shift)); + Ok(&self.biomes[cell.rem_euclid(self.biomes.len() as i32) as usize]) + } +} +#[derive(Clone, Debug)] +pub struct EndBiomeSource { + pub center: T, + pub highlands: T, + pub midlands: T, + pub islands: T, + pub barrens: T, +} +impl EndBiomeSource { + /// The central 64-chunk circle bypasses erosion. Outside it, sample erosion + /// at the containing chunk's center with the original wrapped block Y. + pub fn noise_biome( + &self, + quart: [i32; 3], + erosion: &dyn DensitySampler, + context: &mut SamplerContext, + ) -> Result<&T, SampleError> { + let block = quart.map(|v| v.wrapping_shl(2)); + let x = block[0] >> 4; + let z = block[2] >> 4; + if i64::from(x) * i64::from(x) + i64::from(z) * i64::from(z) <= 4096 { + return Ok(&self.center); + } + let position = [ + x.wrapping_mul(2).wrapping_add(1).wrapping_mul(8), + block[1], + z.wrapping_mul(2).wrapping_add(1).wrapping_mul(8), + ]; + let value = erosion.sample_value(context, position)?; + Ok(if value > 0.25 { + &self.highlands + } else if value >= -0.0625 { + &self.midlands + } else if value < -0.21875 { + &self.islands + } else { + &self.barrens + }) + } +} diff --git a/crates/horizon-world/src/worldgen/biome_source/codec.rs b/crates/horizon-world/src/worldgen/biome_source/codec.rs new file mode 100644 index 000000000..ab78f4588 --- /dev/null +++ b/crates/horizon-world/src/worldgen/biome_source/codec.rs @@ -0,0 +1,262 @@ +//! Registry-bound biome-source definitions. Inline full biome objects are separate. +use crate::worldgen::{ + DecodeError, Object, RawValue, + climate::{ParameterPoint, decode_parameter_point, unquantize}, + density::identifier, + int_range, optional, required, +}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum BiomeSet { + Direct(Vec), + Tag { name: String, members: Vec }, +} +impl BiomeSet { + pub fn members(&self) -> &[String] { + match self { + Self::Direct(values) => values, + Self::Tag { members, .. } => members, + } + } +} +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum BiomeSourceDefinition { + Fixed(String), + Checkerboard { biomes: BiomeSet, scale: i32 }, + End, + MultiNoise(Vec<(ParameterPoint, String)>), + Preset { name: String, inline: bool }, +} +#[derive(Clone, Debug)] +pub struct BiomeSourceCatalog { + biomes: BTreeSet, + tags: BTreeMap>, + presets: BTreeSet, +} +impl BiomeSourceCatalog { + pub fn new( + biomes: &BTreeSet, + tags: &BTreeMap>, + presets: &BTreeSet, + ) -> Result { + if biomes.len() > 8192 + || tags.len() > 8192 + || presets.len() > 8192 + || tags.values().map(Vec::len).sum::() > 65536 + { + return Err(DecodeError::Field("biome source catalog size")); + } + let biomes = biomes + .iter() + .map(|v| identifier(v)) + .collect::, _>>()?; + let presets = presets + .iter() + .map(|v| identifier(v)) + .collect::, _>>()?; + let mut resolved = BTreeMap::new(); + for (name, members) in tags { + let members = members + .iter() + .map(|v| identifier(v)) + .collect::, _>>()?; + if members.iter().any(|v| !biomes.contains(v)) { + return Err(DecodeError::Field("unknown biome tag member")); + } + if resolved.insert(identifier(name)?, members).is_some() { + return Err(DecodeError::Field("duplicate biome tag")); + } + } + Ok(Self { + biomes, + tags: resolved, + presets, + }) + } + fn biome(&self, raw: &RawValue) -> Result { + let name = identifier(&serde_json::from_str::(raw.get())?)?; + if !self.biomes.contains(&name) { + return Err(DecodeError::Field("unknown biome")); + } + Ok(name) + } + fn set(&self, raw: &RawValue) -> Result { + if raw.get().starts_with('"') { + let name: String = serde_json::from_str(raw.get())?; + if let Some(name) = name.strip_prefix('#') { + let name = identifier(name)?; + let members = self + .tags + .get(&name) + .ok_or(DecodeError::Field("unknown biome tag"))? + .clone(); + return Ok(BiomeSet::Tag { name, members }); + } + return Ok(BiomeSet::Direct(vec![self.biome(raw)?])); + } + let values: Vec> = serde_json::from_str(raw.get())?; + if values.len() > 8192 { + return Err(DecodeError::Field("biome holder set size")); + } + Ok(BiomeSet::Direct( + values + .iter() + .map(|v| self.biome(v)) + .collect::>()?, + )) + } + fn inline(&self, raw: &RawValue) -> Result { + let entries: Vec = serde_json::from_str(raw.get())?; + if entries.is_empty() || entries.len() > 65536 { + return Err(DecodeError::Field("multi-noise entry count")); + } + let mut result = Vec::with_capacity(entries.len()); + for entry in entries { + result.push(( + decode_parameter_point(required(&entry, "parameters")?.get())?, + self.biome(required(&entry, "biome")?)?, + )); + } + Ok(BiomeSourceDefinition::MultiNoise(result)) + } + pub fn decode(&self, json: &str) -> Result { + let object: Object = serde_json::from_str(json)?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + Ok(match kind.as_str() { + "minecraft:fixed" => { + BiomeSourceDefinition::Fixed(self.biome(required(&object, "biome")?)?) + } + "minecraft:checkerboard" => BiomeSourceDefinition::Checkerboard { + biomes: self.set(required(&object, "biomes")?)?, + scale: optional(&object, "scale") + .map_or(Ok(2), |v| int_range(v, "biome scale", 0, 62))?, + }, + "minecraft:the_end" => { + for name in [ + "the_end", + "end_highlands", + "end_midlands", + "small_end_islands", + "end_barrens", + ] { + if !self.biomes.contains(&format!("minecraft:{name}")) { + return Err(DecodeError::Field("missing End biome")); + } + } + BiomeSourceDefinition::End + } + "minecraft:multi_noise" => { + // mapEither prefers a successful inline list, then tries preset. + if let Some(raw) = optional(&object, "biomes") { + if let Ok(value) = self.inline(raw) { + return Ok(value); + } + } + let raw = required(&object, "preset")?; + if raw.get().starts_with('"') { + let name = identifier(&serde_json::from_str::(raw.get())?)?; + if !self.presets.contains(&name) { + return Err(DecodeError::Field("unknown biome preset holder")); + } + BiomeSourceDefinition::Preset { + name, + inline: false, + } + } else { + let preset: Object = serde_json::from_str(raw.get())?; + let name = identifier(&serde_json::from_str::( + required(&preset, "preset")?.get(), + )?)?; + if !matches!(name.as_str(), "minecraft:overworld" | "minecraft:nether") { + return Err(DecodeError::Field("unknown built-in biome preset")); + } + BiomeSourceDefinition::Preset { name, inline: true } + } + } + _ => return Err(DecodeError::Field("unknown biome source")), + }) + } + /// Encode definitions in the vanilla canonical shape; decoding the result + /// validates registry references and bounds before publishing JSON. + pub fn encode(&self, definition: &BiomeSourceDefinition) -> Result { + let (kind, fields) = match definition { + BiomeSourceDefinition::Fixed(name) => ("fixed", format!(",\"biome\":{}", quoted(name))), + BiomeSourceDefinition::End => ("the_end", String::new()), + BiomeSourceDefinition::Checkerboard { biomes, scale } => { + let values = match biomes { + BiomeSet::Tag { name, .. } => quoted(&format!("#{name}")), + BiomeSet::Direct(values) if values.len() == 1 => quoted(&values[0]), + BiomeSet::Direct(values) => serde_json::to_string(values)?, + }; + ( + "checkerboard", + format!( + ",\"biomes\":{values}{}", + if *scale == 2 { + String::new() + } else { + format!(",\"scale\":{scale}") + } + ), + ) + } + BiomeSourceDefinition::MultiNoise(entries) => { + let values = entries + .iter() + .map(|(point, name)| { + format!( + "{{\"parameters\":{},\"biome\":{}}}", + point_json(point), + quoted(name) + ) + }) + .collect::>() + .join(","); + ("multi_noise", format!(",\"biomes\":[{values}]")) + } + BiomeSourceDefinition::Preset { name, inline } => { + let value = if *inline { + format!("{{\"preset\":{}}}", quoted(name)) + } else { + quoted(name) + }; + ("multi_noise", format!(",\"preset\":{value}")) + } + }; + let json = format!("{{\"type\":\"minecraft:{kind}\"{fields}}}"); + self.decode(&json)?; + Ok(json) + } +} +fn quoted(value: &str) -> String { + serde_json::to_string(value).expect("string serializes") +} +fn point_json(point: &ParameterPoint) -> String { + let names = [ + "temperature", + "humidity", + "continentalness", + "erosion", + "depth", + "weirdness", + ]; + let mut fields = Vec::with_capacity(7); + for (name, p) in names.into_iter().zip(point.coordinates) { + let min = serde_json::to_string(&unquantize(p.min)).expect("finite coordinate"); + let max = serde_json::to_string(&unquantize(p.max)).expect("finite coordinate"); + let value = if min == max { + min + } else { + format!("[{min},{max}]") + }; + fields.push(format!("{}:{value}", quoted(name))); + } + fields.push(format!( + "\"offset\":{}", + serde_json::to_string(&unquantize(point.offset)).expect("finite offset") + )); + format!("{{{}}}", fields.join(",")) +} diff --git a/crates/horizon-world/src/worldgen/biome_source/runtime.rs b/crates/horizon-world/src/worldgen/biome_source/runtime.rs new file mode 100644 index 000000000..5d78fd835 --- /dev/null +++ b/crates/horizon-world/src/worldgen/biome_source/runtime.rs @@ -0,0 +1,170 @@ +//! World-bound biome sources and per-worker resolver state. +use super::{ + BiomeSourceDefinition, CheckerboardBiomeSource, CheckerboardError, EndBiomeSource, + FixedBiomeSource, +}; +use crate::worldgen::{ + DecodeError, + biome::{BiomeError, BiomeResolver, MultiNoiseBiomeSource}, + climate::{ClimateSampler, ClimateVolume}, +}; +use horizon_core::density::{DensitySampler, SampleError, SamplerContext}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Debug)] +pub enum BiomeSourceError { + Decode(DecodeError), + Biome(BiomeError), + Checkerboard(CheckerboardError), + Sample(SampleError), + MissingPreset, +} +impl std::fmt::Display for BiomeSourceError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{self:?}") + } +} +impl std::error::Error for BiomeSourceError {} +impl From for BiomeSourceError { + fn from(e: DecodeError) -> Self { + Self::Decode(e) + } +} +impl From for BiomeSourceError { + fn from(e: BiomeError) -> Self { + Self::Biome(e) + } +} +impl From for BiomeSourceError { + fn from(e: CheckerboardError) -> Self { + Self::Checkerboard(e) + } +} +impl From for BiomeSourceError { + fn from(e: SampleError) -> Self { + Self::Sample(e) + } +} + +#[derive(Debug)] +pub enum ResolvedBiomeSource { + Fixed(FixedBiomeSource), + Checkerboard(CheckerboardBiomeSource), + End(EndBiomeSource), + MultiNoise(MultiNoiseBiomeSource), +} +impl BiomeSourceDefinition { + /// Resolve a decoded definition using immutable, authenticated quantized + /// preset tables. This does not execute vanilla's built-in preset builders. + pub fn resolve( + &self, + presets: &BTreeMap, + ) -> Result { + Ok(match self { + Self::Fixed(biome) => ResolvedBiomeSource::Fixed(FixedBiomeSource { + biome: biome.clone(), + }), + Self::Checkerboard { biomes, scale } => ResolvedBiomeSource::Checkerboard( + CheckerboardBiomeSource::new(biomes.members().to_vec(), *scale)?, + ), + Self::End => ResolvedBiomeSource::End(EndBiomeSource { + center: "minecraft:the_end".into(), + highlands: "minecraft:end_highlands".into(), + midlands: "minecraft:end_midlands".into(), + islands: "minecraft:small_end_islands".into(), + barrens: "minecraft:end_barrens".into(), + }), + Self::MultiNoise(entries) => { + ResolvedBiomeSource::MultiNoise(MultiNoiseBiomeSource::new(entries.clone())?) + } + Self::Preset { name, .. } => { + ResolvedBiomeSource::MultiNoise(MultiNoiseBiomeSource::from_quantized_json( + presets.get(name).ok_or(BiomeSourceError::MissingPreset)?, + )?) + } + }) + } +} +impl ResolvedBiomeSource { + pub fn possible_biomes(&self) -> BTreeSet<&str> { + match self { + Self::Fixed(source) => [source.biome.as_str()].into(), + Self::Checkerboard(source) => source.biomes.iter().map(String::as_str).collect(), + Self::End(source) => [ + source.center.as_str(), + source.highlands.as_str(), + source.midlands.as_str(), + source.islands.as_str(), + source.barrens.as_str(), + ] + .into(), + Self::MultiNoise(source) => source + .parameters() + .entries() + .iter() + .map(|(_, name)| name.as_str()) + .collect(), + } + } + /// Keep one resolver per worker to retain native previous-leaf tie behavior. + /// Climate and erosion roots must share the worker's compiler/context namespace. + pub fn resolver<'a>( + &'a self, + climate: &'a ClimateSampler, + erosion: &'a dyn DensitySampler, + ) -> BiomeSourceResolver<'a> { + match self { + Self::Fixed(source) => BiomeSourceResolver::Fixed(source), + Self::Checkerboard(source) => BiomeSourceResolver::Checkerboard(source), + Self::End(source) => BiomeSourceResolver::End(source, erosion), + Self::MultiNoise(source) => BiomeSourceResolver::MultiNoise(source.resolver(climate)), + } + } +} +#[derive(Debug)] +pub enum BiomeSourceResolver<'a> { + Fixed(&'a FixedBiomeSource), + Checkerboard(&'a CheckerboardBiomeSource), + End(&'a EndBiomeSource, &'a dyn DensitySampler), + MultiNoise(BiomeResolver<'a>), +} +impl<'a> BiomeSourceResolver<'a> { + pub fn sample( + &mut self, + context: &mut SamplerContext, + quart: [i32; 3], + ) -> Result<&'a str, BiomeSourceError> { + Ok(match self { + Self::Fixed(source) => source.biome.as_str(), + Self::Checkerboard(source) => source.noise_biome(quart)?.as_str(), + Self::End(source, erosion) => source.noise_biome(quart, *erosion, context)?.as_str(), + Self::MultiNoise(source) => source.sample(context, quart)?, + }) + } + /// Native fixed/checkerboard/End sources do not pre-sample a climate volume. + /// Multi-noise preparation samples the full supplied quart extent once. + pub fn prepare_volume( + &self, + context: &mut SamplerContext, + minimum: [i32; 3], + extents: [i32; 3], + ) -> Result, BiomeSourceError> { + match self { + Self::MultiNoise(source) => Ok(Some(source.prepare_volume(context, minimum, extents)?)), + _ => Ok(None), + } + } + pub fn sample_prepared( + &mut self, + context: &mut SamplerContext, + volume: Option<&ClimateVolume>, + quart: [i32; 3], + ) -> Result<&'a str, BiomeSourceError> { + if let Self::MultiNoise(source) = self { + if let Some(volume) = volume { + return Ok(source.sample_prepared(volume, quart)?); + } + } + self.sample(context, quart) + } +} diff --git a/crates/horizon-world/src/worldgen/biome_temperature.rs b/crates/horizon-world/src/worldgen/biome_temperature.rs new file mode 100644 index 000000000..c7e22c985 --- /dev/null +++ b/crates/horizon-world/src/worldgen/biome_temperature.rs @@ -0,0 +1,193 @@ +//! Biome temperature sampling and a worker-local vanilla temperature cache. +use super::{DecodeError, Object, number_text, optional, required}; +use horizon_core::{ + noise::{Noise, NoiseStack, SimplexNoise}, + position::BlockPos, + random::LegacyRandom, +}; +use std::{ + collections::{HashMap, VecDeque, hash_map::Entry}, + sync::{Arc, OnceLock}, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TemperatureModifier { + None, + Frozen, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Precipitation { + None, + Rain, + Snow, +} +#[derive(Clone, Copy, Debug)] +pub struct BiomeTemperatureSettings { + pub base_temperature: f32, + pub modifier: TemperatureModifier, + pub has_precipitation: bool, + pub downfall: f32, +} +struct TemperatureNoises { + height: SimplexNoise, + frozen: NoiseStack, + info: SimplexNoise, +} +fn noises() -> &'static TemperatureNoises { + static NOISES: OnceLock = OnceLock::new(); + NOISES.get_or_init(|| { + let mut random = LegacyRandom::new(3456); + let mut frozen = NoiseStack::builder(); + for (frequency, amplitude) in [ + (1.0, 1.0f32 / 7.0), + (0.5, 2.0f32 / 7.0), + (0.25, 4.0f32 / 7.0), + ] { + frozen.add( + Arc::new(SimplexNoise::with_skipped_offsets(&mut random, true)), + frequency, + amplitude, + ); + } + TemperatureNoises { + height: SimplexNoise::with_skipped_offsets(&mut LegacyRandom::new(1234), true), + frozen: frozen.build().expect("fixed finite noise layers"), + info: SimplexNoise::with_skipped_offsets(&mut LegacyRandom::new(2345), true), + } + }) +} +impl TemperatureModifier { + pub fn modify(self, position: BlockPos, base: f32) -> f32 { + if self == Self::Frozen { + let sources = noises(); + let x = f64::from(position.x); + let z = f64::from(position.z); + let frozen = f64::from(sources.frozen.get2(x * 0.05, z * 0.05) * 7.0); + let info = f64::from(sources.info.get2(x * 0.2, z * 0.2)); + if frozen + info < 0.3 && f64::from(sources.info.get2(x * 0.09, z * 0.09)) < 0.8 { + return 0.2; + } + } + base + } +} +impl BiomeTemperatureSettings { + /// Decode the climate fields of a biome. Other biome fields are ignored, + /// matching the native ClimateSettings map codec rather than the full biome. + pub fn from_json(json: &str) -> Result { + let object: Object = serde_json::from_str(json)?; + let float = |name| { + number_text(required(&object, name)?)? + .parse::() + .map_err(|_| DecodeError::Field(name)) + }; + let modifier = match optional(&object, "temperature_modifier") { + None => TemperatureModifier::None, + Some(raw) => match serde_json::from_str::(raw.get())?.as_str() { + "none" => TemperatureModifier::None, + "frozen" => TemperatureModifier::Frozen, + _ => return Err(DecodeError::Field("temperature_modifier")), + }, + }; + Ok(Self { + base_temperature: float("temperature")?, + downfall: float("downfall")?, + has_precipitation: serde_json::from_str(required(&object, "has_precipitation")?.get())?, + modifier, + }) + } + + pub fn height_adjusted(self, position: BlockPos, sea_level: i32) -> f32 { + let base = self.modifier.modify(position, self.base_temperature); + let start = sea_level.wrapping_add(17); + if position.y > start { + let variation = noises().height.get2( + f64::from(position.x as f32 / 8.0), + f64::from(position.z as f32 / 8.0), + ) * 8.0; + base - ((variation + position.y as f32 - start as f32) * 0.05 / 40.0) + } else { + base + } + } +} + +/// Keep one instance per biome per worker, matching vanilla's thread-local map. +/// Hits do not reorder entries. The packed-position key deliberately omits sea +/// level, so a cached value survives queries with a different sea level. +#[derive(Debug)] +pub struct BiomeTemperature { + settings: BiomeTemperatureSettings, + values: HashMap, + order: VecDeque, +} +impl BiomeTemperature { + pub fn new(settings: BiomeTemperatureSettings) -> Self { + Self { + settings, + values: HashMap::with_capacity(1024), + order: VecDeque::with_capacity(1024), + } + } + pub fn settings(&self) -> BiomeTemperatureSettings { + self.settings + } + pub fn temperature(&mut self, position: BlockPos, sea_level: i32) -> f32 { + let key = position.pack(); + if let Some(value) = self + .values + .get(&key) + .copied() + .filter(|value| !value.is_nan()) + { + return value; + } + let value = self.settings.height_adjusted(position, sea_level); + // NaN is both the missing-value sentinel and a possible stored value. + // Recomputing an existing NaN at capacity still evicts the oldest key. + if self.values.len() == 1024 { + let first = self.order.pop_front().expect("full cache has entries"); + self.values.remove(&first); + } + match self.values.entry(key) { + Entry::Occupied(mut entry) => { + entry.insert(value); + } + Entry::Vacant(entry) => { + entry.insert(value); + self.order.push_back(key); + } + } + value + } + pub fn warm_enough_to_rain(&mut self, position: BlockPos, sea_level: i32) -> bool { + self.temperature(position, sea_level) >= 0.15 + } + pub fn cold_enough_to_snow(&mut self, position: BlockPos, sea_level: i32) -> bool { + !self.warm_enough_to_rain(position, sea_level) + } + pub fn should_melt_frozen_ocean_iceberg_slightly( + &mut self, + position: BlockPos, + sea_level: i32, + ) -> bool { + self.temperature(position, sea_level) > 0.1 + } + pub fn precipitation_at(&mut self, position: BlockPos, sea_level: i32) -> Precipitation { + if !self.settings.has_precipitation { + Precipitation::None + } else if self.cold_enough_to_snow(position, sea_level) { + Precipitation::Snow + } else { + Precipitation::Rain + } + } + pub fn cached_temperatures(&self) -> impl ExactSizeIterator + '_ { + self.order.iter().map(|key| (*key, self.values[key])) + } +} + +/// Fixed biome-information noise shared by temperature and placement rules. +pub fn biome_info_noise(x: f64, z: f64) -> f32 { + noises().info.get2(x, z) +} diff --git a/crates/horizon-world/src/worldgen/block_feature.rs b/crates/horizon-world/src/worldgen/block_feature.rs new file mode 100644 index 000000000..4684a4eb4 --- /dev/null +++ b/crates/horizon-world/src/worldgen/block_feature.rs @@ -0,0 +1,333 @@ +//! Registry-bound block-writing features and their state codec bindings. +use super::{ + DecodeError, Object, + density::identifier, + feature::FeatureWorld, + int_range, + placement::{PlacementContext, PlacementQueryError}, + required, +}; +use crate::block_properties::{BlockPropertiesRegistry, BlockProperty, BoundBlockProperty}; +use crate::registry::{BlockRegistry, BlockStateId, BlockStateJsonCodec}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; + +pub struct FeatureBlockBindings<'r> { + registry: &'r BlockRegistry, + physical_properties: Option<[BoundBlockProperty; 4]>, + biomes: Option>, + fluids: super::fluid_predicate::FluidPredicateBindings, + pub(crate) codec: BlockStateJsonCodec<'r>, + pub(crate) blocks: BTreeMap>>, + pub(crate) tags: BTreeMap>>, + pub(crate) air: [BlockStateId; 3], +} +impl<'r> FeatureBlockBindings<'r> { + pub fn with_block_properties( + mut self, + properties: &BlockPropertiesRegistry<'r>, + ) -> Result { + if !std::ptr::eq(self.registry, properties.registry()) { + return Err(DecodeError::Field( + "block properties use a different registry", + )); + } + self.physical_properties = Some([ + properties.bind(BlockProperty::Solid), + properties.bind(BlockProperty::Replaceable), + properties.bind(BlockProperty::Liquid), + properties.bind(BlockProperty::SolidRender), + ]); + Ok(self) + } + pub fn with_biomes( + mut self, + biomes: Arc, + ) -> Self { + self.biomes = Some(biomes); + self + } + + pub fn with_fluid_tags( + mut self, + tags: &BTreeMap>, + ) -> Result { + self.fluids = self.fluids.with_resolved_tags(tags)?; + Ok(self) + } + pub fn new( + registry: &'r BlockRegistry, + integers: BTreeSet<(String, String)>, + ) -> Result { + Self::with_tags(registry, integers, &BTreeMap::new()) + } + /// Bind an immutable snapshot of already-resolved block tags. + pub fn with_tags( + registry: &'r BlockRegistry, + integers: BTreeSet<(String, String)>, + tags: &BTreeMap>, + ) -> Result { + let codec = BlockStateJsonCodec::new(registry, integers) + .map_err(|e| DecodeError::Registry(e.to_string()))?; + let mut blocks = BTreeMap::>::new(); + for id in 0..registry.len() { + let id = BlockStateId(id as u32); + blocks + .entry(registry.state(id).unwrap().name.clone()) + .or_default() + .insert(id); + } + let mut bound_tags = BTreeMap::new(); + for (name, entries) in tags { + let mut states = BTreeSet::new(); + for name in entries { + states.extend( + blocks + .get(&identifier(name)?) + .ok_or_else(|| DecodeError::Registry(format!("unknown block {name}")))?, + ); + } + if bound_tags + .insert(super::tags::identifier(name)?, Arc::new(states)) + .is_some() + { + return Err(DecodeError::Field("duplicate block tag")); + } + } + let get = |name| { + registry + .default_state(name) + .ok_or_else(|| DecodeError::Registry(format!("unknown air block {name}"))) + }; + Ok(Self { + registry, + codec, + biomes: None, + physical_properties: None, + fluids: super::fluid_predicate::FluidPredicateBindings::new(registry)?, + blocks: blocks + .into_iter() + .map(|(name, states)| (name, Arc::new(states))) + .collect(), + tags: bound_tags, + air: [ + get("minecraft:air")?, + get("minecraft:cave_air")?, + get("minecraft:void_air")?, + ], + }) + } +} +impl super::block_predicate::PredicateBlockResolver for FeatureBlockBindings<'_> { + fn predicate_state(&self, json: &str) -> Result { + self.codec + .decode(json, false) + .map_err(|e| DecodeError::Registry(e.to_string())) + } + fn predicate_property( + &self, + property: BlockProperty, + ) -> Result { + let values = self + .physical_properties + .as_ref() + .ok_or(DecodeError::Field("predicate block property registry"))?; + Ok(values[match property { + BlockProperty::Solid => 0, + BlockProperty::Replaceable => 1, + BlockProperty::Liquid => 2, + BlockProperty::SolidRender => 3, + }] + .clone()) + } + fn predicate_biome_set( + &self, + json: &str, + ) -> Result>, DecodeError> { + self.biomes + .as_ref() + .ok_or(DecodeError::Field("predicate biome registry"))? + .resolve(json) + } + + fn predicate_fluid_set( + &self, + json: &str, + ) -> Result { + self.fluids.resolve(json) + } + fn predicate_block_set(&self, json: &str) -> Result>, DecodeError> { + if let Ok(name) = serde_json::from_str::(json) { + if let Some(tag) = name.strip_prefix('#') { + return self + .tags + .get(&super::tags::identifier(tag)?) + .cloned() + .ok_or_else(|| { + DecodeError::Registry(format!("unknown predicate block tag {tag}")) + }); + } + return self + .blocks + .get(&identifier(&name)?) + .cloned() + .ok_or_else(|| DecodeError::Registry(format!("unknown predicate block {name}"))); + } + let names: Vec = serde_json::from_str(json)?; + if names.len() > 8192 { + return Err(DecodeError::Field("predicate block list size")); + } + let mut states = BTreeSet::new(); + for name in names { + states.extend( + self.blocks + .get(&identifier(&name)?) + .ok_or_else(|| { + DecodeError::Registry(format!("unknown predicate block {name}")) + })? + .iter() + .copied(), + ); + } + Ok(Arc::new(states)) + } +} +#[derive(Clone, Debug)] +pub struct FillLayerFeature { + height: i32, + state: BlockStateId, + air: [BlockStateId; 3], +} +#[derive(Debug)] +pub enum BlockFeatureError { + World(E), + Query(PlacementQueryError), +} +impl std::fmt::Display for BlockFeatureError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::World(e) => e.fmt(f), + Self::Query(e) => e.fmt(f), + } + } +} +impl std::error::Error for BlockFeatureError {} +impl FillLayerFeature { + pub fn from_json(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result { + let object: Object = serde_json::from_str(json)?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + if kind != "minecraft:fill_layer" { + return Err(DecodeError::Field("fill-layer feature type")); + } + Ok(Self { + height: int_range(required(&object, "height")?, "fill-layer height", 0, 4064)?, + state: bindings + .codec + .decode(required(&object, "state")?.get(), false) + .map_err(|e| DecodeError::Registry(e.to_string()))?, + air: bindings.air, + }) + } + pub fn place( + &self, + world: &mut W, + origin: [i32; 3], + ) -> Result> { + for dx in 0..16 { + for dz in 0..16 { + // Vanilla re-queries the world minimum for each column. + let y = world + .min_y() + .map_err(BlockFeatureError::Query)? + .wrapping_add(self.height); + let position = [origin[0].wrapping_add(dx), y, origin[2].wrapping_add(dz)]; + let state = world.block(position).map_err(BlockFeatureError::World)?; + if self.air.contains(&state) { + world + .set_block(position, self.state, 2) + .map_err(BlockFeatureError::World)?; + } + } + } + Ok(true) + } +} + +#[derive(Clone, Debug)] +pub struct ReplaceBlockFeature { + targets: Vec<(super::rule_test::RuleTest, BlockStateId)>, +} +impl ReplaceBlockFeature { + pub fn from_json(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result { + Self::decode(json, bindings, 0, &mut 65536) + } + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + if kind != "minecraft:replace_single_block" { + return Err(DecodeError::Field("replace-block feature type")); + } + let targets = decode_targets(&object, bindings, depth, remaining)?; + Ok(Self { targets }) + } + pub fn place( + &self, + world: &mut W, + random: &mut impl horizon_core::random::RandomSource, + origin: [i32; 3], + ) -> Result> { + for (rule, state) in &self.targets { + let current = world.block(origin).map_err(BlockFeatureError::World)?; + if rule.test(current, origin, random) { + world + .set_block(origin, *state, 2) + .map_err(BlockFeatureError::World)?; + break; + } + } + Ok(true) + } +} + +pub(crate) type BlockReplacements = Vec<(super::rule_test::RuleTest, BlockStateId)>; +pub(crate) fn decode_targets( + object: &Object, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, +) -> Result { + let values: Vec> = + serde_json::from_str(required(object, "targets")?.get())?; + if values.len() > 8192 { + return Err(DecodeError::Field("replacement targets")); + } + values + .iter() + .map(|value| { + let object: Object = serde_json::from_str(value.get())?; + Ok(( + super::rule_test::RuleTest::decode( + required(&object, "target")?.get(), + bindings, + depth + 1, + remaining, + )?, + bindings + .codec + .decode(required(&object, "state")?.get(), false) + .map_err(|e| DecodeError::Registry(e.to_string()))?, + )) + }) + .collect::>() +} diff --git a/crates/horizon-world/src/worldgen/block_predicate.rs b/crates/horizon-world/src/worldgen/block_predicate.rs new file mode 100644 index 000000000..a4709abc2 --- /dev/null +++ b/crates/horizon-world/src/worldgen/block_predicate.rs @@ -0,0 +1,360 @@ +//! Initial world-position predicates with ordered short-circuit evaluation. +use super::anchor::VerticalAnchor; +use super::placement::{PlacementContext, PlacementQueryError}; +use super::{DecodeError, Object, density::identifier, integer, optional, required}; +use crate::{ + block_properties::{BlockProperty, BoundBlockProperty}, + registry::BlockStateId, +}; +use horizon_core::geometry::Direction; +use serde_json::value::RawValue; +use std::{collections::BTreeSet, sync::Arc}; + +/// Resolve a block holder set against the same immutable registry used by world +/// queries. Unknown blocks/tags fail during decoding, even in unused branches. +pub trait PredicateBlockResolver { + fn predicate_state(&self, _json: &str) -> Result { + Err(DecodeError::Field("predicate block state registry")) + } + fn predicate_property( + &self, + _property: BlockProperty, + ) -> Result { + Err(DecodeError::Field("predicate block property registry")) + } + fn predicate_biome_set( + &self, + _json: &str, + ) -> Result>, DecodeError> { + Err(DecodeError::Field("predicate biome registry")) + } + fn predicate_fluid_set( + &self, + _json: &str, + ) -> Result { + Err(DecodeError::Field("predicate fluid registry")) + } + fn predicate_block_set(&self, json: &str) -> Result>, DecodeError>; +} + +#[derive(Clone, Debug)] +pub enum BlockPredicate { + True, + Unobstructed, + WouldSurvive { + state: BlockStateId, + offset: [i32; 3], + }, + HasSturdyFace { + direction: Direction, + offset: [i32; 3], + }, + Property { + property: BoundBlockProperty, + offset: [i32; 3], + }, + MatchingBiomes(Arc>), + MatchingFluids { + fluids: super::fluid_predicate::BoundFluidSet, + offset: [i32; 3], + }, + MatchingBlocks { + states: Arc>, + offset: [i32; 3], + }, + MatchingBlockTag { + tag: String, + offset: [i32; 3], + }, + HeightRange { + min: VerticalAnchor, + max: VerticalAnchor, + }, + Volume { + min: [i32; 3], + max: [i32; 3], + predicate: Box, + }, + Not(Box), + All(Vec), + Any(Vec), + InsideWorldBounds([i32; 3]), +} +impl BlockPredicate { + pub fn from_json(json: &str) -> Result { + Self::decode(json, 0, &mut 65536) + } + pub(crate) fn decode( + json: &str, + depth: usize, + remaining: &mut usize, + ) -> Result { + Self::decode_with_blocks(json, depth, remaining, None) + } + pub fn from_json_with_blocks( + json: &str, + blocks: &impl PredicateBlockResolver, + ) -> Result { + Self::decode_with_blocks(json, 0, &mut 65536, Some(blocks)) + } + pub(crate) fn decode_with_blocks( + json: &str, + depth: usize, + remaining: &mut usize, + blocks: Option<&dyn PredicateBlockResolver>, + ) -> Result { + if depth > 256 || *remaining == 0 { + return Err(DecodeError::Field("block predicate depth or node count")); + } + *remaining -= 1; + let object: Object = serde_json::from_str(json)?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + match kind.as_str() { + "minecraft:would_survive" => Ok(Self::WouldSurvive { + state: blocks + .ok_or(DecodeError::Field("predicate block state registry"))? + .predicate_state(required(&object, "state")?.get())?, + offset: optional(&object, "offset") + .map(offset) + .transpose()? + .unwrap_or([0; 3]), + }), + "minecraft:has_sturdy_face" => { + let name: String = serde_json::from_str(required(&object, "direction")?.get())?; + let direction = match name.as_str() { + "down" => Direction::Down, + "up" => Direction::Up, + "north" => Direction::North, + "south" => Direction::South, + "west" => Direction::West, + "east" => Direction::East, + _ => return Err(DecodeError::Field("predicate direction")), + }; + Ok(Self::HasSturdyFace { + direction, + offset: optional(&object, "offset") + .map(offset) + .transpose()? + .unwrap_or([0; 3]), + }) + } + + "minecraft:solid" | "minecraft:replaceable" => Ok(Self::Property { + property: blocks + .ok_or(DecodeError::Field("predicate block property registry"))? + .predicate_property(if kind == "minecraft:solid" { + BlockProperty::Solid + } else { + BlockProperty::Replaceable + })?, + offset: optional(&object, "offset") + .map(offset) + .transpose()? + .unwrap_or([0; 3]), + }), + "minecraft:unobstructed" => { + if let Some(raw) = optional(&object, "offset") { + vector(raw)?; + } + // The pinned evaluator deliberately ignores its decoded offset. + Ok(Self::Unobstructed) + } + "minecraft:matching_biomes" => Ok(Self::MatchingBiomes( + blocks + .ok_or(DecodeError::Field("predicate biome registry"))? + .predicate_biome_set(required(&object, "biomes")?.get())?, + )), + "minecraft:matching_fluids" => Ok(Self::MatchingFluids { + fluids: blocks + .ok_or(DecodeError::Field("predicate fluid registry"))? + .predicate_fluid_set(required(&object, "fluids")?.get())?, + offset: optional(&object, "offset") + .map(offset) + .transpose()? + .unwrap_or([0; 3]), + }), + "minecraft:matching_blocks" => Ok(Self::MatchingBlocks { + states: blocks + .ok_or(DecodeError::Field("predicate block registry"))? + .predicate_block_set(required(&object, "blocks")?.get())?, + offset: optional(&object, "offset") + .map(offset) + .transpose()? + .unwrap_or([0; 3]), + }), + "minecraft:matching_block_tag" => Ok(Self::MatchingBlockTag { + tag: super::tags::identifier(&serde_json::from_str::( + required(&object, "tag")?.get(), + )?)?, + offset: optional(&object, "offset") + .map(offset) + .transpose()? + .unwrap_or([0; 3]), + }), + "minecraft:height_range" => Ok(Self::HeightRange { + min: VerticalAnchor::from_json(required(&object, "min_inclusive")?.get())?, + max: VerticalAnchor::from_json(required(&object, "max_inclusive")?.get())?, + }), + "minecraft:volume_match" => { + let min = offset(required(&object, "min")?)?; + let max = offset(required(&object, "max")?)?; + if (0..3).any(|i| min[i] > max[i]) { + return Err(DecodeError::Field("predicate volume bounds")); + } + Ok(Self::Volume { + min, + max, + predicate: Box::new(Self::decode_with_blocks( + required(&object, "match")?.get(), + depth + 1, + remaining, + blocks, + )?), + }) + } + "minecraft:true" => Ok(Self::True), + "minecraft:not" => Ok(Self::Not(Box::new(Self::decode_with_blocks( + required(&object, "predicate")?.get(), + depth + 1, + remaining, + blocks, + )?))), + "minecraft:all_of" | "minecraft:any_of" => { + let values: Vec> = + serde_json::from_str(required(&object, "predicates")?.get())?; + if values.len() > 8192 { + return Err(DecodeError::Field("predicate list")); + } + let values = values + .iter() + .map(|v| Self::decode_with_blocks(v.get(), depth + 1, remaining, blocks)) + .collect::>()?; + Ok(if kind == "minecraft:all_of" { + Self::All(values) + } else { + Self::Any(values) + }) + } + "minecraft:inside_world_bounds" => Ok(Self::InsideWorldBounds( + optional(&object, "offset") + .map(offset) + .transpose()? + .unwrap_or([0; 3]), + )), + _ => Err(DecodeError::Field("block predicate type")), + } + } + pub fn test( + &self, + world: &mut impl PlacementContext, + position: [i32; 3], + ) -> Result { + self.test_inner(world, position, 0, &mut 65536) + } + pub(crate) fn test_inner( + &self, + world: &mut impl PlacementContext, + position: [i32; 3], + depth: usize, + remaining: &mut usize, + ) -> Result { + if depth > 256 || *remaining == 0 { + return Err(PlacementQueryError::WorkLimit); + } + *remaining -= 1; + match self { + Self::WouldSurvive { state, offset } => world.block_survives( + *state, + std::array::from_fn(|i| position[i].wrapping_add(offset[i])), + ), + Self::Property { property, offset } => { + let state = world + .block_state(std::array::from_fn(|i| position[i].wrapping_add(offset[i])))?; + Ok(property.contains(state)) + } + Self::HasSturdyFace { direction, offset } => world.face_sturdy( + std::array::from_fn(|i| position[i].wrapping_add(offset[i])), + *direction, + ), + Self::Unobstructed => world.unobstructed_block(position), + Self::MatchingBiomes(biomes) => Ok(biomes.contains(&world.biome_identity(position)?)), + Self::MatchingFluids { fluids, offset } => { + let state = world + .block_state(std::array::from_fn(|i| position[i].wrapping_add(offset[i])))?; + Ok(fluids.contains(state)) + } + Self::MatchingBlocks { states, offset } => { + let state = world + .block_state(std::array::from_fn(|i| position[i].wrapping_add(offset[i])))?; + Ok(states.contains(&state)) + } + Self::MatchingBlockTag { tag, offset } => world.block_matches_tag( + std::array::from_fn(|i| position[i].wrapping_add(offset[i])), + tag, + ), + Self::HeightRange { min, max } => { + let context = world.predicate_generation()?; + let min = min.resolve(context); + let max = max.resolve(context); + Ok(position[1] >= min && position[1] <= max) + } + Self::Volume { + min, + max, + predicate, + } => { + // Native order is X, Z, Y. Each child shares the evaluation + // budget, including nested volumes and early-failing queries. + for x in min[0]..=max[0] { + for z in min[2]..=max[2] { + for y in min[1]..=max[1] { + let offset = [x, y, z]; + let p = std::array::from_fn(|i| position[i].wrapping_add(offset[i])); + if !predicate.test_inner(world, p, depth + 1, remaining)? { + return Ok(false); + } + } + } + } + Ok(true) + } + Self::True => Ok(true), + Self::Not(value) => Ok(!value.test_inner(world, position, depth + 1, remaining)?), + Self::All(values) | Self::Any(values) => { + let all = matches!(self, Self::All(_)); + for value in values { + let result = value.test_inner(world, position, depth + 1, remaining)?; + if result != all { + return Ok(result); + } + } + Ok(all) + } + Self::InsideWorldBounds(offset) => world + .inside_build_height(std::array::from_fn(|i| position[i].wrapping_add(offset[i]))), + } + } +} + +fn vector(raw: &RawValue) -> Result<[i32; 3], DecodeError> { + let values: Vec> = serde_json::from_str(raw.get())?; + if values.len() != 3 { + return Err(DecodeError::Field("predicate offset")); + } + let mut result = [0; 3]; + for (out, value) in result.iter_mut().zip(values.iter()) { + *out = integer(value)?; + } + Ok(result) +} + +fn offset(raw: &RawValue) -> Result<[i32; 3], DecodeError> { + let result = vector(raw)?; + // Native Math.abs(MIN_VALUE) wraps and passes this codec. + if result.iter().any(|v| v.wrapping_abs() > 16) { + return Err(DecodeError::Field("predicate offset")); + } + Ok(result) +} diff --git a/crates/horizon-world/src/worldgen/bulk_section.rs b/crates/horizon-world/src/worldgen/bulk_section.rs new file mode 100644 index 000000000..9628ac510 --- /dev/null +++ b/crates/horizon-world/src/worldgen/bulk_section.rs @@ -0,0 +1,113 @@ +//! Exclusive bulk access to resident sections, bypassing chunk heightmap writes. +use super::{ + feature_region::{RegionError, TerrainRegion}, + placement::{PlacementContext, PlacementQueryError}, + terrain::{TerrainBlockStates, TerrainError}, +}; +use crate::{heightmap::HeightmapType, registry::BlockStateId}; +use horizon_core::position::{BlockPos, SectionPos}; +use std::collections::BTreeMap; + +pub struct TerrainBulkAccess<'a, 'r, B: TerrainBlockStates> { + region: &'a mut TerrainRegion<'r, B>, + min_section: i32, + section_count: i32, + air: BlockStateId, + acquired: BTreeMap, + last: Option<(i64, SectionPos)>, +} +impl<'a, 'r, B: TerrainBlockStates> TerrainBulkAccess<'a, 'r, B> { + pub fn new(region: &'a mut TerrainRegion<'r, B>) -> Result { + let first = region.chunks().next().ok_or(RegionError::InvalidChunks)?; + let min_section = first.min_y() >> 4; + let section_count = first.height() / 16; + let air = first + .registry() + .default_state("minecraft:air") + .ok_or(RegionError::InvalidChunks)?; + Ok(Self { + region, + min_section, + section_count, + air, + acquired: BTreeMap::new(), + last: None, + }) + } + fn resolve(&mut self, p: [i32; 3]) -> Result, RegionError> { + let section = BlockPos::new(p[0], p[1], p[2]).section(); + let index = section.y.wrapping_sub(self.min_section); + if index < 0 || index >= self.section_count { + return Ok(None); + } + let key = section.pack(); + if let Some((last, section)) = self.last { + if last == key { + return Ok(Some(section)); + } + } + let cached = if let Some(cached) = self.acquired.get(&key) { + *cached + } else { + // Missing chunks do not enter the cache. Preserve packed-key aliasing + // at coordinates beyond the signed section-coordinate bit width. + self.region.chunk(section.x, section.z)?; + self.acquired.insert(key, section); + section + }; + self.last = Some((key, cached)); + Ok(Some(cached)) + } + pub fn has_section(&mut self, position: [i32; 3]) -> Result { + Ok(self.resolve(position)?.is_some()) + } + pub fn acquired_section_count(&self) -> usize { + self.acquired.len() + } + /// Direct section reads retain cave/void air in otherwise all-air sections. + /// Positions outside the vertical range return AIR without a chunk lookup. + pub fn block(&mut self, position: [i32; 3]) -> Result { + let Some(section) = self.resolve(position)? else { + return Ok(self.air); + }; + let index = section.y.wrapping_sub(self.min_section) as usize; + let p = BlockPos::new(position[0], position[1], position[2]); + self.region + .chunk(section.x, section.z)? + .section(index) + .ok_or(RegionError::InvalidChunks)? + .get(p.section_index()) + .map_err(|e| TerrainError::from(e).into()) + } + /// Raw section mutation: no chunk heightmap, POI, light or neighbor effects. + /// The caller is responsible for checking the region's write permissions. + pub fn set_block( + &mut self, + position: [i32; 3], + state: BlockStateId, + ) -> Result, RegionError> { + let Some(section) = self.resolve(position)? else { + return Ok(None); + }; + let y = section.y.wrapping_shl(4).wrapping_add(position[1] & 15); + Ok(Some( + self.region.chunk_mut(section.x, section.z)?.set_block_raw( + position[0], + y, + position[2], + state, + )?, + )) + } + pub fn world_block(&self, position: [i32; 3]) -> Result { + self.region.block(position) + } + pub fn height( + &mut self, + kind: HeightmapType, + x: i32, + z: i32, + ) -> Result { + self.region.height(kind, x, z) + } +} diff --git a/crates/horizon-world/src/worldgen/carver.rs b/crates/horizon-world/src/worldgen/carver.rs new file mode 100644 index 000000000..6ca5feb3e --- /dev/null +++ b/crates/horizon-world/src/worldgen/carver.rs @@ -0,0 +1,296 @@ +//! Seeded carver paths using pinned scalar providers and shared mask geometry. +mod canyon; +mod generation; +use super::{ + DecodeError, Object, + anchor::WorldGenerationContext, + density::identifier, + height_provider::HeightProvider, + number_text, optional, required, + value_provider::{FloatProvider, IntProvider}, +}; +pub use canyon::{CanyonCarver, CanyonShape}; +pub use generation::{ + CarverCatalog, MaskGenerationError, WorldCarver, generate_carving_mask, large_feature_random, +}; +use horizon_core::{ + carving::{CarveError, CarverOutput, can_reach, carve_ellipsoid_with_budget}, + geometry::trig::{cos, sin}, + position::ChunkPos, + random::{InvalidBound, LegacyRandom, RandomSource}, +}; + +#[derive(Clone, Debug)] +pub struct CaveCarver { + pub probability: f32, + pub y: HeightProvider, + pub count: IntProvider, + pub thickness: FloatProvider, + pub weird_thickness_bias: bool, + pub room_vertical_radius_multiplier: FloatProvider, + pub horizontal_radius_multiplier: FloatProvider, + pub vertical_radius_multiplier: FloatProvider, + pub start_vertical_radius_multiplier: FloatProvider, + pub floor_level: FloatProvider, +} +#[derive(Debug)] +pub enum CarverError { + Random(InvalidBound), + Geometry(CarveError), + IterationLimit, + InvalidBounds, +} +impl std::fmt::Display for CarverError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Random(e) => e.fmt(f), + Self::Geometry(e) => e.fmt(f), + Self::IterationLimit => f.write_str("carver work limit exceeded"), + Self::InvalidBounds => f.write_str("carver output or generation bounds are invalid"), + } + } +} +impl std::error::Error for CarverError {} +impl From for CarverError { + fn from(e: InvalidBound) -> Self { + Self::Random(e) + } +} +impl From> for CarverError { + fn from(e: CarveError) -> Self { + Self::Geometry(e) + } +} +impl CaveCarver { + pub fn from_json(json: &str) -> Result { + let object: Object = serde_json::from_str(json)?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + if kind != "minecraft:cave" { + return Err(DecodeError::Field("cave carver type")); + } + let probability: f32 = number_text(required(&object, "probability")?)? + .parse() + .map_err(|_| DecodeError::Field("carver probability"))?; + if !(0.0..=1.0).contains(&probability) || probability.is_sign_negative() { + return Err(DecodeError::Field("carver probability")); + } + let count = IntProvider::from_json(required(&object, "count")?.get())?; + if count.bounds()[0] < 0 { + return Err(DecodeError::Field("carver count")); + } + let provider = |name| FloatProvider::from_json(required(&object, name)?.get()); + let thickness = provider("thickness")?; + if thickness.bounds()[0] < 0. { + return Err(DecodeError::Field("carver thickness")); + } + let floor_level = provider("floor_level")?; + if floor_level.bounds()[0] < -1. || floor_level.bounds()[1] > 1. { + return Err(DecodeError::Field("carver floor")); + } + Ok(Self { + probability, + y: HeightProvider::from_json(required(&object, "y")?.get())?, + count, + thickness, + weird_thickness_bias: optional(&object, "weird_thickness_bias") + .map(|v| serde_json::from_str(v.get())) + .transpose()? + .unwrap_or(false), + room_vertical_radius_multiplier: provider("room_vertical_radius_multiplier")?, + horizontal_radius_multiplier: provider("horizontal_radius_multiplier")?, + vertical_radius_multiplier: provider("vertical_radius_multiplier")?, + start_vertical_radius_multiplier: optional(&object, "start_vertical_radius_multiplier") + .map(|v| FloatProvider::from_json(v.get())) + .transpose()? + .unwrap_or(FloatProvider::Constant(1.)), + floor_level, + }) + } + pub fn is_start_chunk(&self, random: &mut impl RandomSource) -> bool { + random.next_float() <= self.probability + } + /// Carve one origin chunk's paths into the target output. The caller performs + /// start-chunk selection separately. Local tunnel RNGs always use the legacy + /// algorithm, regardless of the caller's RNG. At most 4096 starts and 2^24 + /// candidate cells are allowed; errors preserve random draws and prior output. + pub fn carve( + &self, + context: WorldGenerationContext, + random: &mut impl RandomSource, + target: ChunkPos, + origin: ChunkPos, + output: &mut O, + ) -> Result> { + let count = self.count.sample(random)?; + if count > 4096 { + return Err(CarverError::IterationLimit); + } + let mut budget = 1 << 24; + for _ in 0..count { + let x = f64::from( + origin + .x + .wrapping_shl(4) + .wrapping_add(random.next_int_bound(16)?), + ); + let y = f64::from(self.y.sample(random, context)?); + let z = f64::from( + origin + .z + .wrapping_shl(4) + .wrapping_add(random.next_int_bound(16)?), + ); + let horizontal = f64::from(self.horizontal_radius_multiplier.sample(random)); + let vertical = f64::from(self.vertical_radius_multiplier.sample(random)); + let start_vertical = f64::from(self.start_vertical_radius_multiplier.sample(random)); + let floor = f64::from(self.floor_level.sample(random)); + let mut run = CaveRun { + target, + output, + budget: &mut budget, + horizontal, + vertical, + floor, + }; + let mut tunnels = 1; + if random.next_int_bound(4)? == 0 { + let multiplier = f64::from(self.room_vertical_radius_multiplier.sample(random)); + let thickness = 1. + random.next_float() * 6.; + let radius = + 1.5 + f64::from(sin(f64::from(std::f32::consts::FRAC_PI_2)) * thickness); + run.ellipsoid([x + 1., y, z], radius, radius * multiplier)?; + tunnels += random.next_int_bound(4)?; + } + for _ in 0..tunnels { + let yaw = random.next_float() * std::f32::consts::TAU; + let pitch = (random.next_float() - 0.5) / 4.; + let mut thickness = self.thickness.sample(random); + if self.weird_thickness_bias && random.next_int_bound(10)? == 0 { + thickness *= random.next_float() * random.next_float() * 3. + 1.; + } + let end = 112 - random.next_int_bound(28)?; + run.tunnel(Tunnel { + seed: random.next_long(), + position: [x, y, z], + thickness, + yaw, + pitch, + start: 0, + end, + vertical_scale: start_vertical, + })?; + } + } + Ok(true) + } +} +struct CaveRun<'a, O: CarverOutput> { + target: ChunkPos, + output: &'a mut O, + budget: &'a mut usize, + horizontal: f64, + vertical: f64, + floor: f64, +} +#[derive(Clone, Copy)] +struct Tunnel { + seed: i64, + position: [f64; 3], + thickness: f32, + yaw: f32, + pitch: f32, + start: i32, + end: i32, + vertical_scale: f64, +} +impl CaveRun<'_, O> { + fn ellipsoid( + &mut self, + position: [f64; 3], + horizontal: f64, + vertical: f64, + ) -> Result<(), CarverError> { + let floor = self.floor; + Ok(carve_ellipsoid_with_budget( + self.target, + position, + horizontal, + vertical, + self.output, + |[x, y, z], _| y <= floor || x * x + y * y + z * z >= 1., + self.budget, + )?) + } + fn tunnel(&mut self, mut path: Tunnel) -> Result<(), CarverError> { + let mut random = LegacyRandom::new(path.seed); + let split = random.next_int_bound(path.end / 2)? + path.end / 4; + let gentle = random.next_int_bound(6)? == 0; + let (mut yaw_change, mut pitch_change) = (0f32, 0f32); + for step in path.start..path.end { + let radius = 1.5 + + f64::from( + sin(f64::from( + std::f32::consts::PI * step as f32 / path.end as f32, + )) * path.thickness, + ); + let vertical = radius * path.vertical_scale; + let cos_pitch = cos(f64::from(path.pitch)); + path.position[0] += f64::from(cos(f64::from(path.yaw)) * cos_pitch); + path.position[1] += f64::from(sin(f64::from(path.pitch))); + path.position[2] += f64::from(sin(f64::from(path.yaw)) * cos_pitch); + path.pitch *= if gentle { 0.92 } else { 0.7 }; + path.pitch += pitch_change * 0.1; + path.yaw += yaw_change * 0.1; + pitch_change *= 0.9; + yaw_change *= 0.75; + pitch_change += (random.next_float() - random.next_float()) * random.next_float() * 2.; + yaw_change += (random.next_float() - random.next_float()) * random.next_float() * 4.; + if step == split && path.thickness > 1. { + let seed = random.next_long(); + let thickness = random.next_float() * 0.5 + 0.5; + self.tunnel(Tunnel { + seed, + thickness, + yaw: path.yaw - std::f32::consts::FRAC_PI_2, + pitch: path.pitch / 3., + start: step, + vertical_scale: 1., + ..path + })?; + let seed = random.next_long(); + let thickness = random.next_float() * 0.5 + 0.5; + self.tunnel(Tunnel { + seed, + thickness, + yaw: path.yaw + std::f32::consts::FRAC_PI_2, + pitch: path.pitch / 3., + start: step, + vertical_scale: 1., + ..path + })?; + return Ok(()); + } + if random.next_int_bound(4)? == 0 { + continue; + } + if !can_reach( + self.target, + path.position[0], + path.position[2], + step, + path.end, + path.thickness, + ) { + return Ok(()); + } + self.ellipsoid( + path.position, + radius * self.horizontal, + vertical * self.vertical, + )?; + } + Ok(()) + } +} diff --git a/crates/horizon-world/src/worldgen/carver/canyon.rs b/crates/horizon-world/src/worldgen/carver/canyon.rs new file mode 100644 index 000000000..33f745f54 --- /dev/null +++ b/crates/horizon-world/src/worldgen/carver/canyon.rs @@ -0,0 +1,161 @@ +use super::*; +use crate::worldgen::int_range; + +#[derive(Clone, Debug)] +pub struct CanyonShape { + pub distance_factor: FloatProvider, + pub thickness: FloatProvider, + pub width_smoothness: i32, + pub horizontal_radius_factor: FloatProvider, + pub vertical_radius_default_factor: f32, + pub vertical_radius_center_factor: f32, + pub y_scale: FloatProvider, +} +#[derive(Clone, Debug)] +pub struct CanyonCarver { + pub probability: f32, + pub y: HeightProvider, + pub vertical_rotation: FloatProvider, + pub shape: CanyonShape, +} +impl CanyonCarver { + pub fn from_json(json: &str) -> Result { + let object: Object = serde_json::from_str(json)?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + if kind != "minecraft:canyon" { + return Err(DecodeError::Field("canyon carver type")); + } + let probability = scalar(&object, "probability")?; + if !(0.0..=1.0).contains(&probability) || probability.is_sign_negative() { + return Err(DecodeError::Field("carver probability")); + } + let shape: Object = serde_json::from_str(required(&object, "shape")?.get())?; + let provider = |name| FloatProvider::from_json(required(&shape, name)?.get()); + Ok(Self { + probability, + y: HeightProvider::from_json(required(&object, "y")?.get())?, + vertical_rotation: FloatProvider::from_json( + required(&object, "vertical_rotation")?.get(), + )?, + shape: CanyonShape { + distance_factor: provider("distance_factor")?, + thickness: provider("thickness")?, + width_smoothness: int_range( + required(&shape, "width_smoothness")?, + "width_smoothness", + 1, + i32::MAX, + )?, + horizontal_radius_factor: provider("horizontal_radius_factor")?, + vertical_radius_default_factor: scalar(&shape, "vertical_radius_default_factor")?, + vertical_radius_center_factor: scalar(&shape, "vertical_radius_center_factor")?, + y_scale: provider("y_scale")?, + }, + }) + } + pub fn is_start_chunk(&self, random: &mut impl RandomSource) -> bool { + random.next_float() <= self.probability + } + /// Generate a canyon from one origin chunk. Width factors cover the entire + /// generation height and use a separate legacy random stream. Output bounds + /// must lie within that height; paths are bounded to 4096 steps, 4064 width + /// entries and 2^24 candidate cells. Earlier output survives errors. + pub fn carve( + &self, + context: WorldGenerationContext, + random: &mut impl RandomSource, + target: ChunkPos, + origin: ChunkPos, + output: &mut O, + ) -> Result> { + let mut x = f64::from( + origin + .x + .wrapping_shl(4) + .wrapping_add(random.next_int_bound(16)?), + ); + let mut y = f64::from(self.y.sample(random, context)?); + let mut z = f64::from( + origin + .z + .wrapping_shl(4) + .wrapping_add(random.next_int_bound(16)?), + ); + let mut yaw = random.next_float() * std::f32::consts::TAU; + let mut pitch = self.vertical_rotation.sample(random); + let y_scale = f64::from(self.shape.y_scale.sample(random)); + let thickness = self.shape.thickness.sample(random); + let end = (112f32 * self.shape.distance_factor.sample(random)) as i32; + let mut local = LegacyRandom::new(random.next_long()); + if !(1..=4064).contains(&context.height) + || output.min_y() < context.min_y + || i64::from(output.max_y()) > i64::from(context.min_y) + i64::from(context.height) + { + return Err(CarverError::InvalidBounds); + } + if end > 4096 { + return Err(CarverError::IterationLimit); + } + let mut width = Vec::with_capacity(context.height as usize); + let mut factor = 1f32; + for index in 0..context.height { + if index == 0 || local.next_int_bound(self.shape.width_smoothness)? == 0 { + factor = 1. + local.next_float() * local.next_float(); + } + width.push(factor * factor); + } + let (mut yaw_change, mut pitch_change) = (0f32, 0f32); + let mut budget = 1 << 24; + for step in 0..end { + let mut horizontal = 1.5 + + f64::from( + sin(f64::from(step as f32 * std::f32::consts::PI / end as f32)) * thickness, + ); + let mut vertical = horizontal * y_scale; + horizontal *= f64::from(self.shape.horizontal_radius_factor.sample(&mut local)); + let center = 1. - (0.5 - step as f32 / end as f32).abs() * 2.; + let multiplier = self.shape.vertical_radius_default_factor + + self.shape.vertical_radius_center_factor * center; + vertical = (f64::from(multiplier) * vertical) + * f64::from(local.next_float() * (1. - 0.75) + 0.75); + let cos_pitch = cos(f64::from(pitch)); + let sin_pitch = sin(f64::from(pitch)); + x += f64::from(cos(f64::from(yaw)) * cos_pitch); + y += f64::from(sin_pitch); + z += f64::from(sin(f64::from(yaw)) * cos_pitch); + pitch *= 0.7; + pitch += pitch_change * 0.05; + yaw += yaw_change * 0.05; + pitch_change *= 0.8; + yaw_change *= 0.5; + pitch_change += (local.next_float() - local.next_float()) * local.next_float() * 2.; + yaw_change += (local.next_float() - local.next_float()) * local.next_float() * 4.; + if local.next_int_bound(4)? == 0 { + continue; + } + if !can_reach(target, x, z, step, end, thickness) { + return Ok(true); + } + carve_ellipsoid_with_budget( + target, + [x, y, z], + horizontal, + vertical, + output, + |[nx, ny, nz], by| { + let factor = width[by.wrapping_sub(context.min_y).wrapping_sub(1) as usize]; + (nx * nx + nz * nz) * f64::from(factor) + ny * ny / 6. >= 1. + }, + &mut budget, + )?; + } + Ok(true) + } +} +fn scalar(object: &Object, name: &'static str) -> Result { + number_text(required(object, name)?)? + .parse() + .map_err(|_| DecodeError::Field(name)) +} diff --git a/crates/horizon-world/src/worldgen/carver/generation.rs b/crates/horizon-world/src/worldgen/carver/generation.rs new file mode 100644 index 000000000..40cd5cfd3 --- /dev/null +++ b/crates/horizon-world/src/worldgen/carver/generation.rs @@ -0,0 +1,167 @@ +//! Biome-selected neighboring carvers and their per-entry legacy seeds. +use super::{CanyonCarver, CarverError, CaveCarver}; +use crate::worldgen::{ + DecodeError, Object, anchor::WorldGenerationContext, density::identifier, required, +}; +use horizon_core::{ + carving::{CarverOutput, CarvingMask, CarvingMaskError}, + position::ChunkPos, + random::{LegacyRandom, RandomSource}, +}; +use std::{collections::BTreeMap, sync::Arc}; + +#[derive(Clone, Debug)] +pub enum WorldCarver { + Cave(CaveCarver), + Canyon(CanyonCarver), +} +impl WorldCarver { + pub fn from_json(json: &str) -> Result { + let object: Object = serde_json::from_str(json)?; + match identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)? + .as_str() + { + "minecraft:cave" => Ok(Self::Cave(CaveCarver::from_json(json)?)), + "minecraft:canyon" => Ok(Self::Canyon(CanyonCarver::from_json(json)?)), + _ => Err(DecodeError::Field("world carver type")), + } + } + pub fn is_start_chunk(&self, random: &mut impl RandomSource) -> bool { + match self { + Self::Cave(c) => c.is_start_chunk(random), + Self::Canyon(c) => c.is_start_chunk(random), + } + } + pub fn carve( + &self, + context: WorldGenerationContext, + random: &mut impl RandomSource, + target: ChunkPos, + origin: ChunkPos, + output: &mut O, + ) -> Result> { + match self { + Self::Cave(c) => c.carve(context, random, target, origin, output), + Self::Canyon(c) => c.carve(context, random, target, origin, output), + } + } +} +/// Immutable named carvers. Inline definitions and direct holder lists are +/// supported; tagged sets and live registry reloads remain separate work. +pub struct CarverCatalog { + definitions: BTreeMap>, +} +impl CarverCatalog { + pub fn from_json(definitions: &BTreeMap) -> Result { + if definitions.len() > 8192 { + return Err(DecodeError::Field("carver registry size")); + } + let mut result = BTreeMap::new(); + for (name, json) in definitions { + let name = identifier(name)?; + if result + .insert(name, Arc::new(WorldCarver::from_json(json)?)) + .is_some() + { + return Err(DecodeError::Field("duplicate carver name")); + } + } + Ok(Self { + definitions: result, + }) + } + pub fn decode_set(&self, json: &str) -> Result>, DecodeError> { + use serde_json::value::RawValue; + let raw: Box = serde_json::from_str(json)?; + let entries: Vec> = if raw.get().starts_with('[') { + serde_json::from_str(raw.get())? + } else { + vec![raw] + }; + if entries.len() > 1024 { + return Err(DecodeError::Field("biome carver count")); + } + entries + .iter() + .map(|raw| { + if let Ok(name) = serde_json::from_str::(raw.get()) { + let name = identifier(&name)?; + self.definitions + .get(&name) + .cloned() + .ok_or_else(|| DecodeError::Registry(format!("unknown carver {name}"))) + } else { + Ok(Arc::new(WorldCarver::from_json(raw.get())?)) + } + }) + .collect() + } +} +#[derive(Debug)] +pub enum MaskGenerationError { + Source(E), + Mask(CarvingMaskError), + Carver(CarverError), + TooManyCarvers, +} +impl std::fmt::Display for MaskGenerationError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Source(e) => e.fmt(f), + Self::Mask(e) => e.fmt(f), + Self::Carver(e) => e.fmt(f), + Self::TooManyCarvers => f.write_str("biome carver count exceeds 1024"), + } + } +} +impl std::error::Error for MaskGenerationError {} + +/// Build the union mask from a 17×17 origin neighborhood, X then Z. The provider +/// selects each origin's ordered biome carvers using its uncached biome resolver +/// at the origin's minimum quart X/Z and quart Y=0. Repeated entries keep their +/// individual ordinal seeds. The caller applies a successfully returned mask. +pub fn generate_carving_mask<'a, E>( + world_seed: i64, + target: ChunkPos, + context: WorldGenerationContext, + upgrading: bool, + mut carvers: impl FnMut(ChunkPos) -> Result<&'a [Arc], E>, +) -> Result> { + let min = context.min_y.wrapping_add(1); + let max = context + .min_y + .wrapping_add(context.height) + .wrapping_sub(1) + .wrapping_sub(if upgrading { 0 } else { 7 }); + let mut mask = CarvingMask::new(min, max).map_err(MaskGenerationError::Mask)?; + for dx in -8..=8 { + for dz in -8..=8 { + let origin = ChunkPos::new(target.x.wrapping_add(dx), target.z.wrapping_add(dz)); + let selected = carvers(origin).map_err(MaskGenerationError::Source)?; + if selected.len() > 1024 { + return Err(MaskGenerationError::TooManyCarvers); + } + for (index, carver) in selected.iter().enumerate() { + let mut random = + large_feature_random(world_seed.wrapping_add(index as i64), origin); + if carver.is_start_chunk(&mut random) { + carver + .carve(context, &mut random, target, origin, &mut mask) + .map_err(MaskGenerationError::Carver)?; + } + } + } + } + Ok(mask) +} +/// The legacy `WorldgenRandom.setLargeFeatureSeed` stream used by carving. +pub fn large_feature_random(seed: i64, origin: ChunkPos) -> LegacyRandom { + let mut random = LegacyRandom::new(seed); + let x = random.next_long(); + let z = random.next_long(); + random + .set_seed(i64::from(origin.x).wrapping_mul(x) ^ i64::from(origin.z).wrapping_mul(z) ^ seed); + random +} diff --git a/crates/horizon-world/src/worldgen/carving.rs b/crates/horizon-world/src/worldgen/carving.rs new file mode 100644 index 000000000..bb19df9d3 --- /dev/null +++ b/crates/horizon-world/src/worldgen/carving.rs @@ -0,0 +1,122 @@ +//! Apply ordered carving-mask intervals to pre-lighting terrain. +use super::{ + material_condition::{MaterialRule, MaterialSurfaceQueries}, + material_stage::{SurfaceError, TopMaterialInputs, top_material}, + terrain::{TerrainAquifer, TerrainBlockStates, TerrainChunk, TerrainError}, +}; +use crate::{ + heightmap::HeightmapState, + registry::{BlockRegistry, BlockStateId}, +}; +use horizon_core::{carving::CarvingMask, position::BlockPos, random::RandomSource}; +use std::collections::BTreeSet; + +/// Per-state predicates resolved once from the world's block registry and +/// `minecraft:uncarvable` tag. Keep these bound to the same registry as the chunk. +pub struct CarvingBlocks { + flags: Vec, +} +impl CarvingBlocks { + pub fn from_registry( + registry: &BlockRegistry, + uncarvable: &BTreeSet, + ) -> Result { + for name in uncarvable.iter().map(String::as_str).chain([ + "minecraft:grass_block", + "minecraft:mycelium", + "minecraft:dirt", + ]) { + if registry.default_state(name).is_none() { + return Err(TerrainError::InvalidState); + } + } + let flags = (0..registry.len()) + .map(|index| { + let name = ®istry.state(BlockStateId(index as u32)).unwrap().name; + u8::from(uncarvable.contains(name)) + | (u8::from(matches!( + name.as_str(), + "minecraft:grass_block" | "minecraft:mycelium" + )) << 1) + | (u8::from(name == "minecraft:dirt") << 2) + }) + .collect(); + Ok(Self { flags }) + } + fn flags(&self, state: BlockStateId) -> Result { + self.flags + .get(state.0 as usize) + .copied() + .ok_or(TerrainError::InvalidState) + } +} + +/// Visit mask runs in packed order and each interval top to bottom. The filter +/// receives local X/Z and absolute Y before any block or aquifer lookup. A run +/// remembers grass/mycelium even if its aquifer returns no replacement. Exposed +/// dirt below subsequent carved cells is restored through `top_material`. +/// Earlier writes, aquifer state and fluid postprocessing survive later errors. +pub fn apply_carving_mask( + chunk: &mut TerrainChunk<'_, B>, + mask: &CarvingMask, + rule: MaterialRule, + mut inputs: TopMaterialInputs<'_, R, S>, + aquifer: &mut (impl TerrainAquifer + ?Sized), + blocks: &CarvingBlocks, + mut filter: impl FnMut([i32; 3]) -> bool, +) -> Result<(), SurfaceError> +where + R::Positional: Clone, +{ + let cx = chunk.position().x.wrapping_shl(4); + let cz = chunk.position().z.wrapping_shl(4); + for column in mask.columns() { + let mut found_surface = false; + let x = cx.wrapping_add(column.x); + let z = cz.wrapping_add(column.z); + for y in (column.min_y..=column.max_y).rev() { + if !filter([column.x, y, column.z]) { + continue; + } + let flags = blocks.flags(chunk.block(x, y, z))?; + if flags & 1 != 0 { + continue; + } + found_surface |= flags & 2 != 0; + let Some(state) = aquifer + .compute_substance(inputs.density_context, [x, y, z], 0.) + .map_err(TerrainError::from)? + else { + continue; + }; + chunk.set_block_worldgen(x, y, z, state)?; + if aquifer.should_schedule_fluid_update() && chunk.block_properties(state).has_fluid() { + chunk.mark_postprocessing(x, y, z); + } + let below = y.wrapping_sub(1); + if found_surface && blocks.flags(chunk.block(x, below, z))? & 4 != 0 { + let submerged = chunk.block_properties(state).has_fluid(); + let replacement = top_material( + chunk, + rule.clone(), + TopMaterialInputs:: { + generation: inputs.generation, + root: inputs.root.clone(), + surface: &mut inputs.surface, + preliminary_surface: inputs.preliminary_surface.clone(), + density_context: inputs.density_context, + }, + BlockPos::new(x, below, z), + submerged, + )?; + if let Some(replacement) = replacement { + chunk.set_block_worldgen(x, below, z, replacement)?; + if chunk.block_properties(replacement).has_fluid() { + chunk.mark_postprocessing(x, below, z); + } + } + } + } + } + Ok(()) +} diff --git a/crates/horizon-world/src/worldgen/climate.rs b/crates/horizon-world/src/worldgen/climate.rs new file mode 100644 index 000000000..92c8bb080 --- /dev/null +++ b/crates/horizon-world/src/worldgen/climate.rs @@ -0,0 +1,118 @@ +//! Climate coordinates derived from the six terrain-router climate fields. +use horizon_core::density::{DensitySampler, SampleError, SamplerContext}; +use horizon_core::noise::DensityVolume; +use std::sync::Arc; +mod codec; +mod index; +pub use codec::{decode_parameter, decode_parameter_point}; +pub use index::{ClimateIndex, ClimateSearch, IndexError, Parameter, ParameterPoint}; + +/// Vanilla multiplies in float precision before the saturating Java long cast. +pub fn quantize(value: f32) -> i64 { + (value * 10_000.0) as i64 +} +pub fn unquantize(value: i64) -> f32 { + value as f32 / 10_000.0 +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TargetPoint { + pub temperature: i64, + pub humidity: i64, + pub continentalness: i64, + pub erosion: i64, + pub depth: i64, + pub weirdness: i64, +} +impl TargetPoint { + pub fn from_values(values: [f32; 6]) -> Self { + let [ + temperature, + humidity, + continentalness, + erosion, + depth, + weirdness, + ] = values.map(quantize); + Self { + temperature, + humidity, + continentalness, + erosion, + depth, + weirdness, + } + } + /// The seventh parameter is the zero offset used by biome nearest searches. + pub const fn parameters(self) -> [i64; 7] { + [ + self.temperature, + self.humidity, + self.continentalness, + self.erosion, + self.depth, + self.weirdness, + 0, + ] + } +} +#[derive(Clone, Debug)] +pub struct ClimateSampler { + samplers: [Arc; 6], +} +impl ClimateSampler { + /// Temperature, humidity, continentalness, erosion, depth, weirdness. + pub fn new(samplers: [Arc; 6]) -> Self { + Self { samplers } + } + /// Coordinates are biome quart positions, converted with wrapped << 2. + /// Every child uses the same context and runs in field declaration order. + pub fn sample( + &self, + context: &mut SamplerContext, + quart: [i32; 3], + ) -> Result { + let position = quart.map(|coordinate| coordinate.wrapping_shl(2)); + let mut values = [0.; 6]; + for (sampler, value) in self.samplers.iter().zip(&mut values) { + *value = sampler.sample_value(context, position)?; + } + Ok(TargetPoint::from_values(values)) + } + /// Prepare all six field buffers in declaration order on the quart lattice. + /// Lookup quantizes the retained bulk values rather than resampling scalars. + pub fn sample_volume( + &self, + context: &mut SamplerContext, + quart_minimum: [i32; 3], + extents: [i32; 3], + ) -> Result { + let volume = DensityVolume::new(extents, quart_minimum.map(|v| v.wrapping_shl(2)), [4; 3])?; + let mut fields = std::array::from_fn(|_| vec![0.; volume.size()]); + for (sampler, field) in self.samplers.iter().zip(&mut fields) { + sampler.sample_volume(context, field, volume)?; + } + Ok(ClimateVolume { + quart_minimum, + volume, + fields, + }) + } +} +#[derive(Debug)] +pub struct ClimateVolume { + quart_minimum: [i32; 3], + volume: DensityVolume, + fields: [Vec; 6], +} +impl ClimateVolume { + /// Coordinates must be inside the prepared quart volume. The bounded Rust + /// API rejects invalid coordinates instead of Java's unchecked buffer alias. + pub fn target(&self, quart: [i32; 3]) -> Option { + let relative = + std::array::from_fn(|i| quart[i].wrapping_sub(self.quart_minimum[i]) as usize); + let index = self.volume.index(relative)?; + Some(TargetPoint::from_values(std::array::from_fn(|i| { + self.fields[i][index] + }))) + } +} diff --git a/crates/horizon-world/src/worldgen/climate/codec.rs b/crates/horizon-world/src/worldgen/climate/codec.rs new file mode 100644 index 000000000..8ea0d00d6 --- /dev/null +++ b/crates/horizon-world/src/worldgen/climate/codec.rs @@ -0,0 +1,59 @@ +use super::super::{DecodeError, Object, RawValue, number_text, required}; +use super::{Parameter, ParameterPoint, quantize}; + +fn float(raw: &RawValue, min: f32, max: f32) -> Result { + let value: f32 = number_text(raw)? + .parse() + .map_err(|_| DecodeError::Field("climate float"))?; + if value.total_cmp(&min).is_lt() || value.total_cmp(&max).is_gt() { + return Err(DecodeError::Field("climate float bounds")); + } + Ok(value) +} +fn parameter(raw: &RawValue) -> Result { + let (min, max) = if raw.get().starts_with('[') { + let values: Vec> = serde_json::from_str(raw.get())?; + if values.len() != 2 { + return Err(DecodeError::Field("climate interval length")); + } + (float(&values[0], -2., 2.)?, float(&values[1], -2., 2.)?) + } else if raw.get().starts_with('{') { + let object: Object = serde_json::from_str(raw.get())?; + ( + float(required(&object, "min")?, -2., 2.)?, + float(required(&object, "max")?, -2., 2.)?, + ) + } else { + let value = float(raw, -2., 2.)?; + (value, value) + }; + if min.total_cmp(&max).is_gt() { + return Err(DecodeError::Field("climate interval order")); + } + Ok(Parameter::new(quantize(min), quantize(max))) +} +/// Vanilla's scalar, two-element list or min/max object climate interval codec. +pub fn decode_parameter(json: &str) -> Result { + let raw: Box = serde_json::from_str(json)?; + parameter(&raw) +} +/// Six required climate intervals and a required offset in [0,1]. +pub fn decode_parameter_point(json: &str) -> Result { + let object: Object = serde_json::from_str(json)?; + let mut coordinates = [Parameter::new(0, 0); 6]; + for (coordinate, name) in coordinates.iter_mut().zip([ + "temperature", + "humidity", + "continentalness", + "erosion", + "depth", + "weirdness", + ]) { + *coordinate = parameter(required(&object, name)?)?; + } + let offset = quantize(float(required(&object, "offset")?, 0., 1.)?); + Ok(ParameterPoint { + coordinates, + offset, + }) +} diff --git a/crates/horizon-world/src/worldgen/climate/index.rs b/crates/horizon-world/src/worldgen/climate/index.rs new file mode 100644 index 000000000..3e9b50f51 --- /dev/null +++ b/crates/horizon-world/src/worldgen/climate/index.rs @@ -0,0 +1,325 @@ +//! Immutable climate search tree with an explicit per-worker previous result. +use super::{TargetPoint, quantize}; +use std::cmp::Ordering; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Parameter { + pub min: i64, + pub max: i64, +} +impl Parameter { + /// The record constructor does not validate endpoint order. + pub const fn new(min: i64, max: i64) -> Self { + Self { min, max } + } + pub fn point(value: f32) -> Self { + let value = quantize(value); + Self::new(value, value) + } + pub fn span(min: f32, max: f32) -> Result { + if min > max { + return Err(IndexError::InvertedSpan); + } + Ok(Self::new(quantize(min), quantize(max))) + } + pub fn distance(self, value: i64) -> i64 { + let above = value.wrapping_sub(self.max); + if above > 0 { + above + } else { + self.min.wrapping_sub(value).max(0) + } + } + fn union(self, other: Self) -> Self { + Self::new(self.min.min(other.min), self.max.max(other.max)) + } + fn center(self) -> i64 { + self.min.wrapping_add(self.max) / 2 + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ParameterPoint { + /// Temperature, humidity, continentalness, erosion, depth, weirdness. + pub coordinates: [Parameter; 6], + pub offset: i64, +} +impl ParameterPoint { + pub fn fitness(self, target: TargetPoint) -> i64 { + self.coordinates.iter().zip(target.parameters()).fold( + self.offset.wrapping_mul(self.offset), + |sum, (parameter, value)| { + let distance = parameter.distance(value); + sum.wrapping_add(distance.wrapping_mul(distance)) + }, + ) + } + pub fn parameter_space(self) -> [Parameter; 7] { + std::array::from_fn(|i| { + if i < 6 { + self.coordinates[i] + } else { + Parameter::new(self.offset, self.offset) + } + }) + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum IndexError { + Empty, + TooManyEntries, + InvalidBranching, + InvertedSpan, + NoSplit, + NoResult, +} +impl std::fmt::Display for IndexError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Empty => "climate search requires at least one entry", + Self::TooManyEntries => "climate search is limited to 65536 entries", + Self::InvalidBranching => "climate branching must be in 2..=32", + Self::InvertedSpan => "climate interval endpoints are inverted", + Self::NoSplit => "climate tree could not select a split", + Self::NoResult => "climate search found no result", + }) + } +} +impl std::error::Error for IndexError {} + +#[derive(Debug)] +enum Children { + Leaf(usize), + Branch(Vec), +} +#[derive(Debug)] +struct Node { + space: [Parameter; 7], + children: Children, +} +fn distance(space: &[Parameter; 7], values: &[i64; 7]) -> i64 { + space + .iter() + .zip(values) + .fold(0i64, |sum, (parameter, value)| { + let distance = parameter.distance(*value); + sum.wrapping_add(distance.wrapping_mul(distance)) + }) +} +fn compare_space(a: &[Parameter; 7], b: &[Parameter; 7], axis: usize, absolute: bool) -> Ordering { + for i in 0..7 { + let coordinate = (axis + i) % 7; + let key = |p: Parameter| { + if absolute { + p.center().wrapping_abs() + } else { + p.center() + } + }; + let result = key(a[coordinate]).cmp(&key(b[coordinate])); + if result != Ordering::Equal { + return result; + } + } + Ordering::Equal +} +#[derive(Debug)] +struct Bucket { + space: [Parameter; 7], + children: Vec, +} +fn space(nodes: &[Node], children: &[usize]) -> [Parameter; 7] { + let mut space = nodes[children[0]].space; + for child in &children[1..] { + for (parameter, other) in space.iter_mut().zip(nodes[*child].space) { + *parameter = parameter.union(other); + } + } + space +} +fn build( + nodes: &mut Vec, + mut children: Vec, + branching: usize, +) -> Result { + if children.len() == 1 { + return Ok(children[0]); + } + if children.len() <= branching { + // Stable sorting matters when centers and total center distance tie. + children.sort_by_key(|id| { + nodes[*id] + .space + .iter() + .fold(0i64, |sum, p| sum.wrapping_add(p.center().wrapping_abs())) + }); + } else { + // For this bounded domain this is the same bucket size as vanilla's + // pow(branching,floor(log(length-0.01)/log(branching))). Integer powers + // avoid depending on platform double logarithms during construction. + let mut bucket_size = 1; + while bucket_size * branching < children.len() { + bucket_size *= branching; + } + let mut best_cost = i64::MAX; + let mut best = None; + for axis in 0..7 { + children.sort_by(|a, b| compare_space(&nodes[*a].space, &nodes[*b].space, axis, false)); + let buckets: Vec<_> = children + .chunks(bucket_size) + .map(|children| Bucket { + space: space(nodes, children), + children: children.to_vec(), + }) + .collect(); + let cost = buckets.iter().fold(0i64, |sum, bucket| { + bucket.space.iter().fold(sum, |sum, p| { + sum.wrapping_add(p.max.wrapping_sub(p.min).wrapping_abs()) + }) + }); + if best_cost > cost { + best_cost = cost; + best = Some((axis, buckets)); + } + } + let (axis, mut buckets) = best.ok_or(IndexError::NoSplit)?; + buckets.sort_by(|a, b| compare_space(&a.space, &b.space, axis, true)); + children = buckets + .into_iter() + .map(|bucket| build(nodes, bucket.children, branching)) + .collect::>()?; + } + let space = space(nodes, &children); + let id = nodes.len(); + nodes.push(Node { + space, + children: Children::Branch(children), + }); + Ok(id) +} + +/// The index is immutable and can be shared; each searcher owns its cache. +/// Entry count and branching are explicit limits of this bounded Rust API. +#[derive(Debug)] +pub struct ClimateIndex { + entries: Vec<(ParameterPoint, T)>, + nodes: Vec, + root: usize, +} +impl ClimateIndex { + pub fn new(entries: Vec<(ParameterPoint, T)>) -> Result { + Self::with_branching(entries, 19) + } + pub fn with_branching( + entries: Vec<(ParameterPoint, T)>, + branching: usize, + ) -> Result { + if entries.is_empty() { + return Err(IndexError::Empty); + } + if entries.len() > 65536 { + return Err(IndexError::TooManyEntries); + } + if !(2..=32).contains(&branching) { + return Err(IndexError::InvalidBranching); + } + let mut nodes: Vec<_> = entries + .iter() + .enumerate() + .map(|(id, (point, _))| Node { + space: point.parameter_space(), + children: Children::Leaf(id), + }) + .collect(); + let children = (0..nodes.len()).collect(); + let root = build(&mut nodes, children, branching)?; + Ok(Self { + entries, + nodes, + root, + }) + } + pub fn entries(&self) -> &[(ParameterPoint, T)] { + &self.entries + } + pub fn searcher(&self) -> ClimateSearch<'_, T> { + ClimateSearch { + index: self, + last: None, + } + } + /// Vanilla's separate reference path: ties retain input-list order and do + /// not consult or update the searcher's previous indexed result. + pub fn brute_force(&self, target: TargetPoint) -> &T { + let mut best = 0; + let mut fitness = self.entries[0].0.fitness(target); + for (id, (point, _)) in self.entries.iter().enumerate().skip(1) { + let next = point.fitness(target); + if next < fitness { + fitness = next; + best = id; + } + } + &self.entries[best].1 + } + /// Preorder leaf entry indices expose stable tree layout for comparison. + pub fn leaf_order(&self) -> Vec { + fn walk(nodes: &[Node], id: usize, out: &mut Vec) { + match &nodes[id].children { + Children::Leaf(entry) => out.push(*entry), + Children::Branch(children) => { + for child in children { + walk(nodes, *child, out); + } + } + } + } + let mut result = Vec::with_capacity(self.entries.len()); + walk(&self.nodes, self.root, &mut result); + result + } + fn search( + &self, + id: usize, + values: &[i64; 7], + previous: Option, + ) -> Result { + let Children::Branch(children) = &self.nodes[id].children else { + return Ok(id); + }; + let mut best = previous; + let mut fitness = previous.map_or(i64::MAX, |id| distance(&self.nodes[id].space, values)); + for child in children { + let lower = distance(&self.nodes[*child].space, values); + if fitness > lower { + let result = self.search(*child, values, best)?; + let next = if result == *child { + lower + } else { + distance(&self.nodes[result].space, values) + }; + if fitness > next { + fitness = next; + best = Some(result); + } + } + } + best.ok_or(IndexError::NoResult) + } +} +#[derive(Debug)] +pub struct ClimateSearch<'a, T> { + index: &'a ClimateIndex, + last: Option, +} +impl<'a, T> ClimateSearch<'a, T> { + pub fn find(&mut self, target: TargetPoint) -> Result<&'a T, IndexError> { + let result = self + .index + .search(self.index.root, &target.parameters(), self.last)?; + self.last = Some(result); + let Children::Leaf(entry) = self.index.nodes[result].children else { + unreachable!("search returns a leaf"); + }; + Ok(&self.index.entries[entry].1) + } +} diff --git a/crates/horizon-world/src/worldgen/decoration.rs b/crates/horizon-world/src/worldgen/decoration.rs new file mode 100644 index 000000000..0963e3f8b --- /dev/null +++ b/crates/horizon-world/src/worldgen/decoration.rs @@ -0,0 +1,141 @@ +//! Biome-selected feature scheduling. Structure decoration is a separate stage. +use super::{ + feature_sort::{FeatureIdentity, FeatureSortError, StepFeatureData, build_features_per_step}, + placement::FeaturePlacer, +}; +use horizon_core::{ + position::ChunkPos, + random::{WorldgenRandom, XoroshiroRandom}, +}; +use std::collections::{BTreeMap, BTreeSet}; + +pub use super::biome::BiomeId as DecorationBiome; + +/// Transport for resident section palettes and generation progress. +pub trait DecorationWorld { + type Error; + fn min_section_y(&mut self) -> Result; + /// Return values present in every section's biome palette, including values + /// outside the generator's possible-biome set. Duplicates are allowed. + fn chunk_biomes(&mut self, chunk: ChunkPos) -> Result, Self::Error>; + fn set_currently_generating( + &mut self, + feature: Option, + ) -> Result<(), Self::Error>; +} + +#[derive(Debug)] +pub enum DecorationError { + World(E), + Feature { feature: FeatureIdentity, error: E }, + WorkLimit, +} +impl std::fmt::Display for DecorationError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::World(e) => e.fmt(f), + Self::Feature { feature, error } => write!(f, "feature {}: {error}", feature.0), + Self::WorkLimit => f.write_str("decoration work limit exceeded"), + } + } +} +impl std::error::Error for DecorationError {} + +#[derive(Clone, Debug)] +pub struct FeatureDecorationPlan { + biomes: BTreeMap>>, + steps: Vec, +} +impl FeatureDecorationPlan { + /// The list must preserve the generator's possible-biome encounter order. + /// Each biome identity occurs once; feature identity is allocation identity. + pub fn new( + biomes: Vec<(DecorationBiome, Vec>)>, + ) -> Result { + let ordered = biomes + .iter() + .map(|(_, steps)| steps.clone()) + .collect::>(); + let steps = build_features_per_step(&ordered)?; + let count = biomes.len(); + let biomes = biomes.into_iter().collect::>(); + if biomes.len() != count { + return Err(FeatureSortError::DuplicateBiome); + } + Ok(Self { biomes, steps }) + } + + /// Execute the feature branch of chunk decoration with structures disabled. + /// The callback must place the identified root with a biome-check context. + /// It receives one shared placer and the correctly reseeded random stream; + /// false results are ignored. Errors stop immediately without clearing the + /// current-feature marker. A subsequent call starts with fresh placer state. + pub fn decorate_features( + &self, + world: &mut W, + chunk: ChunkPos, + world_seed: i64, + mut place: impl FnMut( + &mut W, + &mut FeaturePlacer, + &mut WorldgenRandom, + FeatureIdentity, + [i32; 3], + ) -> Result, + ) -> Result<(), DecorationError> { + let origin = [ + chunk.x.wrapping_shl(4), + world + .min_section_y() + .map_err(DecorationError::World)? + .wrapping_shl(4), + chunk.z.wrapping_shl(4), + ]; + let mut random = WorldgenRandom::new(XoroshiroRandom::new(0)); + let seed = random.set_decoration_seed(world_seed, origin[0], origin[2]); + // ChunkPos.rangeClosed overflows into a huge reversed traversal at the + // extreme i32 chunk coordinates. Bound that unsupported work explicitly. + if [chunk.x, chunk.z] + .iter() + .any(|v| *v == i32::MIN || *v == i32::MAX) + { + return Err(DecorationError::WorkLimit); + } + let mut present = BTreeSet::new(); + for z in chunk.z - 1..=chunk.z + 1 { + for x in chunk.x - 1..=chunk.x + 1 { + let values = world + .chunk_biomes(ChunkPos::new(x, z)) + .map_err(DecorationError::World)?; + if values.len() > 65536 { + return Err(DecorationError::WorkLimit); + } + present.extend(values.into_iter().filter(|id| self.biomes.contains_key(id))); + } + } + let mut placer = FeaturePlacer::new(); + for (step, data) in self.steps.iter().enumerate() { + let mut selected = BTreeSet::new(); + for biome in &present { + if let Some(features) = self.biomes[biome].get(step) { + selected.extend(features.iter().map(|feature| { + data.index(*feature) + .expect("plan owns complete biome feature lists") + })); + } + } + for index in selected { + let feature = data.features()[index]; + random.set_feature_seed(seed, index as i32, step as i32); + world + .set_currently_generating(Some(feature)) + .map_err(|error| DecorationError::Feature { feature, error })?; + place(world, &mut placer, &mut random, feature, origin) + .map_err(|error| DecorationError::Feature { feature, error })?; + } + } + world + .set_currently_generating(None) + .map_err(DecorationError::World) + } +} diff --git a/crates/horizon-world/src/worldgen/density.rs b/crates/horizon-world/src/worldgen/density.rs new file mode 100644 index 000000000..6cd2c7df7 --- /dev/null +++ b/crates/horizon-world/src/worldgen/density.rs @@ -0,0 +1,578 @@ +//! Bounded decoding of density registries into the immutable core graph. +//! Named registry holders and raw numeric tokens preserve compilation behavior. +use super::*; +use horizon_core::{ + density::{ + BlendedNoise, CubicSpline, DistanceMetric, RoundMode, ShiftNoiseKind, SplinePoint, + TilingMode, WorldField, + graph::{DensityGraph, FunctionId, GraphBinary, GraphNode, GraphUnary, NoiseId}, + }, + geometry::Axis, +}; +use std::{collections::BTreeSet, sync::Arc}; + +pub(super) fn identifier(name: &str) -> Result { + let (namespace, path) = name.split_once(':').unwrap_or(("minecraft", name)); + let namespace = if namespace.is_empty() { + "minecraft" + } else { + namespace + }; + let valid = |c: u8| c.is_ascii_lowercase() || c.is_ascii_digit() || b"_.-".contains(&c); + if !namespace.bytes().all(valid) + || !path.bytes().all(|c| valid(c) || c == b'/') + || path.is_empty() + { + return Err(DecodeError::Registry(format!( + "invalid registry identifier: {name}" + ))); + } + Ok(format!("{namespace}:{path}")) +} +fn string(raw: &RawValue) -> Result { + Ok(serde_json::from_str(raw.get())?) +} +fn float(raw: &RawValue) -> Result { + number_text(raw)? + .parse() + .map_err(|_| DecodeError::Field("float")) +} +fn noise_value(raw: &RawValue) -> Result { + let value = float(raw)?; + if (-1e6..=1e6).contains(&value) { + Ok(value) + } else { + Err(DecodeError::Field("density value")) + } +} +fn axis(raw: &RawValue) -> Result { + match string(raw)?.as_str() { + "x" => Ok(Axis::X), + "y" => Ok(Axis::Y), + "z" => Ok(Axis::Z), + _ => Err(DecodeError::Field("axis")), + } +} + +/// All entries are loaded atomically. Named child references resolve through +/// distinct registry holders; returned entry values are their direct graphs. +#[derive(Debug)] +pub struct DensityRegistry { + graph: DensityGraph, + values: BTreeMap, + noises: BTreeMap, +} +impl DensityRegistry { + /// Input keys are registry identifiers, and values contain original JSON. + /// This API accepts acyclic registries, at most 256 nested graph levels and + /// at most 256 interval branches. Inline noise holders are not yet supported. + pub fn from_json( + noises: &BTreeMap, + densities: &BTreeMap, + ) -> Result { + let mut loader = Loader { + graph: DensityGraph::new(), + noises: BTreeMap::new(), + definitions: BTreeMap::new(), + values: BTreeMap::new(), + active: BTreeSet::new(), + }; + for (name, json) in noises { + let name = identifier(name)?; + let noise = loader + .graph + .register_noise(name.clone(), decode_noise(json)?)?; + loader.noises.insert(name, noise); + } + for (name, json) in densities { + let name = identifier(name)?; + let raw: Box = serde_json::from_str(json)?; + if loader.definitions.insert(name.clone(), raw).is_some() { + return Err(DecodeError::Registry(format!( + "duplicate density identifier: {name}" + ))); + } + } + let names: Vec<_> = loader.definitions.keys().cloned().collect(); + for name in names { + loader.resolve(&name, 0)?; + } + Ok(Self { + graph: loader.graph, + values: loader.values, + noises: loader.noises, + }) + } + pub fn graph(&self) -> &DensityGraph { + &self.graph + } + pub fn into_graph(self) -> DensityGraph { + self.graph + } + pub fn entries(&self) -> impl Iterator { + self.values.iter().map(|(name, id)| (name.as_str(), *id)) + } + pub fn value(&self, name: &str) -> Option { + self.values.get(name).copied() + } + pub fn reference(&self, name: &str) -> Option { + self.graph.function(name) + } + /// Decode direct roots against this registry, retaining shared named holders. + /// All roots are added atomically; a failure leaves existing IDs and graphs + /// intact. Roots are not registered as additional named density entries. + pub fn decode_functions(&mut self, json: &[&str]) -> Result, DecodeError> { + let mut loader = Loader { + graph: self.graph.clone(), + noises: self.noises.clone(), + definitions: BTreeMap::new(), + values: BTreeMap::new(), + active: BTreeSet::new(), + }; + let roots = json + .iter() + .map(|json| { + let raw: Box = serde_json::from_str(json)?; + loader.decode(&raw, 0) + }) + .collect::>()?; + self.graph = loader.graph; + Ok(roots) + } +} +struct Loader { + graph: DensityGraph, + noises: BTreeMap, + definitions: BTreeMap>, + values: BTreeMap, + active: BTreeSet, +} +impl Loader { + fn resolve(&mut self, name: &str, depth: usize) -> Result { + if let Some(id) = self.graph.function(name) { + return Ok(id); + } + if depth > 256 { + return Err(DecodeError::Field("density nesting")); + } + if !self.active.insert(name.to_owned()) { + return Err(DecodeError::Registry(format!( + "cyclic density reference: {name}" + ))); + } + let raw = self + .definitions + .get(name) + .ok_or_else(|| DecodeError::Registry(format!("unknown density reference: {name}")))? + .clone(); + let value = self.decode(&raw, depth + 1)?; + let reference = self.graph.register_function(name.to_owned(), value)?; + self.values.insert(name.to_owned(), value); + self.active.remove(name); + Ok(reference) + } + fn input( + &mut self, + object: &Object, + name: &'static str, + depth: usize, + ) -> Result { + self.decode(required(object, name)?, depth + 1) + } + fn optional_input( + &mut self, + object: &Object, + name: &'static str, + fallback: f32, + depth: usize, + ) -> Result { + match optional(object, name) { + Some(raw) => self.decode(raw, depth + 1), + None => Ok(self.graph.insert(GraphNode::Constant(fallback))?), + } + } + fn noise(&self, object: &Object) -> Result { + let raw = required(object, "noise")?; + if !raw.get().starts_with('"') { + return Err(DecodeError::Field("inline noise holder unsupported")); + } + let name = identifier(&string(raw)?)?; + self.noises + .get(&name) + .copied() + .ok_or_else(|| DecodeError::Registry(format!("unknown noise reference: {name}"))) + } + fn decode(&mut self, raw: &RawValue, depth: usize) -> Result { + if depth > 256 { + return Err(DecodeError::Field("density nesting")); + } + if raw.get().starts_with('"') { + return self.resolve(&identifier(&string(raw)?)?, depth); + } + if !raw.get().starts_with('{') { + return Ok(self.graph.insert(GraphNode::Constant(noise_value(raw)?))?); + } + let object: Object = serde_json::from_str(raw.get())?; + let kind = identifier(&string(required(&object, "type")?)?)?; + let unary = match kind.as_str() { + "minecraft:abs" => Some(GraphUnary::Abs), + "minecraft:square" => Some(GraphUnary::Square), + "minecraft:cube" => Some(GraphUnary::Cube), + "minecraft:sqrt" => Some(GraphUnary::Sqrt), + "minecraft:half_negative" => Some(GraphUnary::HalfNegative), + "minecraft:quarter_negative" => Some(GraphUnary::QuarterNegative), + "minecraft:reciprocal" => Some(GraphUnary::Reciprocal), + "minecraft:negate" => Some(GraphUnary::Negate), + "minecraft:squeeze" => Some(GraphUnary::Squeeze), + "minecraft:log" => Some(GraphUnary::Log), + "minecraft:sign" => Some(GraphUnary::Sign), + _ => None, + }; + let binary = match kind.as_str() { + "minecraft:add" => Some(GraphBinary::Add), + "minecraft:sub" => Some(GraphBinary::Subtract), + "minecraft:mul" => Some(GraphBinary::Multiply), + "minecraft:div" => Some(GraphBinary::Divide), + "minecraft:min" => Some(GraphBinary::Minimum), + "minecraft:max" => Some(GraphBinary::Maximum), + _ => None, + }; + let node = if let Some(kind) = unary { + GraphNode::Unary { + kind, + input: self.input(&object, "input", depth)?, + } + } else if let Some(kind) = binary { + GraphNode::Binary { + kind, + left: self.input(&object, "left", depth)?, + right: self.input(&object, "right", depth)?, + } + } else { + match kind.as_str() { + "minecraft:constant" => { + GraphNode::Constant(noise_value(required(&object, "value")?)?) + } + "minecraft:blend_alpha" => GraphNode::WorldField(WorldField::BlendAlpha), + "minecraft:blend_offset" => GraphNode::WorldField(WorldField::BlendOffset), + "minecraft:beardifier" => GraphNode::WorldField(WorldField::Beardifier), + "minecraft:end_outer_islands" => GraphNode::EndIslands, + "minecraft:cache" => GraphNode::Cache(self.input(&object, "input", depth)?), + "minecraft:blend_density" => { + GraphNode::BlendDensity(self.input(&object, "input", depth)?) + } + "minecraft:pow" => GraphNode::Power { + base: self.input(&object, "base", depth)?, + exponent: self.input(&object, "exponent", depth)?, + }, + "minecraft:floor" | "minecraft:round" | "minecraft:ceil" | "minecraft:truncate" => { + GraphNode::Round { + mode: match kind.as_str() { + "minecraft:floor" => RoundMode::Floor, + "minecraft:round" => RoundMode::Round, + "minecraft:ceil" => RoundMode::Ceil, + _ => RoundMode::Truncate, + }, + input: self.input(&object, "input", depth)?, + multiple: self.optional_input(&object, "multiple", 1.0, depth)?, + } + } + "minecraft:gradient" => { + let from = integer(required(&object, "from_coordinate")?)?; + let to = integer(required(&object, "to_coordinate")?)?; + if from == to { + return Err(DecodeError::Field("gradient coordinates")); + } + GraphNode::Gradient { + axis: axis(required(&object, "axis")?)?, + tiling: match optional(&object, "tiling") + .map(string) + .transpose()? + .as_deref() + .unwrap_or("clamp_to_edge") + { + "clamp_to_edge" => TilingMode::ClampToEdge, + "repeat" => TilingMode::Repeat, + "mirrored_repeat" => TilingMode::MirroredRepeat, + _ => return Err(DecodeError::Field("tiling")), + }, + from, + to, + low: noise_value(required(&object, "from_value")?)?, + high: noise_value(required(&object, "to_value")?)?, + } + } + "minecraft:noise" => GraphNode::Noise { + noise: self.noise(&object)?, + xz_scale: double(required(&object, "xz_scale")?)?, + y_scale: double(required(&object, "y_scale")?)?, + shift_x: self.optional_input(&object, "shift_x", 0.0, depth)?, + shift_y: self.optional_input(&object, "shift_y", 0.0, depth)?, + shift_z: self.optional_input(&object, "shift_z", 0.0, depth)?, + }, + "minecraft:shift" | "minecraft:shift_a" | "minecraft:shift_b" => { + GraphNode::OffsetNoise { + noise: self.noise(&object)?, + kind: match kind.as_str() { + "minecraft:shift" => ShiftNoiseKind::Shift, + "minecraft:shift_a" => ShiftNoiseKind::ShiftA, + _ => ShiftNoiseKind::ShiftB, + }, + } + } + "minecraft:old_blended_noise" => GraphNode::BlendedNoise(BlendedNoise { + xz_scale: double_range( + required(&object, "xz_scale")?, + "xz_scale", + 0.001, + 1000.0, + )?, + y_scale: double_range(required(&object, "y_scale")?, "y_scale", 0.001, 1000.0)?, + xz_factor: double_range( + required(&object, "xz_factor")?, + "xz_factor", + 0.001, + 1000.0, + )?, + y_factor: double_range( + required(&object, "y_factor")?, + "y_factor", + 0.001, + 1000.0, + )?, + smear_scale_multiplier: double_range( + required(&object, "smear_scale_multiplier")?, + "smear_scale_multiplier", + 1.0, + 8.0, + )?, + }), + "minecraft:slice" => GraphNode::Slice { + axis: axis(required(&object, "axis")?)?, + coordinate: integer(required(&object, "coordinate")?)?, + input: self.input(&object, "input", depth)?, + }, + "minecraft:interpolated" => GraphNode::Interpolated { + input: self.input(&object, "input", depth)?, + xz: int_range( + required(&object, "cell_size_xz")?, + "cell_size_xz", + 1, + i32::MAX, + )?, + y: int_range( + required(&object, "cell_size_y")?, + "cell_size_y", + 1, + i32::MAX, + )?, + }, + "minecraft:find_top_surface" => GraphNode::Surface { + density: self.input(&object, "density", depth)?, + upper: self.input(&object, "upper_bound", depth)?, + lower: int_range( + required(&object, "lower_bound")?, + "lower_bound", + -4064, + 4062, + )?, + height: int_range( + required(&object, "cell_height")?, + "cell_height", + 1, + i32::MAX, + )?, + }, + "minecraft:clamp" => { + let min = noise_value(required(&object, "min")?)?; + let max = noise_value(required(&object, "max")?)?; + if max < min { + return Err(DecodeError::Field("clamp bounds")); + } + GraphNode::Clamp { + input: self.input(&object, "input", depth)?, + min, + max, + } + } + "minecraft:range_choice" => GraphNode::Choice { + input: self.input(&object, "input", depth)?, + min: noise_value(required(&object, "min_inclusive")?)?, + max: noise_value(required(&object, "max_exclusive")?)?, + inside: self.input(&object, "when_in_range", depth)?, + outside: self.input(&object, "when_out_of_range", depth)?, + }, + "minecraft:lerp" => GraphNode::Lerp { + alpha: self.input(&object, "alpha", depth)?, + first: self.input(&object, "first", depth)?, + second: self.input(&object, "second", depth)?, + }, + "minecraft:interval_select" => { + let thresholds: Vec> = + serde_json::from_str(required(&object, "thresholds")?.get())?; + let thresholds: Vec = thresholds + .iter() + .map(|raw| noise_value(raw)) + .collect::>()?; + let functions: Vec> = + serde_json::from_str(required(&object, "functions")?.get())?; + if functions.len() < 2 + || functions.len() > 256 + || functions.len() != thresholds.len() + 1 + || thresholds + .windows(2) + .any(|pair| pair[0].total_cmp(&pair[1]).is_gt()) + { + return Err(DecodeError::Field("interval selection")); + } + let input = self.input(&object, "input", depth)?; + let branches = functions + .iter() + .map(|raw| self.decode(raw, depth + 1)) + .collect::>()?; + GraphNode::IntervalSelect { + input, + thresholds: Arc::from(thresholds), + branches, + } + } + "minecraft:distance_to_point" => { + let raw: Vec> = + serde_json::from_str(required(&object, "point")?.get())?; + if raw.len() != 3 { + return Err(DecodeError::Field("point")); + } + let point = [integer(&raw[0])?, integer(&raw[1])?, integer(&raw[2])?]; + let metric = match string(required(&object, "metric")?)?.as_str() { + "euclidean" => DistanceMetric::Euclidean, + "euclidean_squared" => DistanceMetric::EuclideanSquared, + "manhattan" => DistanceMetric::Manhattan, + "chebyshev" => DistanceMetric::Chebyshev, + _ => return Err(DecodeError::Field("metric")), + }; + GraphNode::DistanceToPoint { point, metric } + } + "minecraft:spline" => { + GraphNode::Spline(self.spline(required(&object, "spline")?, depth + 1)?) + } + _ => { + return Err(DecodeError::Registry(format!( + "unknown density type: {kind}" + ))); + } + } + }; + Ok(self.graph.insert(node)?) + } + fn spline( + &mut self, + raw: &RawValue, + depth: usize, + ) -> Result, DecodeError> { + if depth > 256 { + return Err(DecodeError::Field("spline nesting")); + } + if !raw.get().starts_with('{') { + return Ok(CubicSpline::Constant(float(raw)?)); + } + let object: Object = serde_json::from_str(raw.get())?; + let coordinate = self.input(&object, "coordinate", depth)?; + let points: Vec> = serde_json::from_str(required(&object, "points")?.get())?; + let points = points + .iter() + .map(|raw| { + let point: Object = serde_json::from_str(raw.get())?; + Ok(SplinePoint { + location: float(required(&point, "location")?)?, + derivative: float(required(&point, "derivative")?)?, + value: self.spline(required(&point, "value")?, depth + 1)?, + }) + }) + .collect::>()?; + CubicSpline::multipoint(coordinate, points) + .map_err(|error| DecodeError::Graph(error.into())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::density::{SamplerContext, graph::DensityCompiler}; + #[test] + fn numeric_tokens_keep_negative_zero_and_avoid_double_rounding() { + let densities = BTreeMap::from([ + ("minecraft:negative_zero".into(), "-0".into()), + ( + "minecraft:rounded".into(), + "1.0000000596046447753906250000000001".into(), + ), + ]); + let registry = DensityRegistry::from_json(&BTreeMap::new(), &densities).unwrap(); + let zero = registry.value("minecraft:negative_zero").unwrap(); + let rounded = registry.value("minecraft:rounded").unwrap(); + let compiler = DensityCompiler::new(registry.into_graph()); + let mut context = SamplerContext::default(); + assert_eq!( + compiler + .compile_raw(zero) + .unwrap() + .sample_value(&mut context, [0; 3]) + .unwrap() + .to_bits(), + 0x8000_0000 + ); + assert_eq!( + compiler + .compile_raw(rounded) + .unwrap() + .sample_value(&mut context, [0; 3]) + .unwrap() + .to_bits(), + 0x3f80_0001 + ); + } + #[test] + fn forward_references_share_named_holders_and_reject_cycles_or_missing_values() { + let mut densities = BTreeMap::from([ + ( + "minecraft:a".into(), + r#"{"type":"add","left":"z","right":"minecraft:z"}"#.into(), + ), + ("minecraft:z".into(), "0.5".into()), + ]); + let registry = DensityRegistry::from_json(&BTreeMap::new(), &densities).unwrap(); + let root = registry.value("minecraft:a").unwrap(); + let compiler = DensityCompiler::new(registry.into_graph()); + assert_eq!( + compiler + .compile_raw(root) + .unwrap() + .sample_value(&mut SamplerContext::default(), [0; 3]) + .unwrap(), + 1.0 + ); + densities.insert("minecraft:z".into(), r#""a""#.into()); + assert!(DensityRegistry::from_json(&BTreeMap::new(), &densities).is_err()); + densities.remove("minecraft:z"); + assert!(DensityRegistry::from_json(&BTreeMap::new(), &densities).is_err()); + } + #[test] + fn codec_validation_rejects_invalid_gradients_intervals_and_splines() { + for json in [ + r#"{"type":"gradient","axis":"y","from_coordinate":0,"to_coordinate":0,"from_value":0,"to_value":1}"#, + r#"{"type":"interval_select","input":0,"thresholds":[0,-0],"functions":[0,1,2]}"#, + r#"{"type":"interpolated","input":0,"cell_size_xz":0,"cell_size_y":8}"#, + r#"{"type":"spline","spline":{"coordinate":0,"points":[]}}"#, + r#"{"type":"clamp","input":0,"min":1,"max":-1}"#, + ] { + assert!( + DensityRegistry::from_json( + &BTreeMap::new(), + &BTreeMap::from([("minecraft:a".into(), json.into())]) + ) + .is_err(), + "{json}" + ); + } + } +} diff --git a/crates/horizon-world/src/worldgen/feature.rs b/crates/horizon-world/src/worldgen/feature.rs new file mode 100644 index 000000000..1dac307e8 --- /dev/null +++ b/crates/horizon-world/src/worldgen/feature.rs @@ -0,0 +1,162 @@ +//! Initial block-writing features. Full feature registries and block behavior +//! remain separate work; world access supplies mutation and update semantics. +use super::{DecodeError, Object, density::identifier, required}; +use crate::registry::{BlockRegistry, BlockStateId}; +use horizon_core::random::{InvalidBound, RandomSource}; +#[derive(Clone, Copy, Debug)] +pub struct FeatureBlocks { + pub air: BlockStateId, + pub stone: BlockStateId, + pub cobblestone: BlockStateId, + pub end_stone: BlockStateId, + pub obsidian: BlockStateId, +} +impl FeatureBlocks { + pub fn from_registry(registry: &BlockRegistry) -> Result { + let get = |name| { + registry + .default_state(name) + .ok_or_else(|| DecodeError::Registry(format!("unknown feature block {name}"))) + }; + Ok(Self { + air: get("minecraft:air")?, + stone: get("minecraft:stone")?, + cobblestone: get("minecraft:cobblestone")?, + end_stone: get("minecraft:end_stone")?, + obsidian: get("minecraft:obsidian")?, + }) + } +} +pub trait FeatureWorld { + type Error; + fn block(&mut self, position: [i32; 3]) -> Result; + fn set_block( + &mut self, + position: [i32; 3], + state: BlockStateId, + flags: i32, + ) -> Result; +} +#[derive(Debug)] +pub enum FeatureError { + Random(InvalidBound), + World(E), +} +impl std::fmt::Display for FeatureError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Random(e) => e.fmt(f), + Self::World(e) => e.fmt(f), + } + } +} +impl std::error::Error for FeatureError {} +impl From for FeatureError { + fn from(e: InvalidBound) -> Self { + Self::Random(e) + } +} +#[derive(Clone, Copy, Debug)] +pub enum BasicFeature { + VoidStartPlatform, + EndIsland, + EndPlatform, +} +impl BasicFeature { + pub fn from_json(json: &str) -> Result { + let object: Object = serde_json::from_str(json)?; + match identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)? + .as_str() + { + "minecraft:void_start_platform" => Ok(Self::VoidStartPlatform), + "minecraft:end_island" => Ok(Self::EndIsland), + "minecraft:end_platform" => Ok(Self::EndPlatform), + _ => Err(DecodeError::Field("basic feature type")), + } + } + pub fn place( + &self, + world: &mut W, + random: &mut impl RandomSource, + origin: [i32; 3], + blocks: FeatureBlocks, + ) -> Result> { + let [x, y, z] = origin; + match self { + Self::VoidStartPlatform => { + let (cx, cz) = (x >> 4, z >> 4); + if cx.wrapping_abs().max(cz.wrapping_abs()) > 1 { + return Ok(true); + } + let y = y.wrapping_add(3); + for z in cz.wrapping_shl(4)..=cz.wrapping_shl(4).wrapping_add(15) { + for x in cx.wrapping_shl(4)..=cx.wrapping_shl(4).wrapping_add(15) { + if 8_i32 + .wrapping_sub(x) + .wrapping_abs() + .max(8_i32.wrapping_sub(z).wrapping_abs()) + <= 16 + { + let state = if x == 8 && z == 8 { + blocks.cobblestone + } else { + blocks.stone + }; + world + .set_block([x, y, z], state, 2) + .map_err(FeatureError::World)?; + } + } + } + } + Self::EndIsland => { + let mut radius = random.next_int_bound(3)? as f32 + 4.; + let mut dy = 0_i32; + while radius > 0.5 { + let low = (-radius).floor() as i32; + let high = radius.ceil() as i32; + for dx in low..=high { + for dz in low..=high { + if (dx * dx + dz * dz) as f32 <= (radius + 1.) * (radius + 1.) { + world + .set_block( + [ + x.wrapping_add(dx), + y.wrapping_add(dy), + z.wrapping_add(dz), + ], + blocks.end_stone, + 3, + ) + .map_err(FeatureError::World)?; + } + } + } + radius -= random.next_int_bound(2)? as f32 + 0.5; + dy -= 1; + } + } + Self::EndPlatform => { + for dz in -2..=2 { + for dx in -2..=2 { + for dy in -1..3 { + let p = [x.wrapping_add(dx), y.wrapping_add(dy), z.wrapping_add(dz)]; + let state = if dy == -1 { + blocks.obsidian + } else { + blocks.air + }; + // Both target blocks have one state in the pinned registry. + if world.block(p).map_err(FeatureError::World)? != state { + world.set_block(p, state, 3).map_err(FeatureError::World)?; + } + } + } + } + } + } + Ok(true) + } +} diff --git a/crates/horizon-world/src/worldgen/feature_catalog.rs b/crates/horizon-world/src/worldgen/feature_catalog.rs new file mode 100644 index 000000000..ebdf29c4f --- /dev/null +++ b/crates/horizon-world/src/worldgen/feature_catalog.rs @@ -0,0 +1,266 @@ +//! Immutable feature resource snapshots. Requested roots resolve named feature +//! and placed-feature holders and tags into bounded executable inline trees. +//! This is not a complete datapack registry loader or live-reload implementation. +use super::{ + DecodeError, Object, + block_feature::FeatureBlockBindings, + density::identifier, + feature_graph::{FeatureDefinition, PlacedFeatureDefinition}, + required, + tags::TagDefinitions, +}; +use serde_json::value::RawValue; +use std::collections::{BTreeMap, BTreeSet}; + +pub struct FeatureCatalog { + features: BTreeMap>, + placed: BTreeMap>, + tags: BTreeMap>, + empty_tags: BTreeSet, +} +struct Expansion { + remaining: usize, + active: Vec<(bool, String)>, +} +impl Expansion { + fn visit(&mut self, depth: usize) -> Result<(), DecodeError> { + if depth > 128 || self.remaining == 0 { + return Err(DecodeError::Field("feature resource expansion limit")); + } + self.remaining -= 1; + Ok(()) + } +} +fn resources( + source: &BTreeMap, +) -> Result>, DecodeError> { + if source.len() > 8192 { + return Err(DecodeError::Field("feature resource count")); + } + let mut result = BTreeMap::new(); + for (name, json) in source { + if result + .insert(identifier(name)?, serde_json::from_str(json)?) + .is_some() + { + return Err(DecodeError::Field("duplicate feature resource")); + } + } + Ok(result) +} +fn raw(json: String) -> Result, DecodeError> { + Ok(RawValue::from_string(json)?) +} +fn entries(value: &RawValue) -> Result>, DecodeError> { + let values: Vec> = serde_json::from_str(value.get())?; + if values.len() > 8192 { + return Err(DecodeError::Field("feature resource list")); + } + Ok(values) +} +impl FeatureCatalog { + /// Stores source JSON without validating unused feature algorithms. Resolving + /// a root validates its entire reachable tree, including unselected children. + pub fn from_resources( + features: &BTreeMap, + placed: &BTreeMap, + tags: &TagDefinitions, + ) -> Result { + let features = resources(features)?; + let placed = resources(placed)?; + let built = tags + .build(|name, _| placed.contains_key(name).then(|| name.to_owned())) + .map_err(|e| DecodeError::Registry(e.to_string()))?; + Ok(Self { + features, + placed, + empty_tags: built + .tags + .iter() + .filter_map(|(name, values)| values.is_empty().then_some(name.clone())) + .collect(), + tags: built.tags, + }) + } + pub fn feature(&self, json: &str) -> Result { + self.feature_with_optional_blocks(json, None) + } + pub fn feature_with_blocks( + &self, + json: &str, + blocks: &FeatureBlockBindings<'_>, + ) -> Result { + self.feature_with_optional_blocks(json, Some(blocks)) + } + fn feature_with_optional_blocks( + &self, + json: &str, + blocks: Option<&FeatureBlockBindings<'_>>, + ) -> Result { + let value: Box = serde_json::from_str(json)?; + let expanded = self.expand_feature( + &value, + 0, + &mut Expansion { + remaining: 65536, + active: vec![], + }, + )?; + FeatureDefinition::from_catalog_json(&expanded, &self.empty_tags, blocks) + } + pub fn placed_feature(&self, json: &str) -> Result { + self.placed_with_optional_blocks(json, None) + } + pub fn placed_feature_with_blocks( + &self, + json: &str, + blocks: &FeatureBlockBindings<'_>, + ) -> Result { + self.placed_with_optional_blocks(json, Some(blocks)) + } + fn placed_with_optional_blocks( + &self, + json: &str, + blocks: Option<&FeatureBlockBindings<'_>>, + ) -> Result { + let value: Box = serde_json::from_str(json)?; + let expanded = self.expand_placed( + &value, + 0, + &mut Expansion { + remaining: 65536, + active: vec![], + }, + )?; + PlacedFeatureDefinition::from_catalog_json(&expanded, &self.empty_tags, blocks) + } + fn named( + &self, + name: &str, + placed: bool, + depth: usize, + work: &mut Expansion, + ) -> Result { + let name = identifier(name)?; + let key = (placed, name.clone()); + if work.active.contains(&key) { + return Err(DecodeError::Registry(format!( + "cyclic feature reference {name}" + ))); + } + let value = if placed { &self.placed } else { &self.features } + .get(&name) + .ok_or_else(|| DecodeError::Registry(format!("unknown feature reference {name}")))?; + work.active.push(key); + let result = if placed { + self.expand_placed(value, depth + 1, work) + } else { + self.expand_feature(value, depth + 1, work) + }; + work.active.pop(); + result + } + fn expand_placed( + &self, + value: &RawValue, + depth: usize, + work: &mut Expansion, + ) -> Result { + work.visit(depth)?; + if let Ok(name) = serde_json::from_str::(value.get()) { + return self.named(&name, true, depth, work); + } + let mut object: Object = serde_json::from_str(value.get())?; + let feature = self.expand_feature(required(&object, "feature")?, depth + 1, work)?; + object.insert("feature".into(), raw(feature)?); + Ok(serde_json::to_string(&object)?) + } + fn expand_set( + &self, + value: &RawValue, + depth: usize, + work: &mut Expansion, + ) -> Result { + let values = if let Ok(name) = serde_json::from_str::(value.get()) { + if let Some(tag) = name.strip_prefix('#') { + let tag = identifier(tag)?; + let names = self.tags.get(&tag).ok_or_else(|| { + DecodeError::Registry(format!("unknown placed-feature tag {tag}")) + })?; + // Native nonEmptyHolderSet validates direct lists, but permits + // a named tag whose bound contents are empty. + if names.is_empty() { + return Ok(serde_json::to_string(&format!("#{tag}"))?); + } + if names.len() > 8192 { + return Err(DecodeError::Field("placed-feature tag size")); + } + names + .iter() + .map(|name| raw(serde_json::to_string(name)?)) + .collect::, DecodeError>>()? + } else { + vec![value.to_owned()] + } + } else if value.get().trim_start().starts_with('[') { + entries(value)? + } else { + vec![value.to_owned()] + }; + let expanded = values + .iter() + .map(|v| raw(self.expand_placed(v, depth + 1, work)?)) + .collect::, _>>()?; + Ok(serde_json::to_string(&expanded)?) + } + fn expand_feature( + &self, + value: &RawValue, + depth: usize, + work: &mut Expansion, + ) -> Result { + work.visit(depth)?; + if let Ok(name) = serde_json::from_str::(value.get()) { + return self.named(&name, false, depth, work); + } + let mut object: Object = serde_json::from_str(value.get())?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + match kind.as_str() { + "minecraft:sequence" | "minecraft:simple_random_selector" => { + let expanded = self.expand_set(required(&object, "features")?, depth + 1, work)?; + object.insert("features".into(), raw(expanded)?); + } + "minecraft:random_boolean_selector" => { + for name in ["feature_true", "feature_false"] { + let expanded = self.expand_placed(required(&object, name)?, depth + 1, work)?; + object.insert(name.into(), raw(expanded)?); + } + } + "minecraft:random_selector" | "minecraft:weighted_random_selector" => { + let key = if kind == "minecraft:random_selector" { + "feature" + } else { + "data" + }; + let values = entries(required(&object, "features")?)?; + let mut expanded = Vec::with_capacity(values.len()); + for value in values { + let mut entry: Object = serde_json::from_str(value.get())?; + let child = self.expand_placed(required(&entry, key)?, depth + 1, work)?; + entry.insert(key.into(), raw(child)?); + expanded.push(entry); + } + object.insert("features".into(), raw(serde_json::to_string(&expanded)?)?); + if kind == "minecraft:random_selector" { + let child = + self.expand_placed(required(&object, "default")?, depth + 1, work)?; + object.insert("default".into(), raw(child)?); + } + } + _ => {} + } + Ok(serde_json::to_string(&object)?) + } +} diff --git a/crates/horizon-world/src/worldgen/feature_graph.rs b/crates/horizon-world/src/worldgen/feature_graph.rs new file mode 100644 index 000000000..5b2d48c94 --- /dev/null +++ b/crates/horizon-world/src/worldgen/feature_graph.rs @@ -0,0 +1,441 @@ +//! Inline feature composition. Named holders, tags and registry reloads remain +//! separate from this bounded executable tree. +use super::{ + DecodeError, Object, + block_feature::{ + BlockFeatureError, FeatureBlockBindings, FillLayerFeature, ReplaceBlockFeature, + }, + density::identifier, + feature::{BasicFeature, FeatureBlocks, FeatureError, FeatureWorld}, + number_text, + ore_feature::ScatteredOreFeature, + placement::{ + FeaturePlacementError, FeaturePlacer, PlacementContext, PlacementModifier, + PlacementQueryError, + }, + required, + weighted::OptionalWeightedList, +}; +use horizon_core::random::{InvalidBound, RandomSource}; +use serde_json::value::RawValue; +use std::{cell::Cell, collections::BTreeSet}; + +#[derive(Clone, Debug)] +pub struct PlacedFeatureDefinition { + pub feature: Box, + pub placement: Vec, +} +#[derive(Clone, Debug)] +pub enum FeatureDefinition { + Basic(BasicFeature), + FillLayer(FillLayerFeature), + ReplaceBlock(ReplaceBlockFeature), + ScatteredOre(ScatteredOreFeature), + NoOp, + WeightedChoice(OptionalWeightedList), + Sequence(Vec), + BooleanChoice(Box<[PlacedFeatureDefinition; 2]>), + RandomChoice(Vec), + ChanceChoice { + features: Vec<(f32, PlacedFeatureDefinition)>, + fallback: Box, + }, +} +#[derive(Debug)] +pub enum FeatureExecutionError { + Basic(FeatureError), + Random(InvalidBound), + Query(PlacementQueryError), + WorkLimit, + InvalidPendingIndex, +} +impl std::fmt::Display for FeatureExecutionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Basic(e) => e.fmt(f), + Self::Random(e) => e.fmt(f), + Self::Query(e) => e.fmt(f), + Self::WorkLimit => f.write_str("feature graph work limit exceeded"), + Self::InvalidPendingIndex => f.write_str("invalid pending modifier index"), + } + } +} +impl std::error::Error for FeatureExecutionError {} +impl From for FeatureExecutionError { + fn from(error: InvalidBound) -> Self { + Self::Random(error) + } +} +impl From> for FeatureExecutionError { + fn from(error: FeaturePlacementError) -> Self { + match error { + FeaturePlacementError::Feature(e) => e, + FeaturePlacementError::Random(e) => Self::Random(e), + FeaturePlacementError::World(e) => Self::Query(e), + FeaturePlacementError::WorkLimit => Self::WorkLimit, + FeaturePlacementError::InvalidPendingIndex => Self::InvalidPendingIndex, + } + } +} +struct Run { + blocks: FeatureBlocks, + depth: Cell, + remaining: Cell, +} +fn visit(depth: usize, remaining: &mut usize) -> Result<(), DecodeError> { + if depth > 128 || *remaining == 0 { + return Err(DecodeError::Field("feature graph depth or node count")); + } + *remaining -= 1; + Ok(()) +} +fn list(raw: &RawValue) -> Result>, DecodeError> { + let values: Vec> = serde_json::from_str(raw.get())?; + if values.len() > 8192 { + return Err(DecodeError::Field("feature list")); + } + Ok(values) +} +impl PlacedFeatureDefinition { + pub fn from_json(json: &str) -> Result { + Self::decode(json, 0, &mut 65536, &BTreeSet::new(), None) + } + pub fn from_json_with_blocks( + json: &str, + blocks: &FeatureBlockBindings<'_>, + ) -> Result { + Self::decode(json, 0, &mut 65536, &BTreeSet::new(), Some(blocks)) + } + pub(crate) fn from_catalog_json( + json: &str, + empty_tags: &BTreeSet, + blocks: Option<&FeatureBlockBindings<'_>>, + ) -> Result { + Self::decode(json, 0, &mut 65536, empty_tags, blocks) + } + fn decode( + json: &str, + depth: usize, + remaining: &mut usize, + empty_tags: &BTreeSet, + blocks: Option<&FeatureBlockBindings<'_>>, + ) -> Result { + visit(depth, remaining)?; + let object: Object = serde_json::from_str(json)?; + let feature = Box::new(FeatureDefinition::decode( + required(&object, "feature")?.get(), + depth + 1, + remaining, + empty_tags, + blocks, + )?); + let values = list(required(&object, "placement")?)?; + if values.len() > 1024 { + return Err(DecodeError::Field("feature modifier chain")); + } + let placement = values + .iter() + .map(|raw| { + PlacementModifier::decode_with_blocks( + raw.get(), + depth + 1, + remaining, + blocks.map(|b| b as &dyn super::block_predicate::PredicateBlockResolver), + ) + }) + .collect::>()?; + Ok(Self { feature, placement }) + } + pub fn place( + &self, + world: &mut W, + random: &mut impl RandomSource, + origin: [i32; 3], + blocks: FeatureBlocks, + ) -> Result> { + self.place_in( + &mut FeaturePlacer::new(), + world, + random, + origin, + &Run { + blocks, + depth: Cell::new(0), + remaining: Cell::new(65536), + }, + ) + } + fn place_in( + &self, + placer: &mut FeaturePlacer, + world: &mut W, + random: &mut impl RandomSource, + origin: [i32; 3], + run: &Run, + ) -> Result> { + if run.remaining.get() == 0 { + return Err(FeatureExecutionError::WorkLimit); + } + run.remaining.set(run.remaining.get() - 1); + Ok(placer.place_with_budget( + &self.placement, + world, + random, + origin, + &run.remaining, + |world, random, p| self.feature.place_inner(world, random, p, run), + )?) + } +} +impl FeatureDefinition { + pub fn from_json(json: &str) -> Result { + Self::decode(json, 0, &mut 65536, &BTreeSet::new(), None) + } + pub fn from_json_with_blocks( + json: &str, + blocks: &FeatureBlockBindings<'_>, + ) -> Result { + Self::decode(json, 0, &mut 65536, &BTreeSet::new(), Some(blocks)) + } + pub(crate) fn from_catalog_json( + json: &str, + empty_tags: &BTreeSet, + blocks: Option<&FeatureBlockBindings<'_>>, + ) -> Result { + Self::decode(json, 0, &mut 65536, empty_tags, blocks) + } + fn decode( + json: &str, + depth: usize, + remaining: &mut usize, + empty_tags: &BTreeSet, + blocks: Option<&FeatureBlockBindings<'_>>, + ) -> Result { + visit(depth, remaining)?; + let object: Object = serde_json::from_str(json)?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + match kind.as_str() { + "minecraft:no_op" => Ok(Self::NoOp), + "minecraft:fill_layer" => FillLayerFeature::from_json( + json, + blocks.ok_or_else(|| { + DecodeError::Registry("feature block bindings unavailable".into()) + })?, + ) + .map(Self::FillLayer), + "minecraft:replace_single_block" => ReplaceBlockFeature::decode( + json, + blocks.ok_or_else(|| { + DecodeError::Registry("feature block bindings unavailable".into()) + })?, + depth, + remaining, + ) + .map(Self::ReplaceBlock), + "minecraft:scattered_ore" => ScatteredOreFeature::decode( + json, + blocks.ok_or_else(|| { + DecodeError::Registry("feature block bindings unavailable".into()) + })?, + depth, + remaining, + ) + .map(Self::ScatteredOre), + "minecraft:weighted_random_selector" => Ok(Self::WeightedChoice( + OptionalWeightedList::decode(required(&object, "features")?, |raw| { + PlacedFeatureDefinition::decode( + raw.get(), + depth + 1, + remaining, + empty_tags, + blocks, + ) + })?, + )), + "minecraft:sequence" | "minecraft:simple_random_selector" => { + let raw = required(&object, "features")?; + let name = serde_json::from_str::(raw.get()).ok(); + let named_empty = name + .as_deref() + .and_then(|s| s.strip_prefix('#')) + .map(identifier) + .transpose()? + .is_some_and(|name| empty_tags.contains(&name)); + if named_empty { + return Ok(if kind == "minecraft:sequence" { + Self::Sequence(vec![]) + } else { + Self::RandomChoice(vec![]) + }); + } + let values = if raw.get().trim_start().starts_with('[') { + list(raw)? + } else { + vec![raw.to_owned()] + }; + if values.is_empty() { + return Err(DecodeError::Field("empty feature list")); + } + let features = values + .iter() + .map(|raw| { + PlacedFeatureDefinition::decode( + raw.get(), + depth + 1, + remaining, + empty_tags, + blocks, + ) + }) + .collect::>()?; + Ok(if kind == "minecraft:sequence" { + Self::Sequence(features) + } else { + Self::RandomChoice(features) + }) + } + "minecraft:random_boolean_selector" => Ok(Self::BooleanChoice(Box::new([ + PlacedFeatureDefinition::decode( + required(&object, "feature_true")?.get(), + depth + 1, + remaining, + empty_tags, + blocks, + )?, + PlacedFeatureDefinition::decode( + required(&object, "feature_false")?.get(), + depth + 1, + remaining, + empty_tags, + blocks, + )?, + ]))), + "minecraft:random_selector" => { + let values = list(required(&object, "features")?)?; + let mut features = Vec::with_capacity(values.len()); + for raw in values { + let entry: Object = serde_json::from_str(raw.get())?; + let feature = PlacedFeatureDefinition::decode( + required(&entry, "feature")?.get(), + depth + 1, + remaining, + empty_tags, + blocks, + )?; + let chance: f32 = number_text(required(&entry, "chance")?)? + .parse() + .map_err(|_| DecodeError::Field("feature chance"))?; + if !(0. ..=1.).contains(&chance) || chance.is_sign_negative() { + return Err(DecodeError::Field("feature chance")); + } + features.push((chance, feature)); + } + Ok(Self::ChanceChoice { + features, + fallback: Box::new(PlacedFeatureDefinition::decode( + required(&object, "default")?.get(), + depth + 1, + remaining, + empty_tags, + blocks, + )?), + }) + } + _ => BasicFeature::from_json(json).map(Self::Basic), + } + } + pub fn place( + &self, + world: &mut W, + random: &mut impl RandomSource, + origin: [i32; 3], + blocks: FeatureBlocks, + ) -> Result> { + self.place_inner( + world, + random, + origin, + &Run { + blocks, + depth: Cell::new(0), + remaining: Cell::new(65536), + }, + ) + } + fn place_inner( + &self, + world: &mut W, + random: &mut impl RandomSource, + origin: [i32; 3], + run: &Run, + ) -> Result> { + if run.depth.get() >= 128 || run.remaining.get() == 0 { + return Err(FeatureExecutionError::WorkLimit); + } + run.depth.set(run.depth.get() + 1); + run.remaining.set(run.remaining.get() - 1); + let result = self.evaluate(world, random, origin, run); + run.depth.set(run.depth.get() - 1); + result + } + fn evaluate( + &self, + world: &mut W, + random: &mut impl RandomSource, + origin: [i32; 3], + run: &Run, + ) -> Result> { + let mut placer = FeaturePlacer::new(); + match self { + Self::Basic(feature) => feature + .place(world, random, origin, run.blocks) + .map_err(FeatureExecutionError::Basic), + Self::NoOp => Ok(true), + Self::ScatteredOre(feature) => feature + .place(world, random, origin) + .map_err(FeatureExecutionError::Basic), + Self::FillLayer(feature) => feature.place(world, origin).map_err(|e| match e { + BlockFeatureError::World(e) => FeatureExecutionError::Basic(FeatureError::World(e)), + BlockFeatureError::Query(e) => FeatureExecutionError::Query(e), + }), + Self::ReplaceBlock(feature) => { + feature.place(world, random, origin).map_err(|e| match e { + BlockFeatureError::World(e) => { + FeatureExecutionError::Basic(FeatureError::World(e)) + } + BlockFeatureError::Query(e) => FeatureExecutionError::Query(e), + }) + } + Self::WeightedChoice(features) => match features.sample(random)? { + Some(feature) => feature.place_in(&mut placer, world, random, origin, run), + None => Ok(false), + }, + Self::Sequence(features) => { + for feature in features { + if !feature.place_in(&mut placer, world, random, origin, run)? { + return Ok(false); + } + } + Ok(true) + } + Self::BooleanChoice(features) => { + let index = if random.next_boolean() { 0 } else { 1 }; + features[index].place_in(&mut placer, world, random, origin, run) + } + Self::RandomChoice(features) => { + let index = random.next_int_bound(features.len() as i32)? as usize; + features[index].place_in(&mut placer, world, random, origin, run) + } + Self::ChanceChoice { features, fallback } => { + for (chance, feature) in features { + if random.next_float() < *chance { + return feature.place_in(&mut placer, world, random, origin, run); + } + } + fallback.place_in(&mut placer, world, random, origin, run) + } + } + } +} diff --git a/crates/horizon-world/src/worldgen/feature_region.rs b/crates/horizon-world/src/worldgen/feature_region.rs new file mode 100644 index 000000000..242e61d73 --- /dev/null +++ b/crates/horizon-world/src/worldgen/feature_region.rs @@ -0,0 +1,231 @@ +//! Resident pre-light chunks shared by modifier queries and feature mutations. +//! The caller supplies world write policy/effects; storage alone cannot implement +//! neighbor updates, block entities, POIs or lighting. +use super::{ + anchor::WorldGenerationContext, + biome_chunk::{BiomeRegion, BiomeRegionError}, + feature::FeatureWorld, + placement::{LayerBlock, PlacementContext, PlacementQueryError}, + terrain::{PreLightChunkStage, TerrainBlockStates, TerrainChunk, TerrainError}, +}; +use crate::{ + heightmap::{HeightmapState, HeightmapType}, + registry::BlockStateId, +}; +use horizon_core::position::BlockPos; +use std::collections::BTreeMap; + +#[derive(Debug)] +pub enum RegionError { + InvalidChunks, + MissingChunk([i32; 2]), + Terrain(TerrainError), + Biome(BiomeRegionError), + BiomesNotGenerated([i32; 2]), +} +impl std::fmt::Display for RegionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{self:?}") + } +} +impl std::error::Error for RegionError {} +impl From for RegionError { + fn from(error: TerrainError) -> Self { + Self::Terrain(error) + } +} +impl From for PlacementQueryError { + fn from(error: RegionError) -> Self { + Self::Failed(error.to_string()) + } +} +pub struct TerrainRegion<'r, B: TerrainBlockStates> { + chunks: BTreeMap<(i32, i32), TerrainChunk<'r, B>>, + min_y: i32, + height: i32, + generation: WorldGenerationContext, +} +impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { + pub fn new( + chunks: Vec>, + generator: WorldGenerationContext, + ) -> Result { + if chunks.is_empty() || chunks.len() > 4096 { + return Err(RegionError::InvalidChunks); + } + let first = &chunks[0]; + let (min_y, height, registry) = (first.min_y(), first.height(), first.registry()); + if chunks.iter().any(|c| { + c.min_y() != min_y || c.height() != height || !std::ptr::eq(c.registry(), registry) + }) { + return Err(RegionError::InvalidChunks); + } + let mut stored = BTreeMap::new(); + for chunk in chunks { + let p = chunk.position(); + if stored.insert((p.x, p.z), chunk).is_some() { + return Err(RegionError::InvalidChunks); + } + } + Ok(Self { + chunks: stored, + min_y, + height, + generation: WorldGenerationContext::with_generator( + min_y, + height, + generator.min_y, + generator.height, + generator.sea_level, + ), + }) + } + pub fn chunks(&self) -> impl Iterator> { + self.chunks.values() + } + pub fn chunk(&self, x: i32, z: i32) -> Result<&TerrainChunk<'r, B>, RegionError> { + self.chunks + .get(&(x, z)) + .ok_or(RegionError::MissingChunk([x, z])) + } + pub fn chunk_mut(&mut self, x: i32, z: i32) -> Result<&mut TerrainChunk<'r, B>, RegionError> { + self.chunks + .get_mut(&(x, z)) + .ok_or(RegionError::MissingChunk([x, z])) + } + pub fn block(&self, [x, y, z]: [i32; 3]) -> Result { + Ok(self.chunk(x >> 4, z >> 4)?.block(x, y, z)) + } + /// Level-style biome lookup checks the selected chunk's generation status + /// before reading its palette. Raw biome storage remains independently + /// accessible for generation itself. Below-zero retrogen is not modeled. + pub fn biome_at<'b, T: Clone>( + &self, + biomes: &'b BiomeRegion, + position: BlockPos, + ) -> Result<&'b T, RegionError> { + self.noise_biome(biomes, biomes.quart_at_block(position)) + } + pub fn noise_biome<'b, T: Clone>( + &self, + biomes: &'b BiomeRegion, + quart: [i32; 3], + ) -> Result<&'b T, RegionError> { + let chunk = self.chunk(quart[0] >> 2, quart[2] >> 2)?; + if !matches!( + chunk.generation_stage(), + PreLightChunkStage::Biomes | PreLightChunkStage::Terrain | PreLightChunkStage::Features + ) { + return Err(RegionError::BiomesNotGenerated([ + quart[0] >> 2, + quart[2] >> 2, + ])); + } + biomes.noise_biome(quart).map_err(RegionError::Biome) + } + /// Storage mutation only. World code must apply its write permissions, + /// block-entity/POI effects and postprocessing around this operation. + pub fn set_block_worldgen( + &mut self, + [x, y, z]: [i32; 3], + state: BlockStateId, + ) -> Result { + Ok(self + .chunk_mut(x >> 4, z >> 4)? + .set_block_worldgen(x, y, z, state)?) + } +} +impl PlacementContext for TerrainRegion<'_, B> { + fn generation(&self) -> WorldGenerationContext { + self.generation + } + fn block_state(&mut self, position: [i32; 3]) -> Result { + self.block(position).map_err(Into::into) + } + fn min_y(&mut self) -> Result { + Ok(self.min_y) + } + fn max_y(&mut self) -> Result { + Ok(self.min_y.wrapping_add(self.height).wrapping_sub(1)) + } + fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result { + let chunk = self.chunk_mut(x >> 4, z >> 4)?; + if chunk.heightmap(kind).is_none() { + chunk.prime_heightmaps(&[kind]).map_err(RegionError::from)?; + } + chunk + .heightmap(kind) + .unwrap() + .first_available(x & 15, z & 15) + .map_err(|e| RegionError::from(TerrainError::from(e)).into()) + } + fn layer_block(&mut self, position: [i32; 3]) -> Result { + let chunk = self.chunk(position[0] >> 4, position[2] >> 4)?; + let state = chunk.block(position[0], position[1], position[2]); + let name = &chunk + .registry() + .state(state) + .expect("registered chunk state") + .name; + Ok( + if chunk.block_properties(state).is_air() + || name == "minecraft:water" + || name == "minecraft:lava" + { + LayerBlock::Empty + } else if name == "minecraft:bedrock" { + LayerBlock::Bedrock + } else { + LayerBlock::Ground + }, + ) + } +} +/// Gives feature algorithms and placement queries one region. All update flags +/// reach the supplied write function, which owns world mutation policy/effects. +pub struct TerrainFeatureAccess<'a, 'r, B: TerrainBlockStates, F> { + region: &'a mut TerrainRegion<'r, B>, + write: F, +} +impl<'a, 'r, B: TerrainBlockStates, F> TerrainFeatureAccess<'a, 'r, B, F> { + pub fn new(region: &'a mut TerrainRegion<'r, B>, write: F) -> Self { + Self { region, write } + } +} +impl PlacementContext for TerrainFeatureAccess<'_, '_, B, F> { + fn generation(&self) -> WorldGenerationContext { + self.region.generation() + } + fn block_state(&mut self, position: [i32; 3]) -> Result { + self.region.block_state(position) + } + fn min_y(&mut self) -> Result { + self.region.min_y() + } + fn max_y(&mut self) -> Result { + self.region.max_y() + } + fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result { + self.region.height(kind, x, z) + } + fn layer_block(&mut self, position: [i32; 3]) -> Result { + self.region.layer_block(position) + } +} +impl<'r, B: TerrainBlockStates, F> FeatureWorld for TerrainFeatureAccess<'_, 'r, B, F> +where + F: FnMut(&mut TerrainRegion<'r, B>, [i32; 3], BlockStateId, i32) -> Result, +{ + type Error = RegionError; + fn block(&mut self, position: [i32; 3]) -> Result { + self.region.block(position) + } + fn set_block( + &mut self, + position: [i32; 3], + state: BlockStateId, + flags: i32, + ) -> Result { + (self.write)(self.region, position, state, flags) + } +} diff --git a/crates/horizon-world/src/worldgen/feature_sort.rs b/crates/horizon-world/src/worldgen/feature_sort.rs new file mode 100644 index 000000000..82d4ef6a0 --- /dev/null +++ b/crates/horizon-world/src/worldgen/feature_sort.rs @@ -0,0 +1,116 @@ +//! Deterministic feature ordering across biome generation steps. +use std::collections::{BTreeMap, BTreeSet}; + +/// A placed-feature object identity, assigned by the owning registry snapshot. +/// Structurally equal but separately allocated features need distinct IDs. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct FeatureIdentity(pub u32); + +#[derive(Clone, Debug)] +pub struct StepFeatureData { + features: Vec, + indices: BTreeMap, +} +impl StepFeatureData { + pub fn features(&self) -> &[FeatureIdentity] { + &self.features + } + pub fn index(&self, feature: FeatureIdentity) -> Option { + self.indices.get(&feature).copied() + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FeatureSortError { + Cycle, + WorkLimit, + DuplicateBiome, +} +impl std::fmt::Display for FeatureSortError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Cycle => "feature order cycle found", + Self::WorkLimit => "feature ordering input limit exceeded", + Self::DuplicateBiome => "duplicate biome identity in decoration plan", + }) + } +} +impl std::error::Error for FeatureSortError {} + +/// Inputs preserve biome order, step order and each holder set's encounter order. +pub fn build_features_per_step( + biomes: &[Vec>], +) -> Result, FeatureSortError> { + if biomes.len() > 8192 { + return Err(FeatureSortError::WorkLimit); + } + type Node = (usize, usize); // Native comparator: step, then first identity index. + let mut identities = BTreeMap::new(); + let mut encountered = Vec::new(); + let mut graph = BTreeMap::>::new(); + let mut steps = 0; + let mut remaining = 65536usize; + for biome in biomes { + if biome.len() > 8192 { + return Err(FeatureSortError::WorkLimit); + } + steps = steps.max(biome.len()); + let mut previous = None; + for (step, features) in biome.iter().enumerate() { + remaining = remaining + .checked_sub(1) + .ok_or(FeatureSortError::WorkLimit)?; + for feature in features { + remaining = remaining + .checked_sub(1) + .ok_or(FeatureSortError::WorkLimit)?; + let index = *identities.entry(*feature).or_insert_with(|| { + encountered.push(*feature); + encountered.len() - 1 + }); + let node = (step, index); + graph.entry(node).or_default(); + if let Some(previous) = previous { + graph.entry(previous).or_default().insert(node); + } + previous = Some(node); + } + } + } + let mut colors = BTreeMap::::new(); + let mut ordered = Vec::with_capacity(graph.len()); + let mut stack = Vec::new(); + for &root in graph.keys() { + if colors.get(&root) == Some(&2) { + continue; + } + stack.push((root, false)); + while let Some((node, finish)) = stack.pop() { + if finish { + colors.insert(node, 2); + ordered.push(node); + continue; + } + match colors.get(&node) { + Some(2) => continue, + Some(1) => return Err(FeatureSortError::Cycle), + _ => {} + } + colors.insert(node, 1); + stack.push((node, true)); + stack.extend(graph[&node].iter().rev().map(|&next| (next, false))); + } + } + let mut result = (0..steps) + .map(|_| StepFeatureData { + features: Vec::new(), + indices: BTreeMap::new(), + }) + .collect::>(); + for (step, index) in ordered.into_iter().rev() { + let feature = encountered[index]; + let data = &mut result[step]; + data.indices.insert(feature, data.features.len()); + data.features.push(feature); + } + Ok(result) +} diff --git a/crates/horizon-world/src/worldgen/fluid_predicate.rs b/crates/horizon-world/src/worldgen/fluid_predicate.rs new file mode 100644 index 000000000..bc227d577 --- /dev/null +++ b/crates/horizon-world/src/worldgen/fluid_predicate.rs @@ -0,0 +1,92 @@ +//! Resolved fluid holder sets bound to immutable vanilla block-state identities. +use super::{DecodeError, density::identifier}; +use crate::{ + fluid::{FluidKind, FluidStateTable}, + registry::{BlockRegistry, BlockStateId}, +}; +use std::{collections::BTreeMap, sync::Arc}; +pub struct FluidPredicateBindings { + table: Arc, + tags: BTreeMap, +} +impl FluidPredicateBindings { + pub fn new(registry: &BlockRegistry) -> Result { + Ok(Self { + table: Arc::new( + FluidStateTable::new(registry).map_err(|e| DecodeError::Registry(e.to_string()))?, + ), + tags: BTreeMap::new(), + }) + } + pub fn with_resolved_tags( + mut self, + tags: &BTreeMap>, + ) -> Result { + if tags.len() > 8192 { + return Err(DecodeError::Field("fluid tag count")); + } + let mut resolved = BTreeMap::new(); + for (tag, names) in tags { + if names.len() > 8192 { + return Err(DecodeError::Field("fluid tag size")); + } + let mut mask = 0; + for name in names { + mask |= fluid(name)?.mask(); + } + if resolved + .insert(super::tags::identifier(tag)?, mask) + .is_some() + { + return Err(DecodeError::Field("duplicate fluid tag")); + } + } + self.tags = resolved; + Ok(self) + } + pub fn resolve(&self, json: &str) -> Result { + let mask = if let Ok(name) = serde_json::from_str::(json) { + if let Some(tag) = name.strip_prefix('#') { + *self + .tags + .get(&super::tags::identifier(tag)?) + .ok_or_else(|| DecodeError::Registry(format!("unknown fluid tag {tag}")))? + } else { + fluid(&name)?.mask() + } + } else { + let names: Vec = serde_json::from_str(json)?; + if names.len() > 8192 { + return Err(DecodeError::Field("fluid holder list")); + } + let mut mask = 0; + for name in names { + mask |= fluid(&name)?.mask(); + } + mask + }; + Ok(BoundFluidSet { + table: self.table.clone(), + mask, + }) + } +} +fn fluid(name: &str) -> Result { + FluidKind::from_name(&identifier(name)?) + .ok_or_else(|| DecodeError::Registry(format!("unknown fluid {name}"))) +} + +/// A fluid-family mask over one shared immutable state table. Membership needs +/// one indexed lookup and avoids allocating large sets of equivalent states. +#[derive(Clone, Debug)] +pub struct BoundFluidSet { + table: Arc, + mask: u8, +} +impl BoundFluidSet { + pub fn contains(&self, state: BlockStateId) -> bool { + self.table + .get(state) + .is_some_and(|value| value.kind().mask() & self.mask != 0) + } +} diff --git a/crates/horizon-world/src/worldgen/height_provider.rs b/crates/horizon-world/src/worldgen/height_provider.rs new file mode 100644 index 000000000..6849f3a3a --- /dev/null +++ b/crates/horizon-world/src/worldgen/height_provider.rs @@ -0,0 +1,149 @@ +//! Anchored scalar height distributions used by cave and canyon generation. +//! Codec encoding remains separate work. +use super::{ + DecodeError, Object, + anchor::{VerticalAnchor, WorldGenerationContext}, + density::identifier, + int_range, integer, optional, required, + weighted::WeightedList, +}; +use horizon_core::random::{InvalidBound, RandomSource}; + +#[derive(Clone, Debug)] +pub enum HeightProvider { + Weighted(WeightedList), + Constant(VerticalAnchor), + Uniform { + min: VerticalAnchor, + max: VerticalAnchor, + }, + BiasedToBottom { + min: VerticalAnchor, + max: VerticalAnchor, + inner: i32, + }, + VeryBiasedToBottom { + min: VerticalAnchor, + max: VerticalAnchor, + inner: i32, + }, + Trapezoid { + min: VerticalAnchor, + max: VerticalAnchor, + plateau: i32, + }, +} +impl HeightProvider { + pub fn from_json(json: &str) -> Result { + Self::decode(json, 0, &mut 65536) + } + fn decode(json: &str, depth: usize, remaining: &mut usize) -> Result { + if depth > 256 || *remaining == 0 { + return Err(DecodeError::Field("height provider depth or node count")); + } + *remaining -= 1; + if let Ok(anchor) = VerticalAnchor::from_json(json) { + return Ok(Self::Constant(anchor)); + } + let object: Object = serde_json::from_str(json)?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + let anchor = |name| VerticalAnchor::from_json(required(&object, name)?.get()); + if kind == "minecraft:constant" { + return Ok(Self::Constant(anchor("value")?)); + } + if kind == "minecraft:weighted_list" { + return Ok(Self::Weighted(WeightedList::decode( + required(&object, "distribution")?, + |raw| Self::decode(raw.get(), depth + 1, remaining), + )?)); + } + let min = anchor("min_inclusive")?; + let max = anchor("max_inclusive")?; + match kind.as_str() { + "minecraft:uniform" => Ok(Self::Uniform { min, max }), + "minecraft:biased_to_bottom" | "minecraft:very_biased_to_bottom" => { + let inner = optional(&object, "inner") + .map(|raw| int_range(raw, "inner", 1, i32::MAX)) + .transpose()? + .unwrap_or(1); + Ok(if kind == "minecraft:biased_to_bottom" { + Self::BiasedToBottom { min, max, inner } + } else { + Self::VeryBiasedToBottom { min, max, inner } + }) + } + "minecraft:trapezoid" => Ok(Self::Trapezoid { + min, + max, + plateau: optional(&object, "plateau") + .map(integer) + .transpose()? + .unwrap_or(0), + }), + _ => Err(DecodeError::Field("height provider type")), + } + } + pub fn sample( + &self, + random: &mut impl RandomSource, + context: WorldGenerationContext, + ) -> Result { + let (min, max) = match self { + Self::Weighted(list) => return list.sample(random)?.sample(random, context), + Self::Constant(anchor) => return Ok(anchor.resolve(context)), + Self::Uniform { min, max } + | Self::BiasedToBottom { min, max, .. } + | Self::VeryBiasedToBottom { min, max, .. } + | Self::Trapezoid { min, max, .. } => (min.resolve(context), max.resolve(context)), + }; + match self { + Self::Constant(_) | Self::Weighted(_) => unreachable!(), + Self::Uniform { .. } => { + if min > max { + Ok(min) + } else { + random.next_int_between_inclusive(min, max) + } + } + Self::BiasedToBottom { inner, .. } | Self::VeryBiasedToBottom { inner, .. } => { + let range = max.wrapping_sub(min).wrapping_sub(*inner).wrapping_add(1); + if range <= 0 { + return Ok(min); + } + if matches!(self, Self::BiasedToBottom { .. }) { + let first = random.next_int_bound(range)?; + Ok(random + .next_int_bound(first.wrapping_add(*inner))? + .wrapping_add(min)) + } else { + let first = next_int(random, min.wrapping_add(*inner), max)?; + let second = next_int(random, min, first.wrapping_sub(1))?; + next_int(random, min, second.wrapping_sub(1).wrapping_add(*inner)) + } + } + Self::Trapezoid { plateau, .. } => { + if min > max { + return Ok(min); + } + let range = max.wrapping_sub(min); + if *plateau >= range { + return random.next_int_between_inclusive(min, max); + } + let slope = range.wrapping_sub(*plateau) / 2; + let middle = range.wrapping_sub(slope); + let left = random.next_int_between_inclusive(0, middle)?; + let right = random.next_int_between_inclusive(0, slope)?; + Ok(min.wrapping_add(left).wrapping_add(right)) + } + } + } +} +fn next_int(random: &mut impl RandomSource, min: i32, max: i32) -> Result { + if min >= max { + Ok(min) + } else { + random.next_int_between_inclusive(min, max) + } +} diff --git a/crates/horizon-world/src/worldgen/material_condition.rs b/crates/horizon-world/src/worldgen/material_condition.rs new file mode 100644 index 000000000..30eb26ec8 --- /dev/null +++ b/crates/horizon-world/src/worldgen/material_condition.rs @@ -0,0 +1,611 @@ +//! Numeric material conditions and their column/block evaluation caches. +//! +//! This worker owns its condition caches so they cannot be reused accidentally +//! against a different column context. +mod codec; +mod density; +mod library; +mod noise; +mod rule; +use super::{ + DecodeError, + anchor::{VerticalAnchor, WorldGenerationContext}, + material_surface::MaterialSurface, +}; +use crate::registry::BlockStateId; +pub use codec::{MaterialBiomeTag, MaterialConditionReference, MaterialConditionRegistry}; +pub use density::MaterialDensitySources; +use horizon_core::noise::Noise; +use horizon_core::{ + position::BlockPos, + random::{PositionalRandom, RandomSource}, +}; +pub use library::MaterialRuleLibrary; +pub use noise::MaterialNoiseSources; +use rule::CompiledRule; +pub use rule::{MaterialRule, MaterialRuleError}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; + +/// Surface inputs come from the material system. Implementations should keep +/// world configuration fixed for the lifetime of a condition worker. +pub trait MaterialSurfaceQueries { + /// Bind a compiled density root, optionally sampling the expected chunk now. + fn bind_density( + &mut self, + _sampler: Arc, + _eager: bool, + ) -> Result { + Err(DecodeError::Field("missing material density provider")) + } + fn density(&mut self, _index: usize, _position: BlockPos) -> Result { + Err(MaterialRuleError::MissingDensityProvider) + } + fn preliminary_surface(&mut self, _position: BlockPos) -> Result { + Err(MaterialRuleError::MissingDensityProvider) + } + fn possible_biomes(&self) -> Option> { + None + } + fn biome(&mut self, _position: BlockPos) -> Result>, MaterialRuleError> { + Err(MaterialRuleError::MissingBiomeProvider) + } + fn melts_frozen_ocean( + &mut self, + _biome: &str, + _position: BlockPos, + _sea_level: i32, + ) -> Result { + Err(MaterialRuleError::MissingBiomeProvider) + } + fn cold_enough_to_snow( + &mut self, + _biome: &str, + _position: BlockPos, + _sea_level: i32, + ) -> Result { + Err(MaterialRuleError::MissingBiomeProvider) + } + fn bind_noise(&mut self, _name: &str) -> Result, DecodeError> { + Err(DecodeError::Field("missing material noise provider")) + } + fn surface_depth(&mut self, x: i32, z: i32) -> i32; + fn surface_secondary(&mut self, x: i32, z: i32) -> f64; + fn band(&mut self, _position: BlockPos) -> Result { + Err(MaterialRuleError::MissingBandProvider) + } +} +impl MaterialSurfaceQueries for &mut T { + fn bind_density( + &mut self, + sampler: Arc, + eager: bool, + ) -> Result { + (**self).bind_density(sampler, eager) + } + fn density(&mut self, index: usize, position: BlockPos) -> Result { + (**self).density(index, position) + } + fn preliminary_surface(&mut self, position: BlockPos) -> Result { + (**self).preliminary_surface(position) + } + fn possible_biomes(&self) -> Option> { + (**self).possible_biomes() + } + fn biome(&mut self, position: BlockPos) -> Result>, MaterialRuleError> { + (**self).biome(position) + } + fn cold_enough_to_snow( + &mut self, + biome: &str, + position: BlockPos, + sea: i32, + ) -> Result { + (**self).cold_enough_to_snow(biome, position, sea) + } + fn melts_frozen_ocean( + &mut self, + biome: &str, + position: BlockPos, + sea: i32, + ) -> Result { + (**self).melts_frozen_ocean(biome, position, sea) + } + fn bind_noise(&mut self, name: &str) -> Result, DecodeError> { + (**self).bind_noise(name) + } + fn surface_depth(&mut self, x: i32, z: i32) -> i32 { + (**self).surface_depth(x, z) + } + fn surface_secondary(&mut self, x: i32, z: i32) -> f64 { + (**self).surface_secondary(x, z) + } + fn band(&mut self, position: BlockPos) -> Result { + (**self).band(position) + } +} +impl MaterialSurfaceQueries for MaterialSurface

{ + fn band(&mut self, position: BlockPos) -> Result { + MaterialSurface::band(self, [position.x, position.y, position.z]) + .ok_or(MaterialRuleError::InvalidBandIndex) + } + fn surface_depth(&mut self, x: i32, z: i32) -> i32 { + MaterialSurface::surface_depth(self, x, z) + } + fn surface_secondary(&mut self, x: i32, z: i32) -> f64 { + MaterialSurface::surface_secondary(self, x, z) + } +} + +#[derive(Clone, Debug)] +pub enum MaterialCondition { + Hole, + Steep, + Biome(Vec), + BiomeTag(MaterialBiomeTag), + Temperature, + AbovePreliminarySurface, + NoiseThreshold { + noise: String, + min: f64, + max: f64, + is_3d: bool, + }, + YAbove { + anchor: VerticalAnchor, + surface_depth_multiplier: i32, + add_stone_depth: bool, + }, + Water { + offset: i32, + surface_depth_multiplier: i32, + add_stone_depth: bool, + }, + StoneDepth { + offset: i32, + add_surface_depth: bool, + secondary_depth_range: i32, + ceiling: bool, + }, + VerticalGradient { + random_name: String, + true_at_and_below: VerticalAnchor, + false_at_and_above: VerticalAnchor, + }, + Not(Box), + Reference(MaterialConditionReference), +} + +struct Context { + surface: S, + generation: WorldGenerationContext, + column_revision: i64, + block_revision: i64, + position: BlockPos, + gradient: [i32; 2], + depth: i32, + water_height: i32, + stone_above: i32, + stone_below: i32, + secondary_revision: i64, + secondary: f64, + minimum_revision: i64, + minimum: i32, + noises: Vec, + noise_indices: BTreeMap<(String, bool), usize>, + possible_biomes: Option>, + biome: Option>, +} +struct CachedNoise { + sampler: Arc, + is_3d: bool, + revision: i64, + value: f64, +} +impl Context { + fn minimum_surface_level(&mut self) -> Result { + if self.minimum_revision != self.column_revision { + // Vanilla stamps before sampling, including when sampling fails. + self.minimum_revision = self.column_revision; + let value = self.surface.preliminary_surface(BlockPos::new( + self.position.x, + 0, + self.position.z, + ))?; + // 26.3 floors before the saturating Java numeric conversion. + let floor = value.floor() as i32; + self.minimum = floor.wrapping_add(self.depth).wrapping_sub(8); + } + Ok(self.minimum) + } + fn biome(&mut self) -> Result>, MaterialRuleError> { + if self.biome.is_none() { + self.biome = self.surface.biome(self.position)?; + } + Ok(self.biome.clone()) + } + fn bind_noise(&mut self, name: &str, is_3d: bool) -> Result { + let key = (name.to_owned(), is_3d); + if let Some(index) = self.noise_indices.get(&key) { + return Ok(*index); + } + let sampler = self.surface.bind_noise(name)?; + let index = self.noises.len(); + self.noises.push(CachedNoise { + sampler, + is_3d, + revision: if is_3d { + self.block_revision + } else { + self.column_revision + } + .wrapping_sub(1), + value: 0.0, + }); + self.noise_indices.insert(key, index); + Ok(index) + } + fn noise(&mut self, index: usize) -> f64 { + let noise = &mut self.noises[index]; + let revision = if noise.is_3d { + self.block_revision + } else { + self.column_revision + }; + if noise.revision != revision { + noise.value = f64::from(noise.sampler.get3( + f64::from(self.position.x), + if noise.is_3d { + f64::from(self.position.y) + } else { + 0.0 + }, + f64::from(self.position.z), + )); + noise.revision = revision; + } + noise.value + } + fn secondary(&mut self) -> f64 { + if self.secondary_revision != self.column_revision { + self.secondary_revision = self.column_revision; + self.secondary = self + .surface + .surface_secondary(self.position.x, self.position.z); + } + self.secondary + } +} +struct Compiled { + kind: Kind, + revision: i64, + result: Option, +} +enum Kind { + Simple(MaterialCondition), + Biome(BTreeSet), + Constant(bool), + Noise { + sampler: usize, + min: f64, + max: f64, + }, + Gradient { + low: i32, + high: i32, + random: R::Positional, + }, + Not(Box>), +} +impl Compiled { + fn compile( + condition: MaterialCondition, + root: &R::Positional, + context: &mut Context, + depth: usize, + ) -> Result { + if depth >= 256 { + return Err(DecodeError::Field("material condition depth")); + } + let column = matches!( + condition, + MaterialCondition::Hole | MaterialCondition::Steep + ); + let kind = match condition { + MaterialCondition::BiomeTag(tag) => { + return Self::compile( + MaterialCondition::Biome(tag.members().to_vec()), + root, + context, + depth + 1, + ); + } + MaterialCondition::Biome(names) => { + if names.len() > 8192 { + return Err(DecodeError::Field("biome condition size")); + } + let names = names + .iter() + .map(|name| codec::identifier(name)) + .collect::, _>>()?; + match &context.possible_biomes { + Some(possible) if names.is_disjoint(possible) => Kind::Constant(false), + Some(possible) if possible.is_subset(&names) => Kind::Constant(true), + _ => Kind::Biome(names), + } + } + MaterialCondition::NoiseThreshold { + noise, + min, + max, + is_3d, + } => Kind::Noise { + sampler: context.bind_noise(&codec::identifier(&noise)?, is_3d)?, + min, + max, + }, + MaterialCondition::Reference(reference) => { + return Self::compile(reference.value().clone(), root, context, depth + 1); + } + MaterialCondition::Not(child) => { + Kind::Not(Box::new(Self::compile(*child, root, context, depth + 1)?)) + } + MaterialCondition::VerticalGradient { + random_name, + true_at_and_below, + false_at_and_above, + } => { + let random_name = codec::identifier(&random_name)?; + Kind::Gradient { + low: true_at_and_below.resolve(context.generation), + high: false_at_and_above.resolve(context.generation), + random: root.from_hash_of(&random_name).fork_positional(), + } + } + other => Kind::Simple(other), + }; + Ok(Self { + kind, + revision: if column { + context.column_revision + } else { + context.block_revision + } + .wrapping_sub(1), + result: None, + }) + } + fn test( + &mut self, + context: &mut Context, + ) -> Result { + if let Kind::Constant(value) = self.kind { + return Ok(value); + } + if matches!( + self.kind, + Kind::Simple(MaterialCondition::AbovePreliminarySurface) + ) { + return Ok(context.position.y >= context.minimum_surface_level()?); + } + if matches!(self.kind, Kind::Simple(MaterialCondition::Temperature)) { + let biome = context.biome()?.ok_or(MaterialRuleError::MissingBiome)?; + return context.surface.cold_enough_to_snow( + &biome, + context.position, + context.generation.sea_level, + ); + } + if let Kind::Noise { sampler, min, max } = &self.kind { + let value = context.noise(*sampler); + return Ok(value >= *min && value <= *max); + } + if let Kind::Not(child) = &mut self.kind { + return child.test(context).map(|value| !value); + } + let column = matches!( + self.kind, + Kind::Simple(MaterialCondition::Hole | MaterialCondition::Steep) + ); + let revision = if column { + context.column_revision + } else { + context.block_revision + }; + if self.revision == revision { + return self + .result + .ok_or(MaterialRuleError::CachedConditionUnavailable); + } + self.revision = revision; + let result = match &self.kind { + Kind::Biome(names) => names.contains( + context + .biome()? + .ok_or(MaterialRuleError::MissingBiome)? + .as_ref(), + ), + Kind::Simple(MaterialCondition::Hole) => context.depth <= 0, + Kind::Simple(MaterialCondition::Steep) => { + context.gradient[0] <= -4 || context.gradient[1] >= 4 + } + Kind::Simple(MaterialCondition::YAbove { + anchor, + surface_depth_multiplier, + add_stone_depth, + }) => { + let y = context.position.y.wrapping_add(if *add_stone_depth { + context.stone_above + } else { + 0 + }); + y >= anchor + .resolve(context.generation) + .wrapping_add(context.depth.wrapping_mul(*surface_depth_multiplier)) + } + Kind::Simple(MaterialCondition::Water { + offset, + surface_depth_multiplier, + add_stone_depth, + }) => { + context.water_height == i32::MIN + || context.position.y.wrapping_add(if *add_stone_depth { + context.stone_above + } else { + 0 + }) >= context + .water_height + .wrapping_add(*offset) + .wrapping_add(context.depth.wrapping_mul(*surface_depth_multiplier)) + } + Kind::Simple(MaterialCondition::StoneDepth { + offset, + add_surface_depth, + secondary_depth_range, + ceiling, + }) => { + let stone = if *ceiling { + context.stone_below + } else { + context.stone_above + }; + let surface = if *add_surface_depth { context.depth } else { 0 }; + let secondary = if *secondary_depth_range == 0 { + 0 + } else { + (0.0 + ((context.secondary() - -1.0) / (1.0 - -1.0)) + * (f64::from(*secondary_depth_range) - 0.0)) as i32 + }; + stone + <= 1i32 + .wrapping_add(*offset) + .wrapping_add(surface) + .wrapping_add(secondary) + } + Kind::Gradient { low, high, random } => { + let y = context.position.y; + if y <= *low { + true + } else if y >= *high { + false + } else { + let probability = 1.0 + + ((f64::from(y) - f64::from(*low)) / (f64::from(*high) - f64::from(*low))) + * (0.0 - 1.0); + f64::from(random.at(context.position).next_float()) < probability + } + } + _ => unreachable!("all recursive and gradient definitions are compiled"), + }; + self.result = Some(result); + Ok(result) + } +} + +/// A thread-local material-condition worker. Surface state and evaluations are +/// owned together; updates invalidate exactly the corresponding vanilla caches. +pub struct MaterialConditions { + root: R::Positional, + context: Context, + conditions: Vec>, + rules: Vec>, +} +impl MaterialConditions { + pub fn new(generation: WorldGenerationContext, root: R::Positional, surface: S) -> Self { + let possible_biomes = surface.possible_biomes(); + Self::with_possible_biomes(generation, root, surface, possible_biomes) + } + pub(crate) fn with_possible_biomes( + generation: WorldGenerationContext, + root: R::Positional, + surface: S, + possible_biomes: Option>, + ) -> Self { + Self { + root, + context: Context { + surface, + generation, + column_revision: i64::MIN + 1, + block_revision: i64::MIN + 1, + position: BlockPos::new(0, 0, 0), + gradient: [0, 0], + depth: 0, + water_height: 0, + stone_above: 0, + stone_below: 0, + secondary_revision: i64::MIN, + secondary: 0.0, + minimum_revision: i64::MIN, + minimum: 0, + noises: Vec::new(), + noise_indices: BTreeMap::new(), + possible_biomes, + biome: None, + }, + conditions: Vec::new(), + rules: Vec::new(), + } + } + /// Compile a condition at the current context revision. Gradient bounds and + /// named random factories are bound now, before the first evaluation. + pub fn add(&mut self, condition: MaterialCondition) -> Result { + if self.conditions.len() >= 8192 { + return Err(DecodeError::Field("material condition count")); + } + let compiled = Compiled::compile(condition, &self.root, &mut self.context, 0)?; + let index = self.conditions.len(); + self.conditions.push(compiled); + Ok(index) + } + pub fn update_xz(&mut self, x: i32, z: i32, gradient_x: i32, gradient_z: i32) { + self.context.column_revision = self.context.column_revision.wrapping_add(1); + self.context.block_revision = self.context.block_revision.wrapping_add(1); + self.context.position.x = x; + self.context.position.z = z; + self.context.gradient = [gradient_x, gradient_z]; + self.context.depth = self.context.surface.surface_depth(x, z); + } + pub fn update_y(&mut self, stone_above: i32, stone_below: i32, water_height: i32, y: i32) { + self.context.block_revision = self.context.block_revision.wrapping_add(1); + self.context.biome = None; + self.context.position.y = y; + self.context.stone_above = stone_above; + self.context.stone_below = stone_below; + self.context.water_height = water_height; + } + pub fn test(&mut self, index: usize) -> Result { + self.conditions + .get_mut(index) + .ok_or(MaterialRuleError::UnknownCondition)? + .test(&mut self.context) + } + /// Direct biome lookup for the outer column scan, independent of condition caching. + pub fn biome_at(&mut self, position: BlockPos) -> Result>, MaterialRuleError> { + self.context.surface.biome(position) + } + pub fn melts_frozen_ocean( + &mut self, + biome: &str, + position: BlockPos, + sea_level: i32, + ) -> Result { + self.context + .surface + .melts_frozen_ocean(biome, position, sea_level) + } + pub fn minimum_surface_level(&mut self) -> Result { + self.context.minimum_surface_level() + } + pub fn into_surface(self) -> S { + self.context.surface + } + pub fn surface_depth(&self) -> i32 { + self.context.depth + } + pub fn surface_secondary(&mut self) -> f64 { + self.context.secondary() + } +} diff --git a/crates/horizon-world/src/worldgen/material_condition/codec.rs b/crates/horizon-world/src/worldgen/material_condition/codec.rs new file mode 100644 index 000000000..ec646697e --- /dev/null +++ b/crates/horizon-world/src/worldgen/material_condition/codec.rs @@ -0,0 +1,474 @@ +//! Bounded numeric-condition registry loading and direct/holder JSON codecs. +use super::MaterialCondition; +use crate::worldgen::{ + DecodeError, Object, anchor::VerticalAnchor, double, int_range, integer, optional, required, +}; +use serde_json::{Value, value::RawValue}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; + +pub(super) fn identifier(name: &str) -> Result { + let (namespace, path) = name.split_once(':').unwrap_or(("minecraft", name)); + let namespace = if namespace.is_empty() { + "minecraft" + } else { + namespace + }; + let valid = |c: u8| c.is_ascii_lowercase() || c.is_ascii_digit() || b"_.-".contains(&c); + if !namespace.bytes().all(valid) || !path.bytes().all(|c| valid(c) || c == b'/') { + return Err(DecodeError::Field("material identifier")); + } + Ok(format!("{namespace}:{path}")) +} +#[derive(Clone, Debug)] +pub struct MaterialConditionReference { + name: String, + value: Arc, +} +impl MaterialConditionReference { + pub fn name(&self) -> &str { + &self.name + } + pub fn value(&self) -> &MaterialCondition { + &self.value + } +} +/// A named biome-tag snapshot for a fixed world-generation configuration. +#[derive(Clone, Debug)] +pub struct MaterialBiomeTag { + name: String, + members: Arc<[String]>, +} +impl MaterialBiomeTag { + pub fn name(&self) -> &str { + &self.name + } + pub fn members(&self) -> &[String] { + &self.members + } +} +#[derive(Debug)] +struct BiomeCatalog { + names: BTreeSet, + tags: BTreeMap>, +} +#[derive(Clone, Debug, Default)] +pub struct MaterialConditionRegistry { + values: BTreeMap>, + biomes: Option>, +} +impl MaterialConditionRegistry { + /// Load an immutable set atomically, including forward references. Cycles, + /// unresolved references and resource-limit violations are typed errors. + pub fn from_json(definitions: &BTreeMap) -> Result { + Self::load(definitions, None) + } + pub fn from_json_with_biomes( + definitions: &BTreeMap, + biomes: &BTreeSet, + ) -> Result { + Self::from_json_with_biome_tags(definitions, biomes, &BTreeMap::new()) + } + /// Bind resolved biome tags, such as `TagDefinitions::build().tags`. + /// Names and memberships remain immutable for the lifetime of this registry. + pub fn from_json_with_biome_tags( + definitions: &BTreeMap, + biomes: &BTreeSet, + tags: &BTreeMap>, + ) -> Result { + if biomes.len() > 8192 || tags.len() > 8192 { + return Err(DecodeError::Field("material biome catalog size")); + } + let names: BTreeSet<_> = biomes + .iter() + .map(|name| identifier(name)) + .collect::>()?; + let mut values = BTreeMap::new(); + let mut count = 0usize; + for (name, members) in tags { + count = count.saturating_add(members.len()); + if count > 65536 { + return Err(DecodeError::Field("material biome tag size")); + } + let mut bound = Vec::with_capacity(members.len()); + for member in members { + let member = identifier(member)?; + if !names.contains(&member) { + return Err(DecodeError::Field("unknown tagged biome")); + } + bound.push(member); + } + if values.insert(identifier(name)?, Arc::from(bound)).is_some() { + return Err(DecodeError::Field("duplicate biome tag")); + } + } + Self::load( + definitions, + Some(Arc::new(BiomeCatalog { + names, + tags: values, + })), + ) + } + fn load( + definitions: &BTreeMap, + biomes: Option>, + ) -> Result { + if definitions.len() > 8192 { + return Err(DecodeError::Field("material registry size")); + } + let mut loader = Loader { + biomes, + ..Loader::default() + }; + for (name, json) in definitions { + if loader + .definitions + .insert(identifier(name)?, serde_json::from_str(json)?) + .is_some() + { + return Err(DecodeError::Field("duplicate material condition")); + } + } + let names: Vec<_> = loader.definitions.keys().cloned().collect(); + for name in names { + loader.resolve(&name, 0)?; + } + Ok(Self { + values: loader.values, + biomes: loader.biomes, + }) + } + pub fn decode(&self, json: &str) -> Result { + let raw: Box = serde_json::from_str(json)?; + Loader { + values: self.values.clone(), + biomes: self.biomes.clone(), + ..Loader::default() + } + .node(&raw, 0) + } + pub fn get(&self, name: &str) -> Option { + let name = identifier(name).ok()?; + self.values + .get(&name) + .map(|value| MaterialConditionReference { + name, + value: value.clone(), + }) + } + pub fn entries(&self) -> impl Iterator { + self.values + .iter() + .map(|(name, value)| (name.as_str(), value.as_ref())) + } +} +#[derive(Default)] +struct Loader { + definitions: BTreeMap>, + values: BTreeMap>, + active: BTreeSet, + biomes: Option>, + nodes: usize, +} +impl Loader { + fn resolve(&mut self, name: &str, depth: usize) -> Result, DecodeError> { + if depth >= 256 { + return Err(DecodeError::Field("material condition depth")); + } + if let Some(value) = self.values.get(name) { + return Ok(value.clone()); + } + if !self.active.insert(name.to_owned()) { + return Err(DecodeError::Field("cyclic material condition")); + } + let json = self + .definitions + .get(name) + .ok_or(DecodeError::Field("missing material condition"))? + .clone(); + if !json.get().starts_with('{') { + return Err(DecodeError::Field("material definition must be direct")); + } + let value = Arc::new(self.node(&json, depth + 1)?); + self.active.remove(name); + self.values.insert(name.to_owned(), value.clone()); + Ok(value) + } + fn node(&mut self, raw: &RawValue, depth: usize) -> Result { + self.nodes += 1; + if depth >= 256 || self.nodes > 65536 { + return Err(DecodeError::Field("material condition size")); + } + if raw.get().starts_with('"') { + let name = identifier(&serde_json::from_str::(raw.get())?)?; + let value = self.resolve(&name, depth + 1)?; + return Ok(MaterialCondition::Reference(MaterialConditionReference { + name, + value, + })); + } + let object: Object = serde_json::from_str(raw.get())?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + let number = |name| integer(required(&object, name)?); + let boolean = |name| { + serde_json::from_str::(required(&object, name)?.get()).map_err(DecodeError::from) + }; + let anchor = |name| VerticalAnchor::from_json(required(&object, name)?.get()); + let multiplier = || { + int_range( + required(&object, "surface_depth_multiplier")?, + "surface_depth_multiplier", + -20, + 20, + ) + }; + Ok(match kind.as_str() { + "minecraft:noise_threshold" => MaterialCondition::NoiseThreshold { + noise: identifier(&serde_json::from_str::( + required(&object, "noise")?.get(), + )?)?, + min: double(required(&object, "min_threshold")?)?, + max: double(required(&object, "max_threshold")?)?, + is_3d: optional(&object, "is_3d") + .map(|raw| serde_json::from_str(raw.get())) + .transpose()? + .unwrap_or(false), + }, + "minecraft:temperature" => MaterialCondition::Temperature, + "minecraft:above_preliminary_surface" => MaterialCondition::AbovePreliminarySurface, + "minecraft:biome" => { + let catalog = self + .biomes + .as_ref() + .ok_or(DecodeError::Field("missing biome catalog"))?; + let raw = required(&object, "biome_is")?; + let names: Vec = if raw.get().starts_with('"') { + let name: String = serde_json::from_str(raw.get())?; + if let Some(tag) = name.strip_prefix('#') { + let name = identifier(tag)?; + let members = catalog + .tags + .get(&name) + .ok_or(DecodeError::Field("unknown biome tag"))? + .clone(); + return Ok(MaterialCondition::BiomeTag(MaterialBiomeTag { + name, + members, + })); + } + vec![name] + } else { + serde_json::from_str(raw.get())? + }; + if names.len() > 8192 { + return Err(DecodeError::Field("biome condition size")); + } + let mut resolved = Vec::with_capacity(names.len()); + for name in names { + let name = identifier(&name)?; + if !catalog.names.contains(&name) { + return Err(DecodeError::Field("unknown material biome")); + } + resolved.push(name); + } + MaterialCondition::Biome(resolved) + } + "minecraft:hole" => MaterialCondition::Hole, + "minecraft:steep" => MaterialCondition::Steep, + "minecraft:y_above" => MaterialCondition::YAbove { + anchor: anchor("anchor")?, + surface_depth_multiplier: multiplier()?, + add_stone_depth: boolean("add_stone_depth")?, + }, + "minecraft:water" => MaterialCondition::Water { + offset: number("offset")?, + surface_depth_multiplier: multiplier()?, + add_stone_depth: boolean("add_stone_depth")?, + }, + "minecraft:stone_depth" => { + let surface: String = + serde_json::from_str(required(&object, "surface_type")?.get())?; + let ceiling = match surface.as_str() { + "ceiling" => true, + "floor" => false, + _ => return Err(DecodeError::Field("surface_type")), + }; + MaterialCondition::StoneDepth { + offset: number("offset")?, + add_surface_depth: boolean("add_surface_depth")?, + secondary_depth_range: number("secondary_depth_range")?, + ceiling, + } + } + "minecraft:vertical_gradient" => MaterialCondition::VerticalGradient { + random_name: identifier(&serde_json::from_str::( + required(&object, "random_name")?.get(), + )?)?, + true_at_and_below: anchor("true_at_and_below")?, + false_at_and_above: anchor("false_at_and_above")?, + }, + "minecraft:not" => MaterialCondition::Not(Box::new( + self.node(required(&object, "invert")?, depth + 1)?, + )), + _ => return Err(DecodeError::Field("unsupported material condition type")), + }) + } +} +impl MaterialCondition { + pub fn from_json(json: &str) -> Result { + MaterialConditionRegistry::default().decode(json) + } + /// Encode the vanilla codec value. Nonfinite double thresholds use the + /// same NaN/Infinity tokens as Gson; strict JSON decoding rejects those tokens. + pub fn to_json(&self) -> Result { + self.encoded(0) + } + fn encoded(&self, depth: usize) -> Result { + if depth >= 256 { + return Err(DecodeError::Field("material condition depth")); + } + match self { + Self::Not(child) => Ok(format!( + "{{\"type\":\"minecraft:not\",\"invert\":{}}}", + child.encoded(depth + 1)? + )), + Self::NoiseThreshold { + noise, + min, + max, + is_3d, + } => { + let number = |v: f64| { + if v.is_nan() { + "NaN".to_owned() + } else if v == f64::INFINITY { + "Infinity".to_owned() + } else if v == f64::NEG_INFINITY { + "-Infinity".to_owned() + } else { + serde_json::to_string(&v).unwrap() + } + }; + Ok(format!( + "{{\"type\":\"minecraft:noise_threshold\",\"noise\":{},\"min_threshold\":{},\"max_threshold\":{}{}}}", + serde_json::to_string(&identifier(noise)?)?, + number(*min), + number(*max), + if *is_3d { ",\"is_3d\":true" } else { "" } + )) + } + _ => Ok(serde_json::to_string(&self.json_value(depth)?)?), + } + } + fn json_value(&self, depth: usize) -> Result { + if depth >= 256 { + return Err(DecodeError::Field("material condition depth")); + } + let multiplier = |value: i32| { + if (-20..=20).contains(&value) { + Ok(value) + } else { + Err(DecodeError::Field("surface_depth_multiplier")) + } + }; + let anchor = |value: VerticalAnchor| -> Result { + Ok(serde_json::from_str(&value.to_json()?)?) + }; + Ok(match self { + Self::Temperature => serde_json::json!({"type":"minecraft:temperature"}), + Self::AbovePreliminarySurface => { + serde_json::json!({"type":"minecraft:above_preliminary_surface"}) + } + Self::BiomeTag(tag) => { + serde_json::json!({"type":"minecraft:biome","biome_is":format!("#{}",tag.name)}) + } + Self::Biome(names) => { + let names = names + .iter() + .map(|name| identifier(name)) + .collect::, _>>()?; + let value = if names.len() == 1 { + Value::String(names[0].clone()) + } else { + serde_json::to_value(names)? + }; + serde_json::json!({"type":"minecraft:biome","biome_is":value}) + } + Self::Hole => serde_json::json!({"type":"minecraft:hole"}), + Self::Steep => serde_json::json!({"type":"minecraft:steep"}), + Self::YAbove { + anchor: a, + surface_depth_multiplier, + add_stone_depth, + } => { + serde_json::json!({"type":"minecraft:y_above","anchor":anchor(*a)?,"surface_depth_multiplier":multiplier(*surface_depth_multiplier)?,"add_stone_depth":add_stone_depth}) + } + Self::Water { + offset, + surface_depth_multiplier, + add_stone_depth, + } => { + serde_json::json!({"type":"minecraft:water","offset":offset,"surface_depth_multiplier":multiplier(*surface_depth_multiplier)?,"add_stone_depth":add_stone_depth}) + } + Self::StoneDepth { + offset, + add_surface_depth, + secondary_depth_range, + ceiling, + } => { + serde_json::json!({"type":"minecraft:stone_depth","offset":offset,"add_surface_depth":add_surface_depth,"secondary_depth_range":secondary_depth_range,"surface_type":if *ceiling{"ceiling"}else{"floor"}}) + } + Self::VerticalGradient { + random_name, + true_at_and_below, + false_at_and_above, + } => { + serde_json::json!({"type":"minecraft:vertical_gradient","random_name":identifier(random_name)?,"true_at_and_below":anchor(*true_at_and_below)?,"false_at_and_above":anchor(*false_at_and_above)?}) + } + Self::Not(_) | Self::NoiseThreshold { .. } => { + return Err(DecodeError::Field("condition requires direct encoding")); + } + Self::Reference(reference) => Value::String(reference.name.clone()), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn forward_references_are_stable_and_invalid_graphs_fail_atomically() { + let definitions = BTreeMap::from([ + ("a".to_owned(), r#"{"type":"not","invert":"z"}"#.to_owned()), + ("z".to_owned(), r#"{"type":"hole"}"#.to_owned()), + ]); + let registry = MaterialConditionRegistry::from_json(&definitions).unwrap(); + let reference = registry.decode(r#""a""#).unwrap(); + assert_eq!(reference.to_json().unwrap(), r#""minecraft:a""#); + assert!( + registry + .decode(r#"{"type":"not","invert":"missing"}"#) + .is_err() + ); + assert_eq!(registry.entries().count(), 2); + assert_eq!( + registry.get("z").unwrap().value().to_json().unwrap(), + r#"{"type":"minecraft:hole"}"# + ); + let mut cyclic = definitions.clone(); + cyclic.insert("z".to_owned(), r#"{"type":"not","invert":"a"}"#.to_owned()); + assert!(MaterialConditionRegistry::from_json(&cyclic).is_err()); + let mut alias = definitions.clone(); + alias.insert("z".to_owned(), r#""a""#.to_owned()); + assert!(MaterialConditionRegistry::from_json(&alias).is_err()); + let mut duplicate = definitions; + duplicate.insert("minecraft:z".to_owned(), r#"{"type":"steep"}"#.to_owned()); + assert!(MaterialConditionRegistry::from_json(&duplicate).is_err()); + assert_eq!(reference.to_json().unwrap(), r#""minecraft:a""#); + } +} diff --git a/crates/horizon-world/src/worldgen/material_condition/density.rs b/crates/horizon-world/src/worldgen/material_condition/density.rs new file mode 100644 index 000000000..5c98c75e0 --- /dev/null +++ b/crates/horizon-world/src/worldgen/material_condition/density.rs @@ -0,0 +1,147 @@ +//! Preliminary surface density sampling scoped to one material context. +use super::{MaterialRuleError, MaterialSurfaceQueries}; +use crate::{registry::BlockStateId, worldgen::DecodeError}; +use horizon_core::{ + density::{DensitySampler, SamplerContext}, + noise::{DensityVolume, Noise}, + position::BlockPos, +}; +use std::{collections::BTreeSet, sync::Arc}; + +/// A lazy unit-spaced XZ plane and scalar fallback for preliminary heights. +/// Construct a fresh provider for each material context, with that world's +/// compiled preliminary-surface density root and bound sampler context. +pub struct MaterialDensitySources { + surface: S, + expected: DensityVolume, + densities: Vec, + retained_samples: usize, + plane: DensityVolume, + sampler: Arc, + context: SamplerContext, + buffer: Option>, +} +struct BoundDensity { + sampler: Arc, + buffer: Option>, +} +impl MaterialDensitySources { + pub fn sampler_context_mut(&mut self) -> &mut SamplerContext { + &mut self.context + } + pub fn into_parts(self) -> (S, SamplerContext) { + (self.surface, self.context) + } + pub fn new( + surface: S, + expected: DensityVolume, + sampler: Arc, + context: SamplerContext, + ) -> Result { + let [sx, _, sz] = expected.sizes(); + // Bound retained allocation. Normal chunk planes contain 256 samples. + if sx * sz > 1 << 20 { + return Err(DecodeError::Field("material preliminary plane size")); + } + let [x, _, z] = expected.minimum(); + let plane = DensityVolume::new([sx as i32, 1, sz as i32], [x, 0, z], [1; 3]) + .map_err(|_| DecodeError::Field("material preliminary plane"))?; + Ok(Self { + surface, + expected, + densities: Vec::new(), + retained_samples: 0, + plane, + sampler, + context, + buffer: None, + }) + } +} +impl MaterialSurfaceQueries for MaterialDensitySources { + fn bind_density( + &mut self, + sampler: Arc, + eager: bool, + ) -> Result { + if self.densities.len() >= 32768 + || (eager + && (self.expected.size() > 1 << 20 + || self.retained_samples + self.expected.size() > 1 << 24)) + { + return Err(DecodeError::Field("material density storage bound")); + } + let buffer = if eager { + let mut buffer = vec![0.0; self.expected.size()]; + sampler.sample_volume(&mut self.context, &mut buffer, self.expected)?; + self.retained_samples += buffer.len(); + Some(buffer) + } else { + None + }; + let index = self.densities.len(); + self.densities.push(BoundDensity { sampler, buffer }); + Ok(index) + } + fn density(&mut self, index: usize, position: BlockPos) -> Result { + let source = self + .densities + .get(index) + .ok_or(MaterialRuleError::MissingDensityProvider)?; + let position = [position.x, position.y, position.z]; + if let Some(buffer) = &source.buffer { + if let Some(index) = self.expected.index_of_block(position) { + return Ok(buffer[index]); + } + } + Ok(source.sampler.sample_value(&mut self.context, position)?) + } + fn preliminary_surface(&mut self, position: BlockPos) -> Result { + let position = [position.x, 0, position.z]; + if let Some(index) = self.plane.index_of_block(position) { + if self.buffer.is_none() { + // Retain the allocation and partial writes if sampling fails. + let buffer = self.buffer.insert(vec![0.0; self.plane.size()]); + self.sampler + .sample_volume(&mut self.context, buffer, self.plane)?; + } + Ok(self.buffer.as_ref().unwrap()[index]) + } else { + Ok(self.sampler.sample_value(&mut self.context, position)?) + } + } + fn possible_biomes(&self) -> Option> { + self.surface.possible_biomes() + } + fn biome(&mut self, position: BlockPos) -> Result>, MaterialRuleError> { + self.surface.biome(position) + } + fn melts_frozen_ocean( + &mut self, + biome: &str, + position: BlockPos, + sea_level: i32, + ) -> Result { + self.surface.melts_frozen_ocean(biome, position, sea_level) + } + fn cold_enough_to_snow( + &mut self, + biome: &str, + position: BlockPos, + sea_level: i32, + ) -> Result { + self.surface.cold_enough_to_snow(biome, position, sea_level) + } + fn bind_noise(&mut self, name: &str) -> Result, DecodeError> { + self.surface.bind_noise(name) + } + fn surface_depth(&mut self, x: i32, z: i32) -> i32 { + self.surface.surface_depth(x, z) + } + fn surface_secondary(&mut self, x: i32, z: i32) -> f64 { + self.surface.surface_secondary(x, z) + } + fn band(&mut self, position: BlockPos) -> Result { + self.surface.band(position) + } +} diff --git a/crates/horizon-world/src/worldgen/material_condition/library.rs b/crates/horizon-world/src/worldgen/material_condition/library.rs new file mode 100644 index 000000000..9debd7307 --- /dev/null +++ b/crates/horizon-world/src/worldgen/material_condition/library.rs @@ -0,0 +1,359 @@ +//! Immutable material-rule definitions with a world-seeded density compiler. +use super::{MaterialCondition, MaterialConditionRegistry, MaterialRule, codec::identifier}; +use crate::{ + registry::{BlockStateId, BlockStateJsonCodec}, + worldgen::{ + DecodeError, Object, + aquifer::{AquiferConfig, AquiferSamplers}, + density::DensityRegistry, + number_text, required, + router::{NoiseRouter, RouterSamplers}, + }, +}; +use horizon_core::density::{ + DensitySampler, + graph::{DensityCompiler, FunctionId}, +}; +use serde_json::value::RawValue; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; + +#[derive(Debug)] +enum Definition { + Block(BlockStateId), + Bandlands, + Sequence(Vec>), + Condition(MaterialCondition, Arc), + Reference(Arc), + Ore { + blocks: [BlockStateId; 3], + chance: f32, + roots: [usize; 3], + }, +} + +/// Definitions are decoded atomically. Density samplers are compiled lazily for +/// this world's seed; create workers with the same seed/random mode and a fresh +/// cached SamplerContext per worker. The library does not own mutable chunk data. +#[derive(Debug)] +pub struct MaterialRuleLibrary { + definitions: BTreeMap>, + roots: Vec, + compiler: DensityCompiler, + compiled: BTreeMap>, +} +impl MaterialRuleLibrary { + pub fn from_json( + definitions: &BTreeMap, + conditions: &MaterialConditionRegistry, + blocks: &BlockStateJsonCodec<'_>, + mut densities: DensityRegistry, + seed: i64, + legacy: bool, + ) -> Result { + if definitions.len() > 8192 { + return Err(DecodeError::Field("material rule registry size")); + } + let mut raw = BTreeMap::new(); + for (name, json) in definitions { + let value: Box = serde_json::from_str(json)?; + if raw.insert(identifier(name)?, value).is_some() { + return Err(DecodeError::Field("duplicate material rule")); + } + } + let mut loader = Loader { + raw, + values: BTreeMap::new(), + active: BTreeSet::new(), + conditions, + blocks, + roots: Vec::new(), + nodes: 0, + }; + for name in loader.raw.keys().cloned().collect::>() { + loader.resolve(&name, 0)?; + } + let roots = densities + .decode_functions(&loader.roots.iter().map(String::as_str).collect::>())?; + Ok(Self { + definitions: loader.values, + roots, + compiler: DensityCompiler::new_seeded(densities.into_graph(), seed, legacy), + compiled: BTreeMap::new(), + }) + } + pub fn names(&self) -> impl Iterator { + self.definitions.keys().map(String::as_str) + } + /// Resolve a named rule without sampling chunk densities yet. Binding the + /// returned rule to MaterialConditions performs eager per-chunk sampling. + pub fn rule(&mut self, name: &str) -> Result { + let definition = self + .definitions + .get(&identifier(name)?) + .ok_or(DecodeError::Field("unknown material rule"))? + .clone(); + Ok(MaterialRule::Reference(self.compile(&definition)?)) + } + /// Share this compiler's cache namespace with preliminary surface sampling. + pub fn named_density(&mut self, name: &str) -> Result, DecodeError> { + let id = self + .compiler + .graph() + .function(&identifier(name)?) + .ok_or(DecodeError::Field("unknown material density"))?; + Ok(self.compiler.get_sampler(id)?) + } + /// Compile a router decoded into the density registry passed to `from_json`. + /// Its roots share cache IDs with all material and aquifer samplers. + pub fn compile_router(&mut self, router: NoiseRouter) -> Result { + Ok(router.compile(&mut self.compiler)?) + } + /// Compile an aquifer decoded into the same density registry as this library. + /// Reuse the returned roots and the router in one worker's sampler context. + pub fn compile_aquifer( + &mut self, + config: AquiferConfig, + ) -> Result { + Ok(config.compile(&mut self.compiler)?) + } + fn compile(&mut self, definition: &Arc) -> Result, DecodeError> { + let key = Arc::as_ptr(definition) as usize; + if let Some(value) = self.compiled.get(&key) { + return Ok(value.clone()); + } + let value = Arc::new(match definition.as_ref() { + Definition::Block(id) => MaterialRule::Block(*id), + Definition::Bandlands => MaterialRule::Bandlands, + Definition::Reference(value) => MaterialRule::Reference(self.compile(value)?), + Definition::Sequence(children) => MaterialRule::Sequence( + children + .iter() + .map(|child| self.compile(child).map(MaterialRule::Reference)) + .collect::>()?, + ), + Definition::Condition(condition, child) => MaterialRule::Condition { + if_true: condition.clone(), + then_run: Box::new(MaterialRule::Reference(self.compile(child)?)), + }, + Definition::Ore { + blocks, + chance, + roots, + } => MaterialRule::OreVein { + ore: blocks[0], + raw_ore: blocks[1], + filler: blocks[2], + raw_ore_chance: *chance, + density: self.compiler.get_sampler(self.roots[roots[0]])?, + richness: self.compiler.get_sampler(self.roots[roots[1]])?, + filler_gap: self.compiler.get_sampler(self.roots[roots[2]])?, + }, + }); + self.compiled.insert(key, value.clone()); + Ok(value) + } +} +struct Loader<'a, 'b> { + raw: BTreeMap>, + values: BTreeMap>, + active: BTreeSet, + conditions: &'a MaterialConditionRegistry, + blocks: &'a BlockStateJsonCodec<'b>, + roots: Vec, + nodes: usize, +} +impl Loader<'_, '_> { + fn resolve(&mut self, name: &str, depth: usize) -> Result, DecodeError> { + if depth >= 256 { + return Err(DecodeError::Field("material rule depth")); + } + if let Some(value) = self.values.get(name) { + return Ok(value.clone()); + } + if !self.active.insert(name.to_owned()) { + return Err(DecodeError::Field("cyclic material rule")); + } + let raw = self + .raw + .get(name) + .ok_or(DecodeError::Field("missing material rule"))? + .clone(); + if !raw.get().starts_with('{') { + return Err(DecodeError::Field( + "material rule definition must be direct", + )); + } + let value = self.node(&raw, depth + 1)?; + self.active.remove(name); + self.values.insert(name.to_owned(), value.clone()); + Ok(value) + } + fn node(&mut self, raw: &RawValue, depth: usize) -> Result, DecodeError> { + self.nodes += 1; + if depth >= 256 || self.nodes > 65536 { + return Err(DecodeError::Field("material rule size")); + } + if raw.get().starts_with('"') { + let name = identifier(&serde_json::from_str::(raw.get())?)?; + return Ok(Arc::new(Definition::Reference( + self.resolve(&name, depth + 1)?, + ))); + } + let object: Object = serde_json::from_str(raw.get())?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + let block = |name| { + self.blocks + .decode(required(&object, name)?.get(), false) + .map_err(|e| DecodeError::Registry(e.to_string())) + }; + let value = match kind.as_str() { + "minecraft:block" => Definition::Block(block("result_state")?), + "minecraft:bandlands" => Definition::Bandlands, + "minecraft:sequence" => { + let children: Vec> = + serde_json::from_str(required(&object, "sequence")?.get())?; + Definition::Sequence( + children + .iter() + .map(|child| self.node(child, depth + 1)) + .collect::>()?, + ) + } + "minecraft:condition" => Definition::Condition( + self.conditions + .decode(required(&object, "if_true")?.get())?, + self.node(required(&object, "then_run")?, depth + 1)?, + ), + "minecraft:ore_vein" => { + let blocks = [ + block("ore_block")?, + block("raw_ore_block")?, + block("filler_block")?, + ]; + let chance = number_text(required(&object, "raw_ore_chance")?)? + .parse::() + .map_err(|_| DecodeError::Field("raw ore chance"))?; + if !(0.0..=1.0).contains(&chance) { + return Err(DecodeError::Field("raw ore chance")); + } + let base = self.roots.len(); + for name in ["density", "richness", "filler_gap"] { + self.roots.push(required(&object, name)?.get().to_owned()); + } + Definition::Ore { + blocks, + chance, + roots: [base, base + 1, base + 2], + } + } + _ => return Err(DecodeError::Field("material rule type")), + }; + Ok(Arc::new(value)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + DATA_VERSION, + nbt::Tag, + registry::BlockRegistry, + worldgen::{ + anchor::WorldGenerationContext, + material_condition::{MaterialConditions, MaterialSurfaceQueries}, + }, + }; + use horizon_core::{ + position::BlockPos, + random::{LegacyRandom, RandomSource}, + }; + struct Surface; + impl MaterialSurfaceQueries for Surface { + fn surface_depth(&mut self, _: i32, _: i32) -> i32 { + 0 + } + fn surface_secondary(&mut self, _: i32, _: i32) -> f64 { + 0.0 + } + } + #[test] + fn forward_rule_holders_and_invalid_graphs_are_atomic() { + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List(vec![Tag::compound([( + "id", + Tag::String("minecraft:stone".into()), + )])]), + ), + ( + "defaults", + Tag::compound([("minecraft:stone", Tag::Int(0))]), + ), + ])) + .unwrap(); + let blocks = BlockStateJsonCodec::new(®istry, BTreeSet::new()).unwrap(); + let conditions = MaterialConditionRegistry::default(); + let definitions = BTreeMap::from([ + ( + "horizon:a".to_owned(), + r#"{"type":"condition","if_true":{"type":"hole"},"then_run":"horizon:z"}"# + .to_owned(), + ), + ( + "horizon:z".to_owned(), + r#"{"type":"block","result_state":"stone"}"#.to_owned(), + ), + ]); + let load = |definitions: &BTreeMap| { + MaterialRuleLibrary::from_json( + definitions, + &conditions, + &blocks, + DensityRegistry::from_json(&BTreeMap::new(), &BTreeMap::new()).unwrap(), + 0, + false, + ) + }; + let mut valid = load(&definitions).unwrap(); + for bad in [ + r#"{"type":"condition","if_true":{"type":"hole"},"then_run":"horizon:a"}"#, + r#"{"type":"condition","if_true":{"type":"hole"},"then_run":"horizon:missing"}"#, + r#""horizon:z""#, + r#"{"type":"ore_vein","ore_block":"stone","raw_ore_block":"stone","filler_block":"stone","raw_ore_chance":0.1,"density":"horizon:missing","richness":0,"filler_gap":0}"#, + ] { + let mut invalid = definitions.clone(); + invalid.insert("horizon:z".to_owned(), bad.to_owned()); + assert!(load(&invalid).is_err()); + } + let mut duplicate = definitions; + duplicate.insert("z".to_owned(), r#"{"type":"bandlands"}"#.to_owned()); + duplicate.insert( + "minecraft:z".to_owned(), + r#"{"type":"bandlands"}"#.to_owned(), + ); + assert!(load(&duplicate).is_err()); + assert_eq!( + valid.names().collect::>(), + vec!["horizon:a", "horizon:z"] + ); + let mut random = LegacyRandom::new(0); + let mut worker = MaterialConditions::::new( + WorldGenerationContext::new(-64, 384, 63), + random.fork_positional(), + Surface, + ); + let index = worker.add_rule(valid.rule("horizon:a").unwrap()).unwrap(); + assert_eq!( + worker.try_apply(index, BlockPos::new(0, 64, 0)).unwrap(), + Some(BlockStateId(0)) + ); + } +} diff --git a/crates/horizon-world/src/worldgen/material_condition/noise.rs b/crates/horizon-world/src/worldgen/material_condition/noise.rs new file mode 100644 index 000000000..9ec6a4074 --- /dev/null +++ b/crates/horizon-world/src/worldgen/material_condition/noise.rs @@ -0,0 +1,112 @@ +//! Named material-noise sources derived from the world's positional factory. +use super::{MaterialRuleError, MaterialSurfaceQueries, codec::identifier}; +use crate::{ + registry::BlockStateId, + worldgen::{DecodeError, decode_noise}, +}; +use horizon_core::{ + noise::{Noise, NormalNoise}, + position::BlockPos, + random::PositionalRandom, +}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; + +/// Add lazy, shared named noise sources to a material surface provider. +/// Both providers must be configured for the same world seed and random mode. +pub struct MaterialNoiseSources { + root: P, + surface: S, + definitions: BTreeMap, + samplers: BTreeMap>, +} +impl MaterialNoiseSources { + pub fn from_json( + root: P, + surface: S, + definitions: &BTreeMap, + ) -> Result { + if definitions.len() > 8192 { + return Err(DecodeError::Field("material noise registry size")); + } + let mut noises = BTreeMap::new(); + for (name, json) in definitions { + if noises + .insert(identifier(name)?, decode_noise(json)?) + .is_some() + { + return Err(DecodeError::Field("duplicate material noise")); + } + } + Ok(Self { + root, + surface, + definitions: noises, + samplers: BTreeMap::new(), + }) + } +} +impl MaterialSurfaceQueries + for MaterialNoiseSources +{ + fn bind_density( + &mut self, + sampler: Arc, + eager: bool, + ) -> Result { + self.surface.bind_density(sampler, eager) + } + fn density(&mut self, index: usize, position: BlockPos) -> Result { + self.surface.density(index, position) + } + fn preliminary_surface(&mut self, position: BlockPos) -> Result { + self.surface.preliminary_surface(position) + } + fn possible_biomes(&self) -> Option> { + self.surface.possible_biomes() + } + fn biome(&mut self, position: BlockPos) -> Result>, MaterialRuleError> { + self.surface.biome(position) + } + fn melts_frozen_ocean( + &mut self, + biome: &str, + position: BlockPos, + sea_level: i32, + ) -> Result { + self.surface.melts_frozen_ocean(biome, position, sea_level) + } + fn cold_enough_to_snow( + &mut self, + biome: &str, + position: BlockPos, + sea_level: i32, + ) -> Result { + self.surface.cold_enough_to_snow(biome, position, sea_level) + } + fn surface_depth(&mut self, x: i32, z: i32) -> i32 { + self.surface.surface_depth(x, z) + } + fn surface_secondary(&mut self, x: i32, z: i32) -> f64 { + self.surface.surface_secondary(x, z) + } + fn band(&mut self, position: BlockPos) -> Result { + self.surface.band(position) + } + fn bind_noise(&mut self, name: &str) -> Result, DecodeError> { + let name = identifier(name)?; + if let Some(noise) = self.samplers.get(&name) { + return Ok(noise.clone()); + } + let definition = self + .definitions + .get(&name) + .ok_or(DecodeError::Field("unknown material noise"))?; + let noise: Arc = + Arc::new(definition.create(&mut self.root.from_hash_of(&name))?); + self.samplers.insert(name, noise.clone()); + Ok(noise) + } +} diff --git a/crates/horizon-world/src/worldgen/material_condition/rule.rs b/crates/horizon-world/src/worldgen/material_condition/rule.rs new file mode 100644 index 000000000..9dfc2ff1e --- /dev/null +++ b/crates/horizon-world/src/worldgen/material_condition/rule.rs @@ -0,0 +1,222 @@ +//! Compiled material rule composition, sharing the condition worker's context. +use super::{Compiled, Context, MaterialCondition, MaterialConditions, MaterialSurfaceQueries}; +use crate::{registry::BlockStateId, worldgen::DecodeError}; +use horizon_core::{ + density::DensitySampler, + position::BlockPos, + random::{PositionalRandom, RandomSource}, +}; +use std::sync::Arc; + +#[derive(Clone, Debug)] +pub enum MaterialRule { + Block(BlockStateId), + Reference(Arc), + /// Density roots must be compiled for the same world and sampler context. + OreVein { + ore: BlockStateId, + raw_ore: BlockStateId, + filler: BlockStateId, + raw_ore_chance: f32, + density: Arc, + richness: Arc, + filler_gap: Arc, + }, + Sequence(Vec), + Condition { + if_true: MaterialCondition, + then_run: Box, + }, + /// Vanilla calls this rule "bandlands"; it queries terracotta bands. + Bandlands, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MaterialRuleError { + UnknownRule, + UnknownCondition, + MissingBiomeProvider, + BiomeQueryFailed, + MissingBiome, + CachedConditionUnavailable, + MissingBandProvider, + MissingDensityProvider, + Density(horizon_core::density::SampleError), + InvalidBandIndex, +} +impl std::fmt::Display for MaterialRuleError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if let Self::Density(error) = self { + return error.fmt(f); + } + f.write_str(match self { + Self::Density(_) => unreachable!(), + Self::MissingDensityProvider => "missing material density provider", + Self::UnknownRule => "unknown material rule", + Self::UnknownCondition => "unknown material condition", + Self::MissingBiomeProvider => "missing material biome provider", + Self::BiomeQueryFailed => "material biome lookup failed", + Self::MissingBiome => "material position has no biome", + Self::CachedConditionUnavailable => "condition was updated without a cached result", + Self::MissingBandProvider => "missing material band provider", + Self::InvalidBandIndex => "negative material band index", + }) + } +} +impl std::error::Error for MaterialRuleError {} +impl From for MaterialRuleError { + fn from(error: horizon_core::density::SampleError) -> Self { + Self::Density(error) + } +} + +pub(super) enum CompiledRule { + Block(BlockStateId), + OreVein { + blocks: [BlockStateId; 3], + raw_ore_chance: f32, + densities: [usize; 3], + random: R::Positional, + }, + Sequence(Vec), + Condition { + condition: Compiled, + rule: Box, + }, + Bandlands, +} +impl CompiledRule { + fn compile( + rule: MaterialRule, + root: &R::Positional, + context: &mut Context, + depth: usize, + nodes: &mut usize, + ) -> Result { + *nodes += 1; + if depth >= 256 || *nodes > 65536 { + return Err(DecodeError::Field("material rule size")); + } + Ok(match rule { + MaterialRule::Block(block) => Self::Block(block), + MaterialRule::Reference(value) => { + return Self::compile((*value).clone(), root, context, depth + 1, nodes); + } + MaterialRule::OreVein { + ore, + raw_ore, + filler, + raw_ore_chance, + density, + richness, + filler_gap, + } => { + let density = context.surface.bind_density(density, true)?; + let richness = context.surface.bind_density(richness, true)?; + let gap = context.surface.bind_density(filler_gap, false)?; + let random = root.from_hash_of("minecraft:ore").fork_positional(); + Self::OreVein { + blocks: [ore, raw_ore, filler], + raw_ore_chance, + densities: [density, richness, gap], + random, + } + } + MaterialRule::Bandlands => Self::Bandlands, + MaterialRule::Condition { if_true, then_run } => { + // Compile the predicate before the nested rule, regardless of + // whether the predicate will match any subsequent position. + let condition = Compiled::compile(if_true, root, context, depth + 1)?; + let rule = Box::new(Self::compile(*then_run, root, context, depth + 1, nodes)?); + Self::Condition { condition, rule } + } + MaterialRule::Sequence(mut children) => { + if children.len() == 1 { + return Self::compile(children.pop().unwrap(), root, context, depth + 1, nodes); + } + let mut result = Vec::with_capacity(children.len()); + for child in children { + result.push(Self::compile(child, root, context, depth + 1, nodes)?); + } + Self::Sequence(result) + } + }) + } + fn apply( + &mut self, + position: BlockPos, + context: &mut Context, + ) -> Result, MaterialRuleError> { + match self { + Self::Block(block) => Ok(Some(*block)), + Self::OreVein { + blocks, + raw_ore_chance, + densities, + random, + } => { + // Densities use the context; randomness uses application coordinates. + let density = context.surface.density(densities[0], context.position)?; + if density <= 0.0 { + return Ok(None); + } + let mut random = random.at(position); + if random.next_float() > density { + return Ok(None); + } + let richness = context.surface.density(densities[1], context.position)?; + if random.next_float() < richness + && context.surface.density(densities[2], context.position)? < 0.0 + { + Ok(Some(if random.next_float() < *raw_ore_chance { + blocks[1] + } else { + blocks[0] + })) + } else { + Ok(Some(blocks[2])) + } + } + Self::Bandlands => context.surface.band(position).map(Some), + Self::Condition { condition, rule } => { + if condition.test(context)? { + rule.apply(position, context) + } else { + Ok(None) + } + } + Self::Sequence(children) => { + for child in children { + if let Some(block) = child.apply(position, context)? { + return Ok(Some(block)); + } + } + Ok(None) + } + } + } +} +impl MaterialConditions { + /// Compile all children in order, even after an unconditional block rule. + /// Failed compilation never adds a partial rule to this worker. + pub fn add_rule(&mut self, rule: MaterialRule) -> Result { + if self.rules.len() >= 8192 { + return Err(DecodeError::Field("material rule count")); + } + let compiled = CompiledRule::compile(rule, &self.root, &mut self.context, 0, &mut 0)?; + let index = self.rules.len(); + self.rules.push(compiled); + Ok(index) + } + /// Predicates read the worker's updated context. Position arguments are + /// forwarded to block-producing rules independently, as in vanilla. + pub fn try_apply( + &mut self, + index: usize, + position: BlockPos, + ) -> Result, MaterialRuleError> { + self.rules + .get_mut(index) + .ok_or(MaterialRuleError::UnknownRule)? + .apply(position, &mut self.context) + } +} diff --git a/crates/horizon-world/src/worldgen/material_extensions.rs b/crates/horizon-world/src/worldgen/material_extensions.rs new file mode 100644 index 000000000..8fb5735ac --- /dev/null +++ b/crates/horizon-world/src/worldgen/material_extensions.rs @@ -0,0 +1,229 @@ +//! Eroded-badlands pillars and frozen-ocean icebergs, before chunk integration. +use super::biome_temperature::BiomeTemperature; +use crate::registry::BlockStateId; +use horizon_core::{ + noise::Noise, + position::BlockPos, + random::{PositionalRandom, RandomSource}, +}; +use std::sync::Arc; + +/// Reads and writes retain provider order. The chunk adapter supplies vanilla +/// out-of-height reads and generation-height write clipping. +pub trait MaterialColumn { + type Error; + fn block(&mut self, y: i32) -> Result; + fn set_block(&mut self, y: i32, state: BlockStateId) -> Result<(), Self::Error>; + fn is_air(&self, state: BlockStateId) -> bool; + fn same_block(&self, left: BlockStateId, right: BlockStateId) -> bool; +} +#[derive(Clone, Copy, Debug)] +pub struct ExtensionBlocks { + pub default: BlockStateId, + pub water: BlockStateId, + pub packed_ice: BlockStateId, + pub snow: BlockStateId, +} +#[derive(Clone, Debug)] +pub struct ExtensionNoises { + pub badlands_surface: Arc, + pub badlands_pillar: Arc, + pub badlands_roof: Arc, + pub iceberg_surface: Arc, + pub iceberg_pillar: Arc, + pub iceberg_roof: Arc, +} +#[derive(Debug)] +pub enum ExtensionError { + Column(E), + IterationLimit, +} +impl std::fmt::Display for ExtensionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Column(error) => error.fmt(f), + Self::IterationLimit => f.write_str("material column iteration bound exceeded"), + } + } +} +impl std::error::Error for ExtensionError {} +impl From for ExtensionError { + fn from(error: E) -> Self { + Self::Column(error) + } +} + +/// Random is the world's root positional factory. Noises and biome temperatures +/// must be configured for the same immutable world-generation settings. +pub struct MaterialExtensions

{ + random: P, + blocks: ExtensionBlocks, + noises: ExtensionNoises, + sea_level: i32, +} +impl MaterialExtensions

{ + pub fn new( + random: P, + blocks: ExtensionBlocks, + noises: ExtensionNoises, + sea_level: i32, + ) -> Self { + Self { + random, + blocks, + noises, + sea_level, + } + } + pub fn eroded_badlands( + &self, + column: &mut C, + x: i32, + z: i32, + surface_y: i32, + min_y: i32, + ) -> Result<(), ExtensionError> { + let x = f64::from(x); + let z = f64::from(z); + let amplitude = java_min( + (f64::from(self.noises.badlands_surface.get3(x, 0.0, z)) * 8.25).abs(), + f64::from(self.noises.badlands_pillar.get3(x * 0.2, 0.0, z * 0.2) * 15.0), + ); + if amplitude <= 0.0 { + return Ok(()); + } + let roof = (f64::from(self.noises.badlands_roof.get3(x * 0.75, 0.0, z * 0.75)) * 1.5).abs(); + let top = (64.0 + java_min(amplitude * amplitude * 2.5, (roof * 50.0).ceil() + 24.0)) + .floor() as i32; + if surface_y > top { + return Ok(()); + } + let mut budget = 1 << 20; + let mut y = top; + while y >= min_y { + tick(&mut budget)?; + let state = column.block(y)?; + if column.same_block(state, self.blocks.default) { + break; + } + if column.same_block(state, self.blocks.water) { + return Ok(()); + } + y = y.wrapping_sub(1); + } + y = top; + while y >= min_y { + tick(&mut budget)?; + let state = column.block(y)?; + if !column.is_air(state) { + break; + } + column.set_block(y, self.blocks.default)?; + y = y.wrapping_sub(1); + } + Ok(()) + } + pub fn frozen_ocean( + &self, + column: &mut C, + biome: &mut BiomeTemperature, + position: [i32; 2], + surface_y: i32, + minimum_surface_y: i32, + ) -> Result<(), ExtensionError> { + self.frozen_ocean_with_melt( + column, + position, + surface_y, + minimum_surface_y, + |position, sea| Ok(biome.should_melt_frozen_ocean_iceberg_slightly(position, sea)), + ) + } + /// Defer the biome lookup until the native noise/height checks reach it. + pub fn frozen_ocean_with_melt( + &self, + column: &mut C, + position: [i32; 2], + surface_y: i32, + minimum_surface_y: i32, + melt: impl FnOnce(BlockPos, i32) -> Result, + ) -> Result<(), ExtensionError> { + let [x, z] = position; + let dx = f64::from(x); + let dz = f64::from(z); + let amplitude = java_min( + (f64::from(self.noises.iceberg_surface.get3(dx, 0.0, dz)) * 8.25).abs(), + f64::from(self.noises.iceberg_pillar.get3(dx * 1.28, 0.0, dz * 1.28) * 15.0), + ); + if amplitude <= 1.8 { + return Ok(()); + } + let roof = + (f64::from(self.noises.iceberg_roof.get3(dx * 1.17, 0.0, dz * 1.17)) * 1.5).abs(); + let mut height = java_min(amplitude * amplitude * 1.2, (roof * 40.0).ceil() + 14.0); + if melt(BlockPos::new(x, self.sea_level, z), self.sea_level)? { + height -= 2.0; + } + if height <= 2.0 { + return Ok(()); + } + let bottom = f64::from(self.sea_level) - height - 7.0; + let top = height + f64::from(self.sea_level); + let mut random = self.random.at(BlockPos::new(x, 0, z)); + let snow_limit = 2 + random.next_int_bound(4).unwrap(); + let snow_height = self + .sea_level + .wrapping_add(18) + .wrapping_add(random.next_int_bound(10).unwrap()); + let mut snow_count = 0; + let mut y = surface_y.max((top as i32).wrapping_add(1)); + let mut budget = 1 << 20; + while y >= minimum_surface_y { + tick(&mut budget)?; + let state = column.block(y)?; + let air = column.is_air(state) && y < (top as i32) && random.next_double() > 0.01; + let fill = if air { + true + } else { + // The second getBlock is observable even when the first read + // found air but failed its height or random test. + let state = column.block(y)?; + column.same_block(state, self.blocks.water) + && y > (bottom as i32) + && y < self.sea_level + && random.next_double() > 0.15 + }; + if fill { + let state = if snow_count <= snow_limit && y > snow_height { + snow_count += 1; + self.blocks.snow + } else { + self.blocks.packed_ice + }; + column.set_block(y, state)?; + } + y = y.wrapping_sub(1); + } + Ok(()) + } +} +fn tick(remaining: &mut usize) -> Result<(), ExtensionError> { + if *remaining == 0 { + return Err(ExtensionError::IterationLimit); + } + *remaining -= 1; + Ok(()) +} +fn java_min(a: f64, b: f64) -> f64 { + if a.is_nan() { + a + } else if b.is_nan() { + b + } else if a == 0.0 && b == 0.0 { + f64::from_bits(a.to_bits() | b.to_bits()) + } else if a <= b { + a + } else { + b + } +} diff --git a/crates/horizon-world/src/worldgen/material_stage.rs b/crates/horizon-world/src/worldgen/material_stage.rs new file mode 100644 index 000000000..0763c4e63 --- /dev/null +++ b/crates/horizon-world/src/worldgen/material_stage.rs @@ -0,0 +1,351 @@ +//! Surface-stage column traversal and pre-lighting chunk writes. +use super::{ + DecodeError, + anchor::WorldGenerationContext, + material_condition::{ + MaterialConditions, MaterialDensitySources, MaterialRule, MaterialRuleError, + MaterialSurfaceQueries, + }, + material_extensions::{ExtensionError, MaterialColumn, MaterialExtensions}, + terrain::{TerrainBlockStates, TerrainChunk, TerrainError}, +}; +use crate::{ + heightmap::{HeightmapState, HeightmapType}, + registry::BlockStateId, +}; +use horizon_core::{ + density::{DensitySampler, SamplerContext}, + noise::DensityVolume, + position::BlockPos, + random::RandomSource, +}; +use std::sync::Arc; + +pub struct SurfaceInputs<'a, R: RandomSource, S: MaterialSurfaceQueries> { + pub generation: WorldGenerationContext, + pub noise_volume: DensityVolume, + pub root: R::Positional, + pub surface: S, + pub preliminary_surface: Arc, + pub density_context: &'a mut SamplerContext, + /// Inclusive generation write bounds, contained within the chunk. + pub write_min_y: i32, + pub write_max_y: i32, +} +pub struct TopMaterialInputs<'a, R: RandomSource, S: MaterialSurfaceQueries> { + pub generation: WorldGenerationContext, + pub root: R::Positional, + pub surface: S, + pub preliminary_surface: Arc, + pub density_context: &'a mut SamplerContext, +} +#[derive(Debug)] +pub enum SurfaceError { + Terrain(TerrainError), + Rule(MaterialRuleError), + Decode(DecodeError), + InvalidBounds, + InvalidVolume, + IterationLimit, +} +impl std::fmt::Display for SurfaceError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{self:?}") + } +} +impl std::error::Error for SurfaceError {} +impl From for SurfaceError { + fn from(e: TerrainError) -> Self { + Self::Terrain(e) + } +} +impl From for SurfaceError { + fn from(e: MaterialRuleError) -> Self { + Self::Rule(e) + } +} +impl From for SurfaceError { + fn from(e: DecodeError) -> Self { + Self::Decode(e) + } +} +impl From> for SurfaceError { + fn from(e: ExtensionError) -> Self { + match e { + ExtensionError::Column(e) => e, + ExtensionError::IterationLimit => Self::IterationLimit, + } + } +} + +struct Column<'a, 'r, B: TerrainBlockStates> { + chunk: &'a mut TerrainChunk<'r, B>, + x: i32, + z: i32, + min: i32, + max: i32, +} +impl MaterialColumn for Column<'_, '_, B> { + type Error = SurfaceError; + fn block(&mut self, y: i32) -> Result { + Ok(self.chunk.block(self.x, y, self.z)) + } + fn set_block(&mut self, y: i32, state: BlockStateId) -> Result<(), SurfaceError> { + if y >= self.min && y <= self.max { + self.chunk.set_block_worldgen(self.x, y, self.z, state)?; + if self.chunk.block_properties(state).has_fluid() { + self.chunk.mark_postprocessing(self.x, y, self.z); + } + } + Ok(()) + } + fn is_air(&self, state: BlockStateId) -> bool { + self.chunk.block_properties(state).is_air() + } + fn same_block(&self, left: BlockStateId, right: BlockStateId) -> bool { + self.chunk.same_block(left, right) + } +} +fn first_available( + chunk: &mut TerrainChunk<'_, B>, + x: i32, + z: i32, +) -> Result { + if chunk.heightmap(HeightmapType::WorldSurfaceWg).is_none() { + chunk.prime_heightmaps(&[HeightmapType::WorldSurfaceWg])?; + } + chunk + .heightmap(HeightmapType::WorldSurfaceWg) + .unwrap() + .first_available(x, z) + .map_err(TerrainError::from) + .map_err(SurfaceError::from) +} +fn tick(remaining: &mut usize) -> Result<(), SurfaceError> { + if *remaining == 0 { + return Err(SurfaceError::IterationLimit); + } + *remaining -= 1; + Ok(()) +} + +/// Evaluate the replacement surface under a carved block. Each call binds a +/// fresh one-cell material context, without restricting possible biomes, and +/// uses one stone block above/below. The caller applies the returned state. +/// Required heightmaps may be primed; block values are not changed here. +/// The caller's density context is retained on successful and failed evaluation. +pub fn top_material( + chunk: &mut TerrainChunk<'_, B>, + rule: MaterialRule, + inputs: TopMaterialInputs<'_, R, S>, + position: BlockPos, + submerged: bool, +) -> Result, SurfaceError> { + let volume = DensityVolume::new([1; 3], [position.x, position.y, position.z], [1; 3]) + .map_err(|_| SurfaceError::InvalidVolume)?; + let mut sources = MaterialDensitySources::new( + inputs.surface, + volume, + inputs.preliminary_surface, + SamplerContext::default(), + )?; + std::mem::swap(sources.sampler_context_mut(), inputs.density_context); + let mut worker = MaterialConditions::::with_possible_biomes( + inputs.generation, + inputs.root, + sources, + None, + ); + let result = (|| { + let rule = worker.add_rule(rule)?; + let (lx, lz) = (position.x & 15, position.z & 15); + let gx = first_available(chunk, (lx + 1).min(15), lz)?.wrapping_sub(first_available( + chunk, + (lx - 1).max(0), + lz, + )?); + let gz = first_available(chunk, lx, (lz + 1).min(15))?.wrapping_sub(first_available( + chunk, + lx, + (lz - 1).max(0), + )?); + worker.update_xz(position.x, position.z, gx, gz); + worker.update_y( + 1, + 1, + if submerged { + position.y.wrapping_add(1) + } else { + i32::MIN + }, + position.y, + ); + worker.try_apply(rule, position).map_err(SurfaceError::from) + })(); + let (_, mut context) = worker.into_surface().into_parts(); + std::mem::swap(&mut context, inputs.density_context); + result +} + +/// Build one chunk's surface in vanilla X/Z/descending-Y order. Required heightmaps +/// are updated during writes, so later columns observe earlier modifications. +/// Providers, rule roots, extensions and random settings must belong to one world. +/// Failures retain prior chunk writes and fluid postprocessing entries. +pub fn build_surface( + chunk: &mut TerrainChunk<'_, B>, + rule: MaterialRule, + inputs: SurfaceInputs<'_, R, S>, + extensions: &MaterialExtensions, +) -> Result<(), SurfaceError> { + let min = chunk.min_y(); + let max = min + chunk.height() - 1; + if inputs.write_min_y < min + || inputs.write_max_y > max + || inputs.write_min_y > inputs.write_max_y + { + return Err(SurfaceError::InvalidBounds); + } + let highest = chunk + .highest_filled_section_index() + .map_or(min - 1, |i| min + (i as i32) * 16 + 15); + let sizes = inputs.noise_volume.sizes(); + let origin = inputs.noise_volume.minimum(); + let height = highest.wrapping_sub(origin[1]).wrapping_add(1).max(1); + let expected = DensityVolume::new([sizes[0] as i32, height, sizes[2] as i32], origin, [1; 3]) + .map_err(|_| SurfaceError::InvalidVolume)?; + let mut sources = MaterialDensitySources::new( + inputs.surface, + expected, + inputs.preliminary_surface, + SamplerContext::default(), + )?; + std::mem::swap(sources.sampler_context_mut(), inputs.density_context); + let mut worker = MaterialConditions::::new(inputs.generation, inputs.root, sources); + let result = build_columns( + chunk, + rule, + &mut worker, + extensions, + inputs.write_min_y, + inputs.write_max_y, + ); + let (_, mut context) = worker.into_surface().into_parts(); + std::mem::swap(&mut context, inputs.density_context); + result +} +fn build_columns( + chunk: &mut TerrainChunk<'_, B>, + rule: MaterialRule, + worker: &mut MaterialConditions, + extensions: &MaterialExtensions, + write_min_y: i32, + write_max_y: i32, +) -> Result<(), SurfaceError> { + let min = chunk.min_y(); + let rule = worker.add_rule(rule)?; + let cx = chunk.position().x.wrapping_shl(4); + let cz = chunk.position().z.wrapping_shl(4); + for lx in 0..16 { + for lz in 0..16 { + let x = cx.wrapping_add(lx); + let z = cz.wrapping_add(lz); + let original_top = first_available(chunk, lx, lz)?; + let biome = worker + .biome_at(BlockPos::new(x, original_top, z))? + .ok_or(MaterialRuleError::MissingBiome)?; + if biome.as_ref() == "minecraft:eroded_badlands" { + extensions.eroded_badlands( + &mut Column { + chunk, + x, + z, + min: write_min_y, + max: write_max_y, + }, + x, + z, + original_top, + min, + )?; + } + let top = first_available(chunk, lx, lz)?; + let gx = first_available(chunk, (lx + 1).min(15), lz)?.wrapping_sub(first_available( + chunk, + (lx - 1).max(0), + lz, + )?); + let gz = first_available(chunk, lx, (lz + 1).min(15))?.wrapping_sub(first_available( + chunk, + lx, + (lz - 1).max(0), + )?); + worker.update_xz(x, z, gx, gz); + let mut above = 0i32; + let mut water = i32::MIN; + let mut bottom = i32::MAX; + let mut y = top; + let mut budget = 1 << 20; + let mut column = Column { + chunk, + x, + z, + min: write_min_y, + max: write_max_y, + }; + while y >= min { + tick(&mut budget)?; + let state = column.block(y)?; + let properties = column.chunk.block_properties(state); + if properties.is_air() { + above = 0; + water = i32::MIN; + } else if properties.has_fluid() { + if water == i32::MIN { + water = y.wrapping_add(1); + } + } else { + if bottom >= y { + bottom = -32512; // DimensionType.MIN_Y << 4 for 26.3. + let mut below = y.wrapping_sub(1); + while below >= min - 1 { + tick(&mut budget)?; + let state = column.block(below)?; + let properties = column.chunk.block_properties(state); + if properties.is_air() || properties.has_fluid() { + bottom = below.wrapping_add(1); + break; + } + below = below.wrapping_sub(1); + } + } + above = above.wrapping_add(1); + worker.update_y(above, y.wrapping_sub(bottom).wrapping_add(1), water, y); + if y >= write_min_y && y <= write_max_y { + if let Some(state) = worker.try_apply(rule, BlockPos::new(x, y, z))? { + column.set_block(y, state)?; + } + } + } + y = y.wrapping_sub(1); + } + if matches!( + biome.as_ref(), + "minecraft:frozen_ocean" | "minecraft:deep_frozen_ocean" + ) { + let minimum = worker.minimum_surface_level()?; + extensions.frozen_ocean_with_melt( + &mut column, + [x, z], + original_top, + minimum, + |position, sea| { + worker + .melts_frozen_ocean(&biome, position, sea) + .map_err(SurfaceError::from) + }, + )?; + } + } + } + Ok(()) +} diff --git a/crates/horizon-world/src/worldgen/material_surface.rs b/crates/horizon-world/src/worldgen/material_surface.rs new file mode 100644 index 000000000..c463ec063 --- /dev/null +++ b/crates/horizon-world/src/worldgen/material_surface.rs @@ -0,0 +1,142 @@ +//! Seeded terracotta bands and the material system's surface-noise queries. +use crate::registry::{BlockRegistry, BlockStateId}; +use horizon_core::{ + noise::Noise, + random::{PositionalRandom, RandomSource}, +}; +use std::sync::Arc; + +#[derive(Clone, Copy, Debug)] +pub struct ClayBandBlocks { + pub terracotta: BlockStateId, + pub orange: BlockStateId, + pub yellow: BlockStateId, + pub brown: BlockStateId, + pub red: BlockStateId, + pub white: BlockStateId, + pub light_gray: BlockStateId, +} +impl ClayBandBlocks { + pub fn from_registry(registry: &BlockRegistry) -> Option { + Some(Self { + terracotta: registry.default_state("minecraft:terracotta")?, + orange: registry.default_state("minecraft:orange_terracotta")?, + yellow: registry.default_state("minecraft:yellow_terracotta")?, + brown: registry.default_state("minecraft:brown_terracotta")?, + red: registry.default_state("minecraft:red_terracotta")?, + white: registry.default_state("minecraft:white_terracotta")?, + light_gray: registry.default_state("minecraft:light_gray_terracotta")?, + }) + } +} +#[derive(Clone, Debug)] +pub struct ClayBands([BlockStateId; 192]); +impl ClayBands { + /// The input is MaterialSystem's clay_bands child stream. Every conditional + /// random draw and overwrite retains vanilla order. + pub fn generate(random: &mut impl RandomSource, blocks: ClayBandBlocks) -> Self { + let mut bands = [blocks.terracotta; 192]; + let mut i = 0; + while i < bands.len() { + i += random.next_int_bound(5).unwrap() as usize + 1; + if i < bands.len() { + bands[i] = blocks.orange; + } + i += 1; + } + Self::make_bands(random, &mut bands, 1, blocks.yellow); + Self::make_bands(random, &mut bands, 2, blocks.brown); + Self::make_bands(random, &mut bands, 1, blocks.red); + let count = random.next_int_between_inclusive(9, 15).unwrap(); + let mut position = 0; + for _ in 0..count { + if position >= bands.len() { + break; + } + bands[position] = blocks.white; + if position > 1 && random.next_boolean() { + bands[position - 1] = blocks.light_gray; + } + if position + 1 < bands.len() && random.next_boolean() { + bands[position + 1] = blocks.light_gray; + } + position += random.next_int_bound(16).unwrap() as usize + 4; + } + Self(bands) + } + fn make_bands( + random: &mut impl RandomSource, + bands: &mut [BlockStateId; 192], + base_width: usize, + state: BlockStateId, + ) { + let count = random.next_int_between_inclusive(6, 15).unwrap(); + for _ in 0..count { + let width = base_width + random.next_int_bound(3).unwrap() as usize; + let start = random.next_int_bound(192).unwrap() as usize; + let end = (start + width).min(bands.len()); + bands[start..end].fill(state); + } + } + pub fn states(&self) -> &[BlockStateId; 192] { + &self.0 + } + /// Preserve Java's signed remainder. Extreme or unsupported negative heights + /// can produce an invalid index, which returns None instead of an exception. + pub fn at_noise(&self, y: i32, noise: f32) -> Option { + let offset = round_float(noise * 4.); + let index = y.wrapping_add(offset).wrapping_add(192) % 192; + self.0.get(index as usize).copied() + } +} +fn round_float(value: f32) -> i32 { + // f64 retains every relevant half-integer boundary of a float that fits an + // int. Rust's cast supplies Java's NaN-to-zero and saturating endpoints. + (f64::from(value) + 0.5).floor() as i32 +} +#[derive(Debug)] +pub struct MaterialSurface

{ + bands: ClayBands, + random: P, + clay_offset: Arc, + surface: Arc, + secondary: Arc, +} +impl MaterialSurface

{ + /// `random` is the world's root positional factory, not a surface child. + pub fn new( + random: P, + blocks: ClayBandBlocks, + clay_offset: Arc, + surface: Arc, + secondary: Arc, + ) -> Self { + let bands = ClayBands::generate(&mut random.from_hash_of("minecraft:clay_bands"), blocks); + Self { + bands, + random, + clay_offset, + surface, + secondary, + } + } + pub fn bands(&self) -> &ClayBands { + &self.bands + } + pub fn band(&self, [x, y, z]: [i32; 3]) -> Option { + self.bands + .at_noise(y, self.clay_offset.get3(f64::from(x), 0., f64::from(z))) + } + pub fn surface_depth(&self, x: i32, z: i32) -> i32 { + let noise = f64::from(self.surface.get3(f64::from(x), 0., f64::from(z))); + ((noise * 2.75 + 3.) + + self + .random + .at(horizon_core::position::BlockPos::new(x, 0, z)) + .next_double() + * 0.25) as i32 + } + pub fn surface_secondary(&self, x: i32, z: i32) -> f64 { + f64::from(self.secondary.get3(f64::from(x), 0., f64::from(z))) + } +} diff --git a/crates/horizon-world/src/worldgen/ore_feature.rs b/crates/horizon-world/src/worldgen/ore_feature.rs new file mode 100644 index 000000000..a6a6f4006 --- /dev/null +++ b/crates/horizon-world/src/worldgen/ore_feature.rs @@ -0,0 +1,101 @@ +//! Ore placement with ordered replacement rules and air-exposure checks. +use super::{ + DecodeError, Object, + block_feature::{BlockReplacements, FeatureBlockBindings, decode_targets}, + density::identifier, + feature::{FeatureError, FeatureWorld}, + int_range, number_text, required, +}; +use crate::registry::BlockStateId; +use horizon_core::{geometry::Direction, random::RandomSource}; + +#[derive(Clone, Debug)] +pub struct ScatteredOreFeature { + targets: BlockReplacements, + size: i32, + discard: f32, + air: [BlockStateId; 3], +} +impl ScatteredOreFeature { + pub fn from_json(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result { + Self::decode(json, bindings, 0, &mut 65536) + } + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + if kind != "minecraft:scattered_ore" { + return Err(DecodeError::Field("scattered ore type")); + } + let targets = decode_targets(&object, bindings, depth, remaining)?; + let size = int_range(required(&object, "size")?, "ore size", 0, 64)?; + let discard: f32 = number_text(required(&object, "discard_chance_on_air_exposure")?)? + .parse() + .map_err(|_| DecodeError::Field("ore air exposure"))?; + if !(0.0..=1.0).contains(&discard) || discard.is_sign_negative() { + return Err(DecodeError::Field("ore air exposure")); + } + Ok(Self { + targets, + size, + discard, + air: bindings.air, + }) + } + pub fn place( + &self, + world: &mut W, + random: &mut impl RandomSource, + origin: [i32; 3], + ) -> Result> { + let count = random + .next_int_bound(self.size + 1) + .map_err(FeatureError::Random)?; + for attempt in 0..count { + let spread = attempt.min(7) as f32; + let position = origin.map(|component| { + let offset = (random.next_float() - random.next_float()) * spread; + // Widen before adding 0.5 so a float just below a tie cannot + // round up during addition. Values are bounded by +/-7. + let offset = (f64::from(offset) + 0.5).floor() as i32; + component.wrapping_add(offset) + }); + let current = world.block(position).map_err(FeatureError::World)?; + for (rule, state) in &self.targets { + if !rule.test(current, position, random) { + continue; + } + let skip_air = self.discard <= 0.0 + || (self.discard < 1.0 && random.next_float() >= self.discard); + if !skip_air { + let mut exposed = false; + for direction in Direction::ALL { + let delta = direction.normal(); + let neighbor = std::array::from_fn(|i| position[i].wrapping_add(delta[i])); + if self + .air + .contains(&world.block(neighbor).map_err(FeatureError::World)?) + { + exposed = true; + break; + } + } + if exposed { + continue; + } + } + world + .set_block(position, *state, 2) + .map_err(FeatureError::World)?; + break; + } + } + Ok(true) + } +} diff --git a/crates/horizon-world/src/worldgen/placement.rs b/crates/horizon-world/src/worldgen/placement.rs new file mode 100644 index 000000000..0c4ed8223 --- /dev/null +++ b/crates/horizon-world/src/worldgen/placement.rs @@ -0,0 +1,505 @@ +//! Placement modifiers that depend on random state and generation bounds. +//! Block-query modifiers and actual configured features remain separate work. +mod chain; +mod layer; +use super::block_predicate::{BlockPredicate, PredicateBlockResolver}; +use super::{ + DecodeError, Object, anchor::WorldGenerationContext, biome_temperature::biome_info_noise, + density::identifier, double, height_provider::HeightProvider, int_range, integer, number_text, + optional, required, value_provider::IntProvider, +}; +use crate::heightmap::HeightmapType; +pub use chain::{FeaturePlacementError, FeaturePlacer}; +use horizon_core::random::{InvalidBound, RandomSource}; +use serde_json::value::RawValue; +mod context; +pub use context::{LayerBlock, PlacementContext, PlacementQueryError}; + +#[derive(Clone, Debug)] +pub enum PlacementModifier { + Biome, + BlockPredicate(BlockPredicate), + EnvironmentScan { + upwards: bool, + target: BlockPredicate, + allowed: BlockPredicate, + max_steps: i32, + }, + Heightmap(HeightmapType), + SurfaceRelative { + heightmap: HeightmapType, + min: i32, + max: i32, + }, + SurfaceWaterDepth(i32), + Count(IntProvider), + CountOnEveryLayer(IntProvider), + NoiseBasedCount { + ratio: i32, + factor: f64, + offset: f64, + }, + NoiseThresholdCount { + level: f64, + below: i32, + above: i32, + }, + InSquare, + Cuboid { + xz_size: IntProvider, + y_size: IntProvider, + include_edges: bool, + include_interior: bool, + }, + Offset([IntProvider; 3]), + HeightRange(HeightProvider), + Rarity(i32), + RandomChance(f32), + Fixed(Vec<[i32; 3]>), + RandomlySelected(Vec), +} +#[derive(Debug)] +pub enum PlacementError { + Random(InvalidBound), + World(PlacementQueryError), + Output(E), + WorkLimit, +} +impl std::fmt::Display for PlacementError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Random(e) => e.fmt(f), + Self::World(e) => e.fmt(f), + Self::Output(e) => e.fmt(f), + Self::WorkLimit => f.write_str("placement work limit exceeded"), + } + } +} +impl std::error::Error for PlacementError {} +impl From for PlacementError { + fn from(value: InvalidBound) -> Self { + Self::Random(value) + } +} +impl From for PlacementError { + fn from(value: PlacementQueryError) -> Self { + Self::World(value) + } +} +impl PlacementModifier { + pub fn from_json(json: &str) -> Result { + Self::decode(json, 0, &mut 65536) + } + pub(crate) fn decode( + json: &str, + depth: usize, + remaining: &mut usize, + ) -> Result { + Self::decode_with_blocks(json, depth, remaining, None) + } + pub fn from_json_with_blocks( + json: &str, + blocks: &impl PredicateBlockResolver, + ) -> Result { + Self::decode_with_blocks(json, 0, &mut 65536, Some(blocks)) + } + pub(crate) fn decode_with_blocks( + json: &str, + depth: usize, + remaining: &mut usize, + blocks: Option<&dyn PredicateBlockResolver>, + ) -> Result { + if depth > 256 || *remaining == 0 { + return Err(DecodeError::Field("placement depth or node count")); + } + *remaining -= 1; + let object: Object = serde_json::from_str(json)?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + let provider = |name, min, max| { + let value = IntProvider::from_json(required(&object, name)?.get())?; + let bounds = value.bounds(); + if bounds[0] < min || bounds[1] > max { + return Err(DecodeError::Field("placement provider bounds")); + } + Ok(value) + }; + let heightmap = || { + let name: String = serde_json::from_str(required(&object, "heightmap")?.get())?; + HeightmapType::ALL + .into_iter() + .find(|kind| kind.name() == name) + .ok_or(DecodeError::Field("heightmap")) + }; + match kind.as_str() { + "minecraft:biome" => Ok(Self::Biome), + "minecraft:block_predicate_filter" => { + Ok(Self::BlockPredicate(BlockPredicate::decode_with_blocks( + required(&object, "predicate")?.get(), + depth + 1, + remaining, + blocks, + )?)) + } + "minecraft:environment_scan" => { + let direction: String = + serde_json::from_str(required(&object, "direction_of_search")?.get())?; + let upwards = match direction.as_str() { + "up" => true, + "down" => false, + _ => return Err(DecodeError::Field("scan direction")), + }; + Ok(Self::EnvironmentScan { + upwards, + target: BlockPredicate::decode_with_blocks( + required(&object, "target_condition")?.get(), + depth + 1, + remaining, + blocks, + )?, + allowed: optional(&object, "allowed_search_condition") + .map(|v| { + BlockPredicate::decode_with_blocks( + v.get(), + depth + 1, + remaining, + blocks, + ) + }) + .transpose()? + .unwrap_or(BlockPredicate::True), + max_steps: int_range(required(&object, "max_steps")?, "scan steps", 1, 32)?, + }) + } + "minecraft:heightmap" => Ok(Self::Heightmap(heightmap()?)), + "minecraft:surface_relative_threshold_filter" => Ok(Self::SurfaceRelative { + heightmap: heightmap()?, + min: optional(&object, "min_inclusive") + .map(integer) + .transpose()? + .unwrap_or(i32::MIN), + max: optional(&object, "max_inclusive") + .map(integer) + .transpose()? + .unwrap_or(i32::MAX), + }), + "minecraft:surface_water_depth_filter" => Ok(Self::SurfaceWaterDepth(integer( + required(&object, "max_water_depth")?, + )?)), + "minecraft:noise_based_count" => Ok(Self::NoiseBasedCount { + ratio: integer(required(&object, "noise_to_count_ratio")?)?, + factor: double(required(&object, "noise_factor")?)?, + offset: optional(&object, "noise_offset") + .map(double) + .transpose()? + .unwrap_or(0.), + }), + "minecraft:noise_threshold_count" => Ok(Self::NoiseThresholdCount { + level: double(required(&object, "noise_level")?)?, + below: integer(required(&object, "below_noise")?)?, + above: integer(required(&object, "above_noise")?)?, + }), + "minecraft:count_on_every_layer" => { + Ok(Self::CountOnEveryLayer(provider("count", 0, 256)?)) + } + "minecraft:count" => Ok(Self::Count(provider("count", 0, 4096)?)), + "minecraft:in_square" => Ok(Self::InSquare), + "minecraft:cuboid" => Ok(Self::Cuboid { + xz_size: provider("xz_size", 1, 16)?, + y_size: provider("y_size", 1, 16)?, + include_edges: optional(&object, "include_edges") + .map(|raw| serde_json::from_str(raw.get())) + .transpose()? + .unwrap_or(true), + include_interior: optional(&object, "include_interior") + .map(|raw| serde_json::from_str(raw.get())) + .transpose()? + .unwrap_or(true), + }), + "minecraft:offset" => Ok(Self::Offset([ + provider("x", -16, 16)?, + provider("y", -16, 16)?, + provider("z", -16, 16)?, + ])), + "minecraft:height_range" => Ok(Self::HeightRange(HeightProvider::from_json( + required(&object, "height")?.get(), + )?)), + "minecraft:rarity_filter" => Ok(Self::Rarity(int_range( + required(&object, "chance")?, + "chance", + 1, + i32::MAX, + )?)), + "minecraft:random_chance" => { + let chance: f32 = number_text(required(&object, "chance")?)? + .parse() + .map_err(|_| DecodeError::Field("chance"))?; + if !(0. ..=1.).contains(&chance) || chance.is_sign_negative() { + return Err(DecodeError::Field("chance")); + } + Ok(Self::RandomChance(chance)) + } + "minecraft:fixed_placement" => { + let values: Vec> = + serde_json::from_str(required(&object, "positions")?.get())?; + if values.len() > 8192 { + return Err(DecodeError::Field("fixed positions")); + } + let mut positions = Vec::with_capacity(values.len()); + for raw in values { + let coords: Vec> = serde_json::from_str(raw.get())?; + if coords.len() != 3 { + return Err(DecodeError::Field("block position")); + } + positions.push([ + integer(&coords[0])?, + integer(&coords[1])?, + integer(&coords[2])?, + ]); + } + Ok(Self::Fixed(positions)) + } + "minecraft:randomly_selected" => { + let values: Vec> = + serde_json::from_str(required(&object, "placements")?.get())?; + if values.is_empty() || values.len() > 8192 { + return Err(DecodeError::Field("selected placements")); + } + Ok(Self::RandomlySelected( + values + .iter() + .map(|v| Self::decode_with_blocks(v.get(), depth + 1, remaining, blocks)) + .collect::>()?, + )) + } + _ => Err(DecodeError::Field("placement modifier type")), + } + } + /// Return the count for repeating modifiers without allocating or emitting + /// positions. Sampling still consumes the count provider's random draws. + pub fn repetitions( + &self, + random: &mut impl RandomSource, + position: [i32; 3], + ) -> Result, InvalidBound> { + let [x, _, z] = position; + Ok(match self { + Self::Count(provider) => Some(provider.sample(random)?), + Self::NoiseBasedCount { + ratio, + factor, + offset, + } => { + let noise = f64::from(biome_info_noise( + f64::from(x) / factor, + f64::from(z) / factor, + )); + Some(((noise + offset) * f64::from(*ratio)).ceil() as i32) + } + Self::NoiseThresholdCount { + level, + below, + above, + } => { + let noise = f64::from(biome_info_noise(f64::from(x) / 200., f64::from(z) / 200.)); + Some(if noise < *level { *below } else { *above }) + } + _ => None, + }) + } + /// Emit positions in native callback order. The callback shares the random + /// stream; failures retain prior emissions and consumed draws. + pub fn modify( + &self, + mut context: WorldGenerationContext, + random: &mut R, + position: [i32; 3], + emit: impl FnMut(&mut R, [i32; 3]) -> Result<(), E>, + ) -> Result<(), PlacementError> { + self.modify_in(&mut context, random, position, emit) + } + pub fn modify_in( + &self, + context: &mut impl PlacementContext, + random: &mut R, + position: [i32; 3], + mut emit: impl FnMut(&mut R, [i32; 3]) -> Result<(), E>, + ) -> Result<(), PlacementError> { + self.modify_inner(context, random, position, &mut emit, &mut 65536) + } + fn modify_inner( + &self, + context: &mut impl PlacementContext, + random: &mut R, + position: [i32; 3], + emit: &mut impl FnMut(&mut R, [i32; 3]) -> Result<(), E>, + remaining: &mut usize, + ) -> Result<(), PlacementError> { + if *remaining == 0 { + return Err(PlacementError::WorkLimit); + } + *remaining -= 1; + let [x, y, z] = position; + match self { + Self::Biome => { + let feature = context + .top_feature() + .ok_or(PlacementQueryError::Unavailable)?; + if context.biome_allows_feature(position, feature)? { + emit(random, position).map_err(PlacementError::Output)?; + } + } + Self::BlockPredicate(predicate) => { + if predicate.test_inner(context, position, 0, remaining)? { + emit(random, position).map_err(PlacementError::Output)?; + } + } + Self::EnvironmentScan { + upwards, + target, + allowed, + max_steps, + } => { + let mut position = position; + if !allowed.test_inner(context, position, 0, remaining)? { + return Ok(()); + } + for _ in 0..*max_steps { + if target.test_inner(context, position, 0, remaining)? { + return emit(random, position).map_err(PlacementError::Output); + } + position[1] = position[1].wrapping_add(if *upwards { 1 } else { -1 }); + if context.outside_build_height(position[1])? { + return Ok(()); + } + if !allowed.test_inner(context, position, 0, remaining)? { + break; + } + } + if target.test_inner(context, position, 0, remaining)? { + emit(random, position).map_err(PlacementError::Output)?; + } + } + Self::CountOnEveryLayer(count) => { + layer::modify(count, context, random, position, emit, remaining)? + } + Self::Heightmap(kind) => { + let height = context.height(*kind, x, z)?; + if height > context.min_y()? { + emit(random, [x, height, z]).map_err(PlacementError::Output)?; + } + } + Self::SurfaceRelative { + heightmap, + min, + max, + } => { + let height = i64::from(context.height(*heightmap, x, z)?); + if height + i64::from(*min) <= i64::from(y) + && i64::from(y) <= height + i64::from(*max) + { + emit(random, position).map_err(PlacementError::Output)?; + } + } + Self::SurfaceWaterDepth(max) => { + let floor = context.height(HeightmapType::OceanFloor, x, z)?; + let surface = context.height(HeightmapType::WorldSurface, x, z)?; + if surface.wrapping_sub(floor) <= *max { + emit(random, position).map_err(PlacementError::Output)?; + } + } + Self::Count(_) | Self::NoiseBasedCount { .. } | Self::NoiseThresholdCount { .. } => { + let count = self + .repetitions(random, position)? + .expect("repeating modifier"); + if count > 4096 { + return Err(PlacementError::WorkLimit); + } + for _ in 0..count { + emit(random, position).map_err(PlacementError::Output)?; + } + } + Self::Cuboid { + xz_size, + y_size, + include_edges, + include_interior, + } => { + let ny = y_size.sample(random)?; + let nx = xz_size.sample(random)?; + let nz = xz_size.sample(random)?; + if nx < 0 || ny < 0 || nz < 0 { + return Ok(()); + } + for dx in 0..=nx { + for dy in 0..=ny { + for dz in 0..=nz { + if *remaining == 0 { + return Err(PlacementError::WorkLimit); + } + *remaining -= 1; + let bx = dx == 0 || dx == nx; + let by = dy == 0 || dy == ny; + let bz = dz == 0 || dz == nz; + if !include_edges && (u8::from(bx) + u8::from(by) + u8::from(bz)) >= 2 { + continue; + } + if !include_interior && !(bx || by || bz) { + continue; + } + emit( + random, + [x.wrapping_add(dx), y.wrapping_add(dy), z.wrapping_add(dz)], + ) + .map_err(PlacementError::Output)?; + } + } + } + } + Self::InSquare => { + let x = x.wrapping_add(random.next_int_bound(16)?); + let z = z.wrapping_add(random.next_int_bound(16)?); + emit(random, [x, y, z]).map_err(PlacementError::Output)?; + } + Self::Offset(offsets) => { + let x = x.wrapping_add(offsets[0].sample(random)?); + let y = y.wrapping_add(offsets[1].sample(random)?); + let z = z.wrapping_add(offsets[2].sample(random)?); + emit(random, [x, y, z]).map_err(PlacementError::Output)?; + } + Self::HeightRange(height) => { + let y = height.sample(random, context.generation())?; + emit(random, [x, y, z]).map_err(PlacementError::Output)?; + } + Self::Rarity(chance) => { + if random.next_float() < 1. / *chance as f32 { + emit(random, position).map_err(PlacementError::Output)?; + } + } + Self::RandomChance(chance) => { + if random.next_float() < *chance { + emit(random, position).map_err(PlacementError::Output)?; + } + } + Self::Fixed(positions) => { + if positions.len() > 8192 { + return Err(PlacementError::WorkLimit); + } + for p in positions { + if p[0] >> 4 == x >> 4 && p[2] >> 4 == z >> 4 { + emit(random, *p).map_err(PlacementError::Output)?; + } + } + } + Self::RandomlySelected(placements) => { + if placements.len() > 8192 { + return Err(PlacementError::WorkLimit); + } + let index = random.next_int_bound(placements.len() as i32)? as usize; + placements[index].modify_inner(context, random, position, emit, remaining)?; + } + } + Ok(()) + } +} diff --git a/crates/horizon-world/src/worldgen/placement/chain.rs b/crates/horizon-world/src/worldgen/placement/chain.rs new file mode 100644 index 000000000..63d526256 --- /dev/null +++ b/crates/horizon-world/src/worldgen/placement/chain.rs @@ -0,0 +1,270 @@ +//! Ordered modifier-chain execution with reusable native-style pending buffers. +use super::{PlacementContext, PlacementError, PlacementModifier, PlacementQueryError}; +use crate::worldgen::anchor::WorldGenerationContext; +use crate::{heightmap::HeightmapType, worldgen::feature_sort::FeatureIdentity}; +use horizon_core::random::{InvalidBound, RandomSource}; +use std::cell::Cell; + +struct Queries<'a, C> { + world: &'a mut C, + top: Option, +} +impl PlacementContext for Queries<'_, C> { + fn block_survives( + &mut self, + state: crate::registry::BlockStateId, + position: [i32; 3], + ) -> Result { + self.world.block_survives(state, position) + } + fn face_sturdy( + &mut self, + position: [i32; 3], + direction: horizon_core::geometry::Direction, + ) -> Result { + self.world.face_sturdy(position, direction) + } + fn unobstructed_block(&mut self, position: [i32; 3]) -> Result { + self.world.unobstructed_block(position) + } + fn biome_identity( + &mut self, + position: [i32; 3], + ) -> Result { + self.world.biome_identity(position) + } + fn top_feature(&self) -> Option { + self.top + } + fn biome_allows_feature( + &mut self, + p: [i32; 3], + feature: FeatureIdentity, + ) -> Result { + self.world.biome_allows_feature(p, feature) + } + fn generation(&self) -> WorldGenerationContext { + self.world.generation() + } + fn predicate_generation(&mut self) -> Result { + self.world.predicate_generation() + } + fn block_state( + &mut self, + position: [i32; 3], + ) -> Result { + self.world.block_state(position) + } + fn block_matches_tag( + &mut self, + position: [i32; 3], + tag: &str, + ) -> Result { + self.world.block_matches_tag(position, tag) + } + fn min_y(&mut self) -> Result { + self.world.min_y() + } + fn max_y(&mut self) -> Result { + self.world.max_y() + } + fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result { + self.world.height(kind, x, z) + } + fn layer_block(&mut self, p: [i32; 3]) -> Result { + self.world.layer_block(p) + } + fn inside_build_height(&mut self, p: [i32; 3]) -> Result { + self.world.inside_build_height(p) + } + fn outside_build_height(&mut self, y: i32) -> Result { + self.world.outside_build_height(y) + } +} + +#[derive(Debug)] +pub enum FeaturePlacementError { + Random(InvalidBound), + World(PlacementQueryError), + Feature(E), + WorkLimit, + InvalidPendingIndex, +} +impl std::fmt::Display for FeaturePlacementError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Random(e) => e.fmt(f), + Self::World(e) => e.fmt(f), + Self::Feature(e) => e.fmt(f), + Self::WorkLimit => f.write_str("feature placement work limit exceeded"), + Self::InvalidPendingIndex => { + f.write_str("pending modifier index is outside the current chain") + } + } + } +} +impl std::error::Error for FeaturePlacementError {} + +/// Processes one modifier completely before running its descendants. Siblings +/// retain emitted order. The reusable buffers also retain partial state after +/// errors, like vanilla; a fresh placer starts without that state. +#[derive(Default, Debug)] +pub struct FeaturePlacer { + pending: Vec<([i32; 3], usize)>, + modified: Vec<[i32; 3]>, +} +impl FeaturePlacer { + pub fn new() -> Self { + Self::default() + } + pub fn place( + &mut self, + modifiers: &[PlacementModifier], + mut context: WorldGenerationContext, + random: &mut R, + origin: [i32; 3], + feature: impl FnMut(&mut R, [i32; 3]) -> Result, + ) -> Result> { + self.place_in(modifiers, &mut context, random, origin, feature) + } + pub fn place_in( + &mut self, + modifiers: &[PlacementModifier], + context: &mut impl PlacementContext, + random: &mut R, + origin: [i32; 3], + mut feature: impl FnMut(&mut R, [i32; 3]) -> Result, + ) -> Result> { + self.place_with_context(modifiers, context, random, origin, |_, random, position| { + feature(random, position) + }) + } + /// Shares the mutable world and random stream between modifier queries and + /// feature writes. Later siblings observe earlier feature mutations. + pub fn place_with_context( + &mut self, + modifiers: &[PlacementModifier], + context: &mut C, + random: &mut R, + origin: [i32; 3], + feature: impl FnMut(&mut C, &mut R, [i32; 3]) -> Result, + ) -> Result> { + self.place_with_budget( + modifiers, + context, + random, + origin, + &Cell::new(1 << 20), + feature, + ) + } + /// Set the root placed feature only for this invocation's modifier queries. + /// Nested feature callbacks receive the original world, so their own plain + /// placers do not inherit this root's biome-check context. + pub fn place_with_biome_check( + &mut self, + modifiers: &[PlacementModifier], + context: &mut C, + random: &mut R, + origin: [i32; 3], + top_feature: FeatureIdentity, + feature: impl FnMut(&mut C, &mut R, [i32; 3]) -> Result, + ) -> Result> { + self.place_control( + modifiers, + context, + random, + origin, + (&Cell::new(1 << 20), Some(top_feature)), + feature, + ) + } + pub(crate) fn place_with_budget( + &mut self, + modifiers: &[PlacementModifier], + context: &mut C, + random: &mut R, + origin: [i32; 3], + remaining: &Cell, + feature: impl FnMut(&mut C, &mut R, [i32; 3]) -> Result, + ) -> Result> { + self.place_control( + modifiers, + context, + random, + origin, + (remaining, None), + feature, + ) + } + fn place_control( + &mut self, + modifiers: &[PlacementModifier], + context: &mut C, + random: &mut R, + origin: [i32; 3], + control: (&Cell, Option), + mut feature: impl FnMut(&mut C, &mut R, [i32; 3]) -> Result, + ) -> Result> { + let (remaining, top) = control; + const LIMIT: usize = 1 << 20; + if modifiers.len() > 1024 || self.pending.len() >= LIMIT { + return Err(FeaturePlacementError::WorkLimit); + } + if modifiers.is_empty() { + return feature(context, random, origin).map_err(FeaturePlacementError::Feature); + } + self.pending.push((origin, 0)); + let mut any = false; + while let Some((position, index)) = self.pending.pop() { + if remaining.get() == 0 { + return Err(FeaturePlacementError::WorkLimit); + } + remaining.set(remaining.get() - 1); + let modifier = modifiers + .get(index) + .ok_or(FeaturePlacementError::InvalidPendingIndex)?; + modifier + .modify_in( + &mut Queries { + world: context, + top, + }, + random, + position, + |_, p| { + if self.modified.len() >= LIMIT { + return Err(()); + } + self.modified.push(p); + Ok(()) + }, + ) + .map_err(|e| match e { + PlacementError::Random(e) => FeaturePlacementError::Random(e), + PlacementError::World(e) => FeaturePlacementError::World(e), + PlacementError::Output(()) | PlacementError::WorkLimit => { + FeaturePlacementError::WorkLimit + } + })?; + let next = index + 1; + if next < modifiers.len() { + if self.pending.len() + self.modified.len() > LIMIT { + return Err(FeaturePlacementError::WorkLimit); + } + self.pending + .extend(self.modified.iter().rev().map(|p| (*p, next))); + } else { + for p in &self.modified { + if remaining.get() == 0 { + return Err(FeaturePlacementError::WorkLimit); + } + remaining.set(remaining.get() - 1); + any |= feature(context, random, *p).map_err(FeaturePlacementError::Feature)?; + } + } + self.modified.clear(); + } + Ok(any) + } +} diff --git a/crates/horizon-world/src/worldgen/placement/context.rs b/crates/horizon-world/src/worldgen/placement/context.rs new file mode 100644 index 000000000..695f0bde6 --- /dev/null +++ b/crates/horizon-world/src/worldgen/placement/context.rs @@ -0,0 +1,117 @@ +//! Query interface for placement against a generated world. +use crate::worldgen::feature_sort::FeatureIdentity; +use crate::{heightmap::HeightmapType, worldgen::anchor::WorldGenerationContext}; +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum PlacementQueryError { + Unavailable, + WorkLimit, + Failed(String), +} +impl std::fmt::Display for PlacementQueryError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::WorkLimit => f.write_str("predicate work limit exceeded"), + Self::Unavailable => f.write_str("placement world query is unavailable"), + Self::Failed(message) => f.write_str(message), + } + } +} +impl std::error::Error for PlacementQueryError {} +/// Classification for layered placement: air states and exact WATER/LAVA blocks +/// are empty; exact BEDROCK is excluded from ground; every other block is ground. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LayerBlock { + Empty, + Bedrock, + Ground, +} +pub trait PlacementContext { + /// Evaluate this candidate state's survival without placing it. + fn block_survives( + &mut self, + _state: crate::registry::BlockStateId, + _position: [i32; 3], + ) -> Result { + Err(PlacementQueryError::Unavailable) + } + /// Read the block state and evaluate FULL support on the requested face. + fn face_sturdy( + &mut self, + _position: [i32; 3], + _direction: horizon_core::geometry::Direction, + ) -> Result { + Err(PlacementQueryError::Unavailable) + } + /// Test entity obstruction of a unit-block shape with no excluded entity. + fn unobstructed_block(&mut self, _position: [i32; 3]) -> Result { + Err(PlacementQueryError::Unavailable) + } + fn biome_identity( + &mut self, + _position: [i32; 3], + ) -> Result { + Err(PlacementQueryError::Unavailable) + } + fn top_feature(&self) -> Option { + None + } + /// Resolve the biome at this position and test its generation settings for + /// the supplied placed feature. Registry equality/ownership belongs here. + fn biome_allows_feature( + &mut self, + _position: [i32; 3], + _feature: FeatureIdentity, + ) -> Result { + Err(PlacementQueryError::Unavailable) + } + fn block_state( + &mut self, + _position: [i32; 3], + ) -> Result { + Err(PlacementQueryError::Unavailable) + } + /// Read the state at the requested position and test its block-tag identity. + fn block_matches_tag( + &mut self, + _position: [i32; 3], + _tag: &str, + ) -> Result { + Err(PlacementQueryError::Unavailable) + } + fn max_y(&mut self) -> Result { + Err(PlacementQueryError::Unavailable) + } + fn inside_build_height(&mut self, position: [i32; 3]) -> Result { + Ok(position[1] >= self.min_y()? && position[1] <= self.max_y()?) + } + fn outside_build_height(&mut self, y: i32) -> Result { + Ok(y < self.min_y()? || y > self.max_y()?) + } + fn layer_block(&mut self, _position: [i32; 3]) -> Result { + Err(PlacementQueryError::Unavailable) + } + fn generation(&self) -> WorldGenerationContext; + /// Recreate the generation bounds for a block-predicate invocation. World + /// adapters may perform fallible level/generator queries here; ordinary + /// placement retains its already-created immutable generation context. + fn predicate_generation(&mut self) -> Result { + Ok(self.generation()) + } + /// World minimum, which can differ from the generator's minimum. + fn min_y(&mut self) -> Result; + fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result; +} +impl PlacementContext for WorldGenerationContext { + fn max_y(&mut self) -> Result { + Ok(self.min_y.wrapping_add(self.height).wrapping_sub(1)) + } + fn generation(&self) -> WorldGenerationContext { + *self + } + fn min_y(&mut self) -> Result { + Ok(self.min_y) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + Err(PlacementQueryError::Unavailable) + } +} diff --git a/crates/horizon-world/src/worldgen/placement/layer.rs b/crates/horizon-world/src/worldgen/placement/layer.rs new file mode 100644 index 000000000..ac794bc55 --- /dev/null +++ b/crates/horizon-world/src/worldgen/placement/layer.rs @@ -0,0 +1,68 @@ +//! Layer scanning and its interleaved count-provider sampling. +use super::{LayerBlock, PlacementContext, PlacementError}; +use crate::{heightmap::HeightmapType, worldgen::value_provider::IntProvider}; +use horizon_core::random::RandomSource; + +pub(super) fn modify( + count: &IntProvider, + context: &mut impl PlacementContext, + random: &mut R, + position: [i32; 3], + emit: &mut impl FnMut(&mut R, [i32; 3]) -> Result<(), E>, + remaining: &mut usize, +) -> Result<(), PlacementError> { + let mut layer = 0_i32; + loop { + let mut found = false; + let mut attempt = 0_i32; + loop { + take(remaining)?; + // Native samples on every loop condition, including the final check. + if attempt >= count.sample(random)? { + break; + } + let x = position[0].wrapping_add(random.next_int_bound(16)?); + let z = position[2].wrapping_add(random.next_int_bound(16)?); + let y = context.height(HeightmapType::MotionBlocking, x, z)?; + if let Some(y) = ground(context, [x, y, z], layer, remaining)? { + emit(random, [x, y, z]).map_err(PlacementError::Output)?; + found = true; + } + attempt = attempt.wrapping_add(1); + } + layer = layer.wrapping_add(1); + if !found { + return Ok(()); + } + } +} +fn ground( + context: &mut impl PlacementContext, + position: [i32; 3], + layer: i32, + remaining: &mut usize, +) -> Result, PlacementError> { + let [x, mut y, z] = position; + let mut above = context.layer_block(position)?; + let mut found = 0_i32; + while y >= context.min_y()?.wrapping_add(1) { + take(remaining)?; + let below = context.layer_block([x, y.wrapping_sub(1), z])?; + if below == LayerBlock::Ground && above == LayerBlock::Empty { + if found == layer { + return Ok((y != i32::MAX).then_some(y)); + } + found = found.wrapping_add(1); + } + above = below; + y = y.wrapping_sub(1); + } + Ok(None) +} +fn take(remaining: &mut usize) -> Result<(), PlacementError> { + if *remaining == 0 { + return Err(PlacementError::WorkLimit); + } + *remaining -= 1; + Ok(()) +} diff --git a/crates/horizon-world/src/worldgen/router.rs b/crates/horizon-world/src/worldgen/router.rs new file mode 100644 index 000000000..aed50353d --- /dev/null +++ b/crates/horizon-world/src/worldgen/router.rs @@ -0,0 +1,168 @@ +//! The eight terrain-router fields used by Java Edition 26.3. +use super::{DecodeError, Object, climate::ClimateSampler, density::DensityRegistry, required}; +use horizon_core::density::{ + DensitySampler, + graph::{CompileError, DensityCompiler, FunctionId}, +}; +use std::sync::Arc; + +/// Declaration and compilation order: the six climate fields, surface, density. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(usize)] +pub enum RouterField { + Temperature, + Vegetation, + Continents, + Erosion, + Depth, + Ridges, + ChunkSurfaceLevel, + FinalDensity, +} +impl RouterField { + pub const ALL: [Self; 8] = [ + Self::Temperature, + Self::Vegetation, + Self::Continents, + Self::Erosion, + Self::Depth, + Self::Ridges, + Self::ChunkSurfaceLevel, + Self::FinalDensity, + ]; + pub const fn name(self) -> &'static str { + match self { + Self::Temperature => "temperature", + Self::Vegetation => "vegetation", + Self::Continents => "continents", + Self::Erosion => "erosion", + Self::Depth => "depth", + Self::Ridges => "ridges", + Self::ChunkSurfaceLevel => "chunk_surface_level", + Self::FinalDensity => "final_density", + } + } +} + +/// Root IDs belong to the registry graph used to decode this router. +#[derive(Clone, Copy, Debug)] +pub struct NoiseRouter { + functions: [FunctionId; 8], +} +impl NoiseRouter { + /// Decode the router object itself. Noise settings, aquifer and material + /// configuration are separate codecs and are not parsed by this method. + /// Missing/null fields or any invalid root leave the registry unchanged. + pub fn from_json(json: &str, registry: &mut DensityRegistry) -> Result { + let object: Object = serde_json::from_str(json)?; + let inputs = RouterField::ALL + .iter() + .map(|field| required(&object, field.name()).map(|raw| raw.get())) + .collect::, _>>()?; + let functions = registry + .decode_functions(&inputs)? + .try_into() + .map_err(|_| DecodeError::Field("router field count"))?; + Ok(Self { functions }) + } + pub fn function(self, field: RouterField) -> FunctionId { + self.functions[field as usize] + } + /// One compiler owns the cache namespace for every router field. Existing + /// compiler samplers and cache IDs are reused rather than reset per root. + pub fn compile(self, compiler: &mut DensityCompiler) -> Result { + let samplers = self + .functions + .iter() + .map(|id| compiler.get_sampler(*id)) + .collect::, _>>()? + .try_into() + .expect("one sampler for each of eight router fields"); + Ok(RouterSamplers { samplers }) + } + /// Compile only the six climate roots, in vanilla's sampler-binding order. + pub fn compile_climate( + self, + compiler: &mut DensityCompiler, + ) -> Result { + let samplers = self.functions[..6] + .iter() + .map(|id| compiler.get_sampler(*id)) + .collect::, _>>()? + .try_into() + .expect("one sampler for each of six climate fields"); + Ok(ClimateSampler::new(samplers)) + } +} +#[derive(Debug)] +pub struct RouterSamplers { + samplers: [Arc; 8], +} +impl RouterSamplers { + pub fn get(&self, field: RouterField) -> &Arc { + &self.samplers[field as usize] + } + pub fn climate_sampler(&self) -> ClimateSampler { + ClimateSampler::new(std::array::from_fn(|i| self.samplers[i].clone())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::density::SamplerContext; + use std::collections::BTreeMap; + + #[test] + fn roots_share_holder_cache_and_failed_router_leaves_graph_unchanged() { + let mut registry = DensityRegistry::from_json( + &BTreeMap::new(), + &BTreeMap::from([( + "minecraft:shared".into(), + r#"{"type":"cache","input":{"type":"gradient","axis":"x","from_coordinate":0,"to_coordinate":16,"from_value":-1,"to_value":1}}"#.into(), + )]), + ) + .unwrap(); + let object: BTreeMap<_, _> = RouterField::ALL + .iter() + .map(|field| (field.name(), "minecraft:shared")) + .collect(); + let json = serde_json::to_string(&object).unwrap(); + let expected = registry + .graph() + .clone() + .insert(horizon_core::density::graph::GraphNode::Constant(123.0)) + .unwrap(); + let invalid = json + .replace( + "\"temperature\":\"minecraft:shared\"", + "\"temperature\":123", + ) + .replace( + "\"final_density\":\"minecraft:shared\"", + "\"final_density\":{\"type\":\"missing\"}", + ); + assert!(NoiseRouter::from_json(&invalid, &mut registry).is_err()); + assert_eq!(registry.decode_functions(&["123"]).unwrap()[0], expected); + let router = NoiseRouter::from_json(&json, &mut registry).unwrap(); + for field in RouterField::ALL { + assert_eq!( + router.function(field), + registry.reference("minecraft:shared").unwrap() + ); + } + let mut compiler = DensityCompiler::new_seeded(registry.into_graph(), 0, false); + let samplers = router.compile(&mut compiler).unwrap(); + assert_eq!(compiler.cache_count(), 1); + let mut context = SamplerContext::cached(); + for field in RouterField::ALL { + assert_eq!( + samplers + .get(field) + .sample_value(&mut context, [4, 99, -32]) + .unwrap(), + -0.5 + ); + } + } +} diff --git a/crates/horizon-world/src/worldgen/rule_test.rs b/crates/horizon-world/src/worldgen/rule_test.rs new file mode 100644 index 000000000..d9f836961 --- /dev/null +++ b/crates/horizon-world/src/worldgen/rule_test.rs @@ -0,0 +1,133 @@ +//! Registry-bound replacement predicates with ordered short-circuit evaluation. +use super::{ + DecodeError, Object, block_feature::FeatureBlockBindings, density::identifier, integer, + number_text, required, +}; +use crate::registry::BlockStateId; +use horizon_core::random::RandomSource; +use serde_json::value::RawValue; +use std::{collections::BTreeSet, sync::Arc}; + +#[derive(Clone, Debug)] +pub struct RuleTest(Node); +#[derive(Clone, Debug)] +enum Node { + True, + Not(Box), + All(Vec), + Any(Vec), + States(Arc>), + State(BlockStateId), + RandomStates(Arc>, f32), + RandomState(BlockStateId, f32), + Height(i32, i32), +} +impl RuleTest { + pub fn from_json(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result { + Self::decode(json, bindings, 0, &mut 65536) + } + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + ) -> Result { + if depth > 128 || *remaining == 0 { + return Err(DecodeError::Field("replacement rule depth or node count")); + } + *remaining -= 1; + let object: Object = serde_json::from_str(json)?; + let name = |field| -> Result { + identifier(&serde_json::from_str::( + required(&object, field)?.get(), + )?) + }; + let state = || { + bindings + .codec + .decode(required(&object, "block_state")?.get(), false) + .map_err(|e| DecodeError::Registry(e.to_string())) + }; + let block = || { + let name = name("block")?; + bindings + .blocks + .get(&name) + .cloned() + .ok_or_else(|| DecodeError::Registry(format!("unknown block {name}"))) + }; + // These native codecs use unrestricted FLOAT, including out-of-range + // probabilities. Matching the state still consumes a draw at zero/one. + let probability = || { + number_text(required(&object, "probability")?)? + .parse::() + .map_err(|_| DecodeError::Field("probability")) + }; + let node = match name("predicate_type")?.as_str() { + "minecraft:always_true" => Node::True, + "minecraft:block_match" => Node::States(block()?), + "minecraft:blockstate_match" => Node::State(state()?), + "minecraft:tag_match" => Node::States( + bindings + .tags + .get(&super::tags::identifier(&serde_json::from_str::( + required(&object, "tag")?.get(), + )?)?) + .cloned() + .unwrap_or_default(), + ), + "minecraft:random_block_match" => Node::RandomStates(block()?, probability()?), + "minecraft:random_blockstate_match" => Node::RandomState(state()?, probability()?), + "minecraft:height_match" => Node::Height( + integer(required(&object, "min_inclusive")?)?, + integer(required(&object, "max_inclusive")?)?, + ), + "minecraft:not" => Node::Not(Box::new(Self::decode( + required(&object, "rule")?.get(), + bindings, + depth + 1, + remaining, + )?)), + kind @ ("minecraft:all_of" | "minecraft:any_of") => { + let values: Vec> = + serde_json::from_str(required(&object, "rules")?.get())?; + if values.len() > 8192 { + return Err(DecodeError::Field("replacement rule list")); + } + let values = values + .iter() + .map(|v| Self::decode(v.get(), bindings, depth + 1, remaining)) + .collect::>()?; + if kind == "minecraft:all_of" { + Node::All(values) + } else { + Node::Any(values) + } + } + _ => return Err(DecodeError::Field("replacement rule type")), + }; + Ok(Self(node)) + } + pub fn test( + &self, + state: BlockStateId, + position: [i32; 3], + random: &mut impl RandomSource, + ) -> bool { + match &self.0 { + Node::True => true, + Node::Not(rule) => !rule.test(state, position, random), + Node::All(rules) => rules.iter().all(|rule| rule.test(state, position, random)), + Node::Any(rules) => rules.iter().any(|rule| rule.test(state, position, random)), + Node::States(states) => states.contains(&state), + Node::State(expected) => state == *expected, + Node::RandomStates(states, probability) => { + states.contains(&state) && random.next_float() < *probability + } + Node::RandomState(expected, probability) => { + state == *expected && random.next_float() < *probability + } + Node::Height(min, max) => *min <= position[1] && position[1] <= *max, + } + } +} diff --git a/crates/horizon-world/src/worldgen/settings.rs b/crates/horizon-world/src/worldgen/settings.rs new file mode 100644 index 000000000..770f12bd6 --- /dev/null +++ b/crates/horizon-world/src/worldgen/settings.rs @@ -0,0 +1,45 @@ +//! Vertical terrain bounds used by Java Edition 26.3. +use super::{DecodeError, Object, int_range, required}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct NoiseSettings { + pub min_y: i32, + pub height: i32, +} +impl NoiseSettings { + /// The record constructor itself does not check bounds or alignment. + pub const fn new(min_y: i32, height: i32) -> Self { + Self { min_y, height } + } + /// Vanilla's create helper checks the wrapped upper bound, then height + /// alignment, then minimum alignment. JSON adds stricter field bounds. + pub fn create(min_y: i32, height: i32) -> Result { + if min_y.wrapping_add(height) > 2032 { + return Err(DecodeError::Field("noise upper bound")); + } + if height % 16 != 0 { + return Err(DecodeError::Field("noise height alignment")); + } + if min_y % 16 != 0 { + return Err(DecodeError::Field("noise minimum alignment")); + } + Ok(Self::new(min_y, height)) + } + pub fn from_json(json: &str) -> Result { + let object: Object = serde_json::from_str(json)?; + let min_y = int_range(required(&object, "min_y")?, "noise minimum", -2032, 2031)?; + let height = int_range(required(&object, "height")?, "noise height", 0, 4064)?; + Self::create(min_y, height) + } + /// Accessor maximum is minimum + height - 1 with Java integer wrapping. + /// Disjoint ranges can produce negative heights; vanilla does not clamp + /// those to zero or reapply codec alignment constraints to the result. + pub fn clamp_to_height(self, accessor_minimum: i32, accessor_height: i32) -> Self { + let min_y = self.min_y.max(accessor_minimum); + let upper = self + .min_y + .wrapping_add(self.height) + .min(accessor_minimum.wrapping_add(accessor_height)); + Self::new(min_y, upper.wrapping_sub(min_y)) + } +} diff --git a/crates/horizon-world/src/worldgen/state_provider.rs b/crates/horizon-world/src/worldgen/state_provider.rs new file mode 100644 index 000000000..be1901a44 --- /dev/null +++ b/crates/horizon-world/src/worldgen/state_provider.rs @@ -0,0 +1,601 @@ +//! Initial block-state providers, bound to immutable block and tag identities. +mod catalog; +mod noise; +pub use catalog::StateProviderCatalog; +mod properties; +use super::{ + DecodeError, Object, + block_predicate::{BlockPredicate, PredicateBlockResolver}, + density::identifier, + feature::FeatureWorld, + optional, + placement::{PlacementContext, PlacementQueryError}, + required, + value_provider::IntProvider, + weighted::WeightedList, +}; +use crate::block_properties::{BlockPropertiesRegistry, BlockProperty, BoundBlockProperty}; +use crate::registry::{BlockRegistry, BlockStateId, BlockStateJsonCodec}; +use horizon_core::random::{InvalidBound, RandomSource}; +use noise::NoiseProvider; +use properties::StateProperties; +use serde_json::value::RawValue; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::{Arc, OnceLock}, +}; +const DIRECTIONS: [&str; 6] = ["down", "up", "north", "south", "west", "east"]; +type Rotations = Arc>; + +pub struct StateProviderBindings<'r> { + physical_properties: Option<[BoundBlockProperty; 4]>, + biomes: Option>, + fluids: super::fluid_predicate::FluidPredicateBindings, + codec: BlockStateJsonCodec<'r>, + blocks: BTreeMap, + tags: BTreeMap>>, + registry: &'r BlockRegistry, + rotations: OnceLock>, + integers: BTreeSet<(String, String)>, + properties: OnceLock, String>>, + predicate_states: OnceLock>>>, +} +impl<'r> StateProviderBindings<'r> { + pub fn with_block_properties( + mut self, + properties: &BlockPropertiesRegistry<'r>, + ) -> Result { + if !std::ptr::eq(self.registry, properties.registry()) { + return Err(DecodeError::Field( + "block properties use a different registry", + )); + } + self.physical_properties = Some([ + properties.bind(BlockProperty::Solid), + properties.bind(BlockProperty::Replaceable), + properties.bind(BlockProperty::Liquid), + properties.bind(BlockProperty::SolidRender), + ]); + Ok(self) + } + pub fn with_biomes( + mut self, + biomes: Arc, + ) -> Self { + self.biomes = Some(biomes); + self + } + + pub fn with_fluid_tags( + mut self, + tags: &BTreeMap>, + ) -> Result { + self.fluids = self.fluids.with_resolved_tags(tags)?; + Ok(self) + } + /// Resolved tag lists preserve holder order, including an empty named set. + pub fn new( + registry: &'r BlockRegistry, + integers: BTreeSet<(String, String)>, + tags: &BTreeMap>, + ) -> Result { + let codec = BlockStateJsonCodec::new(registry, integers.clone()) + .map_err(|e| DecodeError::Registry(e.to_string()))?; + let mut blocks = BTreeMap::new(); + for index in 0..registry.len() { + let name = ®istry.state(BlockStateId(index as u32)).unwrap().name; + blocks + .entry(name.clone()) + .or_insert_with(|| registry.default_state(name).unwrap()); + } + let mut bound_tags = BTreeMap::new(); + for (name, entries) in tags { + if entries.len() > 8192 { + return Err(DecodeError::Field("provider tag size")); + } + let values = entries + .iter() + .map(|name| { + blocks + .get(&identifier(name)?) + .copied() + .ok_or_else(|| DecodeError::Registry(format!("unknown block {name}"))) + }) + .collect::, _>>()?; + if bound_tags + .insert(super::tags::identifier(name)?, Arc::new(values)) + .is_some() + { + return Err(DecodeError::Field("duplicate provider block tag")); + } + } + Ok(Self { + codec, + biomes: None, + physical_properties: None, + fluids: super::fluid_predicate::FluidPredicateBindings::new(registry)?, + blocks, + tags: bound_tags, + registry, + rotations: OnceLock::new(), + integers, + properties: OnceLock::new(), + predicate_states: OnceLock::new(), + }) + } + fn state(&self, json: &str, full: bool) -> Result { + self.codec + .decode(json, full) + .map_err(|e| DecodeError::Registry(e.to_string())) + } + fn rotations(&self) -> Result { + self.rotations + .get_or_init(|| rotation_table(self.registry)) + .clone() + .map_err(DecodeError::Registry) + } + fn properties(&self) -> Result, DecodeError> { + self.properties + .get_or_init(|| StateProperties::build(self.registry, &self.integers).map(Arc::new)) + .clone() + .map_err(DecodeError::Registry) + } + fn block_set(&self, raw: &RawValue) -> Result>, DecodeError> { + if let Ok(name) = serde_json::from_str::(raw.get()) { + if let Some(tag) = name.strip_prefix('#') { + return self + .tags + .get(&super::tags::identifier(tag)?) + .cloned() + .ok_or_else(|| { + DecodeError::Registry(format!("unknown provider block tag {tag}")) + }); + } + let state = self + .blocks + .get(&identifier(&name)?) + .copied() + .ok_or_else(|| DecodeError::Registry(format!("unknown block {name}")))?; + return Ok(Arc::new(vec![state])); + } + let names: Vec = serde_json::from_str(raw.get())?; + if names.len() > 8192 { + return Err(DecodeError::Field("provider block list size")); + } + Ok(Arc::new( + names + .iter() + .map(|name| { + self.blocks + .get(&identifier(name)?) + .copied() + .ok_or_else(|| DecodeError::Registry(format!("unknown block {name}"))) + }) + .collect::, _>>()?, + )) + } +} +impl PredicateBlockResolver for StateProviderBindings<'_> { + fn predicate_state(&self, json: &str) -> Result { + self.state(json, false) + } + fn predicate_property( + &self, + property: BlockProperty, + ) -> Result { + let values = self + .physical_properties + .as_ref() + .ok_or(DecodeError::Field("predicate block property registry"))?; + Ok(values[match property { + BlockProperty::Solid => 0, + BlockProperty::Replaceable => 1, + BlockProperty::Liquid => 2, + BlockProperty::SolidRender => 3, + }] + .clone()) + } + fn predicate_biome_set( + &self, + json: &str, + ) -> Result>, DecodeError> { + self.biomes + .as_ref() + .ok_or(DecodeError::Field("predicate biome registry"))? + .resolve(json) + } + + fn predicate_fluid_set( + &self, + json: &str, + ) -> Result { + self.fluids.resolve(json) + } + fn predicate_block_set(&self, json: &str) -> Result>, DecodeError> { + let raw: Box = serde_json::from_str(json)?; + let defaults = self.block_set(&raw)?; + let states = self.predicate_states.get_or_init(|| { + let mut states = BTreeMap::>::new(); + for id in 0..self.registry.len() { + let id = BlockStateId(id as u32); + let default = self.blocks[&self.registry.state(id).unwrap().name]; + states.entry(default).or_default().insert(id); + } + states + .into_iter() + .map(|(id, values)| (id, Arc::new(values))) + .collect() + }); + if defaults.len() == 1 { + return Ok(states[&defaults[0]].clone()); + } + Ok(Arc::new( + defaults + .iter() + .flat_map(|id| states[id].iter().copied()) + .collect(), + )) + } +} +#[derive(Clone, Debug)] +pub struct BlockStateProvider(Node); +#[derive(Clone, Debug)] +enum Node { + RuleBased { + fallback: Option>, + rules: Vec<(BlockPredicate, BlockStateProvider)>, + }, + Noise(Box), + Simple(BlockStateId), + Weighted(WeightedList), + RandomBlock(Arc>), + Rotated { + source: Box, + direction: Option, + rotations: Rotations, + }, + CopyProperties(Box, Arc), + RandomizedInt { + source: Box, + property: String, + values: IntProvider, + properties: Arc, + }, +} +#[derive(Debug)] +pub enum StateProviderError { + Random(InvalidBound), + World(E), + Query(PlacementQueryError), + InvalidState, + InvalidPropertyValue, + EmptyNoiseSelection, +} +impl std::fmt::Display for StateProviderError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Random(e) => e.fmt(f), + Self::World(e) => e.fmt(f), + Self::Query(e) => e.fmt(f), + Self::InvalidState => f.write_str("unregistered provider source state"), + Self::InvalidPropertyValue => f.write_str("invalid randomized property value"), + Self::EmptyNoiseSelection => f.write_str("empty dual-noise state selection"), + } + } +} +impl std::error::Error for StateProviderError {} +impl From for StateProviderError { + fn from(e: InvalidBound) -> Self { + Self::Random(e) + } +} +impl BlockStateProvider { + /// Native DIRECT_CODEC is an exclusive choice: exactly one of a full state + /// object and a typed provider must decode. Compact state strings are not + /// direct providers; named provider holders are a separate registry layer. + pub fn from_json( + json: &str, + bindings: &StateProviderBindings<'_>, + ) -> Result { + Self::decode(json, bindings, 0, &mut 65536, None) + } + fn decode_holder( + json: &str, + bindings: &StateProviderBindings<'_>, + depth: usize, + remaining: &mut usize, + catalog: Option<&StateProviderCatalog>, + ) -> Result { + if depth > 128 || *remaining == 0 { + return Err(DecodeError::Field( + "state provider resource expansion limit", + )); + } + if let Ok(name) = serde_json::from_str::(json) { + let name = identifier(&name)?; + let resource = catalog + .and_then(|c| c.lookup(&name)) + .ok_or_else(|| DecodeError::Registry(format!("unknown state provider {name}")))?; + *remaining -= 1; + Self::decode(resource, bindings, depth + 1, remaining, catalog) + } else { + Self::decode(json, bindings, depth, remaining, catalog) + } + } + fn decode( + json: &str, + bindings: &StateProviderBindings<'_>, + depth: usize, + remaining: &mut usize, + catalog: Option<&StateProviderCatalog>, + ) -> Result { + if depth > 128 || *remaining == 0 { + return Err(DecodeError::Field("state provider depth")); + } + match ( + bindings.state(json, true), + Self::decode_typed(json, bindings, depth, remaining, catalog), + ) { + (Ok(state), Err(_)) => Ok(Self(Node::Simple(state))), + (Err(_), Ok(provider)) => Ok(provider), + _ => Err(DecodeError::Field("exclusive state or provider")), + } + } + pub fn from_typed_json( + json: &str, + bindings: &StateProviderBindings<'_>, + ) -> Result { + Self::decode_typed(json, bindings, 0, &mut 65536, None) + } + fn decode_typed( + json: &str, + bindings: &StateProviderBindings<'_>, + depth: usize, + remaining: &mut usize, + catalog: Option<&StateProviderCatalog>, + ) -> Result { + if depth > 128 || *remaining == 0 { + return Err(DecodeError::Field("state provider depth")); + } + *remaining -= 1; + let object: Object = serde_json::from_str(json)?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + Ok(Self(match kind.as_str() { + "minecraft:rule_based" => { + let fallback = optional(&object, "fallback") + .map(|raw| { + Self::decode_holder(raw.get(), bindings, depth + 1, remaining, catalog) + .map(Box::new) + }) + .transpose()?; + let raw_rules: Vec> = + serde_json::from_str(required(&object, "rules")?.get())?; + if raw_rules.len() > 8192 { + return Err(DecodeError::Field("provider rule count")); + } + let mut rules = Vec::with_capacity(raw_rules.len()); + for raw in raw_rules { + if *remaining == 0 { + return Err(DecodeError::Field("provider node count")); + } + *remaining -= 1; + let rule: Object = serde_json::from_str(raw.get())?; + let predicate = BlockPredicate::decode_with_blocks( + required(&rule, "if_true")?.get(), + depth + 1, + remaining, + Some(bindings), + )?; + let provider = Self::decode_holder( + required(&rule, "then")?.get(), + bindings, + depth + 1, + remaining, + catalog, + )?; + rules.push((predicate, provider)); + } + Node::RuleBased { fallback, rules } + } + "minecraft:noise" | "minecraft:noise_threshold" | "minecraft:dual_noise" => { + Node::Noise(Box::new(NoiseProvider::decode(&object, bindings, &kind)?)) + } + "minecraft:simple" => { + Node::Simple(bindings.state(required(&object, "state")?.get(), false)?) + } + "minecraft:weighted" => { + Node::Weighted(WeightedList::decode(required(&object, "entries")?, |v| { + bindings.state(v.get(), false) + })?) + } + "minecraft:random_block" => { + Node::RandomBlock(bindings.block_set(required(&object, "blocks")?)?) + } + "minecraft:rotated" => { + let direction = optional(&object, "direction") + .map(|v| { + let name: String = serde_json::from_str(v.get())?; + DIRECTIONS + .iter() + .position(|v| *v == name) + .ok_or(DecodeError::Field("provider direction")) + }) + .transpose()?; + Node::Rotated { + source: Box::new(Self::decode_holder( + required(&object, "state")?.get(), + bindings, + depth + 1, + remaining, + catalog, + )?), + direction, + rotations: bindings.rotations()?, + } + } + "minecraft:copy_properties" => Node::CopyProperties( + Box::new(Self::decode_holder( + required(&object, "source")?.get(), + bindings, + depth + 1, + remaining, + catalog, + )?), + bindings.properties()?, + ), + "minecraft:randomized_int" => Node::RandomizedInt { + source: Box::new(Self::decode_holder( + required(&object, "source")?.get(), + bindings, + depth + 1, + remaining, + catalog, + )?), + property: serde_json::from_str(required(&object, "property")?.get())?, + values: IntProvider::decode(required(&object, "values")?, depth + 1, remaining)?, + properties: bindings.properties()?, + }, + _ => return Err(DecodeError::Field("block state provider type")), + })) + } + pub fn get_optional_state( + &self, + world: &mut W, + random: &mut impl RandomSource, + position: [i32; 3], + ) -> Result, StateProviderError> { + Ok(match &self.0 { + Node::RuleBased { fallback, rules } => { + for (predicate, provider) in rules { + if predicate + .test(world, position) + .map_err(StateProviderError::Query)? + { + if let Some(state) = provider.get_optional_state(world, random, position)? { + return Ok(Some(state)); + } + } + } + match fallback { + Some(provider) => provider.get_optional_state(world, random, position)?, + None => None, + } + } + Node::Noise(provider) => Some(provider.sample(random, position)?), + Node::Simple(state) => Some(*state), + Node::Weighted(states) => Some(*states.sample(random)?), + Node::RandomBlock(states) => { + if states.is_empty() { + None + } else { + Some(states[random.next_int_bound(states.len() as i32)? as usize]) + } + } + Node::Rotated { + source, + direction, + rotations, + } => { + // Native orientation selection precedes the nested state draw. + let direction = match direction { + Some(value) => *value, + None => random.next_int_bound(6)? as usize, + }; + let state = source.get_state(world, random, position)?; + Some( + rotations + .get(state.0 as usize) + .ok_or(StateProviderError::InvalidState)?[direction], + ) + } + Node::CopyProperties(source, properties) => { + let target = source.get_state(world, random, position)?; + let source = world.block(position).map_err(StateProviderError::World)?; + Some( + properties + .copy(target, source) + .ok_or(StateProviderError::InvalidState)?, + ) + } + Node::RandomizedInt { + source, + property, + values, + properties, + } => { + let state = source.get_state(world, random, position)?; + if properties + .has_integer(state, property) + .ok_or(StateProviderError::InvalidState)? + { + let value = values.sample(random)?; + Some( + properties + .set_integer(state, property, value) + .ok_or(StateProviderError::InvalidPropertyValue)?, + ) + } else { + Some(state) + } + } + }) + } + pub fn get_state( + &self, + world: &mut W, + random: &mut impl RandomSource, + position: [i32; 3], + ) -> Result> { + match self.get_optional_state(world, random, position)? { + Some(state) => Ok(state), + None => world.block(position).map_err(StateProviderError::World), + } + } +} + +/// Bind the pinned registry's full-axis/full-facing/horizontal-facing property +/// families. A five-way facing or two-axis property is a different property and +/// is intentionally left unchanged. Unrelated properties retain their values. +fn rotation_table(registry: &BlockRegistry) -> Result { + let mut values = BTreeMap::<(String, String), BTreeSet>::new(); + for index in 0..registry.len() { + let state = registry.state(BlockStateId(index as u32)).unwrap(); + for name in ["axis", "facing"] { + if let Some(value) = state.properties.get(name) { + values + .entry((state.name.clone(), name.into())) + .or_default() + .insert(value.clone()); + } + } + } + let axis = ["x", "y", "z"].map(str::to_owned).into_iter().collect(); + let facing = DIRECTIONS.map(str::to_owned).into_iter().collect(); + let horizontal = DIRECTIONS[2..].iter().map(|s| (*s).to_owned()).collect(); + let mut result = Vec::with_capacity(registry.len()); + for index in 0..registry.len() { + let state = registry.state(BlockStateId(index as u32)).unwrap(); + let full_axis = values.get(&(state.name.clone(), "axis".into())) == Some(&axis); + let directions = values.get(&(state.name.clone(), "facing".into())); + let mut rotated = [BlockStateId(index as u32); 6]; + for (direction, name) in DIRECTIONS.iter().enumerate() { + let mut value = state.clone(); + if full_axis { + value.properties.insert( + "axis".into(), + ["y", "y", "z", "z", "x", "x"][direction].into(), + ); + } + if directions == Some(&facing) || (direction >= 2 && directions == Some(&horizontal)) { + value.properties.insert("facing".into(), (*name).into()); + } + rotated[direction] = registry + .id(&value) + .ok_or_else(|| "incomplete rotation state registry".to_owned())?; + } + result.push(rotated); + } + Ok(Arc::new(result)) +} diff --git a/crates/horizon-world/src/worldgen/state_provider/catalog.rs b/crates/horizon-world/src/worldgen/state_provider/catalog.rs new file mode 100644 index 000000000..0cda3d1e8 --- /dev/null +++ b/crates/horizon-world/src/worldgen/state_provider/catalog.rs @@ -0,0 +1,55 @@ +//! Immutable resource snapshots for named state-provider holders. +use super::{BlockStateProvider, DecodeError, StateProviderBindings, identifier}; +use serde_json::value::RawValue; +use std::collections::BTreeMap; + +pub struct StateProviderCatalog { + resources: BTreeMap>, +} +impl StateProviderCatalog { + /// Store resources without evaluating unused definitions. Resolving a root + /// validates its reachable providers, including branches not sampled at run + /// time. Cycles and excessive expansion fail the shared depth/work budget. + pub fn from_resources(resources: &BTreeMap) -> Result { + if resources.len() > 8192 { + return Err(DecodeError::Field("state provider resource count")); + } + let mut result = BTreeMap::new(); + for (name, json) in resources { + if result + .insert(identifier(name)?, serde_json::from_str(json)?) + .is_some() + { + return Err(DecodeError::Field("duplicate state provider resource")); + } + } + Ok(Self { resources: result }) + } + pub(super) fn lookup(&self, name: &str) -> Option<&str> { + self.resources.get(name).map(|v| v.get()) + } + /// Decode the holder codec: an inline direct provider or a registry name. + pub fn provider( + &self, + json: &str, + bindings: &StateProviderBindings<'_>, + ) -> Result { + BlockStateProvider::decode_holder(json, bindings, 0, &mut 65536, Some(self)) + } + /// Decode DIRECT_CODEC while allowing nested named holder references. + pub fn direct_provider( + &self, + json: &str, + bindings: &StateProviderBindings<'_>, + ) -> Result { + BlockStateProvider::decode(json, bindings, 0, &mut 65536, Some(self)) + } + /// Decode TYPED_CODEC while allowing nested named holder references. + pub fn typed_provider( + &self, + json: &str, + bindings: &StateProviderBindings<'_>, + ) -> Result { + BlockStateProvider::decode_typed(json, bindings, 0, &mut 65536, Some(self)) + } +} diff --git a/crates/horizon-world/src/worldgen/state_provider/noise.rs b/crates/horizon-world/src/worldgen/state_provider/noise.rs new file mode 100644 index 000000000..ee8b7c460 --- /dev/null +++ b/crates/horizon-world/src/worldgen/state_provider/noise.rs @@ -0,0 +1,231 @@ +use super::{StateProviderBindings, StateProviderError}; +use crate::registry::BlockStateId; +use crate::worldgen::{ + DecodeError, Object, decode_noise, int_range, integer, number_text, required, +}; +use horizon_core::{ + noise::{Noise, NoiseStack}, + random::{LegacyRandom, RandomSource, WorldgenRandom}, +}; +use serde_json::value::RawValue; +#[derive(Clone, Debug)] +pub(super) struct NoiseProvider { + noise: NoiseStack, + scale: f32, + choice: Choice, +} +#[derive(Clone, Debug)] +enum Choice { + States(Vec), + Threshold { + threshold: f32, + chance: f32, + default: BlockStateId, + low: Vec, + high: Vec, + }, + Dual { + states: Vec, + variety: [i32; 2], + slow: NoiseStack, + scale: f32, + }, +} +impl NoiseProvider { + pub fn decode( + object: &Object, + bindings: &StateProviderBindings<'_>, + kind: &str, + ) -> Result { + let seed = long(required(object, "seed")?)?; + let noise = decode_noise(required(object, "noise")?.get())? + .create(&mut WorldgenRandom::new(LegacyRandom::new(seed)))?; + let scale = positive(required(object, "scale")?)?; + let choice = match kind { + "minecraft:noise" => Choice::States(states(required(object, "states")?, bindings)?), + "minecraft:noise_threshold" => Choice::Threshold { + threshold: range(required(object, "threshold")?, -1., 1.)?, + chance: range(required(object, "high_chance")?, 0., 1.)?, + default: bindings.state(required(object, "default_state")?.get(), false)?, + low: states(required(object, "low_states")?, bindings)?, + high: states(required(object, "high_states")?, bindings)?, + }, + "minecraft:dual_noise" => Choice::Dual { + states: states(required(object, "states")?, bindings)?, + variety: variety(required(object, "variety")?)?, + slow: decode_noise(required(object, "slow_noise")?.get())? + .create(&mut WorldgenRandom::new(LegacyRandom::new(seed)))?, + scale: positive(required(object, "slow_scale")?)?, + }, + _ => return Err(DecodeError::Field("noise state provider type")), + }; + Ok(Self { + noise, + scale, + choice, + }) + } + pub fn sample( + &self, + random: &mut impl RandomSource, + p: [i32; 3], + ) -> Result> { + let fast = || { + self.noise.get3( + f64::from(p[0]) * f64::from(self.scale), + f64::from(p[1]) * f64::from(self.scale), + f64::from(p[2]) * f64::from(self.scale), + ) + }; + Ok(match &self.choice { + Choice::States(states) => states[index(fast(), states.len())], + Choice::Threshold { + threshold, + chance, + default, + low, + high, + } => { + if fast() < *threshold { + low[random.next_int_bound(low.len() as i32)? as usize] + } else if random.next_float() < *chance { + high[random.next_int_bound(high.len() as i32)? as usize] + } else { + *default + } + } + Choice::Dual { + states, + variety, + slow, + scale, + } => { + // The slow path intentionally multiplies at float precision. + let sample = |p: [i32; 3]| { + slow.get3( + f64::from(p[0] as f32 * *scale), + f64::from(p[1] as f32 * *scale), + f64::from(p[2] as f32 * *scale), + ) + }; + let fraction = (f64::from(sample(p)) - -1.) / 2.; + let low = f64::from(variety[0]); + let high = f64::from(variety[1] + 1); + let count = (if fraction < 0. { + low + } else if fraction > 1. { + high + } else { + low + fraction * (high - low) + }) as i32; + if count <= 0 { + return Err(StateProviderError::EmptyNoiseSelection); + } + // Every candidate is a pure noise query. Compute just the one + // the final fast-noise lookup selects, avoiding a temporary list. + let selected = index(fast(), count as usize) as i32; + let offset = [ + p[0].wrapping_add(selected.wrapping_mul(54545)), + p[1], + p[2].wrapping_add(selected.wrapping_mul(34234)), + ]; + states[index(sample(offset), states.len())] + } + }) + } +} +fn index(noise: f32, count: usize) -> usize { + (((1.0f32 + noise) / 2.0f32).clamp(0., 0.9999) * count as f32) as usize +} +fn states( + raw: &RawValue, + bindings: &StateProviderBindings<'_>, +) -> Result, DecodeError> { + let values: Vec> = serde_json::from_str(raw.get())?; + if values.is_empty() || values.len() > 8192 { + return Err(DecodeError::Field("noise provider states")); + } + values + .iter() + .map(|v| bindings.state(v.get(), false)) + .collect() +} +fn float(raw: &RawValue) -> Result { + number_text(raw)? + .parse() + .map_err(|_| DecodeError::Field("provider float")) +} +fn positive(raw: &RawValue) -> Result { + let value = float(raw)?; + if value > 0. && value <= f32::MAX { + Ok(value) + } else { + Err(DecodeError::Field("positive provider scale")) + } +} +fn range(raw: &RawValue, low: f32, high: f32) -> Result { + let value = float(raw)?; + if value.total_cmp(&low).is_ge() && value.total_cmp(&high).is_le() { + Ok(value) + } else { + Err(DecodeError::Field("provider float range")) + } +} +fn variety(raw: &RawValue) -> Result<[i32; 2], DecodeError> { + let range = if let Ok(value) = integer(raw) { + [value, value] + } else if let Ok(values) = serde_json::from_str::>>(raw.get()) { + if values.len() != 2 { + return Err(DecodeError::Field("provider variety")); + } + [integer(&values[0])?, integer(&values[1])?] + } else { + let object: Object = serde_json::from_str(raw.get())?; + [ + int_range(required(&object, "min_inclusive")?, "variety", 1, 64)?, + int_range(required(&object, "max_inclusive")?, "variety", 1, 64)?, + ] + }; + if range[0] < 1 || range[1] > 64 || range[0] > range[1] { + Err(DecodeError::Field("provider variety")) + } else { + Ok(range) + } +} +// Gson's LONG codec truncates decimal tokens and retains the low 64 bits. +fn long(raw: &RawValue) -> Result { + let text = number_text(raw)?; + let negative = text.starts_with('-'); + let text = text.strip_prefix('-').unwrap_or(text); + let (mantissa, exponent) = match text.split_once(['e', 'E']) { + Some((m, e)) => ( + m, + e.parse::() + .map_err(|_| DecodeError::Field("long exponent"))? as i64, + ), + None => (text, 0), + }; + let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, "")); + let length = whole.len() as i64 + exponent; + if length <= 0 { + return Ok(0); + } + let zeroes = (length - (whole.len() + fraction.len()) as i64).max(0); + if zeroes >= 64 { + return Ok(0); + } + let mut result = 0u64; + for digit in whole.bytes().chain(fraction.bytes()).take(length as usize) { + result = result + .wrapping_mul(10) + .wrapping_add(u64::from(digit - b'0')); + } + for _ in 0..zeroes { + result = result.wrapping_mul(10); + } + Ok(if negative { + result.wrapping_neg() + } else { + result + } as i64) +} diff --git a/crates/horizon-world/src/worldgen/state_provider/properties.rs b/crates/horizon-world/src/worldgen/state_provider/properties.rs new file mode 100644 index 000000000..ee8389401 --- /dev/null +++ b/crates/horizon-world/src/worldgen/state_provider/properties.rs @@ -0,0 +1,178 @@ +//! Compact property transitions derived from the pinned Cartesian state tables. +use crate::registry::{BlockRegistry, BlockStateId}; +use std::collections::{BTreeMap, BTreeSet}; +#[derive(Clone, Copy, Debug)] +struct Address { + block: usize, + local: usize, +} +#[derive(Debug)] +struct Property { + identity: usize, + name: String, + values: Vec, + lookup: BTreeMap, + numeric: Option>, + stride: usize, +} +#[derive(Debug)] +struct Block { + states: Vec, + properties: Vec, +} +#[derive(Debug)] +pub(super) struct StateProperties { + blocks: Vec, + addresses: Vec

, +} +impl StateProperties { + pub fn build( + registry: &BlockRegistry, + integers: &BTreeSet<(String, String)>, + ) -> Result { + let mut grouped = BTreeMap::>::new(); + for index in 0..registry.len() { + let id = BlockStateId(index as u32); + grouped + .entry(registry.state(id).unwrap().name.clone()) + .or_default() + .push(id); + } + let mut identities = BTreeMap::new(); + let mut result = Self { + blocks: Vec::new(), + addresses: vec![Address { block: 0, local: 0 }; registry.len()], + }; + for (name, states) in grouped { + let mut properties = Vec::new(); + let first = registry.state(states[0]).unwrap(); + for (property, initial) in &first.properties { + let mut values = Vec::new(); + let mut lookup = BTreeMap::new(); + let mut stride = None; + for (index, id) in states.iter().enumerate() { + let state = registry.state(*id).unwrap(); + if state.properties.len() != first.properties.len() { + return Err("inconsistent block properties".into()); + } + let value = state + .properties + .get(property) + .ok_or("missing block property")?; + if value != initial && stride.is_none() { + stride = Some(index); + } + if !lookup.contains_key(value) { + lookup.insert(value.clone(), values.len()); + values.push(value.clone()); + } + } + let stride = stride.unwrap_or(1); + for (index, id) in states.iter().enumerate() { + if registry.state(*id).unwrap().properties[property] + != values[(index / stride) % values.len()] + { + return Err("non-Cartesian property state order".into()); + } + } + let integer = integers.contains(&(name.clone(), property.clone())); + // In the pinned registry these signatures uniquely identify + // Java Property.equals families; the native harness checks this. + let signature = ( + property.clone(), + integer, + lookup.keys().cloned().collect::>(), + ); + let next = identities.len(); + let identity = *identities.entry(signature).or_insert(next); + let numeric = if integer { + Some( + values + .iter() + .enumerate() + .map(|(i, s)| { + s.parse::() + .map(|v| (v, i)) + .map_err(|_| "invalid integer property".to_owned()) + }) + .collect::>()?, + ) + } else { + None + }; + properties.push(Property { + identity, + name: property.clone(), + values, + lookup, + numeric, + stride, + }); + } + let mut dimensions = properties + .iter() + .filter(|p| p.values.len() > 1) + .collect::>(); + dimensions.sort_by_key(|p| p.stride); + let mut size = 1usize; + for p in dimensions { + if p.stride != size { + return Err("overlapping property state dimensions".into()); + } + size = size + .checked_mul(p.values.len()) + .ok_or("property state size overflow")?; + } + if size != states.len() { + return Err("incomplete Cartesian state table".into()); + } + for (local, id) in states.iter().enumerate() { + result.addresses[id.0 as usize] = Address { + block: result.blocks.len(), + local, + }; + } + result.blocks.push(Block { states, properties }); + } + Ok(result) + } + pub fn copy(&self, target: BlockStateId, source: BlockStateId) -> Option { + let mut target = *self.addresses.get(target.0 as usize)?; + let source = *self.addresses.get(source.0 as usize)?; + let block = &self.blocks[target.block]; + for source_property in &self.blocks[source.block].properties { + if let Some(property) = block + .properties + .iter() + .find(|p| p.identity == source_property.identity) + { + let value = &source_property.values + [(source.local / source_property.stride) % source_property.values.len()]; + let index = *property.lookup.get(value)?; + let previous = (target.local / property.stride) % property.values.len(); + target.local = target.local - previous * property.stride + index * property.stride; + } + } + block.states.get(target.local).copied() + } + pub fn has_integer(&self, state: BlockStateId, name: &str) -> Option { + let address = self.addresses.get(state.0 as usize)?; + Some( + self.blocks[address.block] + .properties + .iter() + .any(|p| p.name == name && p.numeric.is_some()), + ) + } + pub fn set_integer(&self, state: BlockStateId, name: &str, value: i32) -> Option { + let address = self.addresses.get(state.0 as usize)?; + let block = &self.blocks[address.block]; + let property = block.properties.iter().find(|p| p.name == name)?; + let index = property.numeric.as_ref()?.get(&value)?; + let previous = (address.local / property.stride) % property.values.len(); + block + .states + .get(address.local - previous * property.stride + index * property.stride) + .copied() + } +} diff --git a/crates/horizon-world/src/worldgen/tags.rs b/crates/horizon-world/src/worldgen/tags.rs new file mode 100644 index 000000000..6cc94a467 --- /dev/null +++ b/crates/horizon-world/src/worldgen/tags.rs @@ -0,0 +1,369 @@ +//! Version-pinned tag codecs, resource-stack merging and dependency resolution. +use super::{DecodeError, Object, optional, required}; +use horizon_core::random::java_string_hash; +use serde_json::value::RawValue; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TagEntry { + pub id: String, + pub tag: bool, + pub required: bool, +} +impl TagEntry { + pub fn from_json(json: &str) -> Result { + let raw: Box = serde_json::from_str(json)?; + let (name, mandatory) = if raw.get().starts_with('"') { + (serde_json::from_str::(raw.get())?, true) + } else { + let object: Object = serde_json::from_str(raw.get())?; + ( + serde_json::from_str(required(&object, "id")?.get())?, + optional(&object, "required") + .map(|v| serde_json::from_str(v.get())) + .transpose()? + .unwrap_or(true), + ) + }; + let (tag, name) = name + .strip_prefix('#') + .map_or((false, name.as_str()), |s| (true, s)); + Ok(Self { + id: identifier(name)?, + tag, + required: mandatory, + }) + } + pub fn display(&self) -> String { + format!( + "{}{}{}", + if self.tag { "#" } else { "" }, + self.id, + if self.required { "" } else { "?" } + ) + } +} +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TagFile { + pub entries: Vec, + pub replace: bool, +} +impl TagFile { + pub fn from_json(json: &str) -> Result { + let object: Object = serde_json::from_str(json)?; + let values: Vec> = serde_json::from_str(required(&object, "values")?.get())?; + let entries = values + .iter() + .map(|v| TagEntry::from_json(v.get())) + .collect::>()?; + let replace = optional(&object, "replace") + .map(|v| serde_json::from_str(v.get())) + .transpose()? + .unwrap_or(false); + Ok(Self { entries, replace }) + } +} +// Identifier.CODEC permits the empty path as well as an omitted namespace. +pub(super) fn identifier(name: &str) -> Result { + let (namespace, path) = name.split_once(':').unwrap_or(("minecraft", name)); + let namespace = if namespace.is_empty() { + "minecraft" + } else { + namespace + }; + let valid = |c: u8| c.is_ascii_lowercase() || c.is_ascii_digit() || b"_.-".contains(&c); + if !namespace.bytes().all(valid) || !path.bytes().all(|c| valid(c) || c == b'/') { + return Err(DecodeError::Registry(format!( + "invalid tag identifier: {name}" + ))); + } + Ok(format!("{namespace}:{path}")) +} +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TagEntryWithSource { + pub entry: TagEntry, + pub source: String, +} +#[derive(Clone, Debug, Default)] +pub struct TagDefinitions { + entries: BTreeMap>, + insertion_order: Vec, +} +#[derive(Clone, Debug)] +pub struct BuiltTags { + pub tags: BTreeMap>, + pub missing: BTreeMap>, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TagBuildError { + TooManyTags, + DependencyDepth, + HashTreeBucket, +} +impl std::fmt::Display for TagBuildError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::TooManyTags => "tag definitions exceed 8192 entries", + Self::DependencyDepth => { + "tag dependency depth exceeds 256 or cyclic reachability does not terminate" + } + Self::HashTreeBucket => "tag identifiers require an unsupported Java hash tree bucket", + }) + } +} +impl std::error::Error for TagBuildError {} +impl TagDefinitions { + /// Apply resources in their pack priority order. A successfully decoded + /// replace file clears earlier entries; a rejected file changes nothing. + pub fn add(&mut self, name: &str, source: &str, file: TagFile) -> Result<(), DecodeError> { + let name = identifier(name)?; + if !self.entries.contains_key(&name) { + self.insertion_order.push(name.clone()); + } + let entries = self.entries.entry(name).or_default(); + if file.replace { + entries.clear(); + } + entries.extend(file.entries.into_iter().map(|entry| TagEntryWithSource { + entry, + source: source.into(), + })); + Ok(()) + } + /// A valid JSON resource with a codec error still creates an empty tag in + /// vanilla's resource loader; existing entries are retained on that error. + pub fn apply_json(&mut self, name: &str, source: &str, json: &str) -> Result<(), DecodeError> { + let _: Box = serde_json::from_str(json)?; + let name = identifier(name)?; + if !self.entries.contains_key(&name) { + self.insertion_order.push(name.clone()); + self.entries.insert(name.clone(), Vec::new()); + } + self.add(&name, source, TagFile::from_json(json)?) + } + pub fn definitions(&self) -> &BTreeMap> { + &self.entries + } + /// Missing required references invalidate their own tags, not unrelated tags. + /// Element lookup receives the entry's required flag, as in vanilla. + pub fn build( + &self, + mut lookup: impl FnMut(&str, bool) -> Option, + ) -> Result, TagBuildError> { + if self.entries.len() > 8192 { + return Err(TagBuildError::TooManyTags); + } + // DependencySorter owns a fresh default-sized HashMap. Required edges + // are inserted for every tag before any optional edge is considered. + // The resource loader creates keys with HashMap.computeIfAbsent, + // which inserts at the head of a bucket. DependencySorter then copies + // that map with put (tail insertion), retaining the reversed order of + // colliding resource keys. Resizing preserves each split chain's order. + let order = java_bucket_order(self.insertion_order.iter().rev().map(String::as_str), 16)?; + let mut edges: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); + for mandatory in [true, false] { + for &name in &order { + for entry in &self.entries[name] { + let e = &entry.entry; + if e.tag && e.required == mandatory && !reaches(&edges, &e.id, name, 0)? { + let children = edges.entry(name).or_default(); + if !children.contains(&e.id.as_str()) { + children.push(&e.id); + } + } + } + } + } + // Guava HashMultimap value sets start with capacity four (two expected + // values). Their native bucket order matters when cycles are pruned. + let edges = edges + .into_iter() + .map(|(key, children)| Ok((key, java_bucket_order(children, 4)?))) + .collect::, TagBuildError>>()?; + let mut visited = BTreeSet::new(); + let mut sorted = Vec::new(); + for name in order { + visit(name, &edges, &mut visited, &mut sorted, 0)?; + } + let mut result: BuiltTags = BuiltTags { + tags: BTreeMap::new(), + missing: BTreeMap::new(), + }; + for name in sorted { + let Some(entries) = self.entries.get(name) else { + continue; + }; + let mut seen = BTreeSet::new(); + let mut values = Vec::new(); + let mut missing = Vec::new(); + for sourced in entries { + let entry = &sourced.entry; + if entry.tag { + if let Some(children) = result.tags.get(&entry.id) { + for value in children { + if seen.insert(value.clone()) { + values.push(value.clone()); + } + } + } else if entry.required { + missing.push(sourced.clone()); + } + } else if let Some(value) = lookup(&entry.id, entry.required) { + if seen.insert(value.clone()) { + values.push(value); + } + } else if entry.required { + missing.push(sourced.clone()); + } + } + if missing.is_empty() { + result.tags.insert(name.into(), values); + } else { + result.missing.insert(name.into(), missing); + } + } + Ok(result) + } +} +fn reaches( + edges: &BTreeMap<&str, Vec<&str>>, + from: &str, + target: &str, + depth: usize, +) -> Result { + if depth > 256 { + return Err(TagBuildError::DependencyDepth); + } + if let Some(children) = edges.get(from) { + if children.contains(&target) { + return Ok(true); + } + for child in children { + if reaches(edges, child, target, depth + 1)? { + return Ok(true); + } + } + } + Ok(false) +} +fn visit<'a>( + name: &'a str, + edges: &BTreeMap<&'a str, Vec<&'a str>>, + visited: &mut BTreeSet<&'a str>, + sorted: &mut Vec<&'a str>, + depth: usize, +) -> Result<(), TagBuildError> { + if !visited.insert(name) { + return Ok(()); + } + if depth > 256 { + return Err(TagBuildError::DependencyDepth); + } + if let Some(children) = edges.get(name) { + for child in children { + visit(child, edges, visited, sorted, depth + 1)?; + } + } + sorted.push(name); + Ok(()) +} +fn hash(name: &str) -> u32 { + let (namespace, path) = name.split_once(':').expect("canonical tag identifier"); + let raw = java_string_hash(namespace.encode_utf16()) + .wrapping_mul(31) + .wrapping_add(java_string_hash(path.encode_utf16())) as u32; + raw ^ (raw >> 16) +} +fn java_bucket_order<'a>( + names: impl IntoIterator, + initial: usize, +) -> Result, TagBuildError> { + let names: Vec<_> = names.into_iter().collect(); + let mut capacity = initial; + for count in 1..=names.len() { + let bucket = hash(names[count - 1]) as usize & (capacity - 1); + let collisions = names[..count] + .iter() + .filter(|name| hash(name) as usize & (capacity - 1) == bucket) + .count(); + if collisions >= 9 { + if capacity < 64 { + capacity *= 2; + } else { + return Err(TagBuildError::HashTreeBucket); + } + } + if count > capacity * 3 / 4 { + capacity *= 2; + } + } + let mut ordered = names; + ordered.sort_by_key(|name| hash(name) as usize & (capacity - 1)); + Ok(ordered) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn invalid_replacement_keeps_entries_and_codec_error_can_create_empty_tag() { + let mut definitions = TagDefinitions::default(); + definitions + .apply_json("a", "first", r##"{"values":["one","two","one"]}"##) + .unwrap(); + assert!( + definitions + .apply_json("a", "bad", r##"{"replace":true,"values":[false]}"##) + .is_err() + ); + assert!(definitions.apply_json("empty", "bad", "{}").is_err()); + assert!(definitions.apply_json("syntax", "bad", "{").is_err()); + let built = definitions.build(|id, _| Some(id.to_owned())).unwrap(); + assert_eq!( + built.tags["minecraft:a"], + vec!["minecraft:one", "minecraft:two"] + ); + assert_eq!(built.tags["minecraft:empty"], Vec::::new()); + assert!(!built.tags.contains_key("minecraft:syntax")); + definitions + .apply_json( + "a", + "replacement", + r##"{"replace":true,"values":["three"]}"##, + ) + .unwrap(); + let built = definitions.build(|id, _| Some(id.to_owned())).unwrap(); + assert_eq!(built.tags["minecraft:a"], vec!["minecraft:three"]); + } + #[test] + fn required_edges_precede_optional_edges_and_missing_tags_do_not_poison_siblings() { + let mut definitions = TagDefinitions::default(); + for (name, json) in [ + ("a", r##"{"values":[{"id":"#b","required":false},"one"]}"##), + ("b", r##"{"values":["#a","two"]}"##), + ("bad", r##"{"values":["absent","also_absent"]}"##), + ( + "c", + r##"{"values":[{"id":"#bad","required":false},"two"]}"##, + ), + ] { + definitions.apply_json(name, "fixture", json).unwrap(); + } + let built = definitions + .build(|id, _| (!id.ends_with("absent")).then(|| id.to_owned())) + .unwrap(); + assert_eq!(built.tags["minecraft:a"], vec!["minecraft:one"]); + assert_eq!( + built.tags["minecraft:b"], + vec!["minecraft:one", "minecraft:two"] + ); + assert_eq!(built.tags["minecraft:c"], vec!["minecraft:two"]); + assert_eq!( + built.missing["minecraft:bad"] + .iter() + .map(|e| e.entry.id.as_str()) + .collect::>(), + vec!["minecraft:absent", "minecraft:also_absent"] + ); + } +} diff --git a/crates/horizon-world/src/worldgen/terrain.rs b/crates/horizon-world/src/worldgen/terrain.rs new file mode 100644 index 000000000..9daf04cb7 --- /dev/null +++ b/crates/horizon-world/src/worldgen/terrain.rs @@ -0,0 +1,479 @@ +//! Noise-stage chunk filling. Material rules, structures and chunk lifecycle are +//! separate stages; this module does not produce a complete generated chunk. +use super::aquifer::{ + AquiferBlockStates, AquiferError, DisabledAquifer, FluidPicker, NoiseBasedAquifer, +}; +use crate::{ + chunk::BlockSection, + heightmap::{Heightmap, HeightmapChunk, HeightmapError, HeightmapState, HeightmapType}, + registry::{BlockRegistry, BlockStateId}, +}; +use horizon_core::{ + density::{DensitySampler, SampleError, SamplerContext}, + noise::DensityVolume, + position::ChunkPos, + random::PositionalRandom, +}; +use std::io; + +/// Behavior and resolved tags for every state in the chunk's immutable registry. +pub trait TerrainBlockStates { + type State: HeightmapState; + fn heightmap_state(&self, id: BlockStateId) -> Self::State; +} + +pub trait TerrainAquifer { + fn compute_substance( + &mut self, + context: &mut SamplerContext, + position: [i32; 3], + density: f64, + ) -> Result, AquiferError>; + fn should_schedule_fluid_update(&self) -> bool; +} +impl TerrainAquifer for DisabledAquifer

{ + fn compute_substance( + &mut self, + _: &mut SamplerContext, + position: [i32; 3], + density: f64, + ) -> Result, AquiferError> { + Ok(DisabledAquifer::compute_substance(self, position, density)) + } + fn should_schedule_fluid_update(&self) -> bool { + false + } +} +impl TerrainAquifer + for NoiseBasedAquifer +{ + fn compute_substance( + &mut self, + context: &mut SamplerContext, + position: [i32; 3], + density: f64, + ) -> Result, AquiferError> { + NoiseBasedAquifer::compute_substance(self, context, position, density) + } + fn should_schedule_fluid_update(&self) -> bool { + NoiseBasedAquifer::should_schedule_fluid_update(self) + } +} + +#[derive(Debug)] +pub enum TerrainError { + Storage(io::Error), + Heightmap(HeightmapError), + Sample(SampleError), + Aquifer(AquiferError), + MissingAir, + InvalidState, + InvalidVolume, + OutsideBuildHeight, +} +impl std::fmt::Display for TerrainError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{self:?}") + } +} +impl std::error::Error for TerrainError {} +impl From for TerrainError { + fn from(value: io::Error) -> Self { + Self::Storage(value) + } +} +impl From for TerrainError { + fn from(value: HeightmapError) -> Self { + Self::Heightmap(value) + } +} +impl From for TerrainError { + fn from(value: SampleError) -> Self { + Self::Sample(value) + } +} +impl From for TerrainError { + fn from(value: AquiferError) -> Self { + Self::Aquifer(value) + } +} + +/// Resident registry-backed sections, optional heightmaps and ordered per-section +/// fluid postprocessing offsets for the noise and surface generation stages. +pub struct TerrainChunk<'r, B: TerrainBlockStates> { + stage: PreLightChunkStage, + position: ChunkPos, + blocks: TerrainBlocks<'r, B>, + heightmaps: [Option; 6], + postprocessing: Vec>, +} +/// The persisted generation statuses before lighting initialization. This models +/// their block-write heightmap selection, not scheduling or persisted metadata. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum PreLightChunkStage { + #[default] + Empty, + StructureStarts, + StructureReferences, + Biomes, + Terrain, + Features, +} +impl PreLightChunkStage { + pub const ALL: [Self; 6] = [ + Self::Empty, + Self::StructureStarts, + Self::StructureReferences, + Self::Biomes, + Self::Terrain, + Self::Features, + ]; + pub fn name(self) -> &'static str { + match self { + Self::Empty => "empty", + Self::StructureStarts => "structure_starts", + Self::StructureReferences => "structure_references", + Self::Biomes => "biomes", + Self::Terrain => "terrain", + Self::Features => "features", + } + } + pub fn heightmaps(self) -> &'static [HeightmapType] { + if matches!(self, Self::Terrain | Self::Features) { + &[ + HeightmapType::WorldSurface, + HeightmapType::OceanFloor, + HeightmapType::MotionBlocking, + HeightmapType::MotionBlockingNoLeaves, + ] + } else { + &[HeightmapType::WorldSurfaceWg, HeightmapType::OceanFloorWg] + } + } +} +struct TerrainBlocks<'r, B: TerrainBlockStates> { + min_y: i32, + height: i32, + sections: Vec>, + non_air: Vec, + registry: &'r BlockRegistry, + properties: B, + air: BlockStateId, + void_air: BlockStateId, +} +impl HeightmapChunk for TerrainBlocks<'_, B> { + type State = B::State; + fn min_y(&self) -> i32 { + self.min_y + } + fn height(&self) -> i32 { + self.height + } + fn highest_section_y(&self) -> i32 { + self.non_air + .iter() + .rposition(|&count| count != 0) + .map_or(self.min_y, |i| self.min_y + i as i32 * 16) + } + fn block_state(&self, x: i32, y: i32, z: i32) -> B::State { + self.properties.heightmap_state(self.block(x, y, z)) + } +} +impl TerrainBlocks<'_, B> { + fn section_index(&self, y: i32) -> Option { + let dy = i64::from(y) - i64::from(self.min_y); + (dy >= 0 && dy < i64::from(self.height)).then_some((dy >> 4) as usize) + } + fn block(&self, x: i32, y: i32, z: i32) -> BlockStateId { + let Some(section) = self.section_index(y) else { + return self.void_air; + }; + if self.non_air[section] == 0 { + return self.air; + } + self.sections[section] + .get(local_index(x, y, z)) + .expect("valid section coordinates") + } +} +fn local_index(x: i32, y: i32, z: i32) -> usize { + (((y & 15) << 8) | ((z & 15) << 4) | (x & 15)) as usize +} + +impl<'r, B: TerrainBlockStates> TerrainChunk<'r, B> { + pub fn new( + position: ChunkPos, + min_y: i32, + height: i32, + registry: &'r BlockRegistry, + properties: B, + ) -> Result { + // Share the heightmap's supported range and fail before allocating sections. + Heightmap::new(HeightmapType::WorldSurfaceWg, min_y, height)?; + let air = registry + .default_state("minecraft:air") + .ok_or(TerrainError::MissingAir)?; + let void_air = registry + .default_state("minecraft:void_air") + .ok_or(TerrainError::MissingAir)?; + let section_count = (height / 16) as usize; + let sections = (0..section_count) + .map(|_| BlockSection::uniform(air, registry)) + .collect::>>()?; + Ok(Self { + stage: PreLightChunkStage::Empty, + position, + blocks: TerrainBlocks { + min_y, + height, + sections, + non_air: vec![0; section_count], + registry, + properties, + air, + void_air, + }, + heightmaps: std::array::from_fn(|_| None), + postprocessing: vec![Vec::new(); section_count], + }) + } + pub(crate) fn registry(&self) -> &BlockRegistry { + self.blocks.registry + } + pub fn highest_filled_section_index(&self) -> Option { + self.blocks.non_air.iter().rposition(|&count| count != 0) + } + pub fn block_properties(&self, state: BlockStateId) -> B::State { + self.blocks.properties.heightmap_state(state) + } + pub fn same_block(&self, left: BlockStateId, right: BlockStateId) -> bool { + self.blocks + .registry + .state(left) + .zip(self.blocks.registry.state(right)) + .is_some_and(|(left, right)| left.name == right.name) + } + pub fn generation_stage(&self) -> PreLightChunkStage { + self.stage + } + /// Changing status alone does not prime or clear any heightmaps. Native + /// persisted-status assignment also permits earlier statuses. + pub fn set_generation_stage(&mut self, stage: PreLightChunkStage) { + self.stage = stage; + } + /// ProtoChunk writes before lighting. The current stage selects heightmaps; + /// missing maps are primed after existing maps are updated. + pub fn set_block_worldgen( + &mut self, + x: i32, + y: i32, + z: i32, + state: BlockStateId, + ) -> Result { + let Some(section) = self.blocks.section_index(y) else { + return Ok(self.blocks.void_air); + }; + if self.blocks.non_air[section] == 0 && state == self.blocks.air { + return Ok(state); + } + let previous = self.set_block_raw(x, y, z, state)?; + let mut missing = Vec::new(); + for &kind in self.stage.heightmaps() { + if self.heightmap(kind).is_some() { + self.update_heightmap(kind, x & 15, y, z & 15, state)?; + } else { + missing.push(kind); + } + } + if !missing.is_empty() { + self.prime_heightmaps(&missing)?; + } + Ok(previous) + } + pub fn position(&self) -> ChunkPos { + self.position + } + pub fn min_y(&self) -> i32 { + self.blocks.min_y + } + pub fn height(&self) -> i32 { + self.blocks.height + } + pub fn highest_section_y(&self) -> i32 { + self.blocks.highest_section_y() + } + /// ProtoChunk reads collapse an all-air section to its default AIR state. + pub fn block(&self, x: i32, y: i32, z: i32) -> BlockStateId { + self.blocks.block(x, y, z) + } + pub fn section(&self, index: usize) -> Option<&BlockSection<'r>> { + self.blocks.sections.get(index) + } + pub fn heightmap(&self, kind: HeightmapType) -> Option<&Heightmap> { + self.heightmaps[kind as usize].as_ref() + } + pub fn postprocessing(&self) -> &[Vec] { + &self.postprocessing + } + + pub fn ensure_heightmap(&mut self, kind: HeightmapType) -> &mut Heightmap { + self.heightmaps[kind as usize].get_or_insert_with(|| { + Heightmap::new(kind, self.blocks.min_y, self.blocks.height) + .expect("validated chunk range") + }) + } + /// Section write only. The caller chooses which generation-stage maps to update. + pub fn set_block_raw( + &mut self, + x: i32, + y: i32, + z: i32, + state: BlockStateId, + ) -> Result { + let section = self + .blocks + .section_index(y) + .ok_or(TerrainError::OutsideBuildHeight)?; + let old = self.blocks.sections[section].set(local_index(x, y, z), state)?; + let old_air = self.blocks.properties.heightmap_state(old).is_air(); + let new_air = self.blocks.properties.heightmap_state(state).is_air(); + if old_air && !new_air { + self.blocks.non_air[section] += 1; + } else if !old_air && new_air { + self.blocks.non_air[section] -= 1; + } + Ok(old) + } + pub fn update_heightmap( + &mut self, + kind: HeightmapType, + x: i32, + y: i32, + z: i32, + state: BlockStateId, + ) -> Result { + if self.blocks.registry.state(state).is_none() { + return Err(TerrainError::InvalidState); + } + self.ensure_heightmap(kind); + let state = self.blocks.properties.heightmap_state(state); + Ok(self.heightmaps[kind as usize] + .as_mut() + .unwrap() + .update(&self.blocks, x, y, z, state)?) + } + pub fn prime_heightmaps(&mut self, kinds: &[HeightmapType]) -> Result<(), TerrainError> { + let mut order = Vec::new(); + for &kind in kinds { + self.ensure_heightmap(kind); + if !order.contains(&(kind as usize)) { + order.push(kind as usize); + } + } + // Split references preserve the supplied set's iteration order. + let mut maps: Vec<_> = self + .heightmaps + .iter_mut() + .enumerate() + .filter_map(|(i, map)| { + order + .iter() + .position(|&key| key == i) + .map(|position| (position, map.as_mut().unwrap())) + }) + .collect(); + maps.sort_by_key(|(position, _)| *position); + Heightmap::prime( + &self.blocks, + &mut maps.into_iter().map(|(_, map)| map).collect::>(), + )?; + Ok(()) + } + pub fn set_heightmap_raw( + &mut self, + kind: HeightmapType, + words: &[u64], + ) -> Result<(), TerrainError> { + self.ensure_heightmap(kind); + self.heightmaps[kind as usize] + .as_mut() + .unwrap() + .set_raw_data(&self.blocks, words)?; + Ok(()) + } + /// Preserves duplicates and insertion order, as ProtoChunk does. + pub fn mark_postprocessing(&mut self, x: i32, y: i32, z: i32) { + if let Some(section) = self.blocks.section_index(y) { + self.postprocessing[section] + .push(((x & 15) | ((y & 15) << 4) | ((z & 15) << 8)) as u16); + } + } +} + +/// Evaluate final density in bulk before writes, then visit Z/X/descending Y. +/// The aquifer and final density must share this already prepared sampler context. +/// Failures retain earlier writes and aquifer/cache state; there is no rollback. +/// Regular gameplay only: developer preliminary-surface markers are not applied. +pub fn fill_noise( + chunk: &mut TerrainChunk<'_, B>, + volume: DensityVolume, + final_density: &dyn DensitySampler, + context: &mut SamplerContext, + aquifer: &mut (impl TerrainAquifer + ?Sized), + default_block: BlockStateId, +) -> Result<(), TerrainError> { + let [sx, sy, sz] = volume.sizes(); + let [bx, by, bz] = volume.minimum(); + if sx != 16 + || sz != 16 + || volume.steps() != [1; 3] + || bx != chunk.position.x.wrapping_shl(4) + || bz != chunk.position.z.wrapping_shl(4) + || by < chunk.min_y() + || i64::from(by) + sy as i64 > i64::from(chunk.min_y()) + i64::from(chunk.height()) + || chunk.blocks.registry.state(default_block).is_none() + { + return Err(TerrainError::InvalidVolume); + } + chunk.ensure_heightmap(HeightmapType::OceanFloorWg); + chunk.ensure_heightmap(HeightmapType::WorldSurfaceWg); + let mut density = vec![0.; volume.size()]; + final_density.sample_volume(context, &mut density, volume)?; + for z in 0..sz { + let world_z = bz.wrapping_add(z as i32); + for x in 0..sx { + let world_x = bx.wrapping_add(x as i32); + for y in (0..sy).rev() { + let world_y = by.wrapping_add(y as i32); + let value = density[volume.index([x, y, z]).expect("valid density coordinates")]; + let state = aquifer + .compute_substance(context, [world_x, world_y, world_z], f64::from(value))? + .unwrap_or(default_block); + if state == chunk.blocks.air { + continue; + } + chunk.set_block_raw(x as i32, world_y, z as i32, state)?; + chunk.update_heightmap( + HeightmapType::OceanFloorWg, + x as i32, + world_y, + z as i32, + state, + )?; + chunk.update_heightmap( + HeightmapType::WorldSurfaceWg, + x as i32, + world_y, + z as i32, + state, + )?; + if aquifer.should_schedule_fluid_update() + && chunk.blocks.properties.heightmap_state(state).has_fluid() + { + chunk.mark_postprocessing(world_x, world_y, world_z); + } + } + } + } + Ok(()) +} diff --git a/crates/horizon-world/src/worldgen/value_provider.rs b/crates/horizon-world/src/worldgen/value_provider.rs new file mode 100644 index 000000000..27bc8d4ae --- /dev/null +++ b/crates/horizon-world/src/worldgen/value_provider.rs @@ -0,0 +1,215 @@ +//! Scalar distributions used by cave/canyon definitions. Gaussian providers +//! remain separate work; this module does not yet cover every provider. +use super::weighted::WeightedList; +use super::{DecodeError, Object, density::identifier, integer, number_text, required}; +use horizon_core::random::{InvalidBound, RandomSource}; +use serde_json::value::RawValue; + +#[derive(Clone, Debug)] +pub enum FloatProvider { + Constant(f32), + Uniform { min: f32, max: f32 }, + Trapezoid { min: f32, max: f32, plateau: f32 }, +} +impl FloatProvider { + pub fn from_json(json: &str) -> Result { + let raw: Box = serde_json::from_str(json)?; + if let Ok(value) = float(&raw) { + return Ok(Self::Constant(if value == 0. { 0. } else { value })); + } + let object: Object = serde_json::from_str(raw.get())?; + let field = |name| required(&object, name).and_then(float); + match kind(&object)?.as_str() { + "minecraft:constant" => { + let value = field("value")?; + Ok(Self::Constant(if value == 0. { 0. } else { value })) + } + "minecraft:uniform" => { + let (min, max) = (field("min_inclusive")?, field("max_exclusive")?); + if max <= min { + return Err(DecodeError::Field("uniform float bounds")); + } + Ok(Self::Uniform { min, max }) + } + "minecraft:trapezoid" => { + let (min, max, plateau) = (field("min")?, field("max")?, field("plateau")?); + if max < min || plateau > max - min { + return Err(DecodeError::Field("trapezoid float bounds")); + } + Ok(Self::Trapezoid { min, max, plateau }) + } + _ => Err(DecodeError::Field("float provider type")), + } + } + pub fn bounds(&self) -> [f32; 2] { + match *self { + Self::Constant(value) => [value; 2], + Self::Uniform { min, max } | Self::Trapezoid { min, max, .. } => [min, max], + } + } + pub fn sample(&self, random: &mut impl RandomSource) -> f32 { + match *self { + Self::Constant(value) => value, + Self::Uniform { min, max } => random.next_float() * (max - min) + min, + Self::Trapezoid { min, max, plateau } => { + let range = max - min; + let slope = (range - plateau) / 2.; + let middle = range - slope; + (min + random.next_float() * middle) + random.next_float() * slope + } + } + } +} + +#[derive(Clone, Debug)] +pub enum IntProvider { + Weighted(WeightedList), + Constant(i32), + Uniform { + min: i32, + max: i32, + }, + BiasedToBottom { + min: i32, + max: i32, + }, + VeryBiasedToBottom { + min: i32, + max: i32, + }, + Trapezoid { + min: i32, + max: i32, + plateau: i32, + }, + Clamped { + source: Box, + min: i32, + max: i32, + }, +} +impl IntProvider { + pub fn from_json(json: &str) -> Result { + let raw: Box = serde_json::from_str(json)?; + Self::decode(&raw, 0, &mut 65536) + } + pub(crate) fn decode( + raw: &RawValue, + depth: usize, + remaining: &mut usize, + ) -> Result { + if depth > 256 || *remaining == 0 { + return Err(DecodeError::Field("integer provider depth")); + } + *remaining -= 1; + if let Ok(value) = integer(raw) { + return Ok(Self::Constant(value)); + } + let object: Object = serde_json::from_str(raw.get())?; + let kind = kind(&object)?; + let field = |name| required(&object, name).and_then(integer); + if kind == "minecraft:constant" { + return Ok(Self::Constant(field("value")?)); + } + if kind == "minecraft:weighted_list" { + return Ok(Self::Weighted(WeightedList::decode( + required(&object, "distribution")?, + |raw| Self::decode(raw, depth + 1, remaining), + )?)); + } + let trapezoid = kind == "minecraft:trapezoid"; + let min = field(if trapezoid { "min" } else { "min_inclusive" })?; + let max = field(if trapezoid { "max" } else { "max_inclusive" })?; + if max < min { + return Err(DecodeError::Field("integer provider bounds")); + } + match kind.as_str() { + "minecraft:uniform" => Ok(Self::Uniform { min, max }), + "minecraft:biased_to_bottom" => Ok(Self::BiasedToBottom { min, max }), + "minecraft:very_biased_to_bottom" => Ok(Self::VeryBiasedToBottom { min, max }), + "minecraft:trapezoid" => { + let plateau = field("plateau")?; + if plateau > max.wrapping_sub(min) { + return Err(DecodeError::Field("integer provider plateau")); + } + Ok(Self::Trapezoid { min, max, plateau }) + } + "minecraft:clamped" => Ok(Self::Clamped { + source: Box::new(Self::decode( + required(&object, "source")?, + depth + 1, + remaining, + )?), + min, + max, + }), + _ => Err(DecodeError::Field("integer provider type")), + } + } + pub fn bounds(&self) -> [i32; 2] { + match self { + Self::Weighted(list) => { + list.entries() + .iter() + .fold([i32::MAX, i32::MIN], |bounds, (provider, _)| { + let next = provider.bounds(); + [bounds[0].min(next[0]), bounds[1].max(next[1])] + }) + } + Self::Constant(value) => [*value; 2], + Self::Uniform { min, max } + | Self::BiasedToBottom { min, max } + | Self::VeryBiasedToBottom { min, max } + | Self::Trapezoid { min, max, .. } => [*min, *max], + Self::Clamped { source, min, max } => { + let bounds = source.bounds(); + [(*min).max(bounds[0]), (*max).min(bounds[1])] + } + } + } + pub fn sample(&self, random: &mut impl RandomSource) -> Result { + match self { + Self::Weighted(list) => list.sample(random)?.sample(random), + Self::Constant(value) => Ok(*value), + Self::Uniform { min, max } => random.next_int_between_inclusive(*min, *max), + Self::BiasedToBottom { min, max } | Self::VeryBiasedToBottom { min, max } => { + let mut value = random.next_int_bound(max.wrapping_sub(*min).wrapping_add(1))?; + value = random.next_int_bound(value.wrapping_add(1))?; + if matches!(self, Self::VeryBiasedToBottom { .. }) { + value = random.next_int_bound(value.wrapping_add(1))?; + } + Ok(min.wrapping_add(value)) + } + Self::Trapezoid { min, max, plateau } => { + if *plateau == 0 && *max == min.wrapping_neg() { + let left = random.next_int_bound(max.wrapping_add(1))?; + let right = random.next_int_bound(max.wrapping_add(1))?; + return Ok(left.wrapping_sub(right)); + } + let range = max.wrapping_sub(*min); + if *plateau == range { + return random.next_int_between_inclusive(*min, *max); + } + let slope = range.wrapping_sub(*plateau) / 2; + let middle = range.wrapping_sub(slope); + let left = random.next_int_between_inclusive(0, middle)?; + let right = random.next_int_between_inclusive(0, slope)?; + Ok(min.wrapping_add(left).wrapping_add(right)) + } + Self::Clamped { source, min, max } => { + let value = source.sample(random)?; + Ok(if value < *min { *min } else { value.min(*max) }) + } + } + } +} +fn float(raw: &RawValue) -> Result { + number_text(raw)? + .parse() + .map_err(|_| DecodeError::Field("float provider number")) +} +fn kind(object: &Object) -> Result { + identifier(&serde_json::from_str::( + required(object, "type")?.get(), + )?) +} diff --git a/crates/horizon-world/src/worldgen/weighted.rs b/crates/horizon-world/src/worldgen/weighted.rs new file mode 100644 index 000000000..c5149c8dc --- /dev/null +++ b/crates/horizon-world/src/worldgen/weighted.rs @@ -0,0 +1,105 @@ +//! Weighted choices with vanilla draw consumption and ordered entries. +use super::{DecodeError, Object, int_range, required}; +use horizon_core::random::{InvalidBound, RandomSource}; +use serde_json::value::RawValue; + +#[derive(Clone, Debug)] +pub struct WeightedList { + entries: Vec<(T, i32)>, + cumulative: Vec, + total: i32, +} +impl WeightedList { + /// Zero weights are retained. A positive total no greater than i32::MAX is + /// required, and lists are bounded to 8192 entries. + pub fn new(entries: Vec<(T, i32)>) -> Result { + Self::build(entries, false) + } + fn build(entries: Vec<(T, i32)>, allow_empty: bool) -> Result { + if entries.len() > 8192 { + return Err(DecodeError::Field("weighted list size")); + } + let mut total = 0_i32; + let mut cumulative = Vec::with_capacity(entries.len()); + for (_, weight) in &entries { + if *weight < 0 { + return Err(DecodeError::Field("negative weight")); + } + total = total + .checked_add(*weight) + .ok_or(DecodeError::Field("total weight"))?; + cumulative.push(total); + } + if total == 0 && !allow_empty { + return Err(DecodeError::Field("empty weighted list")); + } + Ok(Self { + entries, + cumulative, + total, + }) + } + pub fn entries(&self) -> &[(T, i32)] { + &self.entries + } + pub fn sample(&self, random: &mut impl RandomSource) -> Result<&T, InvalidBound> { + // Even a singleton with total weight one consumes a bounded draw. + let index = random.next_int_bound(self.total)?; + let entry = self.cumulative.partition_point(|end| *end <= index); + Ok(&self.entries[entry].0) + } + pub(crate) fn decode( + raw: &RawValue, + decode: impl FnMut(&RawValue) -> Result, + ) -> Result { + Self::decode_inner(raw, decode, false) + } + fn decode_inner( + raw: &RawValue, + mut decode: impl FnMut(&RawValue) -> Result, + allow_empty: bool, + ) -> Result { + let entries: Vec> = serde_json::from_str(raw.get())?; + if entries.len() > 8192 { + return Err(DecodeError::Field("weighted list size")); + } + Self::build( + entries + .iter() + .map(|raw| { + let object: Object = serde_json::from_str(raw.get())?; + let data = decode(required(&object, "data")?)?; + let weight = int_range(required(&object, "weight")?, "weight", 0, i32::MAX)?; + Ok((data, weight)) + }) + .collect::>()?, + allow_empty, + ) + } +} + +/// Optional choices preserve zero-weight entries without weakening the positive +/// total invariant required by integer and height providers. +#[derive(Clone, Debug)] +pub struct OptionalWeightedList(WeightedList); +impl OptionalWeightedList { + pub fn new(entries: Vec<(T, i32)>) -> Result { + WeightedList::build(entries, true).map(Self) + } + pub fn entries(&self) -> &[(T, i32)] { + self.0.entries() + } + pub fn sample(&self, random: &mut impl RandomSource) -> Result, InvalidBound> { + if self.0.total == 0 { + Ok(None) + } else { + self.0.sample(random).map(Some) + } + } + pub(crate) fn decode( + raw: &RawValue, + decode: impl FnMut(&RawValue) -> Result, + ) -> Result { + WeightedList::decode_inner(raw, decode, true).map(Self) + } +} diff --git a/crates/horizon-world/tests/biome_data.rs b/crates/horizon-world/tests/biome_data.rs new file mode 100644 index 000000000..51be40cfc --- /dev/null +++ b/crates/horizon-world/tests/biome_data.rs @@ -0,0 +1,91 @@ +use horizon_core::{ + density::{ConstantSampler, DensitySampler, GradientSampler, SamplerContext, TilingMode}, + geometry::Axis, +}; +use horizon_world::worldgen::{ + biome::{BiomeError, MultiNoiseBiomeSource}, + climate::ClimateSampler, +}; +use std::sync::Arc; + +fn fixture() -> MultiNoiseBiomeSource { + MultiNoiseBiomeSource::from_quantized_json( + r#"[ + {"coordinates":[[-10,-10],[0,0],[0,0],[0,0],[0,0],[0,0]],"offset":0,"biome":"left"}, + {"coordinates":[[10,10],[0,0],[0,0],[0,0],[0,0],[0,0]],"offset":0,"biome":"right"} + ]"#, + ) + .unwrap() +} + +#[test] +fn scalar_and_prepared_queries_share_ties_and_reject_outside_volume() { + let fields: [Arc; 6] = + std::array::from_fn(|i| -> Arc { + if i == 0 { + Arc::new(GradientSampler::new( + Axis::X, + TilingMode::ClampToEdge, + -4, + 4, + -0.001, + 0.001, + )) + } else { + Arc::new(ConstantSampler(0.)) + } + }); + let climate = ClimateSampler::new(fields); + let source = fixture(); + let mut resolver = source.resolver(&climate); + let mut context = SamplerContext::cached(); + assert_eq!( + resolver.sample(&mut context, [1, 0, 0]).unwrap(), + "minecraft:right" + ); + let volume = resolver + .prepare_volume(&mut context, [-1, 0, 0], [3, 2, 2]) + .unwrap(); + assert_eq!( + resolver.sample_prepared(&volume, [0, 0, 0]).unwrap(), + "minecraft:right" + ); + assert_eq!( + source + .resolver(&climate) + .sample_prepared(&volume, [0, 0, 0]) + .unwrap(), + "minecraft:left" + ); + assert!(matches!( + resolver.sample_prepared(&volume, [-2, 1, 1]), + Err(BiomeError::OutsideVolume) + )); + assert!(matches!( + resolver.sample_prepared(&volume, [2, 0, 0]), + Err(BiomeError::OutsideVolume) + )); + assert_eq!( + resolver.sample_prepared(&volume, [-1, 1, 1]).unwrap(), + "minecraft:left" + ); + assert_eq!( + resolver.sample(&mut context, [0, 0, 0]).unwrap(), + "minecraft:left" + ); +} + +#[test] +fn quantized_import_rejects_malformed_dimensions_numbers_and_identifiers() { + for json in [ + "[]", + r#"[{"coordinates":[[0,0]],"offset":0,"biome":"left"}]"#, + r#"[{"coordinates":[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],"offset":0.5,"biome":"left"}]"#, + r#"[{"coordinates":[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],"offset":0,"biome":"UPPER"}]"#, + ] { + assert!( + MultiNoiseBiomeSource::from_quantized_json(json).is_err(), + "{json}" + ); + } +} diff --git a/crates/horizon-world/tests/biome_predicate_bounds.rs b/crates/horizon-world/tests/biome_predicate_bounds.rs new file mode 100644 index 000000000..5910ebbcf --- /dev/null +++ b/crates/horizon-world/tests/biome_predicate_bounds.rs @@ -0,0 +1,39 @@ +use horizon_world::worldgen::{biome::BiomeId, biome_predicate::BiomePredicateBindings}; +use std::collections::BTreeMap; +#[test] +fn biome_registry_identity_and_holder_set_bounds() { + let names = BTreeMap::from([ + ("minecraft:plains".into(), BiomeId(0)), + ("minecraft:desert".into(), BiomeId(1)), + ]); + let tags = BTreeMap::from([ + ("horizon:empty".into(), vec![]), + ( + "horizon:both".into(), + vec!["plains".into(), "desert".into(), "plains".into()], + ), + ]); + let bindings = BiomePredicateBindings::new(&names, &tags).unwrap(); + assert!( + bindings + .resolve(r##""#horizon:empty""##) + .unwrap() + .is_empty() + ); + assert_eq!(bindings.resolve(r##""#horizon:both""##).unwrap().len(), 2); + assert!(bindings.resolve(r##"["#horizon:both"]"##).is_err()); + assert!( + bindings + .resolve(&serde_json::to_string(&vec!["plains"; 8193]).unwrap()) + .is_err() + ); + let duplicate = BTreeMap::from([("plains".into(), BiomeId(0)), ("desert".into(), BiomeId(0))]); + assert!(BiomePredicateBindings::new(&duplicate, &tags).is_err()); + let duplicate = BTreeMap::from([ + ("plains".into(), BiomeId(0)), + ("minecraft:plains".into(), BiomeId(1)), + ]); + assert!(BiomePredicateBindings::new(&duplicate, &BTreeMap::new()).is_err()); + let unknown = BTreeMap::from([("tag".into(), vec!["missing".into()])]); + assert!(BiomePredicateBindings::new(&names, &unknown).is_err()); +} diff --git a/crates/horizon-world/tests/biome_region.rs b/crates/horizon-world/tests/biome_region.rs new file mode 100644 index 000000000..13afd9533 --- /dev/null +++ b/crates/horizon-world/tests/biome_region.rs @@ -0,0 +1,40 @@ +use horizon_core::position::ChunkPos; +use horizon_world::worldgen::biome_chunk::{BiomeChunk, BiomeRegion, BiomeRegionError}; +#[test] +fn resident_biomes_track_replacement_fills_and_reject_ambiguous_chunks() { + let p = ChunkPos::new(-1, 1); + let mut chunk = BiomeChunk::new(p, -64, 32, 7).unwrap(); + chunk + .fill(-64, -33, |[x, y, z]| { + Ok::<_, ()>(x.wrapping_add(y).wrapping_add(z).rem_euclid(3)) + }) + .unwrap(); + assert!(matches!( + BiomeRegion::new(vec![chunk.clone(), chunk.clone()], 0), + Err(BiomeRegionError::InvalidChunks) + )); + assert!(matches!( + BiomeRegion::new( + vec![ + chunk.clone(), + BiomeChunk::new(ChunkPos::new(0, 0), 0, 32, 0).unwrap() + ], + 0 + ), + Err(BiomeRegionError::InvalidChunks) + )); + let mut region = BiomeRegion::new(vec![chunk], 0).unwrap(); + assert_eq!(region.present_in_chunk(p).unwrap(), vec![0, 1, 2]); + region + .chunk_mut(p) + .unwrap() + .fill(-64, -33, |_| Ok::<_, ()>(9)) + .unwrap(); + assert_eq!(region.present_in_chunk(p).unwrap(), vec![9]); + assert_eq!(region.noise_biome([-1, i32::MIN, 4]).unwrap(), &9); + assert_eq!(region.noise_biome([-1, i32::MAX, 4]).unwrap(), &9); + assert!(matches!( + region.noise_biome([0, 0, 4]), + Err(BiomeRegionError::MissingChunk(_)) + )); +} diff --git a/crates/horizon-world/tests/block_predicate_bounds.rs b/crates/horizon-world/tests/block_predicate_bounds.rs new file mode 100644 index 000000000..fc7e07ef6 --- /dev/null +++ b/crates/horizon-world/tests/block_predicate_bounds.rs @@ -0,0 +1,92 @@ +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::{ + heightmap::HeightmapType, + worldgen::{ + anchor::WorldGenerationContext, + block_predicate::BlockPredicate, + placement::{PlacementContext, PlacementError, PlacementModifier, PlacementQueryError}, + }, +}; +struct UnboundedWorld(usize); +impl PlacementContext for UnboundedWorld { + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new(0, 16, 8) + } + fn min_y(&mut self) -> Result { + Ok(i32::MIN) + } + fn max_y(&mut self) -> Result { + Ok(i32::MAX) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + unreachable!() + } + fn outside_build_height(&mut self, _: i32) -> Result { + self.0 += 1; + Ok(false) + } +} +#[test] +fn directly_constructed_scans_share_predicate_work_budget() { + let scan = PlacementModifier::EnvironmentScan { + upwards: true, + target: BlockPredicate::Not(Box::new(BlockPredicate::True)), + allowed: BlockPredicate::True, + max_steps: i32::MAX, + }; + let mut world = UnboundedWorld(0); + let mut random = LegacyRandom::new(1); + let mut expected = random.clone(); + let result = scan.modify_in( + &mut world, + &mut random, + [0, i32::MAX, 0], + |_, _| -> Result<(), ()> { panic!("false target must not emit") }, + ); + assert!(matches!( + result, + Err(PlacementError::World(PlacementQueryError::WorkLimit)) + )); + assert!(world.0 > 0 && world.0 < 65536); + assert_eq!(random.next_long(), expected.next_long()); +} +#[test] +fn predicate_trees_share_decode_and_evaluation_budgets() { + let leaf = r#"{"type":"true"}"#; + let branch = format!( + r#"{{"type":"all_of","predicates":[{}]}}"#, + vec![leaf; 256].join(",") + ); + let tree = format!( + r#"{{"type":"all_of","predicates":[{}]}}"#, + vec![branch; 256].join(",") + ); + assert!(BlockPredicate::from_json(&tree).is_err()); + let tree = BlockPredicate::All(vec![ + BlockPredicate::All(vec![BlockPredicate::True; 256]); + 256 + ]); + assert!(matches!( + tree.test(&mut UnboundedWorld(0), [0; 3]), + Err(PlacementQueryError::WorkLimit) + )); +} + +#[test] +fn oversized_volume_keeps_early_exit_and_bounds_total_work() { + let mut world = UnboundedWorld(0); + let volume = |predicate| BlockPredicate::Volume { + min: [i32::MIN; 3], + max: [i32::MAX; 3], + predicate: Box::new(predicate), + }; + assert!( + !volume(BlockPredicate::Not(Box::new(BlockPredicate::True))) + .test(&mut world, [0; 3]) + .unwrap() + ); + assert!(matches!( + volume(BlockPredicate::True).test(&mut world, [0; 3]), + Err(PlacementQueryError::WorkLimit) + )); +} diff --git a/crates/horizon-world/tests/carver_generation.rs b/crates/horizon-world/tests/carver_generation.rs new file mode 100644 index 000000000..688daea45 --- /dev/null +++ b/crates/horizon-world/tests/carver_generation.rs @@ -0,0 +1,89 @@ +use horizon_core::position::ChunkPos; +use horizon_world::worldgen::{ + anchor::WorldGenerationContext, + carver::{CarverCatalog, MaskGenerationError, generate_carving_mask}, +}; +use std::{collections::BTreeMap, sync::Arc}; + +#[test] +fn origin_order_wraps_coordinates_and_upgrading_changes_the_ceiling() { + let target = ChunkPos::new(i32::MAX, i32::MIN); + for upgrading in [false, true] { + let mut visited = Vec::new(); + let mask = generate_carving_mask( + 0, + target, + WorldGenerationContext::new(-64, 384, 63), + upgrading, + |origin| { + visited.push(origin); + Ok::<_, ()>(&[]) + }, + ) + .unwrap(); + assert!(mask.is_empty()); + assert_eq!(mask.min_y(), -63); + assert_eq!(mask.max_y(), if upgrading { 319 } else { 312 }); + let expected: Vec<_> = (-8..=8) + .flat_map(|dx| { + (-8..=8).map(move |dz| { + ChunkPos::new(target.x.wrapping_add(dx), target.z.wrapping_add(dz)) + }) + }) + .collect(); + assert_eq!(visited, expected); + } +} + +#[test] +fn invalid_bounds_skip_the_source_and_source_failures_stop_immediately() { + let target = ChunkPos::new(0, 0); + let invalid = generate_carving_mask( + 0, + target, + WorldGenerationContext::new(0, 8, 0), + false, + |_| -> Result<_, ()> { panic!("invalid bounds must precede biome queries") }, + ); + assert!(matches!(invalid, Err(MaskGenerationError::Mask(_)))); + let mut calls = 0; + let failed = generate_carving_mask( + 0, + target, + WorldGenerationContext::new(0, 16, 0), + false, + |_| { + calls += 1; + if calls == 19 { + Err("biome failure") + } else { + Ok(&[]) + } + }, + ); + assert!(matches!( + failed, + Err(MaskGenerationError::Source("biome failure")) + )); + assert_eq!(calls, 19); +} + +#[test] +fn holder_lists_preserve_duplicate_identity_and_reject_unknown_names() { + let definition = r#"{"type":"cave","probability":1,"y":{"absolute":8},"count":0,"thickness":1,"room_vertical_radius_multiplier":1,"horizontal_radius_multiplier":1,"vertical_radius_multiplier":1,"floor_level":-1}"#; + let catalog = + CarverCatalog::from_json(&BTreeMap::from([("test".into(), definition.into())])).unwrap(); + let entries = catalog.decode_set(r#"["test","minecraft:test"]"#).unwrap(); + assert_eq!(entries.len(), 2); + assert!(Arc::ptr_eq(&entries[0], &entries[1])); + assert_eq!(catalog.decode_set(definition).unwrap().len(), 1); + assert!(catalog.decode_set("[]").unwrap().is_empty()); + assert!(catalog.decode_set(r#"["test","missing"]"#).is_err()); + assert!( + CarverCatalog::from_json(&BTreeMap::from([ + ("test".into(), definition.into()), + ("minecraft:test".into(), definition.into()), + ])) + .is_err() + ); +} diff --git a/crates/horizon-world/tests/carving_stage.rs b/crates/horizon-world/tests/carving_stage.rs new file mode 100644 index 000000000..3af6d4570 --- /dev/null +++ b/crates/horizon-world/tests/carving_stage.rs @@ -0,0 +1,172 @@ +use horizon_core::{ + carving::CarvingMask, + density::{ConstantSampler, SamplerContext}, + position::ChunkPos, + random::{RandomSource, XoroshiroRandom}, +}; +use horizon_world::{ + DATA_VERSION, + heightmap::HeightmapState, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + worldgen::{ + anchor::WorldGenerationContext, + aquifer::AquiferError, + carving::{CarvingBlocks, apply_carving_mask}, + material_condition::{MaterialRule, MaterialSurfaceQueries}, + material_stage::TopMaterialInputs, + terrain::{TerrainAquifer, TerrainBlockStates, TerrainChunk}, + }, +}; +use std::{collections::BTreeSet, sync::Arc}; +#[derive(Clone, Copy)] +struct State(u32); +impl HeightmapState for State { + fn is_air(self) -> bool { + self.0 < 2 + } + fn is_air_block(self) -> bool { + self.0 == 0 + } + fn has_fluid(self) -> bool { + self.0 == 3 + } + fn blocks_motion_in_heightmap(self) -> bool { + self.0 >= 2 && self.0 != 3 + } + fn blocks_motion_in_heightmap_no_leaves(self) -> bool { + self.blocks_motion_in_heightmap() + } +} +struct Properties; +impl TerrainBlockStates for Properties { + type State = State; + fn heightmap_state(&self, id: BlockStateId) -> State { + State(id.0) + } +} +struct Surface; +impl MaterialSurfaceQueries for Surface { + fn surface_depth(&mut self, _: i32, _: i32) -> i32 { + 1 + } + fn surface_secondary(&mut self, _: i32, _: i32) -> f64 { + 0. + } +} +struct Aquifer(Vec); +impl TerrainAquifer for Aquifer { + fn compute_substance( + &mut self, + _: &mut SamplerContext, + [_x, y, _z]: [i32; 3], + density: f64, + ) -> Result, AquiferError> { + assert_eq!(density.to_bits(), 0); + self.0.push(y); + match y { + 8 => Ok(None), + 7 => Ok(Some(BlockStateId(0))), + _ => Err(AquiferError::OutsideGrid), + } + } + fn should_schedule_fluid_update(&self) -> bool { + false + } +} +fn registry() -> BlockRegistry { + let names = [ + "minecraft:air", + "minecraft:void_air", + "minecraft:stone", + "minecraft:water", + "minecraft:grass_block", + "minecraft:mycelium", + "minecraft:dirt", + ]; + BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List( + names + .iter() + .map(|name| Tag::compound([("id", Tag::String((*name).into()))])) + .collect(), + ), + ), + ( + "defaults", + Tag::Compound( + names + .iter() + .enumerate() + .map(|(id, name)| ((*name).into(), Tag::Int(id as i32))) + .collect(), + ), + ), + ])) + .unwrap() +} +#[test] +fn filters_and_uncarvable_blocks_precede_aquifers_and_failures_keep_surface_restoration() { + let registry = registry(); + for scenario in 0..3 { + let uncarvable = if scenario == 2 { + BTreeSet::from(["minecraft:grass_block".to_owned()]) + } else { + BTreeSet::new() + }; + let blocks = CarvingBlocks::from_registry(®istry, &uncarvable).unwrap(); + let mut chunk = + TerrainChunk::new(ChunkPos::new(-1, 2), 0, 16, ®istry, Properties).unwrap(); + for (y, state) in [(8, 4), (7, 2), (6, 6)] { + chunk.set_block_raw(0, y, 0, BlockStateId(state)).unwrap(); + } + let mut mask = CarvingMask::new(0, 15).unwrap(); + for y in 6..=8 { + mask.carve(0, y, 0).unwrap(); + } + let mut context = SamplerContext::cached(); + let mut aquifer = Aquifer(Vec::new()); + let mut filtered = Vec::new(); + let result = apply_carving_mask( + &mut chunk, + &mask, + MaterialRule::Block(BlockStateId(3)), + TopMaterialInputs:: { + generation: WorldGenerationContext::new(0, 16, 8), + root: XoroshiroRandom::new(0).fork_positional(), + surface: Surface, + preliminary_surface: Arc::new(ConstantSampler(0.)), + density_context: &mut context, + }, + &mut aquifer, + &blocks, + |position| { + filtered.push(position); + scenario != 1 || position[1] != 8 + }, + ); + assert!(result.is_err()); + assert_eq!(filtered, [[0, 8, 0], [0, 7, 0], [0, 6, 0]]); + assert_eq!( + aquifer.0, + if scenario == 0 { + vec![8, 7, 6] + } else { + vec![7, 6] + } + ); + assert_eq!(chunk.block(0, 8, 0), BlockStateId(4)); + assert_eq!(chunk.block(0, 7, 0), BlockStateId(0)); + assert_eq!( + chunk.block(0, 6, 0), + BlockStateId(if scenario == 0 { 3 } else { 6 }) + ); + assert_eq!( + chunk.postprocessing()[0], + if scenario == 0 { vec![6 << 4] } else { vec![] } + ); + } +} diff --git a/crates/horizon-world/tests/collision_data.rs b/crates/horizon-world/tests/collision_data.rs new file mode 100644 index 000000000..35ec3c569 --- /dev/null +++ b/crates/horizon-world/tests/collision_data.rs @@ -0,0 +1,157 @@ +use horizon_world::{ + DATA_VERSION, + chunk::BlockSection, + collision::CachedCollisionRegistry, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, +}; + +fn fixture() -> (Tag, Tag) { + let states = vec![ + Tag::String("minecraft:air".into()), + Tag::String("minecraft:stone".into()), + Tag::String("minecraft:context".into()), + ]; + let registry = Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", Tag::List(states.clone())), + ( + "defaults", + Tag::compound([ + ("minecraft:air", Tag::Int(0)), + ("minecraft:stone", Tag::Int(1)), + ("minecraft:context", Tag::Int(2)), + ]), + ), + ]); + let empty = Tag::compound([ + ("x", Tag::LongArray(vec![0])), + ("y", Tag::LongArray(vec![0])), + ("z", Tag::LongArray(vec![0])), + ("occupied", Tag::ByteArray(vec![])), + ("cube", Tag::Byte(0)), + ("cube_axes", Tag::Byte(0)), + ("discrete_min", Tag::IntArray(vec![0; 3])), + ("discrete_max", Tag::IntArray(vec![0; 3])), + ]); + let coords = Tag::LongArray(vec![0, 1.0f64.to_bits() as i64]); + let block = Tag::compound([ + ("x", coords.clone()), + ("y", coords.clone()), + ("z", coords), + ("occupied", Tag::ByteArray(vec![1])), + ("cube", Tag::Byte(1)), + ("cube_axes", Tag::Byte(7)), + ("discrete_min", Tag::IntArray(vec![0; 3])), + ("discrete_max", Tag::IntArray(vec![1; 3])), + ]); + let collision = Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", Tag::List(states)), + ("shapes", Tag::List(vec![empty, block])), + ("cached_shapes", Tag::IntArray(vec![0, 1, -1])), + ]); + (registry, collision) +} + +#[test] +fn empty_cached_and_context_states_are_distinct() { + let (registry_tag, collision_tag) = fixture(); + let registry = BlockRegistry::from_nbt(®istry_tag).unwrap(); + let collision = CachedCollisionRegistry::from_nbt(&collision_tag, ®istry).unwrap(); + assert_eq!(collision.cached_state_count(), 2); + assert_eq!(collision.shape_count(), 2); + assert!( + collision + .cached_shape(BlockStateId(0)) + .unwrap() + .unwrap() + .is_empty() + ); + assert!( + !collision + .cached_shape(BlockStateId(1)) + .unwrap() + .unwrap() + .is_empty() + ); + assert!(collision.cached_shape(BlockStateId(2)).unwrap().is_none()); + assert!(collision.cached_shape(BlockStateId(3)).is_err()); + let mut section = BlockSection::uniform(BlockStateId(0), ®istry).unwrap(); + section.set(4095, BlockStateId(1)).unwrap(); + assert!( + !collision + .section_shape(§ion, 4095) + .unwrap() + .unwrap() + .is_empty() + ); + assert!(collision.section_shape(§ion, 4096).is_err()); + let different = BlockRegistry::from_nbt(®istry_tag).unwrap(); + let foreign_section = BlockSection::uniform(BlockStateId(0), &different).unwrap(); + assert!(collision.section_shape(&foreign_section, 0).is_err()); +} + +#[test] +fn invalid_imports_fail_before_collision_queries() { + let (registry_tag, valid) = fixture(); + let registry = BlockRegistry::from_nbt(®istry_tag).unwrap(); + for (field, tag) in [ + ("DataVersion", Tag::Int(0)), + ("cached_shapes", Tag::IntArray(vec![0, 1])), + ("cached_shapes", Tag::IntArray(vec![0, 2, -1])), + ("cached_shapes", Tag::IntArray(vec![0, 1, -2])), + ] { + let mut bad = valid.clone(); + *bad.get_mut(field).unwrap() = tag; + assert!(CachedCollisionRegistry::from_nbt(&bad, ®istry).is_err()); + } + let mut bad = valid.clone(); + let Some(Tag::List(states)) = bad.get_mut("states") else { + unreachable!() + }; + states.swap(0, 1); + assert!(CachedCollisionRegistry::from_nbt(&bad, ®istry).is_err()); + for (field, tag) in [ + ("cube", Tag::Byte(2)), + ("cube_axes", Tag::Byte(8)), + ("cube_axes", Tag::Byte(0)), + ("occupied", Tag::ByteArray(vec![2])), + ("discrete_min", Tag::IntArray(vec![0, 0])), + ("discrete_min", Tag::IntArray(vec![-1, 0, 0])), + ("discrete_max", Tag::IntArray(vec![1, 0, 1])), + ("occupied", Tag::ByteArray(vec![])), + ("x", Tag::LongArray(vec![0, 0])), + ("x", Tag::LongArray(vec![0, f64::NAN.to_bits() as i64])), + ("x", Tag::LongArray(vec![0, 0.5f64.to_bits() as i64])), + ] { + let mut bad = valid.clone(); + let Some(Tag::List(shapes)) = bad.get_mut("shapes") else { + unreachable!() + }; + *shapes[1].get_mut(field).unwrap() = tag; + assert!(CachedCollisionRegistry::from_nbt(&bad, ®istry).is_err()); + } +} + +#[test] +fn equal_grids_share_storage_without_collapsing_shape_identities() { + let (registry_tag, mut collision_tag) = fixture(); + let registry = BlockRegistry::from_nbt(®istry_tag).unwrap(); + let Some(Tag::List(shapes)) = collision_tag.get_mut("shapes") else { + unreachable!() + }; + shapes.push(shapes[1].clone()); + *collision_tag.get_mut("cached_shapes").unwrap() = Tag::IntArray(vec![0, 1, 2]); + let collision = CachedCollisionRegistry::from_nbt(&collision_tag, ®istry).unwrap(); + assert_eq!(collision.shape_count(), 3); + assert_eq!(collision.unique_grid_count(), 2); + let first = collision.cached_shape(BlockStateId(1)).unwrap().unwrap(); + let second = collision.cached_shape(BlockStateId(2)).unwrap().unwrap(); + assert!(!first.same_identity(second)); + assert!(std::ptr::eq( + first.boxes().as_ptr(), + second.boxes().as_ptr() + )); + assert!(first.same_identity(collision.cached_shape(BlockStateId(1)).unwrap().unwrap())); +} diff --git a/crates/horizon-world/tests/decoration_bounds.rs b/crates/horizon-world/tests/decoration_bounds.rs new file mode 100644 index 000000000..2ba2eb885 --- /dev/null +++ b/crates/horizon-world/tests/decoration_bounds.rs @@ -0,0 +1,35 @@ +use horizon_core::position::ChunkPos; +use horizon_world::worldgen::{ + decoration::{DecorationBiome, DecorationError, DecorationWorld, FeatureDecorationPlan}, + feature_sort::{FeatureIdentity, FeatureSortError}, +}; +struct NoChunks; +impl DecorationWorld for NoChunks { + type Error = (); + fn min_section_y(&mut self) -> Result { + Ok(-4) + } + fn chunk_biomes(&mut self, _: ChunkPos) -> Result, ()> { + panic!("unbounded neighborhood must be rejected before reading chunks") + } + fn set_currently_generating(&mut self, _: Option) -> Result<(), ()> { + panic!("invalid neighborhood must not start or finish decoration") + } +} +#[test] +fn invalid_registry_identity_and_unbounded_neighborhood_are_rejected() { + assert!(matches!( + FeatureDecorationPlan::new(vec![ + (DecorationBiome(0), vec![]), + (DecorationBiome(0), vec![]) + ]), + Err(FeatureSortError::DuplicateBiome) + )); + let plan = FeatureDecorationPlan::new(vec![]).unwrap(); + for chunk in [ChunkPos::new(i32::MIN, 0), ChunkPos::new(0, i32::MAX)] { + let result = plan.decorate_features(&mut NoChunks, chunk, 0, |_, _, _, _, _| { + panic!("invalid neighborhood must not place features") + }); + assert!(matches!(result, Err(DecorationError::WorkLimit))); + } +} diff --git a/crates/horizon-world/tests/feature_catalog.rs b/crates/horizon-world/tests/feature_catalog.rs new file mode 100644 index 000000000..769ce8bbe --- /dev/null +++ b/crates/horizon-world/tests/feature_catalog.rs @@ -0,0 +1,62 @@ +use horizon_world::worldgen::{feature_catalog::FeatureCatalog, tags::TagDefinitions}; +use std::collections::BTreeMap; +fn map(values: &[(&str, &str)]) -> BTreeMap { + values + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() +} +#[test] +fn canonical_duplicates_cycles_and_unknown_unselected_children_fail() { + let tags = TagDefinitions::default(); + assert!( + FeatureCatalog::from_resources( + &map(&[ + ("a", r#"{"type":"no_op"}"#), + ("minecraft:a", r#"{"type":"no_op"}"#) + ]), + &BTreeMap::new(), + &tags + ) + .is_err() + ); + let features = map(&[ + ( + "horizon:loop", + r#"{"type":"sequence","features":["horizon:loop"]}"#, + ), + ("horizon:unused", r#"{"type":"not_implemented"}"#), + ]); + let placed = map(&[( + "horizon:loop", + r#"{"feature":"horizon:loop","placement":[]}"#, + )]); + let catalog = FeatureCatalog::from_resources(&features, &placed, &tags).unwrap(); + assert!(catalog.feature(r#""horizon:loop""#).is_err()); + assert!(catalog.placed_feature(r#""horizon:loop""#).is_err()); + assert!(catalog.feature(r#"{"type":"no_op"}"#).is_ok()); + assert!(catalog.feature(r#"{"type":"weighted_random_selector","features":[{"data":"horizon:missing","weight":0}]}"#).is_err()); +} +#[test] +fn shared_reference_expansion_is_bounded_before_building_a_large_tree() { + let leaf = r#"{"feature":{"type":"no_op"},"placement":[]}"#; + let branch = format!( + r#"{{"type":"sequence","features":[{}]}}"#, + vec![r#""horizon:leaf""#; 8192].join(",") + ); + let features = BTreeMap::from([("horizon:branch".into(), branch)]); + let placed = map(&[ + ("horizon:leaf", leaf), + ( + "horizon:branch", + r#"{"feature":"horizon:branch","placement":[]}"#, + ), + ]); + let catalog = + FeatureCatalog::from_resources(&features, &placed, &TagDefinitions::default()).unwrap(); + let root = format!( + r#"{{"type":"sequence","features":[{}]}}"#, + [r#""horizon:branch""#; 9].join(",") + ); + assert!(catalog.feature(&root).is_err()); +} diff --git a/crates/horizon-world/tests/feature_graph_bounds.rs b/crates/horizon-world/tests/feature_graph_bounds.rs new file mode 100644 index 000000000..63da02b19 --- /dev/null +++ b/crates/horizon-world/tests/feature_graph_bounds.rs @@ -0,0 +1,89 @@ +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::{ + heightmap::HeightmapType, + registry::BlockStateId, + worldgen::{ + anchor::WorldGenerationContext, + feature::{FeatureBlocks, FeatureWorld}, + feature_graph::{FeatureDefinition, FeatureExecutionError, PlacedFeatureDefinition}, + placement::{PlacementContext, PlacementQueryError}, + }, +}; +struct World; +impl PlacementContext for World { + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new(0, 16, 8) + } + fn min_y(&mut self) -> Result { + Ok(0) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + panic!("no-op graph queried height") + } +} +impl FeatureWorld for World { + type Error = std::convert::Infallible; + fn block(&mut self, _: [i32; 3]) -> Result { + panic!("no-op graph read blocks") + } + fn set_block(&mut self, _: [i32; 3], _: BlockStateId, _: i32) -> Result { + panic!("no-op graph wrote blocks") + } +} +fn blocks() -> FeatureBlocks { + FeatureBlocks { + air: BlockStateId(0), + stone: BlockStateId(1), + cobblestone: BlockStateId(2), + end_stone: BlockStateId(3), + obsidian: BlockStateId(4), + } +} +#[test] +fn large_graphs_fail_at_a_shared_visit_bound_without_drawing_randomness() { + let leaf = PlacedFeatureDefinition { + feature: Box::new(FeatureDefinition::NoOp), + placement: vec![], + }; + let branch = PlacedFeatureDefinition { + feature: Box::new(FeatureDefinition::Sequence(vec![leaf; 8192])), + placement: vec![], + }; + let tree = FeatureDefinition::Sequence(vec![branch; 9]); + let mut random = LegacyRandom::new(5); + let mut expected = random.clone(); + assert!(matches!( + tree.place(&mut World, &mut random, [0; 3], blocks()), + Err(FeatureExecutionError::WorkLimit) + )); + assert_eq!(random.next_long(), expected.next_long()); +} +#[test] +fn nested_inline_decoding_rejects_excessive_depth() { + let mut value = String::from(r#"{"type":"no_op"}"#); + for _ in 0..70 { + value = + format!(r#"{{"type":"sequence","features":[{{"feature":{value},"placement":[]}}]}}"#); + } + assert!(FeatureDefinition::from_json(&value).is_err()); +} + +#[test] +fn modifier_expansion_without_leaf_calls_uses_the_shared_graph_budget() { + use horizon_world::worldgen::{placement::PlacementModifier, value_provider::IntProvider}; + let feature = PlacedFeatureDefinition { + feature: Box::new(FeatureDefinition::NoOp), + placement: vec![ + PlacementModifier::Count(IntProvider::Constant(4096)), + PlacementModifier::Count(IntProvider::Constant(4096)), + PlacementModifier::Count(IntProvider::Constant(0)), + ], + }; + let mut random = LegacyRandom::new(5); + let mut expected = random.clone(); + assert!(matches!( + feature.place(&mut World, &mut random, [0; 3], blocks()), + Err(FeatureExecutionError::WorkLimit) + )); + assert_eq!(random.next_long(), expected.next_long()); +} diff --git a/crates/horizon-world/tests/feature_placement.rs b/crates/horizon-world/tests/feature_placement.rs new file mode 100644 index 000000000..8eb9c1af6 --- /dev/null +++ b/crates/horizon-world/tests/feature_placement.rs @@ -0,0 +1,41 @@ +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::worldgen::{ + anchor::WorldGenerationContext, + placement::{FeaturePlacementError, FeaturePlacer, PlacementModifier}, + value_provider::IntProvider, +}; + +#[test] +fn oversized_chains_fail_before_random_draws_or_feature_calls() { + let mut random = LegacyRandom::new(17); + let mut expected = random.clone(); + let mut placer = FeaturePlacer::new(); + let result = placer.place( + &vec![PlacementModifier::InSquare; 1025], + WorldGenerationContext::new(-64, 384, 63), + &mut random, + [0, 0, 0], + |_, _| -> Result { panic!("oversized chain reached feature") }, + ); + assert!(matches!(result, Err(FeaturePlacementError::WorkLimit))); + assert_eq!(random.next_long(), expected.next_long()); +} + +#[test] +fn multiplicative_counts_stop_at_the_shared_work_bound() { + let mut random = LegacyRandom::new(17); + let mut placer = FeaturePlacer::new(); + let mut calls = 0; + let result = placer.place( + &vec![PlacementModifier::Count(IntProvider::Constant(4096)); 2], + WorldGenerationContext::new(-64, 384, 63), + &mut random, + [0, 0, 0], + |_, _| { + calls += 1; + Ok::<_, ()>(true) + }, + ); + assert!(matches!(result, Err(FeaturePlacementError::WorkLimit))); + assert!(calls > 0 && calls < 1 << 20); +} diff --git a/crates/horizon-world/tests/feature_region.rs b/crates/horizon-world/tests/feature_region.rs new file mode 100644 index 000000000..1209a5282 --- /dev/null +++ b/crates/horizon-world/tests/feature_region.rs @@ -0,0 +1,148 @@ +use horizon_core::position::ChunkPos; +use horizon_world::{ + DATA_VERSION, + heightmap::{HeightmapState, HeightmapType}, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + worldgen::{ + anchor::WorldGenerationContext, + feature::FeatureWorld, + feature_region::{RegionError, TerrainFeatureAccess, TerrainRegion}, + placement::PlacementContext, + terrain::{PreLightChunkStage, TerrainBlockStates, TerrainChunk}, + }, +}; +#[derive(Clone, Copy)] +struct State(u32); +impl HeightmapState for State { + fn is_air(self) -> bool { + self.0 < 2 + } + fn is_air_block(self) -> bool { + self.0 == 0 + } + fn has_fluid(self) -> bool { + self.0 == 3 + } + fn blocks_motion_in_heightmap(self) -> bool { + self.0 >= 2 && self.0 != 3 + } + fn blocks_motion_in_heightmap_no_leaves(self) -> bool { + self.blocks_motion_in_heightmap() + } +} +struct Properties; +impl TerrainBlockStates for Properties { + type State = State; + fn heightmap_state(&self, id: BlockStateId) -> State { + State(id.0) + } +} +fn registry() -> BlockRegistry { + let names = [ + "minecraft:air", + "minecraft:void_air", + "minecraft:stone", + "minecraft:water", + "minecraft:grass_block", + "minecraft:mycelium", + "minecraft:dirt", + ]; + BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List( + names + .iter() + .map(|name| Tag::compound([("id", Tag::String((*name).into()))])) + .collect(), + ), + ), + ( + "defaults", + Tag::Compound( + names + .iter() + .enumerate() + .map(|(id, name)| ((*name).into(), Tag::Int(id as i32))) + .collect(), + ), + ), + ])) + .unwrap() +} +#[test] +fn rejects_incompatible_regions_and_routes_negative_chunk_coordinates() { + let other_registry = registry(); + let registry = registry(); + let context = WorldGenerationContext::new(0, 16, 8); + let chunk = + |x, min, reg| TerrainChunk::new(ChunkPos::new(x, 0), min, 16, reg, Properties).unwrap(); + assert!(TerrainRegion::::new(vec![], context).is_err()); + assert!( + TerrainRegion::new( + vec![chunk(0, 0, ®istry), chunk(0, 0, ®istry)], + context + ) + .is_err() + ); + assert!( + TerrainRegion::new( + vec![chunk(0, 0, ®istry), chunk(1, 16, ®istry)], + context + ) + .is_err() + ); + assert!( + TerrainRegion::new( + vec![chunk(0, 0, ®istry), chunk(1, 0, &other_registry)], + context + ) + .is_err() + ); + let mut region = TerrainRegion::new( + vec![chunk(-1, 0, ®istry), chunk(0, 0, ®istry)], + context, + ) + .unwrap(); + region + .set_block_worldgen([-1, 7, 0], BlockStateId(2)) + .unwrap(); + assert_eq!(region.block([-1, 7, 0]).unwrap(), BlockStateId(2)); + assert_eq!(region.block([15, 7, 0]).unwrap(), BlockStateId(0)); + assert!(matches!( + region.set_block_worldgen([16, 7, 0], BlockStateId(2)), + Err(RegionError::MissingChunk([1, 0])) + )); + assert_eq!(region.block([0, 7, 0]).unwrap(), BlockStateId(0)); +} +#[test] +fn write_callback_controls_mutation_and_receives_all_flags() { + let registry = registry(); + let mut chunk = TerrainChunk::new(ChunkPos::new(0, 0), 0, 16, ®istry, Properties).unwrap(); + chunk.set_generation_stage(PreLightChunkStage::Terrain); + let mut region = + TerrainRegion::new(vec![chunk], WorldGenerationContext::new(-16, 32, 8)).unwrap(); + assert_eq!(region.generation(), WorldGenerationContext::new(0, 16, 8)); + assert_eq!(region.height(HeightmapType::WorldSurface, 0, 0).unwrap(), 0); + let mut flags = Vec::new(); + { + let mut world = TerrainFeatureAccess::new( + &mut region, + |region: &mut TerrainRegion<'_, Properties>, p, state, flag| { + flags.push(flag); + if flag == 2 { + return Ok(false); + } + region.set_block_worldgen(p, state)?; + Ok(true) + }, + ); + assert!(!world.set_block([0, 7, 0], BlockStateId(2), 2).unwrap()); + assert_eq!(world.height(HeightmapType::WorldSurface, 0, 0).unwrap(), 0); + assert!(world.set_block([0, 7, 0], BlockStateId(2), 3).unwrap()); + assert_eq!(world.height(HeightmapType::WorldSurface, 0, 0).unwrap(), 8); + } + assert_eq!(flags, [2, 3]); +} diff --git a/crates/horizon-world/tests/feature_sort_bounds.rs b/crates/horizon-world/tests/feature_sort_bounds.rs new file mode 100644 index 000000000..84bbfb05e --- /dev/null +++ b/crates/horizon-world/tests/feature_sort_bounds.rs @@ -0,0 +1,34 @@ +use horizon_world::worldgen::feature_sort::{ + FeatureIdentity, FeatureSortError, build_features_per_step, +}; + +#[test] +fn long_dependency_chains_use_bounded_iterative_traversal() { + let features = (0..50000).map(FeatureIdentity).collect::>(); + let result = build_features_per_step(&[vec![features.clone()]]).unwrap(); + assert_eq!(result[0].features(), features); + assert_eq!(result[0].index(FeatureIdentity(49999)), Some(49999)); + assert_eq!(result[0].index(FeatureIdentity(50000)), None); + assert!(matches!( + build_features_per_step(&[vec![vec![FeatureIdentity(0); 65536]]]), + Err(FeatureSortError::WorkLimit) + )); +} + +#[test] +fn opposite_biome_orders_and_repeated_identity_form_cycles() { + let a = FeatureIdentity(91); + let b = FeatureIdentity(7); + assert!(matches!( + build_features_per_step(&[vec![vec![a, b]], vec![vec![b, a]]]), + Err(FeatureSortError::Cycle) + )); + assert!(matches!( + build_features_per_step(&[vec![vec![a, a]]]), + Err(FeatureSortError::Cycle) + )); + let result = build_features_per_step(&[vec![vec![a], vec![], vec![a, b]]]).unwrap(); + assert_eq!(result[0].features(), [a]); + assert!(result[1].features().is_empty()); + assert_eq!(result[2].features(), [a, b]); +} diff --git a/crates/horizon-world/tests/material_stage.rs b/crates/horizon-world/tests/material_stage.rs new file mode 100644 index 000000000..fa17bf0e9 --- /dev/null +++ b/crates/horizon-world/tests/material_stage.rs @@ -0,0 +1,295 @@ +use horizon_core::{ + density::{ + CachingDensitySampler, ConstantSampler, ContextBoundSampler, DensitySampler, SampleError, + SamplerContext, WorldField, WorldFields, + }, + noise::{DensityVolume, NanRange, Noise}, + position::{BlockPos, ChunkPos}, + random::{RandomSource, XoroshiroRandom}, +}; +use horizon_world::{ + DATA_VERSION, + heightmap::HeightmapState, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + worldgen::{ + anchor::WorldGenerationContext, + material_condition::{ + MaterialCondition, MaterialRule, MaterialRuleError, MaterialSurfaceQueries, + }, + material_extensions::{ExtensionBlocks, ExtensionNoises, MaterialExtensions}, + material_stage::{SurfaceInputs, TopMaterialInputs, build_surface, top_material}, + terrain::{TerrainBlockStates, TerrainChunk}, + }, +}; +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; + +#[derive(Clone, Copy)] +struct State(u32); +impl HeightmapState for State { + fn is_air(self) -> bool { + self.0 < 2 + } + fn is_air_block(self) -> bool { + self.0 == 0 + } + fn has_fluid(self) -> bool { + self.0 == 3 + } + fn blocks_motion_in_heightmap(self) -> bool { + self.0 == 2 + } + fn blocks_motion_in_heightmap_no_leaves(self) -> bool { + self.0 == 2 + } +} +struct Properties; +impl TerrainBlockStates for Properties { + type State = State; + fn heightmap_state(&self, id: BlockStateId) -> State { + State(id.0) + } +} +#[derive(Debug)] +struct Zero; +impl Noise for Zero { + fn range(&self) -> Result<[f32; 2], NanRange> { + Ok([0.; 2]) + } + fn get2(&self, _: f64, _: f64) -> f32 { + 0. + } + fn get3(&self, _: f64, _: f64, _: f64) -> f32 { + 0. + } +} +struct Surface { + calls: usize, + fail_at: Option, +} +impl MaterialSurfaceQueries for Surface { + fn surface_depth(&mut self, _: i32, _: i32) -> i32 { + 1 + } + fn surface_secondary(&mut self, _: i32, _: i32) -> f64 { + 0. + } + fn biome(&mut self, _: BlockPos) -> Result>, MaterialRuleError> { + self.calls += 1; + if self.fail_at == Some(self.calls) { + Err(MaterialRuleError::MissingBiome) + } else { + Ok(Some(Arc::from("minecraft:plains"))) + } + } +} +#[derive(Debug)] +struct Count(Arc); +impl DensitySampler for Count { + fn sample_value(&self, _: &mut SamplerContext, _: [i32; 3]) -> Result { + self.0.fetch_add(1, Ordering::SeqCst); + Ok(42.) + } +} +#[derive(Debug)] +struct Fails; +impl DensitySampler for Fails { + fn sample_value(&self, _: &mut SamplerContext, _: [i32; 3]) -> Result { + Err(SampleError::RecursiveCache) + } +} +fn registry() -> BlockRegistry { + let names = [ + "minecraft:air", + "minecraft:void_air", + "minecraft:stone", + "minecraft:water", + ]; + BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List( + names + .iter() + .map(|name| Tag::compound([("id", Tag::String((*name).into()))])) + .collect(), + ), + ), + ( + "defaults", + Tag::Compound( + names + .iter() + .enumerate() + .map(|(id, name)| ((*name).into(), Tag::Int(id as i32))) + .collect(), + ), + ), + ])) + .unwrap() +} + +#[test] +fn density_context_survives_success_binding_failure_and_partial_chunk_failure() { + let registry = registry(); + for scenario in 0..3 { + let mut chunk = + TerrainChunk::new(ChunkPos::new(0, 0), 0, 16, ®istry, Properties).unwrap(); + chunk.set_block_raw(0, 5, 0, BlockStateId(2)).unwrap(); + chunk.set_block_raw(0, 5, 1, BlockStateId(2)).unwrap(); + let count = Arc::new(AtomicUsize::new(0)); + let cached = CachingDensitySampler::new(0, Arc::new(Count(count.clone()))).unwrap(); + let mut context = SamplerContext::cached().with_world_fields( + WorldFields::default() + .with_field(WorldField::BlendOffset, Arc::new(ConstantSampler(73.))), + ); + assert_eq!(cached.sample_value(&mut context, [100, 2, 3]).unwrap(), 42.); + let root = XoroshiroRandom::new(0).fork_positional(); + let extensions = MaterialExtensions::new( + root, + ExtensionBlocks { + default: BlockStateId(2), + water: BlockStateId(3), + packed_ice: BlockStateId(2), + snow: BlockStateId(2), + }, + ExtensionNoises { + badlands_surface: Arc::new(Zero), + badlands_pillar: Arc::new(Zero), + badlands_roof: Arc::new(Zero), + iceberg_surface: Arc::new(Zero), + iceberg_pillar: Arc::new(Zero), + iceberg_roof: Arc::new(Zero), + }, + 8, + ); + let mut surface = Surface { + calls: 0, + fail_at: (scenario == 1).then_some(2), + }; + let rule = if scenario == 2 { + MaterialRule::OreVein { + ore: BlockStateId(2), + raw_ore: BlockStateId(2), + filler: BlockStateId(2), + raw_ore_chance: 0.5, + density: Arc::new(Fails), + richness: Arc::new(ConstantSampler(1.)), + filler_gap: Arc::new(ConstantSampler(-1.)), + } + } else { + MaterialRule::Block(BlockStateId(3)) + }; + let result = build_surface( + &mut chunk, + rule, + SurfaceInputs:: { + generation: WorldGenerationContext::new(0, 16, 8), + noise_volume: DensityVolume::new([16; 3], [0; 3], [1; 3]).unwrap(), + root, + surface: &mut surface, + preliminary_surface: Arc::new(ConstantSampler(0.)), + density_context: &mut context, + write_min_y: 0, + write_max_y: 15, + }, + &extensions, + ); + assert_eq!(result.is_ok(), scenario == 0); + assert_eq!(cached.sample_value(&mut context, [100, 2, 3]).unwrap(), 42.); + assert_eq!( + count.load(Ordering::SeqCst), + 1, + "the caller's cache was lost" + ); + assert_eq!( + ContextBoundSampler::new(WorldField::BlendOffset) + .sample_value(&mut context, [0; 3]) + .unwrap(), + 73. + ); + assert_eq!( + chunk.block(0, 5, 0), + BlockStateId(if scenario == 2 { 2 } else { 3 }) + ); + assert_eq!( + chunk.block(0, 5, 1), + BlockStateId(if scenario == 0 { 3 } else { 2 }) + ); + assert_eq!(chunk.postprocessing()[0].len(), [2, 1, 0][scenario]); + assert_eq!(surface.calls, [256, 2, 0][scenario]); + } +} + +#[test] +fn top_material_retains_context_on_failure_and_ignores_possible_biome_shortcuts() { + struct Restricted(Surface); + impl MaterialSurfaceQueries for Restricted { + fn possible_biomes(&self) -> Option> { + Some(std::collections::BTreeSet::new()) + } + fn surface_depth(&mut self, _: i32, _: i32) -> i32 { + 1 + } + fn surface_secondary(&mut self, _: i32, _: i32) -> f64 { + 0. + } + fn biome(&mut self, p: BlockPos) -> Result>, MaterialRuleError> { + self.0.biome(p) + } + } + let registry = registry(); + for fail in [false, true] { + let mut chunk = + TerrainChunk::new(ChunkPos::new(0, 0), 0, 16, ®istry, Properties).unwrap(); + chunk.set_block_raw(0, 5, 0, BlockStateId(2)).unwrap(); + let count = Arc::new(AtomicUsize::new(0)); + let cached = CachingDensitySampler::new(0, Arc::new(Count(count.clone()))).unwrap(); + let mut context = SamplerContext::cached().with_world_fields( + WorldFields::default() + .with_field(WorldField::BlendOffset, Arc::new(ConstantSampler(73.))), + ); + assert_eq!(cached.sample_value(&mut context, [100, 2, 3]).unwrap(), 42.); + let mut surface = Restricted(Surface { + calls: 0, + fail_at: fail.then_some(1), + }); + let rule = MaterialRule::Condition { + if_true: MaterialCondition::Biome(vec!["minecraft:plains".to_owned()]), + then_run: Box::new(MaterialRule::Block(BlockStateId(3))), + }; + let result = top_material( + &mut chunk, + rule, + TopMaterialInputs:: { + generation: WorldGenerationContext::new(0, 16, 8), + root: XoroshiroRandom::new(0).fork_positional(), + surface: &mut surface, + preliminary_surface: Arc::new(ConstantSampler(0.)), + density_context: &mut context, + }, + BlockPos::new(0, 5, 0), + true, + ); + if fail { + assert!(result.is_err()); + } else { + assert_eq!(result.unwrap(), Some(BlockStateId(3))); + } + assert_eq!(surface.0.calls, 1); + assert_eq!(cached.sample_value(&mut context, [100, 2, 3]).unwrap(), 42.); + assert_eq!(count.load(Ordering::SeqCst), 1); + assert_eq!( + ContextBoundSampler::new(WorldField::BlendOffset) + .sample_value(&mut context, [0; 3]) + .unwrap(), + 73. + ); + assert_eq!(chunk.block(0, 5, 0), BlockStateId(2)); + assert!(chunk.postprocessing()[0].is_empty()); + } +} diff --git a/crates/horizon-world/tests/placement_bounds.rs b/crates/horizon-world/tests/placement_bounds.rs new file mode 100644 index 000000000..ca9610ceb --- /dev/null +++ b/crates/horizon-world/tests/placement_bounds.rs @@ -0,0 +1,58 @@ +use horizon_core::random::LegacyRandom; +use horizon_world::{ + heightmap::HeightmapType, + worldgen::{ + anchor::WorldGenerationContext, + placement::{ + LayerBlock, PlacementContext, PlacementError, PlacementModifier, PlacementQueryError, + }, + value_provider::IntProvider, + }, +}; + +#[test] +fn negative_cuboid_extent_skips_empty_loops_even_with_huge_other_extents() { + let modifier = PlacementModifier::Cuboid { + xz_size: IntProvider::Constant(i32::MAX), + y_size: IntProvider::Constant(-1), + include_edges: true, + include_interior: true, + }; + let result = modifier.modify( + WorldGenerationContext::new(0, 16, 8), + &mut LegacyRandom::new(0), + [0, 0, 0], + |_, _| -> Result<(), ()> { panic!("empty cuboid emitted") }, + ); + assert!(result.is_ok()); +} +struct UnboundedColumn { + reads: usize, +} +impl PlacementContext for UnboundedColumn { + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new(-64, 384, 63) + } + fn min_y(&mut self) -> Result { + Ok(-64) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + Ok(i32::MAX) + } + fn layer_block(&mut self, _: [i32; 3]) -> Result { + self.reads += 1; + Ok(LayerBlock::Empty) + } +} +#[test] +fn layered_scans_bound_work_when_world_queries_return_extreme_heights() { + let mut context = UnboundedColumn { reads: 0 }; + let result = PlacementModifier::CountOnEveryLayer(IntProvider::Constant(1)).modify_in( + &mut context, + &mut LegacyRandom::new(0), + [0, 0, 0], + |_, _| -> Result<(), ()> { panic!("empty column emitted") }, + ); + assert!(matches!(result, Err(PlacementError::WorkLimit))); + assert!(context.reads > 0 && context.reads <= 65536); +} diff --git a/crates/horizon-world/tests/placement_queries.rs b/crates/horizon-world/tests/placement_queries.rs new file mode 100644 index 000000000..e49bfd8ae --- /dev/null +++ b/crates/horizon-world/tests/placement_queries.rs @@ -0,0 +1,45 @@ +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::{ + heightmap::HeightmapType, + worldgen::{ + anchor::WorldGenerationContext, + placement::{PlacementContext, PlacementError, PlacementModifier, PlacementQueryError}, + }, +}; +struct Context { + queries: Vec, +} +impl PlacementContext for Context { + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new(0, 16, 8) + } + fn min_y(&mut self) -> Result { + panic!("water depth does not query the world minimum") + } + fn height(&mut self, kind: HeightmapType, _: i32, _: i32) -> Result { + self.queries.push(kind); + if kind == HeightmapType::OceanFloor { + Ok(7) + } else { + Err(PlacementQueryError::Failed("surface unavailable".into())) + } + } +} +#[test] +fn second_height_query_failure_preserves_order_without_emission_or_random_draws() { + let mut context = Context { queries: vec![] }; + let mut random = LegacyRandom::new(17); + let mut expected = random.clone(); + let result = PlacementModifier::SurfaceWaterDepth(7).modify_in( + &mut context, + &mut random, + [1, 9, 2], + |_, _| -> Result<(), ()> { panic!("failed query emitted a position") }, + ); + assert!(matches!(result, Err(PlacementError::World(_)))); + assert_eq!( + context.queries, + [HeightmapType::OceanFloor, HeightmapType::WorldSurface] + ); + assert_eq!(random.next_long(), expected.next_long()); +} diff --git a/crates/horizon-world/tests/rule_test_bounds.rs b/crates/horizon-world/tests/rule_test_bounds.rs new file mode 100644 index 000000000..de4862f54 --- /dev/null +++ b/crates/horizon-world/tests/rule_test_bounds.rs @@ -0,0 +1,69 @@ +use horizon_world::{ + DATA_VERSION, + nbt::Tag, + registry::BlockRegistry, + worldgen::{block_feature::FeatureBlockBindings, rule_test::RuleTest}, +}; +use std::collections::{BTreeMap, BTreeSet}; +fn registry() -> BlockRegistry { + let names = [ + "minecraft:air", + "minecraft:cave_air", + "minecraft:void_air", + "minecraft:stone", + ]; + BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List( + names + .iter() + .map(|name| Tag::compound([("id", Tag::String((*name).into()))])) + .collect(), + ), + ), + ( + "defaults", + Tag::Compound( + names + .iter() + .enumerate() + .map(|(id, name)| ((*name).into(), Tag::Int(id as i32))) + .collect(), + ), + ), + ])) + .unwrap() +} +#[test] +fn rule_decoding_bounds_nested_and_branching_data() { + let registry = registry(); + let bindings = FeatureBlockBindings::new(®istry, BTreeSet::new()).unwrap(); + let leaf = r#"{"predicate_type":"always_true"}"#; + let mut nested = leaf.to_owned(); + for _ in 0..130 { + nested = format!(r#"{{"predicate_type":"not","rule":{nested}}}"#); + } + assert!(RuleTest::from_json(&nested, &bindings).is_err()); + let branch = format!( + r#"{{"predicate_type":"all_of","rules":[{}]}}"#, + vec![leaf; 8192].join(",") + ); + let tree = format!( + r#"{{"predicate_type":"all_of","rules":[{}]}}"#, + [branch.as_str(); 9].join(",") + ); + assert!(RuleTest::from_json(&tree, &bindings).is_err()); +} +#[test] +fn binding_rejects_unknown_tag_blocks_and_duplicate_canonical_tags() { + let registry = registry(); + let tags = BTreeMap::from([("horizon:test".into(), vec!["missing".into()])]); + assert!(FeatureBlockBindings::with_tags(®istry, BTreeSet::new(), &tags).is_err()); + let tags = BTreeMap::from([ + ("test".into(), vec!["stone".into()]), + ("minecraft:test".into(), vec!["air".into()]), + ]); + assert!(FeatureBlockBindings::with_tags(®istry, BTreeSet::new(), &tags).is_err()); +} diff --git a/crates/horizon-world/tests/state_provider_bounds.rs b/crates/horizon-world/tests/state_provider_bounds.rs new file mode 100644 index 000000000..033d4675c --- /dev/null +++ b/crates/horizon-world/tests/state_provider_bounds.rs @@ -0,0 +1,81 @@ +use horizon_world::{ + DATA_VERSION, + nbt::Tag, + registry::BlockRegistry, + worldgen::state_provider::{BlockStateProvider, StateProviderBindings, StateProviderCatalog}, +}; +use std::collections::{BTreeMap, BTreeSet}; +#[test] +fn bound_recursive_providers_and_registry_lists_before_sampling() { + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List(vec![Tag::compound([( + "id", + Tag::String("minecraft:stone".into()), + )])]), + ), + ( + "defaults", + Tag::compound([("minecraft:stone", Tag::Int(0))]), + ), + ])) + .unwrap(); + let bindings = + StateProviderBindings::new(®istry, BTreeSet::new(), &BTreeMap::new()).unwrap(); + let mut source = r#"{"id":"stone"}"#.to_owned(); + for _ in 0..140 { + source = format!(r#"{{"type":"rotated","state":{source}}}"#); + } + assert!(BlockStateProvider::from_json(&source, &bindings).is_err()); + let source = serde_json::json!({"type":"random_block","blocks":vec!["stone";8193]}).to_string(); + assert!(BlockStateProvider::from_json(&source, &bindings).is_err()); + let rule = serde_json::json!({"if_true":{"type":"true"},"then":{"id":"stone"}}); + let valid = serde_json::json!({"type":"rule_based","rules":vec![rule.clone();8192]}); + assert!(BlockStateProvider::from_json(&valid.to_string(), &bindings).is_ok()); + let oversized = serde_json::json!({"type":"rule_based","rules":vec![rule;8193]}); + assert!(BlockStateProvider::from_json(&oversized.to_string(), &bindings).is_err()); + // Every individual list fits, but the aggregate predicate/provider tree + // must share a work budget rather than resetting it for each rule. + let branching = serde_json::json!({"if_true":{"type":"all_of","predicates":vec![serde_json::json!({"type":"true"});7]},"then":{"id":"stone"}}); + let oversized = serde_json::json!({"type":"rule_based","rules":vec![branching;8192]}); + assert!(BlockStateProvider::from_json(&oversized.to_string(), &bindings).is_err()); + let tags = BTreeMap::from([("horizon:oversized".into(), vec!["stone".into(); 8193])]); + assert!(StateProviderBindings::new(®istry, BTreeSet::new(), &tags).is_err()); + let tags = BTreeMap::from([("tag".into(), vec![]), ("minecraft:tag".into(), vec![])]); + assert!(StateProviderBindings::new(®istry, BTreeSet::new(), &tags).is_err()); + let definitions = BTreeMap::from([ + ( + "horizon:cycle".into(), + r#"{"type":"copy_properties","source":"horizon:cycle"}"#.into(), + ), + ("horizon:valid".into(), r#"{"id":"stone"}"#.into()), + ("horizon:invalid".into(), r#"{"type":"missing"}"#.into()), + ("horizon:alias".into(), r#""horizon:valid""#.into()), + ]); + let catalog = StateProviderCatalog::from_resources(&definitions).unwrap(); + assert!(catalog.provider(r#""horizon:valid""#, &bindings).is_ok()); + for name in [ + "horizon:cycle", + "horizon:invalid", + "horizon:alias", + "horizon:missing", + ] { + assert!( + catalog + .provider(&serde_json::to_string(name).unwrap(), &bindings) + .is_err() + ); + } + assert!( + catalog + .direct_provider(r#""horizon:valid""#, &bindings) + .is_err() + ); + let duplicate = BTreeMap::from([ + ("stone".into(), "{}".into()), + ("minecraft:stone".into(), "{}".into()), + ]); + assert!(StateProviderCatalog::from_resources(&duplicate).is_err()); +} diff --git a/crates/horizon-world/tests/tick_data.rs b/crates/horizon-world/tests/tick_data.rs new file mode 100644 index 000000000..7060b57a4 --- /dev/null +++ b/crates/horizon-world/tests/tick_data.rs @@ -0,0 +1,117 @@ +use horizon_core::{ + position::BlockPos, + ticks::{SavedTick, TickPriority, TickTypeId}, +}; +use horizon_world::{ + DATA_VERSION, + chunk::ChunkData, + nbt::{NamedTag, Tag}, + tick_data::{self, TickKind}, +}; + +fn saved(pos: BlockPos) -> SavedTick { + SavedTick { + kind: TickTypeId(7), + pos, + delay: -1, + priority: TickPriority::High, + } +} +fn root() -> NamedTag { + NamedTag { + name: "".into(), + tag: Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("xPos", Tag::Int(-1)), + ("zPos", Tag::Int(-1)), + ("sections", Tag::List(vec![])), + ("unknown", Tag::Long(42)), + ]), + } +} +#[test] +fn numeric_codec_narrowing_and_malformed_data() { + let tag = Tag::List(vec![Tag::compound([ + ("i", Tag::String("minecraft:stone".into())), + ("x", Tag::Double((-1.5f64).to_bits())), + ("y", Tag::Float(f32::NAN.to_bits())), + ("z", Tag::Byte(-1)), + ("t", Tag::Long(i64::MAX)), + ("p", Tag::Double(f64::NEG_INFINITY.to_bits())), + ])]); + let ticks = tick_data::read_list(&tag, |_| Some(TickTypeId(7))).unwrap(); + assert_eq!( + ticks, + [SavedTick { + pos: BlockPos::new(-1, 0, -1), + priority: TickPriority::ExtremelyHigh, + ..saved(BlockPos::default()) + }] + ); + assert!(tick_data::read_list(&tag, |_| None).is_err()); + assert!(tick_data::read_list(&Tag::List(vec![Tag::Int(1)]), |_| Some(TickTypeId(0))).is_err()); + assert!(tick_data::read_list(&Tag::Int(0), |_| Some(TickTypeId(0))).is_err()); + assert!(tick_data::write_list(&ticks, |_| None).is_err()); +} +#[test] +fn saved_chunk_ticks_filter_coordinates_and_write_atomically() { + let mut root = root(); + let Tag::Compound(map) = &mut root.tag else { + unreachable!() + }; + map.insert( + "block_ticks".into(), + tick_data::write_list( + &[ + saved(BlockPos::new(-1, 64, -1)), + saved(BlockPos::new(0, 64, -1)), + ], + |_| Some("minecraft:stone".to_owned()), + ) + .unwrap(), + ); + let mut chunk = ChunkData::new(root).unwrap(); + let mut ticks = chunk + .saved_ticks(TickKind::Block, |_| Some(TickTypeId(7))) + .unwrap(); + assert_eq!(ticks.count(), 1); + assert!(ticks.has_scheduled(BlockPos::new(-1, 64, -1), TickTypeId(7))); + assert!(!ticks.has_scheduled(BlockPos::new(0, 64, -1), TickTypeId(7))); + assert!( + chunk + .saved_ticks(TickKind::Fluid, |_| None) + .unwrap() + .peek() + .is_none() + ); + ticks.unpack(100); + let packed = ticks.pack(100); + let before = chunk.root().clone(); + assert!( + chunk + .set_saved_ticks(TickKind::Block, &packed, |_| None) + .is_err() + ); + assert_eq!(chunk.root(), &before); + assert!( + chunk + .set_saved_ticks(TickKind::Block, &[saved(BlockPos::new(0, 64, -1))], |_| { + Some("minecraft:stone".to_owned()) + }) + .is_err() + ); + assert_eq!(chunk.root(), &before); + chunk + .set_saved_ticks(TickKind::Block, &packed, |_| { + Some("minecraft:stone".to_owned()) + }) + .unwrap(); + assert_eq!(chunk.root().tag.get("unknown"), Some(&Tag::Long(42))); + assert_eq!( + chunk + .saved_ticks(TickKind::Block, |_| Some(TickTypeId(7))) + .unwrap() + .count(), + 1 + ); +} diff --git a/crates/horizon-world/tests/weighted_provider.rs b/crates/horizon-world/tests/weighted_provider.rs new file mode 100644 index 000000000..574e1bb4c --- /dev/null +++ b/crates/horizon-world/tests/weighted_provider.rs @@ -0,0 +1,53 @@ +use horizon_world::worldgen::{ + height_provider::HeightProvider, value_provider::IntProvider, weighted::WeightedList, +}; + +#[test] +fn weighted_lists_reject_invalid_totals_and_bound_entry_allocations() { + assert!(WeightedList::<()>::new(vec![]).is_err()); + assert!(WeightedList::new(vec![((), 0)]).is_err()); + assert!(WeightedList::new(vec![((), -1), ((), 2)]).is_err()); + assert!(WeightedList::new(vec![((), i32::MAX), ((), 1)]).is_err()); + assert!(WeightedList::new(vec![((), i32::MAX)]).is_ok()); + assert!(WeightedList::new(vec![((), 1); 8192]).is_ok()); + assert!(WeightedList::new(vec![((), 1); 8193]).is_err()); +} + +#[test] +fn branching_provider_decoders_share_a_total_node_budget() { + for height in [false, true] { + let leaf = if height { r#"{"absolute":0}"# } else { "0" }; + let entry = format!(r#"{{"data":{leaf},"weight":1}}"#); + let branch = format!( + r#"{{"type":"weighted_list","distribution":[{}]}}"#, + vec![entry; 256].join(",") + ); + let entry = format!(r#"{{"data":{branch},"weight":1}}"#); + let tree = format!( + r#"{{"type":"weighted_list","distribution":[{}]}}"#, + vec![entry; 256].join(",") + ); + // Each list is below its own limit, but the whole tree exceeds 65536 nodes. + if height { + assert!(HeightProvider::from_json(&tree).is_err()); + } else { + assert!(IntProvider::from_json(&tree).is_err()); + } + } +} + +#[test] +fn optional_weighted_choices_retain_zero_entries_and_skip_empty_draws() { + use horizon_core::random::{LegacyRandom, RandomSource}; + use horizon_world::worldgen::weighted::OptionalWeightedList; + let mut random = LegacyRandom::new(12); + let mut expected = random.clone(); + let empty = OptionalWeightedList::<()>::new(vec![]).unwrap(); + assert_eq!(empty.sample(&mut random).unwrap(), None); + let zero = OptionalWeightedList::new(vec![(1, 0), (2, 0)]).unwrap(); + assert_eq!(zero.entries(), &[(1, 0), (2, 0)]); + assert_eq!(zero.sample(&mut random).unwrap(), None); + assert_eq!(random.next_long(), expected.next_long()); + assert!(WeightedList::new(vec![(1, 0), (2, 0)]).is_err()); + assert!(OptionalWeightedList::new(vec![(1, i32::MAX), (2, 1)]).is_err()); +} diff --git a/crates/horizon-world/tests/world_io.rs b/crates/horizon-world/tests/world_io.rs new file mode 100644 index 000000000..bbbfab360 --- /dev/null +++ b/crates/horizon-world/tests/world_io.rs @@ -0,0 +1,199 @@ +use horizon_core::position::{BlockPos, ChunkPos}; +use horizon_world::{ + DATA_VERSION, + chunk::{BlockState, ChunkData, PalettedContainer}, + compression::Compression, + nbt::{JavaString, Limits, NamedTag, Tag}, + region::{ChunkRecord, RegionFile, RegionWriter}, +}; +use std::{ + fs, + io::{Seek, SeekFrom, Write}, + path::{Path, PathBuf}, + sync::atomic::{AtomicU64, Ordering}, +}; + +static NEXT: AtomicU64 = AtomicU64::new(0); +struct Directory(PathBuf); +impl Directory { + fn new() -> Self { + let stamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let path = std::env::temp_dir().join(format!( + "horizon-world-test-{}-{stamp}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + Self(path) + } + fn region(&self) -> PathBuf { + self.0.join("r.-1.0.mca") + } +} +impl Drop for Directory { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn record(len: usize) -> ChunkRecord { + ChunkRecord { + compression: Compression::None, + compressed: vec![37; len], + timestamp: 0x8000_0001, + } +} + +#[test] +fn external_threshold_negative_coordinates_and_timestamps_roundtrip() { + let dir = Directory::new(); + let a = ChunkPos::new(-32, 0); + let b = ChunkPos::new(-1, 31); + let inline = record(255 * 4096 - 5); + let external = record(255 * 4096 - 4); + let mut writer = RegionWriter::create(dir.region()).unwrap(); + writer.write(a, &inline).unwrap(); + writer.write(b, &external).unwrap(); + writer.finish().unwrap(); + assert!(!dir.0.join("c.-32.0.mcc").exists()); + assert!(dir.0.join("c.-1.31.mcc").exists()); + let mut reader = RegionFile::open(dir.region()).unwrap(); + assert_eq!( + reader.chunks().collect::>(), + [(a, inline.timestamp), (b, external.timestamp)] + ); + for (pos, expected) in [(a, inline), (b, external)] { + let actual = reader.read(pos).unwrap().unwrap(); + assert_eq!(actual.compressed, expected.compressed); + assert_eq!(actual.timestamp, expected.timestamp); + } + assert!(reader.read(ChunkPos::new(-31, 0)).unwrap().is_none()); + assert!(reader.read(ChunkPos::new(0, 0)).is_err()); +} + +#[test] +fn failed_writer_cannot_commit_and_removes_its_own_external_files() { + let dir = Directory::new(); + let mut writer = RegionWriter::create(dir.region()).unwrap(); + writer + .write(ChunkPos::new(-1, 0), &record(1_100_000)) + .unwrap(); + assert!(dir.0.join("c.-1.0.mcc").exists()); + assert!(writer.write(ChunkPos::new(0, 0), &record(4)).is_err()); + assert!(writer.finish().is_err()); + assert!(!dir.region().exists()); + assert_eq!(fs::read_dir(&dir.0).unwrap().count(), 0); +} + +#[test] +fn existing_external_and_concurrent_destination_are_preserved() { + let dir = Directory::new(); + let external = dir.0.join("c.-1.0.mcc"); + fs::write(&external, b"owned by someone else").unwrap(); + let mut writer = RegionWriter::create(dir.region()).unwrap(); + assert!( + writer + .write(ChunkPos::new(-1, 0), &record(1_100_000)) + .is_err() + ); + drop(writer); + assert_eq!(fs::read(&external).unwrap(), b"owned by someone else"); + let mut writer = RegionWriter::create(dir.region()).unwrap(); + writer.write(ChunkPos::new(-32, 0), &record(3)).unwrap(); + fs::write(dir.region(), b"another writer won").unwrap(); + assert!(writer.finish().is_err()); + assert_eq!(fs::read(dir.region()).unwrap(), b"another writer won"); + assert!(RegionWriter::create(dir.region()).is_err()); +} + +fn malformed_region(path: &Path, first: u32, second: u32, payload_len: u32, codec: u8) { + let mut file = fs::File::create(path).unwrap(); + file.set_len(12288).unwrap(); + file.write_all(&first.to_be_bytes()).unwrap(); + file.write_all(&second.to_be_bytes()).unwrap(); + file.seek(SeekFrom::Start(8192)).unwrap(); + file.write_all(&payload_len.to_be_bytes()).unwrap(); + file.write_all(&[codec]).unwrap(); +} + +#[test] +fn corrupt_allocations_lengths_codecs_and_missing_external_files_fail() { + let dir = Directory::new(); + for (first, second) in [(257, 0), (512, 0), (1025, 0), (513, 513)] { + malformed_region(&dir.region(), first, second, 1, 3); + assert!(RegionFile::open(dir.region()).is_err()); + } + for (len, codec) in [ + (0, 3), + (4093, 3), + (u32::MAX, 3), + (1, 127), + (2, 131), + (1, 131), + ] { + malformed_region(&dir.region(), 513, 0, len, codec); + let mut reader = RegionFile::open(dir.region()).unwrap(); + assert!(reader.read(ChunkPos::new(-32, 0)).is_err()); + } +} + +#[test] +fn chunk_storage_edit_preserves_unknown_fields_and_other_blocks() { + let palette = + PalettedContainer::uniform(Tag::String(JavaString::from("minecraft:air")), 4096, 4) + .unwrap(); + let root = NamedTag { + name: "".into(), + tag: Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("xPos", Tag::Int(-1)), + ("zPos", Tag::Int(-1)), + ("extra", Tag::ByteArray(vec![1, 2, 3])), + ( + "sections", + Tag::List(vec![Tag::compound([ + ("Y", Tag::Byte(-4)), + ("block_states", palette.to_nbt()), + ("unknown", Tag::Long(99)), + ])]), + ), + ]), + }; + let mut chunk = ChunkData::new(root).unwrap(); + let p = BlockPos::new(-1, -64, -1); + let state = BlockState { + name: "minecraft:oak_log".to_owned(), + properties: [("axis".to_owned(), "x".to_owned())].into(), + }; + assert_eq!( + chunk.set_block_data(p, state.clone()).unwrap().name, + "minecraft:air" + ); + assert_eq!(chunk.block(p).unwrap(), Some(state)); + assert_eq!( + chunk.block(p.offset(-1, 0, 0)).unwrap().unwrap().name, + "minecraft:air" + ); + assert!( + chunk + .set_block_data( + p.offset(1, 0, 0), + BlockState { + name: "minecraft:stone".into(), + properties: Default::default() + } + ) + .is_err() + ); + let root = chunk.into_nbt(); + assert_eq!(root.tag.get("extra"), Some(&Tag::ByteArray(vec![1, 2, 3]))); + let Some(Tag::List(sections)) = root.tag.get("sections") else { + panic!() + }; + assert_eq!(sections[0].get("unknown"), Some(&Tag::Long(99))); + let record = ChunkRecord::from_nbt(&root, Compression::Lz4, 17, Limits::default()).unwrap(); + assert_eq!(record.nbt(Limits::default()).unwrap(), root); +} diff --git a/docs/biome-lookup.md b/docs/biome-lookup.md new file mode 100644 index 000000000..a1d069b34 --- /dev/null +++ b/docs/biome-lookup.md @@ -0,0 +1,133 @@ +# Biome lookup + +Horizon implements Java Edition **26.3** block-to-quart biome lookup. `BiomeZoom` +accepts the obfuscated biome seed and chooses among eight jittered quart corners +in vanilla order, retaining strict distance ties and signed coordinate wrapping. +The caller resolves the selected quart coordinate through its biome provider. +Direct noise-biome queries bypass this selection and shift block coordinates; +floating-point positions are floored with Java's saturating integer conversion. + +`obfuscate_seed` computes the vanilla SHA-256 transform of the little-endian world +seed and reads the first eight digest bytes as a little-endian signed long. The +core keeps a fixed-input implementation without adding runtime dependencies. + +Run `python3 tools/test_biome_zoom_parity.py`. The +[local report](../benchmarks/rust-biome-zoom-2026-10-06/scoped-parity.json) records +**256,933 matching lines per reference JAR**: **4,104 seed hashes**, **169,408 block +queries** and **83,421 floating-position queries**. Actual vanilla `BiomeManager` +methods call a traced resolver; the suite compares selected quart coordinates, +direct queries and source replacement retaining the same zoom seed. Seed hashes +also match Python `hashlib` independently. + +The corpus includes dense neighborhoods, negative quart boundaries, both signed +integer extremes, distant coordinates, randomized seeds/positions, and double +NaNs, infinities and subnormals. Source and fixture hashes are captured, changes +during validation invalidate the result, and reference artifacts stay private. +CI includes the comparison; remote outcomes have not been observed. + +This validates coordinate selection, not biome storage, biome-source generation, +chunk blending, or complete generated worlds. + + +## Chunk biome storage + +`BiomeChunk` stores each section's 64 quart-resolution biome values. Reads clamp +quart Y to the chunk and wrap quart X/Z into its local grid. Fills visit sections +bottom to top and query each section in X/Y/Z order. Each completed section is +committed; a resolver failure retains the failing section's previous values. +Inclusive generation bounds select all intersecting sections. + +Run `python3 tools/test_biome_chunk_parity.py`. The +[local chunk report](../benchmarks/rust-biome-chunk-2026-10-06/scoped-parity.json) +records **478,340 matching lines per reference JAR** across **20 fixtures** and +**160 fills**, including **21,120 quart-biome queries**. Native `ProtoChunk` and +`LevelChunkSection` methods supply the reference behavior. Tests use synthetic +holder identities, up to 512 distinct values, repeated fills, provider failures +at calls 0/63/64/65, generation bounds cutting through sections, and the complete +supported aligned vertical range. The reference chunk is at BIOMES status. + +This storage uses dense arrays and compares biome values rather than vanilla's +internal palette layout. Packet/save integration and chunk lifecycle transitions +remain separate work. Clipped generation bounds must remain within the chunk; +invalid bounds return an error before mutation. + + +## Chunk biome generation + +The [generation report](../benchmarks/rust-biome-generation-2026-10-06/scoped-parity.json) +records **383,072 matching lines per JAR** across **252 fixtures**, **322 fills**, +**341,504 stored biome values** and **35,910 subsequent block-position lookups**. +Run `python3 tools/test_biome_generation_parity.py` to compare against actual +`ChunkGenerator.doCreateBiomes`, invoked through `NoiseBasedChunkGenerator`. + +Rust compiles the climate fields of all seven bundled terrain routers, samples +the chunk's quart volume, searches its multi-noise parameter table and fills +biome sections. The suite pairs each router with both Overworld and Nether +presets, both random modes and three seed/coordinate combinations. Repeated +fills create fresh density contexts while retaining nearest-search state. +Generation bounds also exercise omitted top and bottom sections. Subsequent +block lookups use seeded fuzzy selection and clamped chunk reads. + +Both JARs independently export the preset tables and must agree: **7,594 Overworld +entries** and **5 Nether entries**. Rust imports those quantized tables; preset +builders remain unported. Registry-bound source codecs are described below. Reference holders +supply identities without evaluating biome properties. The comparison uses empty +blending and no below-zero retrogen. An additional 168 fixtures generate chunks through fixed, checkerboard and End +sources using every bundled terrain router. They cover real seeded End erosion, +the central-island boundary and wrapped checkerboard shifts. The [surface-stage integration](material-surfaces.md#chunk-surface-stage) now +links a 3×3 biome neighborhood to terrain filling and surface application, using +stored neighbor biome lookups. Saved biome palettes and complete world generation +remain pending. + + +## Fixed, checkerboard and End sources + +`FixedBiomeSource` always returns its configured value. `CheckerboardBiomeSource` +preserves masked Java shifts, wrapped addition and floor-modulo selection, +including duplicate values and unrestricted constructor scales. It supports up to +8,192 values; an empty list returns a typed lookup error. Its vanilla JSON codec +has the narrower scale range 0–62, with a default of 2. + +`EndBiomeSource` returns the central biome without querying erosion inside the +64-chunk radius. Outside that circle it samples erosion at the containing chunk's +center and wrapped block Y, then applies vanilla's highlands/midlands/islands/ +barrens thresholds. Sampler errors propagate without substituting a biome. + +Run `python3 tools/test_biome_source_parity.py`. The +[local source report](../benchmarks/rust-biome-source-2026-10-06/scoped-parity.json) +records **1,306,096 matching lines per JAR**, covering **457 fixtures** and +**1,147,984 queries**. Actual native source methods supply the results. The corpus +includes all 63 codec-valid checkerboard scales, unrestricted runtime scales, +empty/duplicate/512-value lists, extreme coordinates, exact End threshold +neighbors, NaN/infinity samples and failing erosion providers. Ordered erosion +sampling coordinates are compared. This source-level suite supplies constant +End density values; seeded density and chunk generation are validated separately. + + +## Registry-bound source codecs + +`BiomeSourceCatalog` decodes and canonically encodes fixed, checkerboard, End and +multi-noise definitions against known biome, tag and preset registries. Named +biomes, direct or tagged biome sets, inline climate lists, and named or inline +preset holders retain vanilla selection and fallback behavior. The catalog +validates references before returning a definition. + +`BiomeSourceDefinition::resolve` builds a `ResolvedBiomeSource` using imported +quantized preset tables. A worker resolver retains multi-noise search state, +prepares climate volumes only for multi-noise sources, and exposes one query API +for all four source kinds. Chunk generation and the surface-stage neighborhood +now use this API; surface integration decodes the source configuration itself. + +Run `python3 tools/test_biome_source_codec_parity.py`. The +[local codec report](../benchmarks/rust-biome-source-codec-2026-10-06/scoped-parity.json) +records **363,121 matching lines per JAR** across **40,481 inputs**, using all +**67 biome definitions** and **86 biome tags**. The native `BiomeSource.CODEC` +supplies parsing, canonical encoding, possible-biome sets and queries at seven +positions. The corpus covers every quantized climate step from −2 to 2, scale +bounds and numeric narrowing, malformed fields, duplicate keys, holder sets, +and inline-list preference and fallback to presets. Encoding comparisons use +serialized JSON numeric values, rather than Java's widened float values. + +Full inline biome definitions, native preset builders, live registry ownership +and reloads, biome-search helpers, blending, and complete generated worlds remain +pending. The bounded catalog is not a complete registry lifecycle implementation. diff --git a/docs/biome-temperatures.md b/docs/biome-temperatures.md new file mode 100644 index 000000000..b27e91edc --- /dev/null +++ b/docs/biome-temperatures.md @@ -0,0 +1,33 @@ +# Biome temperatures + +Horizon implements Java Edition **26.3** biome temperature sampling, including the +frozen modifier, height adjustment, rain/snow thresholds, precipitation selection +and the small frozen-ocean iceberg melt predicate. The fixed seeded simplex and +noise-stack sources use the existing Rust noise implementation. + +`BiomeTemperatureSettings` supplies the immutable inputs. `BiomeTemperature` is a +per-biome, per-worker cache, corresponding to vanilla's thread-local cache. Its +1,024-entry insertion order does not change on hits. Keys use packed block +positions and omit sea level, preserving both coordinate aliases and cached +results across sea-level changes. NaN values are recomputed, including vanilla's +eviction behavior when a cached NaN is queried at capacity. + +Run `python3 tools/test_biome_temperature_parity.py`. The +[local report](../benchmarks/rust-biome-temperature-2026-10-06/scoped-parity.json) +records **836,659 matching output lines per reference JAR** over **387 fixtures**, +including **12 thread-isolation fixtures**. The original Java transport invokes +actual biome methods and inspects native ordered cache contents. Test inputs +include arbitrary base-temperature bits, threshold neighbors, both modifiers, +precipitation enabled/disabled, extreme coordinates, sea-level overflow, packed +aliases, cache hits/eviction and actual native threads with separate Rust workers. + +The oracle constructs native climate settings and biomes with only the fields +these methods use. Climate-setting parsing now covers all **67 bundled biome definitions** and +**183 codec inputs**, including float rounding, overflow, field validation and +modifier defaults. Full biome codecs, climate encoding, world-dependent snow/ice placement, +automatic thread-local ownership for a shared +Rust biome object remain pending. Source/fixture hashes guard the comparison; +raw reference artifacts stay private under `.local`. + +[Material temperature and biome conditions](material-conditions.md) now use these +climate settings and cached temperature calculations in a separate integration suite. diff --git a/docs/block-state-codecs.md b/docs/block-state-codecs.md new file mode 100644 index 000000000..f56e48403 --- /dev/null +++ b/docs/block-state-codecs.md @@ -0,0 +1,25 @@ +# Block-state JSON codecs + +`BlockStateJsonCodec` implements compact and full Java Edition **26.3** block-state +JSON forms over the imported `BlockRegistry`, with integer property kinds supplied +alongside the registry. Compact encoding uses a block name for the default state; +full encoding uses an `id` object and properties for blocks with multiple states. + +Missing or invalid properties retain their defaults. Unknown property names are +ignored. Integer properties accept Java decimal strings, including signs, leading +zeroes and JDK 25 BMP decimal digits; enum and boolean properties use exact names. +This codec is separate from `BlockRegistry::resolve`, whose descriptor validation +continues to reject invalid properties. + +Run `python3 tools/test_block_state_codec_parity.py`. The +[local report](../benchmarks/rust-block-state-codec-2026-10-06/scoped-parity.json) +records **221,261 matching output lines per reference JAR**, covering all +**35,723 states**, **1,286 blocks**, **146 integer properties** and **185,538 decoding +inputs**. Tests exercise default/full encoding, namespaces, invalid types, +property fallback, integer overflow and duplicate fields. + +The two authenticated JARs must export identical state metadata. Exports and raw +comparison traces remain private under `.local`. The public report contains +metadata and hashes. This validates codec behavior over imported identities; +block gameplay, registry lifecycle, warning messages and arbitrary malformed +JSON/unpaired-surrogate text remain outside the tested scope. diff --git a/docs/carving.md b/docs/carving.md new file mode 100644 index 000000000..9dfcde8e6 --- /dev/null +++ b/docs/carving.md @@ -0,0 +1,126 @@ +# Carving + +Horizon implements Java Edition **26.3** carving-mask storage and traversal. +`CarvingMask` packs cells in Y/Z/X order into 64-bit words. Its column iterator +finds contiguous marked runs and splits them into inclusive vertical intervals, +using word scans without allocating a list of individual cells or columns. + +`try_visit_mut` retains vanilla callback behavior: adding cells during traversal +changes subsequent run searches, while an already selected run keeps its original +boundaries. Callback failures stop immediately and retain prior mutations. +Coordinate arithmetic wraps like Java, including positive out-of-range aliases; +negative indices return an error. Rust bounds height to 1–4,064 and positive growth +to 2^24 bits. Invalid construction and allocation limits are explicit errors. + +Run `python3 tools/test_carving_mask_parity.py`. The +[local report](../benchmarks/rust-carving-mask-2026-10-06/scoped-parity.json) +records **45,742 matching output lines per reference JAR**, across **28 fixtures** +and **6,988 operations**. The native `CarvingMask` supplies all reference results. +The corpus includes sparse and fully filled masks, duplicate insertions, word and +column boundaries, extreme signed coordinates, positive aliases, negative-index +failures, and successful or failing callbacks that add cells during traversal. +All corpus indices remain below 2^20. Reference artifacts remain private and +source/fixture hashes guard validation. + +This comparison covers masks. The combined generation check below also covers +neighbor biome selection and carver seeding; complete generated worlds remain pending. + +## Applying masks to terrain + +`apply_carving_mask` traverses each marked interval from top to bottom, applying +an optional caller-supplied predicate before block or aquifer queries. The +resolved `minecraft:uncarvable` tag prevents replacement. Grass and mycelium mark +a surface encountered within the current interval, including when the aquifer +returns no replacement. Subsequent exposed dirt beneath carved cells is restored +through `top_material`. Block changes update WG heightmaps; fluid postprocessing +retains vanilla order and duplicates. Later errors preserve prior effects. + +The [combined surface-stage report](../benchmarks/rust-material-stage-2026-10-06/scoped-parity.json) +records **6,733,382 matching lines per JAR**, including **158 carving passes** and +**21,757,952 block values** across noise filling, surface building and carving. +Actual `NoiseBasedChunkGenerator.applyCarvingMask` supplies the reference results; +its existing aquifer is wrapped to trace ordered requests, results and fluid +scheduling decisions. The test applies explicit masks, filtered and unfiltered, +with grass/mycelium/dirt and uncarvable blocks, repeated writes and disjoint runs. +The filter is synthetic; native blending-filter generation remains pending. + +Run `python3 tools/test_material_stage_parity.py`. Unit tests additionally verify +that filters and uncarvable tags skip aquifer calls, a surface observation survives +an absent aquifer result, and later aquifer failure preserves earlier surface +restoration and its fluid postprocessing even when aquifer scheduling is disabled. + + + +## Shared shape primitives + +`carve_ellipsoid` visits candidate cells in X/Z/descending-Y order, retaining +vanilla's exclusive lower Y bound, Y−0.5 normalization, chunk clipping and ordered +skip callbacks. Output failures preserve earlier marked cells. `can_reach` uses +wrapped step differences and float-rounded thickness before double-distance math. +Traversal has a 2^24-candidate work bound. + +Run `python3 tools/test_carving_geometry_parity.py`. The +[geometry report](../benchmarks/rust-carving-geometry-2026-10-06/scoped-parity.json) +records **106,699 matching lines per JAR**, across **690 ellipsoids** and **5,536 +reachability queries**. Actual `WorldCarver.carveEllipsoid` and `canReach` supply +the reference results. Tests compare normalized skip inputs, marked-cell order, +partial failures and final mask intervals, with distant/overflowing coordinates, +clipped bounds, degenerate radii, NaNs, infinities and subnormals. NaN trace values +are canonicalized. The seeded cave/canyon paths below use these primitives. Gaussian provider codecs remain separate work. + + +## Seeded cave and canyon paths + +`CaveCarver` decodes cave definitions and reproduces start selection, rooms, +thickness bias, randomized tunnel movement and branching. `CanyonCarver` decodes +canyon definitions and reproduces height-dependent width factors, varying radii +and randomized path movement. Both preserve float/double operation order and +vanilla's quantized trigonometry. Their local path RNG is always the legacy +algorithm, independently of the caller's outer random mode. + +Run `python3 tools/test_cave_carver_parity.py` and +`python3 tools/test_canyon_carver_parity.py`. The +[cave report](../benchmarks/rust-cave-carver-2026-10-06/scoped-parity.json) records +**882,005 matching lines per JAR** across **415 fixtures** and **739 requested +carve invocations**. All three bundled cave definitions are independently +imported from both JARs. The +[canyon report](../benchmarks/rust-canyon-carver-2026-10-06/scoped-parity.json) +records **1,094,517 matching lines per JAR** for the bundled canyon and custom +shapes across four generation heights. + +The native `WorldCarver.DIRECT_CODEC` and actual cave/canyon methods supply +reference results. Comparisons include ordered cell writes with duplicates, +mask intervals, partial output failures and subsequent random longs. Both random +modes, repeated invocation, distant/overflowing coordinates and neighboring/far +origins are covered. Custom shapes force branching, floor and width variation, +degenerate radii and failure boundaries; malformed selected fields are tested. + +Rust bounds a cave call to 4,096 starts, a canyon to 4,096 steps and 4,064 width +entries, and either call to 2^24 candidate cells through a shared traversal budget. +Budget exhaustion retains prior mask writes. Gaussian provider codecs, +encoding, blending and complete worlds remain pending; these suites invoke +individual carvers directly. The combined stage check covers neighbor selection and seeding. + + +## Biome-selected neighboring carvers + +`CarverCatalog` resolves named and inline carvers while preserving ordered holder +lists and repeated references. `generate_carving_mask` visits the 17×17 origin +neighborhood in X/Z order. Each carver receives a legacy random stream initialized +from the world seed plus its list ordinal and the origin chunk coordinates, then +runs its native start-selection and shape path. The mask clips below the ceiling +with vanilla's seven-block allowance, or without that allowance for upgrading +chunks. Source errors stop generation before mask application. + +The combined stage report includes **42 procedural carving passes** through actual +`NoiseBasedChunkGenerator.generateCarvers`, after noise filling and surface work +and before the explicit-mask stress passes. Biome selection uses uncached quart +queries and retains the source's prior search state from biome filling. Carved +surface restoration switches fuzzy lookup to that raw source. All four bundled +carvers and all seven terrain settings are available to biome selection; the +native biome settings retain actual carver lists with empty placed-feature lists. + +Unit tests cover origin order with coordinate overflow, upgrading bounds, +invalid bounds before source calls, early source failure and duplicate holder +identity. Tagged carver sets, region-neighbor caching, nonempty blending, +retrogen integration, placed features and complete generated worlds remain pending. diff --git a/docs/collision-geometry.md b/docs/collision-geometry.md new file mode 100644 index 000000000..fa39e7000 --- /dev/null +++ b/docs/collision-geometry.md @@ -0,0 +1,283 @@ +# Horizon collision geometry + +The version target is Minecraft Java Edition **26.3**. Geometry is a simulation +foundation; Horizon still has no Rust client, live world, or entity simulation. + +`horizon-core::geometry` provides `Vec3`, `Aabb`, `Axis`, `Direction`, `BlockHit`, +and immutable `VoxelShape` values. Coordinates are doubles. Arithmetic keeps +vanilla's operation order, signed zero, NaN comparisons, normalization threshold, +and collision epsilon. It does not enable approximate or fused simulation math. + +Implemented vector operations include addition/subtraction, vector-to, component +products, scaling, normalization, dot/cross products, interpolation, projection, +distance/length, horizontal vectors and finite/equality checks. Rotations, look +directions, alignment, axis replacement, direction offsets, and pitch/yaw extraction +are also implemented. The full Vec3 API and entity integration remain absent. + +Trig uses vanilla's 65,536-entry float sine table with double angle scaling and +Java long narrowing. The table is generated from the pinned formula in Rust; +the geometry suite compares every generated entry against the runtime table. +Inverse trig narrows to float at vanilla's conversion points. These comparisons +validate the tested platform; other platforms need the same bit comparisons. + +Bounding boxes normalize endpoints with Java-compatible min/max. Queries include +half-open containment, strict intersection, transforms, distances, ray clipping, +block-coordinate construction with wrapping integer endpoints, setters, next-value +deflation, and swept-box collision tests. A disjoint `intersect` preserves vanilla's +constructor normalization rather than introducing a different empty-box rule. + +Shapes keep exact coordinate arrays and a packed occupancy grid. Greedy boxes are +cached once in vanilla order. Collision-distance queries use occupied grid cells; +ray and closest-point queries reuse the cached boxes. Column minima/maxima use +vanilla's cyclic perpendicular coordinates and infinity for empty/outside cells. +Cube shapes retain arithmetic +lookup; moved shapes use array lookup even for a zero offset. Ray hits preserve +face tie ordering, endpoint exclusion, tolerances, and the 0.001 inside-hit nudge. +Boolean shape joins and overlap predicates preserve cube, identical, +disjoint and epsilon-merger behavior. Shape operations reject truth tables that +fill two empty cells, as vanilla does. Per-axis cube-coordinate metadata survives +partial merges and is checked when importing cached shapes. Box construction +preserves thin-box rejection and up to 1/8 cube quantization. Optimized joins +reconstruct greedy boxes in vanilla order. Face/edge extraction and shape rotations remain absent. + +Discrete axis extrema are retained separately from occupied cells. A box can +quantize to no occupied cells while retaining a finite minimum/maximum on other +axes. That state affects vanilla's lower-block floor-height lookup. Empty joins +also preserve their integer sentinel extrema; optimization and moving an empty +shape return the canonical empty shape. + +Shape clones preserve identity and share immutable coordinate, occupancy and box +storage. New shapes keep separate identities even when their grids are equal. +This preserves alias-sensitive join shortcuts and avoids copying large grids +when an operation returns an existing shape. The cache importer shares equal +grid storage while retaining the distinct vanilla shape identities. + +`resolve_shape_movement` ports vanilla's movement resolver over a supplied shape +list: Y first, then horizontal axes in movement-magnitude order, translating the +box by resolved motion before each axis query. `candidate_step_heights` preserves +float narrowing, duplicate identity, current-Y exclusion, and sorted candidate +heights. `resolve_step_movement` adds the initial collision and step-up decision, +including landing-height adjustment, a second collider query, and the first +candidate improving horizontal movement. `entity_collision_bounds` preserves +the initial entity query bounds. These helpers take caller-selected colliders; +they do not choose world/entity shapes, set grounding, change velocity, or apply +inside-block effects. + +The step-up corpus calls the actual private `Entity.collide` method for **17,680 +cases** per JAR. Reference fixtures supply entity inputs and controlled +block/entity/border shape lists; vanilla performs the movement decisions. Query +bounds and results are compared bit for bit. This verifies the decision with +those inputs, not live world selection or entity state transitions. + +`block_floor_height` returns the selected shape's maximum Y, or lazily queries +the lower shape only when the current one is empty. Its 12,000-case corpus also +checks the lower supplier's invocation count against `BlockGetter`. + +`traverse_blocks` visits blocks in vanilla ray order, including its endpoint nudge, +strict corner comparisons, early callback return, integer wrap and signed-zero +endpoint equality. It accepts finite rays and an explicit visit budget. Invalid +geometry or exceeding that budget returns a typed error; earlier callbacks remain +applied. Actual block/fluid ray selection is a separate integration task. + +Inclusive block-box iterators preserve X/Y/Z order, while directional iterators +preserve vanilla's movement-dependent axis order and corner signs. AABB iteration +includes floored maximum faces. They return independent position values and +reject true volumes above the positive Java-int domain, instead of reproducing +overflowed Java iteration counts. + +`sweep_intersected_blocks` ports movement-path visits from +`BlockGetter.forEachBlockIntersectedBetween`: tiny movement, the initial box, +ray-clipped footprints, packed-position deduplication, final box, step indices, +and early callback stops. Stationary/tiny movement avoids a deduplication-set +allocation. Inputs and computed geometry must be finite; a caller-selected work +budget counts ray steps and iterator candidates, including suppressed duplicates. +Earlier callbacks are not rolled back on an error. Block effects still need +their own implementations and integration with entity movement. + +`horizon-world::collision::CachedCollisionRegistry` imports a private local export +of vanilla cache data. The export includes DataVersion, all state descriptors, +deduplicated shapes, coordinate-kind metadata, discrete extrema, and a per-state +cache index. Import verifies every state ID +against the block registry. Section lookup also requires the same borrowed registry. +Imported nonempty extrema must agree with occupancy; empty extrema must be in +the grid's domain or match vanilla's empty-join sentinel triple. Extrema form part +of the grid-sharing key, so equal occupancy does not erase different metadata. +There is no fallback shape for an unsupported state: `None` means block behavior +must select it, while a cached empty shape is a valid `Some` value. + +This covers the cached branch of the **no-context** `BlockState.getCollisionShape` +method. Vanilla's overload taking `CollisionContext` always calls block behavior; +the cache cannot establish entity collision parity. Dynamic and entity-dependent +selection, neighboring blocks, world borders, movement integration, fluids, block +effects, and live collision broad-phase queries still need implementation. + +Run the comparisons after preparing the pinned artifacts: + +```sh +python3 tools/test_geometry_parity.py +python3 tools/test_collision_parity.py +``` + +Both suites invoke actual vanilla methods from the authenticated client and server +JARs. They compare canonical double bits, including infinities/NaNs, rather than +using a numerical tolerance. The geometry corpus includes empty and sparse grids, +greedy decomposition, overlapping boxes, rays, tiny movements and IEEE boundaries. +It compares **1,320,187 output lines per JAR**, including **2,400 integer-box +iterator cases**, **2,400 AABB iterator cases**, and **9,022 movement-path traces**. +The registry suite exercises cached shape queries through resident section IDs, +translation at negative and world-border coordinates, and invalid import rejection. +Its export records **35,524 cached states**, **199 uncached states**, **6,093 +shape identities**, and **330 distinct grids**. The comparison runs **213,144 queries** plus state/box/identity checks, +producing **1,097,456 matching output lines per JAR**. These counts describe this +branch and corpus; they are not a gameplay coverage percentage. + +Raw grids admit at most 1,048,576 cells with strictly increasing, non-NaN +coordinates. Oversized or malformed imports/joins return typed errors. This +bounded library API does not reproduce Java's complete exception/object surface. + +All exported data, test inputs, reference output, and compiled adapters remain +under gitignored `.local/`. Success reports record exact sources, inputs, outputs, +and reference hashes. A runner removes its prior success report before running +and rejects edits to the captured sources during validation. Passing these suites +does not prove whole-game parity or any FPS/render-distance improvement. + +Checked-in [geometry metadata](../benchmarks/rust-geometry-2026-10-05/scoped-parity.json) +and [cached-collision metadata](../benchmarks/rust-collision-2026-10-05/scoped-parity.json) +identify their tested source versions. Reports cover their recorded snapshots; +later changes require fresh validation. + +Entity obstruction now evaluates ordered candidate snapshots, excluded entity +identity, spectator/removal/building flags, shared root-vehicle identity and +voxel-shape intersection. Empty shapes skip the query; candidate collection +finishes before obstruction evaluation. Unit-block queries translate in floating +point, including integer-coordinate boundaries. Run +`python3 tools/test_entity_obstruction_parity.py` to compare against the actual +vanilla `EntityGetter` default methods and entity metadata queries. + +The [entity-obstruction report](../benchmarks/rust-entity-obstruction-2026-10-06/scoped-parity.json) +records **15,121 matching output lines per JAR** over composite shapes, boundary +contacts, thin boxes, metadata filters, vehicle roots and injected query failures. +The Java fixture privately allocates entity snapshots without running their +constructors. Entity lifecycle, spatial indexing and vehicle-tree maintenance +remain separate implementation work. Workspace tests, warning-free Clippy and +**138 Python tests** passed at this snapshot. + +Legacy block solidity now uses explicit definition overrides and cached collision +bounds, with force-on precedence and native mean-size/height thresholds. The +no-context replaceable and liquid flags are kept independently. Solid rendering +uses the occlusion definition flag and a full-shape test over imported raw +occlusion geometry. Import validates the pinned +DataVersion, full state identities and complete block definitions before building +a shared property table. Predicates query this table in constant time. + +`python3 tools/test_block_properties_parity.py` compares all **35,723 states** and +**18,096 synthetic cache/flag/shape cases**, including adjacent floating-point values +around solidity thresholds and both occlusion flag values. The [block-properties report](../benchmarks/rust-block-properties-2026-10-06/scoped-parity.json) +records **143,361 matching lines per JAR**. Definition flags, collision and raw +occlusion data are private runtime inputs; Rust calculates solidity and solid +rendering. The report was produced in an isolated staging copy and archived only +after the integrated sources and copied fixtures matched every recorded hash. +Item/fluid-context replacement and collision with live entities remain separate work. + +Face selection now preserves native cube-axis shortcuts, epsilon sample points, +slice coordinates and clamped parent extrema, including sparse slices whose +native bounds differ from occupied boxes. Repeated queries share face identities. +The FULL, CENTER and RIGID support tests execute against the selected shape. +`python3 tools/test_face_support_parity.py` compares **1,615 input shapes** and +nested faces, producing **595,686 matching lines per JAR** in the +[face-support report](../benchmarks/rust-face-support-2026-10-06/scoped-parity.json). +The [refreshed geometry report](../benchmarks/rust-geometry-2026-10-06/scoped-parity.json) +also retains **1,320,187 matching lines per JAR** after face slicing was added. +Block-specific support-shape selection is a separate layer. + +Registered support caches now derive FULL/CENTER/RIGID masks from privately +imported support geometry and share results by shape identity. The importer +checks the data kind and full state identities. `None` explicitly requests +uncached behavior; it never becomes an assumed unsupported face. +`python3 tools/test_block_support_parity.py` compares **35,524 cached states** +across six directions and three support kinds, while retaining **199 uncached +states**. The [cached-support report](../benchmarks/rust-block-support-2026-10-06/scoped-parity.json) +records **248,867 matching lines per JAR**. + +Face-cache storage is now lazy and attached to shape identity. Clones share it; +new identities and moved shapes start with an empty cache. A regression test +checks that cached faces do not retain their parent after it is dropped. The +face and geometry differential suites passed again after this allocation change, +as did workspace tests, Clippy and **140 Python tests**. No FPS claim is inferred +from these library checks. + +Dynamic support selection now handles bamboo collision offsets, dripstone and +sulfur-spike thickness/direction, the empty-context scaffolding support shape, +powder snow, and shulker animation-state support faces. Moving-piston lookup +preserves missing/wrong block-entity behavior and delegates active entity shape +calculation to the world. The [dynamic-support report](../benchmarks/rust-dynamic-support-2026-10-06/scoped-parity.json) +records **4,867,780 matching lines per JAR** over **107,308 fixtures** covering all +**199 uncached states**, coordinate boundaries, block-entity snapshots and query +failures. Run `python3 tools/test_dynamic_support_parity.py` to reproduce it. +The current suite also compares no-entity-context collision geometry in **60,161 +fixtures**, including **13,014 shulker progress fixtures**. Shulker collision +bounds retain native float interpolation and differ from animation-state support +faces. `BlockCollisionRegistry` dispatches cached and dynamic collision queries; +entity movement contexts and block-entity lifecycle remain separate work. +Workspace tests, warning-free Clippy and seven focused Python tests passed. + +Moving-piston collision now selects stationary extended bases and moving heads, +translates shapes using native float progress arithmetic, and honors the +movement-direction collision exclusion. Interpolation preserves float operation +order, including negative partial ticks and IEEE edge cases. The separate +collision-related state used for entity pushing retains its own sticky/head +rules; entity pushing itself is not implemented by this module. + +`python3 tools/test_piston_shape_parity.py` compares **102,315 fixtures**, +including every registered moved state and **10,000 raw float interpolation +cases**. The [piston-shape report](../benchmarks/rust-piston-shape-2026-10-06/scoped-parity.json) +records **1,096,811 matching lines per JAR**. This corpus uses absent block +entities for moved-block collision selection. Workspace tests, warning-free +Clippy and **142 Python tests** passed. Tick progression and live world mutation +remain separate work. + +The refreshed dynamic-support corpus also includes **9,216 active piston +snapshots**, composing block-entity lookup with piston collision generation and +all support tests. It compares extension/retraction, source heads, progress +boundaries, collision exclusions and query failures. These snapshots do not +exercise piston ticks, pushed entities or chunk updates. + +The archived block-survival snapshot executes 42 rule kinds with 54 distinct rule/tag +bindings over registry-bound solid flags, air identity, support tags and +FULL/CENTER/RIGID geometry. The verified snapshot covers **1,274 block definitions +and 34,758 states**; unsupported definitions return an explicit error. Candidate +properties select attachment direction, hanging state, door/plant halves and +pale moss carpet's serialized `bottom` property. Pressure plates and cactus +flowers preserve repeated neighbor reads. Downward center support applies the +unstable-bottom-center tag only where native helpers do. Upper doors require the +same block below; upper double plants also require its lower half. Crop survival +checks brightness against 8 before querying support; farmland preserves its +conditional second read above, and dripleaf stems read both neighbors. Sugar cane, +lily pads, frogspawn, spore blossoms, small dripleaves and tall seagrass preserve +their independent fluid queries, source/full-water requirements and tag checks. +Growing plants preserve head/body identity and kelp support restrictions. +Scaffolding recomputes neighbor distance in native order; chorus plants and flowers +preserve branching reads and early exits. Piston heads validate base type, facing +and extension. Mangrove propagules, speleothems, pitcher crops, bells and shelf +mushrooms use their version-specific attachment rules. + +Interrupted runs can be resumed with `python3 tools/test_block_survival_parity.py --resume`. +The runner verifies source, environment, fixture and compiled-artifact hashes +before reusing completed stages. A changed output is regenerated; changed inputs +require a fresh run without `--resume`. Checkpoints stay under `.local`, and +a parity report is written only after both native comparisons pass. + +`python3 tools/test_block_survival_parity.py` compares actual native `canSurvive` +calls in both pinned JARs. The [block-survival report](../benchmarks/rust-block-survival-2026-10-06/scoped-parity.json) +records **14,574,905 matching output lines per JAR** across **4,501,019 fixtures**. +Each supported candidate state is exercised; behavior representatives are tested +against every neighbor state, changing repeated reads, integer-coordinate +wrapping, absent/closed/open shulker snapshots and injected block/entity query +failures, plus light thresholds, independent fluid sequences and fluid-query +failures. Native method ownership +and support-tag fields supply private +definition metadata; survival results are calculated in Rust. Workspace tests, +Clippy, the prior **145-test Python suite**, and five focused harness tests passed. +This establishes the recorded survival +scope, not full placement, neighbor updates, unsupported plant rules or complete +block gameplay. diff --git a/docs/compact-headers.md b/docs/compact-headers.md index f9601c5e0..932d90a0a 100644 --- a/docs/compact-headers.md +++ b/docs/compact-headers.md @@ -52,7 +52,7 @@ measurements yielded the same medians: | Plain `Object` | 16 | 8 | [Raw platform results](../benchmarks/object-headers-2026-10-03) come from -[CI run 37153955462](https://github.com/ludovic111/minecraft-optimization-lab/actions/runs/37153955462). +[CI run 37153955462](https://github.com/ludovic111/Horizon/actions/runs/37153955462). Each platform has nine measured batches per type/mode across three JVM forks. The hosted ARM Mac has three logical CPUs and is not the user's M2 Pro. diff --git a/docs/debounce-queue.md b/docs/debounce-queue.md index 1707957f3..a22760e0c 100644 --- a/docs/debounce-queue.md +++ b/docs/debounce-queue.md @@ -59,7 +59,7 @@ Hosted medians and nearest-rank p95 over 20 measured trials: The upstream Mac maximum was 108.892 ms; its requested 50 ms sleep overshot. The wakeable Mac maximum also shows scheduler variability. The hosted ARM Mac has three logical CPUs and is not the user's M2 Pro. [Raw trials](../benchmarks/idle-queue-2026-10-03) -are from [CI run 37155695460](https://github.com/ludovic111/minecraft-optimization-lab/actions/runs/37155695460). +are from [CI run 37155695460](https://github.com/ludovic111/Horizon/actions/runs/37155695460). This isolates idle wakeup, including enqueue/pop overhead. It does not simulate the existing 250 ms debounce, preprocessing, chunk generation, meshing, network diff --git a/docs/density-functions.md b/docs/density-functions.md new file mode 100644 index 000000000..5357abeb3 --- /dev/null +++ b/docs/density-functions.md @@ -0,0 +1,502 @@ +# Compiled density evaluation + +Horizon targets the repository-pinned Minecraft Java Edition **26.3**. The +`horizon_core::density` module implements selected compiled samplers and an initial +integrated graph compiler. Complete graph coverage and terrain generation remain pending. + +Implemented samplers: + +- Constants, including signed zero and nonfinite values. +- Context-bound blend alpha, blend offset and structure density; blend-density wrappers. +- Axis gradients with clamped, repeating and mirrored repeating coordinates. +- Unshifted noise and both XZ and XYZ shifted-noise specializations. +- Shift, shift-A and shift-B offset noise; old blended terrain noise; outer End + island density. +- Euclidean, squared Euclidean, Manhattan and Chebyshev distance metrics and + distance-to-point evaluation. +- X/Y/Z coordinate slices and the combined XZ bulk specialization. +- Coarse-grid interpolation with positive horizontal and vertical cell sizes. +- Surface-height searches and their compiled horizontal slice. +- Nested cubic splines, lazy coordinate evaluation and spline range analysis. +- Absolute value, negation, square, cube, square root, logarithm, reciprocal, sign, squeeze + and leaky ReLU. +- Floor, nearest, ceiling and truncation to integer or sampled multiples. +- Addition, subtraction, multiplication, division, minimum and maximum, including + their constant-operand specializations; clamping. +- Powers with general, constant-base and constant-exponent samplers. +- Range choice with general or constant branches, and linear interpolation with + general or constant endpoints; single- and multi-threshold interval selection. + +Immutable samplers share children and noise sources through `Arc`. A worker owns +its `SamplerContext`, which retains temporary vectors for nested bulk evaluation +and returns them on typed errors. `clear_scratch` releases the retained buffers. +This avoids allocating a temporary vector for each repeated evaluation after +warm-up; no whole-game performance improvement has been measured. + +## World fields and references + +`WorldFields` stores immutable sampler bindings for blend alpha, blend offset and +structure density, plus an optional `DensityBlender` provider. A worker attaches +these with `SamplerContext::with_world_fields`; changing them clears its cached +densities. Context-bound samplers resolve the binding on each scalar or bulk call +and delegate with the same context. Missing bindings use constants 1, 0 and 0, +respectively, including constant bulk tail writes. Custom fallbacks are supported. +Declared metadata remains independent of the bindings: alpha has range `[0,1]`, +offset and structure density have infinite ranges, and their axis masks are X/Z, +X/Z and X/Y/Z. Uniform-axis rewriting follows that metadata even for synthetic +bindings which vary along omitted axes. + +`BlendDensitySampler` evaluates its input first. Absent or empty providers return +that result unchanged; other providers transform the logical volume in Z/X/Y +order while preserving the input's tail writes. Graph range and axes come solely +from the input. Differential checks cover absent and actual vanilla EMPTY Blender +contexts. Provider delegation/order tests do **not** validate the still missing +nonempty old-world blending algorithm or structure-density producer. + +Direct reference holders compare by their value; registered holders compare by +holder identity. `register_function` creates an immutable named holder and +`function` retrieves it. Raw compilation delegates through its value. Optimization +inlines one holder layer before detecting cache nodes, preserving vanilla's +ordering and nested-wrapper behavior. A holder whose child changes during +rewriting is replaced by that child directly. These choices affect constant +specializations and cache allocation, and are checked against actual vanilla +holder records, named registries and the compiler. + +## Graph compilation + +`density::graph` defines immutable constants, gradients, eleven unary operations, +six binary operations, powers, rounding, clamps, range choices, lerps, interval selection, +distance-to-point, slices, caches, interpolation, surface searches, nested splines, +registered normal/shifted noise, offset noise, old blended noise and outer End +island density, context-bound world fields, blend-density wrappers and direct/named +reference holders. +Definitions reference earlier nodes in the same graph; +construction rejects nesting beyond 256 nodes. For ordinary float fields, +structural interning distinguishes signed zeros and canonicalizes NaN payloads, +matching Java record equality. +Precompiled input bindings carry caller-supplied ranges and axis dependencies; +the compiler trusts this metadata. Bindings have distinct identities. + +`DensityCompiler::get_sampler` prepares shared caches, slices uniform axes, then +compiles and memoizes the root. Cache IDs belong to that compiler: worker contexts +must not reuse cache cells across compiler instances. Failed preparation consumes +its allocated ID and retains any successfully prepared children; retrying a failed +root does not return a cached failure. `compile_raw` bypasses rewriting and rejects +unprepared cache definitions. + +Compilation integrates range propagation with min/max specialization and scalar +short-circuit bounds. Strictly disjoint min/max ranges can eliminate a sampler, +but both children compile before that decision. Touching ranges retain the branch. +Literal operands select dedicated arithmetic paths, including reciprocal +multiplication for a literal right-hand divisor. These choices affect float bits, +child evaluation and buffer tails. Uniform-axis rewriting introduces zero slices +in X/Z/Y order, combines adjacent X/Z slices, and reduces child volumes while +retaining coordinate strides. + +The differential suite compares these passes with vanilla's actual +`DensityFunctionCompiler` across 368 independent unseeded graphs, 64 mixed seeded +graphs and six seeded failure cases, with 18,282 successful root compilation +requests. It checks declared ranges and axes, structural equality, cache-ID counts, +memoized sampler identity, failure state, scalar/bulk values and child call counts. +Some bound inputs deliberately use synthetic metadata to exercise compiler +decisions; those cases do not validate terrain metadata or seeded terrain output. +Serialized codecs, concrete world-field producers and complete terrain integration +remain pending. + +`DensityCompiler::new_seeded` fixes the world seed and random algorithm for the +compiler's lifetime. Registered noise definitions use canonical namespaced registry +identifiers; duplicate names are rejected. Ordinary noise instances reuse a sampler +created from the world positional factory and the identifier's hash. The +`minecraft:nether/temperature` and `minecraft:nether/vegetation` keys bypass that +map and create legacy Nether biome samplers from the world seed and seed plus one, +respectively. The addition wraps as Java `long`. `get_noise_sampler` exposes this +lookup for callers needing the same registered sources. + +Old blended terrain noise uses the world seed directly in legacy mode and the +positional `minecraft:terrain` stream in modern mode. Noise compilation retains +literal positive-zero tests when choosing unshifted, XZ and XYZ implementations; +negative-zero shifts retain the shifted path. Shift functions compile in X/Z/Y +order, while the XYZ sampler evaluates them in X/Y/Z order. Declared noise ranges +come from their registered definitions; axis dependencies combine nonzero scales +with all shift functions. + +The seeded oracle constructs vanilla's actual `RandomState` with a frozen test +noise registry, then uses its compiler and compile context. Constructor-only +material inputs use zero-noise fixtures; this does not validate material rules or +surface generation. The corpus includes extreme signed seeds, both algorithms, +instance identity, special Nether failures, offsets, blended noise and mixed +cached/interpolated/spline graphs. The graph API still expects registered, +canonical identifiers. The [world-generation codec suite](world-generation.md) +now loads and compares all bundled noise and density registry definitions against +the actual registry-aware codecs. Complete chunk generation remains pending. + +`EndIslandSampler` uses a legacy stream initialized directly from the world seed, +regardless of the world noise algorithm. It discards 17,292 random draws before +constructing simplex noise with skipped offsets. The island search retains +vanilla's strict noise threshold, float arithmetic, integer wrapping and division +toward zero for negative coordinates. Its declared range is `[-0.84375, 0.5625]`, +and its dependency mask is X/Z. Bulk sampling computes each horizontal column +once, repeats the result over Y and preserves the output tail. The center island +is supplied by the surrounding terrain graph; this source supplies outer islands. + +Spline coordinates can reference graph functions directly through +`CubicSpline`. Graph rewriting visits parent coordinates before nested +values, retaining repeated coordinate occurrences and point order. Compilation +shares structurally identical coordinate inputs, validates each unique coordinate +range immediately after compiling it, and then creates the existing spline +sampler. Graph range analysis remains lazy: a NaI coordinate can stop range lookup +before visiting a nested value even when compilation later rejects that value's +coordinate. Errors follow their respective traversal paths. Spline point arrays +use Java's bit-based equality, including canonical NaNs and distinct signed zeros. +The graph nesting bound includes paths through nested spline values and coordinate +definitions. + +Interval-selection definitions retain threshold order, duplicates and nonfinite +values. Their declared range covers all branches without asking for the selector's +range; their axis dependencies include both the selector and every branch. The +Rust definition API requires one more branch than thresholds and limits the list +to 256 branches. The JSON decoder separately requires ordered thresholds and a +minimum of two branches. Its ordering retains Java's float comparator, including +distinct signed zeros; equal consecutive thresholds are allowed. +Threshold lists retain vanilla's separate equality and hashing rules: opposite +zeros compare equal but hash differently; separate lists containing NaN compare +unequal. Thresholds use an immutable `Arc` so rewritten definitions preserve list +identity. Interning tracks equality classes and signed-zero hash differences, +including cancellation through parent definitions. `DensityGraph::java_equals` +exposes equality separately from interned IDs and compiler cache reuse. +Distance-to-point definitions declare all three axes and `[0, infinity]`, and +compile to the checked wrapping-coordinate metric sampler. + +## Scalar and bulk behavior + +Power graphs compile both children in base/exponent order before selecting a +specialization. A literal base takes precedence over a literal exponent. Otherwise, +literal exponents with absolute values one half, one, two or three select square +root, identity, square or cube. Negative exponents wrap those specialized samplers +in a reciprocal. Other exponents return directly from the fallback power sampler, +which uses the original signed exponent. These paths retain distinct float +arithmetic and signed-zero behavior. +General samplers evaluate both operands without zero/one shortcuts and retain +base writes if exponent evaluation fails. Constant-operand bulk samplers also +transform buffer tails. + +`RoundSampler` implements floor, nearest, ceiling and truncation to integer or +sampled multiples. Nearest uses Java's float-to-int rounding: ties go toward +positive infinity, NaNs become zero, and extreme values saturate to the signed +32-bit integer domain before conversion back to float. Floor, ceiling and +truncation retain nonfinite float values. A zero multiple returns the input, +preserving its signed zero and NaN behavior; the multiple still evaluates after +the input. Other multiples use float division, integer rounding and float +multiplication in that order. + +Only a literal-one graph multiple selects the integer specialization. It modifies +the input buffer, including its tail. A sampled multiple uses a volume-sized +temporary after the input and requires an exactly volume-sized output through +this Rust API. Failure in the multiple leaves input writes visible. Range +propagation evaluates the multiple's range first, divides the input range, maps +the rounding operation over the endpoints and multiplies by the multiple range. + +All densities are `f32`; noise coordinates and scales are `f64`. Gradient +coordinate arithmetic wraps as Java `int`, including overflow of the endpoint +difference and `MIN / -1`. Repeating gradients use floor division, not truncation. +A zero repeating period returns a typed error at evaluation time. Clamped +zero-width gradients retain the reference floating-point behavior. + +Scalar and bulk evaluation deliberately remain separate. Unshifted noise bulk +sampling calls the noise source's bulk kernel, whose arithmetic can differ from +scalar Perlin evaluation. Shifted noise evaluates child volumes first and then +samples its source using those values. XYZ evaluates shifts in X, Y, Z order; +XZ omits the Y addition entirely. Inserting a synthetic zero would change signed +zero behavior. + +Scalar multiplication and division return positive zero without evaluating the +right child when the left child is zero. Scalar minimum and maximum can skip the +right child using their supplied compiled range bounds. Bulk binary operations +evaluate both child volumes. Bulk minimum and maximum replace a value only on a +strict comparison; their handling of NaNs and equal signed zeros therefore differs +from scalar `Math.min` and `Math.max`. Constant-operand min/max retain that same +scalar/bulk distinction. Constant multiplication and division do not inherit the +generic scalar zero shortcut. + +Range choice samples its selector first and evaluates only the selected branch +for a scalar query. Bulk range choice evaluates the in-range branch first, then +the selector, then the out-of-range branch, retaining earlier output writes when +a later child fails. Interpolation evaluates only the selected endpoint at alpha +zero or one in scalar queries; bulk interpolation evaluates its dynamic endpoint +volumes before selecting or blending values. Constant endpoints avoid allocating +a scratch vector. Neither path clamps alpha to the unit interval. + +Interval selection preserves threshold order and chooses the first strictly +higher threshold, or the last branch. NaN comparisons fall through. Scalar +queries run only the selected branch; bulk queries evaluate the selector and +then every branch in order before replacing output values. A contiguous scratch +vector holds branch volumes, with an exact-volume slice passed to each child. +The Rust constructor requires one more branch than thresholds and caps the +number of branches at 256. The JSON decoder validates threshold order; it does +not sort the list. + +A slice's length is its logical density-buffer size. Constants fill that whole +slice. Unshifted noise clears it before accumulation. Gradients overwrite only +the volume's cells; shifted noise retains whatever its X child wrote outside the +volume. Unary operators transform the whole logical buffer after their child +returns. Binary, general range-choice, interval selection and interpolation bulk evaluation require exactly a volume-sized buffer, +matching the valid size of its temporary right-hand buffer. Horizon rejects an +oversized multi-input output before evaluating children; Java's accidental reads beyond +the temporary array and backing-pool capacity are outside this bounded API. +Short buffers are always rejected before writes. Errors from evaluated children +retain earlier writes, and scratch storage is returned for reuse. + +## Coordinate slicing + +`SliceSampler` fixes an X, Y or Z coordinate, or both X and Z. Scalar requests +replace those coordinates before calling the child. Bulk requests sample a +reduced volume once, then copy its samples into the repeated columns or planes. +The reduced descriptor retains the original steps on all axes, including fixed +axes, so cached children see the same descriptor as vanilla. Expansion uses +column copies or fills and does not repeat child sampling. + +When every fixed axis already has size one and the requested minimum coordinate, +the sampler passes the original output directly to its child. This distinction +preserves child writes outside the volume and partial writes on errors. Otherwise +the child receives scratch storage; its failure leaves the caller's output +untouched, and successful expansion writes only the volume's cells. Graph-level +slice insertion and combining adjacent X/Z slice definitions remain compiler work. +The corpus checks all four compiled forms, nested slices, cached children, +unchanged and reduced volumes, call counts, buffer tails and integer boundaries. + +## Grid interpolation + +`InterpolatedSampler` accepts positive XZ and Y cell sizes. A scalar request at +an exact grid point delegates to the child's scalar method. Other points sample +a `2 × 2 × 2` corner volume through the child's bulk method, then interpolate X, +Y and Z in that order. Negative positions use floor division and remainders; +corner coordinates retain Java integer wrapping. + +An aligned bulk volume whose steps equal the cell sizes delegates directly to +the child; size-one axes may have other steps. Other volumes sample a coarse +grid covering the requested block extent. The bulk path blends Z, then X, and +advances each Y column through repeated float additions. Scalar interpolation +uses division for its fractions; bulk interpolation uses precomputed reciprocal +multiplication. These differences can change low bits even with simple linear +input and are retained intentionally. End corners are clamped to the last coarse +sample when the output ends exactly on a grid point. + +For strided output, vanilla first evaluates a full block-resolution volume with +sizes equal to output sizes times steps, then selects the strided cells. Horizon +preserves that extent, including trailing blocks, the child's volume descriptor, +and the repeated-addition rounding. Scratch vectors are retained in the context. +The interpolating paths write only volume cells; direct delegation retains the +child's tail behavior. A failed coarse-grid child leaves the caller unchanged. +Invalid derived volumes are rejected through the bounded volume API; accidental +Java array behavior for overflowing or unallocatable extents is outside this +scope. The JSON decoder loads interpolation nodes with positive cell sizes. +Automatic insertion by the chunk-generation pipeline remains pending. + +## Surface-height search + +`FindTopSurfaceSampler` evaluates its upper bound, rounds it downward onto the +cell-height grid using the pinned float-to-integer floor behavior, then samples +density at descending grid heights. It returns the first strictly positive +sample, or the lower bound. Zero and NaN densities do not stop the search. When +the aligned upper height is at or below the lower bound, it returns immediately +without sampling density, including at the equal-height boundary. + +`compile_surface_search` adds the Y=0 slice used by vanilla's function compiler. +This forces the upper bound to be evaluated at Y=0 and repeats horizontal results +through the requested volume. The raw sampler accepts only one Y layer for bulk +requests. It first samples all upper bounds into the output, then searches columns +in Z/X order, replacing each successful result. A later child failure preserves +earlier results and the remaining upper-bound values. The surrounding slice can +instead isolate those partial writes in scratch storage. + +The constructor requires positive cell height. Manually constructed searches +whose descending height overflows return a typed error; wrapped nonterminating +searches are outside this bounded API. The differential corpus covers ordinary +finite bounds, exceptional float bounds with immediate crossings, grid alignment, +Y slicing, invalid multi-layer raw calls, cached children, NaN/zero crossings, +short circuits, buffer tails and child failures. + +## Cubic splines + +`CubicSpline` represents a constant or an immutable set of points. Each point has +a location, derivative and nested spline value. `SplineSampler::new` resolves +coordinate IDs against a density-sampler table and assigns compact local IDs in +parent-first traversal order. Repeated IDs share one coordinate cache. Structural +deduplication of equivalent density definitions remains graph-compiler work. + +Evaluation retains vanilla's binary interval search, including behavior for +manually supplied equal, unsorted or NaN locations. An endpoint extends linearly; +a zero derivative returns the endpoint value without multiplying a possibly +nonfinite coordinate. Interior evaluation samples the left nested value before +the right, then performs the float cubic correction in the reference order. +A constant NaN may occur as a nested value, but vanilla rejects it as the root of +a compiled constant sampler; Horizon preserves that distinction. + +Scalar queries compute coordinates lazily and retain non-NaN values for the +remainder of that query. NaN results are queried again when the same coordinate +is needed. Bulk evaluation walks output cells, evaluating a coordinate's entire +child volume only when a selected branch first needs it. Those buffers remain +available through the call, including NaN cells. Unselected coordinates are not +evaluated. A later lazy child failure retains completed output cells, and Horizon +returns acquired buffers to the context on both success and error. + +Constant roots fill the entire logical output slice. Nonconstant splines use an +exact-volume output; oversized output would read beyond coordinate buffers in +the reference and is rejected by the bounded Rust API. Spline nesting is bounded +to 256 levels, and empty point lists or unresolved coordinate IDs are rejected. + +Range analysis accepts coordinate ranges from the enclosing graph. It preserves +endpoint extension, child range evaluation order, all-point bounds and the +conservative derivative correction used by vanilla. A NaI coordinate stops +analysis before child ranges are evaluated. Invalid finite/nonfinite arithmetic +returns an interval error; the implementation does not substitute tighter bounds +or a numerically different cubic-extrema calculation. The JSON decoder loads +nested spline graphs, preserves their point order and requires explicit +derivatives. Spline builders and complete terrain integration remain pending. + +## Cached evaluation + +`SamplerContext::cached()` enables context-owned cache cells; the default context +continues to evaluate cache wrappers directly. `CachingDensitySampler` shares +immutable child samplers while keeping cached data in the context. IDs are +bounded to `0..=65535`, and the API rejects recursive evaluation of the same cache +cell. `DensityCompiler` allocates IDs for supported graph definitions. Callers +constructing cache samplers directly must supply consistent IDs themselves. + +A scalar request first checks its last-value cache, using vanilla's packed block +position as the key. This intentionally retains key collisions for coordinates +outside the packed domain. A NaN value is never a last-value hit. Next, a request +may read an exact lattice sample from the cached volume. Off-lattice positions +miss; lookup retains Java's wrapped relative coordinates and extent products. +A volume hit does not update the last scalar key, and replacing a volume does not +invalidate that scalar entry. These details matter because bulk noise can round +differently from a fresh scalar sample. + +A bulk request reuses its cached buffer when every volume descriptor field +matches. Otherwise it evaluates the child into a private retained buffer and +copies to the caller only on success. Vanilla installs that cache entry before +calling the child: a failed child can leave a partially written cached volume +that a later request reads without recomputation. Horizon preserves the writes +and the entry. Unwritten values are initialized to zero; failure comparisons use +a vanilla context with a zero-initializing arena. Unwritten data from vanilla's +global recycling pool is not claimed to match. Cached bulk output must have +exactly the volume's size; invalid lengths are rejected before child evaluation. +`clear_caches()` releases stored values and buffers for context lifecycle use. + +The differential corpus tests enabled and disabled caches, nested nodes, scalar +key collisions, NaN misses, repeated volumes, replacing volumes, on/off-lattice +queries and child failures. Counting wrappers report actual child scalar and +bulk calls as well as output bits, so a correct value produced through the wrong +cache path cannot silently pass the trace comparison. + +## Terrain noise composition + +The offset-noise compilers preserve the pinned version's evaluation paths. Shift +and shift-A use a noise sampler with quarter-scale coordinates followed by a +separate multiplication by four. Shift-A sets the vertical scale to zero. +Shift-B samples `(z / 4, x / 4, 0)` in scalar calls. Its bulk path constructs a +transposed horizontal plane, accumulates noise into that plane with amplitude +four, then repeats each result through its Y column. It leaves the output tail +untouched. These paths are checked with Perlin, simplex, smeared and modern +normal-noise stacks, from both random streams. + +`BlendedNoise` creates the minimum-limit, maximum-limit and main stacks in that +order from the caller's random stream. The two limit stacks contain 16 smeared +layers each; the main stack contains eight. Layers are created from high to low +frequency, retaining the version's double-precision amplitude calculation before +the float conversion. The compiled sampler adds `0.5` to the main result, clamps +it to `[0, 1]`, then interpolates the limit samplers. This composition reuses the +checked scalar/bulk sampler implementations, including their evaluation order. +Its declared range is computed separately from the limit-stack parameters. + +The public `create_blended_fbm` helper also supports first octaves from `-4095` +through zero. It rejects requests outside that work bound before consuming RNG +state. Invalid ranges are rejected at stack build time after layer construction, +matching vanilla's draw consumption within the supported bound. Serialized +parameter restrictions remain integration work; the graph compiler now supplies +the compile context's `terrain` seed lookup. The comparison corpus includes the bundled overworld/nether +and End parameter sets, valid random parameters, nonfinite inputs, constructor +failures, post-construction RNG state, octave metadata and scalar/bulk outputs. + +Distance-to-point evaluation subtracts coordinates as wrapping Java integers +before converting to floats. It retains the reference float arithmetic and +square-root conversion order, rather than using a double-precision hypot. +Metric tests also exercise arbitrary float inputs, including NaNs and infinities. + +## Interval analysis + +`Interval` implements checked exact, symmetric and general bounds; NaI and +infinite ranges; endpoint and interval hulls; addition, subtraction, +multiplication, division, min/max, reciprocal, absolute value, square, sign, +powers, logarithms, clamp, monotonic endpoint mapping and linear interpolation. + +Power propagation handles exact and interval exponents separately, including +signed-zero bases, negative bases with integer exponent bounds, infinite +exponents and NaI endpoint hulls. Negative-base ranges preserve vanilla's +floating-point neighbor checks when probing odd/even integer exponents. +Logarithmic ranges intersect the valid nonnegative domain before endpoint +mapping. A fully negative range becomes NaI. Square-root graph ranges use the +power interval with exponent one half, retaining valid endpoints even when +some input values produce NaN. + +These operations preserve vanilla's special rules. Multiplication treats a zero +bound times infinity as positive zero. The reciprocal of an exact zero interval +is NaI; an interval spanning both sides of zero maps to infinite bounds. Hulls +ignore NaI members unless all members are NaI. Monotonic mapping skips NaI and +otherwise evaluates both endpoints before rejecting a NaN result. It accepts a +caller-supplied transformation; neither implementation proves monotonicity. + +Interpolation range analysis has distinct finite- and infinite-endpoint paths. +It uses range-specific zero products and infinity handling, rather than calling +the scalar density interpolator. Interval construction also canonicalizes a +negative-zero lower bound when the upper bound is one, matching the reference's +cached `[0, 1]` instance. NaI compares equal to itself, and signed-zero endpoints +compare numerically equal. `java_hash_code` exposes vanilla's endpoint-bit hash +separately: implementing Rust `Hash` with that function would violate Rust's +requirement that equal keys have equal hashes for some signed-zero intervals. + +## Validation and limits + +Run `python3 tools/test_density_parity.py` after preparing the pinned artifacts +with `python3 tools/test_rust_parity.py --prepare`. The original Java adapter +instantiates the actual vanilla sampler classes; it does not duplicate their +arithmetic. Both the client and server JARs process the same deterministic corpus +as the release Rust binary. Reference artifacts are checksum-verified, and source +hashes must remain unchanged during a run. Finite outputs and signed zeros are +compared by bits, with NaNs canonicalized. + +The corpus includes all axes and tiling modes, raw floating-point inputs, +nonfinite values, overflowing block coordinates, both RNG streams, Perlin, +simplex and smeared noise, nested shift graphs, repeated bulk evaluations, +logical buffer tails, unary and binary combinations, scalar short circuits, +zero-period failures and partial writes. The runner removes an old success report +before artifact verification, so a failed run cannot retain a stale success. + +The [recorded local comparison](../benchmarks/rust-density-2026-10-05/scoped-parity.json) +matched **15,524,627 output lines per reference JAR**. + +The separate [float-log comparison](../benchmarks/rust-float-log-2026-10-05/scoped-parity.json) +exhaustively matched **all 4,294,967,296 float input bit patterns** for the compiled +scalar logarithm against both JARs on the recorded Linux/JDK runtime. Signed zeros, +subnormals, infinities and NaNs are included; NaN results use Java's canonical +`Float.floatToIntBits` representation. This does not establish double-precision +logarithm parity or other-platform math parity. Reproduce it with: + +```bash +python3 tools/test_float_log_parity.py --exhaustive +``` + +The default command checks 1,048,576 inputs around domain and rounding boundaries +and is configured in CI. The density suite covers bulk composition and graph +range propagation separately. + +Private inputs, output dumps and reference classes remain under +`.local/rust-density-parity/`. Only the metadata report belongs in +`benchmarks/rust-density-2026-10-05/`. Local results are Linux evidence; +configured Windows/macOS CI checks are not a claim that those remote jobs ran. + +Pending work includes remaining graph definitions, serialized graphs, +serialized registries, concrete structure-density and nonempty old-world blending +providers, and full seeded chunk generation. +This suite establishes only the operations and inputs it exercises; +it does not establish whole-game parity or an FPS/render-distance improvement. diff --git a/docs/dispatch-retry.md b/docs/dispatch-retry.md index 62e70865a..0ea8564b1 100644 --- a/docs/dispatch-retry.md +++ b/docs/dispatch-retry.md @@ -56,7 +56,7 @@ earlier patched return produce different caller durations; these measurements describe the rejected-submission path, not normal task throughput. Linux CI runs the applied hooks; Windows and ARM Mac CI compile the fixture and production mod. -In [Linux CI run 37158922187](https://github.com/ludovic111/minecraft-optimization-lab/actions/runs/37158922187), +In [Linux CI run 37158922187](https://github.com/ludovic111/Horizon/actions/runs/37158922187), [the raw fixture result](../benchmarks/dispatch-retry-2026-10-04/linux-applied-hooks.json) reported 216,987,192 caller allocation bytes and 63,790 rejections upstream, versus 103,384 caller bytes and 6 rejections with the hook. Caller wall times were diff --git a/docs/feature-placement.md b/docs/feature-placement.md new file mode 100644 index 000000000..2e686c3ad --- /dev/null +++ b/docs/feature-placement.md @@ -0,0 +1,543 @@ +# Feature placement + +Horizon implements eighteen Java Edition **26.3** placement modifiers: count, +square spread, three-axis offset, height range, rarity filtering, random-chance +filtering, fixed positions, random selection among modifiers, heightmap positions, surface-relative +thresholds, water-depth filtering, both noise-based count forms, cuboid placement, +count-on-every-layer scans, predicate filtering, vertical environment scans and biome filtering. + +Placement preserves callback order, duplicate positions, wrapping coordinates, +provider sampling and random draw consumption. Fixed positions are filtered by +the origin's chunk X/Z. Random-choice nesting is bounded to depth 256 and 65,536 +modifier nodes; lists are bounded to 8,192 entries. Consumer failures retain +previous emissions and consumed draws. Probability-range decoding distinguishes +negative zero from positive zero, matching the native codec. + +Run `python3 tools/test_placement_parity.py`. The +[local report](../benchmarks/rust-placement-2026-10-06/scoped-parity.json) records +**1,268,600 matching lines per reference JAR**, across **520 definitions** and +**21,840 seeded fixtures**, with **70,080 requested modification calls** and **17,280 direct count queries**. Actual +`PlacementModifier.CODEC` and modifier callbacks supply the reference results. +The corpus tests both random modes, relative-height overflow, nested choices, +malformed fields, repeated calls, consumers that draw randomness and failures +before or after earlier emissions. + +This suite uses an actual placement context backed by a world proxy with traced synthetic heightmaps. +Additional block predicates, full feature registries, registry integration, +Gaussian providers, encoding and complete generated worlds remain pending. + + +## Modifier chains + +`FeaturePlacer` collects a modifier's outputs before processing its descendants, +preserving sibling order through a reusable pending stack. Actual feature callbacks +share the modifier random stream. Boolean results accumulate without skipping later +placements. An empty chain calls the feature directly. Errors retain pending and +modified-position buffers, matching vanilla when the same placer is used again. + +Run `python3 tools/test_feature_placement_parity.py`. The +[chain report](../benchmarks/rust-feature-placement-2026-10-06/scoped-parity.json) +records **548,461 matching lines per JAR**. Actual native `FeaturePlacer` executes +native modifiers and a synthetic feature sink, comparing emitted positions, +feature results, consumed randomness and repeated calls after failures. This tests +the execution machinery; the separate feature suite below connects it to initial block-writing algorithms. + +Rust bounds chains to 1,024 modifiers and per-call work/pending buffers to 2^20. +Unit tests reject oversized chains before feature calls or random draws and stop +multiplicative count expansion after bounded partial progress. + + +## Heightmap queries + +`PlacementContext` supplies generation bounds, the world minimum and heightmap +queries. These are separate: the world minimum can differ from the generator's +minimum. Heightmap placement emits only above the world minimum. Surface-relative +thresholds use 64-bit sums; water-depth subtraction retains Java integer wrapping. +Queries and emitted positions retain native order, and query errors stop the +current operation without drawing randomness or emitting a replacement position. + +Both suites include ordinary/extreme synthetic heights, all six map types, +distinct world/generator minima, default/reversed threshold ranges and injected +query failures. This validates how modifiers consume heightmaps; connecting +feature generation to complete world regions remains pending. + + +## Noise-based counts + +Noise-based and noise-threshold counts share vanilla's fixed biome-information +simplex noise. They preserve the float noise result before double arithmetic, +ceiling/narrowing behavior and strict threshold comparison. They consume no caller +random draws. `repetitions` exposes counts without expanding position lists. + +Primitive comparisons include extreme ratios, factors, offsets and thresholds, +including count-only queries that can return enormous counts safely. Chain tests +exercise ordinary noise counts together with other modifiers and feature callbacks. +Emitting repeating modifiers remains bounded to 4,096 repetitions in Rust. + + +Cuboid placement samples Y size, then independent X and Z sizes, before emitting +positions in X/Y/Z order. Its extents are inclusive. Edge and interior controls +are independent, and coordinates wrap. The suites cover all four control +combinations, provider variation, maximum decoded extents, consumer failures and +cuboids embedded in modifier chains. + + +## Layered placement + +Count-on-every-layer placement samples its count provider at every loop-condition +check, including the final check. Each attempt draws X/Z offsets, queries the +motion-blocking heightmap and scans down for the requested surface layer. Air +states and exact water/lava blocks count as empty. Bedrock is excluded as ground; +other blocks, including bubble columns, are potential ground. Emissions and count +sampling interleave, sharing the caller's random stream. + +The suites compare traced synthetic strata containing these block kinds, random +count providers, repeated passes and injected height/block/consumer failures. +`LayerBlock` is a query classification supplied by the world; complete block +behavior and region-backed feature generation remain pending. A shared 65,536-step +budget bounds scans, including when world queries supply extreme heights. + + +## Initial block-writing features + +`BasicFeature` implements the void start platform, End islands and the End +arrival platform. The world supplies block reads and mutations; required block +states bind through its registry. The algorithms preserve write order, update +flags, wrapped coordinates, ignored false mutation results and partial effects +when a world operation fails. End-island radius sampling retains native draw order. + +Run `python3 tools/test_basic_feature_parity.py`. The +[feature report](../benchmarks/rust-basic-feature-2026-10-06/scoped-parity.json) +records **1,820,614 matching lines per JAR**. Actual feature codecs and native place +methods operate on a mutable world proxy. Both random modes, multiple seeds, +nearby/far chunks, extreme coordinates, rejected writes, thrown failures and +repeated placements are compared, including complete accumulated stored states. +Native `setBlockAndUpdate` executes its actual default method, exposing its flags. +The suite also composes these features with modifier chains, sharing the mutable +world and random stream and reusing placer buffers after failures. +`place_with_context` gives feature callbacks the same world used by modifiers. + +This covers feature algorithms against a supplied mutation interface. Actual chunk +mutation, neighbor updates, lighting, entities/drops, complete feature registries +and generated worlds remain pending. The End-platform generation path does not +request the separate block-destruction/drop behavior used by portal recreation. + + +## Predicate filters and environment scans + +Logical predicates (`true`, `not`, `all_of`, `any_of`) preserve ordered +short-circuiting, including empty-list identities. Inside-world-bounds predicates +apply wrapping offsets before checking the world's inclusive height bounds. +Their offset codec retains Java's wrapping absolute-value behavior for the +minimum signed integer. These five predicate kinds also work inside filters and +vertical scans; state-dependent predicates remain pending. + +Environment scans check the initial allowed condition before the target, then +move one block at a time. They stop immediately outside build height. A failed +allowed condition after a move still permits the final target test at that +position. The codec limits scans to 1–32 steps; shared work and nesting budgets +also bound directly constructed predicates and scans. + +Both placement suites compare actual native codecs and predicate execution, +traced world-bound queries, short-circuiting, wrapped offsets, invalid directions, +step limits and query failures. Unit tests exercise oversized trees and scans +that would otherwise traverse billions of positions. + + +## Resident feature regions + +`TerrainRegion` routes block reads/writes by signed chunk coordinates and lazily +primes missing heightmaps. It requires consistent vertical bounds and registry +identity across resident chunks. Its placement context supplies generation bounds, +world bounds, heightmaps and layer classifications from those same chunks. +`TerrainFeatureAccess` shares that region with feature algorithms and forwards +all writes and flags to a caller-supplied mutation callback. + +Run `python3 tools/test_feature_region_parity.py`. The +[region report](../benchmarks/rust-feature-region-2026-10-06/scoped-parity.json) +records **28,922,634 matching lines per JAR** across 192 fixtures and 2,304 requested +placements. Actual native features and `FeaturePlacer` operate over a world proxy +backed by nine `ProtoChunk`s per fixture. The comparison includes both heightmap +groups, count/square/heightmap/layered chains, repeated writes, missing neighbors, +rejected writes, failures, update flags, random state, final raw sections and +packed heightmaps. + +The region corpus also runs a composed sequence of configured fill layers over +the same live chunks: water, horizontal logs, air and an out-of-height layer. +This connects block-state decoding, nested feature execution, shared placement +and chunk heightmap updates; the standalone fill-layer suite below covers +integer-property parsing and per-column query ordering in more detail. +Single-block replacement and scattered ore also execute against those resident +chunks, sharing the updated state, heightmaps, failure policy and random stream. + +The reference proxy supplies storage mutation. This verifies the connection +between features, placement queries and resident chunks; actual region write +zones, POIs, block entities, postprocessing, lighting and the full feature registry +remain pending. Unit tests check mixed-registry/bounds rejection, negative chunk +routing, missing-neighbor errors and mutation-callback flag/return handling. + + +## Inline feature composition + +`FeatureDefinition` and `PlacedFeatureDefinition` compose the initial block-writing +features with no-op, sequence, boolean choice, uniform choice, chance-based +choice and weighted-choice features. Sequences stop on the first false child. Selectors return the +chosen child's result directly. Child modifiers and features share world state +and randomness; each sequence uses one fresh placer across its children. +Native single-object holder-set shorthand is accepted for sequence/uniform lists. + +Run `python3 tools/test_feature_graph_parity.py`. The +[graph report](../benchmarks/rust-feature-graph-2026-10-06/scoped-parity.json) records +**737,779 matching lines per JAR** for actual native feature codecs and nested +placement. Cases include empty/malformed lists, singleton and nested choices, +zero/one probabilities, negative zero, false child results, partial writes, world +failures, repeated calls and top-level modifier chains. + +Decode depth, node count and list size are bounded. Feature/placed-feature visits +and nested modifier-chain execution share a runtime budget. Unit tests cover deep +decoding, large trees and modifier expansion that reaches no leaf features. +Weighted choices retain zero-weight children and return false without random draws +when their total weight is zero. Positive totals preserve the existing bounded +weighted draw algorithm. `OptionalWeightedList` keeps this behavior separate from +the nonempty weighted lists required by integer/height providers. The graph suite +covers empty/zero lists, integer narrowing, invalid/overflowing weights and nested +choices; both provider suites also pass after the shared implementation change. +The resource resolver below adds named holders and tags. Encoders and the full +feature registry remain pending. + + +## Named feature resources + +`FeatureCatalog` stores an immutable resource snapshot and resolves requested +feature or placed-feature roots. Named children, compact singleton holder sets, +mixed named/inline lists and ordered placed-feature tags expand into executable +trees. Resolution preserves numeric JSON fields, validates unselected children +and bounds dependency depth and expanded nodes. Duplicate canonical resource +names, missing dependencies and cycles return errors. + +Run `python3 tools/test_feature_catalog_parity.py`. The +[catalog report](../benchmarks/rust-feature-catalog-2026-10-06/scoped-parity.json) +records **1,734,390 matching lines per JAR** against actual registry-aware holder +codecs, registered feature snapshots and native `TagLoader`. It compares nine +named features, fourteen placed features, five tag files, nested/duplicate references, +optional/required missing tags, namespace shorthand and subsequent execution. +Configured fill layers, single-block replacements and scattered ore bind block-state +metadata through named roots, nested tags and modifier chains. Block-set +predicates execute through filters, ordered volumes and environment scans against +the mutable world, including repeated placement after earlier writes and flowing-water replacement +that changes later fluid-predicate results. + +Empty named tags retain a native distinction from empty inline lists: a sequence +can resolve an empty tag and succeed, while a uniform selector resolves it and +then fails its zero-bound random choice. The inline list codecs reject empty +lists during decoding. These cases and their random-state effects are compared. + +The resource API validates requested reachable roots, allowing unused unported +resources to remain in the snapshot. Complete datapack loading, live reloads, +registry ownership/identity semantics and all feature algorithms remain pending. + +## Configured fill layers + +`FeatureBlockBindings` binds block-state JSON against the pinned registry and its +integer-property metadata. `FillLayerFeature` visits 16 by 16 columns in native +X/Z order, queries the world minimum for each column and replaces only air states. +It preserves wrapping coordinates, write flags, ignored false write results and +early termination on world errors. Placement consumes no random draws. + +Run `python3 tools/test_fill_layer_parity.py`. The +[fill-layer report](../benchmarks/rust-fill-layer-2026-10-06/scoped-parity.json) +records **1,305,274 matching lines per JAR**, including codec inputs for all +35,723 pinned states, compact/full states, integer properties, invalid-property +defaults, height bounds, extreme coordinates, rejected writes and injected query, +read and write failures. Both random implementations retain matching subsequent +state. This comparison uses observable mutable storage; complete region effects +and full generated worlds remain pending. + +## Replacement rules + +`RuleTest` implements all ten pinned replacement-rule kinds: constant true, +negation, all/any, block identity, exact block state, block tags, inclusive height +range and the two random block/state matches. Logical rules preserve ordering and +short-circuiting. Random rules draw only after matching identity, including at +zero/one probability; their codecs allow probabilities outside that interval. + +Run `python3 tools/test_rule_test_parity.py`. The +[rule report](../benchmarks/rust-rule-test-2026-10-06/scoped-parity.json) records +**1,890,716 matching lines per JAR**, covering every block/state identity, all +300 bundled block tags, absent and empty-path tags, malformed inputs, reversed +height ranges, nested logic and subsequent draws from both random streams. +Decode depth, node count and list size are bounded, including branching inputs. + +Bindings share immutable sets of state IDs for blocks and resolved tags. +Native tag identifiers permit an empty path, which remains distinct from a +missing field. These predicates do not establish complete ore generation or +structure-processor behavior. + +## Single-block replacement + +`ReplaceBlockFeature` applies ordered rule/state pairs at an origin. It re-reads +the current state for each candidate and stops at the first match, regardless of +whether the write returns true. Empty or unmatched target lists still succeed; +read/write errors stop evaluation with the preceding mutations and RNG state +intact. Target decoding shares the graph's node budget when nested in a feature. + +Run `python3 tools/test_replace_block_parity.py`. The +[replacement report](../benchmarks/rust-replace-block-2026-10-06/scoped-parity.json) +records **303,678 matching lines per JAR** for actual native codecs and placement, +including rule ordering, shared random state, update flags, rejected writes, +partial failures, repeated mutations and invalid unselected targets. + +## Scattered ore + +`ScatteredOreFeature` samples the native attempt count, consumes six float draws +for each offset (including zero spread), rounds with Java's tie behavior and +captures the candidate state once per attempt. Matching target rules then apply +the configured air-exposure probability and ordered directional neighbor checks. +The first accepted target writes with flag 2; a false write result is ignored. + +Run `python3 tools/test_scattered_ore_parity.py`. The +[scattered-ore report](../benchmarks/rust-scattered-ore-2026-10-06/scoped-parity.json) +records **758,484 matching lines per JAR** across 11,544 fixtures and 23,088 +requested placements. Cases include size/discard codec boundaries, empty targets, +solid/mixed worlds, each of the six air-neighbor directions, wrapping positions, +partial failures, rejected writes and both shared random streams. + +Ordinary ore veins use a separate bulk-section mutation path and remain pending. +A private Linux/JDK 25 probe also found 4,935 bit differences among 2,581,112 +double sine/cosine results for sampled ore angles when using Rust platform math. +Those intermediates are not yet validated for vein geometry; no exact double-trig +parity is claimed. +This scoped feature comparison does not establish biome decoration or full +generated-world parity. + +## Bulk section access + +`TerrainBulkAccess` exclusively borrows resident chunks and caches sections by +vanilla's packed section key. Raw reads retain cave/void air even when normal +chunk reads collapse an all-air section to AIR. Outside-height reads return AIR +before resolving a chunk. Raw writes maintain section occupancy but leave chunk +heightmaps untouched; region write permissions remain the caller's responsibility. + +Run `python3 tools/test_bulk_section_parity.py`. The +[bulk report](../benchmarks/rust-bulk-section-2026-10-06/scoped-parity.json) records +**959,640 matching lines per JAR** against actual `BulkSectionAccess` and resident +`ProtoChunk`s. It covers every state, primed/lazy heightmaps, missing chunks, +vertical boundaries, packed-coordinate aliases, cache reset and complete final +section/heightmap data. The exclusive Rust borrow replaces Java's acquire/release +locks within this resident-region API; concurrent section ownership remains pending. + +## Biome feature ordering + +`build_features_per_step` combines ordered biome feature lists using placed-feature +object identities. It assigns encounter indices, orders graph traversal by step +and index, detects cycles and reverses DFS completion order to produce each step's +feature list and identity-to-index mapping. Equal feature payloads remain separate +when their identities differ. Traversal uses an explicit stack and bounded input +work; tests include a 50,000-feature dependency chain. + +Run `python3 tools/test_feature_sort_parity.py`. The +[ordering report](../benchmarks/rust-feature-sort-2026-10-06/scoped-parity.json) +records **411,751 matching lines per JAR** across 3,871 fixtures. Native +`FeatureSorter` receives identity-distinct dummy payloads for synthetic graphs and +the feature lists from all 67 bundled biomes, including shuffled/subset combinations. +Cycles, duplicate references, cross-step reuse, empty steps and index lookups are +compared. Cycle diagnostic minimization/text and complete decoration remain pending. + +## World-generation random streams + +`WorldgenRandom` applies vanilla's legacy bit-sampling interface to legacy or +xoroshiro sources. Longs and doubles retain their multi-draw assembly, bounded +integers retain legacy rejection and each bit request increments a wrapping count. +Reseeding preserves the counter. Forks and positional factories delegate to the +underlying source and return its normal draw behavior through a transparent variant. + +Run `python3 tools/test_worldgen_random_parity.py`. The +[random-adapter report](../benchmarks/rust-worldgen-random-2026-10-06/scoped-parity.json) +records **238,800 matching lines per JAR** for 119,100 operations in 300 fixtures. +It includes one to three nested wrappers, arbitrary signed bit-width shifts, +failed bounds, parent/child streams, positional UTF-16 hashes and decoration, +feature, large-feature, salted and slime-chunk seeds with int/long overflow. +Gaussian sampling, concurrent use and complete chunk decoration remain pending. + +## Biome placement filtering + +`Biome` requires the invocation's top placed feature before querying the biome and +its generation settings. `place_with_biome_check` establishes that context for +the current modifier chain; a nested ordinary placer starts without it. Biome +resolution and membership are supplied by the world. Native membership treats +structurally equal placed-feature copies as equal, while feature ordering uses +object identities. + +Run `python3 tools/test_biome_placement_parity.py`. The +[biome-filter report](../benchmarks/rust-biome-placement-2026-10-06/scoped-parity.json) +records **121,423 matching lines per JAR** for 27,456 requested placements across +9,152 fixtures. Actual `BiomeFilter` and `FeaturePlacer` compare missing roots, +equal copies, different features, ordered queries, nested ordinary placement, +injected failures and repeated calls with retained buffers. Both random sources +are tested directly and through `WorldgenRandom`. Complete registry membership, +biome sampling integration and chunk decoration remain pending. + +## Decoration feature scheduling + +`FeatureDecorationPlan` owns immutable biome generation lists and their globally +ordered step features. It reads the surrounding nine chunks in X-first order, +intersects their resident biomes with the generator's possible-biome set and +executes the sorted union of global feature indices for each step. Each root +receives its decoration/feature seed and a shared placer. False results do not +skip subsequent roots. Errors retain previous work and the current-feature +marker; successful completion clears the marker. + +Run `python3 tools/test_decoration_parity.py`. The +[decoration report](../benchmarks/rust-decoration-2026-10-06/scoped-parity.json) +records **337,398 matching lines per JAR** across 2,188 fixtures and 4,376 requested +decoration calls. Actual `ChunkGenerator.applyBiomeDecoration` runs with +structures disabled, resident `ProtoChunk` biome palettes and traced feature +sinks. All 67 bundled biome feature lists participate. Sparse selections, +excluded biomes, step gaps, cycles, coordinate overflow, biome-check modifiers, +false returns and query/placement/progress failures are compared. Rust bounds +extreme signed chunk neighborhoods and input work explicitly. Structure +decoration, real feature payloads in this suite and full chunk lifecycle remain +pending. + +## Decoration over resident chunks + +`BiomeRegion` connects quart biome sections to seeded block-position biome zoom. +`TerrainRegion::biome_at` checks the selected chunk's generation stage before +reading its biome. Premature reads fail even if raw palette values already exist; +decoration's initial palette collection can still inspect those raw values. + +Run `python3 tools/test_decoration_region_parity.py`. The +[resident decoration report](../benchmarks/rust-decoration-region-2026-10-06/scoped-parity.json) +records **36,173,951 matching lines per JAR** for 240 fixtures and 480 requested +decoration calls. Java's actual decoration entry point places three basic +features, configured fill-layer sequences, replacements and scattered ore into +nine `ProtoChunk`s. Uniform/mixed biome palettes, biome zoom, global scheduling, +feature seeds, biome filters, named biome-set and volume predicates, live +heightmaps, repeated decoration and rejected +or failed writes execute together. Every final raw block and heightmap word is +compared, including EMPTY, BIOMES and TERRAIN stage behavior. Workspace tests, +Clippy and 137 Python tests passed after this integration. + +The world transport supplies storage mutation. Actual `WorldGenRegion` write +zones, retrogen, POIs, block entities, postprocessing, lighting, structures and +the complete noise-to-decoration lifecycle remain pending. + +## Block-state providers + +`BlockStateProvider` supports simple states, weighted states, random blocks, +rotation, property copying, randomized integer properties, three noise-based +providers and rule-based selection. Direct decoding preserves the exclusive choice +between a full state object and a typed provider. Random block choices retain +holder/tag order and duplicates. Empty choices return no optional state, while +ordinary sampling reads the existing world state. Rotation chooses a direction +before sampling its nested provider, changes only compatible axis/facing +properties and preserves other properties. Fixed directions consume no direction +draw. Property copying preserves only compatible property families. Integer +sampling leaves states without the named integer property unchanged without +drawing a value; invalid sampled values fail after consuming the draw. Shared +compact state layouts avoid rebuilding property maps during these transforms. + +Noise providers use independently seeded legacy noise and preserve the native +float/double coordinate conversions. Threshold selection preserves conditional +random draws. Dual noise computes the selected candidate directly: the other +candidates are pure noise queries without random or world side effects. +Rule-based providers evaluate conditions in order, continue after empty optional +results and sample their fallback only after all rules are exhausted. Current +conditions cover true, not, all-of, any-of, world bounds, height ranges, block tags +volume matching and registry-bound block/fluid/biome sets. Height-range predicates reconstruct generation bounds per +evaluation; volume matching visits X, Z, then Y and stops on the first failure. +World adapters supply tag membership and fallible generation-bound queries. The +height-range comparison currently exercises ordinary LevelAccessor bounds; the +WorldGenLevel server/generator lookup branch is not covered by this fixture. + +Interrupted runs can be resumed with `python3 tools/test_state_provider_parity.py --resume`. +The runner verifies source, environment, fixture and compiled-artifact hashes +before reusing completed stages. A changed output is regenerated; changed inputs +require a fresh run without `--resume`. Checkpoints stay under `.local`, and +a parity report is written only after both native comparisons pass. + +Run `python3 tools/test_state_provider_parity.py`. The +[provider report](../benchmarks/rust-state-provider-2026-10-06/scoped-parity.json) +records **105,340,143 matching lines per JAR**, with 299,507 codec inputs +and 39,270,062 requested samples across ten provider kinds. Every pinned state is decoded and tested +under all six fixed rotations; random/nested rotations, both sampling methods, +empty tags, weighted boundaries, fallback query failures and four random-stream +combinations are compared. Every target state is also tested against +representatives of all compatible property values, including cross-block copies +and integer-property boundaries. The native harness verifies that the pinned +property-family signatures are unambiguous; Rust validates the Cartesian state +tables before binding their transitions. Noise cases include all eight bundled +provider definitions, coordinate boundaries, extreme scales, variety +selection and malformed codec inputs. Rule cases cover ordered empty results, +fallbacks, nested rules, bound-query failures and wrapping coordinates. Block-tag +cases cover every tag against all block defaults and the two bundled rule-based +definitions against every state. Volume comparisons include exact read order and +early exits, while Rust-only tests bound pathological nested evaluation work. Workspace +tests, Clippy and 137 Python tests passed at this stage. + +The unobstructed predicate validates its optional integer-vector offset but +ignores it during evaluation, matching the pinned Java implementation. The +comparison checks exact translated unit-block bounds, a null excluded entity, +true/false world results, nested volumes and query failures. + +`BiomePredicateBindings` resolves biome names and holder tags to IDs in the +world's owning registry snapshot. The comparison covers every pinned biome and +every bundled biome tag, empty sets, missing names, query failures and nested +volume/short-circuit conditions. Decoration shares the same `BiomeId` identity. + +`FluidStateTable` derives fluid identity, amount, falling/source flags and own +height from the pinned block descriptors. The harness compares every state, +including falling source water in all eight waterlogged copper grates. Fluid +predicates compare all five fluid kinds, holder lists and every bundled fluid tag +against every block state. This covers contained fluid state, not spreading or +entity interactions. + +`StateProviderCatalog` resolves named holder references from an immutable resource +snapshot. Holder, direct and typed entry points retain their distinct decoding +semantics, including ambiguous state/provider objects. The comparison registers +all eight bundled definitions plus nested fixture resources and checks missing +names, nested references and later random draws. Unused resources are not +evaluated; Rust tests reject reachable cycles, duplicate canonical names and +excessive expansion. Full datapack registry loading/reloading remains separate. + +Recursive provider decoding is bounded to depth 128 and shares a 65,536-node +budget with rules, predicates and integer providers; holder/rule lists are bounded +to 8,192 entries. Additional predicates, complete registry loading, block survival +and complete feature placement remain pending. + +Solid and replaceable predicates now bind immutable property tables to the same +block registry as provider and feature decoding. Their offsets, state reads, +short-circuit composition, empty optional-child fallthrough and read failures +are compared across the entire state registry. Together with the earlier kinds, +**14 block-predicate kinds** are covered in the state-provider report. Full +workspace tests, warning-free Clippy and **139 Python tests** passed at this +integration snapshot. Face support and block survival still need implementation. + +The has-sturdy-face predicate now decodes native directions and bounded offsets, +then delegates the ordered state/support query to its placement world. The +state-provider comparison covers all **35,524 cached states**, six directions, +read failures and composed predicates, bringing the scoped corpus to **15 +predicate kinds**. Dynamic state support is not established by this integration +report; unavailable world behavior remains an explicit query error. Workspace +tests, warning-free Clippy and **140 Python tests** passed at this snapshot. + +Unified block-support dispatch now extends that predicate corpus to all **35,723 +states**, including the **199 dynamic states** with absent block entities and +injected block-entity query failures. The updated provider report covers the +combined path. Shulker animation snapshots are covered separately by the dynamic +support suite; active moving-piston shape generation and block-entity lifecycle +remain outside this integration snapshot. Workspace tests, Clippy and **141 +Python tests** passed. + +The `would_survive` predicate now decodes a candidate block state and bounded +offset, then invokes survival at the translated position without placing it. +Both provider and feature bindings use the shared block-state codec; placement +chains forward the survival query. The refreshed provider report records +**105,340,143 matching lines per JAR**, **299,507 inputs**, **39,270,062 requested +samples** and **16 predicate kinds**. Its survival snapshot covers 15 rules, +1,138 definitions and 31,171 candidate states, with each rule tested against the +entire neighbor-state registry, malformed definitions, wrapped offsets, +short-circuit conditions, optional-child fallthrough and query failures. +Unsupported survival definitions remain errors. This report does not establish +full block placement or every block's survival behavior. Workspace tests, +warning-free Clippy and **143 Python tests** passed at this snapshot. diff --git a/docs/heightmaps.md b/docs/heightmaps.md new file mode 100644 index 000000000..74d28b21c --- /dev/null +++ b/docs/heightmaps.md @@ -0,0 +1,57 @@ +# Heightmaps + +Horizon implements the six heightmap types in the pinned Minecraft Java Edition +**26.3**. Each map stores 256 relative column heights in padded 64-bit words. +World-surface predicates use `isAir`; ocean-floor predicates use the version's +`blocks_motion_in_heightmap` block tag. Motion-blocking maps also include nonempty +fluid states, with the separate no-leaves tag for that variant. + +`HeightmapState` supplies block behavior and tag membership. `HeightmapChunk` +supplies the vertical extent, highest occupied section and block reads. The map +owns its packed data and checks that a supplied chunk has the same bounds. Its +current constructor accepts positive, aligned ranges within the vanilla noise +settings codec domain; zero-height and arbitrary runtime accessors are outside +this bounded API. + +Updates retain the early return for blocks below the top two positions. Removing +a qualifying surface scans downward until another qualifying block is found. +Priming scans X, then Z, then descending Y, sharing each block read across the +selected maps. It skips exact AIR blocks and stops a column when all selected +maps have found a surface. If a column finds nothing, its existing value remains. +This also applies to re-priming after a raw-data length mismatch. + +Raw imports preserve every bit when the word count matches, including padding, +unused slots and values above the build height. Column addressing retains Java's +wrapped `x + z * 16` calculation; invalid final indices return typed errors. The +Rust API does not expose a mutable alias to its internal words. + +Run the differential suite with: + +```sh +python3 tools/test_heightmap_parity.py +``` + +The [local metadata report](../benchmarks/rust-heightmap-2026-10-06/scoped-parity.json) +records **1,671,668 matching output lines per reference JAR**, checked separately +against the authenticated client and server. It covers all **35,723 block states**, +all six predicate and persistence/client flags, and **100 chunk fixtures** with +86,806 state writes, 54,306 column queries, 516 priming calls, 378 raw-data loads +and additional update-only error cases. Selected fixtures compare exact ordered +block reads. Cases include section and vertical bounds, leaves, fluid-bearing +states, air variants, removal rescans, empty-column retention, packed padding, +invalid raw lengths and wrapped column indices. + +Air/fluid facts and state identities are exported independently from each JAR and +required to agree. These are private test inputs, not ports of block behavioral +methods. Rust resolves heightmap tag membership using its tag loader and the +300 bundled block-tag resources. The reference binds those resources to the +actual vanilla block registry and invokes `Heightmap` on `ProtoChunk` instances. +Only in-memory section storage is used; placeholder biome holders do not exercise +biome properties or section codecs. + +Source and fixture changes during a run invalidate its report. Raw resources, +state exports and comparison traces stay under ignored `.local`; the checked-in +report contains metadata and hashes. CI runs this suite on its configured +platforms; the local result does not establish those remote results. Chunk +lifecycle integration, generated terrain, lighting and playable gameplay remain +pending. diff --git a/docs/mac-first-test.md b/docs/mac-first-test.md index e361ac809..e5eaf47cf 100644 --- a/docs/mac-first-test.md +++ b/docs/mac-first-test.md @@ -7,7 +7,7 @@ The Linux software-rendering observations do not predict an M2 speedup. ## Import after installing Prism -1. Download [horizon-mac-starter-0.21.0.zip](https://github.com/ludovic111/minecraft-optimization-lab/releases/download/v0.21.0/horizon-mac-starter-0.21.0.zip) +1. Download [horizon-mac-starter-0.21.0.zip](https://github.com/ludovic111/Horizon/releases/download/v0.21.0/horizon-mac-starter-0.21.0.zip) and extract it in Finder. 2. In Prism, choose **Add Instance > Import**, then select `horizon-m2-balanced-0.21.0.mrpack` from the extracted folder. The individual diff --git a/docs/material-conditions.md b/docs/material-conditions.md new file mode 100644 index 000000000..044d9dd0b --- /dev/null +++ b/docs/material-conditions.md @@ -0,0 +1,88 @@ +# Numeric material conditions + +Horizon evaluates the pinned Java Edition **26.3** hole, steepness, height, +water, stone-depth, vertical-gradient, noise-threshold, biome-membership, temperature +preliminary-surface and negated material conditions. +`MaterialConditions` owns each worker's context and compiled conditions, keeping +cache lifetimes tied to that worker. Column updates invalidate both column and +block conditions; block updates leave column caches intact. Secondary surface +noise is shared and sampled lazily once per column revision. + +Height and layer arithmetic preserves signed integer wrapping. Vertical gradients +resolve anchors during compilation, derive named positional random factories and +preserve the boundary order even with equal or reversed bounds. Stone depth uses +the appropriate floor/ceiling depth and Java's floating-point mapping and casts. +`MaterialSurface` implements the surface input interface used by this worker. + +Run `python3 tools/test_material_condition_parity.py`. The +[local report](../benchmarks/rust-material-condition-2026-10-06/scoped-parity.json) +records **5,627,426 matching output lines per reference JAR** across **245 fixtures**, +**11,288 initially compiled conditions** and **217,969 context operations**. +The original Java transport constructs actual vanilla conditions and calls their +compiled evaluators against actual context updates. Secondary sampler queries +are traced to compare lazy evaluation and cache reuse. Tests include both random +algorithms, integer extremes, nonfinite secondary values, floor/ceiling selection, +reversed gradient bounds, repeated evaluations and late compilation. + +For isolation, the native context's surface depth is supplied after each column +update, and secondary noise comes from a traced constant sampler. Full seeded +surface queries have a [separate comparison](material-surfaces.md). Sources and +fixtures are authenticated, and raw reference artifacts stay under `.local`. + +The comparison also covers **8,609 codec inputs**, all **eight bundled material +condition definitions**, forward/nested references, canonical encoding and numeric +conversions. Immutable registry loading rejects missing/cyclic references and +duplicate canonical names without publishing partial results. + +This scope excludes live biome-tag reloads, registry-owner +validation and arbitrary provider failures. Chunk application has a +[separate comparison](material-surfaces.md#chunk-surface-stage). Runtime trees +are bounded to 256 levels and 8,192 registered conditions per worker; these limits +are explicit resource bounds, not vanilla gameplay claims. + +The same comparison now includes **6,271 initially compiled material rules**: +block results, ordered sequences, conditional rules and seeded terracotta bands. +It checks empty/singleton/nested sequences, first-match short circuiting, late +compilation, band-index failures and separate context/application coordinates. +[Bundled rule loading](material-rule-libraries.md) now integrates these runtime +rules; rule encoding remains pending. + +Noise thresholds share lazy suppliers by canonical noise name and dimension mode. +Column-only suppliers still call the three-coordinate sampler with Y fixed at +zero. The comparison includes all 64 bundled noises under both random algorithms, +traced mutable inputs, repeated updates, late binding and nonfinite thresholds. +`MaterialNoiseSources` supplies lazy named samplers from the world positional +factory. Encoded numeric values are compared as double bits to preserve values +independently of JSON number formatting, including Gson NaN/Infinity output. + +Biome membership and temperature checks use the climate fields of all 67 bundled +biomes. Tests cover possible-biome constant folding, shared biome lookup caches, +column/block updates, null lookups, thrown lookup failures and same-revision +retries that retain earlier condition results. A missing result after a failed +first evaluation remains an error. Worker condition evaluation returns typed errors. + +Named biome-tag conditions resolve all **86 bundled tags** through the tag loader +and retain their tag identity when encoded. Comparisons cover nested references, +optional missing members, duplicate entries, empty tags, namespace aliases, +possible-biome folding and conditional-rule application. Registry snapshots are +immutable; live tag reloads remain pending. + +Preliminary heights use a lazily populated unit-spaced XZ density plane, with +scalar sampling outside it. `MaterialDensitySources` accepts the compiled +preliminary-surface root and its world sampler context. The comparison checks +column minimum caching, Y-only updates, ignored original volume strides, partial +failed fills, retries, floor conversions, infinities/NaN and integer wrapping. +The preliminary plane is bounded to 1,048,576 samples. + +Ore-vein rules accept three compiled density roots. Density and richness fill +the expected chunk volume at compilation; gap sampling stays lazy. Cached +lookups require an exact lattice position. Density queries use the block context; +random choices use application coordinates and the seeded `minecraft:ore` stream. +Tests cover both random algorithms, draw order, repeated calls, independent +coordinates, nonfinite runtime values, raw-ore chances and failed compilation. +Debug ore-vein visualization flags are outside this gameplay scope. + +Material density storage is bounded to 32,768 bindings, 1,048,576 samples per +eager volume and 16,777,216 retained eager samples per context. Bundled rule +decoding has a [separate comparison](material-rule-libraries.md); rule encoding +remains pending. The surface-stage comparison integrates these density bindings. diff --git a/docs/material-rule-libraries.md b/docs/material-rule-libraries.md new file mode 100644 index 000000000..47a434d9f --- /dev/null +++ b/docs/material-rule-libraries.md @@ -0,0 +1,36 @@ +# Material-rule libraries + +`MaterialRuleLibrary` loads the pinned Java Edition **26.3** rule resources against +block-state, condition, noise and density registries. It supports block rules, +ordered sequences, conditional rules, terracotta bands, ore veins and nested named +rule references. Loading is atomic; missing references, cycles and duplicate +canonical names return errors. Limits are 8,192 registered definitions, 65,536 +parsed nodes and 256 nested levels. + +The library owns a density compiler configured for one world seed and random +mode. `rule(name)` resolves a runtime tree and lazily compiles its density roots. +Binding that tree to `MaterialConditions` performs per-chunk density sampling. +`named_density(name)` shares the compiler with preliminary-surface sampling. +`compile_router` and `compile_aquifer` bind configurations decoded into the same +density registry before it is passed to the library. Their samplers share the +material roots' cache namespace, so noise filling and surface application can +reuse a worker context. Workers need matching world random settings and separate +cached sampler contexts. + +Run `python3 tools/test_material_rule_library_parity.py`. The +[local report](../benchmarks/rust-material-rule-library-2026-10-06/scoped-parity.json) +records **678,174 matching output lines per reference JAR**, including **665,712 +rule applications** and **142 codec inputs** across 12 fixtures. The test loads all +**42 bundled rules**, **8 conditions**, **55 densities**, **64 noises**, **67 biome +climates** and **86 biome tags** from both authenticated reference JARs. It also +checks synthetic forward references and constant-density ore rules. + +Comparisons use actual seeded noise and ore densities, strided chunk caches, +scalar fallback, varying biomes/depths/heights, possible-biome sets and distinct +context/application coordinates. Surface depth and secondary noise are supplied +context inputs; preliminary density is zero to isolate rule evaluation. + +The [surface stage](material-surfaces.md#chunk-surface-stage) now applies these +rules to chunks. Rule/density encoding, live reload, registry-owner checks and +playable integration remain pending. The report establishes +this tested scope, not complete vanilla gameplay parity or an FPS improvement. diff --git a/docs/material-surfaces.md b/docs/material-surfaces.md new file mode 100644 index 000000000..2f8ad65b1 --- /dev/null +++ b/docs/material-surfaces.md @@ -0,0 +1,125 @@ +# Seeded material surfaces + +Horizon implements the pinned Java Edition **26.3** material system's terracotta +band generation, band lookup, surface depth and secondary surface-noise query. +These primitives now feed the [chunk surface stage](#chunk-surface-stage). + +`ClayBands` generates all 192 entries from the supplied clay-band random stream. +It preserves orange placement, colored-band widths and overwrites, white/gray +adjacency checks and conditional random draws. `MaterialSurface` derives that +stream from the world's root positional factory using `minecraft:clay_bands`. +Its surface-depth query uses a fresh position-derived random stream. + +Band lookup rounds the float noise offset with Java's tie and saturation rules, +then uses wrapped integer addition and signed remainder. A negative final index +returns `None`, corresponding to vanilla's array-index failure. Surface-depth +arithmetic promotes the sampled float to double before applying coefficients and +truncating to an integer. Secondary noise similarly retains the float-to-double +conversion. + +Run: + +```sh +python3 tools/test_material_surface_parity.py +``` + +The [local report](../benchmarks/rust-material-surface-2026-10-06/scoped-parity.json) +records **122,988 matching output lines per reference JAR**, covering **277 fixtures** +and **5,263 surface-query positions**. The original Java transport invokes actual +`MaterialSystem` methods and its real constructor. Comparisons include both random +algorithms, direct and derived streams, preconsumed random inputs, every band +entry, subsequent random draws, real bundled noise definitions and constant-noise +overrides for rounding boundaries, infinities, NaNs and extreme coordinates. + +Reference artifacts and noise resources are authenticated, source/fixture changes +invalidate the report, and raw inputs/outputs stay private under `.local`. CI +includes this comparison on its configured platforms; the local result does not +establish remote outcomes. Subsequent suites cover rule binding, biome-specific +extensions and chunk surface application. + +[Vertical anchors](vertical-anchors.md), used by material conditions, now have a +separate differential implementation and codec comparison. + +[Numeric material conditions](material-conditions.md) now evaluate surface inputs +with worker-owned caches. [Bundled rule libraries](material-rule-libraries.md) +bind the pinned material definitions and their ore-density samplers. + +## Biome-specific column extensions + +`MaterialExtensions` implements eroded-badlands pillars and frozen-ocean icebergs. +It preserves noise coordinate arithmetic, temperature-dependent melting, seeded +random draw order, repeated column reads and property-independent block identity. +The column provider controls out-of-height reads and write clipping; failed calls +retain earlier writes. Each extension call is bounded to 1,048,576 iterations. + +Run `python3 tools/test_material_extension_parity.py`. The +[local extension report](../benchmarks/rust-material-extension-2026-10-06/scoped-parity.json) +records **233,100 matching lines per JAR** across **410 fixtures** and **3,920 +extension calls**. It compares ordered noise/read/write traces and complete +columns, including both random modes, all 67 biome climates, actual seeded noises, +constant threshold/nonfinite inputs, air/water variants and provider failures. +The chunk surface stage integrates these extensions with heightmaps and fluid +postprocessing. + + +## Chunk surface stage + +`build_surface` traverses columns in vanilla X/Z order and scans down each column, +maintaining stone-depth and water-level counters. It applies bound material rules, +eroded-badlands pillars and frozen-ocean icebergs. Writes update both world-generation +heightmaps and append fluid-postprocessing offsets in order, including duplicates. +Generation bounds clip writes while scans retain the chunk's full height. The +worker returns its density context to the caller on success and typed failure; +previous writes remain visible after failure. + +Run `python3 tools/test_material_stage_parity.py`. The +[local stage report](../benchmarks/rust-material-stage-2026-10-06/scoped-parity.json) +records **6,733,382 matching output lines per reference JAR**, covering **79 fixtures**, +**42 terrain fills**, **42 procedural carving passes**, **106 surface builds** and **21,757,952 block values**. The reference invokes actual +`MaterialSystem.buildSurface` on vanilla `ProtoChunk` instances. Comparisons include +complete sections, packed heightmaps, ordered postprocessing and biome queries. +Fixtures exercise both random modes, the bundled rule registries, real seeded +noises, empty and populated chunks, cavities, nondefault solids, clipped writes, +primed and lazy heightmaps, and repeated builds sharing density contexts. +Generated fixtures run actual `NoiseBasedChunkGenerator.doFill` followed by surface +application on the same native noise chunk. Rust shares a compiler and worker +context across both stages. All seven bundled terrain routers and aquifer +configurations are tested with multiple seeds and distant positive/negative +coordinates, comparing full chunk state before and after surface application. + +Synthetic initial chunks use a supplied block-position biome resolver. Generated +terrain fixtures first generate a 3×3 biome neighborhood through actual +`ChunkGenerator.doCreateBiomes`, using multi-noise presets or the End source. +The comparison checks **378 biome chunks** and **400,896 biome cells**, then +performs seeded `BiomeManager` lookups against those stored neighbor biomes. +Both block and quart lookup traces are compared. Rust imports independently +authenticated preset tables; their builders remain separate work. +Generated fixtures additionally select and run biome carvers across the 17×17 +origin neighborhood, comparing uncached biome queries and the complete terrain +state after procedural carving. They then apply explicit masks twice as a stress +check. See [carving integration](carving.md#biome-selected-neighboring-carvers). +The neighborhood decodes its source JSON through the registry-bound biome-source +catalog and uses the shared resolved-source worker API. Block air/fluid metadata +is imported from both authenticated JARs. Native preset builders, full inline biome +codecs, feature/structure stages, nonempty blending, lighting +and complete generated worlds +remain pending. A separate Rust test verifies that successful builds, eager binding +failures and late biome-provider failures preserve density caches and world fields, +and that late failure retains prior chunk writes and fluid offsets. +CI includes the stage gate; remote results have not been observed. + + +## Surface material beneath carved blocks + +`top_material` binds a fresh one-cell material context at the supplied position, +using clamped neighboring heightmap gradients and one stone block above and below. +Submerged queries set water height to Y+1; dry queries use the vanilla sentinel. +Possible-biome restrictions are omitted, as in vanilla's method. The returned +state is left for the carving stage to apply. Both successful and failed queries +retain the caller's density context; the query itself does not change blocks. + +The surface-stage comparison includes **7,584 top-material queries** against +actual `MaterialSystem.topMaterial`, at column edges and interiors, around sea +level and immediately outside vertical bounds, in both dry and submerged contexts. +The latest combined report records **6,733,382 matching lines per JAR**. Unit tests +also check failure-state retention and the omission of possible-biome shortcuts. diff --git a/docs/noise-generation.md b/docs/noise-generation.md new file mode 100644 index 000000000..055c32202 --- /dev/null +++ b/docs/noise-generation.md @@ -0,0 +1,96 @@ +# Horizon noise-generation scope + +The target is the repository-pinned Minecraft Java Edition **26.3**. The Rust +samplers live in `crates/horizon-core/src/noise/` and use the checked legacy or +xoroshiro streams. They are a world-generation foundation; Horizon does not yet +generate complete vanilla chunks or run a playable Rust game. + +## Implemented behavior + +- Gradient offsets and all 256 permutation entries, including the three random + draws consumed when simplex offsets are disabled. +- 26.3 Perlin 2D/3D sampling, single-precision interpolation and accumulation into + caller-supplied derivative arrays. Smeared Perlin uses its adjusted Y component + for gradient dots and the original component for interpolation. Its inherited + derivative method samples the unsmeared field. +- Simplex 2D/3D sampling with both offset modes, double-precision corner arithmetic + and single-precision return values. The second 2D coordinate uses the Y offset. +- Normal coordinate wrapping with the Far Lands debug flag disabled, including + the fast-path boundary immediately below 2^24. +- Positive strided density volumes with Z/X/Y flat ordering, Java-wrapping block + coordinates, bulk Perlin/smeared-Perlin gradient reuse, scalar simplex volumes, + repeated scaled accumulation and untouched buffer tails. +- Ordered noise stacks, nested sampling, flattened stack composition, layer + access and range arithmetic. Zero-amplitude layers are retained. Flattening + rescales each layer before sampling and can differ from a nested stack. +- Normal-noise octave selection, frequencies, amplitude modifiers, compensated + amplitude sums, enabled/disabled/legacy normalization and the parity factory. + Modern creation forks two positional factories and derives each octave from + its name, then interleaves the two sets of Perlin layers. +- Legacy Nether biome initialization, including reverse octave construction, + exactly 262 integer draws for skipped octaves, rejected positive octaves and + the RNG state left by initialization failures. Its two stacks are flattened in + sequence, preserving their distinct accumulation order. + +The bulk Perlin kernel adds X/Z gradient contributions before Y. Calling the +scalar sampler repeatedly would rearrange those operations and can change the +result. Rust preserves the bulk path and caches its eight gradients while the +Y cell remains unchanged. These are implementation choices checked for behavior; +no whole-game frame-rate or generation-speed improvement has been measured. + +## Validation + +After preparing the pinned artifacts with `python3 tools/lab.py prepare`, run: + +```sh +cargo test --workspace +cargo clippy --workspace --all-targets -- -D warnings +python3 tools/test_noise_parity.py +``` + +The original Java adapter invokes the actual downloaded classes on both client +and server JARs. It exposes offsets, permutations, octave parameters and layer +weights for comparison, and calls the reference scalar and bulk methods. +Artifacts and dependencies are authenticated against the repository lock and +the official bundled checksums. Generated corpus/output and compiled adapters +remain private under `.local/rust-noise-parity/`. + +The corpus covers both random streams; offset and lattice boundaries; very large +coordinates; signed zero, subnormals, infinities and NaNs; negative and zero +amplitudes; rejected ranges; nested and flattened stacks; octave gaps; all three +normalization modes; empty definitions; and modern/legacy RNG consumption. +Finite values and signed zeros are compared by bits. NaN payloads/signs are +canonicalized on both sides, matching Java's `floatToIntBits`/`doubleToLongBits`. + +The local run matches **1,443,539 output lines per reference JAR**. This is a +count of output records, including repeated checks, not distinct gameplay +behaviors or a coverage percentage. The metadata-only +[scoped report](../benchmarks/rust-noise-2026-10-05/scoped-parity.json) records +source/input/output hashes and reference identities. The runner removes a prior +success report before running and rejects source changes during validation. +CI includes the suite on Linux, Windows and Apple Silicon macOS; the recorded +local result is Linux, not proof that remote jobs or physical gameplay passed. + +## API limits and remaining integration + +Rust returns typed errors and uses immutable shared samplers. Density dimensions +and strides must be positive, total volume must fit a Java signed array index, +and a short output buffer is rejected before any writes. Vanilla can overflow +its volume-size arithmetic or partially write before an array exception; those +invalid-buffer behaviors are outside this bounded API. + +The normal-noise builder limits allocation to 4,096 octaves; the legacy +initializer also limits reverse construction to 4,096 octave steps. Requests +beyond these limits fail before RNG draws. Vanilla's serialized definition +codec limits octave count to 32. Rust's builder owns a snapshot of parameters; +Java object identity, mutable builder-list aliases, equality/hash methods and +the complete Java API surface are not reproduced. + +The direct normal-noise JSON codec is now implemented and checked against every +bundled noise definition in the [world-generation codec suite](world-generation.md). +The density registry loader is also compared against all bundled definitions. +Remaining noise initializers, complete terrain-router integration, +aquifers, surface rules, biome/feature/structure placement and complete chunk +generation still require implementation and integration evidence. Gaussian +sampling remains absent from the RNG API pending exact logarithm behavior. +No generated-world or full gameplay parity claim follows from this suite. diff --git a/docs/optimization-plan.md b/docs/optimization-plan.md index ff85fc316..eb860fa4e 100644 --- a/docs/optimization-plan.md +++ b/docs/optimization-plan.md @@ -8,6 +8,13 @@ Inspect both pinned game JARs locally, retain bytecode as the reference, and mea Whole-game translation is a long-term research objective. Decompiled Java is an inspection artifact, not the original source tree: build configuration, comments, tooling history, and some source-level constructs cannot be recovered faithfully. A mechanically translated Rust game would also have to preserve behavior, data formats, networking and rendering. An isolated hot-path replacement is a useful first experiment. +The Rust rewrite now has an original `horizon-core` foundation and a bytecode +differential runner for selected position, random-stream and packed-storage +operations. [Rust parity status](rust-parity.md) distinguishes that tested slice +from the unimplemented gameplay and renderer. This establishes compatibility +testing infrastructure; it does not select an FPS bottleneck or supply a playable +Rust client. + ## Local code map These entry points were verified present in the decompiled 26.3 client. Paths below are relative to `.local/minecraft/26.3/sources/client/net/minecraft/`; shared/server logic can also be inspected in the dedicated-server tree. diff --git a/docs/playable-validation.md b/docs/playable-validation.md index 159bcaace..9b881c3ec 100644 --- a/docs/playable-validation.md +++ b/docs/playable-validation.md @@ -5,7 +5,7 @@ Version 0.2.0 targets Minecraft 26.3 / Fabric 0.19.5 / Java 25. This is an initi ## Local checks - Official client runs through a Wayland virtual screen in built-in limited demo mode, without Microsoft credentials. Normal Mac play uses licensed Prism sign-in. -- Balanced stack (Sodium, Lithium, FerriteCore, ImmediatelyFast, EntityCulling, Distant Horizons, Fabric API, Horizon Lab) reaches the menu, loads the demo world, logs in locally, renders terrain, and saves/quits. +- Balanced stack (Sodium, Lithium, FerriteCore, ImmediatelyFast, EntityCulling, Distant Horizons, Fabric API, Horizon) reaches the menu, loads the demo world, logs in locally, renders terrain, and saves/quits. - DH generates and accepts the current configuration schema: 128-chunk LOD radius, two background threads at 0.5 run-time ratio, priority 3. No old-version guessed config keys. - A missing desktop AWT component in the local headless JRE initially caused a DH cloud-texture error. Installing the complete Java 25 runtime resolved it; this was an environment issue, not a packaged mod change. - Native libraries are chosen by OS and architecture, including ARM64 selection when the official manifest has OS-only rules. Builds use portable `/` ZIP paths on Windows too. @@ -167,4 +167,4 @@ terrain generation and steady-state rendering are separate workloads. ## Release content -Packs embed only the original MIT Horizon Lab JAR and config. Mod/game/library downloads retain upstream licenses and are checked against pinned hashes. No game JAR, class, decompiled source, asset, world or credential is committed or uploaded in a starter. The narrow publication allowance is for original Java under `dev/horizonlab`, and the built JAR checks its emitted class namespace. +Packs embed only the original MIT Horizon JAR and config. Mod/game/library downloads retain upstream licenses and are checked against pinned hashes. No game JAR, class, decompiled source, asset, world or credential is committed or uploaded in a starter. The narrow publication allowance is for original Java under `dev/horizonlab`, and the built JAR checks its emitted class namespace. diff --git a/docs/process-memory.md b/docs/process-memory.md index 64ff7aab3..1f4e7186a 100644 --- a/docs/process-memory.md +++ b/docs/process-memory.md @@ -1,6 +1,6 @@ # Measuring resident process memory -Horizon Lab 0.6.0 records process RSS alongside JVM heap and nonheap pools. RSS +Horizon 0.6.0 records process RSS alongside JVM heap and nonheap pools. RSS counts resident pages belonging to the Minecraft process, including native allocations and mapped pages. It helps detect cases where reducing heap use merely moves memory elsewhere. It is not unique physical-memory ownership or diff --git a/docs/rust-parity.md b/docs/rust-parity.md new file mode 100644 index 000000000..6ee0a0378 --- /dev/null +++ b/docs/rust-parity.md @@ -0,0 +1,381 @@ +# Horizon Rust rewrite status + +The behavior target is the repository's pinned **Minecraft Java Edition 26.3**. +One-to-one vanilla gameplay parity is the acceptance criterion. It has **not** +been reached: Horizon's Rust code does not yet run a client, server, or simulation. +It can read and export region files and access saved and resident block sections. +Scheduled block/fluid queues can now collect and dispatch callbacks with +vanilla-checked ordering; the actual block/fluid behavior is still absent. +Double-precision geometry and voxel-grid queries are implemented, with a registry +adapter for vanilla's no-context cached collision branch. +Base noise samplers, octave stacks, normal-noise definitions and bulk density +sampling are implemented. Compiled density samplers now evaluate constants, gradients, +shifted noise, all eleven unary operators, rounding and selected arithmetic operations. An initial density graph compiler +integrates range analysis, specialization, uniform-axis slicing, shared caches, +nested splines and seeded noise; +complete graph coverage, serialized graphs and generated terrain remain absent. +The playable Java performance packs remain available during development. + +## Implemented foundation + +`crates/horizon-core` is a dependency-free Rust library with no unsafe code. +It uses small integer position values, exclusively owned RNG state, and packed +64-bit storage. These choices avoid Java object overhead in this slice; no +whole-game memory, FPS, or render-distance gain has been measured. + +| Area | Implemented and checked operations | Remaining scope | +| --- | --- | --- | +| Positions | Block, section, and chunk packing/unpacking; wrapping block offsets; block-to-section/chunk conversion; section-relative packet positions; block-state storage indices; region coordinates/local indices; bounded inclusive/directional block-box iteration | Remaining iterators, world bounds and entity/world integration | +| Simulation geometry | Selected Vec3 operations, quantized trig/rotations, normalized AABB bounds and transforms, finite block traversal/swept visitation, ray faces, immutable cube/array voxel grids, greedy boxes, collision distances, column heights, closest points, lazy floor height, box quantization and Boolean/optimized joins; movement resolution over supplied shapes, step candidates and step-up decisions/query bounds | Shape rotations/faces/edges, entity-context shape selection, full entity movement and side effects | +| Legacy random stream | Seeding/reseeding; int, bounded/inclusive/exclusive int, long, boolean, float, double; triangular float/double draws; fork; consume count; positional factories and Java UTF-16 string hashes | Gaussian sampling, threading-error behavior and remaining world-generation call sites | +| Xoroshiro random stream | 64-bit seed expansion; explicit 128-bit state including all-zero fallback; the same selected random operations as above; positional factories and MD5-derived seeds with Java UTF-8 surrogate handling | Gaussian sampling, serialization and remaining world-generation call sites | +| Noise generation | 26.3 Perlin/simplex/smeared Perlin; permutation construction and coordinate wrap; Perlin derivatives; cached/scalar density-volume accumulation; nested/flattened stacks; normal-noise octave weights and normalization; modern and legacy Nether seeding | Serialized noise definitions, density graphs, complete chunk generation, biome/feature/structure integration | +| Density evaluation | Compiled constants, clamped/repeating/mirrored gradients, unshifted and XZ/XYZ shifted noise; offset-noise variants, old blended noise, outer End islands and distance-to-point; all eleven unary operators, six binary operators, powers, rounding, constant-operand specializations, min/max, clamp, range choice, interval selection and linear interpolation; separate scalar/bulk paths, nested scratch buffers, context-bound blend alpha/offset/structure samplers, absent/empty blend-density wrappers, context-owned scalar/volume caches, coordinate slices, coarse-grid interpolation, surface searches and nested cubic splines | Codecs, structure-density producers, nonempty old-world blending and terrain integration | +| Density graph compilation | Immutable definitions for constants, gradients, arithmetic/selection operations, powers, rounding, distance-to-point, slices, caches, interpolation, surface search, nested splines, outer End islands and normal/offset/blended noise; context fields, blend-density wrappers, direct/named reference holders; range/axis metadata, constant and disjoint-range specialization, uniform-axis rewriting, cache-ID allocation/deduplication, memoized roots, spline coordinate sharing/validation, world-seed lookup and failure state | Codecs, concrete world-field producers and complete terrain integration | +| Density range analysis | Checked interval constructors, hulls, arithmetic/min/max, reciprocal, abs/square/sign, powers/logarithms, clamp, monotonic endpoint mapping, finite/infinite interpolation, predicates, equality and Java hashes; conservative spline range propagation; integration with supported graph definitions | Propagation through remaining graph definitions | +| Packed palette-index storage | Widths 1–32; allocation; imported raw words; reads; writes returning old values; unpack; fill; padding/tail preservation; invalid-write rejection | Remaining network container integration | +| World data | Named/network NBT, modified UTF-8, mixed lists; gzip/zlib/uncompressed/lz4-java codecs; region exports including external chunks; block/biome saved palettes | Complete save lifecycle, data fixing, concurrent saves and recovery | +| Resident block sections | Pinned block-state registry import, defaults, numeric IDs, uniform sections, packed palette growth, freed-slot reuse and compaction; cached collision shape lookup bound to the same registry | Block behavior, entity-context collision shapes, light and full chunk-lifecycle integration | +| Heightmaps | Six type predicates and flags, packed heights, updates/removal rescans, shared priming, raw imports and length-mismatch fallback; all pinned states and mutation fixtures compared | Block air/fluid behavior and chunk-lifecycle integration | +| Scheduled ticks | Chunk queues, level collection/drain ordering, duplicate suppression, seven priorities, saved delays, chunk eligibility, callback mutations, area removal/copying, saved block/fluid NBT | Actual block/fluid callbacks, neighbor updates, tick-time and chunk-lifecycle integration | + +Packet-relative positions use X/Z/Y ordering; block-state storage indices use +Y/Z/X ordering. Negative coordinate conversion must floor rather than truncate. +The legacy RNG must retain Java's signed-int arithmetic and rejection rules; +the xoroshiro RNG has a different bounded-int algorithm and bit selection. +Positional factories preserve signed coordinate hashing and each stream's distinct +seed derivation. The hash API accepts UTF-16 units so malformed surrogate sequences +retain Java's replacement behavior. Gaussian sampling is still absent: a private +probe found bit differences between Java `Math.log` and the platform logarithm, +which must be resolved before its values and cached-draw behavior can be claimed. +Storage entries never cross a word boundary. Vanilla's fill operation also +writes padding and unused tail bits; imported words retain their original bits +when a slot is changed. These details are covered by the differential corpus. + +Rust APIs return typed errors instead of Java exceptions. Storage lengths and +indices use `usize`; raw decoded values use `u32` bit patterns. Writes reject +values above the nonnegative Java-int domain, including at width 32. Test output +casts raw imported width-32 reads back to signed Java ints for comparison. +Negative lengths and the complete Java object/API surface are not supported. + +## Reproduce validation + +Requires Rust 1.85 or newer, Python 3.10 or newer, and JDK 25. From the checkout: + +```sh +cargo test --workspace +cargo clippy --workspace --all-targets -- -D warnings +python3 tools/test_rust_parity.py --prepare +python3 tools/test_world_parity.py +python3 tools/test_tick_parity.py +python3 tools/test_geometry_parity.py +python3 tools/test_collision_parity.py +python3 tools/test_noise_parity.py +python3 tools/test_density_parity.py +python3 tools/test_worldgen_parity.py +python3 tools/test_heightmap_parity.py +python3 tools/test_terrain_parity.py +python3 tools/test_structure_density_parity.py +python3 tools/test_material_surface_parity.py +python3 tools/test_material_condition_parity.py +python3 tools/test_material_stage_parity.py +python3 tools/test_biome_zoom_parity.py +python3 tools/test_biome_chunk_parity.py +python3 tools/test_biome_generation_parity.py +python3 tools/test_biome_source_parity.py +python3 tools/test_anchor_parity.py +python3 tools/test_biome_temperature_parity.py +python3 tools/test_float_log_parity.py +``` + +`--prepare` regenerates the local reference artifacts from the existing lock; +omit it after preparation to run without downloads. The runner verifies the +official manifest and both game downloads, the server's inner game JAR, and each +server dependency against pinned/bundled hashes. The original Java test adapter +calls vanilla classes directly; it does not substitute a Java reimplementation +of the Rust algorithms. The same corpus runs against client and server code. +The fixtures need no display, account, assets, or world generation. + +The deterministic corpus contains coordinate extremes, all 4,096 local section +positions, 8,192 random coordinate/offset queries, boundary and random signed +seeds, mixed RNG operations, fork/reseed/consume checks, invalid bounds, and +all 32 storage widths at boundary and 4,096-entry sizes. It also imports words +containing all set bits and compares the raw padding and fill results. The +current run produces **1,634,520 matching output lines per reference JAR**. +It includes 4,400 positional-factory commands and 5,000 random-helper commands, +with overflowing integer intervals, hash padding boundaries and malformed UTF-16. +This count includes repeated checks and raw entries; it is not a count of +distinct vanilla behaviors or a percentage of game coverage. + +Artifacts remain gitignored under `.local/rust-parity/`: corpus, Rust output, +client/server output, compiled oracle, and `report.json`. The report records +source/input/output hashes, reference identities, tool versions, and matched +line counts. A prior success report is removed before a new run can fail. +CI runs the same comparison in addition to offline Rust and Python checks. +The checked-in [scoped validation report](../benchmarks/rust-core-2026-10-05/scoped-parity.json) +contains only metadata and digests from the local run, not game code or artifacts. + +The additional [world-data suite](world-data.md) checks NBT and region +interoperability, saved palettes, all 35,723 registered block-state IDs, and +resident sections after repeated mutation. The corresponding +[scoped report](../benchmarks/rust-world-2026-10-05/scoped-parity.json) +records client/server reference hashes and the tested source hashes. + +The [scheduled-tick suite](scheduled-ticks.md) adds 25,815 commands including +2,096 tick invocations, producing 97,776 matching output lines per reference. +It also verifies block/fluid tick save codecs and a persisted region chunk. +The [geometry and cached-collision suites](collision-geometry.md) check numerical +boundaries and runtime block-state shape data, with separate +[geometry](../benchmarks/rust-geometry-2026-10-05/scoped-parity.json) and +[cached-collision](../benchmarks/rust-collision-2026-10-05/scoped-parity.json) +metadata reports. All differential runners reject changed source hashes during a run before publishing +a success report. Historic reports describe their own recorded source versions. + +The [noise suite](noise-generation.md) checks base sampling, derivative and bulk +arithmetic, nested/flattened stacks, normal-noise normalization and both modern +and legacy Nether initialization. Its [scoped report](../benchmarks/rust-noise-2026-10-05/scoped-parity.json) +records the tested sources and both reference artifacts. + +The [density suite](density-functions.md) checks compiled scalar and bulk samplers, +including gradients, nested shifted noise, arithmetic, caching, axis slicing and +coarse-grid interpolation, surface searches and nested splines with range analysis; +it also compares the initial graph compiler with vanilla's compiler. Its +[scoped report](../benchmarks/rust-density-2026-10-05/scoped-parity.json) records +**15,524,627 matching output lines per reference JAR**. That suite constructs graphs through its transport. Serialized registry +comparisons are covered separately below; generated terrain remains pending. + +The [float-log report](../benchmarks/rust-float-log-2026-10-05/scoped-parity.json) +records exhaustive compiled scalar comparisons for all **4,294,967,296 float bit +patterns** against both JARs on the local Linux/JDK runtime, with canonical NaN +results. Double-precision logarithms and other-platform math remain separate +validation work. + +The [world-generation codec suite](world-generation.md) checks every bundled +normal-noise JSON definition and all 55 bundled density definitions against +vanilla's actual registry-aware codecs. It compares decoded octave metadata, +graph ranges and axes, raw and optimized compilation, cache allocation and +seeded scalar and strided bulk sampling. Its +[scoped report](../benchmarks/rust-worldgen-2026-10-06/scoped-parity.json) records +**961,693 matching output lines per reference JAR**. All seven bundled eight-field +routers and their climate samplers are also +compared, including quart-coordinate wrapping and float/long quantization. +Climate search-tree construction and warm/fresh ties are checked across the +bounded API. Scalar and prepared-volume multi-noise biome resolvers are implemented +using private imported built-in parameter tables and compared against vanilla +scalar and bulk biome resolvers. Climate parameter codecs, vertical terrain bounds and the global fluid picker/ +disabled-aquifer path are also compared. Noise-based aquifer configuration and +fluid-pressure selection are implemented, with differential checks for seeded +decisions, sampling order, caches and failure recovery. Tag codecs, stacked resource +replacement and bounded dependency resolution are compared across all 300 bundled +block tags and synthetic missing-reference/cycle fixtures. Complete terrain +integration remains pending. + +The [heightmap suite](heightmaps.md) records **1,671,668 matching output lines per +reference JAR** across all 35,723 block states and 100 chunk fixtures. Rust resolves +tag membership; block air/fluid facts are private, independently verified imports. +Actual vanilla heightmaps compare predicates, mutations, packed words, priming and +selected ordered block reads. Chunk-lifecycle integration remains pending. + +The [noise-fill suite](terrain-filling.md) now compares **7,950,873 output lines per +reference JAR** across 114 fixtures and 200 fills. Final density, aquifers, resident +sections, world-generation heightmaps and fluid postprocessing are integrated for +this stage. The surface stage has a separate comparison; biome, feature and +structure stages remain pending. + +The [structure-density sampler](structure-density.md) matches **1,360,095 output +lines per reference JAR**, including ordered rigid-piece/junction contributions +and scalar/bulk clipping. Live structure discovery and placement remain pending. + +The [vertical-anchor suite](vertical-anchors.md) matches **181,632 output lines per +reference JAR**, including four anchor codecs, runtime overflow, nested exclusive +fields and generation bounds. + +The [material-surface primitives](material-surfaces.md) match **122,988 output +lines per reference JAR** for seeded terracotta bands, band lookup and surface +noise queries. Subsequent suites cover rule evaluation and surface application. + +The [numeric material-condition suite](material-conditions.md) matches **5,627,426 +output lines per reference JAR** for eleven condition forms and their column/block +cache transitions, including codecs, all eight bundled condition definitions and +block/sequence/conditional/terracotta-band rule composition. +The chunk surface comparison below integrates these rules. + +The [biome-temperature suite](biome-temperatures.md) matches **836,659 output lines +per reference JAR** for temperature modifiers, precipitation decisions and ordered +cache behavior, including thread isolation and climate fields from all 67 bundled +biome definitions. Full weather placement remains pending. + +The [surface-extension suite](material-surfaces.md#biome-specific-column-extensions) +matches **233,100 output lines per reference JAR** for badlands pillars and +frozen-ocean icebergs, including ordered column reads/writes and both random modes. + +The [bundled material-rule suite](material-rule-libraries.md) matches **678,174 +output lines per reference JAR**, including 665,712 rule applications across all +42 bundled definitions and the pinned biome, noise and density registries. +The [chunk surface stage](material-surfaces.md#chunk-surface-stage) matches +**6,733,382 output lines per reference JAR** across 79 fixtures, 42 terrain fills +and 106 surface builds, followed by 158 carving-mask passes, including 21,757,952 block values, heightmaps, fluid +postprocessing and ordered biome queries. It tests all seven bundled terrain +settings through both stages with shared density contexts and vanilla fuzzy +biome lookup against 378 generated neighbor biome chunks (400,896 stored cells). +Preset builders and complete generated worlds remain pending. + +The [biome-lookup suite](biome-lookup.md) matches **256,933 output lines per +reference JAR** for seed obfuscation, eight-corner fuzzy selection, direct quart +queries and source replacement. Seed hashes also match an independent SHA-256 +implementation. [Chunk biome storage](biome-lookup.md#chunk-biome-storage) matches +**478,340 lines per JAR** across 160 fills, including section-atomic failure +behavior and clamped reads. [Chunk biome generation](biome-lookup.md#chunk-biome-generation) +matches **383,072 lines per JAR** across 322 fills, including both imported +multi-noise presets and fixed/checkerboard/End sources through all seven terrain +routers. Preset builders and complete world generation remain pending. + +The [fixed/checkerboard/End source suite](biome-lookup.md#fixed-checkerboard-and-end-sources) +matches **1,306,096 lines per JAR**, including 1,147,984 biome queries and ordered +End erosion sampling. [Registry-bound source codecs](biome-lookup.md#registry-bound-source-codecs) +match **363,121 lines per JAR** across 40,481 inputs, including canonical encoding, +possible-biome sets and resolved queries. Chunk generation and surface integration +share the resolved-source API. Inline biome definitions and complete registry +lifecycle behavior remain pending. + +The [carving-mask suite](carving.md) matches **45,742 lines per JAR** across +28 fixtures, including packed column ranges, coordinate wrapping and mutations +retained after failing traversal callbacks. Mask application is included in the +surface-stage suite. [Shared carving geometry](carving.md#shared-shape-primitives) +matches **106,699 lines per JAR**, including 690 ellipsoids and 5,536 reachability +queries. [Seeded cave/canyon paths](carving.md#seeded-cave-and-canyon-paths) match +**882,005** and **1,094,517 lines per JAR**, respectively. The combined stage suite +also covers 42 procedural carving passes, including neighboring biome selection +and ordinal carver seeds. Full-world integration remains pending. + +The [feature-placement primitives](feature-placement.md) match **1,268,600 lines per +JAR** across seventeen modifier kinds, including callback failures and shared random +state. [Modifier-chain execution](feature-placement.md#modifier-chains) matches +**548,461 lines per JAR**, including feature callback failures and reused pending +buffers. [Initial block-writing features](feature-placement.md#initial-block-writing-features) +match **1,820,614 lines per JAR** for the void platform, End islands and End arrival +platform. Remaining feature algorithms and complete world integration remain pending. + +The [scalar value-provider suite](value-providers.md) matches **429,920 lines per +JAR** across 504 definitions and 5,040 seeded fixtures, including exact random +stream consumption. [Anchored height providers](value-providers.md#anchored-height-providers) +match **507,660 lines per JAR**, including all four anchors and overflowing contexts. +Weighted lists include zero weights, nested choices and maximum totals. Gaussian +distributions and provider encoding remain pending. + +The [block-state JSON codec suite](block-state-codecs.md) matches **221,261 output +lines per reference JAR**, covering every registered state and compact/full +encoding plus malformed-property fallback. Block gameplay remains pending. + +## Work required for a playable rewrite + +| Subsystem | Current Rust status | Required parity evidence | +| --- | --- | --- | +| Registries, block states, items and data components | Block-state IDs, property descriptors and defaults imported and checked; items/components absent | Registry lifecycle, remaining registries, data components and behavior | +| World/chunk storage, NBT and region files | Bounded NBT, four codecs, region export, saved and resident section palettes | Generated-save integration, entity/POI integration, upgrades, live saves and crash recovery | +| Terrain, biomes, structures and lighting | Seeded noise/density graphs, bundled registry and router loading, climate sampling/search and imported-table multi-noise biome resolution, aquifer decisions, noise-stage filling and surface-stage application implemented; complete terrain generation absent | Remaining terrain/biome codecs and world fields, seeded generated-chunk comparisons, biome/feature/structure placement, chunk lifecycle and light propagation | +| Tick scheduling, blocks, fluids and redstone | Scheduled queues, eligibility, callback mutations and saved tick data implemented; block/fluid/redstone behavior absent | Actual block/fluid state transitions, neighbor updates, world integration and end-to-end ordered traces | +| Entities, AI, movement and combat | Bounding-box and voxel collision geometry implemented; live entities absent | Context-dependent collision/physics and tick traces, spawning, pathfinding, damage, equipment and lifecycle | +| Survival, inventory, crafting and progression | Not implemented | Recipes, item transitions, hunger/health, effects, experience and advancement behavior | +| Dimensions, portals, weather and game rules | Not implemented | Cross-dimension state, transitions, time/weather and rule-dependent behavior | +| Multiplayer, protocol, authentication and commands | Not implemented | Packet/codec fixtures, vanilla interoperability, reconnects and command behavior | +| Rendering, resources, sound, UI and input | Not implemented | Resource compatibility, render/culling correctness, controls and playable interaction tests | +| Performance and platform support | Not measured for a Rust game | Repeated matched gameplay workloads, frame/tick distributions, memory and physical GPU tests | + +The next simulation milestone is integrating the checked scheduler and +registry-backed sections with actual block behavior and neighbor updates. World +generation now has noise-stage filling, aquifers and surface-stage application; +biome assignment and remaining generation stages need work, +followed by complete seeded-world comparisons. A renderer needs +actual block models, neighboring sections and light data. Simplified geometry +alone cannot establish vanilla behavior. Performance tuning must preserve the +validated simulation and use measured workloads; changing render distance, +simulation distance or terrain detail invalidates an equal-workload speed claim. + +No finite corpus proves every vanilla behavior. Future milestones need broader +version-specific differential suites and playable integration checks. The +project will report implemented/validated scope rather than label a partial +port as 100% parity. + +The [pre-light chunk-stage comparison](terrain-filling.md#block-writes-across-generation-stages) +adds **8,090,090 matching lines per JAR** for stage-dependent block mutation and +heightmap selection, including insertion/removal of every pinned state. This does +not establish the complete chunk lifecycle or region integration. + +The [resident feature-region comparison](feature-placement.md#resident-feature-regions) +adds **28,922,634 matching lines per JAR** for basic features, configured fill layers, replacements and scattered ore sharing +modifier chains and resident neighboring chunks, including live heightmap updates. +World-region side effects and complete feature generation remain pending. + +The [inline feature-graph comparison](feature-placement.md#inline-feature-composition) +adds **737,779 matching lines per JAR** for nested sequences and random selectors, +including short-circuit results, shared randomness and partial mutations. + +The [named feature-resource comparison](feature-placement.md#named-feature-resources) +adds **1,734,390 matching lines per JAR** for registry-aware feature/placed-feature +holders, ordered tags and subsequent nested execution. Complete registry loading, +reloads and remaining feature algorithms are still pending. + +The [configured fill-layer comparison](feature-placement.md#configured-fill-layers) +adds **1,305,274 matching lines per JAR** for block-state binding and ordered +column placement, including decoding every pinned block state. Complete feature +generation and gameplay remain pending. + +The [replacement-rule comparison](feature-placement.md#replacement-rules) adds +**1,890,716 matching lines per JAR** for all ten native predicate kinds, bound +state/tag identities and ordered random evaluation. Complete ore and structure +generation remain pending. + +The [single-block replacement comparison](feature-placement.md#single-block-replacement) +adds **303,678 matching lines per JAR** for ordered rule-driven block mutations, +rejected writes, failures and subsequent random state. + +The [scattered-ore comparison](feature-placement.md#scattered-ore) adds +**758,484 matching lines per JAR** for attempt offsets, ordered air-exposure checks, +rule evaluation and block mutations. Ordinary ore veins and complete biome +decoration remain pending. + +The [bulk-section comparison](feature-placement.md#bulk-section-access) adds +**959,640 matching lines per JAR** for cached raw section access, every block state, +all-air reads and unchanged heightmaps. This supplies storage behavior needed by +ordinary ore generation; vein geometry and concurrent ownership remain pending. + +The [biome feature-order comparison](feature-placement.md#biome-feature-ordering) +adds **411,751 matching lines per JAR** for identity-based ordering, cycles and +step index mappings, including every bundled biome's feature lists. This does +not yet execute complete chunk decoration. + +The [world-generation random-adapter comparison](feature-placement.md#world-generation-random-streams) +adds **238,800 matching lines per JAR** for native bit sampling, counters, forks, +nested wrappers and decoration/feature seeding. Gaussian sampling and complete +chunk decoration remain pending. + +The [biome-placement comparison](feature-placement.md#biome-placement-filtering) +adds **121,423 matching lines per JAR** for top-feature contexts, native generation +settings membership, query order, nested ordinary placers and partial failures. +Complete biome sampling integration and chunk decoration remain pending. + +The [decoration scheduler comparison](feature-placement.md#decoration-feature-scheduling) +adds **337,398 matching lines per JAR** through the native chunk-decoration entry +point, with structures disabled and traced feature sinks. It covers resident +biome selection, global ordering, per-feature seeds and failure/progress state; +complete feature algorithms and chunk lifecycle remain pending. + +The [resident decoration comparison](feature-placement.md#decoration-over-resident-chunks) +adds **36,173,951 matching lines per JAR** for native chunk decoration combining +biome storage/zoom, generation-stage guards, scheduling, implemented feature +graphs, block writes and live heightmaps. It compares complete final resident +sections; structures, lighting and the full generation lifecycle remain pending. + +The [block-state provider comparison](feature-placement.md#block-state-providers) +adds **105,340,143 matching lines per JAR** for ten state-provider kinds, including +all eight bundled provider definitions. It includes every state under six +directions, property transforms, nested draw order and empty selections. Rule-based +selection includes twelve predicate kinds, ordered conditions, empty results and +query failures. Named holder references are resolved through immutable resource +snapshots. Additional predicates, complete registry loading and complete feature placement remain pending. + +The [contained-fluid comparison](world-data.md#contained-fluid-states) adds +**239,190 matching lines per JAR** for fluid-state mapping, liquid-block conversion +and surface/camera height queries. It covers every pinned block state and query +failures; fluid spreading, entity interactions and rendering remain pending. diff --git a/docs/scheduled-ticks.md b/docs/scheduled-ticks.md new file mode 100644 index 000000000..e6faca658 --- /dev/null +++ b/docs/scheduled-ticks.md @@ -0,0 +1,136 @@ +# Horizon scheduled ticks + +The Rust scheduler targets the repository-pinned **Minecraft Java Edition +26.3**. It implements scheduled block/fluid queue mechanics and saved tick +lists. Actual block/fluid updates, random ticks, block events, neighbor updates, +redstone behavior and a running game world remain unimplemented. + +## Behavior + +`horizon_core::ticks` supplies `TickPriority`, `ScheduledTick`, `SavedTick`, +`ChunkTicks` and `LevelTicks`. A numeric `TickTypeId` represents a registry-owned +block or fluid type. Block and fluid scheduling use separate `LevelTicks` +instances. Callers supply identities, game time, sub-tick counters, eligibility, +per-call tick limits and behavior callbacks. + +The first request for a type and position wins, even if a duplicate has an +earlier trigger time or a higher priority. A chunk queue orders by signed +trigger time, then one of seven priorities, then signed sub-tick order. Once +heads are due, **different chunks compete by priority and sub-tick order**. +Consequently, globally sorting every tick by trigger time changes execution. +Within the selected chunk, draining stops when its next head loses to the +competing chunk head, exceeds the time bound, or exhausts the tick limit. + +Equal comparator keys follow the pinned Java array heap behavior. Deadline +traversal follows the pinned fastutil long-map layout, including resizing, +collision shifts and wrapped iterator removals. These details matter when +loaded ticks in different chunks share priority and negative sub-tick order. +They are covered by differential tests rather than replaced with a new tie +breaker. The heap stores tick records inline and retains collection capacity +between frames. Area operations probe small chunk grids directly and visit +only loaded chunks for large sparse areas, preserving X/Z traversal order. +No game FPS or memory gain has been measured. + +Collection happens before callbacks. A callback can schedule, query, clear, +copy, disable or unload chunks; newly scheduled ticks wait for the next +collection. `has_scheduled` covers container queues and pending saved ticks; +`will_tick_this_tick` covers the remaining collected queue. The current callback +has already moved to the already-run list. Vanilla's lazily built membership +set can remain stale after an area clear; that behavior is preserved until +cleanup. Area copying includes already-run, collected and queued ticks and +places copied sub-tick orders after the copied source range with wrapping +signed-long arithmetic. + +Disabled chunks retain due entries. Removing a container returns its queue +for saving or later reinsertion; collected callbacks still run. Scheduling into +an absent chunk returns `MissingChunk` and does not enqueue. The Rust API adds +invariant checks for duplicate chunk insertion, wrong-chunk contents and invalid +collection phase transitions. These checks differ from Java's unchecked API +and logging, while preserving the tested valid lifecycle. + +## Persistence and use + +Saved ticks hold a signed 32-bit relative delay. Packing narrows the wrapped +time difference as Java does and stably sorts active ticks by sub-tick order. +Pending saved entries precede active entries. Unpacking assigns orders from +`-saved_count` through `-1` and adds delays with signed-long wrapping. Vanilla +does not deduplicate a saved list during unpack; duplicate entries and their +membership behavior are retained. + +`horizon_world::tick_data` bridges the vanilla `i`, `x`, `y`, `z`, `t`, `p` +fields to type IDs through caller-supplied names. `ChunkData::saved_ticks` +loads a pending container and filters out positions belonging to other chunks; +`set_saved_ticks` writes packed entries while preserving unrelated root data. +The separate block/fluid name lookup is required because their IDs are not +the resident section's block-state IDs. + +```rust +use horizon_core::{position::ChunkPos, ticks::{LevelTicks, ScheduledTick}}; +use horizon_world::{chunk::ChunkData, tick_data::TickKind}; + +fn run_saved_blocks( + chunk: &mut ChunkData, + now: i64, + resolve: impl FnMut(&str) -> Option, + name: impl FnMut(horizon_core::ticks::TickTypeId) -> Option, + run: impl FnMut(&mut LevelTicks, ScheduledTick), +) -> Result<(), Box> { + let pos: ChunkPos = chunk.position(); + let mut pending = chunk.saved_ticks(TickKind::Block, resolve)?; + pending.unpack(now); + let mut level = LevelTicks::default(); + level.add_chunk(pos, pending)?; + level.tick(now, 65_536, |_| true, run)?; + let pending = level.remove_chunk(pos).unwrap(); + chunk.set_saved_ticks(TickKind::Block, &pending.pack(now), name)?; + Ok(()) +} +``` + +The caller supplies the behavior callback. A game integration must check the +current block/fluid type, invoke its actual behavior, +apply resulting state/neighbor/light changes, and persist remaining queues +through the chunk lifecycle. The scheduler alone does not provide gameplay. + +## Validation + +```sh +cargo test --workspace +cargo clippy --workspace --all-targets -- -D warnings +python3 tools/test_tick_parity.py --prepare +``` + +The runner authenticates both official reference JARs and dependencies against +the repository lock and bundled hashes. An original Java adapter invokes the +actual `LevelTicks`, `LevelChunkTicks`, `ScheduledTick`, `SavedTick` and +`TickPriority` classes; expected traces are not computed by another port. + +The corpus has **25,815 commands**, including **2,096 tick invocations**, and +produces **97,776 matching output lines per reference JAR**. It covers: + +- All priorities, overdue chunk competition, exact comparator ties, duplicate + requests and signed time/order extremes. +- Map growth/shrink, collisions crossing the table boundary, limited draining, + disabled chunks, unloading and restoration. +- Pending-list duplicates, save packing, negative load orders and repeated + save/reload with changed game time. +- Membership queries and rescheduling, clearing, copying, unloading or + disabling chunks during callbacks. +- Eight deterministic randomized scenarios with queue snapshots, saves, + eligibility changes and area operations. + +A separate adapter uses the actual block and fluid `SavedTick` registry codecs. +Rust loads, filters, unpacks, polls, reschedules and saves **251 block ticks and +251 fluid ticks**. Vanilla checks the resulting NBT and a Rust-written region +chunk. Fixtures include duplicate saved entries, out-of-chunk coordinates, +negative delays, overflowing times and numeric NBT coercions including NaNs, +infinities and narrowed longs. + +Offline tests cover phase guards, eligibility, callback deferral, ordering, +area membership, copying, invalid data and atomic saved-list updates. CI runs +this suite alongside core and world-data comparisons. Evidence stays under +`.local/rust-tick-parity/`; success reports are cleared before each run and +source hashes must remain unchanged during validation. The checked-in +[scoped report](../benchmarks/rust-ticks-2026-10-05/scoped-parity.json) contains +metadata and hashes only. Line counts are corpus observations, not gameplay +coverage percentages or proof of complete vanilla parity. diff --git a/docs/shader-world-smoke.md b/docs/shader-world-smoke.md index 6a8464212..c0277408e 100644 --- a/docs/shader-world-smoke.md +++ b/docs/shader-world-smoke.md @@ -54,7 +54,7 @@ snapshot. Waiting state contains only six booleans and a tick count; arbitrary screen names, messages and paths are excluded. An unsuccessful research run remains unsuccessful. Playable shader/backend defaults remain unchanged. -Diagnostic repeat [37199837867](https://github.com/ludovic111/minecraft-optimization-lab/actions/runs/37199837867) +Diagnostic repeat [37199837867](https://github.com/ludovic111/Horizon/actions/runs/37199837867) uses the richer diagnostics. Both cases again hit the 240-second timeout and require bounded termination. OpenGL initializes its device and loads a world with a player, no overlay, an active window and no pause; a screen remains diff --git a/docs/structure-density.md b/docs/structure-density.md new file mode 100644 index 000000000..448d462c9 --- /dev/null +++ b/docs/structure-density.md @@ -0,0 +1,43 @@ +# Structure terrain-adaptation density + +`horizon_core::density::Beardifier` implements the pinned Java Edition **26.3** +structure-density sampler from supplied ordered rigid pieces, jigsaw junctions +and an affected bounding box. It supports `NONE`, `BURY`, `BEARD_THIN`, `BEARD_BOX` +and `ENCAPSULATE` adjustments. Live structure discovery, filtering and placement +remain separate work. + +The sampler retains float accumulation order, wrapped coordinate arithmetic, +ground-level deltas, the 24-by-24-by-24 kernel and vanilla's inverse-square-root +approximation. Its kernel is computed once from the formula. No extracted vanilla +kernel data is stored in the source tree. The immutable sampler can be attached +to `WorldField::Beardifier` and shared between worker contexts. + +Scalar reads return zero outside the affected box. Bulk reads clear the entire +output, including an oversized tail, then scan the clipped strided volume. +Vanilla floors the lower clipping index rather than rounding it upward, so a +first bulk sample can be outside the scalar bounds. Horizon preserves this +scalar/bulk distinction. A missing affected box produces zero even if component +lists are nonempty. Bounds supplied to the Rust constructor must already be +normalized; short output buffers return a typed error before mutation. + +Run: + +```sh +python3 tools/test_structure_density_parity.py +``` + +The [local report](../benchmarks/rust-structure-density-2026-10-06/scoped-parity.json) +records **1,360,095 matching output lines per reference JAR** across **183 fixtures**, +**28,093 scalar queries** and **339 volumes**. The original Java adapter calls the +actual `Beardifier` constructor and samplers. Cases include every adjustment mode, +the full junction kernel neighborhood, ground offsets, overlapping components, +reversed accumulation order, null/empty bounds, floor clipping, output tails and +extreme wrapped coordinates. Float outputs are compared by raw bits with +canonical NaNs. + +The report records the authenticated JARs, source and fixture hashes. Raw outputs +stay private under `.local`. CI runs the comparison on its configured platforms; +the local `Math.pow`-derived kernel check does not establish cross-platform math +parity. The [noise-fill comparison](terrain-filling.md) also checks supplied structure +density through final-density and aquifer graphs. Structure-start selection, +invalid-box repair and complete structure terrain generation remain pending. diff --git a/docs/terrain-filling.md b/docs/terrain-filling.md new file mode 100644 index 000000000..8daf2804d --- /dev/null +++ b/docs/terrain-filling.md @@ -0,0 +1,88 @@ +# Noise-stage terrain filling + +Horizon now connects final-density sampling, aquifer selection, resident block +sections, world-generation heightmaps and fluid postprocessing for the pinned +Minecraft Java Edition **26.3**. This implements the initial noise fill, before +the [surface stage](material-surfaces.md#chunk-surface-stage), features and +structure placement. + +`TerrainChunk` owns registry-backed `BlockSection` palettes, non-air counts, +optional heightmaps and per-section postprocessing offsets. Raw section reads +retain stored cave/void air; chunk reads collapse an all-air section to AIR, as +vanilla `ProtoChunk` does. Block air/fluid behavior and tag membership come from a +`TerrainBlockStates` provider tied to the same immutable registry. + +`fill_noise` samples the entire final-density volume before writing blocks. It +then visits increasing Z, increasing X and decreasing Y. Aquifer results use the +default solid block when absent. Exact default AIR results skip writes, preserving +any prior block at that position. Other states are written before updating +`OCEAN_FLOOR_WG`, then `WORLD_SURFACE_WG`. A scheduled aquifer result with nonempty +fluid appends its packed offset; repeated offsets are retained in insertion order. + +The aquifer and final-density sampler share a context. The caller constructs the +aquifer first, then compiles final density through the same compiler. The Rust +fill API accepts a full 16-by-16 chunk footprint with unit steps and a positive +vertical subrange inside its bounded chunk. Typed failures retain earlier writes +and sampler/aquifer state. Developer diagnostic surface markers are outside this +regular-gameplay path. + +Run the differential comparison with: + +```sh +python3 tools/test_terrain_parity.py +``` + +The [local report](../benchmarks/rust-terrain-2026-10-06/scoped-parity.json) records +**7,950,873 matching output lines per reference JAR**, checked against both client +and server. **114 fixtures** perform **200 fills**; **61 fixtures** enable noise-based +aquifers. Cases include all seven bundled routers, their aquifer configurations, +both random algorithms, multiple seeds and positive/negative chunk coordinates, +synthetic density roots, nondefault fluid-bearing states, prefilled chunks, +partial-height fills and repeated fills using the same caches. An additional +24 fixtures bind rigid-piece and junction density through the actual noise chunk, +including synthetic final-density and aquifer roots that consume that field. + +After every fill, the suite compares every raw section state, both packed +heightmaps, the final fluid-scheduling flag and every ordered postprocessing +offset. The reference invokes actual vanilla `NoiseChunk` and +`NoiseBasedChunkGenerator.doFill`, with empty blending and empty or supplied structure-density fields. +Rust resolves bundled tags and compiles density and aquifer roots itself. +Block identities/properties and air/fluid facts are private exports, generated +independently by both authenticated JARs and required to agree. Importing these +facts does not implement the underlying block behaviors. Placeholder material +and biome holders are never evaluated in this fill-only comparison. + +Reports capture source and fixture hashes, and the runner rejects changes during +validation. CI includes the comparison on its configured platforms; the local +report does not establish remote results. Complete generated terrain still needs +biome assignment, structures, features, nonempty +blending and live structure discovery, lighting and chunk lifecycle integration. These +results do not establish a playable client or whole-game performance improvements. + +The [combined surface-stage suite](material-surfaces.md#chunk-surface-stage) now +checks noise filling followed by surface application through shared density +contexts for all seven bundled terrain settings. + + +## Block writes across generation stages + +`PreLightChunkStage` represents the six statuses from empty through features. +`TerrainChunk::set_block_worldgen` maintains the two world-generation maps through +biomes, then the four final maps at terrain/features. Assigning a stage alone +neither clears nor primes maps. Writes update existing selected maps first and +then prime missing selected maps; maps belonging to earlier stages retain their +stored values. This also preserves native behavior when an earlier stage is +assigned again. + +Run `python3 tools/test_chunk_stage_parity.py`. The +[stage report](../benchmarks/rust-chunk-stage-2026-10-06/scoped-parity.json) records +**8,090,090 matching lines per reference JAR** across 32 fixtures. Every pinned +block state is inserted and removed under both map groups. The comparison uses +actual `ProtoChunk.setBlockState` and persisted-status assignment, checking returned +old states, chunk reads, map presence/heights, packed map words and raw sections. +It also covers forward/backward transitions, explicit priming, empty-section AIR +writes, out-of-height writes and wrapping X/Z coordinates. + +This implements stage-dependent storage mutation. Scheduling, saved status +metadata, retrogen, lighting, block entities and complete region behavior remain +pending. diff --git a/docs/value-providers.md b/docs/value-providers.md new file mode 100644 index 000000000..dfca9216f --- /dev/null +++ b/docs/value-providers.md @@ -0,0 +1,63 @@ +# World-generation value providers + +Horizon implements the scalar distributions needed by the pinned Java Edition +**26.3** cave and canyon definitions. `FloatProvider` supports constant, uniform +and trapezoid distributions. `IntProvider` supports constant, uniform, biased and +very biased distributions, trapezoids, recursively clamped sources and weighted lists. + +Decoding retains vanilla numeric narrowing, field defaults and validation rules. +Sampling preserves float operation order, wrapping integer bounds and the number +of random draws. Symmetric integer trapezoids use vanilla's distinct two-draw +subtraction path. Constant float codecs normalize both signed zeros to positive +zero. Invalid random bounds return an error without silently replacing a result. + +Run `python3 tools/test_value_provider_parity.py`. The +[local report](../benchmarks/rust-value-provider-2026-10-06/scoped-parity.json) +records **429,920 matching lines per vanilla JAR**, across **504 definitions** and +**5,040 seeded fixtures**. The suite invokes actual provider codecs, reads declared +bounds and compares up to 64 samples per valid fixture. Every sample is followed +by a random long, checking draw consumption as well as output. Both random modes, +signed zeros, overflow, equal/reversed ranges, negative plateaus, malformed fields, +duplicate keys and sampling failures are covered. + +Gaussian providers and canonical provider encoding remain pending. A local +Gaussian-math probe found double-bit differences between the host Rust logarithm +and the pinned JVM; using the system logarithm directly would not establish exact +Gaussian parity. +This scoped comparison does not establish complete carver or world-generation +parity. Provider definitions use a bounded decoder; nested integer clamps are +limited to depth 256 and 65,536 total provider nodes. + + +## Anchored height providers + +`HeightProvider` supports constant, uniform, biased, very biased, trapezoid and weighted +heights using all four vertical-anchor kinds. Empty resolved ranges return the +vanilla fallback without drawing randomness. Very biased heights preserve the +guarded inclusive draws, while trapezoid heights retain their distinct sampling +behavior even for symmetric bounds. Anchor resolution and bound arithmetic wrap +as signed Java integers. + +Run `python3 tools/test_height_provider_parity.py`. The +[height-provider report](../benchmarks/rust-height-provider-2026-10-06/scoped-parity.json) +records **507,660 matching lines per JAR**. The suite compares actual +`HeightProvider.CODEC` parsing and up to 32 samples per valid definition/context, +with subsequent random longs. It covers all four anchors, ordinary and overflowing +generation contexts, empty/equal ranges, defaults and invalid inner/plateau fields, +and anchor-versus-dispatch preference. Warning logs are excluded. Height-provider encoding remains pending. + + +## Weighted choices + +Weighted integer and height providers retain entry order, nested providers and +zero-weight entries. Integer bounds include zero-weight entries even though they +cannot be selected. Every selection consumes one bounded draw, including a +singleton of weight one. Total weights must be positive and no greater than +2,147,483,647; native constructor rejections are recorded as decode errors. + +Rust stores cumulative weights and selects by binary search, avoiding allocation +proportional to total weight. The differential suites cover totals on either side +of vanilla's 64-weight selector threshold, maximum and overflowing totals, nested +choices, malformed entries and exact subsequent random state. Each list is bounded +to 8,192 entries, with a shared 65,536-node budget across nested provider decoding. +Unit tests check those allocation limits and reject oversized branching trees. diff --git a/docs/vertical-anchors.md b/docs/vertical-anchors.md new file mode 100644 index 000000000..ce743463a --- /dev/null +++ b/docs/vertical-anchors.md @@ -0,0 +1,22 @@ +# Vertical anchors + +Horizon implements the pinned Java Edition **26.3** vertical anchors: absolute, +above bottom, below top and relative to sea level. Runtime resolution preserves +signed integer wrapping. Codec parsing and encoding enforce the vanilla field +range, preserve decimal truncation and integer wrapping, and follow the nested +exclusive alternatives even when multiple fields appear in one object. + +`WorldGenerationContext` carries the minimum, height and sea level. Its generator +adapter chooses the larger minimum and smaller height independently, matching +vanilla; this differs from intersecting the vertical intervals. + +Run `python3 tools/test_anchor_parity.py`. The +[local report](../benchmarks/rust-anchor-2026-10-06/scoped-parity.json) records +**181,632 matching output lines per reference JAR**, across **192 fixtures**, +**74,112 codec inputs** and **107,328 runtime anchors**. The original Java +transport calls the actual codecs, helper constructors and generation context, +including the native noise-based chunk generator for bounds comparisons. + +Sources and fixtures are hash-checked before publishing results. Raw reference +output stays under `.local`. These tests cover anchor behavior and the three +context values, not complete material rules, level access or JSON diagnostic text. diff --git a/docs/worker-pacing.md b/docs/worker-pacing.md index d804b74a7..5b969dee8 100644 --- a/docs/worker-pacing.md +++ b/docs/worker-pacing.md @@ -67,7 +67,7 @@ terrain completion times alongside foreground performance and CPU use. ## Hosted executor measurements [Raw platform results](../benchmarks/worker-pacing-2026-10-03/) came from -[CI run 37147381649](https://github.com/ludovic111/minecraft-optimization-lab/actions/runs/37147381649), +[CI run 37147381649](https://github.com/ludovic111/Horizon/actions/runs/37147381649), using the 50,000-job workload and the revised overshoot credit. Median worker CPU seconds per elapsed second across three runs were: diff --git a/docs/world-data.md b/docs/world-data.md new file mode 100644 index 000000000..26546c847 --- /dev/null +++ b/docs/world-data.md @@ -0,0 +1,147 @@ +# Horizon world data + +`crates/horizon-world` implements part of the Rust rewrite's storage layer for +the repository-pinned Java Edition **26.3**, data version **5023**. It reads and +exports region files and provides block-section access. Lighting, world generation, +networking and rendering remain unimplemented. Scheduled block/fluid queues now +integrate with saved tick lists, but their gameplay callbacks remain unimplemented. + +## Commands + +Build the standalone tools with `cargo build --release -p horizon-world`. +The binary is `target/release/horizon-world` (`.exe` on Windows). + +```sh +target/release/horizon-world inspect /path/to/world/region/r.0.0.mca +target/release/horizon-world get-block /path/to/world/region/r.0.0.mca 0 64 0 +target/release/horizon-world copy-region /path/to/world/region/r.0.0.mca /path/to/export/r.0.0.mca +target/release/horizon-world copy-region /path/to/world/region/r.0.0.mca /path/to/lz4-export/r.0.0.mca lz4 +target/release/horizon-world edit-block-data /path/to/world/region/r.0.0.mca /path/to/edited/r.0.0.mca 0 64 0 minecraft:oak_log axis=y +target/release/horizon-world nbt-copy /path/to/level.dat /path/to/level-uncompressed.nbt gzip none +target/release/horizon-world --help +``` + +Use offline input and a separate export directory. Output filenames must retain +the source region coordinates. Existing destination regions and external chunk +files are refused. An unchanged export preserves chunk payloads and timestamps; +an explicitly recompressed export preserves decoded NBT values, subject to +vanilla's canonicalization. Region allocation layout may change. + +`get-block` reports the stored descriptor; string descriptors can omit default +properties. `edit-block-data` changes an existing saved section's block data and +preserves other chunk fields. It does **not** perform a gameplay placement: +heightmaps, light, block entities, ticks and neighbor updates are not updated. +The raw command accepts descriptors without validating them against a loaded +registry. The library's `BlockRegistry::resolve` validates properties and +supplies defaults, and `BlockSection` uses that registry for resident storage. + +## Implementation + +NBT handles all tag types, named and unnamed network roots, Java modified UTF-8 +including unpaired UTF-16 surrogates, and 26.3 heterogeneous list wrappers. +Compound key order is not preserved; duplicate keys resolve to their last +value. Java's negative-zero normalization on loading and NaN canonicalization +on writing are reproduced. Defaults bound encoded/decoded NBT to 64 MiB, +one million wire nodes and 512 container levels. These are application limits, +not a reproduction of Java's allocation accounting or exception behavior. + +Region codecs are gzip, zlib, uncompressed and **lz4-java block framing**. +The latter includes the pinned library's 28-bit xxHash checksum adapter. +Region headers, chunk lengths, sector overlap and external `.mcc` chunks are +validated. Chunk coordinates use floor division at negative boundaries. + +Exports build a temporary region, sync file content, then publish using a +hard link that fails if the destination exists. Failed writers cannot publish; +normal error cleanup removes their temporary and newly created external files. +The filesystem must support hard links. This is an offline export mechanism: +concurrent source modification, crash recovery, directory fsync and in-place +save transactions are not implemented. + +Saved palettes support uniform zero-bit sections and padded packed words for +4,096 block entries or 64 biome entries. Resident `BlockSection` stores numeric +state IDs through a shared, borrowed registry. Uniform sections have no word +array. Changes reuse unused palette slots; replacing a unique value can update +its slot without repacking 4,096 entries. Width changes repack only when needed. +Explicit compaction removes unused slots and reduces the packed width. + +The registry loader checks data version, duplicate states, default IDs and +block-name coverage. The local oracle exports all 35,723 state identities and +defaults from vanilla. This imports identities, not block implementations, +shapes or behavior. Registry exports and game-derived fixtures stay in `.local/`. +Chunk access requires data version 5023; older saves need an unimplemented +data-fixing layer. `BlockRegistry::resolve` rejects invalid property descriptors. The separate +[block-state JSON codec](block-state-codecs.md) reproduces vanilla property +fallback for compact and full JSON forms. + +`ChunkData::saved_ticks` reads `block_ticks` or `fluid_ticks`, resolves type +identities through a caller-supplied registry lookup, and filters positions +outside the chunk as vanilla does. `set_saved_ticks` writes a queue's packed +relative delays while preserving other root fields. IDs here identify block or +fluid types, not block states. Missing tick lists are empty. Numeric fields use +vanilla's integer narrowing and floating-point conversion. Unknown types and +malformed entries return errors; vanilla's logging/partial-result paths are not +reproduced. [Scheduler integration and its separate suite](scheduled-ticks.md). + +## Validation + +```sh +cargo test --workspace +cargo clippy --workspace --all-targets -- -D warnings +python3 tools/test_rust_parity.py --prepare +python3 tools/test_world_parity.py +python3 tools/test_tick_parity.py +``` + +The world runner verifies the pinned artifacts, generates fixtures by invoking +actual vanilla classes, processes them with Rust, and reads the results with +both official client and server code. Each reference checks: + +- 32 NBT format/codec conversions covering every tag type, UTF-16 edge cases, + mixed lists, floating-point canonicalization and oversized byte arrays. +- 44 edited/compacted palette cases, comparing 123,776 individual values across + uniform, local and global vanilla palette transitions. +- 48 region chunk reads covering four codecs, copying, recompression, a stored + block edit, negative positions and oversized external chunks. +- All 35,723 exported block-state IDs and their serialized registry data. +- 8,192 resident values: a section with 4,096 distinct states, followed by the + result of 100,000 mixed block replacements checked against an independent + array of expected IDs. Rust additionally checks each returned old value, + periodic compaction, every registry ID through one slot, and uniform collapse. + +Offline tests cover malformed lengths, truncation, NBT limits, corrupt checksums, +invalid palette indices, sector corruption, the inline/external size boundary, +unknown-field preservation, failed-writer cleanup and destination collisions. +CI runs both differential suites. Run artifacts and logs stay under +`.local/rust-world-parity/`; a stale top-level success report is removed before +each run. The checked-in [report](../benchmarks/rust-world-2026-10-05/scoped-parity.json) +contains metadata and hashes only. + +These are synthetic storage fixtures, not a generated world's full save/load +lifecycle or playable integration test. They establish the reported tested +scope; they do not establish complete vanilla parity or any FPS improvement. + + +## Contained fluid states + +`FluidStateTable` derives the fluid carried by each pinned block state: empty, +water or lava, source/flowing identity, amount and falling status. Waterlogged +copper grates carry falling source water. `FluidBlockBindings` binds constant-time +conversion back to liquid block identities, including the collapse of liquid +levels 8–15 to their shared falling-fluid block representation. + +`FluidHeightWorld` supplies above-fluid and downward-face support queries. +Ordinary height returns a full block when matching fluid is above; camera height +first checks downward support above a source. Empty fluids skip world queries. +Coordinates wrap as Java integers, and query failures preserve evaluation order. +The adapter owns block-support geometry; this interface does not implement every +block's support shape. + +Run `python3 tools/test_fluid_parity.py`. The +[fluid report](../benchmarks/rust-fluid-2026-10-06/scoped-parity.json) records +**239,190 matching lines per JAR**. It compares all 35,723 block states, five fluid +identities, every fluid-family pair, own-height bits, source/falling/full flags and +legacy block conversion. The 40,344 world fixtures request 80,688 surface/camera +height queries, including coordinate overflow and injected failures. The support +fixtures use actual vanilla stone and air states. Fluid spreading, scheduled +updates, entity interactions and rendering remain pending. Workspace tests, +Clippy and 137 Python tests passed at this stage. diff --git a/docs/world-generation.md b/docs/world-generation.md new file mode 100644 index 000000000..f2d556727 --- /dev/null +++ b/docs/world-generation.md @@ -0,0 +1,192 @@ +# World generation + +Horizon targets the repository-pinned Minecraft Java Edition **26.3**. +`horizon_world::worldgen::decode_noise` implements its direct normal-noise JSON +codec. `DensityRegistry` decodes named density definitions and `NoiseRouter` +loads the eight router roots against the same graph. `AquiferConfig` binds the six +aquifer density roots, and `NoiseBasedAquifer` implements underground fluid and +pressure selection. Complete terrain generation remains pending. + +The decoder reads numeric tokens directly from `serde_json::value::RawValue`. +This preserves decimal precision and the sign of integer `-0`, avoiding a +double-precision intermediate before float density decoding. Integer +fields retain Gson's truncation toward zero and wrapping to the low 32 bits, +including decimal and exponent forms. + +Noise definitions require a base octave in `[-32,32]`. Defaults are one octave, +unit base amplitude, enabled normalization and an empty amplitude-modifier list. +Octave counts range from 1 to 32. Nonempty modifier lists must contain exactly +that many values. Amplitude bounds retain vanilla's floating-point comparator +ordering: negative zero is below the modifier lower bound of positive zero. +Normalization accepts booleans or the string `"legacy"`. Null optional fields +use their defaults; unknown keys are ignored and duplicate keys retain the last +value. + +The API accepts strict JSON. Gson's additional permissive syntax is outside this +decoder's scope. Construction failures return typed errors; comparison checks +classification and values rather than Java exception messages. + +After preparing the pinned artifacts, run: + +```sh +python3 tools/test_worldgen_parity.py +cargo test --workspace +cargo clippy --workspace --all-targets -- -D warnings +``` + +The original Java transport uses vanilla's actual `NormalNoise.DIRECT_CODEC`, +then its normal and legacy Nether initializers. The suite compares every bundled +noise resource, six world seeds, both random streams and both initialization +paths. Additional cases check codec defaults, normalization modes, field bounds, +invalid types, nulls, duplicate/unknown keys, decimal integer conversion, signed +zero and synthetic parameters. Comparisons include octave metadata, +normalization/range bits, scalar noise and parent random state after success or +failure. Raw registry contents and outputs remain private under `.local`. + +The density loader resolves forward references into distinct immutable named +holders. Numeric and object roots retain direct-value semantics. Its graph is +loaded atomically, with typed errors for missing references and cycles. It +implements the bundled function kinds, including nested splines, shifted noise, +interval selection, rounding, surface searches and context-bound fields. Graph +nesting and interval branches are bounded at 256; inline noise holders remain +pending. These bounds are explicit limits of the Rust API. + +The registry comparison decodes all **55 bundled density definitions** using +vanilla's actual registry-aware codecs and the **64 bundled noise resources**. +It compares ranges, axis dependencies, compilation failures, cache allocation, +seeded scalar values and repeated strided volumes in raw and optimized modes. +Density roots are checked through one compiler per seed and mode. Nonempty +blending and structure fields are outside these fixtures. + +The local run produced **961,693 matching output lines per reference JAR**. The +[metadata report](../benchmarks/rust-worldgen-2026-10-06/scoped-parity.json) records +source hashes, reference identities and resource digests. The runner authenticates +both artifacts, verifies that their registry resources agree, removes stale success +reports and rejects source or fixture changes during validation. CI includes the suite on +its configured platforms; the recorded local run does not establish remote +results or gameplay parity. + +The router loader requires all eight fields in vanilla declaration order. It +retains named holder identity and compiles every field through one shared cache +namespace. Failed router decoding leaves the registry graph intact. All seven +bundled preset routers now match the pinned JARs across six seeds, +both random algorithms and raw/optimized compilation. Single-layer surface +volumes and invalid multilayer surface requests are both checked. This API +decodes the router +object. The vertical `NoiseSettings` and optional `aquifers` members are also decoded; +complete generator settings and material configuration remain pending. + +`NoiseSettings` in 26.3 contains only minimum Y and height. Its JSON fields are +bounded to `[-2032,2031]` and `[0,4064]`. The guard checks the wrapped upper limit +first, then height alignment and minimum alignment to 16. The runtime create +helper applies those guards without the JSON field bounds. Height-accessor +clamping retains wrapped arithmetic, unaligned results and negative heights for +disjoint ranges. The suite compares bundled noise members, runtime and codec +construction, integer conversion and extreme accessor bounds. + +Climate sampling converts quart positions to block coordinates with wrapped +32-bit shifts, evaluates all six fields in order with the same context, and +quantizes using float multiplication followed by Java's saturating long cast. +The suite compares vanilla's actual climate sampler binding and 4,116 quantization +fixtures covering random float bits, subnormals, NaNs, infinities and saturation. +The climate parameter decoder accepts scalar intervals, two-element lists and +objects with `min`/`max` fields. Endpoints use directly parsed floats in `[-2,2]`, +with Java float comparator ordering before quantization. Parameter points require +all six coordinates and an offset in `[0,1]`; negative-zero offsets fail that +lower bound. Codec comparisons include precision-sensitive decimals, missing +fields, invalid types and duplicate keys. + +The immutable climate search tree now reproduces vanilla's stable construction +order, 19-child default, wrapped interval distance and squared fitness, pruning, +and previous-result tie handling. A searcher owns its previous leaf and borrows +one index, preventing cache reuse across unrelated indices. Indexed and brute +lookup intentionally retain their respective tie behavior. The suite compares +all supported branching values 2..32, sizes around branch powers, duplicate +entries, a 65,536-entry tree and extreme signed-long ranges/targets. The entry +bound and typed failures are explicit Rust API limits. + +`MultiNoiseBiomeSource` resolves biome identifiers through scalar climate sampling +and prepared quart volumes. Bulk preparation evaluates six fields in declaration +order and retains their float buffers; each query quantizes those stored values. +Scalar and bulk queries share one previous-result state, so their query order +retains vanilla's tie behavior. The bounded API rejects coordinates outside a +prepared volume. + +The runner exports built-in parameter tables independently from both authenticated +JARs, requires them to agree and keeps them private. These contain 7,594 Overworld +entries covering 56 biome identifiers and five Nether entries. Rust loads the +quantized tables using a Horizon import format. This is an import of built-in +data; the preset builders and vanilla biome codecs remain pending. The reference +uses actual `MultiNoiseBiomeSource` resolvers with keyed registration holders. +These checks resolve identities without evaluating biome properties or gameplay. +Both tables are exercised against every router, including cross-preset fixtures; +this does not establish End biome-source behavior. + +The report records table and fixture digests. Source or private fixture changes +during a comparison invalidate its success report. + +The global fluid picker and disabled-aquifer path are now implemented. Lava +selection uses Y below `min(-54, sea_level)`; other positions use the default +fluid status. Fluid status lookup returns its state only below its level. +Disabled aquifers use the default solid block for positive density; +nonpositive or NaN density calls the picker, and this path never schedules fluid +updates. The reference comparison uses the actual global picker lambda and +`Aquifer.createDisabled`, counting picker calls and checking default state +identities. Regular-mode fixtures cover sea-level cutoffs, extreme coordinates, +subnormal density, signed zeros, NaNs and infinities. Developer fluid-disable +behavior is outside this corpus. + +The noise-based aquifer implementation retains the six-field configuration's +binding order, seeded positional cell generation, nearest-cell ties, pressure +barriers, surface sampling, fluid levels and update scheduling. One context is +shared across all density roots. Cell locations and statuses belong to each +chunk aquifer; surface values are snapped to quart coordinates and cached. +Global fluid statuses use exact state identity where vanilla does, while lava, +water and air predicates classify blocks, including nondefault liquid states, +cave air and void air. Dry cells use the version's `WAY_BELOW_MIN_Y` value +`-32512`; this differs from the global developer-disable status's `-4064`. + +The Rust API limits grids to 16,777,216 cells and constructor surface volumes to +2,097,152 samples, checks array bounds and returns typed errors. It preserves +wrapped grid indexing within that domain, including vanilla's final-index +aliasing. Allocation failures and invalid oversized grids are outside the +comparison corpus. Read-only cache inspection does not populate caches. + +The noise-based comparison uses actual vanilla configuration decoding and aquifer +construction. It checks fluid states, scheduling flags, sampler call order and +values, global picker calls and final location/status/surface caches. Fixtures +include all bundled aquifer configurations, both seeded random factories, +strided volume extents, repeated/reversed queries, nonfinite density/sampler +values, malformed roots and injected failures followed by retries. The runner +requires every injected failure to occur. Developer fluid-disable behavior is +outside these regular-mode checks. This does not validate complete generated +chunks or the registry-backed block classification adapter independently. + +`TagDefinitions` decodes tag entries and files, applies resource-stack replacement, +and resolves required and optional dependencies before building ordered, deduplicated +memberships. Missing required references omit the affected tag while unrelated tags +remain available. Lookup order and required flags retain the pinned runtime's hash +bucket and dependency traversal behavior. A valid JSON resource that fails its tag +codec can introduce an empty tag; invalid replacement leaves earlier entries intact. + +The comparison checks all **300 bundled block-tag files** against **1,286 block +identifiers** exported independently from both JARs. Synthetic fixtures cover +replacement, malformed files, missing references, cycles, duplicate members and +lookup order. The API is bounded to 8,192 definitions and dependency depth 256; +Java hash-tree buckets and pathological self-recursive dependency searches remain +unsupported. These checks cover tag loading, not the gameplay behavior of members. + +The separate [heightmap implementation and comparison](heightmaps.md) now checks +all six types, packed data, updates and priming against actual vanilla chunks. + +The [noise-fill stage](terrain-filling.md) now integrates final density, aquifers, +registry-backed sections, world-generation heightmaps and fluid postprocessing. +Complete terrain still requires material and surface rules, nonempty world fields, +biome/feature/structure placement and complete generated-chunk validation. No rendering, frame-rate or complete gameplay claim follows from +these decoder checks. + + +Subsequent [biome lookup and chunk suites](biome-lookup.md) now validate fuzzy +block-to-quart selection, section-atomic biome fills and multi-noise chunk +assignment through actual `ChunkGenerator.doCreateBiomes`. The original report +above remains a record of its narrower tested source snapshot. diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/HorizonLab.java b/mods/horizon/src/main/java/dev/horizonlab/HorizonLab.java similarity index 97% rename from mods/horizon-lab/src/main/java/dev/horizonlab/HorizonLab.java rename to mods/horizon/src/main/java/dev/horizonlab/HorizonLab.java index e2fe279e4..b6933a07e 100644 --- a/mods/horizon-lab/src/main/java/dev/horizonlab/HorizonLab.java +++ b/mods/horizon/src/main/java/dev/horizonlab/HorizonLab.java @@ -39,7 +39,7 @@ public final class HorizonLab implements ModInitializer { return started ? 1 : 0; })))) .then(Commands.literal("stop").executes(command -> { finishTicks(); return 1; })))); - LOGGER.info("Horizon Lab ready. Simulation rules and tick rate are unchanged."); + LOGGER.info("Horizon ready. Simulation rules and tick rate are unchanged."); } public static synchronized boolean startTicks(String label, int seconds, Path output, String profile) { diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/budget/DebounceWait.java b/mods/horizon/src/main/java/dev/horizonlab/budget/DebounceWait.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/budget/DebounceWait.java rename to mods/horizon/src/main/java/dev/horizonlab/budget/DebounceWait.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/budget/DispatchRetry.java b/mods/horizon/src/main/java/dev/horizonlab/budget/DispatchRetry.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/budget/DispatchRetry.java rename to mods/horizon/src/main/java/dev/horizonlab/budget/DispatchRetry.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/budget/TerrainBudget.java b/mods/horizon/src/main/java/dev/horizonlab/budget/TerrainBudget.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/budget/TerrainBudget.java rename to mods/horizon/src/main/java/dev/horizonlab/budget/TerrainBudget.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/budget/TerrainReadWait.java b/mods/horizon/src/main/java/dev/horizonlab/budget/TerrainReadWait.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/budget/TerrainReadWait.java rename to mods/horizon/src/main/java/dev/horizonlab/budget/TerrainReadWait.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/budget/WakeableIdleWait.java b/mods/horizon/src/main/java/dev/horizonlab/budget/WakeableIdleWait.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/budget/WakeableIdleWait.java rename to mods/horizon/src/main/java/dev/horizonlab/budget/WakeableIdleWait.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/budget/WorkerPacer.java b/mods/horizon/src/main/java/dev/horizonlab/budget/WorkerPacer.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/budget/WorkerPacer.java rename to mods/horizon/src/main/java/dev/horizonlab/budget/WorkerPacer.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/client/DistantTerrainBudget.java b/mods/horizon/src/main/java/dev/horizonlab/client/DistantTerrainBudget.java similarity index 97% rename from mods/horizon-lab/src/main/java/dev/horizonlab/client/DistantTerrainBudget.java rename to mods/horizon/src/main/java/dev/horizonlab/client/DistantTerrainBudget.java index 4fa9430c2..c21e9688a 100644 --- a/mods/horizon-lab/src/main/java/dev/horizonlab/client/DistantTerrainBudget.java +++ b/mods/horizon/src/main/java/dev/horizonlab/client/DistantTerrainBudget.java @@ -46,7 +46,7 @@ final class DistantTerrainBudget { double next = policy.update(setting.getTrueValue(), totalNs / 1e6 / count, targetMs, late / (double) count, heap); if (owned == null || Math.abs(next - owned) > 0.0001) { - if (setting.setValue(next, "Horizon Lab adaptive budget")) { + if (setting.setValue(next, "Horizon adaptive budget")) { owned = next; changes++; HorizonLab.LOGGER.info("Adaptive terrain background runtime ratio: {}", next); diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/client/DistantTerrainSettings.java b/mods/horizon/src/main/java/dev/horizonlab/client/DistantTerrainSettings.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/client/DistantTerrainSettings.java rename to mods/horizon/src/main/java/dev/horizonlab/client/DistantTerrainSettings.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/client/HorizonClient.java b/mods/horizon/src/main/java/dev/horizonlab/client/HorizonClient.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/client/HorizonClient.java rename to mods/horizon/src/main/java/dev/horizonlab/client/HorizonClient.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/client/ShaderSettings.java b/mods/horizon/src/main/java/dev/horizonlab/client/ShaderSettings.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/client/ShaderSettings.java rename to mods/horizon/src/main/java/dev/horizonlab/client/ShaderSettings.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/geometry/RelativeTerrainPosition.java b/mods/horizon/src/main/java/dev/horizonlab/geometry/RelativeTerrainPosition.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/geometry/RelativeTerrainPosition.java rename to mods/horizon/src/main/java/dev/horizonlab/geometry/RelativeTerrainPosition.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/ProcessMemoryMonitor.java b/mods/horizon/src/main/java/dev/horizonlab/metrics/ProcessMemoryMonitor.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/metrics/ProcessMemoryMonitor.java rename to mods/horizon/src/main/java/dev/horizonlab/metrics/ProcessMemoryMonitor.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/Recording.java b/mods/horizon/src/main/java/dev/horizonlab/metrics/Recording.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/metrics/Recording.java rename to mods/horizon/src/main/java/dev/horizonlab/metrics/Recording.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/Reports.java b/mods/horizon/src/main/java/dev/horizonlab/metrics/Reports.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/metrics/Reports.java rename to mods/horizon/src/main/java/dev/horizonlab/metrics/Reports.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/ResidentMemory.java b/mods/horizon/src/main/java/dev/horizonlab/metrics/ResidentMemory.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/metrics/ResidentMemory.java rename to mods/horizon/src/main/java/dev/horizonlab/metrics/ResidentMemory.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/SampleStats.java b/mods/horizon/src/main/java/dev/horizonlab/metrics/SampleStats.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/metrics/SampleStats.java rename to mods/horizon/src/main/java/dev/horizonlab/metrics/SampleStats.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/ServerContext.java b/mods/horizon/src/main/java/dev/horizonlab/metrics/ServerContext.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/metrics/ServerContext.java rename to mods/horizon/src/main/java/dev/horizonlab/metrics/ServerContext.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/SoftwareContext.java b/mods/horizon/src/main/java/dev/horizonlab/metrics/SoftwareContext.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/metrics/SoftwareContext.java rename to mods/horizon/src/main/java/dev/horizonlab/metrics/SoftwareContext.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/TickState.java b/mods/horizon/src/main/java/dev/horizonlab/metrics/TickState.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/metrics/TickState.java rename to mods/horizon/src/main/java/dev/horizonlab/metrics/TickState.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/mixin/CullingEmptyWhitelistMixin.java b/mods/horizon/src/main/java/dev/horizonlab/mixin/CullingEmptyWhitelistMixin.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/mixin/CullingEmptyWhitelistMixin.java rename to mods/horizon/src/main/java/dev/horizonlab/mixin/CullingEmptyWhitelistMixin.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/mixin/CullingRayScratchMixin.java b/mods/horizon/src/main/java/dev/horizonlab/mixin/CullingRayScratchMixin.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/mixin/CullingRayScratchMixin.java rename to mods/horizon/src/main/java/dev/horizonlab/mixin/CullingRayScratchMixin.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/mixin/DhDebounceWaitMixin.java b/mods/horizon/src/main/java/dev/horizonlab/mixin/DhDebounceWaitMixin.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/mixin/DhDebounceWaitMixin.java rename to mods/horizon/src/main/java/dev/horizonlab/mixin/DhDebounceWaitMixin.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/mixin/DhPriorityDispatchMixin.java b/mods/horizon/src/main/java/dev/horizonlab/mixin/DhPriorityDispatchMixin.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/mixin/DhPriorityDispatchMixin.java rename to mods/horizon/src/main/java/dev/horizonlab/mixin/DhPriorityDispatchMixin.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/mixin/DhQuadReuseMixin.java b/mods/horizon/src/main/java/dev/horizonlab/mixin/DhQuadReuseMixin.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/mixin/DhQuadReuseMixin.java rename to mods/horizon/src/main/java/dev/horizonlab/mixin/DhQuadReuseMixin.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/mixin/DhRelativePositionMixin.java b/mods/horizon/src/main/java/dev/horizonlab/mixin/DhRelativePositionMixin.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/mixin/DhRelativePositionMixin.java rename to mods/horizon/src/main/java/dev/horizonlab/mixin/DhRelativePositionMixin.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/mixin/DhTerrainReadWaitMixin.java b/mods/horizon/src/main/java/dev/horizonlab/mixin/DhTerrainReadWaitMixin.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/mixin/DhTerrainReadWaitMixin.java rename to mods/horizon/src/main/java/dev/horizonlab/mixin/DhTerrainReadWaitMixin.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/mixin/DhTickDedupMixin.java b/mods/horizon/src/main/java/dev/horizonlab/mixin/DhTickDedupMixin.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/mixin/DhTickDedupMixin.java rename to mods/horizon/src/main/java/dev/horizonlab/mixin/DhTickDedupMixin.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/mixin/DhWorkerPacingMixin.java b/mods/horizon/src/main/java/dev/horizonlab/mixin/DhWorkerPacingMixin.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/mixin/DhWorkerPacingMixin.java rename to mods/horizon/src/main/java/dev/horizonlab/mixin/DhWorkerPacingMixin.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/mixin/FrameMixin.java b/mods/horizon/src/main/java/dev/horizonlab/mixin/FrameMixin.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/mixin/FrameMixin.java rename to mods/horizon/src/main/java/dev/horizonlab/mixin/FrameMixin.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/mixin/HorizonMixinPlugin.java b/mods/horizon/src/main/java/dev/horizonlab/mixin/HorizonMixinPlugin.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/mixin/HorizonMixinPlugin.java rename to mods/horizon/src/main/java/dev/horizonlab/mixin/HorizonMixinPlugin.java diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/mixin/ServerTickMixin.java b/mods/horizon/src/main/java/dev/horizonlab/mixin/ServerTickMixin.java similarity index 100% rename from mods/horizon-lab/src/main/java/dev/horizonlab/mixin/ServerTickMixin.java rename to mods/horizon/src/main/java/dev/horizonlab/mixin/ServerTickMixin.java diff --git a/mods/horizon-lab/src/main/resources/assets/horizonlab/lang/en_us.json b/mods/horizon/src/main/resources/assets/horizonlab/lang/en_us.json similarity index 100% rename from mods/horizon-lab/src/main/resources/assets/horizonlab/lang/en_us.json rename to mods/horizon/src/main/resources/assets/horizonlab/lang/en_us.json diff --git a/mods/horizon-lab/src/main/resources/fabric.mod.json b/mods/horizon/src/main/resources/fabric.mod.json similarity index 95% rename from mods/horizon-lab/src/main/resources/fabric.mod.json rename to mods/horizon/src/main/resources/fabric.mod.json index 6a5f561be..e9978939e 100644 --- a/mods/horizon-lab/src/main/resources/fabric.mod.json +++ b/mods/horizon/src/main/resources/fabric.mod.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "id": "horizonlab", "version": "0.21.0", - "name": "Horizon Lab", + "name": "Horizon", "description": "Client frame pacing and server tick measurements for reproducible optimization experiments.", "authors": [ "Ludovic" diff --git a/mods/horizon-lab/src/main/resources/horizonlab.mixins.json b/mods/horizon/src/main/resources/horizonlab.mixins.json similarity index 100% rename from mods/horizon-lab/src/main/resources/horizonlab.mixins.json rename to mods/horizon/src/main/resources/horizonlab.mixins.json diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/budget/DebounceQueueBenchmark.java b/mods/horizon/src/test/java/dev/horizonlab/budget/DebounceQueueBenchmark.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/budget/DebounceQueueBenchmark.java rename to mods/horizon/src/test/java/dev/horizonlab/budget/DebounceQueueBenchmark.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/budget/DebounceWaitTest.java b/mods/horizon/src/test/java/dev/horizonlab/budget/DebounceWaitTest.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/budget/DebounceWaitTest.java rename to mods/horizon/src/test/java/dev/horizonlab/budget/DebounceWaitTest.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/budget/DispatchRetryTest.java b/mods/horizon/src/test/java/dev/horizonlab/budget/DispatchRetryTest.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/budget/DispatchRetryTest.java rename to mods/horizon/src/test/java/dev/horizonlab/budget/DispatchRetryTest.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/budget/IdleQueueBenchmark.java b/mods/horizon/src/test/java/dev/horizonlab/budget/IdleQueueBenchmark.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/budget/IdleQueueBenchmark.java rename to mods/horizon/src/test/java/dev/horizonlab/budget/IdleQueueBenchmark.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/budget/TerrainBudgetTest.java b/mods/horizon/src/test/java/dev/horizonlab/budget/TerrainBudgetTest.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/budget/TerrainBudgetTest.java rename to mods/horizon/src/test/java/dev/horizonlab/budget/TerrainBudgetTest.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/budget/WakeableIdleWaitTest.java b/mods/horizon/src/test/java/dev/horizonlab/budget/WakeableIdleWaitTest.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/budget/WakeableIdleWaitTest.java rename to mods/horizon/src/test/java/dev/horizonlab/budget/WakeableIdleWaitTest.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/budget/WorkerPacerTest.java b/mods/horizon/src/test/java/dev/horizonlab/budget/WorkerPacerTest.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/budget/WorkerPacerTest.java rename to mods/horizon/src/test/java/dev/horizonlab/budget/WorkerPacerTest.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/budget/WorkerPacingBenchmark.java b/mods/horizon/src/test/java/dev/horizonlab/budget/WorkerPacingBenchmark.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/budget/WorkerPacingBenchmark.java rename to mods/horizon/src/test/java/dev/horizonlab/budget/WorkerPacingBenchmark.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/client/DistantTerrainBudgetTest.java b/mods/horizon/src/test/java/dev/horizonlab/client/DistantTerrainBudgetTest.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/client/DistantTerrainBudgetTest.java rename to mods/horizon/src/test/java/dev/horizonlab/client/DistantTerrainBudgetTest.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/client/DistantTerrainSettingsTest.java b/mods/horizon/src/test/java/dev/horizonlab/client/DistantTerrainSettingsTest.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/client/DistantTerrainSettingsTest.java rename to mods/horizon/src/test/java/dev/horizonlab/client/DistantTerrainSettingsTest.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/CullingEmptyIntegration.java b/mods/horizon/src/test/java/dev/horizonlab/dispatch/CullingEmptyIntegration.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/CullingEmptyIntegration.java rename to mods/horizon/src/test/java/dev/horizonlab/dispatch/CullingEmptyIntegration.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/CullingRayIntegration.java b/mods/horizon/src/test/java/dev/horizonlab/dispatch/CullingRayIntegration.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/CullingRayIntegration.java rename to mods/horizon/src/test/java/dev/horizonlab/dispatch/CullingRayIntegration.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/DispatchIntegration.java b/mods/horizon/src/test/java/dev/horizonlab/dispatch/DispatchIntegration.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/DispatchIntegration.java rename to mods/horizon/src/test/java/dev/horizonlab/dispatch/DispatchIntegration.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/PositionIntegration.java b/mods/horizon/src/test/java/dev/horizonlab/dispatch/PositionIntegration.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/PositionIntegration.java rename to mods/horizon/src/test/java/dev/horizonlab/dispatch/PositionIntegration.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/QuadReuseIntegration.java b/mods/horizon/src/test/java/dev/horizonlab/dispatch/QuadReuseIntegration.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/QuadReuseIntegration.java rename to mods/horizon/src/test/java/dev/horizonlab/dispatch/QuadReuseIntegration.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/QuadSizeIntegration.java b/mods/horizon/src/test/java/dev/horizonlab/dispatch/QuadSizeIntegration.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/QuadSizeIntegration.java rename to mods/horizon/src/test/java/dev/horizonlab/dispatch/QuadSizeIntegration.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/TerrainReadIntegration.java b/mods/horizon/src/test/java/dev/horizonlab/dispatch/TerrainReadIntegration.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/TerrainReadIntegration.java rename to mods/horizon/src/test/java/dev/horizonlab/dispatch/TerrainReadIntegration.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/TickDedupIntegration.java b/mods/horizon/src/test/java/dev/horizonlab/dispatch/TickDedupIntegration.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/TickDedupIntegration.java rename to mods/horizon/src/test/java/dev/horizonlab/dispatch/TickDedupIntegration.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/fixture/CullingRayAccess.java b/mods/horizon/src/test/java/dev/horizonlab/dispatch/fixture/CullingRayAccess.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/fixture/CullingRayAccess.java rename to mods/horizon/src/test/java/dev/horizonlab/dispatch/fixture/CullingRayAccess.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/fixture/GraphicsBackendTraceMixin.java b/mods/horizon/src/test/java/dev/horizonlab/dispatch/fixture/GraphicsBackendTraceMixin.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/dispatch/fixture/GraphicsBackendTraceMixin.java rename to mods/horizon/src/test/java/dev/horizonlab/dispatch/fixture/GraphicsBackendTraceMixin.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/geometry/RelativeTerrainPositionTest.java b/mods/horizon/src/test/java/dev/horizonlab/geometry/RelativeTerrainPositionTest.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/geometry/RelativeTerrainPositionTest.java rename to mods/horizon/src/test/java/dev/horizonlab/geometry/RelativeTerrainPositionTest.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/metrics/ClientGraphicsIntegration.java b/mods/horizon/src/test/java/dev/horizonlab/metrics/ClientGraphicsIntegration.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/metrics/ClientGraphicsIntegration.java rename to mods/horizon/src/test/java/dev/horizonlab/metrics/ClientGraphicsIntegration.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/metrics/MetricsTest.java b/mods/horizon/src/test/java/dev/horizonlab/metrics/MetricsTest.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/metrics/MetricsTest.java rename to mods/horizon/src/test/java/dev/horizonlab/metrics/MetricsTest.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/metrics/ObjectHeaderBenchmark.java b/mods/horizon/src/test/java/dev/horizonlab/metrics/ObjectHeaderBenchmark.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/metrics/ObjectHeaderBenchmark.java rename to mods/horizon/src/test/java/dev/horizonlab/metrics/ObjectHeaderBenchmark.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/metrics/ObjectSizeAgent.java b/mods/horizon/src/test/java/dev/horizonlab/metrics/ObjectSizeAgent.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/metrics/ObjectSizeAgent.java rename to mods/horizon/src/test/java/dev/horizonlab/metrics/ObjectSizeAgent.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/metrics/ResidentMemoryTest.java b/mods/horizon/src/test/java/dev/horizonlab/metrics/ResidentMemoryTest.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/metrics/ResidentMemoryTest.java rename to mods/horizon/src/test/java/dev/horizonlab/metrics/ResidentMemoryTest.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/metrics/ServerGraphicsIntegration.java b/mods/horizon/src/test/java/dev/horizonlab/metrics/ServerGraphicsIntegration.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/metrics/ServerGraphicsIntegration.java rename to mods/horizon/src/test/java/dev/horizonlab/metrics/ServerGraphicsIntegration.java diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/metrics/TickStateIntegration.java b/mods/horizon/src/test/java/dev/horizonlab/metrics/TickStateIntegration.java similarity index 100% rename from mods/horizon-lab/src/test/java/dev/horizonlab/metrics/TickStateIntegration.java rename to mods/horizon/src/test/java/dev/horizonlab/metrics/TickStateIntegration.java diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java new file mode 100644 index 000000000..9d8c4ec70 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java @@ -0,0 +1,57 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.*; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.*; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.densityfunction.DensityFunctions; +import net.minecraft.world.level.levelgen.material.rule.BlockRule; + +/** Original transport for vertical anchor codecs and generation contexts. */ +public final class VanillaAnchorOracle { + private static WorldGenerationContext context(JsonObject f) { + var v=f.getAsJsonArray("context");int min=v.get(0).getAsInt(),height=v.get(1).getAsInt(),sea=v.get(2).getAsInt(); + if(f.has("generator")) { + var g=f.getAsJsonArray("generator");var zero=DensityFunctions.zero(); + var settings=new NoiseGeneratorSettings(new NoiseSettings(g.get(0).getAsInt(),g.get(1).getAsInt()),Blocks.STONE.defaultBlockState(),Blocks.WATER.defaultBlockState(),new NoiseRouter(zero,zero,zero,zero,zero,zero,zero,zero),Holder.direct(new BlockRule(Blocks.STONE.defaultBlockState())),List.of(),g.get(2).getAsInt(),false,Optional.empty(),false,NoiseGeneratorSettings.DebugFunctions.EMPTY); + var biome=Holder.Reference.createStandAlone(new HolderOwner(){},Biomes.PLAINS); + var generator=new NoiseBasedChunkGenerator(new FixedBiomeSource(biome),Holder.direct(settings)); + return new WorldGenerationContext(generator,LevelHeightAccessor.create(min,height)); + } + var accessor=(LevelAccessor)Proxy.newProxyInstance(LevelAccessor.class.getClassLoader(),new Class[]{LevelAccessor.class},(proxy,method,args)->switch(method.getName()) { + case "getMinY"->min;case "getHeight"->height;case "getSeaLevel"->sea; + default->throw new AssertionError("unexpected accessor method "+method); + }); + return WorldGenerationContext.of(accessor); + } + private static void anchor(VerticalAnchor anchor,WorldGenerationContext context,PrintWriter out) { + var encoded=VerticalAnchor.CODEC.encodeStart(JsonOps.INSTANCE,anchor).result(); + out.println("anchor "+anchor.resolveY(context)+" "+encoded.map(Object::toString).orElse("error")); + } + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + Path dir=Path.of(args[1]); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(String line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();var context=context(f); + out.println("context "+context.getMinGenY()+" "+context.getGenDepth()+" "+context.seaLevel()); + anchor(VerticalAnchor.bottom(),context,out);anchor(VerticalAnchor.top(),context,out);anchor(VerticalAnchor.seaLevel(),context,out); + for(var e:f.getAsJsonArray("values")) { + int value=e.getAsInt(); + for(var a:List.of(VerticalAnchor.absolute(value),VerticalAnchor.aboveBottom(value),VerticalAnchor.belowTop(value),VerticalAnchor.relativeToSeaLevel(value)))anchor(a,context,out); + } + for(var e:f.getAsJsonArray("json")) { + var result=VerticalAnchor.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(e.getAsString())).result(); + if(result.isPresent())anchor(result.get(),context,out);else out.println("error"); + } + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBasicFeatureOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBasicFeatureOracle.java new file mode 100644 index 000000000..1b566c2ae --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBasicFeatureOracle.java @@ -0,0 +1,78 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.world.level.levelgen.placement.*; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.feature.Feature; + +/** Invokes native block-writing features through an observable mutable world. */ +public final class VanillaBasicFeatureOracle { + private static final class Stop extends RuntimeException {} + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + final Block[] BLOCKS={Blocks.AIR,Blocks.STONE,Blocks.COBBLESTONE,Blocks.END_STONE,Blocks.OBSIDIAN}; + if(args[0].equals("export")) { + var values=new JsonArray();for(var block:BLOCKS)values.add(Block.getId(block.defaultBlockState()));Files.writeString(Path.of(args[1]),values.toString());return; + } + Path dir=Path.of(args[1]); + var contextMethod=VanillaPlacementOracle.class.getDeclaredMethod("context",JsonObject.class);contextMethod.setAccessible(true); + var bounds=new JsonObject();bounds.add("context",JsonParser.parseString("[-64,384,63]")); + var generator=((PlacementContext)contextMethod.invoke(null,bounds)).generator(); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();long seed=f.get("seed").getAsLong(); + RandomSource random=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + var decoded=Feature.DIRECT_CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(f.get("definition").getAsString())).result(); + var modifiers=new ArrayList();boolean valid=true; + if(f.has("placement"))for(var json:f.getAsJsonArray("placement")) { + try {var modifier=PlacementModifier.CODEC.parse(JsonOps.INSTANCE,json).result();if(modifier.isPresent())modifiers.add(modifier.get());else valid=false;} + catch(IllegalArgumentException error){valid=false;} + } + if(decoded.isEmpty()||!valid)out.println("decode error");else { + out.println("decode ok");int[] calls={0};int fail=f.get("fail").getAsInt(),reject=f.get("reject").getAsInt(); + var states=new TreeMap(Comparator.comparingInt(BlockPos::getX).thenComparingInt(BlockPos::getY).thenComparingInt(BlockPos::getZ)); + var world=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},(proxy,method,values)->{ + if(method.getName().equals("getMinY"))return -64; + if(method.getName().equals("getHeight")&&(values==null||values.length==0))return 384; + if(method.getName().equals("getSeaLevel"))return 63; + if(method.getName().equals("setBlockAndUpdate"))return InvocationHandler.invokeDefault(proxy,method,values); + var p=((BlockPos)values[0]).immutable();int call=calls[0]++; + switch(method.getName()) { + case "getBlockState"->{ + out.println("get "+p.getX()+" "+p.getY()+" "+p.getZ());if(call==fail)throw new Stop(); + var state=states.getOrDefault(p,BLOCKS[Math.floorMod(p.getX()*31+p.getY()*7+p.getZ()*17,5)].defaultBlockState());out.println("state "+Block.getId(state));return state; + } + case "setBlock"->{ + var state=(BlockState)values[1];int flags=(Integer)values[2];out.println("set "+p.getX()+" "+p.getY()+" "+p.getZ()+" "+Block.getId(state)+" "+flags);if(call==fail)throw new Stop(); + boolean result=reject==0||call%reject!=0;if(result)states.put(p,state);out.println("written "+result);return result; + } + default->throw new AssertionError("unexpected world method "+method); + } + }); + var p=f.getAsJsonArray("origin");var origin=new BlockPos(p.get(0).getAsInt(),p.get(1).getAsInt(),p.get(2).getAsInt()); + var placed=new PlacedFeature(Holder.direct(decoded.get()),modifiers);var placer=new FeaturePlacer(world,generator); + for(int repeat=0;repeat>(); + for(int i=0;i<512;i++)ids.add(Holder.Reference.createStandAlone(new HolderOwner(){},ResourceKey.create(Registries.BIOME,Identifier.parse("horizon:biome_"+i)))); + Path dir=Path.of(args[1]); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(String line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();int min=f.get("min").getAsInt(),height=f.get("height").getAsInt(); + var factory=new PalettedContainerFactory(Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY),Blocks.AIR.defaultBlockState(),null,Strategy.createForBiomes(ids),ids.byId(f.get("default").getAsInt()),null); + var bounds=new int[]{min,min+height-1}; + var chunk=new ProtoChunk(new ChunkPos(f.get("cx").getAsInt(),f.get("cz").getAsInt()),UpgradeData.EMPTY,LevelHeightAccessor.create(min,height),factory,null){@Override public LevelHeightAccessor getHeightAccessorForGeneration(){return LevelHeightAccessor.create(bounds[0],bounds[1]-bounds[0]+1);}}; + chunk.setPersistedStatus(net.minecraft.world.level.chunk.status.ChunkStatus.BIOMES); + for(var value:f.getAsJsonArray("ops")) { + var op=value.getAsJsonArray();bounds[0]=op.get(3).getAsInt();bounds[1]=op.get(4).getAsInt();var calls=new int[1];boolean ok=true; + try { chunk.fillBiomesFromNoise((x,y,z)->{ + out.println("resolve "+x+" "+y+" "+z);int previous=calls[0]++; + if(previous==op.get(2).getAsInt())throw new IllegalStateException("synthetic provider failure"); + return ids.byId(Math.floorMod(x*31+y*7+z*17+op.get(0).getAsInt(),op.get(1).getAsInt())); + });}catch(IllegalStateException error){ok=false;} + out.println("fill "+(ok?"ok":"error")+" "+calls[0]); + for(int section=0;section>>(); + MultiNoiseBiomeSourceParameterList.knownPresets().forEach((preset,list)->presets.put(preset.id().toString(),list)); + for(var preset:presets.entrySet()) { + var entries=new JsonArray(); + for(var value:preset.getValue().values()) { + var point=value.getFirst();var entry=new JsonObject();var coordinates=new JsonArray(); + for(var parameter:new Climate.Parameter[]{point.temperature(),point.humidity(),point.continentalness(),point.erosion(),point.depth(),point.weirdness()}) { + var interval=new JsonArray();interval.add(parameter.min());interval.add(parameter.max());coordinates.add(interval); + } + entry.add("coordinates",coordinates);entry.addProperty("offset",point.offset());entry.addProperty("biome",value.getSecond().identifier().toString());entries.add(entry); + } + result.addProperty(preset.getKey(),entries.toString()); + } + Files.writeString(Path.of(args[0]),result.toString(),StandardCharsets.UTF_8); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeGenerationOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeGenerationOracle.java new file mode 100644 index 000000000..817a3d1bd --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeGenerationOracle.java @@ -0,0 +1,69 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.core.registries.*; +import net.minecraft.resources.*; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.chunk.*; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.blending.Blender; +import net.minecraft.world.level.levelgen.densityfunction.*; +import net.minecraft.world.level.levelgen.material.rule.MaterialRule; +import net.minecraft.world.level.levelgen.synth.NormalNoise; + +/** Original transport invoking actual ChunkGenerator.doCreateBiomes. */ +public final class VanillaBiomeGenerationOracle { + @SuppressWarnings("unchecked") + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); + var bundle=JsonParser.parseString(Files.readString(dir.resolve("registries.json"))).getAsJsonObject(); + var noises=new MappedRegistry(Registries.NOISE,Lifecycle.stable());var densities=new MappedRegistry(Registries.DENSITY_FUNCTION,Lifecycle.stable()); + var noiseLookup=noises.createRegistrationLookup();var densityLookup=densities.createRegistrationLookup(); + var ops=RegistryOps.create(JsonOps.INSTANCE,new RegistryOps.RegistryInfoLookup(){public Optional> lookup(ResourceKey> key){ + if(key.equals(Registries.NOISE))return (Optional>)(Optional)Optional.of(noiseLookup); + if(key.equals(Registries.DENSITY_FUNCTION))return (Optional>)(Optional)Optional.of(densityLookup);return Optional.empty();}}); + for(var e:bundle.getAsJsonObject("noises").entrySet())noises.register(ResourceKey.create(Registries.NOISE,Identifier.parse(e.getKey())),NormalNoise.DIRECT_CODEC.parse(ops,JsonParser.parseString(e.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN);noises.freeze(); + for(var e:bundle.getAsJsonObject("densities").entrySet())densities.register(ResourceKey.create(Registries.DENSITY_FUNCTION,Identifier.parse(e.getKey())),DensityFunctions.DIRECT_CODEC.parse(ops,JsonParser.parseString(e.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN);densities.freeze(); + var presets=new TreeMap>>();MultiNoiseBiomeSourceParameterList.knownPresets().forEach((preset,list)->presets.put(preset.id().toString(),list)); + var ids=new IdMapper>();var holders=new TreeMap>(); + var keys=new TreeSet();keys.add("minecraft:plains");keys.addAll(List.of("minecraft:the_end","minecraft:end_highlands","minecraft:end_midlands","minecraft:small_end_islands","minecraft:end_barrens"));for(var list:presets.values())for(var entry:list.values())keys.add(entry.getSecond().identifier().toString()); + for(var key:keys){var holder=Holder.Reference.createStandAlone(new HolderOwner(){},ResourceKey.create(Registries.BIOME,Identifier.parse(key)));holders.put(key,holder);ids.add(holder);} + var factory=new PalettedContainerFactory(Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY),Blocks.AIR.defaultBlockState(),null,Strategy.createForBiomes(ids),holders.get("minecraft:plains"),null); + var fill=ChunkGenerator.class.getDeclaredMethod("doCreateBiomes",Blender.class,RandomState.class,ChunkAccess.class);fill.setAccessible(true); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();int min=f.get("min").getAsInt(),height=f.get("height").getAsInt(),sea=63;long seed=f.get("seed").getAsLong();boolean legacy=f.get("legacy").getAsBoolean(); + var setting=JsonParser.parseString(bundle.getAsJsonObject("settings").get(f.get("setting").getAsString()).getAsString()).getAsJsonObject();var router=NoiseRouter.CODEC.parse(ops,setting.get("noise_router")).getOrThrow(); + var state=RandomState.create(noises,seed,legacy,Blocks.STONE.defaultBlockState(),sea,router); + var entries=new ArrayList>>(); + for(var entry:presets.get(f.get("preset").getAsString()).values())entries.add(com.mojang.datafixers.util.Pair.of(entry.getFirst(),holders.get(entry.getSecond().identifier().toString()))); + BiomeSource source=MultiNoiseBiomeSource.createFromList(new Climate.ParameterList<>(entries)); + if(f.has("source"))switch(f.get("source").getAsString()) { + case "fixed" -> source=new FixedBiomeSource(holders.get("minecraft:plains")); + case "checkerboard" -> source=new CheckerboardColumnBiomeSource(HolderSet.direct(List.of(holders.get("minecraft:plains"),holders.get("minecraft:the_end"),holders.get("minecraft:nether_wastes"))),f.get("scale").getAsInt()); + case "end" -> {var constructor=TheEndBiomeSource.class.getDeclaredConstructor(Holder.class,Holder.class,Holder.class,Holder.class,Holder.class);constructor.setAccessible(true);source=constructor.newInstance(holders.get("minecraft:the_end"),holders.get("minecraft:end_highlands"),holders.get("minecraft:end_midlands"),holders.get("minecraft:small_end_islands"),holders.get("minecraft:end_barrens"));} + default -> throw new IllegalArgumentException("unknown source"); + } + var material=Holder.Reference.createStandAlone(new HolderOwner(){},ResourceKey.create(Registries.MATERIAL_RULE,Identifier.parse("horizon:unused"))); + var settings=new NoiseGeneratorSettings(NoiseSettings.create(min,height),Blocks.STONE.defaultBlockState(),Blocks.WATER.defaultBlockState(),router,material,List.of(),sea,false,Optional.empty(),legacy,NoiseGeneratorSettings.DebugFunctions.EMPTY); + var generator=new NoiseBasedChunkGenerator(source,Holder.direct(settings)); + var bounds=LevelHeightAccessor.create(f.get("write_min").getAsInt(),f.get("write_max").getAsInt()-f.get("write_min").getAsInt()+1); + var chunk=new ProtoChunk(new ChunkPos(f.get("cx").getAsInt(),f.get("cz").getAsInt()),UpgradeData.EMPTY,LevelHeightAccessor.create(min,height),factory,null){@Override public LevelHeightAccessor getHeightAccessorForGeneration(){return bounds;}}; + chunk.setPersistedStatus(net.minecraft.world.level.chunk.status.ChunkStatus.BIOMES); + for(int repeat=0;repeat();for(var value:f.getAsJsonArray("placement"))modifiers.add(PlacementModifier.CODEC.parse(JsonOps.INSTANCE,value).getOrThrow()); + int[] queries={0},calls={0};int queryFail=f.get("query_fail").getAsInt(),featureFail=f.get("feature_fail").getAsInt(); + var bounds=new JsonObject();bounds.add("context",JsonParser.parseString("[-64,384,63]")); + var generator=((PlacementContext)contextMethod.invoke(null,bounds)).generator(); + var biomes=List.of(Holder.Reference.createStandAlone(new HolderOwner(){},ResourceKey.create(Registries.BIOME,Identifier.parse("horizon:a"))),Holder.Reference.createStandAlone(new HolderOwner(){},ResourceKey.create(Registries.BIOME,Identifier.parse("horizon:b")))); + var leaf=new Feature(){ + public MapCodec codec(){return MapCodec.unit(this);} + public boolean place(WorldGenLevel world,ChunkGenerator gen,RandomSource rng,BlockPos p){ + out.println("feature "+p.getX()+" "+p.getY()+" "+p.getZ()); + if(f.get("draw").getAsBoolean())out.println("draw "+rng.nextLong()); + if(calls[0]++==featureFail)throw new Stop(); + if(f.get("nested").getAsBoolean())return new FeaturePlacer(world,gen).place(new PlacedFeature(Holder.direct(this),List.of(BiomeFilter.biome())),rng,p); + return f.get("return_mode").getAsInt()==0||(f.get("return_mode").getAsInt()==2&&Math.floorMod(p.getX()+p.getY()+p.getZ(),2)==0); + } + }; + var root=new PlacedFeature(Holder.direct(leaf),modifiers); + var copy=new PlacedFeature(root.feature(),root.placement()); + var other=new PlacedFeature(Holder.direct(new Feature(){public MapCodec codec(){return MapCodec.unit(this);}public boolean place(WorldGenLevel w,ChunkGenerator g,RandomSource r,BlockPos p){return true;}}),modifiers); + var settings=new ArrayList(); + for(var value:f.getAsJsonArray("membership")) { + int mode=value.getAsInt();var values=mode==0?List.>of():List.of(Holder.direct(mode==1?root:mode==2?copy:other)); + settings.add(constructor.newInstance(HolderSet.direct(List.of()),List.of(HolderSet.direct(values)))); + } + getter.set(generator,(java.util.function.Function,BiomeGenerationSettings>)(biome)->{ + int index=biome==biomes.get(0)?0:1;out.println("settings "+index);if(queries[0]++==queryFail)throw new Stop();return settings.get(index); + }); + var world=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},(proxy,method,values)->switch(method.getName()) { + case "getMinY"->-64;case "getHeight"->384;case "getSeaLevel"->63; + case "getBiome"->{var p=(BlockPos)values[0];out.println("biome "+p.getX()+" "+p.getY()+" "+p.getZ());if(queries[0]++==queryFail)throw new Stop();int index=Math.floorMod(p.getX()*31+p.getY()*7+p.getZ()*17,2);out.println("selected "+index);yield biomes.get(index);} + default->throw new AssertionError(method); + }); + var p=f.getAsJsonArray("origin");var origin=new BlockPos(p.get(0).getAsInt(),p.get(1).getAsInt(),p.get(2).getAsInt()); + boolean top=f.get("top").getAsBoolean(),direct=f.get("direct").getAsBoolean(); + var context=new PlacementContext(world,generator,top?Optional.of(root):Optional.empty());var placer=new FeaturePlacer(world,generator); + for(int repeat=0;repeat<3;repeat++) { + queries[0]=0;calls[0]=0; + try { + if(direct){final RandomSource rng=random;modifiers.get(0).modify(context,random,origin,q->leaf.place(world,generator,rng,q));out.println("place true");} + else out.println("place "+(top?placer.placeWithBiomeCheck(root,random,origin):placer.place(root,random,origin))); + } catch(Stop|IllegalStateException|IndexOutOfBoundsException error){out.println("place error");} + out.println("next "+random.nextLong()); + } + out.println("tail "+random.nextLong()); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceCodecOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceCodecOracle.java new file mode 100644 index 000000000..8e79ae905 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceCodecOracle.java @@ -0,0 +1,47 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.core.registries.*; +import net.minecraft.resources.*; +import net.minecraft.world.level.biome.*; +import net.minecraft.world.level.levelgen.densityfunction.*; + +/** Original transport using BiomeSource.CODEC and decoded vanilla resolvers. */ +public final class VanillaBiomeSourceCodecOracle { + private static JsonElement normalized(JsonElement value) { + if(value.isJsonArray()){var a=new JsonArray();for(var v:value.getAsJsonArray())a.add(normalized(v));return a;} + if(value.isJsonObject()){var a=new JsonObject();for(var key:new TreeSet<>(value.getAsJsonObject().keySet()))a.add(key,normalized(value.getAsJsonObject().get(key)));return a;} + if(value.isJsonPrimitive()&&value.getAsJsonPrimitive().isNumber()){var a=new JsonObject();a.addProperty("float64_bits",String.format("%016x",Double.doubleToRawLongBits(Double.parseDouble(value.toString()))));return a;} + return value; + } + @SuppressWarnings("unchecked") + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); + var load=VanillaMaterialConditionOracle.class.getDeclaredMethod("loadBiomes",Path.class);load.setAccessible(true);load.invoke(null,dir); + var field=VanillaMaterialConditionOracle.class.getDeclaredField("biomes");field.setAccessible(true);var biomes=(MappedRegistry)field.get(null); + var presets=new MappedRegistry(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST,Lifecycle.stable()); + for(var preset:List.of(MultiNoiseBiomeSourceParameterList.Preset.OVERWORLD,MultiNoiseBiomeSourceParameterList.Preset.NETHER))presets.register(ResourceKey.create(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST,preset.id()),new MultiNoiseBiomeSourceParameterList(preset,biomes),RegistrationInfo.BUILT_IN);presets.freeze(); + var ops=RegistryOps.create(JsonOps.INSTANCE,new RegistryOps.RegistryInfoLookup(){public Optional> lookup(ResourceKey> key){ + if(key.equals(Registries.BIOME))return (Optional>)(Optional)Optional.of(biomes); + if(key.equals(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST))return (Optional>)(Optional)Optional.of(presets);return Optional.empty();}}); + var positions=JsonParser.parseString(Files.readString(dir.resolve("positions.json"))).getAsJsonArray(); + var zero=new DensitySampler(){public float sampleValue(SamplerContext c,int x,int y,int z){return 0;}public void sampleVolume(SamplerContext c,DensityBuffer b,DensityVolume v){b.fill(0);}}.bind(SamplerContext.builder().enableCaches().build()); + var climate=new Climate.Sampler(zero,zero,zero,zero,zero,zero); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var json:Files.readAllLines(dir.resolve("inputs.txt"))) { + Optional decoded; + try { decoded=BiomeSource.CODEC.parse(ops,JsonParser.parseString(json)).result(); }catch(IllegalArgumentException|IllegalStateException error){decoded=Optional.empty();} + if(decoded.isEmpty()){out.println("codec error");continue;} + var source=decoded.get();out.println("codec "+normalized(BiomeSource.CODEC.encodeStart(ops,source).getOrThrow())); + var names=new TreeSet();for(var biome:source.possibleBiomes())names.add(biome.unwrapKey().orElseThrow().identifier().toString());out.println("possible "+new Gson().toJson(names)); + var resolver=source.createResolver(climate); + for(var p:positions){var q=p.getAsJsonArray();try{out.println("biome "+resolver.getNoiseBiome(q.get(0).getAsInt(),q.get(1).getAsInt(),q.get(2).getAsInt()).unwrapKey().orElseThrow().identifier());}catch(ArithmeticException|IllegalStateException error){out.println("biome error");}} + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceOracle.java new file mode 100644 index 000000000..0432f22bb --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceOracle.java @@ -0,0 +1,39 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.core.registries.*; +import net.minecraft.resources.*; +import net.minecraft.world.level.biome.*; +import net.minecraft.world.level.levelgen.densityfunction.*; + +/** Original transport calling actual fixed/checkerboard/End biome resolvers. */ +public final class VanillaBiomeSourceOracle { + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + var ids=new IdMapper>();for(int i=0;i<512;i++)ids.add(Holder.Reference.createStandAlone(new HolderOwner(){},ResourceKey.create(Registries.BIOME,Identifier.parse("horizon:biome_"+i)))); + var constructor=TheEndBiomeSource.class.getDeclaredConstructor(Holder.class,Holder.class,Holder.class,Holder.class,Holder.class);constructor.setAccessible(true); + var end=constructor.newInstance(ids.byId(0),ids.byId(1),ids.byId(2),ids.byId(3),ids.byId(4)); + Path dir=Path.of(args[1]);try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();BiomeResolver resolver; + switch(f.get("kind").getAsString()) { + case "fixed" -> resolver=new FixedBiomeSource(ids.byId(7)).createResolver(null); + case "checkerboard" -> {var values=new ArrayList>();for(var v:f.getAsJsonArray("biomes"))values.add(ids.byId(v.getAsInt()));resolver=new CheckerboardColumnBiomeSource(HolderSet.direct(values),f.get("scale").getAsInt()).createResolver(null);} + case "end" -> { + var sampler=new DensitySampler(){ + public float sampleValue(SamplerContext context,int x,int y,int z){out.println("sample "+x+" "+y+" "+z);if(f.get("fail").getAsBoolean())throw new IllegalStateException("synthetic sampler failure");return Float.intBitsToFloat(Integer.parseUnsignedInt(f.get("bits").getAsString(),16));} + public void sampleVolume(SamplerContext context,DensityBuffer buffer,DensityVolume volume){throw new AssertionError("unexpected bulk query");} + }.bind(SamplerContext.builder().enableCaches().build()); + resolver=end.createResolver(new Climate.Sampler(sampler,sampler,sampler,sampler,sampler,sampler)); + } + default -> throw new IllegalArgumentException("invalid source"); + } + for(var p:f.getAsJsonArray("positions")){var q=p.getAsJsonArray();try{out.println("biome "+ids.getId(resolver.getNoiseBiome(q.get(0).getAsInt(),q.get(1).getAsInt(),q.get(2).getAsInt())));}catch(ArithmeticException|IllegalStateException error){out.println("error");}} + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java new file mode 100644 index 000000000..bfe972b19 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java @@ -0,0 +1,69 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.concurrent.atomic.AtomicReference; +import it.unimi.dsi.fastutil.longs.Long2FloatLinkedOpenHashMap; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.biome.Biome; + +/** Original transport for native biome temperature methods and cache contents. */ +public final class VanillaBiomeTemperatureOracle { + private static Method adjusted,temperature; + private static Field cache; + private static Object climate(JsonObject f) throws Exception { + var type=Class.forName("net.minecraft.world.level.biome.Biome$ClimateSettings"); + if(f.has("json")) { + var field=type.getDeclaredField("CODEC");field.setAccessible(true); + var codec=(MapCodec)field.get(null); + return codec.codec().parse(JsonOps.INSTANCE,JsonParser.parseString(f.get("json").getAsString())).result().orElse(null); + } + var constructor=type.getDeclaredConstructor(boolean.class,float.class,Biome.TemperatureModifier.class,float.class);constructor.setAccessible(true); + return constructor.newInstance(f.get("precipitation").getAsBoolean(),Float.intBitsToFloat(Integer.parseUnsignedInt(f.get("base").getAsString(),16)),Biome.TemperatureModifier.valueOf(f.get("modifier").getAsString()),f.has("downfall")?Float.intBitsToFloat(Integer.parseUnsignedInt(f.get("downfall").getAsString(),16)):0f); + } + private static Object field(Object value,String name) throws Exception { + var method=value.getClass().getDeclaredMethod(name);method.setAccessible(true);return method.invoke(value); + } + private static Biome make(Object climate) throws Exception { + var biome=Biome.class.getDeclaredConstructors()[0];biome.setAccessible(true);return (Biome)biome.newInstance(climate,null,null,null); + } + private static String bits(float value){return Integer.toUnsignedString(Float.floatToIntBits(value),16);} + private static void operations(Biome biome,JsonArray operations,PrintWriter out) throws Exception { + for(var item:operations) { + var op=item.getAsJsonArray();switch(op.get(0).getAsString()) { + case "query"->{ + var pos=new BlockPos(op.get(1).getAsInt(),op.get(2).getAsInt(),op.get(3).getAsInt());int sea=op.get(4).getAsInt(); + out.println("adjusted "+bits((Float)adjusted.invoke(biome,pos,sea))); + out.println("cached "+bits((Float)temperature.invoke(biome,pos,sea))); + out.println("weather "+biome.warmEnoughToRain(pos,sea)+" "+biome.coldEnoughToSnow(pos,sea)+" "+biome.shouldMeltFrozenOceanIcebergSlightly(pos,sea)+" "+biome.getPrecipitationAt(pos,sea)); + } + case "fill"->{for(int i=0;i{var map=(Long2FloatLinkedOpenHashMap)((ThreadLocal)cache.get(biome)).get();out.println("cache "+map.size());for(var entry:map.long2FloatEntrySet())out.println(Long.toUnsignedString(entry.getLongKey(),16)+" "+bits(entry.getFloatValue()));} + case "thread"->{ + var failure=new AtomicReference(); + var thread=new Thread(()->{try{operations(biome,op.get(1).getAsJsonArray(),out);}catch(Throwable error){failure.set(error);}}); + thread.start();thread.join();if(failure.get()!=null)throw new AssertionError("temperature worker failed",failure.get()); + } + default->throw new AssertionError("unknown operation "+op); + } + } + } + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + adjusted=Biome.class.getDeclaredMethod("getHeightAdjustedTemperature",BlockPos.class,int.class);adjusted.setAccessible(true); + temperature=Biome.class.getDeclaredMethod("getTemperature",BlockPos.class,int.class);temperature.setAccessible(true); + cache=Biome.class.getDeclaredField("temperatureCache");cache.setAccessible(true); + Path dir=Path.of(args[1]); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(String line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();var climate=climate(f); + if(climate==null){out.println("decode error");continue;} + out.println("settings "+field(climate,"hasPrecipitation")+" "+bits((Float)field(climate,"temperature"))+" "+field(climate,"temperatureModifier")+" "+bits((Float)field(climate,"downfall"))); + operations(make(climate),f.getAsJsonArray("ops"),out); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeZoomOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeZoomOracle.java new file mode 100644 index 000000000..e130df20f --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeZoomOracle.java @@ -0,0 +1,36 @@ +package dev.horizonlab.parity; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.biome.BiomeManager; + +/** Original transport; actual biome manager selects coordinates for a traced resolver. */ +public final class VanillaBiomeZoomOracle { + public static void main(String[] args) throws Exception { + Path dir=Path.of(args[1]); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(String line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var v=line.split(" "); + switch(v[0]) { + case "s" -> out.println("s "+BiomeManager.obfuscateSeed(Long.parseLong(v[1]))); + case "b" -> { + out.print("b"); + var manager=new BiomeManager((x,y,z)->{out.print(" "+x+" "+y+" "+z);return null;},Long.parseLong(v[1])); + var pos=new BlockPos(Integer.parseInt(v[2]),Integer.parseInt(v[3]),Integer.parseInt(v[4])); + manager.getBiome(pos);manager.getNoiseBiomeAtPosition(pos); + manager.withDifferentSource((x,y,z)->{out.print(" "+x+" "+y+" "+z);return null;}).getBiome(pos.getX(),pos.getY(),pos.getZ()); + out.println(); + } + case "p" -> { + out.print("p"); + var manager=new BiomeManager((x,y,z)->{out.print(" "+x+" "+y+" "+z);return null;},0); + manager.getNoiseBiomeAtPosition(Double.longBitsToDouble(Long.parseUnsignedLong(v[1],16)),Double.longBitsToDouble(Long.parseUnsignedLong(v[2],16)),Double.longBitsToDouble(Long.parseUnsignedLong(v[3],16))); + out.println(); + } + default -> throw new IllegalArgumentException("unknown fixture operation"); + } + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPropertiesOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPropertiesOracle.java new file mode 100644 index 000000000..7367beefd --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPropertiesOracle.java @@ -0,0 +1,56 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.state.*; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.shapes.*; +/** Imports definition inputs only; vanilla computes the independently compared solidity results. */ +public final class VanillaBlockPropertiesOracle { + private static Field field(Class cls,String name) throws Exception {var f=cls.getDeclaredField(name);f.setAccessible(true);return f;} + private static VoxelShape shape(JsonElement value) { + var a=value.getAsJsonArray();double[] v=new double[6];for(int i=0;i<6;i++)v[i]=Double.longBitsToDouble(Long.parseUnsignedLong(a.get(i).getAsString(),16)); + return Shapes.create(new AABB(v[0],v[1],v[2],v[3],v[4],v[5])); + } + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + var properties=field(BlockBehaviour.class,"properties");var on=field(BlockBehaviour.Properties.class,"forceSolidOn");var off=field(BlockBehaviour.Properties.class,"forceSolidOff");var replace=field(BlockBehaviour.Properties.class,"replaceable");var liquid=field(BlockBehaviour.Properties.class,"liquid");var occlude=field(BlockBehaviour.Properties.class,"canOcclude"); + var cache=field(BlockBehaviour.BlockStateBase.class,"cache");var collision=field(cache.getType(),"collisionShape"); + var calculate=BlockBehaviour.BlockStateBase.class.getDeclaredMethod("calculateSolid");calculate.setAccessible(true); + Path dir=Path.of(args[1]); + if(args[0].equals("export")) { + VanillaCollisionOracle.main(new String[]{"generate",args[1]}); + var states=new ListTag();var blocks=new CompoundTag(); + for(var state:Block.BLOCK_STATE_REGISTRY)states.add(BlockState.FULL_CODEC.encodeStart(NbtOps.INSTANCE,state).getOrThrow()); + for(var block:BuiltInRegistries.BLOCK) { + var p=properties.get(block);blocks.putByte(BuiltInRegistries.BLOCK.getKey(block).toString(),(byte)((on.getBoolean(p)?1:0)|(off.getBoolean(p)?2:0)|(replace.getBoolean(p)?4:0)|(liquid.getBoolean(p)?8:0)|(occlude.getBoolean(p)?16:0))); + } + var root=new CompoundTag();root.putInt("DataVersion",net.minecraft.SharedConstants.getCurrentVersion().dataVersion().version());root.put("states",states);root.put("blocks",blocks);root.put("occlusion",VanillaCollisionOracle.occlusionDefinitions()); + try(var out=new DataOutputStream(Files.newOutputStream(dir.resolve("block-properties.nbt")))){NbtIo.write(root,out);}return; + } + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt")))) { + for(var state:Block.BLOCK_STATE_REGISTRY) { + var p=properties.get(state.getBlock()); + out.printf("state %d %s %s %s %s%n",Block.getId(state),on.getBoolean(p),off.getBoolean(p),state.canBeReplaced(),state.isSolid()); + out.printf("render %s %s %s%n",state.liquid(),state.canOcclude(),state.isSolidRender()); + var c=cache.get(state);var s=c==null?null:(VoxelShape)collision.get(c); + if(s==null)out.println("cache none");else if(s.isEmpty())out.println("cache empty");else { + var b=s.bounds();out.printf("cache %016x %016x %016x %016x %016x %016x%n",Double.doubleToRawLongBits(b.minX),Double.doubleToRawLongBits(b.minY),Double.doubleToRawLongBits(b.minZ),Double.doubleToRawLongBits(b.maxX),Double.doubleToRawLongBits(b.maxY),Double.doubleToRawLongBits(b.maxZ)); + } + } + var state=Blocks.STONE.defaultBlockState();var p=properties.get(Blocks.STONE);var savedCache=cache.get(state);var savedShape=collision.get(savedCache);boolean savedOn=on.getBoolean(p),savedOff=off.getBoolean(p); + try(var inputs=Files.lines(dir.resolve("inputs.txt"))) { + for(var line:(Iterable)inputs::iterator) { + var f=JsonParser.parseString(line).getAsJsonObject();VoxelShape s=Shapes.empty();for(var value:f.getAsJsonArray("shape"))s=Shapes.or(s,shape(value)); + on.setBoolean(p,f.get("on").getAsBoolean());off.setBoolean(p,f.get("off").getAsBoolean());cache.set(state,f.get("cached").getAsBoolean()?savedCache:null);collision.set(savedCache,s); + out.println("solid "+calculate.invoke(state)); + out.println("render "+Block.isShapeFullBlock(f.get("occludes").getAsBoolean()?s:Shapes.empty())); + } + } finally {cache.set(state,savedCache);collision.set(savedCache,savedShape);on.setBoolean(p,savedOn);off.setBoolean(p,savedOff);} + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java new file mode 100644 index 000000000..12de99201 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java @@ -0,0 +1,46 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.IntegerProperty; + +/** Original transport for actual compact/full block-state codecs. */ +public final class VanillaBlockStateCodecOracle { + private static JsonElement canonical(JsonElement value) { + if(value.isJsonObject()){var result=new JsonObject();for(var e:new TreeMap<>(value.getAsJsonObject().asMap()).entrySet())result.add(e.getKey(),canonical(e.getValue()));return result;} + if(value.isJsonArray()){var result=new JsonArray();for(var e:value.getAsJsonArray())result.add(canonical(e));return result;} + return value; + } + private static String encode(BlockState state,boolean full){return canonical((full?BlockState.FULL_CODEC:BlockState.CODEC).encodeStart(JsonOps.INSTANCE,state).getOrThrow()).toString();} + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + Path dir=Path.of(args[1]); + if(args[0].equals("export")) { + var result=new JsonObject();var states=new JsonArray();var defaults=new JsonObject();var integers=new JsonArray(); + for(var state:Block.BLOCK_STATE_REGISTRY) { + if(Block.getId(state)!=states.size())throw new AssertionError("registry IDs not dense"); + states.add(BlockState.FULL_CODEC.encodeStart(JsonOps.INSTANCE,state).getOrThrow()); + } + for(var id:new TreeSet<>(BuiltInRegistries.BLOCK.keySet())) { + var block=BuiltInRegistries.BLOCK.getValue(id);defaults.addProperty(id.toString(),Block.getId(block.defaultBlockState())); + for(var p:block.getStateDefinition().getProperties())if(p instanceof IntegerProperty){var entry=new JsonArray();entry.add(id.toString());entry.add(p.getName());integers.add(entry);} + } + result.add("states",states);result.add("defaults",defaults);result.add("integers",integers); + Files.writeString(dir,result.toString(),StandardCharsets.UTF_8);return; + } + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var state:Block.BLOCK_STATE_REGISTRY)out.println("state "+Block.getId(state)+" "+encode(state,false)+" "+encode(state,true)); + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var input=JsonParser.parseString(line).getAsJsonArray();boolean full=input.get(0).getAsBoolean(); + var value=(full?BlockState.FULL_CODEC:BlockState.CODEC).parse(JsonOps.INSTANCE,JsonParser.parseString(input.get(1).getAsString())).result(); + if(value.isEmpty())out.println("decode error");else {var state=value.get();out.println("decode "+Block.getId(state)+" "+encode(state,false)+" "+encode(state,true));} + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSupportOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSupportOracle.java new file mode 100644 index 000000000..ce3b327e6 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSupportOracle.java @@ -0,0 +1,37 @@ +package dev.horizonlab.parity; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.nbt.*; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.state.*; +import net.minecraft.world.phys.shapes.*; +/** Private support-shape data export; native cache answers are the independent reference. */ +public final class VanillaBlockSupportOracle { + public static void main(String[] args)throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + var cache=BlockBehaviour.BlockStateBase.class.getDeclaredField("cache");cache.setAccessible(true);Path dir=Path.of(args[1]); + if(args[0].equals("export")) { + VanillaCollisionOracle.main(new String[]{"generate",args[1]}); + var grid=VanillaCollisionOracle.class.getDeclaredMethod("grid",VoxelShape.class);grid.setAccessible(true); + var states=new ListTag();var shapes=new ListTag();var ids=new IdentityHashMap();int[] mapping=new int[Block.BLOCK_STATE_REGISTRY.size()]; + for(var state:Block.BLOCK_STATE_REGISTRY){int id=Block.getId(state);states.add(BlockState.FULL_CODEC.encodeStart(NbtOps.INSTANCE,state).getOrThrow());if(cache.get(state)==null){mapping[id]=-1;continue;} + var shape=state.getBlockSupportShape(EmptyBlockGetter.INSTANCE,BlockPos.ZERO);Integer shapeId=ids.get(shape);if(shapeId==null){shapeId=shapes.size();ids.put(shape,shapeId);shapes.add((CompoundTag)grid.invoke(null,shape));}mapping[id]=shapeId; + } + var cachedIds=new com.google.gson.JsonArray();for(int i=0;i=0)cachedIds.add(i);Files.writeString(dir.resolve("support-cached-states.json"),cachedIds.toString()); + var root=new CompoundTag();root.putInt("DataVersion",net.minecraft.SharedConstants.getCurrentVersion().dataVersion().version());root.putString("Kind","block_support");root.put("states",states);root.put("shapes",shapes);root.putIntArray("cached_shapes",mapping); + try(var out=new DataOutputStream(Files.newOutputStream(dir.resolve("cached-support.nbt")))){NbtIo.write(root,out);}return; + } + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt")))) { + for(var state:Block.BLOCK_STATE_REGISTRY){int id=Block.getId(state);if(cache.get(state)==null){out.println("state "+id+" uncached");continue;} + out.println("state "+id+" cached"); + for(var direction:Direction.values()) { + out.print("support "+direction.ordinal());for(var type:SupportType.values())out.print(" "+state.isFaceSturdy(EmptyBlockGetter.INSTANCE,BlockPos.ZERO,direction,type));out.println(" "+state.isFaceSturdy(EmptyBlockGetter.INSTANCE,BlockPos.ZERO,direction)); + } + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSurvivalOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSurvivalOracle.java new file mode 100644 index 000000000..efd3cd0e4 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSurvivalOracle.java @@ -0,0 +1,91 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import net.minecraft.core.*; +import net.minecraft.resources.*; +import net.minecraft.tags.*; +import net.minecraft.world.level.material.Fluid; +import com.mojang.serialization.JsonOps; +import java.util.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; +import net.minecraft.world.level.block.state.*; +/** Native survival calls over changing neighbor states and independent query failures. */ +public final class VanillaBlockSurvivalOracle { + private static final class Stop extends RuntimeException {} + private static Class declaring(Class type,String name,Class... parameters) { + while(type!=null){try{type.getDeclaredMethod(name,parameters);return type;}catch(NoSuchMethodException e){type=type.getSuperclass();}} + return null; + } + private static void bindFluidTags(JsonObject resources) { + var registry=BuiltInRegistries.FLUID; + var loader=new TagLoader>((id,required)->registry.get(id).map(value->(Holder)value),"tags/fluid"); + var definitions=new HashMap>(); + for(var item:resources.entrySet()) { + var file=TagFile.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(item.getValue().getAsString())).getOrThrow(); + var entries=new ArrayList(); + for(var entry:file.entries())entries.add(new TagLoader.EntryWithSource(entry,"vanilla")); + definitions.put(Identifier.parse(item.getKey()),entries); + } + var tags=new HashMap,List>>(); + loader.build(definitions).forEach((id,values)->tags.put(TagKey.create(Registries.FLUID,id),List.copyOf(values))); + if(tags.size()!=resources.size())throw new AssertionError("incomplete fluid tags"); + registry.prepareTagReload(new TagLoader.LoadResult<>(Registries.FLUID,tags)).apply(); + } + public static void main(String[] args)throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); + if(args[0].equals("export")||args[0].equals("definitions")) { + if(args[0].equals("export")) { + VanillaBlockPropertiesOracle.main(new String[]{"export",args[1]});VanillaBlockSupportOracle.main(new String[]{"export",args[1]});VanillaBlockStateCodecOracle.main(new String[]{"export",dir.resolve("facts.json").toString()}); + } + var extra=new JsonObject();var fenceGates=new JsonArray();var ignition=new JsonObject(); + for(var block:BuiltInRegistries.BLOCK)if(block instanceof FenceGateBlock)fenceGates.add(BuiltInRegistries.BLOCK.getKey(block).toString()); + var ignitionField=FireBlock.class.getDeclaredField("igniteOdds");ignitionField.setAccessible(true); + var odds=(it.unimi.dsi.fastutil.objects.Object2IntMap)ignitionField.get(Blocks.FIRE); + for(var block:BuiltInRegistries.BLOCK)ignition.addProperty(BuiltInRegistries.BLOCK.getKey(block).toString(),odds.getInt(block)); + extra.add("fence_gates",fenceGates);extra.add("ignition_odds",ignition);Files.writeString(dir.resolve("survival-extra-definitions.json"),extra.toString()); + var definitions=new JsonObject();var placement=new JsonObject();var supportTags=new JsonObject(); + for(var block:BuiltInRegistries.BLOCK){ + String name=BuiltInRegistries.BLOCK.getKey(block).toString(); + Class type=declaring(block.getClass(),"canSurvive",BlockState.class,LevelReader.class,BlockPos.class); + definitions.addProperty(name,type.getSimpleName()); + type=declaring(block.getClass(),"mayPlaceOn",BlockState.class,BlockGetter.class,BlockPos.class); + if(type!=null)placement.addProperty(name,type.getSimpleName()); + var fields=new JsonObject(); + for(Class c=block.getClass();c!=null;c=c.getSuperclass())for(var field:c.getDeclaredFields())if(field.getType().equals(net.minecraft.tags.TagKey.class)&&!Modifier.isStatic(field.getModifiers())) { + field.setAccessible(true);var tag=(net.minecraft.tags.TagKey)field.get(block);if(tag!=null)fields.addProperty(field.getName(),tag.location().toString()); + } + if(fields.size()>0)supportTags.add(name,fields); + } + Files.writeString(dir.resolve("survival-classes.json"),definitions.toString()); + Files.writeString(dir.resolve("survival-placement-classes.json"),placement.toString()); + Files.writeString(dir.resolve("survival-support-tags.json"),supportTags.toString());return; + } + VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(dir.resolve("tags.json"))).getAsJsonObject()); + bindFluidTags(JsonParser.parseString(Files.readString(dir.resolve("fluid-tags.json"))).getAsJsonObject()); + var allocator=Class.forName("sun.misc.Unsafe");var access=allocator.getDeclaredField("theUnsafe");access.setAccessible(true);var unsafe=access.get(null);var allocate=allocator.getMethod("allocateInstance",Class.class); + var oldProgress=ShulkerBoxBlockEntity.class.getDeclaredField("progressOld");oldProgress.setAccessible(true);var progress=ShulkerBoxBlockEntity.class.getDeclaredField("progress");progress.setAccessible(true); + var animation=ShulkerBoxBlockEntity.class.getDeclaredField("animationStatus");animation.setAccessible(true); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt")));var inputs=Files.lines(dir.resolve("inputs.txt"))) { + for(var line:(Iterable)inputs::iterator){ + var f=JsonParser.parseString(line).getAsJsonObject();var candidate=Block.stateById(f.get("state").getAsInt());var xyz=f.getAsJsonArray("position");var p=new BlockPos(xyz.get(0).getAsInt(),xyz.get(1).getAsInt(),xyz.get(2).getAsInt());var neighbors=f.getAsJsonArray("neighbors");int[] reads={0},entities={0},lights={0},fluids={0}; + Object entity=null;String mode=f.get("entity").getAsString();if(!mode.equals("none")){entity=allocate.invoke(unsafe,ShulkerBoxBlockEntity.class);Object status=null;for(var value:animation.getType().getEnumConstants())if(((Enum)value).name().equals(mode.toUpperCase(java.util.Locale.ROOT)))status=value;if(status==null)throw new AssertionError(mode);animation.set(entity,status);}if(entity!=null && f.has("shulker_progress")){var data=f.getAsJsonArray("shulker_progress");oldProgress.setFloat(entity,Float.intBitsToFloat(Integer.parseUnsignedInt(data.get(0).getAsString(),16)));progress.setFloat(entity,Float.intBitsToFloat(Integer.parseUnsignedInt(data.get(1).getAsString(),16)));}Object selected=entity; + var world=(LevelReader)Proxy.newProxyInstance(LevelReader.class.getClassLoader(),new Class[]{LevelReader.class},(proxy,method,values)->{ + if(method.getName().equals("getFluidState")){var at=(BlockPos)values[0];out.println("fluid "+at.getX()+" "+at.getY()+" "+at.getZ());int count=fluids[0]++;if(count==(f.has("fluid_fail")?f.get("fluid_fail").getAsInt():-1))throw new Stop();var states=f.has("fluid_states")?f.getAsJsonArray("fluid_states"):neighbors;return Block.stateById(states.get(count%states.size()).getAsInt()).getFluidState();} + if(method.getName().equals("getRawBrightness")){var at=(BlockPos)values[0];out.println("light "+at.getX()+" "+at.getY()+" "+at.getZ()+" "+values[1]);if(lights[0]++==(f.has("light_fail")?f.get("light_fail").getAsInt():-1))throw new Stop();return f.has("brightness")?f.get("brightness").getAsInt():15;} + if(method.getName().equals("getBlockState")){var at=(BlockPos)values[0];out.println("read "+at.getX()+" "+at.getY()+" "+at.getZ());int count=reads[0]++;if(count==f.get("fail").getAsInt())throw new Stop();return Block.stateById(neighbors.get(count%neighbors.size()).getAsInt());} + if(method.getName().equals("getBlockEntity")){var at=(BlockPos)values[0];out.println("entity "+at.getX()+" "+at.getY()+" "+at.getZ());if(entities[0]++==f.get("entity_fail").getAsInt())throw new Stop();return selected;} + if(method.isDefault())return InvocationHandler.invokeDefault(proxy,method,values); + throw new AssertionError(method); + }); + try{out.println("survive "+candidate.canSurvive(world,p));}catch(Stop error){out.println("survive error");} + out.println("counts "+reads[0]+" "+entities[0]+" "+lights[0]+" "+fluids[0]); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBulkSectionOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBulkSectionOracle.java new file mode 100644 index 000000000..160207065 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBulkSectionOracle.java @@ -0,0 +1,88 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.*; +import net.minecraft.world.level.chunk.status.ChunkStatus; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.feature.Feature; +import net.minecraft.world.level.levelgen.placement.*; + +/** Native feature placement into resident ProtoChunks through a world transport. */ +public final class VanillaBulkSectionOracle { + private static ProtoChunk chunk(Map chunks,int x,int z) { + var chunk=chunks.get(new ChunkPos(x>>4,z>>4));if(chunk==null)throw new IllegalArgumentException("missing region chunk");return chunk; + } + private static int count(BulkSectionAccess bulk) throws Exception { + var field=BulkSectionAccess.class.getDeclaredField("acquiredSections");field.setAccessible(true);return ((Map)field.get(bulk)).size(); + } + public static void main(String[] args) throws Exception { + if(args[0].equals("export")){VanillaHeightmapOracle.main(args);return;} + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + Path dir=Path.of(args[1]); + Holder biome=Holder.Reference.createStandAlone(new HolderOwner(){},Biomes.PLAINS); + var ids=new IdMapper>();ids.add(biome); + var factory=new PalettedContainerFactory(Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY),Blocks.AIR.defaultBlockState(),null,Strategy.createForBiomes(ids),biome,null); + VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(dir.resolve("tags.json"))).getAsJsonObject()); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();int minimum=f.get("min").getAsInt(),height=f.get("height").getAsInt(); + var chunks=new TreeMap(Comparator.comparingInt(p->p.x()).thenComparingInt(p->p.z())); + for(var value:f.getAsJsonArray("chunks")) { + var p=value.getAsJsonArray();var cp=new ChunkPos(p.get(0).getAsInt(),p.get(1).getAsInt()); + var chunk=new ProtoChunk(cp,UpgradeData.EMPTY,LevelHeightAccessor.create(minimum,height),factory,null); + chunk.setPersistedStatus(ChunkStatus.TERRAIN); + if(f.get("prime").getAsBoolean())Heightmap.primeHeightmaps(chunk,EnumSet.allOf(Heightmap.Types.class)); + chunks.put(cp,chunk); + } + var world=(LevelAccessor)Proxy.newProxyInstance(LevelAccessor.class.getClassLoader(),new Class[]{LevelAccessor.class},(proxy,method,values)->switch(method.getName()) { + case "getMinY"->minimum; + case "getHeight"->height; + case "getChunk"->{var c=chunks.get(new ChunkPos((Integer)values[0],(Integer)values[1]));if(c==null)throw new IllegalArgumentException("missing chunk");yield c;} + default->{if(method.isDefault())yield InvocationHandler.invokeDefault(proxy,method,values);throw new AssertionError(method);} + }); + var bulk=new BulkSectionAccess(world); + try { + for(var value:f.getAsJsonArray("ops")) { + var op=value.getAsJsonArray();String kind=op.get(0).getAsString(); + try { + if(kind.equals("reset")){bulk.close();bulk=new BulkSectionAccess(world);out.println("reset");} + else if(kind.equals("height")) { + int x=op.get(2).getAsInt(),z=op.get(3).getAsInt(); + out.println("height "+(chunk(chunks,x,z).getHeight(Heightmap.Types.valueOf(op.get(1).getAsString()),x&15,z&15)+1)); + } else { + var p=new BlockPos(op.get(1).getAsInt(),op.get(2).getAsInt(),op.get(3).getAsInt()); + switch(kind) { + case "get"->out.println("get "+Block.getId(bulk.getBlockState(p))); + case "world"->out.println("world "+Block.getId(chunk(chunks,p.getX(),p.getZ()).getBlockState(p))); + case "has"->out.println("has "+(bulk.getSection(p)!=null)); + case "set"->{var section=bulk.getSection(p);if(section==null)out.println("set none");else out.println("set "+Block.getId(section.setBlockState(p.getX()&15,p.getY()&15,p.getZ()&15,Block.stateById(op.get(4).getAsInt()),false)));} + default->throw new AssertionError(kind); + } + } + } catch(IllegalArgumentException error){out.println("error");} + out.println("cache "+count(bulk)); + } + } finally {bulk.close();} + for(var entry:chunks.entrySet()) { + var cp=entry.getKey();var chunk=entry.getValue();out.println("chunk "+cp.x()+" "+cp.z()); + for(var kind:Heightmap.Types.values()) { + if(chunk.hasPrimedHeightmap(kind)){out.println("map "+kind.name());for(long word:chunk.getOrCreateHeightmapUnprimed(kind).getRawData())out.println(Long.toUnsignedString(word,16));} + else out.println("missing "+kind.name()); + } + for(int i=0;iout.println("column "+x+" "+z+" "+low+" "+high));out.println("next "+random.nextLong()); + } + } + out.println("tail "+random.nextLong()); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingGeometryOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingGeometryOracle.java new file mode 100644 index 000000000..a7524b27d --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingGeometryOracle.java @@ -0,0 +1,43 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.*; +import net.minecraft.world.level.levelgen.carver.WorldCarver; + +/** Original transport invoking native shared cave/canyon geometry. */ +public final class VanillaCarvingGeometryOracle { + private static double d(JsonElement v){return Double.longBitsToDouble(Long.parseUnsignedLong(v.getAsString(),16));} + private static float f(JsonElement v){return Float.intBitsToFloat(Integer.parseUnsignedInt(v.getAsString(),16));} + private static String bits(double v){return Long.toHexString(Double.doubleToLongBits(v));} + private static final class OutputFailure extends RuntimeException {} + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + Path dir=Path.of(args[1]); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(String line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var input=JsonParser.parseString(line).getAsJsonObject();var cp=input.getAsJsonArray("chunk");var chunk=new ChunkPos(cp.get(0).getAsInt(),cp.get(1).getAsInt()); + var mask=new CarvingMask(input.get("min").getAsInt(),input.get("max").getAsInt()); + for(var value:input.getAsJsonArray("ellipsoids")) { + var e=value.getAsJsonObject();var center=e.getAsJsonArray("center");int[] calls={0}; + var output=new CarverOutput(){public int minY(){return mask.minY();}public int maxY(){return mask.maxY();}public void carve(int x,int y,int z){ + out.println("cell "+x+" "+y+" "+z);int previous=calls[0]++;if(previous==e.get("fail").getAsInt())throw new OutputFailure();mask.carve(x,y,z); + }}; + int mode=e.get("skip").getAsInt();boolean ok=true; + try {WorldCarver.carveEllipsoid(chunk,d(center.get(0)),d(center.get(1)),d(center.get(2)),d(e.get("horizontal")),d(e.get("vertical")),output,(x,y,z,by)->{ + boolean skip=switch(mode){case 0->x*x+y*y+z*z>=1;case 1->y<=-0.7||x*x+y*y+z*z>=1;case 2->Math.floorMod(by,3)==0;default->false;}; + out.println("skip "+bits(x)+" "+bits(y)+" "+bits(z)+" "+by+" "+skip);return skip; + });}catch(OutputFailure error){ok=false;} + out.println("ellipsoid "+(ok?"ok":"error")+" "+calls[0]); + mask.visit((x,z,low,high)->out.println("column "+x+" "+z+" "+low+" "+high)); + } + } + for(String line:Files.readAllLines(dir.resolve("reach.txt"))) { + var q=JsonParser.parseString(line).getAsJsonArray(); + out.println("reach "+WorldCarver.canReach(new ChunkPos(q.get(0).getAsInt(),q.get(1).getAsInt()),d(q.get(2)),d(q.get(3)),q.get(4).getAsInt(),q.get(5).getAsInt(),f(q.get(6)))); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingMaskOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingMaskOracle.java new file mode 100644 index 000000000..483ab1542 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingMaskOracle.java @@ -0,0 +1,51 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import net.minecraft.world.level.chunk.CarvingMask; + +/** Original transport invoking the pinned vanilla carving mask directly. */ +public final class VanillaCarvingMaskOracle { + private static boolean carve(CarvingMask mask,JsonArray q) { + try {mask.carve(q.get(0).getAsInt(),q.get(1).getAsInt(),q.get(2).getAsInt());return true;} + catch(IndexOutOfBoundsException error){return false;} + } + private static final class VisitorFailure extends RuntimeException {} + public static void main(String[] args) throws Exception { + Path dir=Path.of(args[1]); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(String line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();var mask=new CarvingMask(f.get("min").getAsInt(),f.get("max").getAsInt()); + out.println("mask "+mask.minY()+" "+mask.maxY()); + for(var value:f.getAsJsonArray("ops")) { + var op=value.getAsJsonObject(); + switch(op.get("kind").getAsString()) { + case "carve" -> out.println("carve "+(carve(mask,op.getAsJsonArray("pos"))?"ok":"error")); + case "fill" -> { + var b=op.getAsJsonArray("box");int calls=0; + for(int x=b.get(0).getAsInt();x<=b.get(1).getAsInt();x++)for(int z=b.get(4).getAsInt();z<=b.get(5).getAsInt();z++) { + int low=b.get(2).getAsInt(),high=b.get(3).getAsInt(); + for(int dy=0;dy<=(long)high-low;dy++){mask.carve(x,low+dy,z);calls++;} + } + out.println("fill "+calls); + } + case "visit" -> { + int[] calls={0};boolean ok=true; + try {mask.visit((x,z,low,high)->{ + out.println("column "+x+" "+z+" "+low+" "+high);int previous=calls[0]++; + var points=op.getAsJsonObject("add").get(Integer.toString(previous)); + if(points!=null)for(var q:points.getAsJsonArray())out.println("add "+(carve(mask,q.getAsJsonArray())?"ok":"error")); + if(previous==op.get("fail").getAsInt())throw new VisitorFailure(); + });}catch(VisitorFailure error){ok=false;} + out.println("visit "+(ok?"ok":"error")+" "+calls[0]); + } + case "read" -> {mask.visit((x,z,low,high)->out.println("column "+x+" "+z+" "+low+" "+high));out.println("read");} + default -> throw new IllegalArgumentException("unknown operation"); + } + out.println("empty "+mask.isEmpty()); + } + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCaveCarverOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCaveCarverOracle.java new file mode 100644 index 000000000..db49b6aff --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCaveCarverOracle.java @@ -0,0 +1,40 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.*; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.carver.*; + +/** Original transport calling actual decoded cave carvers and tracing mask writes. */ +public final class VanillaCaveCarverOracle { + private static final class OutputFailure extends RuntimeException {} + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); + var contextMethod=VanillaAnchorOracle.class.getDeclaredMethod("context",JsonObject.class);contextMethod.setAccessible(true); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();long seed=f.get("seed").getAsLong(); + var context=(WorldGenerationContext)contextMethod.invoke(null,f); + RandomSource random=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + var decoded=WorldCarver.DIRECT_CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(f.get("definition").getAsString())); + if(decoded.result().isEmpty())out.println("decode error");else { + var carver=decoded.result().get();out.println("decode ok"); + var mask=new CarvingMask(context.getMinGenY()+1,context.getMinGenY()+context.getGenDepth()-8); + var t=f.getAsJsonArray("target");var o=f.getAsJsonArray("origin");var target=new ChunkPos(t.get(0).getAsInt(),t.get(1).getAsInt());var origin=new ChunkPos(o.get(0).getAsInt(),o.get(1).getAsInt()); + for(int repeat=0;repeatout.println("column "+x+" "+z+" "+low+" "+high));out.println("next "+random.nextLong()); + } + } + out.println("tail "+random.nextLong()); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkStageOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkStageOracle.java new file mode 100644 index 000000000..3e6379837 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkStageOracle.java @@ -0,0 +1,56 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.chunk.*; +import net.minecraft.world.level.chunk.status.ChunkStatus; +import net.minecraft.world.level.levelgen.Heightmap; + +/** Actual pre-light ProtoChunk writes and persisted-status transitions. */ +public final class VanillaChunkStageOracle { + private static final Map STAGES=new HashMap<>(); + public static void main(String[] args) throws Exception { + if(args[0].equals("export")){VanillaHeightmapOracle.main(args);return;} + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + STAGES.put("empty",ChunkStatus.EMPTY);STAGES.put("structure_starts",ChunkStatus.STRUCTURE_STARTS);STAGES.put("structure_references",ChunkStatus.STRUCTURE_REFERENCES);STAGES.put("biomes",ChunkStatus.BIOMES);STAGES.put("terrain",ChunkStatus.TERRAIN);STAGES.put("features",ChunkStatus.FEATURES); + Path dir=Path.of(args[1]); + Holder biome=Holder.Reference.createStandAlone(new HolderOwner(){},Biomes.PLAINS); + var ids=new IdMapper>();ids.add(biome); + var factory=new PalettedContainerFactory(Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY),Blocks.AIR.defaultBlockState(),null,Strategy.createForBiomes(ids),biome,null); + VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(dir.resolve("tags.json"))).getAsJsonObject()); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();int min=f.get("min").getAsInt(),height=f.get("height").getAsInt();var cp=f.getAsJsonArray("chunk");int cx=cp.get(0).getAsInt(),cz=cp.get(1).getAsInt(); + var chunk=new ProtoChunk(new ChunkPos(cx,cz),UpgradeData.EMPTY,LevelHeightAccessor.create(min,height),factory,null); + out.println("chunk "+cx+" "+cz+" "+min+" "+height); + for(var value:f.getAsJsonArray("ops")) { + var a=value.getAsJsonArray();String op=a.get(0).getAsString(); + switch(op) { + case "stage"->{String name=a.get(1).getAsString();chunk.setPersistedStatus(STAGES.get(name));out.println("stage "+name);} + case "set"->{var p=new BlockPos(a.get(1).getAsInt(),a.get(2).getAsInt(),a.get(3).getAsInt());out.println("set "+Block.getId(chunk.setBlockState(p,Block.stateById(a.get(4).getAsInt()),3)));} + case "get"->out.println("get "+Block.getId(chunk.getBlockState(new BlockPos(a.get(1).getAsInt(),a.get(2).getAsInt(),a.get(3).getAsInt())))); + case "prime"->{int mask=a.get(1).getAsInt();var kinds=EnumSet.noneOf(Heightmap.Types.class);for(var kind:Heightmap.Types.values())if((mask&(1<{for(var kind:Heightmap.Types.values()) { + if(chunk.hasPrimedHeightmap(kind))out.println("height "+kind.name()+" "+chunk.getOrCreateHeightmapUnprimed(kind).getFirstAvailable(a.get(1).getAsInt()&15,a.get(2).getAsInt()&15)); + else out.println("missing "+kind.name()); + }} + case "dump"->{ + for(var kind:Heightmap.Types.values()) { + if(chunk.hasPrimedHeightmap(kind)){out.println("map "+kind.name());for(long word:chunk.getOrCreateHeightmapUnprimed(kind).getRawData())out.println(Long.toUnsignedString(word,16));} + else out.println("missing "+kind.name()); + } + for(int i=0;ithrow new AssertionError(op); + } + } + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java new file mode 100644 index 000000000..318bb1251 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java @@ -0,0 +1,153 @@ +package dev.horizonlab.parity; + +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.nbt.*; +import net.minecraft.server.Bootstrap; +import net.minecraft.world.level.EmptyBlockGetter; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.*; +import net.minecraft.world.phys.shapes.*; + +/** Exports private runtime data locally and invokes actual vanilla cached-shape queries. */ +public final class VanillaCollisionOracle { + static { SharedConstants.tryDetectVersion(); Bootstrap.bootStrap(); } + private static final Field CACHE, COLLISION, DISCRETE; + private static final Method INDEX; + static { + try { + CACHE = BlockBehaviour.BlockStateBase.class.getDeclaredField("cache"); CACHE.setAccessible(true); + COLLISION = CACHE.getType().getDeclaredField("collisionShape"); COLLISION.setAccessible(true); + DISCRETE = VoxelShape.class.getDeclaredField("shape"); DISCRETE.setAccessible(true); + INDEX = VoxelShape.class.getDeclaredMethod("findIndex", Direction.Axis.class, double.class); INDEX.setAccessible(true); + } catch (ReflectiveOperationException e) { throw new ExceptionInInitializerError(e); } + } + private static VoxelShape cached(BlockState state) throws ReflectiveOperationException { + Object cache = CACHE.get(state); + if (cache == null) return null; + VoxelShape shape = (VoxelShape) COLLISION.get(cache); + if (state.getCollisionShape(EmptyBlockGetter.INSTANCE, BlockPos.ZERO) != shape) throw new AssertionError("cached dispatch differs"); + return shape; + } + private static CompoundTag grid(VoxelShape shape) throws ReflectiveOperationException { + CompoundTag tag = new CompoundTag(); + tag.putByte("cube", (byte)(shape instanceof CubeVoxelShape ? 1 : 0)); + int cubeAxes=0;for(Direction.Axis axis:Direction.Axis.values())if(shape.getCoords(axis) instanceof CubePointRange)cubeAxes|=1<();int[] mapping=new int[Block.BLOCK_STATE_REGISTRY.size()];int index=0; + for(var state:Block.BLOCK_STATE_REGISTRY) { + states.add(BlockState.FULL_CODEC.encodeStart(NbtOps.INSTANCE,state).getOrThrow()); + var shape=(VoxelShape)method.invoke(state.getBlock(),state);Integer id=ids.get(shape); + if(id==null){id=shapes.size();ids.put(shape,id);shapes.add(grid(shape));} + mapping[index++]=id; + } + var data=new CompoundTag();data.putInt("DataVersion",SharedConstants.getCurrentVersion().dataVersion().version());data.put("states",states);data.put("shapes",shapes);data.putIntArray("cached_shapes",mapping);return data; + } + private static void write(CompoundTag tag, Path path) throws IOException { + try (DataOutputStream out = new DataOutputStream(Files.newOutputStream(path))) { NbtIo.write(tag, out); } + } + private static void inputValues(PrintWriter out, double... values) { for (double value : values) out.printf(" %016x", Double.doubleToRawLongBits(value)); } + private static void generate(Path base) throws Exception { + ListTag states = new ListTag(), shapes = new ListTag(); CompoundTag defaults = new CompoundTag(); + Map ids = new IdentityHashMap<>();Set grids=new HashSet<>(); int[] mapping = new int[Block.BLOCK_STATE_REGISTRY.size()]; int cachedCount = 0; + for (BlockState state : Block.BLOCK_STATE_REGISTRY) { + int id = states.size(); + if (Block.BLOCK_STATE_REGISTRY.getId(state) != id) throw new AssertionError("non-dense states"); + Tag encoded = BlockState.FULL_CODEC.encodeStart(NbtOps.INSTANCE, state).getOrThrow(); states.add(encoded); + if (state == state.getBlock().defaultBlockState()) defaults.putInt(((CompoundTag)encoded).getStringOr("id", ""), id); + VoxelShape shape = cached(state); + if (shape == null) mapping[id] = -1; + else { + cachedCount++; CompoundTag data = grid(shape);grids.add(data); Integer shapeId = ids.get(shape); + if (shapeId == null) { shapeId = shapes.size(); ids.put(shape, shapeId); shapes.add(data); } + mapping[id] = shapeId; + } + } + CompoundTag registry = new CompoundTag(); registry.putInt("DataVersion", SharedConstants.getCurrentVersion().dataVersion().version()); registry.put("states", states); registry.put("defaults", defaults); + write(registry, base.resolve("block-registry.nbt")); + CompoundTag collision = new CompoundTag(); collision.putInt("DataVersion", SharedConstants.getCurrentVersion().dataVersion().version()); collision.put("states", states); collision.put("shapes", shapes); collision.putIntArray("cached_shapes", mapping); + write(collision, base.resolve("cached-collision.nbt")); + Random random = new Random(0x484f52495a4f4eL); + try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(base.resolve("inputs.txt")))) { + for (int id = 0; id < mapping.length; id++) { + if (mapping[id] < 0) continue; + for (int scenario = 0; scenario < 6; scenario++) { + BlockPos offset = switch(scenario % 3) { case 0 -> BlockPos.ZERO; case 1 -> new BlockPos(-17,-64,-1); default -> new BlockPos(30_000_000,64,-30_000_000); }; + double[] origin = {offset.getX(),offset.getY(),offset.getZ()}; double[] lower = new double[3], upper = new double[3], start = new double[3], end = new double[3], point = new double[3]; + for (int axis = 0; axis < 3; axis++) { + lower[axis] = origin[axis] + (scenario < 3 ? -.6 + axis * .4 : random.nextDouble() * 4 - 2); + upper[axis] = lower[axis] + (axis == 1 ? 1.8 : .6); + start[axis] = origin[axis] + (scenario < 3 ? (axis == 0 ? -1 : .5) : random.nextDouble() * 3 - 1); + end[axis] = origin[axis] + (scenario < 3 ? (axis == 0 ? 2 : .5) : random.nextDouble() * 3 - 1); + point[axis] = origin[axis] + random.nextDouble() * 3 - 1; + } + out.print(id); out.printf(" %d %d %d",offset.getX(),offset.getY(),offset.getZ()); + inputValues(out, lower); inputValues(out, upper); inputValues(out, start); inputValues(out, end); inputValues(out, point); + inputValues(out, scenario == 4 ? 1e-8 : scenario == 5 ? -1e-7 : random.nextDouble() * 4 - 2); out.println(); + } + } + } + System.out.printf("HORIZON_COLLISION_RESULT {\"registry_states\":%d,\"cached_states\":%d,\"uncached_states\":%d,\"unique_shapes\":%d,\"unique_grids\":%d,\"queries\":%d}%n", mapping.length,cachedCount,mapping.length-cachedCount,shapes.size(),grids.size(),cachedCount*6); + } + private static void values(PrintWriter out, String label, double... values) { out.print(label); for (double value : values) out.printf(" %016x",Double.doubleToLongBits(value)); out.println(); } + private static void box(PrintWriter out, String label, AABB b) { values(out,label,b.minX,b.minY,b.minZ,b.maxX,b.maxY,b.maxZ); } + private static void hit(PrintWriter out, BlockHitResult h) { + if (h == null) out.println("hit none"); else {Vec3 v=h.getLocation(); out.printf("hit %d %d %016x %016x %016x%n",h.getDirection().ordinal(),h.isInside()?1:0,Double.doubleToLongBits(v.x),Double.doubleToLongBits(v.y),Double.doubleToLongBits(v.z));} + } + private static final class Input { + String[] words; int index; + Input(String line) {words=line.split(" ");} + int integer() {return Integer.parseInt(words[index++]);} + double number() {return Double.longBitsToDouble(Long.parseUnsignedLong(words[index++],16));} + Vec3 vector() {return new Vec3(number(),number(),number());} + } + private static void verify(Path base, String side) throws Exception { + try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(base.resolve("vanilla-"+side+".txt")))) { + IdentityHashMap identities=new IdentityHashMap<>(); + for (BlockState state : Block.BLOCK_STATE_REGISTRY) { + VoxelShape shape=cached(state); int id=Block.BLOCK_STATE_REGISTRY.getId(state); + if (shape==null) {out.printf("state %d uncached%n",id); continue;} + List boxes=shape.toAabbs(); out.printf("state %d cached %d%n",id,boxes.size()); + out.printf("identity %d%n",identities.computeIfAbsent(shape,key->identities.size())); + int cubeAxes=0;for(Direction.Axis axis:Direction.Axis.values())if(shape.getCoords(axis) instanceof CubePointRange)cubeAxes|=1< nearest=moved.closestPointTo(point); if(nearest.isEmpty()) out.println("closest none"); else values(out,"closest",nearest.get().x,nearest.get().y,nearest.get().z); + out.printf("index %d %d %d%n",INDEX.invoke(moved,Direction.Axis.X,point.x),INDEX.invoke(moved,Direction.Axis.Y,point.y),INDEX.invoke(moved,Direction.Axis.Z,point.z)); + if(in.index!=in.words.length) throw new AssertionError("trailing input"); + } + } + } + } + public static void main(String[] args) throws Exception { Path base=Path.of(args[1]); if(args[0].equals("generate"))generate(base);else verify(base,args[0]); } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCoreOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCoreOracle.java new file mode 100644 index 000000000..a2e66cee7 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCoreOracle.java @@ -0,0 +1,161 @@ +package dev.horizonlab.parity; + +import java.io.BufferedReader; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.StringTokenizer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.IdMapper; +import net.minecraft.core.SectionPos; +import net.minecraft.util.RandomSource; +import net.minecraft.util.SimpleBitStorage; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.Strategy; +import net.minecraft.world.level.levelgen.LegacyRandomSource; +import net.minecraft.world.level.levelgen.XoroshiroRandomSource; +import net.minecraft.world.level.levelgen.PositionalRandomFactory; +import net.minecraft.world.level.levelgen.RandomSupport; +import net.minecraft.util.Mth; + +/** Original test adapter. Calls downloaded vanilla classes, never reimplements them. */ +public final class VanillaCoreOracle { + private static final int[] BOUNDS = {1, 2, 3, 16, 31, 256, 65537, 1073741825, Integer.MAX_VALUE, 0, -1}; + private static final Strategy BLOCKS = Strategy.createForBlockStates(new IdMapper<>()); + + private static int integer(StringTokenizer args) { return Integer.parseInt(args.nextToken()); } + private static long longValue(StringTokenizer args) { return Long.parseLong(args.nextToken()); } + private static String utf16(String token) { + if(token.equals("-"))return ""; + char[] units=new char[token.length()/4];for(int i=0;i Integer.toString(rng.nextInt()); + case 1 -> Long.toString(rng.nextLong()); + case 2 -> { + try { yield Integer.toString(rng.nextInt(BOUNDS[(i / 10) % BOUNDS.length])); } + catch (IllegalArgumentException e) { yield "error"; } + } + case 3 -> rng.nextBoolean() ? "1" : "0"; + case 4 -> Integer.toUnsignedString(Float.floatToRawIntBits(rng.nextFloat())); + case 5 -> Long.toUnsignedString(Double.doubleToRawLongBits(rng.nextDouble())); + case 6 -> Long.toString(rng.fork().nextLong()); + case 7 -> { + rng.consumeCount(i % 7 - 2); + yield Long.toString(rng.nextLong()); + } + case 8 -> { + if (i % 101 == 8) rng.setSeed(rng.nextLong() - i); + yield Integer.toString(rng.nextInt(1073741825)); + } + default -> throw new AssertionError(); + }; + out.println("rng " + i + " " + value); + } + } + + private static void probe(String line, PrintWriter out) { + StringTokenizer args = new StringTokenizer(line); + switch (args.nextToken()) { + case "helpers" -> { + String kind=args.nextToken();long seed=longValue(args);int min=integer(args),max=integer(args); + double mean=Double.longBitsToDouble(Long.parseUnsignedLong(args.nextToken(),16)),deviation=Double.longBitsToDouble(Long.parseUnsignedLong(args.nextToken(),16)); + float smallMean=Float.intBitsToFloat(Integer.parseUnsignedInt(args.nextToken(),16)),smallDeviation=Float.intBitsToFloat(Integer.parseUnsignedInt(args.nextToken(),16)); + RandomSource source=kind.equals("legacy")?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + for(int i=0;i<32;i++) { + String inclusive,exclusive; + try { inclusive=Integer.toString(source.nextIntBetweenInclusive(min,max)); } catch(IllegalArgumentException e) { inclusive="error"; } + try { exclusive=Integer.toString(source.nextInt(min,max)); } catch(IllegalArgumentException e) { exclusive="error"; } + String d=Long.toUnsignedString(Double.doubleToLongBits(source.triangle(mean,deviation))); + String f=Integer.toUnsignedString(Float.floatToIntBits(source.triangle(smallMean,smallDeviation))); + out.printf("helpers %d %s %s %s %s %d%n",i,inclusive,exclusive,d,f,source.nextLong()); + } + random(out,source,24); + } + case "factory" -> { + String kind=args.nextToken();int mode=integer(args);long lo=longValue(args),hi=longValue(args); + BlockPos position=new BlockPos(integer(args),integer(args),integer(args));long seed=longValue(args);String name=utf16(args.nextToken());int count=integer(args); + RandomSource source=kind.equals("legacy")?new LegacyRandomSource(lo):new XoroshiroRandomSource(lo); + PositionalRandomFactory factory=mode!=0?source.forkPositional():kind.equals("legacy")?new LegacyRandomSource.LegacyPositionalRandomFactory(lo):new XoroshiroRandomSource.XoroshiroPositionalRandomFactory(lo,hi); + var hash=RandomSupport.seedFromHashOf(name);out.printf("seeds %d %d %d %d%n",Mth.getSeed(position),name.hashCode(),hash.seedLo(),hash.seedHi()); + out.println("factory at");random(out,factory.at(position),count);out.println("factory seed");random(out,factory.fromSeed(seed),count);out.println("factory hash");random(out,factory.fromHashOf(name),count); + if(mode!=0)out.println("parent "+source.nextLong()); + } + case "position" -> { + BlockPos p = new BlockPos(integer(args), integer(args), integer(args)); + BlockPos offset = p.offset(integer(args), integer(args), integer(args)); + long packed = p.asLong(); + BlockPos decoded = BlockPos.of(packed); + SectionPos section = SectionPos.of(p); + long sp = section.asLong(); + SectionPos sd = SectionPos.of(sp); + ChunkPos chunk = ChunkPos.containing(p); + long cp = chunk.pack(); + ChunkPos cd = ChunkPos.unpack(cp); + short relative = SectionPos.sectionRelativePos(p); + BlockPos rebuilt = section.relativeToBlockPos(relative); + out.printf("position %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d%n", + packed, decoded.getX(), decoded.getY(), decoded.getZ(), sp, sd.x(), sd.y(), sd.z(), + cp, cd.x(), cd.z(), chunk.getRegionX(), chunk.getRegionZ(), chunk.getRegionLocalX(), chunk.getRegionLocalZ(), + Short.toUnsignedInt(relative), BLOCKS.getIndex(p.getX() & 15, p.getY() & 15, p.getZ() & 15), + rebuilt.getX(), rebuilt.getY(), rebuilt.getZ(), offset.getX(), offset.getY(), offset.getZ()); + } + case "legacy" -> random(out, new LegacyRandomSource(longValue(args)), integer(args)); + case "xoroshiro" -> random(out, new XoroshiroRandomSource(longValue(args)), integer(args)); + case "xoroshiro_state" -> random(out, new XoroshiroRandomSource(longValue(args), longValue(args)), integer(args)); + case "storage" -> { + int bits = integer(args); + int len = integer(args); + long seed = longValue(args); + SimpleBitStorage storage = new SimpleBitStorage(bits, len); + RandomSource rng = new LegacyRandomSource(seed); + long mask = Math.min((1L << bits) - 1, Integer.MAX_VALUE); + for (int i = 0; i < len * 3; i++) { + int index = rng.nextInt(len); + int value = (int) (Integer.toUnsignedLong(rng.nextInt()) & mask); + int old = storage.getAndSet(index, value); + out.println("set " + i + " " + index + " " + Integer.toUnsignedString(old) + " " + Integer.toUnsignedString(storage.get(index))); + } + for (int i = 0; i < storage.getRaw().length; i++) out.println("word " + i + " " + storage.getRaw()[i]); + int[] unpacked = new int[len]; + storage.unpack(unpacked); + for (int i = 0; i < len; i++) out.println("value " + i + " " + unpacked[i]); + long[] words = new long[storage.getRaw().length]; + Arrays.fill(words, -1L); + SimpleBitStorage imported = new SimpleBitStorage(bits, len, words); + for (int i = 0; i < len; i++) out.println("import " + i + " " + imported.get(i)); + if (len > 0) imported.set(len - 1, 0); + for (int i = 0; i < words.length; i++) out.println("import_word " + i + " " + words[i]); + for (int value : new int[]{0, 1, (int) mask}) { + imported.fill(value); + for (int i = 0; i < words.length; i++) out.println("fill " + value + " " + i + " " + words[i]); + } + long[] before = storage.getRaw().clone(); + try { storage.set(len, 0); out.println("invalid_index 0"); } + catch (IllegalArgumentException e) { out.println("invalid_index 1"); } + if (len > 0) { + try { storage.set(0, bits == 32 ? -1 : 1 << bits); out.println("invalid_value 0"); } + catch (IllegalArgumentException e) { out.println("invalid_value 1"); } + } + out.println("unchanged " + (Arrays.equals(before, storage.getRaw()) ? "1" : "0")); + } + default -> throw new IllegalArgumentException("unknown operation"); + } + if (args.hasMoreTokens()) throw new IllegalArgumentException("unexpected trailing argument"); + } + + public static void main(String[] args) throws Exception { + try (BufferedReader input = Files.newBufferedReader(Path.of(args[0]), StandardCharsets.UTF_8); + PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + String line; + while ((line = input.readLine()) != null) probe(line, out); + if (out.checkError()) throw new IllegalStateException("oracle output failed"); + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationOracle.java new file mode 100644 index 000000000..2af6d7627 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationOracle.java @@ -0,0 +1,102 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.function.*; +import net.minecraft.core.*; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.*; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.chunk.*; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.feature.Feature; +import net.minecraft.world.level.levelgen.placement.*; +import net.minecraft.world.level.levelgen.structure.Structure; + +/** Actual chunk decoration, with structures disabled and traced feature sinks. */ +public final class VanillaDecorationOracle { + private static final class Stop extends RuntimeException {} + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + Path dir=Path.of(args[1]); + var contextMethod=VanillaPlacementOracle.class.getDeclaredMethod("context",JsonObject.class);contextMethod.setAccessible(true); + var settingsConstructor=BiomeGenerationSettings.class.getDeclaredConstructor(HolderSet.class,List.class);settingsConstructor.setAccessible(true); + var getter=ChunkGenerator.class.getDeclaredField("generationSettingsGetter");getter.setAccessible(true); + var stepsField=ChunkGenerator.class.getDeclaredField("featuresPerStep");stepsField.setAccessible(true); + var possibleField=BiomeSource.class.getDeclaredField("possibleBiomes");possibleField.setAccessible(true); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();int min=f.get("min").getAsInt(),height=f.get("height").getAsInt(); + int biomeCount=f.getAsJsonArray("biomes").size(),featureCount=f.getAsJsonArray("placements").size(); + var holders=new ArrayList>();var ids=new IdMapper>(); + for(int i=0;i<=biomeCount;i++){var holder=Holder.Reference.createStandAlone(new HolderOwner(){},ResourceKey.create(Registries.BIOME,Identifier.parse("horizon:b"+i)));holders.add(holder);ids.add(holder);} + var bounds=new JsonObject();bounds.add("context",JsonParser.parseString("[-64,384,63]")); + var generator=((PlacementContext)contextMethod.invoke(null,bounds)).generator(); + var placed=new MappedRegistry(Registries.PLACED_FEATURE,Lifecycle.stable()); + var structures=new MappedRegistry(Registries.STRUCTURE,Lifecycle.stable());structures.freeze(); + int[] calls={0},queries={0},notifications={0},chunksRead={0}; + var features=new ArrayList(); + for(int i=0;i codec(){return MapCodec.unit(this);} + public boolean place(WorldGenLevel w,ChunkGenerator g,RandomSource r,BlockPos p){ + out.println("feature "+id+" "+p.getX()+" "+p.getY()+" "+p.getZ()); + out.println("draw "+r.nextLong()+" "+r.nextInt(17)+" "+Integer.toHexString(Float.floatToRawIntBits(r.nextFloat()))+" "+Long.toHexString(Double.doubleToRawLongBits(r.nextDouble()))); + if(calls[0]++==f.get("feature_fail").getAsInt())throw new Stop(); + return f.get("return_mode").getAsInt()==0||(f.get("return_mode").getAsInt()==2&&id%2==0); + } + }; + var modifiers=new ArrayList();for(var value:f.getAsJsonArray("placements").get(i).getAsJsonArray())modifiers.add(PlacementModifier.CODEC.parse(JsonOps.INSTANCE,value).getOrThrow()); + var root=new PlacedFeature(Holder.direct(leaf),modifiers);features.add(root); + placed.register(ResourceKey.create(Registries.PLACED_FEATURE,Identifier.parse("horizon:f"+i)),root,RegistrationInfo.BUILT_IN); + } + placed.freeze(); + var settings=new ArrayList(); + for(var value:f.getAsJsonArray("biomes")) { + var steps=new ArrayList>(); + for(var step:value.getAsJsonArray()){var roots=new ArrayList>();for(var root:step.getAsJsonArray())roots.add(Holder.direct(features.get(root.getAsInt())));steps.add(HolderSet.direct(roots));} + settings.add(settingsConstructor.newInstance(HolderSet.direct(List.of()),steps)); + } + settings.add(settingsConstructor.newInstance(HolderSet.direct(List.of()),List.of())); + Function,BiomeGenerationSettings> settingsGetter=biome->settings.get(ids.getId(biome));getter.set(generator,settingsGetter); + var possible=new LinkedHashSet>(holders.subList(0,biomeCount));possibleField.set(generator.getBiomeSource(),(Supplier>>)(()->possible)); + List sorted; + try {sorted=FeatureSorter.buildFeaturesPerStep(new ArrayList<>(possible),b->settingsGetter.apply(b).features(),true);} + catch(IllegalStateException error){out.println("plan error");continue;} + stepsField.set(generator,(Supplier>)(()->sorted));out.println("plan ok"); + var factory=new PalettedContainerFactory(Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY),Blocks.AIR.defaultBlockState(),null,Strategy.createForBiomes(ids),holders.get(biomeCount),null); + var cp=new ChunkPos(f.get("cx").getAsInt(),f.get("cz").getAsInt());var chunks=new HashMap(); + var palettes=f.getAsJsonArray("palettes");int ordinal=0; + for(int dz=-1;dz<=1;dz++)for(int dx=-1;dx<=1;dx++) { + var pos=new ChunkPos(cp.x()+dx,cp.z()+dz);var chunk=new ProtoChunk(pos,UpgradeData.EMPTY,LevelHeightAccessor.create(min,height),factory,null); + final var values=palettes.get(ordinal++).getAsJsonArray(); + chunk.fillBiomesFromNoise((x,y,z)->holders.get(values.get(Math.floorMod((y-(min>>2))*16+(z&3)*4+(x&3),values.size())).getAsInt()));chunks.put(pos,chunk); + } + var access=new RegistryAccess.ImmutableRegistryAccess(List.of(structures,placed)).freeze(); + var world=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},(proxy,method,values)->switch(method.getName()) { + case "getMinY"->min;case "getHeight"->height;case "getSeaLevel"->63; + case "getMinSectionY"->InvocationHandler.invokeDefault(proxy,method,values); + case "getSeed"->f.get("seed").getAsLong();case "registryAccess"->access; + case "getChunk"->{int x=(Integer)values[0],z=(Integer)values[1];out.println("chunk "+x+" "+z);if(chunksRead[0]++==f.get("chunk_fail").getAsInt())throw new Stop();var chunk=chunks.get(new ChunkPos(x,z));if(chunk==null)throw new AssertionError("missing chunk");yield chunk;} + case "setCurrentlyGenerating"->{String label=values[0]==null?"none":((Supplier)values[0]).get().toString();out.println("generating "+label);if(notifications[0]++==f.get("notify_fail").getAsInt())throw new Stop();yield null;} + case "getBiome"->{var p=(BlockPos)values[0];int id=Math.floorMod(p.getX()*31+p.getY()*7+p.getZ()*17+f.get("biome_offset").getAsInt(),biomeCount+1);out.println("biome "+p.getX()+" "+p.getY()+" "+p.getZ()+" "+id);if(queries[0]++==f.get("query_fail").getAsInt())throw new Stop();yield holders.get(id);} + default->throw new AssertionError(method); + }); + var manager=new StructureManager(world,new WorldOptions(f.get("seed").getAsLong(),false,false),null); + for(int repeat=0;repeat<2;repeat++) { + calls[0]=queries[0]=notifications[0]=chunksRead[0]=0; + try {generator.applyBiomeDecoration(world,chunks.get(cp),manager);out.println("decorate ok");} + catch(Stop|net.minecraft.ReportedException error){out.println("decorate error");} + } + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationRegionOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationRegionOracle.java new file mode 100644 index 000000000..093d6eeed --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationRegionOracle.java @@ -0,0 +1,125 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.function.*; +import net.minecraft.core.*; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.*; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.chunk.*; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.feature.Feature; +import net.minecraft.world.level.levelgen.placement.*; +import net.minecraft.world.level.levelgen.structure.Structure; + +/** Actual chunk decoration, with structures disabled and resident block-writing features. */ +public final class VanillaDecorationRegionOracle { + private static final class Stop extends RuntimeException {} + @SuppressWarnings("unchecked") + public static void main(String[] args) throws Exception { + if(args[0].equals("export")){VanillaHeightmapOracle.main(args);return;} + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + Path dir=Path.of(args[1]); + VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(dir.resolve("tags.json"))).getAsJsonObject()); + var contextMethod=VanillaPlacementOracle.class.getDeclaredMethod("context",JsonObject.class);contextMethod.setAccessible(true); + var settingsConstructor=BiomeGenerationSettings.class.getDeclaredConstructor(HolderSet.class,List.class);settingsConstructor.setAccessible(true); + var getter=ChunkGenerator.class.getDeclaredField("generationSettingsGetter");getter.setAccessible(true); + var stepsField=ChunkGenerator.class.getDeclaredField("featuresPerStep");stepsField.setAccessible(true); + var possibleField=BiomeSource.class.getDeclaredField("possibleBiomes");possibleField.setAccessible(true); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();int min=f.get("min").getAsInt(),height=f.get("height").getAsInt(); + int biomeCount=f.getAsJsonArray("biomes").size(),featureCount=f.getAsJsonArray("placements").size(); + var holders=new ArrayList>();var ids=new IdMapper>(); + for(int i=0;i<=biomeCount;i++){var holder=Holder.Reference.createStandAlone(new HolderOwner(){},ResourceKey.create(Registries.BIOME,Identifier.parse("horizon:b"+i)));holders.add(holder);ids.add(holder);} + var biomeLookup=new HolderGetter() { + public Optional> get(ResourceKey key) { + return holders.stream().filter(h->h.unwrapKey().orElseThrow().equals(key)).map(h->(Holder.Reference)h).findFirst(); + } + public Optional> get(net.minecraft.tags.TagKey key) {return Optional.empty();} + }; + var ops=RegistryOps.create(JsonOps.INSTANCE,new RegistryOps.RegistryInfoLookup(){public Optional> lookup(ResourceKey> key){ + return key.equals(Registries.BIOME)?(Optional>)(Optional)Optional.of(biomeLookup):Optional.empty(); + }}); + var bounds=new JsonObject();bounds.add("context",JsonParser.parseString("[-64,384,63]")); + var generator=((PlacementContext)contextMethod.invoke(null,bounds)).generator(); + var placed=new MappedRegistry(Registries.PLACED_FEATURE,Lifecycle.stable()); + var structures=new MappedRegistry(Registries.STRUCTURE,Lifecycle.stable());structures.freeze(); + int[] calls={0},queries={0},notifications={0},chunksRead={0}; + var features=new ArrayList(); + for(int i=0;i();for(var value:f.getAsJsonArray("placements").get(i).getAsJsonArray())modifiers.add(PlacementModifier.CODEC.parse(ops,value).getOrThrow()); + var root=new PlacedFeature(Holder.direct(leaf),modifiers);features.add(root); + placed.register(ResourceKey.create(Registries.PLACED_FEATURE,Identifier.parse("horizon:f"+i)),root,RegistrationInfo.BUILT_IN); + } + placed.freeze(); + var settings=new ArrayList(); + for(var value:f.getAsJsonArray("biomes")) { + var steps=new ArrayList>(); + for(var step:value.getAsJsonArray()){var roots=new ArrayList>();for(var root:step.getAsJsonArray())roots.add(Holder.direct(features.get(root.getAsInt())));steps.add(HolderSet.direct(roots));} + settings.add(settingsConstructor.newInstance(HolderSet.direct(List.of()),steps)); + } + settings.add(settingsConstructor.newInstance(HolderSet.direct(List.of()),List.of())); + Function,BiomeGenerationSettings> settingsGetter=biome->settings.get(ids.getId(biome));getter.set(generator,settingsGetter); + var possible=new LinkedHashSet>(holders.subList(0,biomeCount));possibleField.set(generator.getBiomeSource(),(Supplier>>)(()->possible)); + List sorted; + try {sorted=FeatureSorter.buildFeaturesPerStep(new ArrayList<>(possible),b->settingsGetter.apply(b).features(),true);} + catch(IllegalStateException error){out.println("plan error");continue;} + stepsField.set(generator,(Supplier>)(()->sorted));out.println("plan ok"); + var factory=new PalettedContainerFactory(Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY),Blocks.AIR.defaultBlockState(),null,Strategy.createForBiomes(ids),holders.get(biomeCount),null); + var cp=new ChunkPos(f.get("cx").getAsInt(),f.get("cz").getAsInt());var chunks=new TreeMap(Comparator.comparingInt(p->p.x()).thenComparingInt(p->p.z())); + var palettes=f.getAsJsonArray("palettes");int ordinal=0; + for(int dz=-1;dz<=1;dz++)for(int dx=-1;dx<=1;dx++) { + var pos=new ChunkPos(cp.x()+dx,cp.z()+dz);var chunk=new ProtoChunk(pos,UpgradeData.EMPTY,LevelHeightAccessor.create(min,height),factory,null); + chunk.setPersistedStatus(switch(f.get("stage").getAsString()){case "terrain"->net.minecraft.world.level.chunk.status.ChunkStatus.TERRAIN;case "biomes"->net.minecraft.world.level.chunk.status.ChunkStatus.BIOMES;default->net.minecraft.world.level.chunk.status.ChunkStatus.EMPTY;}); + for(int x=0;x<16;x++)for(int z=0;z<16;z++) { + chunk.setBlockState(new BlockPos((pos.x()<<4)+x,-56,(pos.z()<<4)+z),Blocks.STONE.defaultBlockState(),3); + if((x+z)%3!=0)chunk.setBlockState(new BlockPos((pos.x()<<4)+x,-48,(pos.z()<<4)+z),Blocks.DIRT.defaultBlockState(),3); + } + final var values=palettes.get(ordinal++).getAsJsonArray(); + chunk.fillBiomesFromNoise((x,y,z)->holders.get(values.get(Math.floorMod((y-(min>>2))*16+(z&3)*4+(x&3),values.size())).getAsInt()));chunks.put(pos,chunk); + } + var zoom=new BiomeManager((x,y,z)->{var chunk=chunks.get(new ChunkPos(x>>2,z>>2));if(chunk==null)throw new Stop();return chunk.getNoiseBiome(x,y,z);},BiomeManager.obfuscateSeed(f.get("seed").getAsLong())); + var access=new RegistryAccess.ImmutableRegistryAccess(List.of(structures,placed)).freeze(); + var world=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},(proxy,method,values)->switch(method.getName()) { + case "getMinY"->min;case "getSeaLevel"->63; + case "getHeight"->{if(values==null||values.length==0)yield height;var kind=(Heightmap.Types)values[0];int x=(Integer)values[1],z=(Integer)values[2];var chunk=chunks.get(new ChunkPos(x>>4,z>>4));if(chunk==null)throw new Stop();yield chunk.getHeight(kind,x&15,z&15)+1;} + case "getMaxY","isInsideBuildHeight","isOutsideBuildHeight","setBlockAndUpdate"->InvocationHandler.invokeDefault(proxy,method,values); + case "getBlockState"->{var p=(BlockPos)values[0];var chunk=chunks.get(new ChunkPos(p.getX()>>4,p.getZ()>>4));if(chunk==null)throw new Stop();yield chunk.getBlockState(p);} + case "setBlock"->{var p=(BlockPos)values[0];var state=(net.minecraft.world.level.block.state.BlockState)values[1];int flags=(Integer)values[2];out.println("write "+p.getX()+" "+p.getY()+" "+p.getZ()+" "+Block.getId(state)+" "+flags);int call=calls[0]++;if(call==f.get("write_fail").getAsInt())throw new Stop();int reject=f.get("reject").getAsInt();boolean result=reject==0||call%reject!=0;if(result){var chunk=chunks.get(new ChunkPos(p.getX()>>4,p.getZ()>>4));if(chunk==null)throw new Stop();chunk.setBlockState(p,state,flags);}out.println("written "+result);yield result;} + case "getMinSectionY"->InvocationHandler.invokeDefault(proxy,method,values); + case "getSeed"->f.get("seed").getAsLong();case "registryAccess"->access; + case "getChunk"->{int x=(Integer)values[0],z=(Integer)values[1];out.println("chunk "+x+" "+z);if(chunksRead[0]++==f.get("chunk_fail").getAsInt())throw new Stop();var chunk=chunks.get(new ChunkPos(x,z));if(chunk==null)throw new AssertionError("missing chunk");yield chunk;} + case "setCurrentlyGenerating"->{String label=values[0]==null?"none":((Supplier)values[0]).get().toString();out.println("generating "+label);if(notifications[0]++==f.get("notify_fail").getAsInt())throw new Stop();yield null;} + case "getBiome"->{var p=(BlockPos)values[0];var biome=zoom.getBiome(p);out.println("biome "+p.getX()+" "+p.getY()+" "+p.getZ()+" "+ids.getId(biome));yield biome;} + default->throw new AssertionError(method); + }); + var manager=new StructureManager(world,new WorldOptions(f.get("seed").getAsLong(),false,false),null); + for(int repeat=0;repeat<2;repeat++) { + calls[0]=queries[0]=notifications[0]=chunksRead[0]=0; + try {generator.applyBiomeDecoration(world,chunks.get(cp),manager);out.println("decorate ok");} + catch(Stop|net.minecraft.ReportedException error){out.println("decorate error");} + for(int[] p:new int[][]{{0,0},{15,15},{16,16},{-1,-1}})for(var kind:Heightmap.Types.values())out.println("height "+kind.name()+" "+p[0]+" "+p[1]+" "+(chunks.get(new ChunkPos(p[0]>>4,p[1]>>4)).getHeight(kind,p[0]&15,p[1]&15)+1)); + } + for(var entry:chunks.entrySet()) { + var pos=entry.getKey();var chunk=entry.getValue();out.println("stored "+pos.x()+" "+pos.z()); + for(var kind:Heightmap.Types.values()) { + if(chunk.hasPrimedHeightmap(kind)){out.println("map "+kind.name());for(long word:chunk.getOrCreateHeightmapUnprimed(kind).getRawData())out.println(Long.toUnsignedString(word,16));} + else out.println("missing "+kind.name()); + } + for(int i=0;i[] types,Object... arguments) throws Exception { + var constructor=Class.forName("net.minecraft.world.level.levelgen.densityfunction.op."+nested).getDeclaredConstructor(types); + constructor.setAccessible(true);return (DensitySampler)constructor.newInstance(arguments); + } + private static void intervalOutput(PrintWriter out,String name,java.util.function.Supplier compute) { + try { var result=compute.get();out.printf("bounds %s %s %s %d %d%n",name,bits(result.min()),bits(result.max()),result.isNaI()?1:0,result.hashCode()); } + catch(IllegalArgumentException | IllegalStateException e) { out.println("bounds "+name+" error"); } + } + private static void fbmProbe(RandomSource random,int octave,double smear,double amplitude,PrintWriter out) throws Exception { + NoiseStack stack; + try { stack=BlendedNoise.createFbm(random,octave,smear,amplitude); } + catch(IllegalArgumentException e) { out.println("fbm error");out.println("fbm-parent "+random.nextLong());return; } + var layersField=NoiseStack.class.getDeclaredField("layers");layersField.setAccessible(true);Object[] layers=(Object[])layersField.get(stack); + out.printf("fbm %d %s %s%n",layers.length,bits(stack.range().min()),bits(stack.range().max())); + for(int i=0;i holder) { return noise; } + public RandomSource createRandom(net.minecraft.resources.Identifier id) { throw new AssertionError("unexpected random lookup"); } + public RandomSource createEndIslandRandom() { throw new AssertionError("unexpected end lookup"); } + }; + } + private static Interval[] splineRanges = {Interval.INFINITE,Interval.INFINITE,Interval.INFINITE}; + private static final class TransportFunction implements DensityFunction { + private final DensitySampler sampler; + private final int id; + TransportFunction(int id,DensitySampler sampler) { this.id=id;this.sampler=sampler; } + public DensitySampler compileSampler(DensityFunction.CompileContext context) { return sampler; } + public DensityFunction rewriteChildren(DfRewriteRule rule) { return this; } + public Interval range() { return splineRanges[id % 3]; } + public int domainAxes() { return 7; } + public com.mojang.serialization.MapCodec codec() { throw new AssertionError("unexpected codec lookup"); } + } + private static final class BoundFunction implements DensityFunction { + private final DensitySampler sampler; + private final Interval range; + private final int axes; + BoundFunction(DensitySampler sampler,Interval range,int axes){this.sampler=sampler;this.range=range;this.axes=axes;} + public DensitySampler compileSampler(DensityFunction.CompileContext context){return sampler;} + public DensityFunction rewriteChildren(DfRewriteRule rule){return this;} + public Interval range(){return range;} + public int domainAxes(){return axes;} + public com.mojang.serialization.MapCodec codec(){throw new AssertionError("unexpected codec lookup");} + } + private static int cacheCount(DensityFunctionCompiler compiler) throws Exception { + var field=DensityFunctionCompiler.class.getDeclaredField("nextCacheId");field.setAccessible(true);return field.getInt(compiler); + } + // The concrete structure key has an erased DensitySampler runtime contract. + // Widen it solely to attach transport samplers that expose delegation calls. + @SuppressWarnings("unchecked") + private static net.minecraft.util.context.ContextKey structureKey() { + return (net.minecraft.util.context.ContextKey)(net.minecraft.util.context.ContextKey)Beardifier.CONTEXT_KEY; + } + public static void main(String[] paths) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var samplers=new ArrayList(); + var noises=new ArrayList(); + var splines=new ArrayList>(); + var functions=new java.util.HashMap(); + var context=SamplerContext.EMPTY_UNCACHED; + var counters=new ArrayList(); + var graph=new ArrayList(); + var graphFunctions=new net.minecraft.core.MappedRegistry(net.minecraft.core.registries.Registries.DENSITY_FUNCTION,com.mojang.serialization.Lifecycle.stable()); + var namedFunctions=new java.util.HashMap>(); + var graphSplines=new ArrayList>(); + var graphNoises=new ArrayList>(); + var graphContext=shiftContext(null); + net.minecraft.core.MappedRegistry graphRegistry=null; + long graphWorldSeed=0;boolean graphLegacy=false; + var graphCompiler=new DensityFunctionCompiler(shiftContext(null)); + try(var reader=Files.newBufferedReader(Path.of(paths[0]),StandardCharsets.UTF_8); + var out=new PrintWriter(Files.newBufferedWriter(Path.of(paths[1]),StandardCharsets.UTF_8))) { + String line; + while((line=reader.readLine())!=null) { + var args=new StringTokenizer(line); + switch(args.nextToken()) { + case "constant" -> { samplers.add(new ConstantFunction.Sampler(small(args)));out.println("create "+(samplers.size()-1)); } + case "gradient" -> { + var axis=Axis.values()[integer(args)];var tiling=TilingMode.values()[integer(args)]; + int from=integer(args),to=integer(args);float low=small(args),high=small(args); + samplers.add(new GradientFunction(axis,tiling,from,to,low,high).compileSampler(null)); + out.println("create "+(samplers.size()-1)); + } + case "noise" -> { + String kind=args.nextToken(),stream=args.nextToken();long seed=Long.parseLong(args.nextToken());double scale=number(args); + RandomSource random=stream.equals("legacy")?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + Noise noise=switch(kind) { case "normal"->NormalNoise.builder().setBaseOctave(-7).setOctaveCount(4).build().create(random);case "perlin"->new PerlinNoise(random);case "simplex"->new SimplexNoise(random);case "smeared"->new SmearedPerlinNoise(random,scale);default->throw new AssertionError(); }; + var sampler=new NoiseFunction.Sampler(noise,number(args),number(args));noises.add(sampler);samplers.add(sampler); + out.printf("noise %d %d%n",noises.size()-1,samplers.size()-1); + } + case "shift" -> { + var noise=noises.get(integer(args));int x=integer(args),y=integer(args),z=integer(args); + samplers.add(y<0?new NoiseFunction.ShiftedXzSampler(samplers.get(x),samplers.get(z),noise.noise(),noise.xzScale(),noise.yScale()):new NoiseFunction.ShiftedXyzSampler(samplers.get(x),samplers.get(y),samplers.get(z),noise.noise(),noise.xzScale(),noise.yScale())); + out.println("create "+(samplers.size()-1)); + } + case "unary" -> { + String kind=args.nextToken();var input=samplers.get(integer(args));float a=small(args),b=small(args); + DensitySampler result=switch(kind) { + case "abs" -> new UnaryFunction.AbsSampler(input); + case "negate" -> new UnaryFunction.NegateSampler(input); + case "square" -> new UnaryFunction.SquareSampler(input); + case "cube" -> new UnaryFunction.CubeSampler(input); + case "sqrt" -> new UnaryFunction.SqrtSampler(input); + case "log" -> new UnaryFunction.LogSampler(input); + case "reciprocal" -> new UnaryFunction.ReciprocalSampler(input); + case "sign" -> new UnaryFunction.SignSampler(input); + case "squeeze" -> new UnaryFunction.SqueezeSampler(input); + case "leaky" -> new UnaryFunction.LeakyReLUSampler(input,a); + case "add" -> new BinaryFunction.ConstAddSampler(input,a); + case "sub" -> new BinaryFunction.ConstSubSampler(a,input); + case "mul" -> new BinaryFunction.ConstMulSampler(input,a); + case "div" -> new BinaryFunction.ConstDivSampler(a,input); + case "min" -> new BinaryFunction.ConstMinSampler(input,a); + case "max" -> new BinaryFunction.ConstMaxSampler(input,a); + case "clamp" -> new ClampFunction.Sampler(input,a,b); + default -> throw new AssertionError(); + }; + samplers.add(result);out.println("create "+(samplers.size()-1)); + } + case "round" -> { + var type=RoundFunction.Type.values()[integer(args)];var input=samplers.get(integer(args));int multiple=integer(args); + var result=multiple<0?construct("RoundFunction$IntegerMultipleSampler",new Class[]{RoundFunction.Type.class,DensitySampler.class},type,input): + construct("RoundFunction$Sampler",new Class[]{RoundFunction.Type.class,DensitySampler.class,DensitySampler.class},type,input,samplers.get(multiple)); + samplers.add(result);out.println("create "+(samplers.size()-1)); + } + case "power" -> { + int mode=integer(args);DensitySampler result; + if(mode==0)result=construct("PowFunction$Sampler",new Class[]{DensitySampler.class,DensitySampler.class},samplers.get(integer(args)),samplers.get(integer(args))); + else if(mode==1)result=construct("PowFunction$ConstBaseSampler",new Class[]{double.class,DensitySampler.class},number(args),samplers.get(integer(args))); + else if(mode==2)result=construct("PowFunction$ConstExponentSampler",new Class[]{DensitySampler.class,double.class},samplers.get(integer(args)),number(args)); + else throw new AssertionError(); + samplers.add(result);out.println("create "+(samplers.size()-1)); + } + case "binary" -> { + String kind=args.nextToken();var left=samplers.get(integer(args));var right=samplers.get(integer(args));float bound=small(args); + DensitySampler result=switch(kind) { + case "add" -> new BinaryFunction.AddSampler(left,right); + case "sub" -> new BinaryFunction.SubSampler(left,right); + case "mul" -> new BinaryFunction.MulSampler(left,right); + case "div" -> new BinaryFunction.DivSampler(left,right); + case "min" -> new BinaryFunction.MinSampler(left,right,bound); + case "max" -> new BinaryFunction.MaxSampler(left,right,bound); + default -> throw new AssertionError(); + }; + samplers.add(result);out.println("create "+(samplers.size()-1)); + } + case "choice" -> { + int mode=integer(args);var input=samplers.get(integer(args));float min=small(args),max=small(args); + DensitySampler result; + if(mode==1)result=construct("RangeChoiceFunction$ConstSampler",new Class[]{DensitySampler.class,float.class,float.class,float.class,float.class},input,min,max,small(args),small(args)); + else result=construct("RangeChoiceFunction$Sampler",new Class[]{DensitySampler.class,float.class,float.class,DensitySampler.class,DensitySampler.class},input,min,max,samplers.get(integer(args)),samplers.get(integer(args))); + samplers.add(result);out.println("create "+(samplers.size()-1)); + } + case "lerp" -> { + int mode=integer(args);var alpha=samplers.get(integer(args)); + DensitySampler result=switch(mode) { + case 0 -> new LerpFunction.Sampler(alpha,samplers.get(integer(args)),samplers.get(integer(args))); + case 1 -> new LerpFunction.ConstFirstSampler(alpha,small(args),samplers.get(integer(args))); + case 2 -> new LerpFunction.ConstSecondSampler(alpha,samplers.get(integer(args)),small(args)); + default -> throw new AssertionError(); + }; + samplers.add(result);out.println("create "+(samplers.size()-1)); + } + case "interval" -> { + int mode=integer(args);var input=samplers.get(integer(args));int count=integer(args); + float[] thresholds=new float[count];for(int i=0;i[]{DensitySampler.class,float[].class,DensitySampler[].class},input,thresholds,branches): + construct("IntervalSelectFunction$SingleThresholdSampler",new Class[]{DensitySampler.class,float.class,DensitySampler.class,DensitySampler.class},input,thresholds[0],branches[0],branches[1]); + samplers.add(result);out.println("create "+(samplers.size()-1)); + } + case "bounds" -> { + int mode=integer(args);float a=small(args),b=small(args),c=small(args),d=small(args),e=small(args),f=small(args); + Interval left; + try { left=switch(mode) {case 0->Interval.of(a,b);case 1->Interval.ofSymmetric(a);case 2->Interval.ofExact(a);case 3->Interval.encapsulating(a,b);case 4->Interval.NaI;case 5->Interval.INFINITE;default->throw new AssertionError();}; } + catch(IllegalArgumentException error) { out.println("bounds create error");break; } + final var first=left;var right=Interval.encapsulating(c,d);var third=Interval.encapsulating(e,f); + intervalOutput(out,"create",()->first);intervalOutput(out,"right",()->right); + intervalOutput(out,"add",()->Interval.add(first,right));intervalOutput(out,"sub",()->Interval.sub(first,right)); + intervalOutput(out,"mul",()->Interval.mul(first,right));intervalOutput(out,"div",()->Interval.div(first,right)); + intervalOutput(out,"min",()->Interval.min(first,right));intervalOutput(out,"max",()->Interval.max(first,right)); + intervalOutput(out,"reciprocal",()->Interval.reciprocal(first));intervalOutput(out,"abs",()->Interval.abs(first)); + intervalOutput(out,"square",()->Interval.square(first));intervalOutput(out,"sign",()->Interval.sign(first)); + intervalOutput(out,"power",()->Interval.pow(first,right)); + intervalOutput(out,"clamp",()->Interval.clamp(first,c,d)); + intervalOutput(out,"log",()->Interval.log(first)); + intervalOutput(out,"lerp-values",()->Interval.lerp(first,c,d));intervalOutput(out,"lerp-ranges",()->Interval.lerp(first,right,third)); + intervalOutput(out,"map-negate",()->Interval.mapMonotonic(first,v->-v));intervalOutput(out,"map-cube",()->Interval.mapMonotonic(first,v->v*v*v)); + intervalOutput(out,"map-sqrt",()->Interval.mapMonotonic(first,v->(float)Math.sqrt(v)));intervalOutput(out,"map-reciprocal",()->Interval.mapMonotonic(first,v->1.0f/v)); + intervalOutput(out,"hull",()->Interval.encapsulating(first,right,third)); + intervalOutput(out,"empty",()->Interval.encapsulating(new Interval[0])); + out.printf("bounds query %d %d %d %d%n",first.contains(e)?1:0,first.intersects(right)?1:0,first.equals(right)?1:0,first.equals(first)?1:0); + } + case "offset" -> { + int kind=integer(args);var contextForShift=shiftContext(noises.get(integer(args)).noise()); + var sampler=switch(kind) {case 0->new ShiftNoiseFunction.Shift(null).compileSampler(contextForShift);case 1->new ShiftNoiseFunction.ShiftA(null).compileSampler(contextForShift);case 2->new ShiftNoiseFunction.ShiftB(null).compileSampler(contextForShift);default->throw new AssertionError();}; + samplers.add(sampler);out.println("create "+(samplers.size()-1)); + } + case "blended", "blendfail" -> { + String stream=args.nextToken();long seed=Long.parseLong(args.nextToken()); + var definition=new BlendedNoise(number(args),number(args),number(args),number(args),number(args)); + intervalOutput(out,"blended",definition::range); + RandomSource random=stream.equals("legacy")?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + DensitySampler sampler=null; + try { sampler=definition.compileSampler(random); } catch(IllegalArgumentException e) { } + out.printf("blended %s %d%n",sampler==null?"error":"ok",random.nextLong()); + if(sampler!=null) { samplers.add(sampler);out.println("create "+(samplers.size()-1)); } + } + case "blendfbm" -> { + String stream=args.nextToken();long seed=Long.parseLong(args.nextToken());int octave=integer(args);double smear=number(args),amplitude=number(args); + RandomSource random=stream.equals("legacy")?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + fbmProbe(random,octave,smear,amplitude,out); + } + case "distance" -> { + var metric=DistanceMetric.values()[integer(args)];var point=new net.minecraft.core.Vec3i(integer(args),integer(args),integer(args)); + samplers.add(new DistanceToPointFunction(point,metric).compileSampler(null));out.println("create "+(samplers.size()-1)); + } + case "metric" -> { + float x=small(args),y=small(args),z=small(args); + for(var metric:DistanceMetric.values())out.printf("metric %s %s%n",bits(metric.compute(x,y)),bits(metric.compute(x,y,z))); + } + case "wfield" -> { + int field=integer(args),fallback=integer(args); + var key=switch(field){case 0->Blender.ALPHA_KEY;case 1->Blender.OFFSET_KEY;case 2->Beardifier.CONTEXT_KEY;default->throw new AssertionError();}; + samplers.add(fallback<0?SimpleDensityFunction.values()[field].compileSampler(null):new ContextBoundSampler(key,samplers.get(fallback)));out.println("create "+(samplers.size()-1)); + } + case "blenddensity" -> { + samplers.add(new BlendDensityFunction(new BoundFunction(samplers.get(integer(args)),Interval.INFINITE,7)).compileSampler(null));out.println("create "+(samplers.size()-1)); + } + case "context","wcontext" -> { + boolean cached=integer(args)!=0; + var builder=SamplerContext.builder().useBufferArena(new DensityBufferArena() { + public ScopedDensityBuffer acquire(int size) { var result=DensityBufferArena.GLOBAL.acquire(size);result.fill(0.0f);return result; } + public void release(ScopedDensityBuffer buffer) { DensityBufferArena.GLOBAL.release(buffer); } + }); + if(line.startsWith("wcontext ")) { + var fields=ContextMap.builder(); + int alpha=integer(args),offset=integer(args),beard=integer(args),blender=integer(args); + if(alpha>=0)fields.set(Blender.ALPHA_KEY,samplers.get(alpha)); + if(offset>=0)fields.set(Blender.OFFSET_KEY,samplers.get(offset)); + if(beard>=0)fields.set(structureKey(),samplers.get(beard)); + if(blender!=0)fields.set(Blender.CONTEXT_KEY,Blender.empty()); + builder.setUserFields(fields.build()); + } + if(cached)builder.enableCaches();context=builder.build();out.println("context"); + } + case "counted" -> { + var input=samplers.get(integer(args));var calls=new long[2];counters.add(calls); + samplers.add(new DensitySampler() { + public float sampleValue(SamplerContext ctx,int x,int y,int z) { calls[0]++;return input.sampleValue(ctx,x,y,z); } + public void sampleVolume(SamplerContext ctx,DensityBuffer buffer,DensityVolume volume) { calls[1]++;input.sampleVolume(ctx,buffer,volume); } + }); + out.printf("counted %d %d%n",counters.size()-1,samplers.size()-1); + } + case "counts" -> { var calls=counters.get(integer(args));out.printf("counts %d %d%n",calls[0],calls[1]); } + case "greset" -> {graphFunctions=new net.minecraft.core.MappedRegistry<>(net.minecraft.core.registries.Registries.DENSITY_FUNCTION,com.mojang.serialization.Lifecycle.stable());namedFunctions.clear();graph.clear();graphSplines.clear();graphNoises.clear();graphContext=shiftContext(null);graphCompiler=new DensityFunctionCompiler(graphContext);context=SamplerContext.EMPTY_UNCACHED;out.println("graph-reset");} + case "gend" -> {graph.add(new EndIslandFunction());out.println("graph-create "+(graph.size()-1));} + case "gseed" -> { + long seed=Long.parseLong(args.nextToken());boolean legacy=integer(args)!=0; + graphWorldSeed=seed;graphLegacy=legacy; + graphRegistry=new net.minecraft.core.MappedRegistry<>(net.minecraft.core.registries.Registries.NOISE,com.mojang.serialization.Lifecycle.stable()); + // Original fixtures supply constructor-only material inputs; + // RandomState performs all seed derivation and noise creation. + for(var key:java.util.List.of(net.minecraft.world.level.levelgen.Noises.CLAY_BANDS_OFFSET,net.minecraft.world.level.levelgen.Noises.SURFACE,net.minecraft.world.level.levelgen.Noises.SURFACE_SECONDARY,net.minecraft.world.level.levelgen.Noises.BADLANDS_PILLAR,net.minecraft.world.level.levelgen.Noises.BADLANDS_PILLAR_ROOF,net.minecraft.world.level.levelgen.Noises.BADLANDS_SURFACE,net.minecraft.world.level.levelgen.Noises.ICEBERG_PILLAR,net.minecraft.world.level.levelgen.Noises.ICEBERG_PILLAR_ROOF,net.minecraft.world.level.levelgen.Noises.ICEBERG_SURFACE)) + graphRegistry.register(key,NormalNoise.builder().setOctaveCount(0).build(),net.minecraft.core.RegistrationInfo.BUILT_IN); + graphContext=shiftContext(null);graphCompiler=new DensityFunctionCompiler(graphContext); + graphFunctions=new net.minecraft.core.MappedRegistry<>(net.minecraft.core.registries.Registries.DENSITY_FUNCTION,com.mojang.serialization.Lifecycle.stable());namedFunctions.clear();graph.clear();graphSplines.clear();graphNoises.clear();context=SamplerContext.EMPTY_UNCACHED;out.println("graph-seed"); + } + case "gready" -> { + graphRegistry.freeze(); + var zero=DensityFunctions.zero();var router=new net.minecraft.world.level.levelgen.NoiseRouter(zero,zero,zero,zero,zero,zero,zero,zero); + var state=net.minecraft.world.level.levelgen.RandomState.create(graphRegistry,graphWorldSeed,graphLegacy,net.minecraft.world.level.block.Blocks.STONE.defaultBlockState(),63,router); + var compilerField=state.getClass().getDeclaredField("densityFunctionCompiler");compilerField.setAccessible(true);graphCompiler=(DensityFunctionCompiler)compilerField.get(state); + var contextField=DensityFunctionCompiler.class.getDeclaredField("context");contextField.setAccessible(true);graphContext=(DensityFunction.CompileContext)contextField.get(graphCompiler); + out.println("graph-ready"); + } + case "gregister" -> { + String name=args.nextToken();int base=integer(args);double amplitude=number(args);int count=integer(args),normalization=integer(args),modifiers=integer(args); + var builder=NormalNoise.builder().setBaseOctave(base).setBaseAmplitude(amplitude).setOctaveCount(count); + if(normalization==2)builder.setLegacyNormalization();else builder.setNormalize(normalization==1); + for(int i=0;i {var holder=graphNoises.get(integer(args));var a=graphContext.createNoiseSampler(holder);var b=graphContext.createNoiseSampler(holder);out.println("graph-instance "+(a==b?1:0));} + case "gsconstant" -> {graphSplines.add(CubicSpline.constant(small(args)));out.println("graph-spline "+(graphSplines.size()-1));} + case "gspoints" -> { + var coordinate=new SplineFunction.Coordinate(graph.get(integer(args)));int count=integer(args); + var locations=new float[count];var derivatives=new float[count];var values=new ArrayList>(); + for(int i=0;i(coordinate,locations,values,derivatives));out.println("graph-spline "+(graphSplines.size()-1)); + } + case "gref" -> {graph.add(new DensityFunctions.HolderHolder(net.minecraft.core.Holder.direct(graph.get(integer(args)))));out.println("graph-create "+(graph.size()-1));} + case "gnamed" -> { + String name=args.nextToken();var value=graph.get(integer(args)); + // Distinct equal constant objects may have distinct registered holders. + if(value instanceof ConstantFunction constant)value=new ConstantFunction(constant.value()); + var key=net.minecraft.resources.ResourceKey.create(net.minecraft.core.registries.Registries.DENSITY_FUNCTION,net.minecraft.resources.Identifier.parse(name)); + var holder=graphFunctions.register(key,value,net.minecraft.core.RegistrationInfo.BUILT_IN); + // Bind each transport entry immediately, as freeze binds a loaded registry. + var bind=net.minecraft.core.Holder.Reference.class.getDeclaredMethod("bindValue",Object.class);bind.setAccessible(true);bind.invoke(holder,value);namedFunctions.put(name,holder); + graph.add(new DensityFunctions.HolderHolder(holder));out.println("graph-create "+(graph.size()-1)); + } + case "glookup" -> {graph.add(new DensityFunctions.HolderHolder(namedFunctions.get(args.nextToken())));out.println("graph-create "+(graph.size()-1));} + case "gspline" -> {graph.add(new SplineFunction(graphSplines.get(integer(args))));out.println("graph-create "+(graph.size()-1));} + case "gbind" -> { + var sampler=samplers.get(integer(args));var range=Interval.encapsulating(small(args),small(args));int axes=integer(args); + graph.add(new BoundFunction(sampler,range,axes));out.println("graph-create "+(graph.size()-1)); + } + case "gconst","ggradient","gunary","gbinary","gclamp","gchoice","glerp","gslice","gcache","ginterp","gsurface","ginterval","gdistance","gnoise","goffset","gblended","ground","gpow","gwfield","gblenddensity" -> { + String command=line.substring(0,line.indexOf(' ')); + DensityFunction node=switch(command){ + case "gconst"->new ConstantFunction(small(args)); + case "gwfield"->SimpleDensityFunction.values()[integer(args)]; + case "gblenddensity"->new BlendDensityFunction(graph.get(integer(args))); + case "gnoise"->new NoiseFunction(graphNoises.get(integer(args)),number(args),number(args),graph.get(integer(args)),graph.get(integer(args)),graph.get(integer(args))); + case "goffset"->{var noise=graphNoises.get(integer(args));yield switch(integer(args)){case 0->new ShiftNoiseFunction.Shift(noise);case 1->new ShiftNoiseFunction.ShiftA(noise);case 2->new ShiftNoiseFunction.ShiftB(noise);default->throw new AssertionError();};} + case "gblended"->new BlendedNoise(number(args),number(args),number(args),number(args),number(args)); + case "ground"->new RoundFunction(RoundFunction.Type.values()[integer(args)],graph.get(integer(args)),graph.get(integer(args))); + case "gpow"->new PowFunction(graph.get(integer(args)),graph.get(integer(args))); + case "gdistance"->new DistanceToPointFunction(new net.minecraft.core.Vec3i(integer(args),integer(args),integer(args)),DistanceMetric.values()[integer(args)]); + case "ginterval"->{ + var input=graph.get(integer(args));int count=integer(args); + float[] thresholds=new float[count];for(int i=0;i();for(int i=0;i<=count;i++)branches.add(graph.get(integer(args))); + yield new IntervalSelectFunction(input,it.unimi.dsi.fastutil.floats.FloatArrayList.wrap(thresholds),branches); + } + case "ggradient"->new GradientFunction(Axis.values()[integer(args)],TilingMode.values()[integer(args)],integer(args),integer(args),small(args),small(args)); + case "gunary"->new UnaryFunction(UnaryFunction.Type.values()[new int[]{0,1,2,4,5,6,7,8,10,9,3}[integer(args)]],graph.get(integer(args))); + case "gbinary"->new BinaryFunction(BinaryFunction.Type.values()[integer(args)],graph.get(integer(args)),graph.get(integer(args))); + case "gclamp"->new ClampFunction(graph.get(integer(args)),small(args),small(args)); + case "gchoice"->new RangeChoiceFunction(graph.get(integer(args)),small(args),small(args),graph.get(integer(args)),graph.get(integer(args))); + case "glerp"->new LerpFunction(graph.get(integer(args)),graph.get(integer(args)),graph.get(integer(args))); + case "gslice"->new SliceFunction(Axis.values()[integer(args)],integer(args),graph.get(integer(args))); + case "gcache"->new CacheFunction(graph.get(integer(args))); + case "ginterp"->new InterpolatedFunction(graph.get(integer(args)),integer(args),integer(args)); + case "gsurface"->new FindTopSurfaceFunction(graph.get(integer(args)),graph.get(integer(args)),integer(args),integer(args)); + default->throw new AssertionError(); + }; + graph.add(node);out.println("graph-create "+(graph.size()-1)); + } + case "ginfo" -> {var node=graph.get(integer(args));intervalOutput(out,"graph",node::range);out.println("graph-axes "+node.domainAxes());} + case "gsame" -> out.println("graph-same "+(graph.get(integer(args)).equals(graph.get(integer(args)))?1:0)); + case "gcompile","gtry" -> { + String command=line.substring(0,line.indexOf(' '));int mode=integer(args);var node=graph.get(integer(args)); + if(command.equals("gtry")){ + String status="ok"; + try{if(mode==0)node.compileSampler(graphContext);else graphCompiler.getSampler(node);} + catch(IllegalArgumentException | IllegalStateException e){status="error";} + out.printf("graph-try %s %d%n",status,cacheCount(graphCompiler)); + }else{ + var sampler=mode==0?node.compileSampler(graphContext):graphCompiler.getSampler(node); + int same=mode==0?-1:(sampler==graphCompiler.getSampler(node)?1:0); + samplers.add(sampler);out.printf("graph-compile %d %d %d%n",samplers.size()-1,cacheCount(graphCompiler),same); + } + } + case "spconstant" -> { + splines.add(CubicSpline.constant(small(args)));out.println("spline "+(splines.size()-1)); + } + case "sppoints" -> { + int id=integer(args),count=integer(args);var function=functions.computeIfAbsent(id,key->new TransportFunction(key,samplers.get(key))); + var locations=new float[count];var derivatives=new float[count];var values=new ArrayList>(); + for(int i=0;i(new SplineFunction.Coordinate(function),locations,values,derivatives));out.println("spline "+(splines.size()-1)); + } + case "spfail" -> { + var spline=splines.get(integer(args)); + try {new SplineFunction(spline).compileSampler(shiftContext(null));out.println("spline-compile ok");} + catch(IllegalArgumentException e){out.println("spline-compile error");} + } + case "sprange" -> { + var spline=splines.get(integer(args)); + for(int i=0;i<3;i++)splineRanges[i]=Interval.encapsulating(small(args),small(args)); + intervalOutput(out,"spline",spline::range); + java.util.Arrays.fill(splineRanges,Interval.INFINITE); + } + case "spsampler" -> { + samplers.add(new SplineFunction(splines.get(integer(args))).compileSampler(shiftContext(null)));out.println("create "+(samplers.size()-1)); + } + case "surface" -> { + int mode=integer(args);var density=samplers.get(integer(args));var upper=samplers.get(integer(args));int lower=integer(args),height=integer(args); + var sampler=construct("FindTopSurfaceFunction$Sampler",new Class[]{DensitySampler.class,DensitySampler.class,int.class,int.class},density,upper,lower,height); + samplers.add(mode==0?sampler:new SliceFunction.YSampler(sampler,0));out.println("create "+(samplers.size()-1)); + } + case "interpolate" -> { + var input=samplers.get(integer(args));int xz=integer(args),y=integer(args); + samplers.add(construct("InterpolatedFunction$Sampler",new Class[]{DensitySampler.class,int.class,int.class,float.class,float.class},input,xz,y,1.0f/xz,1.0f/y)); + out.println("create "+(samplers.size()-1)); + } + case "slice" -> { + int mode=integer(args);var input=samplers.get(integer(args));int a=integer(args),b=integer(args); + DensitySampler sampler=switch(mode) { + case 0->new SliceFunction.XSampler(input,a); + case 1->new SliceFunction.YSampler(input,a); + case 2->new SliceFunction.ZSampler(input,a); + case 3->new SliceFunction.XzSampler(input,a,b); + default->throw new AssertionError(); + }; + samplers.add(sampler);out.println("create "+(samplers.size()-1)); + } + case "cache" -> { int id=integer(args);samplers.add(new CachingDensitySampler(id,samplers.get(integer(args))));out.println("create "+(samplers.size()-1)); } + case "lookup" -> { + var volume=new DensityVolume(integer(args),integer(args),integer(args),integer(args),integer(args),integer(args),integer(args),integer(args),integer(args)); + out.println("lookup "+volume.indexOfBlock(integer(args),integer(args),integer(args))); + } + case "query" -> { + var sampler=samplers.get(integer(args));int x=integer(args),y=integer(args),z=integer(args); + try { out.println("query "+bits(sampler.sampleValue(context,x,y,z))); } + catch(ArithmeticException e) { out.println("query error"); } + } + case "volume" -> { + var sampler=samplers.get(integer(args)); + int sx=integer(args),sy=integer(args),sz=integer(args),mx=integer(args),my=integer(args),mz=integer(args),dx=integer(args),dy=integer(args),dz=integer(args); + int tail=integer(args);long seed=Long.parseLong(args.nextToken());int repeats=integer(args); + var volume=new DensityVolume(sx,sy,sz,mx,my,mz,dx,dy,dz);var buffer=DensityBuffer.createUnpooled(volume.size()+tail);var random=new LegacyRandomSource(seed); + for(int i=0;i throw new AssertionError(); + } + if(args.hasMoreTokens())throw new AssertionError("extra argument"); + } + if(out.checkError())throw new java.io.IOException("reference output failed"); + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDynamicSupportOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDynamicSupportOracle.java new file mode 100644 index 000000000..26619a5b3 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDynamicSupportOracle.java @@ -0,0 +1,55 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import net.minecraft.core.*; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.entity.*; +import net.minecraft.world.level.block.piston.PistonMovingBlockEntity; +import net.minecraft.world.level.block.state.*; +import net.minecraft.world.phys.shapes.*; +/** Native uncached support selection; block-entity lifecycle is outside these snapshots. */ +public final class VanillaDynamicSupportOracle { + private static final class Stop extends RuntimeException {} + @SuppressWarnings("unchecked") public static void main(String[] args)throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); + if(args[0].equals("export")) { + VanillaCollisionOracle.main(new String[]{"generate",args[1]}); + VanillaBlockStateCodecOracle.main(new String[]{"export",dir.resolve("facts.json").toString()}); + var cache=BlockBehaviour.BlockStateBase.class.getDeclaredField("cache");cache.setAccessible(true);var ids=new JsonArray();for(var state:Block.BLOCK_STATE_REGISTRY)if(cache.get(state)==null)ids.add(Block.getId(state));Files.writeString(dir.resolve("uncached-states.json"),ids.toString());return; + } + var allocator=Class.forName("sun.misc.Unsafe");var access=allocator.getDeclaredField("theUnsafe");access.setAccessible(true);var unsafe=access.get(null);var allocate=allocator.getMethod("allocateInstance",Class.class); + var progress=PistonMovingBlockEntity.class.getDeclaredField("progress");progress.setAccessible(true);var clipField=PistonMovingBlockEntity.class.getDeclaredField("NOCLIP");clipField.setAccessible(true);var noclip=(ThreadLocal)clipField.get(null); + var shulkerOld=ShulkerBoxBlockEntity.class.getDeclaredField("progressOld");shulkerOld.setAccessible(true);var shulkerProgress=ShulkerBoxBlockEntity.class.getDeclaredField("progress");shulkerProgress.setAccessible(true); + var animation=ShulkerBoxBlockEntity.class.getDeclaredField("animationStatus");animation.setAccessible(true); + var emit=VanillaFaceSupportOracle.class.getDeclaredMethod("emit",PrintWriter.class,VoxelShape.class);emit.setAccessible(true); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt")));var inputs=Files.lines(dir.resolve("inputs.txt"))) { + for(var line:(Iterable)inputs::iterator) { + var f=JsonParser.parseString(line).getAsJsonObject();var state=Block.stateById(f.get("state").getAsInt());var xyz=f.getAsJsonArray("position");var p=new BlockPos(xyz.get(0).getAsInt(),xyz.get(1).getAsInt(),xyz.get(2).getAsInt());String mode=f.get("entity").getAsString(); + Object entity=null; + if(!mode.equals("none")) { + if(mode.equals("other"))entity=allocate.invoke(unsafe,state.getBlock() instanceof ShulkerBoxBlock?PistonMovingBlockEntity.class:ShulkerBoxBlockEntity.class); + else if(mode.equals("piston")) { + var data=f.getAsJsonObject("piston");var moving=new PistonMovingBlockEntity(p,state,Block.stateById(data.get("state").getAsInt()),Direction.values()[data.get("direction").getAsInt()],data.get("extending").getAsBoolean(),data.get("source").getAsBoolean()); + progress.setFloat(moving,Float.intBitsToFloat(Integer.parseUnsignedInt(data.get("progress").getAsString(),16)));entity=moving;int clip=data.get("noclip").getAsInt();noclip.set(clip<0?null:Direction.values()[clip]); + } + else {entity=allocate.invoke(unsafe,ShulkerBoxBlockEntity.class);Object status=null;for(var value:animation.getType().getEnumConstants())if(((Enum)value).name().equals(mode.toUpperCase(java.util.Locale.ROOT)))status=value;if(status==null)throw new AssertionError(mode);animation.set(entity,status);} + } + if(entity instanceof ShulkerBoxBlockEntity && f.has("shulker_progress")){var data=f.getAsJsonArray("shulker_progress");shulkerOld.setFloat(entity,Float.intBitsToFloat(Integer.parseUnsignedInt(data.get(0).getAsString(),16)));shulkerProgress.setFloat(entity,Float.intBitsToFloat(Integer.parseUnsignedInt(data.get(1).getAsString(),16)));} + Object selected=entity;int[] calls={0}; + var world=(BlockGetter)Proxy.newProxyInstance(BlockGetter.class.getClassLoader(),new Class[]{BlockGetter.class},(proxy,method,values)->{ + if(!method.getName().equals("getBlockEntity"))throw new AssertionError(method); + var at=(BlockPos)values[0];out.println("entity "+at.getX()+" "+at.getY()+" "+at.getZ());if(calls[0]++==f.get("fail").getAsInt())throw new Stop();return selected; + }); + var offset=state.getOffset(p);out.printf("offset %016x %016x %016x%n",Double.doubleToRawLongBits(offset.x),Double.doubleToRawLongBits(offset.y),Double.doubleToRawLongBits(offset.z)); + try {emit.invoke(null,out,f.has("collision")&&f.get("collision").getAsBoolean()?state.getCollisionShape(world,p):state.getBlockSupportShape(world,p));}catch(Stop error){out.println("shape error");} + for(var direction:Direction.values())for(var type:SupportType.values()) { + try {out.println("support "+direction.ordinal()+" "+type.ordinal()+" "+state.isFaceSturdy(world,p,direction,type));}catch(Stop error){out.println("support "+direction.ordinal()+" "+type.ordinal()+" error");} + } + out.println("queries "+calls[0]);noclip.remove(); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityObstructionOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityObstructionOracle.java new file mode 100644 index 000000000..71e349021 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityObstructionOracle.java @@ -0,0 +1,58 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import java.util.function.Predicate; +import net.minecraft.world.entity.*; +import net.minecraft.world.level.EntityGetter; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.shapes.*; +/** Original snapshot transport executing the actual EntityGetter default method. */ +public final class VanillaEntityObstructionOracle { + private static final class Stop extends RuntimeException {} + public static final class Snapshot extends Marker { + boolean spectator; + // Instances are allocated without constructors: the world-owned entity lifecycle is outside this fixture. + public Snapshot(){super(null,null);} + @Override public boolean isSpectator(){return spectator;} + } + private static AABB box(JsonElement value) { + var a=value.getAsJsonArray();double[] v=new double[6]; + for(int i=0;i<6;i++)v[i]=Double.longBitsToDouble(Long.parseUnsignedLong(a.get(i).getAsString(),16)); + return new AABB(v[0],v[1],v[2],v[3],v[4],v[5]); + } + @SuppressWarnings("unchecked") + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + Class allocator=Class.forName("sun.misc.Unsafe");var field=allocator.getDeclaredField("theUnsafe");field.setAccessible(true);var unsafe=field.get(null);var allocate=allocator.getMethod("allocateInstance",Class.class); + var removed=Entity.class.getDeclaredField("removalReason");removed.setAccessible(true);var vehicle=Entity.class.getDeclaredField("vehicle");vehicle.setAccessible(true); + Path dir=Path.of(args[1]); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt")));var inputs=Files.lines(dir.resolve("inputs.txt"))) { + for(var line:(Iterable)inputs::iterator) { + var f=JsonParser.parseString(line).getAsJsonObject();var entities=new ArrayList(); + for(var value:f.getAsJsonArray("entities")) { + var e=value.getAsJsonObject();var snapshot=(Snapshot)allocate.invoke(unsafe,Snapshot.class); + snapshot.setId(entities.size()+1);snapshot.setBoundingBox(box(e.get("box")));snapshot.blocksBuilding=e.get("building").getAsBoolean();snapshot.spectator=e.get("spectator").getAsBoolean(); + if(e.get("removed").getAsBoolean())removed.set(snapshot,Entity.RemovalReason.DISCARDED); + int parent=e.get("parent").getAsInt();if(parent>=0)vehicle.set(snapshot,entities.get(parent));entities.add(snapshot); + } + VoxelShape shape=Shapes.empty();for(var value:f.getAsJsonArray("shape"))shape=Shapes.or(shape,Shapes.create(box(value))); + int excluded=f.get("exclude").getAsInt();Entity except=excluded<0?null:entities.get(excluded);int[] calls={0}; + var world=(EntityGetter)Proxy.newProxyInstance(EntityGetter.class.getClassLoader(),new Class[]{EntityGetter.class},(proxy,method,values)->{ + if(method.isDefault())return InvocationHandler.invokeDefault(proxy,method,values); + if(!method.getName().equals("getEntities")||values.length!=3)throw new AssertionError(method); + var exceptEntity=(Entity)values[0];var bounds=(AABB)values[1];var predicate=(Predicate)values[2]; + out.printf("query %d %016x %016x %016x %016x %016x %016x%n",exceptEntity==null?-1:exceptEntity.getId(),Double.doubleToRawLongBits(bounds.minX),Double.doubleToRawLongBits(bounds.minY),Double.doubleToRawLongBits(bounds.minZ),Double.doubleToRawLongBits(bounds.maxX),Double.doubleToRawLongBits(bounds.maxY),Double.doubleToRawLongBits(bounds.maxZ)); + calls[0]++;if(f.get("fail").getAsBoolean())throw new Stop(); + var selected=new ArrayList(); + for(var entity:entities)if(entity!=exceptEntity&&entity.getBoundingBox().intersects(bounds)&&predicate.test(entity)){selected.add(entity);out.println("picked "+entity.getId());} + return selected; + }); + try {out.println("clear "+world.isUnobstructed(except,shape));}catch(Stop error){out.println("clear error");} + out.println("queries "+calls[0]); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFaceSupportOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFaceSupportOracle.java new file mode 100644 index 000000000..4e816024b --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFaceSupportOracle.java @@ -0,0 +1,56 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import net.minecraft.core.*; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.*; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.state.*; +import net.minecraft.world.phys.*; +import net.minecraft.world.phys.shapes.*; +/** Native face slicing and support algorithms over caller-specified shape data. */ +public final class VanillaFaceSupportOracle { + private static final class SupportBlock extends Block { + VoxelShape shape;int calls; + SupportBlock(){super(BlockBehaviour.Properties.of().setId(ResourceKey.create(Registries.BLOCK,Identifier.parse("horizon:fixture_support"))));} + @Override protected VoxelShape getBlockSupportShape(BlockState state,BlockGetter world,BlockPos pos){calls++;return shape;} + } + private static double number(JsonElement value){return Double.longBitsToDouble(Long.parseUnsignedLong(value.getAsString(),16));} + private static double[] numbers(JsonArray values){double[] result=new double[values.size()];for(int i=0;i)inputs::iterator) { + var f=JsonParser.parseString(line).getAsJsonObject();VoxelShape shape; + if(f.has("coords")) { + var coords=f.getAsJsonArray("coords");double[] x=numbers(coords.get(0).getAsJsonArray()),y=numbers(coords.get(1).getAsJsonArray()),z=numbers(coords.get(2).getAsJsonArray()); + int nx=x.length-1,ny=y.length-1,nz=z.length-1;var bits=new BitSetDiscreteVoxelShape(nx,ny,nz);var occupied=f.getAsJsonArray("occupied"); + for(int i=0;i decodeRoot(RegistryOps ops,JsonObject f) { + var json=JsonParser.parseString(f.get("definition").getAsString()); + if(!f.get("placed_root").getAsBoolean())return Feature.CODEC.parse(ops,json).result().map(Holder::value); + return PlacedFeature.CODEC.parse(ops,json).result().map(holder->new Feature(){ + public com.mojang.serialization.MapCodec codec(){return com.mojang.serialization.MapCodec.unit(this);} + public boolean place(WorldGenLevel world,ChunkGenerator generator,RandomSource random,BlockPos p){return holder.value().place(world,generator,random,p);} + }); + } + @SuppressWarnings("unchecked") + private static RegistryOps loadCatalog(Path dir) throws Exception { + var bundle=JsonParser.parseString(Files.readString(dir.resolve("catalog.json"))).getAsJsonObject(); + var features=new MappedRegistry(Registries.FEATURE,Lifecycle.stable()); + var placed=new MappedRegistry(Registries.PLACED_FEATURE,Lifecycle.stable()); + var ops=RegistryOps.create(JsonOps.INSTANCE,new RegistryOps.RegistryInfoLookup(){public Optional> lookup(ResourceKey> key){ + if(key.equals(Registries.FLUID))return (Optional>)(Optional)Optional.of(net.minecraft.core.registries.BuiltInRegistries.FLUID); + if(key.equals(Registries.BLOCK))return (Optional>)(Optional)Optional.of(net.minecraft.core.registries.BuiltInRegistries.BLOCK); + if(key.equals(Registries.FEATURE))return (Optional>)(Optional)Optional.of(features); + if(key.equals(Registries.PLACED_FEATURE))return (Optional>)(Optional)Optional.of(placed); + return Optional.empty(); + }}); + for(var entry:bundle.getAsJsonObject("features").entrySet())if(!entry.getKey().equals("horizon:composite"))features.register(ResourceKey.create(Registries.FEATURE,Identifier.parse(entry.getKey())),Feature.DIRECT_CODEC.parse(ops,JsonParser.parseString(entry.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN); + for(var entry:bundle.getAsJsonObject("placed").entrySet())placed.register(ResourceKey.create(Registries.PLACED_FEATURE,Identifier.parse(entry.getKey())),PlacedFeature.DIRECT_CODEC.parse(ops,JsonParser.parseString(entry.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN); + placed.freeze(); + var loader=new TagLoader>((id,required)->placed.get(id).map(value->(Holder)value),"tags/worldgen/placed_feature"); + var definitions=new HashMap>(); + for(var entry:bundle.getAsJsonObject("tags").entrySet()) { + var file=TagFile.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(entry.getValue().getAsString())).getOrThrow(); + var values=new ArrayList();for(var value:file.entries())values.add(new TagLoader.EntryWithSource(value,"fixture")); + definitions.put(Identifier.parse(entry.getKey()),values); + } + var tags=new HashMap,List>>(); + loader.build(definitions).forEach((name,values)->tags.put(TagKey.create(Registries.PLACED_FEATURE,name),List.copyOf(values))); + placed.prepareTagReload(new TagLoader.LoadResult<>(Registries.PLACED_FEATURE,tags)).apply(); + features.register(ResourceKey.create(Registries.FEATURE,Identifier.parse("horizon:composite")),Feature.DIRECT_CODEC.parse(ops,JsonParser.parseString(bundle.getAsJsonObject("features").get("horizon:composite").getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN); + features.freeze();return ops; + } + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + final Block[] BLOCKS={Blocks.AIR,Blocks.STONE,Blocks.COBBLESTONE,Blocks.END_STONE,Blocks.OBSIDIAN}; + if(args[0].equals("export")) { + VanillaBlockStateCodecOracle.main(args);return; + } + Path dir=Path.of(args[1]); + var ops=loadCatalog(dir); + var contextMethod=VanillaPlacementOracle.class.getDeclaredMethod("context",JsonObject.class);contextMethod.setAccessible(true); + var bounds=new JsonObject();bounds.add("context",JsonParser.parseString("[-64,384,63]")); + var generator=((PlacementContext)contextMethod.invoke(null,bounds)).generator(); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();long seed=f.get("seed").getAsLong(); + RandomSource random=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + if(f.get("worldgen").getAsBoolean())random=new WorldgenRandom(random); + Optional decoded; + try {decoded=decodeRoot(ops,f);}catch(IllegalArgumentException|IllegalStateException error){decoded=Optional.empty();} + var modifiers=new ArrayList();boolean valid=true; + if(f.has("placement"))for(var json:f.getAsJsonArray("placement")) { + try {var modifier=PlacementModifier.CODEC.parse(JsonOps.INSTANCE,json).result();if(modifier.isPresent())modifiers.add(modifier.get());else valid=false;} + catch(IllegalArgumentException error){valid=false;} + } + if(decoded.isEmpty()||!valid)out.println("decode error");else { + out.println("decode ok");int[] calls={0};int fail=f.get("fail").getAsInt(),reject=f.get("reject").getAsInt(); + var states=new TreeMap(Comparator.comparingInt(BlockPos::getX).thenComparingInt(BlockPos::getY).thenComparingInt(BlockPos::getZ)); + var world=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},(proxy,method,values)->{ + if(method.getName().equals("getMinY"))return -64; + if(method.getName().equals("getHeight")&&(values==null||values.length==0))return 384; + if(method.getName().equals("getSeaLevel"))return 63; + if(Set.of("getMaxY","isInsideBuildHeight","isOutsideBuildHeight","setBlockAndUpdate").contains(method.getName()))return InvocationHandler.invokeDefault(proxy,method,values); + var p=((BlockPos)values[0]).immutable();int call=calls[0]++; + switch(method.getName()) { + case "getBlockState"->{ + out.println("get "+p.getX()+" "+p.getY()+" "+p.getZ());if(call==fail)throw new Stop(); + var state=states.getOrDefault(p,BLOCKS[Math.floorMod(p.getX()*31+p.getY()*7+p.getZ()*17,5)].defaultBlockState());out.println("state "+Block.getId(state));return state; + } + case "setBlock"->{ + var state=(BlockState)values[1];int flags=(Integer)values[2];out.println("set "+p.getX()+" "+p.getY()+" "+p.getZ()+" "+Block.getId(state)+" "+flags);if(call==fail)throw new Stop(); + boolean result=reject==0||call%reject!=0;if(result)states.put(p,state);out.println("written "+result);return result; + } + default->throw new AssertionError("unexpected world method "+method); + } + }); + var p=f.getAsJsonArray("origin");var origin=new BlockPos(p.get(0).getAsInt(),p.get(1).getAsInt(),p.get(2).getAsInt()); + var placed=new PlacedFeature(Holder.direct(decoded.get()),modifiers);var placer=new FeaturePlacer(world,generator); + for(int repeat=0;repeat decoded; + try {decoded=Feature.DIRECT_CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(f.get("definition").getAsString())).result();}catch(IllegalArgumentException error){decoded=Optional.empty();} + var modifiers=new ArrayList();boolean valid=true; + if(f.has("placement"))for(var json:f.getAsJsonArray("placement")) { + try {var modifier=PlacementModifier.CODEC.parse(JsonOps.INSTANCE,json).result();if(modifier.isPresent())modifiers.add(modifier.get());else valid=false;} + catch(IllegalArgumentException error){valid=false;} + } + if(decoded.isEmpty()||!valid)out.println("decode error");else { + out.println("decode ok");int[] calls={0};int fail=f.get("fail").getAsInt(),reject=f.get("reject").getAsInt(); + var states=new TreeMap(Comparator.comparingInt(BlockPos::getX).thenComparingInt(BlockPos::getY).thenComparingInt(BlockPos::getZ)); + var world=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},(proxy,method,values)->{ + if(method.getName().equals("getMinY"))return -64; + if(method.getName().equals("getHeight")&&(values==null||values.length==0))return 384; + if(method.getName().equals("getSeaLevel"))return 63; + if(Set.of("getMaxY","isInsideBuildHeight","isOutsideBuildHeight","setBlockAndUpdate").contains(method.getName()))return InvocationHandler.invokeDefault(proxy,method,values); + var p=((BlockPos)values[0]).immutable();int call=calls[0]++; + switch(method.getName()) { + case "getBlockState"->{ + out.println("get "+p.getX()+" "+p.getY()+" "+p.getZ());if(call==fail)throw new Stop(); + var state=states.getOrDefault(p,BLOCKS[Math.floorMod(p.getX()*31+p.getY()*7+p.getZ()*17,5)].defaultBlockState());out.println("state "+Block.getId(state));return state; + } + case "setBlock"->{ + var state=(BlockState)values[1];int flags=(Integer)values[2];out.println("set "+p.getX()+" "+p.getY()+" "+p.getZ()+" "+Block.getId(state)+" "+flags);if(call==fail)throw new Stop(); + boolean result=reject==0||call%reject!=0;if(result)states.put(p,state);out.println("written "+result);return result; + } + default->throw new AssertionError("unexpected world method "+method); + } + }); + var p=f.getAsJsonArray("origin");var origin=new BlockPos(p.get(0).getAsInt(),p.get(1).getAsInt(),p.get(2).getAsInt()); + var placed=new PlacedFeature(Holder.direct(decoded.get()),modifiers);var placer=new FeaturePlacer(world,generator); + for(int repeat=0;repeat();boolean valid=true; + for(var json:f.getAsJsonArray("modifiers")) { + try {var decoded=PlacementModifier.CODEC.parse(JsonOps.INSTANCE,json).result();if(decoded.isPresent())modifiers.add(decoded.get());else valid=false;} + catch(IllegalArgumentException error){valid=false;} + } + if(!valid)out.println("decode error");else { + out.println("decode ok");int[] count={0};int fail=f.get("fail").getAsInt();boolean draw=f.get("draw").getAsBoolean();int mode=f.get("result").getAsInt(); + var feature=new Feature() { + public com.mojang.serialization.MapCodec codec(){return com.mojang.serialization.MapCodec.unit(this);} + public boolean place(WorldGenLevel level,ChunkGenerator generator,RandomSource rng,BlockPos p) { + if(count[0]++==fail)throw new Stop(); + out.println("feature "+p.getX()+" "+p.getY()+" "+p.getZ()); + long value=p.getX()+p.getY()+p.getZ();if(draw){value=rng.nextLong();out.println("consumer "+value);} + boolean result=mode==1||(mode==2&&(value&1)==0);out.println("result "+result);return result; + } + }; + var placed=new PlacedFeature(Holder.direct(feature),modifiers);var placer=new FeaturePlacer(context.getLevel(),context.generator()); + for(var value:f.getAsJsonArray("positions")) { + var p=value.getAsJsonArray();var position=new BlockPos(p.get(0).getAsInt(),p.get(1).getAsInt(),p.get(2).getAsInt());count[0]=0; + try {out.println("place "+placer.place(placed,random,position));}catch(Stop|IllegalArgumentException error){out.println("place error");} + out.println("next "+random.nextLong()); + } + } + out.println("tail "+random.nextLong()); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureRegionOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureRegionOracle.java new file mode 100644 index 000000000..a7831c06b --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureRegionOracle.java @@ -0,0 +1,97 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.*; +import net.minecraft.world.level.chunk.status.ChunkStatus; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.feature.Feature; +import net.minecraft.world.level.levelgen.placement.*; + +/** Native feature placement into resident ProtoChunks through a world transport. */ +public final class VanillaFeatureRegionOracle { + private static ProtoChunk chunk(Map chunks,int x,int z) { + var chunk=chunks.get(new ChunkPos(x>>4,z>>4));if(chunk==null)throw new IllegalArgumentException("missing region chunk");return chunk; + } + public static void main(String[] args) throws Exception { + if(args[0].equals("export")){VanillaHeightmapOracle.main(args);return;} + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + Path dir=Path.of(args[1]); + Holder biome=Holder.Reference.createStandAlone(new HolderOwner(){},Biomes.PLAINS); + var ids=new IdMapper>();ids.add(biome); + var factory=new PalettedContainerFactory(Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY),Blocks.AIR.defaultBlockState(),null,Strategy.createForBiomes(ids),biome,null); + VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(dir.resolve("tags.json"))).getAsJsonObject()); + var contextMethod=VanillaPlacementOracle.class.getDeclaredMethod("context",JsonObject.class);contextMethod.setAccessible(true); + var bounds=new JsonObject();bounds.add("context",JsonParser.parseString("[-64,64,0]")); + var generator=((PlacementContext)contextMethod.invoke(null,bounds)).generator(); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();long seed=f.get("seed").getAsLong(); + var features=new ArrayList(); + for(var value:f.getAsJsonArray("features"))features.add(Feature.DIRECT_CODEC.parse(JsonOps.INSTANCE,value).getOrThrow()); + RandomSource random=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + if(f.get("worldgen").getAsBoolean())random=new WorldgenRandom(random); + var chunks=new TreeMap(Comparator.comparingInt(p->p.x()).thenComparingInt(p->p.z())); + for(int cx=-1;cx<=1;cx++)for(int cz=-1;cz<=1;cz++) { + var cp=new ChunkPos(cx,cz);var chunk=new ProtoChunk(cp,UpgradeData.EMPTY,LevelHeightAccessor.create(-64,64),factory,null); + chunk.setPersistedStatus(f.get("stage").getAsString().equals("terrain")?ChunkStatus.TERRAIN:ChunkStatus.EMPTY); + for(int x=0;x<16;x++)for(int z=0;z<16;z++) { + chunk.setBlockState(new BlockPos((cx<<4)+x,-56,(cz<<4)+z),Blocks.STONE.defaultBlockState(),3); + if((x+z)%3!=0)chunk.setBlockState(new BlockPos((cx<<4)+x,-48,(cz<<4)+z),Blocks.DIRT.defaultBlockState(),3); + } + chunks.put(cp,chunk); + } + int[] calls={0};int fail=f.get("fail").getAsInt(),reject=f.get("reject").getAsInt(); + var world=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},(proxy,method,values)->switch(method.getName()) { + case "getMinY"->-64; + case "getSeaLevel"->0; + case "getHeight"->{ + if(values==null||values.length==0)yield 64; + var kind=(Heightmap.Types)values[0];int x=(Integer)values[1],z=(Integer)values[2];yield chunk(chunks,x,z).getHeight(kind,x&15,z&15)+1; + } + case "getMaxY","isInsideBuildHeight","isOutsideBuildHeight","setBlockAndUpdate"->InvocationHandler.invokeDefault(proxy,method,values); + case "getBlockState"->{var p=(BlockPos)values[0];yield chunk(chunks,p.getX(),p.getZ()).getBlockState(p);} + case "setBlock"->{ + var p=(BlockPos)values[0];var state=(BlockState)values[1];int flags=(Integer)values[2]; + out.println("write "+p.getX()+" "+p.getY()+" "+p.getZ()+" "+Block.getId(state)+" "+flags); + int call=calls[0]++;if(call==fail)throw new IllegalArgumentException("injected write failure"); + boolean result=reject==0||call%reject!=0; + if(result)chunk(chunks,p.getX(),p.getZ()).setBlockState(p,state,flags); + out.println("written "+result);yield result; + } + default->throw new AssertionError("unexpected world method "+method); + }); + var modifiers=new ArrayList();for(var value:f.getAsJsonArray("placement"))modifiers.add(PlacementModifier.CODEC.parse(JsonOps.INSTANCE,value).getOrThrow()); + var placer=new FeaturePlacer(world,generator); + for(int repeat=0;repeat<2;repeat++) { + for(var feature:features) { + calls[0]=0; + try {out.println("place "+placer.place(new PlacedFeature(Holder.direct(feature),modifiers),random,new BlockPos(15,-40,15)));}catch(RuntimeException error){out.println("place error");} + out.println("next "+random.nextLong()); + for(int[] p:new int[][]{{0,0},{15,15},{16,16},{-1,-1}})for(var kind:Heightmap.Types.values())out.println("height "+kind.name()+" "+p[0]+" "+p[1]+" "+(chunk(chunks,p[0],p[1]).getHeight(kind,p[0]&15,p[1]&15)+1)); + } + out.println("repeat "+repeat); + } + for(var entry:chunks.entrySet()) { + var cp=entry.getKey();var chunk=entry.getValue();out.println("chunk "+cp.x()+" "+cp.z()); + for(var kind:Heightmap.Types.values()) { + if(chunk.hasPrimedHeightmap(kind)){out.println("map "+kind.name());for(long word:chunk.getOrCreateHeightmapUnprimed(kind).getRawData())out.println(Long.toUnsignedString(word,16));} + else out.println("missing "+kind.name()); + } + for(int i=0;i<4;i++){out.println("section "+i);var section=chunk.getSection(i);for(int y=0;y<16;y++)for(int z=0;z<16;z++)for(int x=0;x<16;x++)out.println(Block.getId(section.getBlockState(x,y,z)));} + } + out.println("tail "+random.nextLong()); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureSortOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureSortOracle.java new file mode 100644 index 000000000..833ede52d --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureSortOracle.java @@ -0,0 +1,45 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.world.level.biome.FeatureSorter; +import net.minecraft.world.level.levelgen.feature.Feature; +import net.minecraft.world.level.levelgen.placement.PlacedFeature; + +/** Exercises identity-based native feature ordering, using equal dummy payloads. */ +public final class VanillaFeatureSortOracle { + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + var noop=Feature.DIRECT_CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString("{\"type\":\"no_op\"}")).getOrThrow(); + Path dir=Path.of(args[1]); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8));var inputs=Files.lines(dir.resolve("inputs.txt"))) { + for(var line:(Iterable)inputs::iterator) { + var f=JsonParser.parseString(line).getAsJsonObject(); + var identities=new HashMap();var names=new IdentityHashMap(); + java.util.function.IntFunction feature=id->identities.computeIfAbsent(id,key->{var value=new PlacedFeature(Holder.direct(noop),List.of());names.put(value,key);return value;}); + var biomes=new ArrayList>>(); + for(var b:f.getAsJsonArray("biomes")) { + var steps=new ArrayList>(); + for(var s:b.getAsJsonArray()) { + var values=new ArrayList>();for(var id:s.getAsJsonArray())values.add(Holder.direct(feature.apply(id.getAsInt()))); + steps.add(HolderSet.direct(values)); + } + biomes.add(steps); + } + try { + var steps=FeatureSorter.buildFeaturesPerStep(biomes,value->value,false); + out.println("steps "+steps.size()); + for(int i=0;i(Comparator.comparingInt(BlockPos::getX).thenComparingInt(BlockPos::getY).thenComparingInt(BlockPos::getZ)); + var world=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},(proxy,method,values)->{ + if(method.getName().equals("getMinY")) { + out.println("min");int call=calls[0]++;if(call==fail)throw new Stop(); + int minimum=f.get("world_min").getAsInt();out.println("minimum "+minimum);return minimum; + } + if(method.getName().equals("getHeight")&&(values==null||values.length==0))return 384; + if(method.getName().equals("getSeaLevel"))return 63; + if(method.getName().equals("setBlockAndUpdate"))return InvocationHandler.invokeDefault(proxy,method,values); + var p=((BlockPos)values[0]).immutable();int call=calls[0]++; + switch(method.getName()) { + case "getBlockState"->{ + out.println("get "+p.getX()+" "+p.getY()+" "+p.getZ());if(call==fail)throw new Stop(); + var state=states.getOrDefault(p,BLOCKS[Math.floorMod(p.getX()*31+p.getY()*7+p.getZ()*17,7)].defaultBlockState());out.println("state "+Block.getId(state));return state; + } + case "setBlock"->{ + var state=(BlockState)values[1];int flags=(Integer)values[2];out.println("set "+p.getX()+" "+p.getY()+" "+p.getZ()+" "+Block.getId(state)+" "+flags);if(call==fail)throw new Stop(); + boolean result=reject==0||call%reject!=0;if(result)states.put(p,state);out.println("written "+result);return result; + } + default->throw new AssertionError("unexpected world method "+method); + } + }); + var p=f.getAsJsonArray("origin");var origin=new BlockPos(p.get(0).getAsInt(),p.get(1).getAsInt(),p.get(2).getAsInt()); + for(int repeat=0;repeat0x100000000L) + throw new IllegalArgumentException("invalid float bit range"); + var sampler=new UnaryFunction.LogSampler(new DensitySampler() { + public float sampleValue(SamplerContext context,int x,int y,int z) {return Float.intBitsToFloat(x);} + public void sampleVolume(SamplerContext context,DensityBuffer buffer,DensityVolume volume) {throw new AssertionError("unexpected volume");} + }); + byte[] buffer=new byte[1<<20]; + try(var out=new BufferedOutputStream(System.out,1<<20)) { + while(remaining>0) { + int count=(int)Math.min(remaining,buffer.length/4); + for(int i=0;i>>24);buffer[at+1]=(byte)(bits>>>16); + buffer[at+2]=(byte)(bits>>>8);buffer[at+3]=(byte)bits; + } + out.write(buffer,0,count*4); + start+=count;remaining-=count; + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidOracle.java new file mode 100644 index 000000000..f3d7e32a7 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidOracle.java @@ -0,0 +1,45 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.material.FlowingFluid; +/** Original transport for native contained fluid state and height queries. */ +public final class VanillaFluidOracle { + private static final class Stop extends RuntimeException {} + public static void main(String[] args) throws Exception { + if(args[0].equals("export")){VanillaBlockStateCodecOracle.main(args);return;} + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + Path dir=Path.of(args[1]); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt")));var inputs=Files.lines(dir.resolve("inputs.txt"))) { + for(var first:BuiltInRegistries.FLUID)for(var second:BuiltInRegistries.FLUID) + out.println("family "+BuiltInRegistries.FLUID.getKey(first)+" "+BuiltInRegistries.FLUID.getKey(second)+" "+first.isSame(second)); + for(var block:Block.BLOCK_STATE_REGISTRY) { + var state=block.getFluidState();boolean falling=state.hasProperty(FlowingFluid.FALLING)&&state.getValue(FlowingFluid.FALLING); + out.println("state "+Block.getId(block)+" "+BuiltInRegistries.FLUID.getKey(state.getType())+" "+state.getAmount()+" "+falling+" "+state.isFull()+" "+state.isSource()+" "+Integer.toUnsignedString(Float.floatToRawIntBits(state.getOwnHeight()))+" "+Block.getId(state.createLegacyBlock())); + } + for(var line:(Iterable)inputs::iterator) { + var f=JsonParser.parseString(line).getAsJsonObject();var state=Block.stateById(f.get("state").getAsInt()).getFluidState(); + var above=Block.stateById(f.get("above").getAsInt()).getFluidState();int[] calls={0};int fail=f.get("fail").getAsInt(); + var world=(BlockGetter)Proxy.newProxyInstance(BlockGetter.class.getClassLoader(),new Class[]{BlockGetter.class},(proxy,method,values)->{ + var p=(BlockPos)values[0];boolean fluid=method.getName().equals("getFluidState"); + if(!fluid&&!method.getName().equals("getBlockState"))throw new AssertionError(method); + out.println((fluid?"fluid ":"block ")+p.getX()+" "+p.getY()+" "+p.getZ()); + if(calls[0]++==fail)throw new Stop(); + return fluid?above:(f.get("sturdy").getAsBoolean()?Blocks.STONE:Blocks.AIR).defaultBlockState(); + }); + var xyz=f.getAsJsonArray("position");var p=new BlockPos(xyz.get(0).getAsInt(),xyz.get(1).getAsInt(),xyz.get(2).getAsInt()); + for(boolean camera:new boolean[]{false,true}) { + try {float height=camera?state.getHeightForCamera(world,p):state.getHeight(world,p);out.println("height "+Integer.toUnsignedString(Float.floatToRawIntBits(height)));} + catch(Stop error){out.println("height error");} + } + out.println("calls "+calls[0]); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGeometryOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGeometryOracle.java new file mode 100644 index 000000000..4241b656b --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGeometryOracle.java @@ -0,0 +1,218 @@ +package dev.horizonlab.parity; + +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.server.Bootstrap; +import net.minecraft.world.entity.Entity; +import net.minecraft.util.Mth; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.phys.*; +import net.minecraft.world.phys.shapes.*; + +/** Original I/O adapter. Every geometry calculation invokes the pinned vanilla classes. */ +public final class VanillaGeometryOracle { + private static final Constructor ARRAY; + private static final Method INDEX; + private static final Method MOTION, STEP, COLLIDE, ALLOCATE; + private static final Object ALLOCATOR; + static { + try { + ARRAY = ArrayVoxelShape.class.getDeclaredConstructor(DiscreteVoxelShape.class, double[].class, double[].class, double[].class); + ARRAY.setAccessible(true); + INDEX = VoxelShape.class.getDeclaredMethod("findIndex", Direction.Axis.class, double.class); + INDEX.setAccessible(true); + MOTION = Entity.class.getDeclaredMethod("collideWithShapes", Vec3.class, AABB.class, List.class); MOTION.setAccessible(true); + STEP = Entity.class.getDeclaredMethod("collectCandidateStepUpHeights", AABB.class, List.class, float.class, float.class); STEP.setAccessible(true); + COLLIDE = Entity.class.getDeclaredMethod("collide", Vec3.class); COLLIDE.setAccessible(true); + Class allocator = Class.forName("sun.misc.Unsafe"); + Field field = allocator.getDeclaredField("theUnsafe"); field.setAccessible(true); + ALLOCATOR = field.get(null); ALLOCATE = allocator.getMethod("allocateInstance", Class.class); + } catch (ReflectiveOperationException error) { throw new ExceptionInInitializerError(error); } + } + private static final class Input { + final String[] words; int cursor = 1; + Input(String line) { words = line.split(" "); } + String word() { return words[cursor++]; } + int integer() { return Integer.parseInt(word()); } + double number() { return Double.longBitsToDouble(Long.parseUnsignedLong(word(), 16)); } + Vec3 vector() { return new Vec3(number(), number(), number()); } + AABB box() { return new AABB(vector(), vector()); } + BlockPos pos() { return new BlockPos(integer(), integer(), integer()); } + } + private final PrintWriter out; + private final List shapes = new ArrayList<>(); + private VanillaGeometryOracle(PrintWriter out) { this.out = out; } + private void values(String label, double... values) { out.print(label); for (double v : values) out.printf(" %016x", Double.doubleToLongBits(v)); out.println(); } + private void vector(String label, Vec3 v) { values(label, v.x, v.y, v.z); } + private void box(String label, AABB b) { values(label, b.minX, b.minY, b.minZ, b.maxX, b.maxY, b.maxZ); } + private void point(String label, Optional p) { if (p.isPresent()) vector(label, p.get()); else out.println(label + " none"); } + private void hit(BlockHitResult h) { if (h == null) out.println("hit none"); else { BlockPos p = h.getBlockPos(); Vec3 v = h.getLocation(); out.printf("hit %d %d %d %d %d %016x %016x %016x%n", h.getDirection().ordinal(), h.isInside() ? 1 : 0, p.getX(), p.getY(), p.getZ(), Double.doubleToLongBits(v.x), Double.doubleToLongBits(v.y), Double.doubleToLongBits(v.z)); } } + private static int flag(boolean v) { return v ? 1 : 0; } + // These fixtures only provide caller-controlled shape lists and entity + // inputs. The private vanilla Entity.collide method performs every movement + // and step decision. Allocation avoids starting a world/server or invoking + // entity lifecycle logic unrelated to this geometry comparison. + private static final class StepBorder extends net.minecraft.world.level.border.WorldBorder { + VoxelShape shape; + @Override public boolean isInsideCloseToBorder(Entity entity, AABB box) { return shape != null; } + @Override public VoxelShape getCollisionShape() { return shape; } + } + private static final class StepLevel extends net.minecraft.server.level.ServerLevel { + VanillaGeometryOracle oracle; + StepBorder border; + List entities, initial, stepping; + int queries; + private StepLevel() { super(null, null, null, null, null, null, false, 0L, List.of(), false); } + @Override public net.minecraft.world.level.border.WorldBorder getWorldBorder() { return border; } + @Override public List getEntityCollisions(Entity entity, AABB query) { oracle.box("entity-query", query); return entities; } + @Override public Iterable getBlockCollisions(Entity entity, AABB query) { oracle.box("block-query", query); return queries++ == 0 ? initial : stepping; } + } + private static final class StepEntity extends net.minecraft.world.entity.decoration.ArmorStand { + float step; + boolean grounded; + private StepEntity() { super(null, null); } + @Override public float maxUpStep() { return step; } + @Override public boolean onGround() { return grounded; } + void configure(StepLevel level, AABB box, float step, boolean grounded) { setLevel(level); setBoundingBox(box); this.step = step; this.grounded = grounded; } + } + private List selected(Input in) { + int count = in.integer(); List selected = new ArrayList<>(count); + for (int i = 0; i < count; i++) selected.add(shapes.get(in.integer())); + return selected; + } + private void positions(String label, Iterable positions, int limit) { + int count = 0; Iterator iterator = positions.iterator(); + while (count < limit && iterator.hasNext()) { BlockPos pos = iterator.next(); out.printf("%s %d %d %d%n", label, pos.getX(), pos.getY(), pos.getZ()); count++; } + out.printf("%s-count %d%n", label, count); + } + private void emitShape(VoxelShape shape) { + values("axis-extrema",shape.min(Direction.Axis.X),shape.min(Direction.Axis.Y),shape.min(Direction.Axis.Z),shape.max(Direction.Axis.X),shape.max(Direction.Axis.Y),shape.max(Direction.Axis.Z)); + List boxes=shape.toAabbs();out.printf("shape %d %d%n",shapes.size(),boxes.size());int cubeAxes=0; + for(Direction.Axis axis:Direction.Axis.values())if(shape.getCoords(axis) instanceof CubePointRange)cubeAxes|=1< { + VoxelShape shape = shapes.get(in.integer()), below = shapes.get(in.integer()); int[] calls = {0}; + values("floor-height", net.minecraft.world.level.EmptyBlockGetter.INSTANCE.getBlockFloorHeight(shape, () -> { calls[0]++; return below; })); + out.printf("below-calls %d%n", calls[0]); + } + case "block-iterate" -> { + BlockPos a = in.pos(), b = in.pos(); Vec3 movement = in.vector(); int limit = in.integer(); + positions("closed", BlockPos.betweenClosed(a, b), limit); + positions("direction", BlockPos.betweenCornersInDirection(a, b, movement), limit); + } + case "box-iterate" -> { + AABB box = in.box(); Vec3 movement = in.vector(); int limit = in.integer(); + positions("closed", BlockPos.betweenClosed(box), limit); + positions("direction", BlockPos.betweenCornersInDirection(box, movement), limit); + } + case "sweep" -> { + Vec3 start = in.vector(), end = in.vector(); AABB box = in.box(); int stop = in.integer(); int[] count = {0}; + boolean completed = BlockGetter.forEachBlockIntersectedBetween(start, end, box, (pos, step) -> { count[0]++; out.printf("block-visit %d %d %d %d%n", pos.getX(), pos.getY(), pos.getZ(), step); return count[0] != stop; }); + out.printf("sweep %d %d%n", flag(completed), count[0]); + } + case "step-motion" -> { + AABB box = in.box(); Vec3 movement = in.vector(); float maxStep = (float)in.number(); boolean grounded = in.integer() != 0; + StepLevel level = (StepLevel)ALLOCATE.invoke(ALLOCATOR, StepLevel.class); + level.oracle = this; level.entities = selected(in); level.initial = selected(in); level.stepping = selected(in); + int border = in.integer(); level.border = new StepBorder(); level.border.shape = border < 0 ? null : shapes.get(border); + StepEntity entity = (StepEntity)ALLOCATE.invoke(ALLOCATOR, StepEntity.class); entity.configure(level, box, maxStep, grounded); + vector("step-motion", (Vec3)COLLIDE.invoke(entity, movement)); + out.printf("block-queries %d%n", level.queries); + } + case "make-box" -> emitShape(Shapes.create(in.box())); + case "optimize" -> emitShape(shapes.get(in.integer()).optimize()); + case "join", "join-optimized" -> { + VoxelShape a=shapes.get(in.integer()),b=shapes.get(in.integer());int bits=in.integer();BooleanOp op=(first,second)->(bits&(1<<((first?2:0)+(second?1:0))))!=0; + if((bits&1)!=0) { + try {Shapes.joinUnoptimized(a,b,op);throw new AssertionError("accepted unbounded Boolean");}catch(IllegalArgumentException expected){out.println("join invalid");} + }else{ + VoxelShape shape=operation.equals("join")?Shapes.joinUnoptimized(a,b,op):Shapes.join(a,b,op);out.printf("overlap %d%n",flag(Shapes.joinIsNotEmpty(a,b,op)));emitShape(shape); + } + } + case "traverse" -> { + Vec3 start=in.vector(),end=in.vector();int stop=in.integer();int[] count={0}; + BlockPos result=BlockGetter.traverseBlocks(start,end,stop,(context,pos)->{count[0]++;out.printf("visit %d %d %d%n",pos.getX(),pos.getY(),pos.getZ());if(count[0]==context)return pos;return null;},context->null); + if(result==null)out.printf("traverse none %d%n",count[0]);else out.printf("traverse %d %d %d %d%n",result.getX(),result.getY(),result.getZ(),count[0]); + } + case "trig-table" -> { + Field field=Mth.class.getDeclaredField("SIN");field.setAccessible(true);float[] table=(float[])field.get(null); + for(int i=0;i { + Vec3 v=in.vector();double angle=in.number();float pitch=(float)in.number(),yaw=(float)in.number();int axes=in.integer();Direction.Axis axis=Direction.Axis.values()[in.integer()];Direction direction=Direction.values()[in.integer()];double amount=in.number(); + values("trig",Mth.sin(angle),Mth.cos(angle));vector("rotate-x",v.xRot((float)angle));vector("rotate-y",v.yRot((float)angle));vector("rotate-z",v.zRot((float)angle));vector("clockwise",v.rotateClockwise90());vector("look",Vec3.directionFromRotation(pitch,yaw)); + Vec2 rotation=v.rotation();values("rotation",rotation.x,rotation.y); + EnumSet selected=EnumSet.noneOf(Direction.Axis.class);for(Direction.Axis a:Direction.Axis.values())if((axes&(1< { + Vec3 a = in.vector(), b = in.vector(); double t = in.number(); + vector("add", a.add(b)); vector("subtract", a.subtract(b)); vector("vector-to", a.vectorTo(b)); vector("multiply", a.multiply(b)); vector("scale", a.scale(t)); vector("normalize", a.normalize()); vector("cross", a.cross(b)); vector("lerp", a.lerp(b, t)); vector("projected", a.projectedOn(b)); vector("reverse", a.reverse()); vector("horizontal", a.horizontal()); + values("scalar", a.dot(b), a.lengthSqr(), a.length(), a.horizontalDistanceSqr(), a.horizontalDistance(), a.distanceToSqr(b), a.distanceTo(b)); + out.printf("flags %d %d %d %d%n", flag(a.equals(b)), flag(a.isFinite()), flag(a.closerThan(b, t)), Direction.getApproximateNearest(a).ordinal()); + var order = Direction.axisStepOrder(a); out.printf("order %d %d %d%n", order.get(0).ordinal(), order.get(1).ordinal(), order.get(2).ordinal()); + } + case "box" -> { + AABB a = in.box(), b = in.box(); Vec3 start = in.vector(), end = in.vector(), amount = in.vector(); Direction.Axis axis = Direction.Axis.values()[in.integer()]; double value = in.number(); + box("bounds", a); box("move", a.move(amount)); box("inflate", a.inflate(amount.x, amount.y, amount.z)); box("deflate", a.deflate(amount.x, amount.y, amount.z)); box("contract", a.contract(amount.x, amount.y, amount.z)); box("expand", a.expandTowards(amount)); box("intersect", a.intersect(b)); box("union", a.minmax(b)); box("next", a.nextDeflated()); + box("set-min", switch(axis) { case X -> a.setMinX(value); case Y -> a.setMinY(value); case Z -> a.setMinZ(value); }); + box("set-max", switch(axis) { case X -> a.setMaxX(value); case Y -> a.setMaxY(value); case Z -> a.setMaxZ(value); }); + box("of-size", AABB.ofSize(start, amount.x, amount.y, amount.z)); box("unit", AABB.unitCubeFromLowerCorner(start)); + vector("center", a.getCenter()); vector("bottom", a.getBottomCenter()); vector("size", new Vec3(a.getXsize(), a.getYsize(), a.getZsize())); + values("distance", a.getSize(), a.distanceToSqr(start), a.distanceToSqr(b)); + out.printf("flags %d %d %d %d%n", flag(a.intersects(b)), flag(a.contains(start)), flag(a.hasNaN()), flag(a.collidedAlongVector(amount, List.of(b)))); + point("clip", a.clip(start, end)); hit(AABB.clip(List.of(a, b), start, end, BlockPos.ZERO)); + } + case "block-box" -> { BlockPos a = in.pos(), b = in.pos(); box("block", new AABB(a)); box("encapsulate", AABB.encapsulatingFullBlocks(a, b)); } + case "grid" -> { + boolean cube = in.integer() != 0; int nx = in.integer(), ny = in.integer(), nz = in.integer(); + double[] xs = new double[nx + 1], ys = new double[ny + 1], zs = new double[nz + 1]; + for (double[] coords : new double[][] {xs, ys, zs}) for (int i = 0; i < coords.length; i++) coords[i] = in.number(); + String occupied = in.word(); BitSetDiscreteVoxelShape discrete = new BitSetDiscreteVoxelShape(nx, ny, nz); + for (int x = 0; x < nx; x++) for (int y = 0; y < ny; y++) for (int z = 0; z < nz; z++) if (occupied.charAt((x * ny + y) * nz + z) == '1') discrete.fill(x, y, z); + VoxelShape shape = cube ? new CubeVoxelShape(discrete) : ARRAY.newInstance(discrete, xs, ys, zs); + List boxes = shape.toAabbs(); out.printf("shape %d %d%n", shapes.size(), boxes.size()); + values("axis-extrema",shape.min(Direction.Axis.X),shape.min(Direction.Axis.Y),shape.min(Direction.Axis.Z),shape.max(Direction.Axis.X),shape.max(Direction.Axis.Y),shape.max(Direction.Axis.Z)); + if (shape.isEmpty()) out.println("shape-bounds none"); else box("shape-bounds", shape.bounds()); + for (AABB b : boxes) box("part", b); shapes.add(shape); + } + case "query" -> { + VoxelShape shape = shapes.get(in.integer()); AABB b = in.box(); Vec3 start = in.vector(), end = in.vector(), p = in.vector(); BlockPos block = in.pos(); Direction.Axis axis = Direction.Axis.values()[in.integer()]; double amount = in.number(); + values("column", shape.min(axis, p.x, p.y), shape.max(axis, p.x, p.y)); + values("collide", shape.collide(axis, b, amount)); hit(shape.clip(start, end, block)); point("closest", shape.closestPointTo(p)); + out.printf("index %d %d %d%n", INDEX.invoke(shape, Direction.Axis.X, p.x), INDEX.invoke(shape, Direction.Axis.Y, p.y), INDEX.invoke(shape, Direction.Axis.Z, p.z)); + } + case "many" -> { + AABB b = in.box(); Direction.Axis axis = Direction.Axis.values()[in.integer()]; double amount = in.number(); int count = in.integer(); List selected = new ArrayList<>(); + for (int i = 0; i < count; i++) selected.add(shapes.get(in.integer())); values("many", Shapes.collide(axis, b, selected, amount)); + } + case "motion" -> { + AABB b = in.box(); Vec3 movement = in.vector(); float maxStep = (float)in.number(), currentY = (float)in.number(); int count = in.integer(); List selected = new ArrayList<>(); + for (int i = 0; i < count; i++) selected.add(shapes.get(in.integer())); + vector("motion", (Vec3)MOTION.invoke(null,movement,b,selected)); + float[] candidates = (float[])STEP.invoke(null,b,selected,maxStep,currentY); + out.printf("steps %d",candidates.length); for(float height:candidates)out.printf(" %08x",Float.floatToIntBits(height)); out.println(); + } + default -> throw new IllegalArgumentException(operation); + } + if (in.cursor != in.words.length) throw new AssertionError("trailing input"); + } + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); Bootstrap.bootStrap(); + try (BufferedReader input = Files.newBufferedReader(Path.of(args[0])); PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])))) { + VanillaGeometryOracle oracle = new VanillaGeometryOracle(out); int lineNumber = 0; + for (String line; (line = input.readLine()) != null;) oracle.command(line, ++lineNumber); + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightProviderOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightProviderOracle.java new file mode 100644 index 000000000..b3fb18aff --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightProviderOracle.java @@ -0,0 +1,32 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.heightproviders.HeightProvider; + +/** Original transport calling native height-provider codecs and samples. */ +public final class VanillaHeightProviderOracle { + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); + var contextMethod=VanillaAnchorOracle.class.getDeclaredMethod("context",JsonObject.class);contextMethod.setAccessible(true); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();long seed=f.get("seed").getAsLong(); + var context=(WorldGenerationContext)contextMethod.invoke(null,f); + RandomSource random=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + com.mojang.serialization.DataResult decoded; + try {decoded=HeightProvider.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(f.get("definition").getAsString()));} catch(IllegalArgumentException error) {out.println("decode error");out.println("tail "+random.nextLong());continue;} + int count=f.get("samples").getAsInt(); + if(decoded.result().isEmpty())out.println("decode error");else { + var provider=decoded.result().get();out.println("decode ok"); + for(int i=0;i(BuiltInRegistries.BLOCK.keySet())) + defaults.addProperty(id.toString(),Block.getId(BuiltInRegistries.BLOCK.getValue(id).defaultBlockState())); + result.add("states",states);result.add("defaults",defaults);return result; + } + static void bindTags(JsonObject resources) { + var registry=BuiltInRegistries.BLOCK; + var loader=new TagLoader>((id,required)->registry.get(id).map(value->(Holder)value),"tags/block"); + var definitions=new HashMap>(); + for(var item:resources.entrySet()) { + var file=TagFile.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(item.getValue().getAsString())).getOrThrow(); + var entries=new ArrayList(); + for(var entry:file.entries())entries.add(new TagLoader.EntryWithSource(entry,"vanilla")); + definitions.put(Identifier.parse(item.getKey()),entries); + } + var tags=new HashMap,List>>(); + loader.build(definitions).forEach((id,values)->tags.put(TagKey.create(Registries.BLOCK,id),List.copyOf(values))); + if(tags.size()!=resources.size())throw new AssertionError("incomplete block tags"); + registry.prepareTagReload(new TagLoader.LoadResult<>(Registries.BLOCK,tags)).apply(); + } + private static final class Chunk extends ProtoChunk { + final List reads=new ArrayList<>(); + final boolean trace; + Chunk(int min,int height,boolean trace) { + super(new ChunkPos(0,0),UpgradeData.EMPTY,LevelHeightAccessor.create(min,height),factory,null); + this.trace=trace; + } + @Override public BlockState getBlockState(BlockPos pos) { + var state=super.getBlockState(pos); + if(trace)reads.add("read "+pos.getX()+" "+pos.getY()+" "+pos.getZ()+" "+Block.getId(state)); + return state; + } + void write(int x,int y,int z,int id) { + getSection(getSectionIndex(y)).setBlockState(x&15,y&15,z&15,Block.stateById(id),false); + } + } + private static void fixture(JsonObject input,PrintWriter out) { + int min=input.get("min").getAsInt(),height=input.get("height").getAsInt(); + var chunk=new Chunk(min,height,input.get("trace").getAsBoolean()); + out.println("chunk "+min+" "+height); + for(var item:input.getAsJsonArray("initial")) { + var a=item.getAsJsonArray();chunk.write(a.get(0).getAsInt(),a.get(1).getAsInt(),a.get(2).getAsInt(),a.get(3).getAsInt()); + } + for(var type:TYPES)chunk.getOrCreateHeightmapUnprimed(type); + for(var item:input.getAsJsonArray("ops")) { + var a=item.getAsJsonArray();String op=a.get(0).getAsString(); + switch(op) { + case "set" -> { + int x=a.get(1).getAsInt(),y=a.get(2).getAsInt(),z=a.get(3).getAsInt(),id=a.get(4).getAsInt(),mask=a.get(5).getAsInt(); + chunk.write(x,y,z,id); + for(int t=0;t { + int x=a.get(1).getAsInt(),y=a.get(2).getAsInt(),z=a.get(3).getAsInt(),id=a.get(4).getAsInt(),t=a.get(5).getAsInt(); + try {out.println("update "+t+" "+chunk.getOrCreateHeightmapUnprimed(TYPES[t]).update(x,y,z,Block.stateById(id)));} + catch(RuntimeException e){out.println("update "+t+" error");} + } + case "prime" -> { + var selected=EnumSet.noneOf(Heightmap.Types.class);int mask=a.get(1).getAsInt(); + for(int t=0;t { + int t=a.get(1).getAsInt();var words=a.get(2).getAsJsonArray();long[] data=new long[words.size()]; + for(int i=0;i { + int x=a.get(1).getAsInt(),z=a.get(2).getAsInt(); + for(int t=0;t { + out.println("highest_section "+chunk.getHighestSectionPosition()); + for(int t=0;t throw new IllegalArgumentException(op); + } + for(String read:chunk.reads)out.println(read);chunk.reads.clear(); + } + } + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion();Bootstrap.bootStrap(); + Path directory=Path.of(args[1]); + if(args[0].equals("export")) { + Files.writeString(directory,new Gson().toJson(facts()),StandardCharsets.UTF_8);return; + } + Holder biome=Holder.Reference.createStandAlone(new HolderOwner(){},Biomes.PLAINS); + var ids=new IdMapper>();ids.add(biome); + // Only in-memory section storage is exercised; biome and section codecs are not invoked. + factory=new PalettedContainerFactory(Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY),Blocks.AIR.defaultBlockState(),null,Strategy.createForBiomes(ids),biome,null); + bindTags(JsonParser.parseString(Files.readString(directory.resolve("tags.json"))).getAsJsonObject()); + try(var out=new PrintWriter(Files.newBufferedWriter(directory.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(int t=0;t noises; + private static MappedRegistry definitions; + private static MappedRegistry biomes; + private static RegistryOps ops; + private static MappedRegistry densities; + private static HolderGetter densityLookup; + private static MappedRegistry ruleDefinitions; + private static HolderGetter ruleLookup; + private static JsonElement canonical(JsonElement value) { + if(value.isJsonObject()) {var result=new JsonObject();for(var e:new TreeMap<>(value.getAsJsonObject().asMap()).entrySet())result.add(e.getKey(),canonical(e.getValue()));return result;} + if(value.isJsonArray()){var result=new JsonArray();for(var e:value.getAsJsonArray())result.add(canonical(e));return result;} + if(value.isJsonPrimitive() && value.getAsJsonPrimitive().isNumber())return new JsonPrimitive("number:"+Long.toUnsignedString(Double.doubleToLongBits(value.getAsDouble()),16)); + return value; + } + private static String encode(MaterialCondition value) {return MaterialCondition.CODEC.encodeStart(ops,value).result().map(v->canonical(v).toString()).orElse("error");} + @SuppressWarnings("unchecked") + private static RegistryOps conditionOps(HolderGetter lookup) { + return RegistryOps.create(JsonOps.INSTANCE,new RegistryOps.RegistryInfoLookup(){ + public Optional> lookup(ResourceKey> key){ + if(key.equals(Registries.NOISE))return (Optional>)(Optional)Optional.of(noises); + if(key.equals(Registries.DENSITY_FUNCTION))return (Optional>)(Optional)Optional.ofNullable(densityLookup); + if(key.equals(Registries.MATERIAL_RULE))return (Optional>)(Optional)Optional.ofNullable(ruleLookup); + if(key.equals(Registries.BIOME))return (Optional>)(Optional)Optional.of(biomes); + if(key.equals(Registries.MATERIAL_CONDITION))return (Optional>)(Optional)Optional.of(lookup); + return Optional.empty(); + } + }); + } + private static void loadBiomes(Path dir) throws Exception { + biomes=new MappedRegistry<>(Registries.BIOME,Lifecycle.stable()); + var climate=VanillaBiomeTemperatureOracle.class.getDeclaredMethod("climate",JsonObject.class);climate.setAccessible(true); + var make=VanillaBiomeTemperatureOracle.class.getDeclaredMethod("make",Object.class);make.setAccessible(true); + var definitions=JsonParser.parseString(Files.readString(dir.resolve("biomes.json"))).getAsJsonObject(); + for(var e:definitions.entrySet()) { + var f=new JsonObject();f.addProperty("json",e.getValue().getAsString()); + var biome=(Biome)make.invoke(null,climate.invoke(null,f)); + biomes.register(ResourceKey.create(Registries.BIOME,Identifier.parse(e.getKey())),biome,RegistrationInfo.BUILT_IN); + } + biomes.freeze(); + var tagResources=JsonParser.parseString(Files.readString(dir.resolve("biome_tags.json"))).getAsJsonObject(); + var loader=new TagLoader>((id,required)->biomes.get(id).map(value->(Holder)value),"tags/worldgen/biome"); + var tags=new HashMap>(); + for(var e:tagResources.entrySet()) { + var file=TagFile.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(e.getValue().getAsString())).getOrThrow(); + var entries=new ArrayList();for(var entry:file.entries())entries.add(new TagLoader.EntryWithSource(entry,"vanilla")); + tags.put(Identifier.parse(e.getKey()),entries); + } + var resolved=new HashMap,List>>(); + loader.build(tags).forEach((id,values)->resolved.put(TagKey.create(Registries.BIOME,id),List.copyOf(values))); + if(resolved.size()!=tagResources.size())throw new AssertionError("unresolved biome tags"); + biomes.prepareTagReload(new TagLoader.LoadResult<>(Registries.BIOME,resolved)).apply(); + } + private static Holder biome(String name) {return biomes.getOrThrow(ResourceKey.create(Registries.BIOME,Identifier.parse(name)));} + private static String test(ConditionEvaluator condition) {try{return Boolean.toString(condition.test());}catch(RuntimeException error){return "error";}} + private static void loadConditions(Path dir) throws Exception { + definitions=new MappedRegistry<>(Registries.MATERIAL_CONDITION,Lifecycle.stable()); + ops=conditionOps(definitions.createRegistrationLookup()); + var data=JsonParser.parseString(Files.readString(dir.resolve("conditions.json"))).getAsJsonObject(); + for(var e:new TreeMap<>(data.asMap()).entrySet())definitions.register(ResourceKey.create(Registries.MATERIAL_CONDITION,Identifier.parse(e.getKey())),MaterialCondition.DIRECT_CODEC.parse(ops,JsonParser.parseString(e.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN); + definitions.freeze();ops=conditionOps(definitions); + } + private static void loadRules(Path dir) throws Exception { + if(!Files.exists(dir.resolve("rules.json")))return; + densities=new MappedRegistry<>(Registries.DENSITY_FUNCTION,Lifecycle.stable());densityLookup=densities.createRegistrationLookup(); + var densityJson=JsonParser.parseString(Files.readString(dir.resolve("densities.json"))).getAsJsonObject(); + for(var e:new TreeMap<>(densityJson.asMap()).entrySet())densities.register(ResourceKey.create(Registries.DENSITY_FUNCTION,Identifier.parse(e.getKey())),DensityFunctions.DIRECT_CODEC.parse(ops,JsonParser.parseString(e.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN); + densities.freeze();densityLookup=densities; + ruleDefinitions=new MappedRegistry<>(Registries.MATERIAL_RULE,Lifecycle.stable());ruleLookup=ruleDefinitions.createRegistrationLookup(); + var data=JsonParser.parseString(Files.readString(dir.resolve("rules.json"))).getAsJsonObject(); + for(var e:new TreeMap<>(data.asMap()).entrySet())ruleDefinitions.register(ResourceKey.create(Registries.MATERIAL_RULE,Identifier.parse(e.getKey())),MaterialRule.DIRECT_CODEC.parse(ops,JsonParser.parseString(e.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN); + ruleDefinitions.freeze();ruleLookup=ruleDefinitions; + } + private static VerticalAnchor anchor(JsonElement e) { + var a=e.getAsJsonArray();int v=a.get(1).getAsInt(); + return switch(a.get(0).getAsInt()) {case 0->VerticalAnchor.absolute(v);case 1->VerticalAnchor.aboveBottom(v);case 2->VerticalAnchor.belowTop(v);case 3->VerticalAnchor.relativeToSeaLevel(v);default->throw new AssertionError();}; + } + private static MaterialCondition condition(JsonElement e) { + var a=e.getAsJsonArray();return switch(a.get(0).getAsString()) { + case "temperature"->TemperatureCondition.INSTANCE; + case "above"->AbovePreliminarySurfaceCondition.INSTANCE; + case "biome"->{var selected=new ArrayList>();for(var name:a.get(1).getAsJsonArray())selected.add(biome(name.getAsString()));yield new BiomeCondition(HolderSet.direct(selected));} + case "noise"->new NoiseThresholdCondition(ResourceKey.create(Registries.NOISE,Identifier.parse(a.get(1).getAsString())),Double.longBitsToDouble(Long.parseUnsignedLong(a.get(2).getAsString(),16)),Double.longBitsToDouble(Long.parseUnsignedLong(a.get(3).getAsString(),16)),a.get(4).getAsBoolean()); + case "json"->MaterialCondition.CODEC.parse(ops,JsonParser.parseString(a.get(1).getAsString())).getOrThrow(); + case "hole"->HoleCondition.INSTANCE; + case "steep"->SteepCondition.INSTANCE; + case "y"->new YCondition(anchor(a.get(1)),a.get(2).getAsInt(),a.get(3).getAsBoolean()); + case "water"->new WaterCondition(a.get(1).getAsInt(),a.get(2).getAsInt(),a.get(3).getAsBoolean()); + case "stone"->new StoneDepthCondition(a.get(1).getAsInt(),a.get(2).getAsBoolean(),a.get(3).getAsInt(),a.get(4).getAsBoolean()?CaveSurface.CEILING:CaveSurface.FLOOR); + case "gradient"->new VerticalGradientCondition(Identifier.parse(a.get(1).getAsString()),anchor(a.get(2)),anchor(a.get(3))); + case "not"->new NotCondition(condition(a.get(1))); + default->throw new AssertionError("unknown condition "+a); + }; + } + private static BlockState[] BLOCKS; + private static DensityFunction[] oreFunctions; + private static int label(BlockState state){if(ruleDefinitions!=null)return net.minecraft.world.level.block.Block.getId(state);for(int i=0;inew BlockRule(BLOCKS[a.get(1).getAsInt()]); + case "band"->BandlandsRule.INSTANCE; + case "ore"->new OreVeinRule(BLOCKS[7],BLOCKS[8],BLOCKS[9],Float.intBitsToFloat(Integer.parseUnsignedInt(a.get(1).getAsString(),16)),oreFunctions[0],oreFunctions[1],oreFunctions[2]); + case "if"->new ConditionRule(condition(a.get(1)),rule(a.get(2))); + case "sequence"->{var rules=new ArrayList();for(var child:a.get(1).getAsJsonArray())rules.add(rule(child));yield new SequenceRule(rules);} + default->throw new AssertionError("unknown rule "+a); + }; + } + @SuppressWarnings("unchecked") + private static void fixture(JsonObject f,PrintWriter out) throws Exception { + long seed=f.get("seed").getAsLong();boolean legacy=f.get("legacy").getAsBoolean(); + var zero=DensityFunctions.zero();var router=new NoiseRouter(zero,zero,zero,zero,zero,zero,zero,zero); + var random=RandomState.create(noises,seed,legacy,Blocks.STONE.defaultBlockState(),63,router);var system=random.surfaceSystem(); + int[] depth={0};float[] secondary={0}; + if(!f.has("real_noise")||!f.get("real_noise").getAsBoolean()) { + var noiseField=RandomState.class.getDeclaredField("noiseInstances");noiseField.setAccessible(true); + var noiseCache=(Map,Noise>)noiseField.get(random); + for(var key:noises.registryKeySet())noiseCache.put(key,new Noise(){ + public net.minecraft.util.Interval range(){return net.minecraft.util.Interval.INFINITE;} + public float get(double x,double z){throw new AssertionError("unexpected 2D noise call");} + public float get(double x,double y,double z){out.println("noise query "+key.identifier()+" "+(int)x+" "+(int)y+" "+(int)z);return secondary[0];} + }); + } + Noise noise=new Noise() { + public net.minecraft.util.Interval range(){return net.minecraft.util.Interval.INFINITE;} + public float get(double x,double z){throw new AssertionError("unexpected 2D lookup");} + public float get(double x,double y,double z){if(y!=0)throw new AssertionError("unexpected secondary Y");out.println("secondary query "+(int)x+" "+(int)z);return secondary[0];} + }; + var secondaryField=MaterialSystem.class.getDeclaredField("surfaceSecondaryNoise");secondaryField.setAccessible(true);secondaryField.set(system,noise); + var getContext=VanillaAnchorOracle.class.getDeclaredMethod("context",JsonObject.class);getContext.setAccessible(true); + var generation=(WorldGenerationContext)getContext.invoke(null,f); + var ctor=MaterialRuleContext.class.getDeclaredConstructors()[0];ctor.setAccessible(true); + String[] currentBiome={"minecraft:plains"}; + Function> biomeGetter=pos->{ + out.println("biome query "+pos.getX()+" "+pos.getY()+" "+pos.getZ()); + if(currentBiome[0]==null)return null; + if(currentBiome[0].equals("#throw"))throw new IllegalStateException("fixture biome lookup failure"); + return biome(currentBiome[0]); + }; + Set> possible=null; + if(f.has("possible_biomes")&&!f.get("possible_biomes").isJsonNull()){possible=new HashSet<>();for(var name:f.getAsJsonArray("possible_biomes"))possible.add(biome(name.getAsString()));} + float[] density={0}; int[] remaining={-1}; + DensitySampler sampler=new DensitySampler(){ + public float sampleValue(SamplerContext c,int x,int y,int z){ + out.println("density query "+x+" "+y+" "+z); + if(remaining[0]==0)throw new IllegalStateException("fixture density failure"); + if(remaining[0]>0)remaining[0]--; + return density[0]; + } + public void sampleVolume(SamplerContext c,DensityBuffer b,DensityVolume v){ + out.println("density volume "+v.sizeX()+" "+v.sizeY()+" "+v.sizeZ()+" "+v.minBlockX()+" "+v.minBlockY()+" "+v.minBlockZ()+" "+v.stepBlockX()+" "+v.stepBlockY()+" "+v.stepBlockZ()); + DensitySampler.sampleVolumeNaive(c,b,v,this); + } + }; + oreFunctions=new DensityFunction[]{DensityFunctions.constant(12345),DensityFunctions.constant(12346),DensityFunctions.constant(12347)}; + float[] oreValues={1,1,-1};int[] oreRemaining={-1,-1,-1}; + if(f.has("ore_values"))for(int i=0;i<3;i++)oreValues[i]=Float.intBitsToFloat(Integer.parseUnsignedInt(f.getAsJsonArray("ore_values").get(i).getAsString(),16)); + var oreSamplers=new DensitySampler[3]; + for(int id=0;id<3;id++) {final int channel=id;oreSamplers[id]=new DensitySampler(){ + public float sampleValue(SamplerContext c,int x,int y,int z){ + out.println("ore "+channel+" query "+x+" "+y+" "+z); + if(oreRemaining[channel]==0)throw new IllegalStateException("fixture ore density failure"); + if(oreRemaining[channel]>0)oreRemaining[channel]--; + return oreValues[channel]; + } + public void sampleVolume(SamplerContext c,DensityBuffer b,DensityVolume v){ + out.println("ore "+channel+" volume "+v.sizeX()+" "+v.sizeY()+" "+v.sizeZ()+" "+v.minBlockX()+" "+v.minBlockY()+" "+v.minBlockZ()+" "+v.stepBlockX()+" "+v.stepBlockY()+" "+v.stepBlockZ()); + DensitySampler.sampleVolumeNaive(c,b,v,this); + } + };} + DensitySamplerSet densitySamplers=function->{ + if(function==system.preliminarySurfaceFunction())return sampler.bind(SamplerContext.EMPTY_UNCACHED); + for(int i=0;i<3;i++)if(function==oreFunctions[i])return oreSamplers[i].bind(SamplerContext.EMPTY_UNCACHED); + throw new AssertionError("unexpected density function"); + }; + if(ruleDefinitions!=null) { + densitySamplers=random.samplersWithContext(SamplerContext.builder().enableCaches().useBufferArena(DensityBufferArena.GLOBAL).build()); + if(f.has("library_json"))for(var value:f.getAsJsonArray("library_json"))out.println("rule decode "+(MaterialRule.DIRECT_CODEC.parse(ops,JsonParser.parseString(value.getAsString())).result().isPresent()?"ok":"error")); + } + int[] dims={16,1,16,0,0,0,1,1,1};if(f.has("volume"))for(int i=0;i<9;i++)dims[i]=f.getAsJsonArray("volume").get(i).getAsInt(); + var expected=new DensityVolume(dims[0],dims[1],dims[2],dims[3],dims[4],dims[5],dims[6],dims[7],dims[8]); + var context=(MaterialRuleContext)ctor.newInstance(system,random,expected,densitySamplers,biomeGetter,generation,possible); + var updateXZ=MaterialRuleContext.class.getDeclaredMethod("updateXZ",int.class,int.class,int.class,int.class);updateXZ.setAccessible(true); + var updateY=MaterialRuleContext.class.getDeclaredMethod("updateY",int.class,int.class,int.class,int.class);updateY.setAccessible(true); + var depthField=MaterialRuleContext.class.getDeclaredField("surfaceDepth");depthField.setAccessible(true); + var conditions=new ArrayList(); + for(var c:f.getAsJsonArray("conditions")) {var value=condition(c);out.println("runtime "+encode(value));conditions.add(value.compile(context));} + if(f.has("json"))for(var c:f.getAsJsonArray("json")) { + var value=MaterialCondition.CODEC.parse(ops,JsonParser.parseString(c.getAsString())).result(); + if(value.isEmpty())out.println("decode error");else {out.println("decode "+encode(value.get()));try{conditions.add(value.get().compile(context));}catch(IllegalStateException|NoSuchElementException error){out.println("compile error");}} + } + var rules=new ArrayList(); + if(f.has("rules"))for(var r:f.getAsJsonArray("rules"))rules.add(rule(r).compile(context)); + if(ruleDefinitions!=null)for(var name:f.getAsJsonArray("library_rules"))rules.add(ruleDefinitions.getValue(Identifier.parse(name.getAsString())).compile(context)); + for(var item:f.getAsJsonArray("ops")) { + var op=item.getAsJsonArray();switch(op.get(0).getAsString()) { + case "ore_input"->{int channel=op.get(1).getAsInt();oreValues[channel]=Float.intBitsToFloat(Integer.parseUnsignedInt(op.get(2).getAsString(),16));oreRemaining[channel]=op.get(3).getAsInt();} + case "density"->{density[0]=Float.intBitsToFloat(Integer.parseUnsignedInt(op.get(1).getAsString(),16));remaining[0]=op.get(2).getAsInt();} + case "minimum"->{try{out.println("minimum "+context.getMinSurfaceLevel());}catch(RuntimeException error){out.println("minimum error");}} + case "biome"->currentBiome[0]=op.get(1).isJsonNull()?null:op.get(1).getAsString(); + case "rule"->{try{rules.add(rule(op.get(1)).compile(context));out.println("rule added "+(rules.size()-1));}catch(RuntimeException error){out.println("rule compile error");}} + case "apply"->{for(int i=0;i{depth[0]=op.get(1).getAsInt();secondary[0]=Float.intBitsToFloat(Integer.parseUnsignedInt(op.get(2).getAsString(),16));} + case "xz"->{updateXZ.invoke(context,op.get(1).getAsInt(),op.get(2).getAsInt(),op.get(3).getAsInt(),op.get(4).getAsInt());depthField.setInt(context,depth[0]);} + case "y"->updateY.invoke(context,op.get(1).getAsInt(),op.get(2).getAsInt(),op.get(3).getAsInt(),op.get(4).getAsInt()); + case "add"->{conditions.add(condition(op.get(1)).compile(context));out.println("added "+(conditions.size()-1));} + case "eval"->{if(op.size()==1){for(int i=0;iout.println("secondary "+Long.toUnsignedString(Double.doubleToLongBits(context.getSurfaceSecondary()),16)); + default->throw new AssertionError("unknown operation "+op); + } + } + } + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + BLOCKS=Arrays.stream(new String[]{"terracotta","orange_terracotta","yellow_terracotta","brown_terracotta","red_terracotta","white_terracotta","light_gray_terracotta","stone","air","water"}).map(name->BuiltInRegistries.BLOCK.getValue(Identifier.withDefaultNamespace(name)).defaultBlockState()).toArray(BlockState[]::new); + Path dir=Path.of(args[1]);noises=new MappedRegistry<>(Registries.NOISE,Lifecycle.stable()); + var noiseDefinitions=JsonParser.parseString(Files.readString(dir.resolve("noises.json"))).getAsJsonObject(); + for(var e:noiseDefinitions.entrySet())noises.register(ResourceKey.create(Registries.NOISE,Identifier.parse(e.getKey())),NormalNoise.DIRECT_CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(e.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN); + noises.freeze();loadBiomes(dir);loadConditions(dir);loadRules(dir); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var name:definitions.keySet().stream().map(Object::toString).sorted().toList())out.println("registry "+name+" "+encode(definitions.getValue(Identifier.parse(name)))); + for(String line:Files.readAllLines(dir.resolve("inputs.txt")))fixture(JsonParser.parseString(line).getAsJsonObject(),out); + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialExtensionOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialExtensionOracle.java new file mode 100644 index 000000000..2204fa6e0 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialExtensionOracle.java @@ -0,0 +1,67 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.lang.reflect.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.core.registries.*; +import net.minecraft.resources.*; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.BlockColumn; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.densityfunction.DensityFunctions; +import net.minecraft.world.level.levelgen.material.MaterialSystem; +import net.minecraft.world.level.levelgen.synth.*; + +/** Original transport invoking the actual private column extension methods. */ +public final class VanillaMaterialExtensionOracle { + private static final String[] NAMES={"badlands_surface","badlands_pillar","badlands_pillar_roof","iceberg_surface","iceberg_pillar","iceberg_pillar_roof"}; + private static final String[] FIELDS={"badlandsSurfaceNoise","badlandsPillarNoise","badlandsPillarRoofNoise","icebergSurfaceNoise","icebergPillarNoise","icebergPillarRoofNoise"}; + private static MappedRegistry noises; + private static JsonObject biomes; + private static BlockState[] states; + private static Method badlands,frozen,climate,make; + private static int label(BlockState state){for(int i=0;i=0 && i=0 && iBlockState.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(text)).getOrThrow()).toArray(BlockState[]::new); + noises=new MappedRegistry<>(Registries.NOISE,Lifecycle.stable());var definitions=JsonParser.parseString(Files.readString(dir.resolve("noises.json"))).getAsJsonObject(); + for(var e:definitions.entrySet())noises.register(ResourceKey.create(Registries.NOISE,Identifier.parse(e.getKey())),NormalNoise.DIRECT_CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(e.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN);noises.freeze(); + biomes=JsonParser.parseString(Files.readString(dir.resolve("biomes.json"))).getAsJsonObject(); + badlands=MaterialSystem.class.getDeclaredMethod("erodedBadlandsExtension",BlockColumn.class,int.class,int.class,int.class,LevelHeightAccessor.class);badlands.setAccessible(true); + frozen=MaterialSystem.class.getDeclaredMethod("frozenOceanExtension",int.class,Biome.class,BlockColumn.class,BlockPos.MutableBlockPos.class,int.class,int.class,int.class);frozen.setAccessible(true); + climate=VanillaBiomeTemperatureOracle.class.getDeclaredMethod("climate",JsonObject.class);climate.setAccessible(true);make=VanillaBiomeTemperatureOracle.class.getDeclaredMethod("make",Object.class);make.setAccessible(true); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))){for(var line:Files.readAllLines(dir.resolve("inputs.txt")))fixture(JsonParser.parseString(line).getAsJsonObject(),out);} + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialStageOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialStageOracle.java new file mode 100644 index 000000000..8a2e81a71 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialStageOracle.java @@ -0,0 +1,181 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.lang.reflect.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.core.registries.*; +import net.minecraft.resources.*; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.state.*; +import net.minecraft.world.level.block.state.properties.IntegerProperty; +import net.minecraft.world.level.chunk.*; +import net.minecraft.world.level.chunk.status.ChunkStatus; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.blending.Blender; +import net.minecraft.world.level.levelgen.densityfunction.*; +import net.minecraft.world.level.levelgen.material.rule.MaterialRule; +import net.minecraft.world.level.levelgen.synth.NormalNoise; + +/** Original transport calling the actual MaterialSystem.buildSurface on ProtoChunk. */ +public final class VanillaMaterialStageOracle { + private static MappedRegistry noises; + private static MappedRegistry biomes; + private static RegistryOps ops; + private static PalettedContainerFactory factory; + private static Object field(String name) throws Exception {var f=VanillaMaterialConditionOracle.class.getDeclaredField(name);f.setAccessible(true);return f.get(null);} + @SuppressWarnings("unchecked") + private static void load(Path dir) throws Exception { + noises=new MappedRegistry<>(Registries.NOISE,Lifecycle.stable()); + var data=JsonParser.parseString(Files.readString(dir.resolve("noises.json"))).getAsJsonObject(); + for(var e:data.entrySet())noises.register(ResourceKey.create(Registries.NOISE,Identifier.parse(e.getKey())),NormalNoise.DIRECT_CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(e.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN);noises.freeze(); + var field=VanillaMaterialConditionOracle.class.getDeclaredField("noises");field.setAccessible(true);field.set(null,noises); + for(var name:new String[]{"loadBiomes","loadConditions","loadRules"}){var method=VanillaMaterialConditionOracle.class.getDeclaredMethod(name,Path.class);method.setAccessible(true);method.invoke(null,dir);} + biomes=(MappedRegistry)field("biomes");ops=(RegistryOps)field("ops"); + VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(dir.resolve("block_tags.json"))).getAsJsonObject()); + var ids=new IdMapper>();for(var id:biomes.keySet())ids.add(biome(id.toString())); + factory=new PalettedContainerFactory(Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY),Blocks.AIR.defaultBlockState(),null,Strategy.createForBiomes(ids),biome("minecraft:plains"),null); + var carvers=new MappedRegistry(Registries.CARVER,Lifecycle.stable()); + var carverJson=JsonParser.parseString(Files.readString(dir.resolve("carvers.json"))).getAsJsonObject(); + for(var e:carverJson.entrySet())carvers.register(ResourceKey.create(Registries.CARVER,Identifier.parse(e.getKey())),net.minecraft.world.level.levelgen.carver.WorldCarver.DIRECT_CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(e.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN);carvers.freeze(); + var carverOps=RegistryOps.create(JsonOps.INSTANCE,new RegistryOps.RegistryInfoLookup(){public Optional> lookup(ResourceKey> key){if(key.equals(Registries.CARVER))return (Optional>)(Optional)Optional.of(carvers);return Optional.empty();}}); + var generationField=Biome.class.getDeclaredField("generationSettings");generationField.setAccessible(true);var biomeJson=JsonParser.parseString(Files.readString(dir.resolve("biomes.json"))).getAsJsonObject(); + for(var e:biomeJson.entrySet()) { + var config=new JsonObject();config.add("carvers",JsonParser.parseString(e.getValue().getAsString()).getAsJsonObject().get("carvers"));config.add("features",new JsonArray()); + generationField.set(biome(e.getKey()).value(),BiomeGenerationSettings.CODEC.codec().parse(carverOps,config).getOrThrow()); + } + } + @SuppressWarnings("unchecked") + private static RegistryOps biomeOps() { + var presets=new MappedRegistry(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST,Lifecycle.stable()); + for(var preset:List.of(MultiNoiseBiomeSourceParameterList.Preset.OVERWORLD,MultiNoiseBiomeSourceParameterList.Preset.NETHER))presets.register(ResourceKey.create(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST,preset.id()),new MultiNoiseBiomeSourceParameterList(preset,biomes),RegistrationInfo.BUILT_IN);presets.freeze(); + return RegistryOps.create(JsonOps.INSTANCE,new RegistryOps.RegistryInfoLookup(){public Optional> lookup(ResourceKey> key){ + if(key.equals(Registries.BIOME))return (Optional>)(Optional)Optional.of(biomes); + if(key.equals(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST))return (Optional>)(Optional)Optional.of(presets);return Optional.empty();}}); + } + private static Holder biome(String name){return biomes.getOrThrow(ResourceKey.create(Registries.BIOME,Identifier.parse(name)));} + private static void export(Path path) throws Exception { + var method=VanillaHeightmapOracle.class.getDeclaredMethod("facts");method.setAccessible(true);var facts=(JsonObject)method.invoke(null); + var integers=new JsonArray();for(var id:new TreeSet<>(BuiltInRegistries.BLOCK.keySet()))for(var p:BuiltInRegistries.BLOCK.getValue(id).getStateDefinition().getProperties())if(p instanceof IntegerProperty){var a=new JsonArray();a.add(id.toString());a.add(p.getName());integers.add(a);} + facts.add("integers",integers);Files.writeString(path,facts.toString(),StandardCharsets.UTF_8); + } + private static void fixture(JsonObject f,PrintWriter out) throws Exception { + int cx=f.get("cx").getAsInt(),cz=f.get("cz").getAsInt(),min=f.get("min").getAsInt(),height=f.get("height").getAsInt(),sea=f.get("sea").getAsInt(); + long seed=f.get("seed").getAsLong();boolean legacy=f.get("legacy").getAsBoolean(); + var rule=MaterialRule.CODEC.parse(ops,new JsonPrimitive(f.get("rule").getAsString())).getOrThrow(); + var routerJson=new JsonObject();for(var name:new String[]{"chunk_surface_level","continents","depth","erosion","final_density","ridges","temperature","vegetation"})routerJson.addProperty(name,0);routerJson.add("chunk_surface_level",f.get("preliminary")); + if(f.has("router"))routerJson=f.getAsJsonObject("router"); + var router=NoiseRouter.CODEC.parse(ops,routerJson).getOrThrow();var defaultBlock=Block.stateById(f.get("default").getAsInt()); + Optional aquifers=f.has("aquifers")&&!f.get("aquifers").isJsonNull()?Optional.of(Aquifer.Config.CODEC.parse(ops,f.get("aquifers")).getOrThrow()):Optional.empty(); + var fluid=f.has("fluid")?Block.stateById(f.get("fluid").getAsInt()):Blocks.WATER.defaultBlockState(); + var settings=new NoiseGeneratorSettings(NoiseSettings.create(f.get("noise_min").getAsInt(),f.get("noise_height").getAsInt()),defaultBlock,fluid,router,Holder.direct(rule),List.of(),sea,false,aquifers,legacy,NoiseGeneratorSettings.DebugFunctions.EMPTY); + var random=RandomState.create(noises,seed,legacy,defaultBlock,sea,router); + var bounds=LevelHeightAccessor.create(f.get("write_min").getAsInt(),f.get("write_max").getAsInt()-f.get("write_min").getAsInt()+1); + var chunk=new ProtoChunk(new ChunkPos(cx,cz),UpgradeData.EMPTY,LevelHeightAccessor.create(min,height),factory,null){@Override public LevelHeightAccessor getHeightAccessorForGeneration(){return bounds;}}; + chunk.setPersistedStatus(ChunkStatus.BIOMES); + for(var value:f.getAsJsonArray("initial")){var a=value.getAsJsonArray();int x=a.get(0).getAsInt(),z=a.get(2).getAsInt();for(int y=a.get(1).getAsInt();y<=a.get(3).getAsInt();y++)chunk.getSection(chunk.getSectionIndex(y)).setBlockState(x&15,y&15,z&15,Block.stateById(a.get(4).getAsInt()),false);} + if(f.get("prime").getAsBoolean())Heightmap.primeHeightmaps(chunk,EnumSet.of(Heightmap.Types.WORLD_SURFACE_WG,Heightmap.Types.OCEAN_FLOOR_WG)); + var neighborhood=new HashMap(); + BiomeSource source=null; + if(f.has("biome_source")) { + source=BiomeSource.CODEC.parse(biomeOps(),f.get("biome_source_json")).getOrThrow(); + var generator=new NoiseBasedChunkGenerator(source,Holder.direct(settings)); + var create=ChunkGenerator.class.getDeclaredMethod("doCreateBiomes",Blender.class,RandomState.class,ChunkAccess.class);create.setAccessible(true); + for(int dx=-1;dx<=1;dx++)for(int dz=-1;dz<=1;dz++) { + int x=cx+dx,z=cz+dz;var neighbor=dx==0&&dz==0?chunk:new ProtoChunk(new ChunkPos(x,z),UpgradeData.EMPTY,LevelHeightAccessor.create(min,height),factory,null); + neighbor.setPersistedStatus(ChunkStatus.BIOMES);create.invoke(generator,Blender.empty(),random,neighbor); + out.println("biomechunk "+x+" "+z); + for(int section=0;section{ + Holder value; + if(!neighborhood.isEmpty())value=neighborhood.get(ChunkPos.pack(x>>2,z>>2)).getNoiseBiome(x,y,z); + else {int hash=x*31+y*7+z*17;value=biome(names.get(Math.floorMod(hash,names.size())).getAsString());} + out.println("quart "+x+" "+y+" "+z+" "+biomes.getKey(value.value()));return value; + },BiomeManager.obfuscateSeed(seed)) { + @Override public Holder getBiome(BlockPos pos) { + Holder value; + if(zoom)value=super.getBiome(pos); + else {int hash=pos.getX()*31+pos.getY()*7+pos.getZ()*17;value=biome(names.get(Math.floorMod(hash,names.size())).getAsString());} + out.println("biome "+pos.getX()+" "+pos.getY()+" "+pos.getZ()+" "+biomes.getKey(value.value()));return value; + } + }; + Set> possible=null;if(!f.get("possible").isJsonNull()){possible=new HashSet<>();for(var name:f.getAsJsonArray("possible"))possible.add(biome(name.getAsString()));} + var contextInput=new JsonObject();var contextArray=new JsonArray();contextArray.add(min);contextArray.add(height);contextArray.add(sea);contextInput.add("context",contextArray); + var contextMethod=VanillaAnchorOracle.class.getDeclaredMethod("context",JsonObject.class);contextMethod.setAccessible(true);var context=(WorldGenerationContext)contextMethod.invoke(null,contextInput); + var volume=new DensityVolume(16,f.get("noise_height").getAsInt(),16,cx<<4,f.get("noise_min").getAsInt(),cz<<4); + var pickerMethod=NoiseBasedChunkGenerator.class.getDeclaredMethod("createFluidPicker",NoiseGeneratorSettings.class);pickerMethod.setAccessible(true); + var picker=(Aquifer.FluidPicker)pickerMethod.invoke(null,settings); + try(var noise=new NoiseChunk(random,Beardifier.EMPTY,settings,picker,Blender.empty(),volume)) { + if(f.has("router")) { + var generator=new NoiseBasedChunkGenerator(new FixedBiomeSource(biome(names.get(0).getAsString())),Holder.direct(settings)); + var fill=NoiseBasedChunkGenerator.class.getDeclaredMethod("doFill",NoiseChunk.class,ChunkAccess.class);fill.setAccessible(true);fill.invoke(generator,noise,chunk); + out.println("terrain "+noise.aquifer().shouldScheduleFluidUpdate());dump(chunk,height,out); + } + for(int repeat=0;repeat codec(){return com.mojang.serialization.MapCodec.unit(delegateSource);} + protected java.util.stream.Stream> collectPossibleBiomes(){return delegateSource.possibleBiomes().stream();} + public BiomeResolver createResolver(Climate.Sampler sampler) { + var resolver=delegateSource.createResolver(sampler); + return (x,y,z)->{var value=resolver.getNoiseBiome(x,y,z);out.println("rawquart "+x+" "+y+" "+z+" "+biomes.getKey(value.value()));return value;}; + } + }; + var generator=new NoiseBasedChunkGenerator(tracedSource,Holder.direct(settings)); + var generate=NoiseBasedChunkGenerator.class.getDeclaredMethod("generateCarvers",ChunkAccess.class,Blender.class,NoiseChunk.class,RandomState.class,BiomeManager.class,net.minecraft.server.level.WorldGenRegion.class,MaterialRule.class);generate.setAccessible(true); + try {generate.invoke(generator,chunk,Blender.empty(),noise,random,manager,null,rule);out.println("generatedcarving ok");} + catch(java.lang.reflect.InvocationTargetException error){out.println("generatedcarving error");error.getCause().printStackTrace();} + dump(chunk,height,out); + } + var carving=f.getAsJsonObject("carving"); + for(var value:carving.getAsJsonArray("initial")) {var q=value.getAsJsonArray();chunk.setBlockState(new BlockPos(q.get(0).getAsInt(),q.get(1).getAsInt(),q.get(2).getAsInt()),Block.stateById(q.get(3).getAsInt()));} + var mask=new CarvingMask(min+1,min+height-8); + for(var value:carving.getAsJsonArray("spans")) {var q=value.getAsJsonArray();for(int y=q.get(2).getAsInt();y<=q.get(3).getAsInt();y++)mask.carve(q.get(0).getAsInt(),y,q.get(1).getAsInt());} + var generator=new NoiseBasedChunkGenerator(new FixedBiomeSource(biome(names.get(0).getAsString())),Holder.direct(settings)); + var apply=NoiseBasedChunkGenerator.class.getDeclaredMethod("applyCarvingMask",ChunkAccess.class,CarvingMask.class,RandomState.class,MaterialRule.class,WorldGenerationContext.class,NoiseChunk.class,java.util.function.Function.class,CarvingMask.Filter.class);apply.setAccessible(true); + for(var value:carving.getAsJsonArray("filters")) { + int mode=value.getAsInt();CarvingMask.Filter filter=mode==0?null:(x,y,z)->{boolean keep=mode==1&&Math.floorMod(x*31+y*7+z*17,5)!=0;out.println("filter "+x+" "+y+" "+z+" "+keep);return keep;}; + try {apply.invoke(generator,chunk,mask,random,rule,context,noise,(java.util.function.Function>)manager::getBiome,filter);out.println("carving "+mode+" ok");} + catch(java.lang.reflect.InvocationTargetException error){out.println("carving "+mode+" error");error.getCause().printStackTrace();} + dump(chunk,height,out); + } + } + } + private static void dump(ProtoChunk chunk,int height,PrintWriter out) { + for(int section=0;section noises; + private static int label(BlockState state) { + String name=BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString(); + for(int i=0;i(Registries.NOISE,Lifecycle.stable()); + var definitions=JsonParser.parseString(Files.readString(dir.resolve("noises.json"))).getAsJsonObject(); + for(var e:definitions.entrySet())noises.register(ResourceKey.create(Registries.NOISE,Identifier.parse(e.getKey())),NormalNoise.DIRECT_CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(e.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN); + noises.freeze(); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(String line:Files.readAllLines(dir.resolve("inputs.txt")))fixture(JsonParser.parseString(line).getAsJsonObject(),out); + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNoiseOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNoiseOracle.java new file mode 100644 index 000000000..cf0cfb7d9 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNoiseOracle.java @@ -0,0 +1,149 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.StringTokenizer; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.levelgen.LegacyRandomSource; +import net.minecraft.world.level.levelgen.XoroshiroRandomSource; +import net.minecraft.world.level.levelgen.synth.GradientNoise; +import net.minecraft.world.level.levelgen.synth.Noise; +import net.minecraft.world.level.levelgen.synth.NoiseStack; +import net.minecraft.world.level.levelgen.synth.NormalNoise; +import net.minecraft.world.level.levelgen.synth.PerlinNoise; +import net.minecraft.world.level.levelgen.synth.SimplexNoise; +import net.minecraft.world.level.levelgen.synth.SmearedPerlinNoise; +import net.minecraft.world.level.levelgen.densityfunction.DensityBuffer; +import net.minecraft.world.level.levelgen.densityfunction.DensityVolume; + +/** Original transport adapter; samples the reference classes directly. */ +public final class VanillaNoiseOracle { + private static int integer(StringTokenizer args) { return Integer.parseInt(args.nextToken()); } + private static double number(StringTokenizer args) { return Double.longBitsToDouble(Long.parseUnsignedLong(args.nextToken(),16)); } + private static float small(StringTokenizer args) { return Float.intBitsToFloat(Integer.parseUnsignedInt(args.nextToken(),16)); } + private static String bits(float value) { return Integer.toUnsignedString(Float.floatToIntBits(value)); } + private static String bits(double value) { return Long.toUnsignedString(Double.doubleToLongBits(value)); } + private static Object field(Object object, String name) throws Exception { + Field field=GradientNoise.class.getDeclaredField(name);field.setAccessible(true);return field.get(object); + } + private static Object declared(Object object,String name) throws Exception { + Field field=object.getClass().getDeclaredField(name);field.setAccessible(true);return field.get(object); + } + private static void normal(StringTokenizer args,PrintWriter out) throws Exception { + String kind=args.nextToken();long seed=Long.parseLong(args.nextToken());int parity=integer(args),base=integer(args),count=integer(args),normalization=integer(args); + double amplitude=number(args);double[] modifiers=new double[integer(args)];for(int i=0;i)declared(definition,"octaves"); + out.printf("normal %d %s %s %s%n",octaves.size(),bits((double)declared(definition,"normalizationFactor")),bits(definition.range().min()),bits(definition.range().max())); + for(Object octave:octaves) { + Method name=octave.getClass().getDeclaredMethod("seed");name.setAccessible(true); + out.printf("octave %d %s %s %s%n",(int)declared(octave,"octaveIndex"),bits((double)declared(octave,"frequency")),bits((double)declared(octave,"amplitude")),name.invoke(octave)); + } + NoiseStack noise; + try { noise=(NoiseStack)((parity&2)!=0?definition.createForLegacyNetherBiome(random):definition.create(random)); } + catch(IllegalArgumentException | IllegalStateException e) { out.println("normal-create error");out.println("normal-parent "+random.nextLong());return; } + Field layerField=NoiseStack.class.getDeclaredField("layers");layerField.setAccessible(true);Object[] layers=(Object[])layerField.get(noise); + out.printf("normal-create %d %s %s%n",layers.length,bits(noise.range().min()),bits(noise.range().max())); + for(int i=0;i(); + Method wrap=GradientNoise.class.getDeclaredMethod("wrap",double.class);wrap.setAccessible(true); + try(var reader=Files.newBufferedReader(Path.of(paths[0]),StandardCharsets.UTF_8); + var out=new PrintWriter(Files.newBufferedWriter(Path.of(paths[1]),StandardCharsets.UTF_8))) { + String line; + while((line=reader.readLine())!=null) { + var args=new StringTokenizer(line); + String operation=args.nextToken(); + switch(operation) { + case "normal" -> normal(args,out); + case "create" -> { + String kind=args.nextToken(),stream=args.nextToken();long seed=Long.parseLong(args.nextToken()); + boolean skip=integer(args)!=0;double scale=number(args); + RandomSource random=switch(stream) {case "legacy"->new LegacyRandomSource(seed);case "xoroshiro"->new XoroshiroRandomSource(seed);default->throw new AssertionError();}; + GradientNoise noise=switch(kind) {case "perlin"->new PerlinNoise(random);case "simplex"->new SimplexNoise(random,skip);case "smeared"->new SmearedPerlinNoise(random,scale);default->throw new AssertionError();}; + samplers.add(noise); + String lower,upper; + try { lower=bits(noise.range().min());upper=bits(noise.range().max()); } + catch(IllegalArgumentException e) { lower="error";upper="error"; } + out.printf("create %s %s %s %s %s %d%n",bits((double)field(noise,"offsetX")),bits((double)field(noise,"offsetY")),bits((double)field(noise,"offsetZ")),lower,upper,random.nextLong()); + out.print("permutations");for(byte v:(byte[])field(noise,"perms"))out.print(" "+(v&255));out.println(); + } + case "query", "local" -> { + var noise=samplers.get(integer(args));double x=number(args),y=number(args),z=number(args); + if(operation.equals("local")) { x-=(double)field(noise,"offsetX");y-=(double)field(noise,"offsetY");z-=(double)field(noise,"offsetZ"); } + float[] derivative={small(args),small(args),small(args)}; + out.print("query "+bits(noise.get(x,z))+" "+bits(noise.get(x,y,z))); + if(noise instanceof PerlinNoise perlin)out.print(" "+bits(perlin.noiseWithDerivative(x,y,z,derivative))+" "+bits(derivative[0])+" "+bits(derivative[1])+" "+bits(derivative[2])); + out.println(); + } + case "volume" -> { + var noise=samplers.get(integer(args)); + int sx=integer(args),sy=integer(args),sz=integer(args),mx=integer(args),my=integer(args),mz=integer(args),dx=integer(args),dy=integer(args),dz=integer(args); + double xzScale=number(args),yScale=number(args);float amplitude=small(args);long seed=Long.parseLong(args.nextToken());int repeats=integer(args); + DensityVolume volume; + try { volume=new DensityVolume(sx,sy,sz,mx,my,mz,dx,dy,dz); } + catch(IllegalArgumentException e) { out.println("volume error");break; } + var buffer=DensityBuffer.createUnpooled(volume.size()+4);var random=new LegacyRandomSource(seed); + for(int i=0;i { + int count=integer(args);var builder=NoiseStack.builder(); + for(int i=0;i out.println("wrap "+bits((double)wrap.invoke(null,number(args)))); + default -> throw new AssertionError(); + } + if(args.hasMoreTokens())throw new AssertionError("extra argument"); + } + if(out.checkError())throw new java.io.IOException("reference output failed"); + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonShapeOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonShapeOracle.java new file mode 100644 index 000000000..4df179e17 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonShapeOracle.java @@ -0,0 +1,41 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import net.minecraft.core.*; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.piston.PistonMovingBlockEntity; +import net.minecraft.world.phys.shapes.*; +/** Executes native moving-piston collision and interpolation with actual registry states. */ +public final class VanillaPistonShapeOracle { + private static final class Stop extends RuntimeException {} + private static Field field(String name)throws Exception {var f=PistonMovingBlockEntity.class.getDeclaredField(name);f.setAccessible(true);return f;} + private static float number(JsonElement value){return Float.intBitsToFloat(Integer.parseUnsignedInt(value.getAsString(),16));} + @SuppressWarnings("unchecked") public static void main(String[] args)throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); + if(args[0].equals("export")){VanillaCollisionOracle.main(new String[]{"generate",args[1]});VanillaBlockStateCodecOracle.main(new String[]{"export",dir.resolve("facts.json").toString()});return;} + var progress=field("progress");var previous=field("progressO");var noclip=(ThreadLocal)field("NOCLIP").get(null); + var related=PistonMovingBlockEntity.class.getDeclaredMethod("getCollisionRelatedBlockState");related.setAccessible(true); + var movement=PistonMovingBlockEntity.class.getDeclaredMethod("getMovementDirection");movement.setAccessible(true); + var emit=VanillaFaceSupportOracle.class.getDeclaredMethod("emit",PrintWriter.class,VoxelShape.class);emit.setAccessible(true); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt")));var inputs=Files.lines(dir.resolve("inputs.txt"))) { + for(var line:(Iterable)inputs::iterator) { + var f=JsonParser.parseString(line).getAsJsonObject();var v=f.getAsJsonArray("position");var p=new BlockPos(v.get(0).getAsInt(),v.get(1).getAsInt(),v.get(2).getAsInt()); + var direction=Direction.values()[f.get("direction").getAsInt()];var moved=Block.stateById(f.get("state").getAsInt()); + var piston=new PistonMovingBlockEntity(p,Blocks.MOVING_PISTON.defaultBlockState(),moved,direction,f.get("extending").getAsBoolean(),f.get("source").getAsBoolean());progress.setFloat(piston,number(f.get("progress")));previous.setFloat(piston,number(f.get("previous")));float partial=number(f.get("partial")); + int clip=f.get("noclip").getAsInt();noclip.set(clip<0?null:Direction.values()[clip]);int[] calls={0}; + var world=(BlockGetter)Proxy.newProxyInstance(BlockGetter.class.getClassLoader(),new Class[]{BlockGetter.class},(proxy,method,values)->{ + if(!method.getName().equals("getBlockEntity"))throw new AssertionError(method);var at=(BlockPos)values[0];out.println("entity "+at.getX()+" "+at.getY()+" "+at.getZ());if(calls[0]++==f.get("fail").getAsInt())throw new Stop();return null; + }); + try { + out.printf("motion %d %08x %08x %08x %08x%n",((Direction)movement.invoke(piston)).ordinal(),Float.floatToIntBits(piston.getProgress(partial)),Float.floatToIntBits(piston.getXOff(partial)),Float.floatToIntBits(piston.getYOff(partial)),Float.floatToIntBits(piston.getZOff(partial))); + out.println("related "+Block.getId((net.minecraft.world.level.block.state.BlockState)related.invoke(piston))); + if(!f.get("kinematic").getAsBoolean())try {emit.invoke(null,out,piston.getCollisionShape(world,p));}catch(Stop error){out.println("shape error");} + out.println("queries "+calls[0]); + } finally {noclip.remove();} + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java new file mode 100644 index 000000000..528b8f893 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java @@ -0,0 +1,101 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.*; +import java.lang.reflect.Proxy; +import java.lang.reflect.InvocationHandler; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.*; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.densityfunction.DensityFunctions; +import net.minecraft.world.level.levelgen.material.rule.BlockRule; +import net.minecraft.world.level.levelgen.placement.*; + +/** Original transport invoking actual placement codecs and modifier callbacks. */ +public final class VanillaPlacementOracle { + private static final class Stop extends RuntimeException {} + private static PlacementContext context(JsonObject f) {return context(f,null);} + private static PlacementContext context(JsonObject f,PrintWriter out) { + var v=f.getAsJsonArray("context");int min=v.get(0).getAsInt(),height=v.get(1).getAsInt(),sea=v.get(2).getAsInt(); + var zero=DensityFunctions.zero(); + var settings=new NoiseGeneratorSettings(new NoiseSettings(min,height),Blocks.STONE.defaultBlockState(),Blocks.WATER.defaultBlockState(),new NoiseRouter(zero,zero,zero,zero,zero,zero,zero,zero),Holder.direct(new BlockRule(Blocks.STONE.defaultBlockState())),List.of(),sea,false,Optional.empty(),false,NoiseGeneratorSettings.DebugFunctions.EMPTY); + var biome=Holder.Reference.createStandAlone(new HolderOwner(){},Biomes.PLAINS); + var generator=new NoiseBasedChunkGenerator(new FixedBiomeSource(biome),Holder.direct(settings)); + int worldMin=f.has("world_min")?f.get("world_min").getAsInt():min;int mode=f.has("height_mode")?f.get("height_mode").getAsInt():0;int fail=f.has("query_fail")?f.get("query_fail").getAsInt():-1;int[] calls={0};boolean layerWorld=f.has("layer_world")&&f.get("layer_world").getAsBoolean(); + var level=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},(proxy,method,args)->switch(method.getName()) { + case "isInsideBuildHeight"->{ + if(args[0] instanceof BlockPos p) { + if(out!=null)out.println("inside "+p.getX()+" "+p.getY()+" "+p.getZ()); + if(calls[0]++==fail)throw new IllegalArgumentException("bounds query failure"); + var result=InvocationHandler.invokeDefault(proxy,method,args); + if(out!=null)out.println("bounds_result "+result);yield result; + } + yield InvocationHandler.invokeDefault(proxy,method,args); + } + case "isOutsideBuildHeight"->{ + if(out!=null)out.println("outside "+args[0]); + if(calls[0]++==fail)throw new IllegalArgumentException("bounds query failure"); + var result=InvocationHandler.invokeDefault(proxy,method,args); + if(out!=null)out.println("bounds_result "+result);yield result; + } + case "getMaxY"->InvocationHandler.invokeDefault(proxy,method,args); + case "getMinY"->worldMin; + case "getHeight"->{ + if(args==null||args.length==0)yield height; + var kind=(Heightmap.Types)args[0];int x=(Integer)args[1],z=(Integer)args[2]; + if(out!=null)out.println("height "+kind.name()+" "+x+" "+z); + if(calls[0]++==fail)throw new IllegalArgumentException("height query failure"); + int result; + if(layerWorld)result=min+24+((x^z)&3); + else if(mode==0)result=min+Math.floorMod(x*31+z*17+kind.ordinal()*7,129)-64; + else {int[] values={Integer.MIN_VALUE,Integer.MAX_VALUE,0,-1,min,min+1};result=values[(kind.ordinal()+((x^z)&3))%6];} + if(out!=null)out.println("height_result "+result);yield result; + } + case "getBlockState"->{ + var p=(BlockPos)args[0];if(out!=null)out.println("block "+p.getX()+" "+p.getY()+" "+p.getZ()); + if(calls[0]++==fail)throw new IllegalArgumentException("block query failure"); + var blocks=new net.minecraft.world.level.block.Block[]{Blocks.BEDROCK,Blocks.STONE,Blocks.AIR,Blocks.WATER,Blocks.DIRT,Blocks.CAVE_AIR,Blocks.LAVA,Blocks.BUBBLE_COLUMN,Blocks.VOID_AIR,Blocks.GRASS_BLOCK,Blocks.AIR,Blocks.WATER}; + int index=p.getY()<=min?0:Math.floorMod(p.getY()-min+((p.getX()*31+p.getZ()*17)&3),12); + var block=blocks[index];if(out!=null)out.println("block_result "+net.minecraft.core.registries.BuiltInRegistries.BLOCK.getKey(block));yield block.defaultBlockState(); + } + case "getSeaLevel"->sea; + default->throw new AssertionError("unexpected world method "+method); + }); + var context=new PlacementContext(level,generator,Optional.empty());return context; + } + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();var context=context(f,out);long seed=f.get("seed").getAsLong(); + RandomSource random=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + Optional decoded; + try {decoded=PlacementModifier.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(f.get("definition").getAsString())).result();}catch(IllegalArgumentException error){decoded=Optional.empty();} + if(decoded.isEmpty())out.println("decode error");else { + out.println("decode ok");var provider=decoded.get(); + for(var value:f.getAsJsonArray("positions")) { + var p=value.getAsJsonArray();var position=new BlockPos(p.get(0).getAsInt(),p.get(1).getAsInt(),p.get(2).getAsInt()); + if(f.has("count_only")&&f.get("count_only").getAsBoolean()) { + try {out.println("count "+((RepeatingPlacement)provider).count(random,position));}catch(IllegalArgumentException error){out.println("count error");} + out.println("next "+random.nextLong());continue; + } + int[] count={0};int fail=f.get("fail").getAsInt();boolean draw=f.get("draw").getAsBoolean(); + try {provider.modify(context,random,position,result->{ + if(count[0]++==fail)throw new Stop(); + out.println("position "+result.getX()+" "+result.getY()+" "+result.getZ()); + if(draw)out.println("consumer "+random.nextLong()); + });out.println("modify ok");}catch(Stop|IllegalArgumentException error){out.println("modify error");} + out.println("next "+random.nextLong()); + } + } + out.println("tail "+random.nextLong()); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaReplaceBlockOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaReplaceBlockOracle.java new file mode 100644 index 000000000..1f14fbec8 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaReplaceBlockOracle.java @@ -0,0 +1,74 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.world.level.levelgen.placement.*; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.feature.Feature; + +/** Invokes native block-writing features through an observable mutable world. */ +public final class VanillaReplaceBlockOracle { + private static final class Stop extends RuntimeException {} + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + final Block[] BLOCKS={Blocks.AIR,Blocks.CAVE_AIR,Blocks.VOID_AIR,Blocks.STONE,Blocks.WATER,Blocks.OAK_LEAVES,Blocks.DIRT}; + if(args[0].equals("export")) { + VanillaBlockStateCodecOracle.main(args); + return; + } + Path dir=Path.of(args[1]); + VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(dir.resolve("tags.json"))).getAsJsonObject()); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();long seed=f.get("seed").getAsLong(); + RandomSource random=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + var decoded=Feature.DIRECT_CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(f.get("definition").getAsString())).result(); + if(decoded.isEmpty())out.println("decode error");else { + out.println("decode ok");int[] calls={0};int fail=f.get("fail").getAsInt(),reject=f.get("reject").getAsInt(); + var states=new TreeMap(Comparator.comparingInt(BlockPos::getX).thenComparingInt(BlockPos::getY).thenComparingInt(BlockPos::getZ)); + var world=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},(proxy,method,values)->{ + if(method.getName().equals("getMinY")) { + out.println("min");int call=calls[0]++;if(call==fail)throw new Stop(); + int minimum=f.get("world_min").getAsInt();out.println("minimum "+minimum);return minimum; + } + if(method.getName().equals("getHeight")&&(values==null||values.length==0))return 384; + if(method.getName().equals("getSeaLevel"))return 63; + if(method.getName().equals("setBlockAndUpdate"))return InvocationHandler.invokeDefault(proxy,method,values); + var p=((BlockPos)values[0]).immutable();int call=calls[0]++; + switch(method.getName()) { + case "getBlockState"->{ + out.println("get "+p.getX()+" "+p.getY()+" "+p.getZ());if(call==fail)throw new Stop(); + var state=states.getOrDefault(p,BLOCKS[Math.floorMod(p.getX()*31+p.getY()*7+p.getZ()*17,7)].defaultBlockState());out.println("state "+Block.getId(state));return state; + } + case "setBlock"->{ + var state=(BlockState)values[1];int flags=(Integer)values[2];out.println("set "+p.getX()+" "+p.getY()+" "+p.getZ()+" "+Block.getId(state)+" "+flags);if(call==fail)throw new Stop(); + boolean result=reject==0||call%reject!=0;if(result)states.put(p,state);out.println("written "+result);return result; + } + default->throw new AssertionError("unexpected world method "+method); + } + }); + var p=f.getAsJsonArray("origin");var origin=new BlockPos(p.get(0).getAsInt(),p.get(1).getAsInt(),p.get(2).getAsInt()); + for(int repeat=0;repeat)inputs::iterator) { + var f=JsonParser.parseString(line).getAsJsonObject();long seed=f.get("seed").getAsLong(); + RandomSource random=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + var decoded=RuleTest.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(f.get("definition").getAsString())).result(); + if(decoded.isEmpty())out.println("decode error");else { + out.println("decode ok");int index=0;var heights=f.getAsJsonArray("heights"); + for(int repeat=0;repeat(Comparator.comparingInt(BlockPos::getX).thenComparingInt(BlockPos::getY).thenComparingInt(BlockPos::getZ)); + var o=f.getAsJsonArray("origin");var center=new BlockPos(o.get(0).getAsInt(),o.get(1).getAsInt(),o.get(2).getAsInt()); + int mode=f.get("mode").getAsInt(); + var world=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},(proxy,method,values)->{ + if(method.getName().equals("getMinY")) { + out.println("min");int call=calls[0]++;if(call==fail)throw new Stop(); + int minimum=f.get("world_min").getAsInt();out.println("minimum "+minimum);return minimum; + } + if(method.getName().equals("getHeight")&&(values==null||values.length==0))return 384; + if(method.getName().equals("getSeaLevel"))return 63; + if(method.getName().equals("setBlockAndUpdate"))return InvocationHandler.invokeDefault(proxy,method,values); + var p=((BlockPos)values[0]).immutable();int call=calls[0]++; + switch(method.getName()) { + case "getBlockState"->{ + out.println("get "+p.getX()+" "+p.getY()+" "+p.getZ());if(call==fail)throw new Stop(); + var fallback=mode==0?BLOCKS[Math.floorMod(p.getX()*31+p.getY()*7+p.getZ()*17,7)].defaultBlockState():Blocks.STONE.defaultBlockState(); + if(mode>=2&&p.equals(center.relative(net.minecraft.core.Direction.values()[mode-2])))fallback=Blocks.CAVE_AIR.defaultBlockState(); + var state=states.getOrDefault(p,fallback);out.println("state "+Block.getId(state));return state; + } + case "setBlock"->{ + var state=(BlockState)values[1];int flags=(Integer)values[2];out.println("set "+p.getX()+" "+p.getY()+" "+p.getZ()+" "+Block.getId(state)+" "+flags);if(call==fail)throw new Stop(); + boolean result=reject==0||call%reject!=0;if(result)states.put(p,state);out.println("written "+result);return result; + } + default->throw new AssertionError("unexpected world method "+method); + } + }); + var p=f.getAsJsonArray("origin");var origin=new BlockPos(p.get(0).getAsInt(),p.get(1).getAsInt(),p.get(2).getAsInt()); + for(int repeat=0;repeat>(); + for(var block:BuiltInRegistries.BLOCK)for(var property:block.getStateDefinition().getProperties()) { + var values=new ArrayList(); + for(var value:property.getPossibleValues())values.add(((net.minecraft.world.level.block.state.properties.Property)property).getName((Comparable)value)); + Collections.sort(values); + String signature=property.getName()+"/"+(property instanceof net.minecraft.world.level.block.state.properties.IntegerProperty)+"/"+values; + var previous=families.putIfAbsent(signature,property); + if(previous!=null&&!previous.equals(property))throw new AssertionError("ambiguous pinned property family: "+signature); + } + } + private static void bindFluidTags(JsonObject resources) { + var registry=BuiltInRegistries.FLUID; + var loader=new TagLoader>((id,required)->registry.get(id).map(value->(Holder)value),"tags/fluid"); + var definitions=new HashMap>(); + for(var item:resources.entrySet()) { + var file=TagFile.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(item.getValue().getAsString())).getOrThrow(); + var entries=new ArrayList(); + for(var entry:file.entries())entries.add(new TagLoader.EntryWithSource(entry,"vanilla")); + definitions.put(Identifier.parse(item.getKey()),entries); + } + var tags=new HashMap,List>>(); + loader.build(definitions).forEach((id,values)->tags.put(TagKey.create(Registries.FLUID,id),List.copyOf(values))); + if(tags.size()!=resources.size())throw new AssertionError("incomplete fluid tags"); + registry.prepareTagReload(new TagLoader.LoadResult<>(Registries.FLUID,tags)).apply(); + } + @SuppressWarnings("unchecked") + public static void main(String[] args) throws Exception { + if(args[0].equals("export")){VanillaBlockStateCodecOracle.main(args);return;} + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap(); + verifyPropertyFamilies(); + Path dir=Path.of(args[1]); + VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(dir.resolve("tags.json"))).getAsJsonObject()); + bindFluidTags(JsonParser.parseString(Files.readString(dir.resolve("fluid-tags.json"))).getAsJsonObject()); + var biomeLoad=VanillaMaterialConditionOracle.class.getDeclaredMethod("loadBiomes",Path.class);biomeLoad.setAccessible(true);biomeLoad.invoke(null,dir); + var biomeField=VanillaMaterialConditionOracle.class.getDeclaredField("biomes");biomeField.setAccessible(true); + var biomeRegistry=(MappedRegistry)biomeField.get(null); + var biomeNames=new ArrayList<>(new TreeSet<>(biomeRegistry.keySet())); + var providers=new MappedRegistry(Registries.BLOCK_STATE_PROVIDER,com.mojang.serialization.Lifecycle.stable()); + var ops=RegistryOps.create(JsonOps.INSTANCE,new RegistryOps.RegistryInfoLookup(){public Optional> lookup(ResourceKey> key){ + if(key.equals(Registries.BIOME))return (Optional>)(Optional)Optional.of(biomeRegistry); + if(key.equals(Registries.FLUID))return (Optional>)(Optional)Optional.of(BuiltInRegistries.FLUID); + if(key.equals(Registries.BLOCK_STATE_PROVIDER))return (Optional>)(Optional)Optional.of(providers); + return key.equals(Registries.BLOCK)?(Optional>)(Optional)Optional.of(BuiltInRegistries.BLOCK):Optional.empty(); + }}); + for(var entry:JsonParser.parseString(Files.readString(dir.resolve("catalog.json"))).getAsJsonObject().entrySet()) { + var provider=BlockStateProvider.DIRECT_CODEC.parse(ops,JsonParser.parseString(entry.getValue().getAsString())).getOrThrow(); + providers.register(ResourceKey.create(Registries.BLOCK_STATE_PROVIDER,Identifier.parse(entry.getKey())),provider,RegistrationInfo.BUILT_IN); + } + providers.freeze(); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8));var inputs=Files.lines(dir.resolve("inputs.txt"))) { + for(var state:Block.BLOCK_STATE_REGISTRY) { + var fluid=state.getFluidState();boolean falling=fluid.hasProperty(FlowingFluid.FALLING)&&fluid.getValue(FlowingFluid.FALLING); + out.println("fluid "+Block.getId(state)+" "+BuiltInRegistries.FLUID.getKey(fluid.getType())+" "+fluid.getAmount()+" "+falling+" "+fluid.isSource()+" "+Integer.toUnsignedString(Float.floatToRawIntBits(fluid.getOwnHeight()))); + } + for(var line:(Iterable)inputs::iterator) { + var f=JsonParser.parseString(line).getAsJsonObject();long seed=f.get("seed").getAsLong(); + RandomSource random=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + if(f.get("worldgen").getAsBoolean())random=new WorldgenRandom(random); + Optional decoded; + try { + var definition=JsonParser.parseString(f.get("definition").getAsString()); + decoded=f.has("holder")&&f.get("holder").getAsBoolean()?BlockStateProvider.CODEC.parse(ops,definition).result().map(Holder::value):(f.get("typed").getAsBoolean()?BlockStateProvider.TYPED_CODEC:BlockStateProvider.DIRECT_CODEC).parse(ops,definition).result(); + } + catch(IllegalArgumentException|IllegalStateException error){decoded=Optional.empty();} + if(decoded.isEmpty())out.println("decode error");else { + out.println("decode ok");int[] calls={0};int[] fallback={0};int[] queries={0};int[] biomeIndex={0}; + int queryFail=f.has("query_fail")?f.get("query_fail").getAsInt():-1; + int min=f.has("bounds")?f.getAsJsonArray("bounds").get(0).getAsInt():-64; + int height=f.has("bounds")?f.getAsJsonArray("bounds").get(1).getAsInt():384; + int sea=f.has("bounds")?f.getAsJsonArray("bounds").get(2).getAsInt():63; + var world=(LevelAccessor)Proxy.newProxyInstance(LevelAccessor.class.getClassLoader(),new Class[]{LevelAccessor.class},(proxy,method,values)->{ + if(method.getName().equals("getFluidState")) { + var at=(BlockPos)values[0];out.println("fluid "+at.getX()+" "+at.getY()+" "+at.getZ()); + if(queries[0]++==queryFail)throw new Stop();return Block.stateById(fallback[0]).getFluidState(); + } + if(method.getName().equals("getRawBrightness")) { + var at=(BlockPos)values[0];out.println("light "+at.getX()+" "+at.getY()+" "+at.getZ()+" "+values[1]); + if(queries[0]++==queryFail)throw new Stop();return f.has("brightness")?f.get("brightness").getAsInt():15; + } + if(method.getName().equals("getBlockEntity")) { + var p=(BlockPos)values[0];out.println("entity "+p.getX()+" "+p.getY()+" "+p.getZ()); + if(queries[0]++==queryFail)throw new Stop();return null; + } + if(method.getName().equals("isUnobstructed")) { + if(values[0]!=null)throw new AssertionError("unexpected excluded entity"); + var box=((net.minecraft.world.phys.shapes.VoxelShape)values[1]).bounds(); + out.printf("clear %016x %016x %016x %016x %016x %016x%n",Double.doubleToRawLongBits(box.minX),Double.doubleToRawLongBits(box.minY),Double.doubleToRawLongBits(box.minZ),Double.doubleToRawLongBits(box.maxX),Double.doubleToRawLongBits(box.maxY),Double.doubleToRawLongBits(box.maxZ)); + if(queries[0]++==queryFail)throw new Stop();return !f.has("unobstructed")||f.get("unobstructed").getAsBoolean(); + } + if(method.getName().equals("getBiome")) { + var p=(BlockPos)values[0];out.println("biome "+p.getX()+" "+p.getY()+" "+p.getZ()); + if(queries[0]++==queryFail)throw new Stop(); + return biomeRegistry.getOrThrow(ResourceKey.create(Registries.BIOME,biomeNames.get(biomeIndex[0]))); + } + if(method.getName().equals("getBlockState")){var p=(BlockPos)values[0];out.println("read "+p.getX()+" "+p.getY()+" "+p.getZ());if(calls[0]++==f.get("fail").getAsInt())throw new Stop();return Block.stateById(fallback[0]);} + if(method.getName().equals("getMinY")||method.getName().equals("getHeight")) { + boolean minimum=method.getName().equals("getMinY");out.println(minimum?"min":"height"); + if(queries[0]++==queryFail)throw new Stop();return minimum?min:height; + } + if(method.getName().equals("getSeaLevel")){out.println("sea");if(queries[0]++==queryFail)throw new Stop();return sea;} + if(method.isDefault())return InvocationHandler.invokeDefault(proxy,method,values); + throw new AssertionError(method); + }); + int positionIndex=0,sampleIndex=0; + for(int repeat=0;repeat();var junctions=new ArrayList(); + for(var e:f.getAsJsonArray("pieces")) {var a=e.getAsJsonArray();pieces.add(new Beardifier.Rigid(box(a.get(0)),TerrainAdjustment.valueOf(a.get(1).getAsString()),a.get(2).getAsInt()));} + for(var e:f.getAsJsonArray("junctions")) {var a=e.getAsJsonArray();junctions.add(new JigsawJunction(a.get(0).getAsInt(),a.get(1).getAsInt(),a.get(2).getAsInt(),0,StructureTemplatePool.Projection.RIGID));} + var sampler=new Beardifier(pieces,junctions,box(f.get("affected")));var context=SamplerContext.builder().build(); + out.println("beardifier "+pieces.size()+" "+junctions.size()); + for(var e:f.getAsJsonArray("points")) {var a=e.getAsJsonArray();out.println("value "+bits(sampler.sampleValue(context,a.get(0).getAsInt(),a.get(1).getAsInt(),a.get(2).getAsInt())));} + for(var e:f.getAsJsonArray("volumes")) { + var a=e.getAsJsonArray();var volume=new DensityVolume(a.get(0).getAsInt(),a.get(1).getAsInt(),a.get(2).getAsInt(),a.get(3).getAsInt(),a.get(4).getAsInt(),a.get(5).getAsInt(),a.get(6).getAsInt(),a.get(7).getAsInt(),a.get(8).getAsInt()); + var buffer=DensityBuffer.createUnpooled(volume.size()+a.get(9).getAsInt());buffer.fill(-123.5f); + sampler.sampleVolume(context,buffer,volume);out.println("volume "+buffer.size()); + for(int i=0;i(); + for(var id:net.minecraft.core.registries.BuiltInRegistries.BLOCK.keySet())names.put(id.toString(),id.toString()); + java.nio.file.Files.writeString(java.nio.file.Path.of(paths[0]),new com.google.gson.Gson().toJson(names),java.nio.charset.StandardCharsets.UTF_8); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTerrainOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTerrainOracle.java new file mode 100644 index 000000000..13fb2de3a --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTerrainOracle.java @@ -0,0 +1,110 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.serialization.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.server.Bootstrap; +import net.minecraft.core.*; +import net.minecraft.core.registries.*; +import net.minecraft.resources.*; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.chunk.*; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.blending.Blender; +import net.minecraft.world.level.levelgen.densityfunction.*; +import net.minecraft.world.level.levelgen.material.rule.MaterialRule; +import net.minecraft.world.level.levelgen.synth.NormalNoise; + +/** Original transport invoking NoiseChunk and the actual generator fill routine. */ +public final class VanillaTerrainOracle { + private static MappedRegistry noises; + private static RegistryOps ops; + private static Holder biome; + private static PalettedContainerFactory factory; + @SuppressWarnings("unchecked") + private static void load(JsonObject bundle) { + noises=new MappedRegistry<>(Registries.NOISE,Lifecycle.stable()); + var densities=new MappedRegistry(Registries.DENSITY_FUNCTION,Lifecycle.stable()); + var noiseLookup=noises.createRegistrationLookup();var densityLookup=densities.createRegistrationLookup(); + ops=RegistryOps.create(JsonOps.INSTANCE,new RegistryOps.RegistryInfoLookup() { + public Optional> lookup(ResourceKey> key) { + if(key.equals(Registries.NOISE))return (Optional>)(Optional)Optional.of(noiseLookup); + if(key.equals(Registries.DENSITY_FUNCTION))return (Optional>)(Optional)Optional.of(densityLookup); + return Optional.empty(); + } + }); + for(var e:bundle.getAsJsonObject("noises").entrySet())noises.register(ResourceKey.create(Registries.NOISE,Identifier.parse(e.getKey())),NormalNoise.DIRECT_CODEC.parse(ops,JsonParser.parseString(e.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN); + noises.freeze(); + for(var e:bundle.getAsJsonObject("densities").entrySet())densities.register(ResourceKey.create(Registries.DENSITY_FUNCTION,Identifier.parse(e.getKey())),DensityFunctions.DIRECT_CODEC.parse(ops,JsonParser.parseString(e.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN); + densities.freeze(); + VanillaHeightmapOracle.bindTags(bundle.getAsJsonObject("tags")); + biome=Holder.Reference.createStandAlone(new HolderOwner(){},Biomes.PLAINS); + var ids=new IdMapper>();ids.add(biome); + factory=new PalettedContainerFactory(Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY),Blocks.AIR.defaultBlockState(),null,Strategy.createForBiomes(ids),biome,null); + } + private static Beardifier structure(JsonObject f) { + if(!f.has("structure"))return Beardifier.EMPTY; + var source=f.getAsJsonObject("structure"); + var pieces=new ArrayList(); + var junctions=new ArrayList(); + java.util.function.Function box=e->{var a=e.getAsJsonArray();return new net.minecraft.world.level.levelgen.structure.BoundingBox(a.get(0).getAsInt(),a.get(1).getAsInt(),a.get(2).getAsInt(),a.get(3).getAsInt(),a.get(4).getAsInt(),a.get(5).getAsInt());}; + for(var e:source.getAsJsonArray("pieces")) {var a=e.getAsJsonArray();pieces.add(new Beardifier.Rigid(box.apply(a.get(0)),net.minecraft.world.level.levelgen.structure.TerrainAdjustment.valueOf(a.get(1).getAsString()),a.get(2).getAsInt()));} + for(var e:source.getAsJsonArray("junctions")) {var a=e.getAsJsonArray();junctions.add(new net.minecraft.world.level.levelgen.structure.pools.JigsawJunction(a.get(0).getAsInt(),a.get(1).getAsInt(),a.get(2).getAsInt(),0,net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool.Projection.RIGID));} + return new Beardifier(pieces,junctions,box.apply(source.get("affected"))); + } + private static void fixture(JsonObject f,PrintWriter out) throws Exception { + int min=f.get("min").getAsInt(),height=f.get("height").getAsInt(),noiseMin=f.get("noise_min").getAsInt(),noiseHeight=f.get("noise_height").getAsInt(); + int cx=f.get("cx").getAsInt(),cz=f.get("cz").getAsInt(),sea=f.get("sea").getAsInt();long seed=f.get("seed").getAsLong();boolean legacy=f.get("legacy").getAsBoolean(); + var block=Block.stateById(f.get("block").getAsInt());var fluid=Block.stateById(f.get("fluid").getAsInt()); + var router=NoiseRouter.CODEC.parse(ops,f.get("router")).getOrThrow(); + Optional config=f.get("aquifers").isJsonNull()?Optional.empty():Optional.of(Aquifer.Config.CODEC.parse(ops,f.get("aquifers")).getOrThrow()); + // Neither material rules nor biome properties are evaluated by doFill. + var rule=Holder.Reference.createStandAlone(new HolderOwner(){},ResourceKey.create(Registries.MATERIAL_RULE,Identifier.parse("horizon:unused"))); + var settings=new NoiseGeneratorSettings(NoiseSettings.create(noiseMin,noiseHeight),block,fluid,router,rule,List.of(),sea,false,config,legacy,NoiseGeneratorSettings.DebugFunctions.EMPTY); + var state=RandomState.create(noises,seed,legacy,block,sea,router); + var generator=new NoiseBasedChunkGenerator(new FixedBiomeSource(biome),Holder.direct(settings)); + var pickerMethod=NoiseBasedChunkGenerator.class.getDeclaredMethod("createFluidPicker",NoiseGeneratorSettings.class);pickerMethod.setAccessible(true); + var picker=(Aquifer.FluidPicker)pickerMethod.invoke(null,settings); + var volume=new DensityVolume(16,noiseHeight,16,cx<<4,noiseMin,cz<<4,1,1,1); + var chunk=new ProtoChunk(new ChunkPos(cx,cz),UpgradeData.EMPTY,LevelHeightAccessor.create(min,height),factory,null); + for(var item:f.getAsJsonArray("initial")) { + var a=item.getAsJsonArray();int x=a.get(0).getAsInt(),y=a.get(1).getAsInt(),z=a.get(2).getAsInt(); + chunk.getSection(chunk.getSectionIndex(y)).setBlockState(x&15,y&15,z&15,Block.stateById(a.get(3).getAsInt()),false); + } + var fill=NoiseBasedChunkGenerator.class.getDeclaredMethod("doFill",NoiseChunk.class,ChunkAccess.class);fill.setAccessible(true); + out.println("chunk "+cx+" "+cz+" "+min+" "+height); + try(var noise=new NoiseChunk(state,structure(f),settings,picker,Blender.empty(),volume)) { + for(int repeat=0;repeat>> BLOCKS = SavedTick.codec(BuiltInRegistries.BLOCK.byNameCodec()).listOf(); + private static final Codec>> FLUIDS = SavedTick.codec(BuiltInRegistries.FLUID.byNameCodec()).listOf(); + private static List> samples(List types) { + List> ticks = new ArrayList<>(); + int[] delays = {Integer.MIN_VALUE, -1, 0, 1, 100, Integer.MAX_VALUE}; + for (int i = 0; i < 256; i++) { + SavedTick tick = new SavedTick<>(types.get(i % types.size()), new BlockPos((i & 15) + (i % 17 == 0 ? 16 : 0), (i % 9 - 4) * 16, (i >>> 4) & 15), delays[i % delays.length], TickPriority.byValue(i % 11 - 5)); + ticks.add(tick); + if (i % 23 == 0) ticks.add(tick); + } + return ticks; + } + private static CompoundTag ids(List types, Registry registry) { + CompoundTag tag = new CompoundTag(); + for (T type : types) tag.putInt(registry.getKey(type).toString(), registry.getId(type)); + return tag; + } + private static Tag encode(Codec>> codec, List> ticks) { return codec.encodeStart(NbtOps.INSTANCE, ticks).getOrThrow(); } + private static List> changed(Codec>> codec, Tag input, long time) { + List> saved = SavedTick.filterTickListForChunk(codec.parse(NbtOps.INSTANCE, input).getOrThrow(), POS); + LevelChunkTicks ticks = new LevelChunkTicks<>(saved); + ticks.unpack(time); + ScheduledTick first = ticks.poll(); + if (first != null) ticks.schedule(new ScheduledTick<>(first.type(), first.pos(), time + 123, TickPriority.HIGH, 77)); + return ticks.pack(time); + } + private static void generate(Path base) throws Exception { + List blocks = List.of(Blocks.STONE, Blocks.OAK_LOG, Blocks.REPEATER, Blocks.WATER, Blocks.CHEST, Blocks.REDSTONE_WIRE); + List fluids = List.of(Fluids.EMPTY, Fluids.WATER, Fluids.FLOWING_WATER, Fluids.LAVA, Fluids.FLOWING_LAVA); + CompoundTag root = new CompoundTag(); + root.putInt("DataVersion", 5023); root.putInt("xPos", 0); root.putInt("zPos", 0); root.put("sections", new ListTag()); + root.put("block_ticks", encode(BLOCKS, samples(blocks))); root.put("fluid_ticks", encode(FLUIDS, samples(fluids))); + for (String field : List.of("block_ticks", "fluid_ticks")) { + ListTag list = (ListTag) root.get(field); + CompoundTag a = (CompoundTag) list.get(3), b = (CompoundTag) list.get(4), c = (CompoundTag) list.get(5); + a.putLong("t", Long.MAX_VALUE); a.putFloat("p", Float.NaN); + b.putDouble("t", Double.POSITIVE_INFINITY); b.putShort("p", (short) 999); b.putByte("y", (byte) -7); + c.putDouble("x", 4.75); c.putDouble("p", Double.NEGATIVE_INFINITY); + } + root.put("block_ids", ids(blocks, BuiltInRegistries.BLOCK)); root.put("fluid_ids", ids(fluids, BuiltInRegistries.FLUID)); + root.putString("unknown-root-data", "preserved through scheduled-tick mutation"); + NbtIo.write(root, base.resolve("ticks-input.nbt")); + } + private static void verify(Path base) throws Exception { + CompoundTag original = NbtIo.read(base.resolve("ticks-input.nbt")); + List> blocks = changed(BLOCKS, original.get("block_ticks"), 1000); + List> fluids = changed(FLUIDS, original.get("fluid_ticks"), Long.MAX_VALUE - 8); + CompoundTag expected = original.copy(); + expected.put("block_ticks", encode(BLOCKS, blocks)); expected.put("fluid_ticks", encode(FLUIDS, fluids)); + CompoundTag actual = NbtIo.read(base.resolve("ticks-output.nbt")); + if (!actual.equals(expected)) throw new AssertionError("Rust saved tick NBT differs from vanilla"); + Path regionPath = base.resolve("tick-region/r.0.0.mca"); + RegionStorageInfo info = new RegionStorageInfo("horizon-tick-fixture", Level.OVERWORLD, "chunk"); + try (RegionFile region = new RegionFile(info, regionPath, regionPath.getParent(), false); + DataInputStream input = region.getChunkDataInputStream(POS)) { + if (input == null || !NbtIo.read(input).equals(expected)) throw new AssertionError("Rust region tick data differs from vanilla"); + } + System.out.printf("HORIZON_TICK_DATA_RESULT {\"block_ticks\":%d,\"fluid_ticks\":%d,\"region_chunks\":1}%n", blocks.size(), fluids.size()); + } + public static void main(String[] args) throws Exception { + Path base = Path.of(args[1]); + switch (args[0]) { case "generate" -> generate(base); case "verify" -> verify(base); default -> throw new AssertionError("unknown mode"); } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTickOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTickOracle.java new file mode 100644 index 000000000..9ccf17050 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTickOracle.java @@ -0,0 +1,109 @@ +package dev.horizonlab.parity; + +import java.io.*; +import java.lang.reflect.Field; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Vec3i; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.levelgen.structure.BoundingBox; +import net.minecraft.world.ticks.*; + +/** Original trace adapter; queues, ordering, mutations and save packing are vanilla. */ +public final class VanillaTickOracle { + private static final Object[] TYPES = new Object[32]; + static { for (int i = 0; i < TYPES.length; i++) TYPES[i] = new Object(); } + private static final Field ALREADY_RUN; + static { + try { ALREADY_RUN = LevelTicks.class.getDeclaredField("alreadyRunThisTick"); ALREADY_RUN.setAccessible(true); } + catch (ReflectiveOperationException error) { throw new ExceptionInInitializerError(error); } + } + private final Set blocked = new HashSet<>(); + private final Map> chunks = new HashMap<>(); + private final Map> detached = new HashMap<>(); + private LevelTicks level = new LevelTicks<>(key -> !blocked.contains(key)); + private final PrintWriter out; + private VanillaTickOracle(PrintWriter out) { this.out = out; } + private static int type(Object type) { for (int i = 0; i < TYPES.length; i++) if (TYPES[i] == type) return i; throw new AssertionError(); } + private static final class Input { + final String[] words; int cursor = 1; + Input(String line) { words = line.split(" "); } + int integer() { return Integer.parseInt(words[cursor++]); } + long number() { return Long.parseLong(words[cursor++]); } + BlockPos pos() { return new BlockPos(integer(), integer(), integer()); } + ChunkPos chunk() { return new ChunkPos(integer(), integer()); } + BoundingBox area() { BlockPos a = pos(), b = pos(); return new BoundingBox(Math.min(a.getX(), b.getX()), Math.min(a.getY(), b.getY()), Math.min(a.getZ(), b.getZ()), Math.max(a.getX(), b.getX()), Math.max(a.getY(), b.getY()), Math.max(a.getZ(), b.getZ())); } + } + private int schedule(ScheduledTick tick) { + if (!chunks.containsKey(ChunkPos.pack(tick.pos()))) { level.schedule(tick); return 2; } + boolean duplicate = level.hasScheduledTick(tick.pos(), tick.type()); + level.schedule(tick); + return duplicate ? 0 : 1; + } + private void add(ChunkPos pos, LevelChunkTicks chunk) { chunks.put(pos.pack(), chunk); level.addContainer(pos, chunk); } + private LevelChunkTicks remove(ChunkPos pos) { level.removeContainer(pos); return chunks.remove(pos.pack()); } + private void scheduled(ScheduledTick tick) { out.printf("queued %d %d %d %d %d %d %d%n", type(tick.type()), tick.pos().getX(), tick.pos().getY(), tick.pos().getZ(), tick.triggerTick(), tick.priority().getValue(), tick.subTickOrder()); } + @SuppressWarnings("unchecked") + private ScheduledTick running() { + try { List> ticks = (List>) ALREADY_RUN.get(level); return ticks.getLast(); } + catch (ReflectiveOperationException error) { throw new AssertionError(error); } + } + private void command(String line, int lineNumber) { + Input in = new Input(line); String operation = in.words[0]; + out.printf("command %d %s%n", lineNumber, operation); + switch (operation) { + case "reset" -> { blocked.clear(); chunks.clear(); detached.clear(); level = new LevelTicks<>(key -> !blocked.contains(key)); } + case "add" -> { ChunkPos pos = in.chunk(); if (!chunks.containsKey(pos.pack())) add(pos, new LevelChunkTicks<>()); } + case "load" -> { + ChunkPos pos = in.chunk(); int count = in.integer(); List> ticks = new ArrayList<>(); + for (int i = 0; i < count; i++) ticks.add(new SavedTick<>(TYPES[in.integer()], in.pos(), in.integer(), TickPriority.byValue(in.integer()))); + remove(pos); add(pos, new LevelChunkTicks<>(ticks)); + } + case "unpack" -> { ChunkPos pos = in.chunk(); long time = in.number(); LevelChunkTicks chunk = chunks.get(pos.pack()); if (chunk != null) chunk.unpack(time); } + case "remove" -> { ChunkPos pos = in.chunk(); LevelChunkTicks chunk = remove(pos); if (chunk != null) detached.put(pos.pack(), chunk); } + case "restore" -> { ChunkPos pos = in.chunk(); if (!chunks.containsKey(pos.pack())) { LevelChunkTicks chunk = detached.remove(pos.pack()); if (chunk != null) add(pos, chunk); } } + case "enable" -> { ChunkPos pos = in.chunk(); if (in.integer() == 0) blocked.add(pos.pack()); else blocked.remove(pos.pack()); } + case "schedule" -> { ScheduledTick tick = new ScheduledTick<>(TYPES[in.integer()], in.pos(), in.number(), TickPriority.byValue(in.integer()), in.number()); out.printf("schedule %d%n", schedule(tick)); } + case "query" -> { Object kind = TYPES[in.integer()]; BlockPos pos = in.pos(); out.printf("query %d %d%n", level.hasScheduledTick(pos, kind) ? 1 : 0, level.willTickThisTick(pos, kind) ? 1 : 0); } + case "chunk" -> { LevelChunkTicks chunk = chunks.get(in.chunk().pack()); if (chunk == null) out.println("chunk absent"); else { out.printf("chunk %d%n", chunk.count()); chunk.getAll().forEach(this::scheduled); } } + case "save" -> { + LevelChunkTicks chunk = chunks.get(in.chunk().pack()); long time = in.number(); + if (chunk == null) out.println("saved absent"); else { + List> ticks = chunk.pack(time); out.printf("saved %d%n", ticks.size()); + for (SavedTick tick : ticks) out.printf("saved-value %d %d %d %d %d %d%n", type(tick.type()), tick.pos().getX(), tick.pos().getY(), tick.pos().getZ(), tick.delay(), tick.priority().getValue()); + } + } + case "reload" -> { ChunkPos pos = in.chunk(); long saveTime = in.number(), loadTime = in.number(); LevelChunkTicks old = remove(pos); if (old != null) { LevelChunkTicks chunk = new LevelChunkTicks<>(old.pack(saveTime)); chunk.unpack(loadTime); add(pos, chunk); } } + case "clear" -> level.clearArea(in.area()); + case "copy" -> { BoundingBox area = in.area(); BlockPos offset = in.pos(); level.copyArea(area, new Vec3i(offset.getX(), offset.getY(), offset.getZ())); } + case "tick" -> { + long time = in.number(); int maximum = in.integer(), action = in.integer(); Object probeKind = TYPES[in.integer()]; BlockPos probe = in.pos(); long[] order = {in.number()}; + level.tick(time, maximum, (pos, kind) -> { + ScheduledTick tick = running(); scheduled(tick); + out.printf("running %d %d %d%n", level.willTickThisTick(pos, kind) ? 1 : 0, level.hasScheduledTick(pos, kind) ? 1 : 0, level.willTickThisTick(probe, probeKind) ? 1 : 0); + switch (action) { + case 1 -> out.printf("callback-schedule %d%n", schedule(new ScheduledTick<>(kind, pos, time, tick.priority(), order[0]++))); + case 2 -> { level.clearArea(new BoundingBox(pos.getX(), pos.getY(), pos.getZ(), pos.getX() + 1, pos.getY() + 1, pos.getZ() + 1)); out.printf("callback-clear %d%n", level.willTickThisTick(probe, probeKind) ? 1 : 0); } + case 3 -> level.copyArea(new BoundingBox(pos.getX() - 2, pos.getY() - 2, pos.getZ() - 2, pos.getX() + 2, pos.getY() + 2, pos.getZ() + 2), new Vec3i(16, 0, 0)); + case 4 -> { ChunkPos chunkPos = new ChunkPos(pos.getX() >> 4, pos.getZ() >> 4); LevelChunkTicks chunk = remove(chunkPos); if (chunk != null) detached.put(chunkPos.pack(), chunk); } + case 5 -> blocked.add(ChunkPos.pack(pos)); + case 0 -> {} + default -> throw new AssertionError("unknown callback action"); + } + }); + } + default -> throw new AssertionError("unknown command: " + operation); + } + if (in.cursor != in.words.length) throw new AssertionError("extra arguments"); + out.printf("count %d%n", level.count()); + } + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + try (BufferedReader input = Files.newBufferedReader(Path.of(args[0])); PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])))) { + VanillaTickOracle oracle = new VanillaTickOracle(out); String line; int index = 0; + while ((line = input.readLine()) != null) oracle.command(line, index++); + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaValueProviderOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaValueProviderOracle.java new file mode 100644 index 000000000..3010569e7 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaValueProviderOracle.java @@ -0,0 +1,39 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import net.minecraft.util.RandomSource; +import net.minecraft.util.valueproviders.*; +import net.minecraft.world.level.levelgen.*; + +/** Original transport calling native value-provider codecs and samples. */ +public final class VanillaValueProviderOracle { + private static String bits(float value){return Integer.toHexString(Float.floatToIntBits(value));} + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();long seed=f.get("seed").getAsLong(); + RandomSource random=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + var json=JsonParser.parseString(f.get("definition").getAsString());int count=f.get("samples").getAsInt(); + if(f.get("kind").getAsString().equals("float")) { + var decoded=FloatProviders.CODEC.parse(JsonOps.INSTANCE,json); + if(decoded.result().isEmpty())out.println("decode error");else { + var provider=decoded.result().get();out.println("float "+bits(provider.min())+" "+bits(provider.max())); + for(int i=0;i decoded; + try {decoded=IntProviders.CODEC.parse(JsonOps.INSTANCE,json);} catch(IllegalArgumentException error) {out.println("decode error");out.println("tail "+random.nextLong());continue;} + if(decoded.result().isEmpty())out.println("decode error");else { + var provider=decoded.result().get();out.println("int "+provider.minInclusive()+" "+provider.maxInclusive()); + for(int i=0;i IDS = new IdMapper<>(); + static { for (int i = 0; i < 8192; i++) IDS.add("state" + i); } + private static final RegionStorageInfo INFO = new RegionStorageInfo("horizon-fixture", Level.OVERWORLD, "chunk"); + private static final Strategy BLOCKS = Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY); + private static final Codec> BLOCK_CODEC = PalettedContainer.codecRW(BlockState.CODEC, BLOCKS, Blocks.AIR.defaultBlockState()); + + private static void check(boolean value, String message) { if (!value) throw new AssertionError(message); } + private static RegionFileVersion codec(int id) { return RegionFileVersion.fromId(id); } + private static Tag read(Path path, int compression, boolean network) throws Exception { + try (DataInputStream in = new DataInputStream(codec(compression).wrap(Files.newInputStream(path)))) { + return network ? NbtIo.readAnyTag(in, NbtAccounter.unlimitedHeap()) : NbtIo.readUnnamedTag(in, NbtAccounter.unlimitedHeap()); + } + } + private static void write(Tag tag, Path path, int compression, boolean network) throws Exception { + Files.createDirectories(path.getParent()); + try (DataOutputStream out = new DataOutputStream(codec(compression).wrap(Files.newOutputStream(path)))) { + if (network) NbtIo.writeAnyTag(tag, out); else NbtIo.writeUnnamedTag(tag, out); + } + } + private static CompoundTag specimen() { + CompoundTag root = new CompoundTag(); + root.putByte("byte", Byte.MIN_VALUE); + root.putShort("short", Short.MIN_VALUE); + root.putInt("int", Integer.MIN_VALUE); + root.putLong("long", Long.MIN_VALUE); + root.putFloat("float", Float.intBitsToFloat(0x7f800001)); + root.putDouble("double", Double.NEGATIVE_INFINITY); + root.put("negative-zero-float", new FloatTag(-0.0f)); + root.put("negative-zero-double", new DoubleTag(-0.0)); + root.putString("text\0\ud800", "nul\0 / unicode \u20ac \ud83c\udf0d / unpaired \ud800x\udfff"); + root.putString("max-ascii", "a".repeat(65535)); + root.putIntArray("ints", new int[]{0, -1, Integer.MIN_VALUE, Integer.MAX_VALUE}); + root.putLongArray("longs", new long[]{0, -1, Long.MIN_VALUE, Long.MAX_VALUE}); + byte[] bytes = new byte[1_200_013]; + new Random(173).nextBytes(bytes); + root.putByteArray("bytes", bytes); + ListTag mixed = new ListTag(); + mixed.add(IntTag.valueOf(42)); + mixed.add(StringTag.valueOf("different type")); + CompoundTag wrapper = new CompoundTag(); + wrapper.putInt("", 19); + mixed.add(wrapper); + CompoundTag normal = new CompoundTag(); + normal.putString("kept", "nested"); + mixed.add(normal); + mixed.add(new ListTag()); + root.put("mixed", mixed); + CompoundTag branch = new CompoundTag(); + for (int i = 0; i < 40; i++) { CompoundTag next = new CompoundTag(); next.put("child", branch); branch = next; } + root.put("deep", branch); + return root; + } + + private static Codec> paletteCodec(boolean biome) { + // IdMapper keys use object identity. Decoding must return registry-owned + // objects, just as the real BlockState codec does. + Codec stateCodec = Codec.STRING.xmap(value -> IDS.byId(Integer.parseInt(value.substring(5))), value -> value); + return PalettedContainer.codecRW(stateCodec, biome ? Strategy.createForBiomes(IDS) : Strategy.createForBlockStates(IDS), IDS.byId(0)); + } + private static PalettedContainer palette(boolean biome, int distinct) { + PalettedContainer result = new PalettedContainer<>(IDS.byId(0), biome ? Strategy.createForBiomes(IDS) : Strategy.createForBlockStates(IDS)); + int axis = biome ? 2 : 4, mask = (1 << axis) - 1, len = biome ? 64 : 4096; + for (int i = 0; i < len; i++) result.set(i & mask, i >> (axis * 2), (i >> axis) & mask, IDS.byId(i % distinct)); + return result; + } + private static CompoundTag chunk(ChunkPos pos, boolean oversized) { + CompoundTag root = new CompoundTag(); + root.putInt("DataVersion", SharedConstants.getCurrentVersion().dataVersion().version()); + root.putInt("xPos", pos.x()); root.putInt("zPos", pos.z()); root.putInt("yPos", -4); + root.putString("Status", "minecraft:full"); + root.putString("unknown-future-field", "preserve this exactly"); + root.putLong("LastUpdate", 123456789L); + ListTag sections = new ListTag(); + CompoundTag section = new CompoundTag(); section.putByte("Y", (byte)-4); + PalettedContainer blocks = new PalettedContainer<>(Blocks.AIR.defaultBlockState(), BLOCKS); + blocks.set(1, 0, 0, Blocks.OAK_LOG.defaultBlockState()); + section.put("block_states", BLOCK_CODEC.encodeStart(NbtOps.INSTANCE, blocks).getOrThrow()); + section.putString("unknown-section-field", "retain"); + sections.add(section); root.put("sections", sections); + root.put("block_entities", new ListTag()); + if (oversized) { byte[] bytes = new byte[1_200_013]; new Random(173).nextBytes(bytes); root.putByteArray("large-fixture", bytes); } + return root; + } + + private static void generate(Path base) throws Exception { + CompoundTag specimen = specimen(); + for (int codec = 1; codec <= 4; codec++) { + write(specimen, base.resolve("nbt/" + codec + ".bin"), codec, false); + write(specimen, base.resolve("network/" + codec + ".bin"), codec, true); + Path folder = base.resolve("regions/" + codec); Files.createDirectories(folder); + try (RegionFile region = new RegionFile(INFO, folder.resolve("r.-1.0.mca"), folder, codec(codec), false)) { + for (ChunkPos pos : List.of(new ChunkPos(-32, 0), new ChunkPos(-1, 31))) { + try (DataOutputStream out = region.getChunkDataOutputStream(pos)) { NbtIo.write(chunk(pos, pos.x() == -1), out); } + } + } + } + for (boolean biome : new boolean[]{false, true}) { + for (int size : SIZES) { + if (biome && size > 64) continue; + Tag data = paletteCodec(biome).encodeStart(NbtOps.INSTANCE, palette(biome, size)).getOrThrow(); + write(data, base.resolve("palettes/" + (biome ? "biome" : "block") + "-" + size + ".nbt"), 3, false); + } + } + CompoundTag registry = new CompoundTag(); + registry.putInt("DataVersion", SharedConstants.getCurrentVersion().dataVersion().version()); + ListTag states = new ListTag(); + CompoundTag defaults = new CompoundTag(); + for (BlockState state : Block.BLOCK_STATE_REGISTRY) { + check(Block.BLOCK_STATE_REGISTRY.getId(state) == states.size(), "registry IDs are not dense"); + states.add(BlockState.FULL_CODEC.encodeStart(NbtOps.INSTANCE, state).getOrThrow()); + if (state == state.getBlock().defaultBlockState()) { + Tag encoded = BlockState.FULL_CODEC.encodeStart(NbtOps.INSTANCE, state).getOrThrow(); + defaults.putInt(((CompoundTag)encoded).getStringOr("id", ""), Block.BLOCK_STATE_REGISTRY.getId(state)); + } + } + registry.put("states", states); registry.put("defaults", defaults); + write(registry, base.resolve("block-registry.nbt"), 3, false); + System.out.println("HORIZON_WORLD_GENERATED states=" + states.size()); + } + + private static void verify(Path base) throws Exception { + int nbt = 0, palettes = 0, regions = 0, blocks = 0; + for (boolean network : new boolean[]{false, true}) for (int source = 1; source <= 4; source++) for (int target = 1; target <= 4; target++) { + String directory = network ? "network" : "nbt"; + Tag original = read(base.resolve(directory + "/" + source + ".bin"), source, network); + Tag actual = read(base.resolve("rust/" + directory + "/" + source + "-" + target + ".bin"), target, network); + check(original.equals(actual), "NBT semantic mismatch " + directory + " " + source + " " + target); + nbt++; + } + for (boolean biome : new boolean[]{false, true}) for (int size : SIZES) { + if (biome && size > 64) continue; + String name = (biome ? "biome" : "block") + "-" + size + ".nbt"; + PalettedContainer control = paletteCodec(biome).parse(NbtOps.INSTANCE, read(base.resolve("palettes/" + name), 3, false)).getOrThrow(); + int controlAxis = biome ? 2 : 4, controlMask = (1 << controlAxis) - 1; + for (int i = 0; i < (biome ? 64 : 4096); i++) + check(control.get(i & controlMask, i >> (controlAxis * 2), (i >> controlAxis) & controlMask).equals("state" + (i % size)), "vanilla palette control failed"); + for (String variant : List.of("edited", "compact")) { + Tag tag = read(base.resolve("rust/palettes/" + variant + "-" + name), 3, false); + PalettedContainer actual = paletteCodec(biome).parse(NbtOps.INSTANCE, tag).getOrThrow(); + int axis = biome ? 2 : 4, mask = (1 << axis) - 1, len = biome ? 64 : 4096; + for (int i = 0; i < len; i++) { + String expected = "state" + (i == len - 1 ? 4096 : i % size); + check(actual.get(i & mask, i >> (axis * 2), (i >> axis) & mask).equals(expected), "palette index mismatch " + name + " " + i); + blocks++; + } + palettes++; + } + } + for (int source = 1; source <= 4; source++) for (String variant : List.of("copy", "1", "2", "3", "4", "edited")) { + Path folder = base.resolve("rust/regions/" + source + "-" + variant); + try (RegionFile region = new RegionFile(INFO, folder.resolve("r.-1.0.mca"), folder, false)) { + for (ChunkPos pos : List.of(new ChunkPos(-32, 0), new ChunkPos(-1, 31))) { + try (DataInputStream in = region.getChunkDataInputStream(pos)) { + check(in != null, "chunk missing"); + CompoundTag actual = NbtIo.read(in); + CompoundTag expected = chunk(pos, pos.x() == -1); + if (variant.equals("edited") && pos.x() == -32) { + CompoundTag section = actual.getListOrEmpty("sections").getCompoundOrEmpty(0); + PalettedContainer states = BLOCK_CODEC.parse(NbtOps.INSTANCE, section.get("block_states")).getOrThrow(); + check(states.get(0, 0, 0) == Blocks.STONE.defaultBlockState(), "edited block differs"); + check(states.get(1, 0, 0) == Blocks.OAK_LOG.defaultBlockState(), "neighbor changed"); + section.put("block_states", expected.getListOrEmpty("sections").getCompoundOrEmpty(0).get("block_states")); + } + check(expected.equals(actual), "region data changed " + source + " " + variant + " " + pos); + regions++; + } + } + check(!region.hasChunk(new ChunkPos(-31, 0)), "unexpected extra chunk"); + } + } + Tag actualRegistry = read(base.resolve("rust/block-registry.nbt"), 3, false); + check(read(base.resolve("block-registry.nbt"), 3, false).equals(actualRegistry), "registry roundtrip differs"); + PalettedContainer resident = BLOCK_CODEC.parse(NbtOps.INSTANCE, read(base.resolve("rust/runtime-section.nbt"), 3, false)).getOrThrow(); + for (int i = 0; i < 4096; i++) check(resident.get(i & 15, i >> 8, (i >> 4) & 15) == Block.BLOCK_STATE_REGISTRY.byId(i * 7 % Block.BLOCK_STATE_REGISTRY.size()), "resident block state differs"); + int[] expectedStates = new int[4096]; + long random = 0x31415926L; + for (int step = 0; step < 100_000; step++) { + random = random * 6364136223846793005L + 1; + int index = (int) ((random >>> 32) % 4096); + expectedStates[index] = step % 3 == 0 ? 0 : Integer.remainderUnsigned((int) (random >>> 16), Block.BLOCK_STATE_REGISTRY.size()); + } + PalettedContainer mutated = BLOCK_CODEC.parse(NbtOps.INSTANCE, read(base.resolve("rust/runtime-mutated.nbt"), 3, false)).getOrThrow(); + for (int i = 0; i < 4096; i++) check(mutated.get(i & 15, i >> 8, (i >> 4) & 15) == Block.BLOCK_STATE_REGISTRY.byId(expectedStates[i]), "mutated resident block state differs"); + System.out.printf("HORIZON_WORLD_RESULT {\"nbt_pairs\":%d,\"palettes\":%d,\"palette_values\":%d,\"region_chunks\":%d,\"registry_states\":%d,\"resident_values\":8192}%n", nbt, palettes, blocks, regions, Block.BLOCK_STATE_REGISTRY.size()); + } + + public static void main(String[] args) throws Exception { + if (args[0].equals("generate")) generate(Path.of(args[1])); + else if (args[0].equals("verify")) verify(Path.of(args[1])); + else throw new IllegalArgumentException("unknown mode"); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenOracle.java new file mode 100644 index 000000000..e42ba7edd --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenOracle.java @@ -0,0 +1,387 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import com.google.gson.JsonParser; +import com.mojang.serialization.JsonOps; +import net.minecraft.world.level.levelgen.LegacyRandomSource; +import net.minecraft.world.level.levelgen.XoroshiroRandomSource; +import net.minecraft.world.level.levelgen.synth.NormalNoise; + +/** Original JSON transport; decoding and evaluation use vanilla classes. */ +public final class VanillaWorldgenOracle { + private static java.util.Map>> biomePresets; + private static void registryProbe(String path,long seed,boolean legacy,boolean optimized,String setting,PrintWriter out) throws Exception { + registryProbe(path,seed,legacy,optimized,setting,null,out); + } + @SuppressWarnings("unchecked") + private static void registryProbe(String path,long seed,boolean legacy,boolean optimized,String setting,String aquiferFixture,PrintWriter out) throws Exception { + var bundle=JsonParser.parseString(Files.readString(Path.of(path))).getAsJsonObject(); + var noises=new net.minecraft.core.MappedRegistry(net.minecraft.core.registries.Registries.NOISE,com.mojang.serialization.Lifecycle.stable()); + var densities=new net.minecraft.core.MappedRegistry(net.minecraft.core.registries.Registries.DENSITY_FUNCTION,com.mojang.serialization.Lifecycle.stable()); + var noiseLookup=noises.createRegistrationLookup();var densityLookup=densities.createRegistrationLookup(); + var ops=net.minecraft.resources.RegistryOps.create(JsonOps.INSTANCE,new net.minecraft.resources.RegistryOps.RegistryInfoLookup() { + public java.util.Optional> lookup(net.minecraft.resources.ResourceKey> key) { + if(key.equals(net.minecraft.core.registries.Registries.NOISE))return (java.util.Optional>)(java.util.Optional)java.util.Optional.of(noiseLookup); + if(key.equals(net.minecraft.core.registries.Registries.DENSITY_FUNCTION))return (java.util.Optional>)(java.util.Optional)java.util.Optional.of(densityLookup); + return java.util.Optional.empty(); + } + }); + for(var entry:bundle.getAsJsonObject("noises").entrySet()) { + var key=net.minecraft.resources.ResourceKey.create(net.minecraft.core.registries.Registries.NOISE,net.minecraft.resources.Identifier.parse(entry.getKey())); + var noise=NormalNoise.DIRECT_CODEC.parse(ops,JsonParser.parseString(entry.getValue().getAsString())).getOrThrow(); + noises.register(key,noise,net.minecraft.core.RegistrationInfo.BUILT_IN); + } + noises.freeze(); + java.util.Map functions=new java.util.TreeMap<>(); + for(var entry:bundle.getAsJsonObject("densities").entrySet()) { + var key=net.minecraft.resources.ResourceKey.create(net.minecraft.core.registries.Registries.DENSITY_FUNCTION,net.minecraft.resources.Identifier.parse(entry.getKey())); + var function=net.minecraft.world.level.levelgen.densityfunction.DensityFunctions.DIRECT_CODEC.parse(ops,JsonParser.parseString(entry.getValue().getAsString())).getOrThrow(); + densities.register(key,function,net.minecraft.core.RegistrationInfo.BUILT_IN);functions.put(entry.getKey(),function); + } + densities.freeze(); + var zero=net.minecraft.world.level.levelgen.densityfunction.DensityFunctions.zero(); + var router=new net.minecraft.world.level.levelgen.NoiseRouter(zero,zero,zero,zero,zero,zero,zero,zero); + if(setting!=null) { + var settings=JsonParser.parseString(bundle.getAsJsonObject("settings").get(setting).getAsString()).getAsJsonObject(); + router=net.minecraft.world.level.levelgen.NoiseRouter.CODEC.parse(ops,settings.get("noise_router")).getOrThrow(); + functions=new java.util.LinkedHashMap<>(); + functions.put("temperature",router.temperature());functions.put("vegetation",router.vegetation()); + functions.put("continents",router.continents());functions.put("erosion",router.erosion()); + functions.put("depth",router.depth());functions.put("ridges",router.ridges()); + functions.put("chunk_surface_level",router.chunkSurfaceLevel());functions.put("final_density",router.finalDensity()); + } + var state=net.minecraft.world.level.levelgen.RandomState.create(noises,seed,legacy,net.minecraft.world.level.block.Blocks.STONE.defaultBlockState(),63,router); + var compilerField=state.getClass().getDeclaredField("densityFunctionCompiler");compilerField.setAccessible(true); + var compiler=(net.minecraft.world.level.levelgen.densityfunction.DensityFunctionCompiler)compilerField.get(state); + var contextField=compiler.getClass().getDeclaredField("context");contextField.setAccessible(true); + var compileContext=(net.minecraft.world.level.levelgen.densityfunction.DensityFunction.CompileContext)contextField.get(compiler); + var countField=compiler.getClass().getDeclaredField("nextCacheId");countField.setAccessible(true); + if(aquiferFixture!=null) { + var fixture=JsonParser.parseString(aquiferFixture).getAsJsonObject(); + var settings=JsonParser.parseString(bundle.getAsJsonObject("settings").get(setting).getAsString()).getAsJsonObject(); + var configJson=fixture.has("config")?JsonParser.parseString(fixture.get("config").getAsString()):settings.get("aquifers"); + if(configJson==null){out.println("aquifer config error");return;} + net.minecraft.world.level.levelgen.Aquifer.Config config; + try{var decoded=net.minecraft.world.level.levelgen.Aquifer.Config.CODEC.parse(ops,configJson).result(); + if(decoded.isEmpty()){out.println("aquifer config error");return;}config=decoded.get();} + catch(IllegalArgumentException | IllegalStateException e){out.println("aquifer config error");return;} + noiseAquiferProbe(fixture,config,compiler,state,countField,out);return; + } + out.println(setting==null?"registry "+functions.size():"router "+setting+" "+functions.size()); + var sharedContext=createContext(); + for(var entry:functions.entrySet()) { + var function=entry.getValue();var range=function.range(); + out.printf("entry %s %s %s %d%n",entry.getKey(),bits(range.min()),bits(range.max()),function.domainAxes()); + net.minecraft.world.level.levelgen.densityfunction.DensitySampler sampler; + try { sampler=optimized?compiler.getSampler(function):function.compileSampler(compileContext); } + catch(IllegalArgumentException | IllegalStateException e){out.println("compile error");continue;} + out.println("compile ok "+countField.getInt(compiler)); + var context=setting==null?createContext():sharedContext; + int[][] points={{0,0,0},{-17,-64,32},{30000000,319,-30000000},{1,-1,-1}}; + for(var point:points)out.println("density "+bits(sampler.sampleValue(context,point[0],point[1],point[2]))); + int[][] origins={{-17,-64,32},{-16,-64,32},{-17,0,32}},steps={{1,1,1},{4,8,4},{4,1,4}},extents={{2,9,2},{2,9,2},{3,1,2}}; + for(int v=0;v<(setting==null?2:3);v++) { + var volume=new net.minecraft.world.level.levelgen.densityfunction.DensityVolume(extents[v][0],extents[v][1],extents[v][2],origins[v][0],origins[v][1],origins[v][2],steps[v][0],steps[v][1],steps[v][2]); + var buffer=net.minecraft.world.level.levelgen.densityfunction.DensityBuffer.createUnpooled(volume.size());buffer.fill(0.0f); + for(int repeat=0;repeat<2;repeat++) { + String status="ok";try{sampler.sampleVolume(context,buffer,volume);}catch(IllegalArgumentException | IllegalStateException e){status="error";} + out.println("volume "+status);for(int i=0;i>>(); + biomePresets.forEach((preset,list)->presets.put(preset.id().toString(),list)); + for(var preset:presets.entrySet()) { + // Resolver lookup needs holder identities, not biome properties. + // Registration placeholders retain actual keys without fabricating + // biome implementations or invoking their gameplay behavior. + var biomes=new net.minecraft.core.MappedRegistry(net.minecraft.core.registries.Registries.BIOME,com.mojang.serialization.Lifecycle.stable()); + var lookup=biomes.createRegistrationLookup(); + var entries=new java.util.ArrayList>>(); + for(var entry:preset.getValue().values())entries.add(com.mojang.datafixers.util.Pair.of(entry.getFirst(),lookup.getOrThrow(entry.getSecond()))); + var source=net.minecraft.world.level.biome.MultiNoiseBiomeSource.createFromList(new net.minecraft.world.level.biome.Climate.ParameterList<>(entries)); + out.println("biomes "+preset.getKey()+" "+entries.size()); + var resolver=source.createResolver(climate); + for(var position:positions)out.println("biome "+resolver.getNoiseBiome(position[0],position[1],position[2]).unwrapKey().orElseThrow().identifier()); + int[][] minima={{-5,-16,8},{-4,-16,8},{Integer.MAX_VALUE-1,Integer.MIN_VALUE,-1}},extents={{3,4,2},{3,4,2},{2,2,2}}; + for(int v=0;v<3;v++) { + var min=minima[v];var size=extents[v]; + var bulk=source.createResolverForChunk(climate,min[0],min[1],min[2],size[0],size[1],size[2]); + var queries=new java.util.ArrayList(); + for(int z=0;z(queries);var reverse=new java.util.ArrayList<>(queries);java.util.Collections.reverse(reverse);queries.addAll(reverse);queries.addAll(forward.subList(0,3)); + for(var position:queries)out.println("biomecell "+bulk.getNoiseBiome(position[0],position[1],position[2]).unwrapKey().orElseThrow().identifier()); + } + } + + } + + } + private static net.minecraft.world.level.levelgen.densityfunction.SamplerContext createContext() { + return net.minecraft.world.level.levelgen.densityfunction.SamplerContext.builder().enableCaches().useBufferArena(new net.minecraft.world.level.levelgen.densityfunction.DensityBufferArena() { + public net.minecraft.world.level.levelgen.densityfunction.ScopedDensityBuffer acquire(int size) { var buffer=net.minecraft.world.level.levelgen.densityfunction.DensityBufferArena.GLOBAL.acquire(size);buffer.fill(0.0f);return buffer; } + public void release(net.minecraft.world.level.levelgen.densityfunction.ScopedDensityBuffer buffer) { net.minecraft.world.level.levelgen.densityfunction.DensityBufferArena.GLOBAL.release(buffer); } + }).build(); + } + private static void leafOrder(Object node,PrintWriter out) throws Exception { + try { + var value=node.getClass().getDeclaredField("value");value.setAccessible(true);out.println("leaf "+value.get(node)); + } catch(NoSuchFieldException e) { + var children=node.getClass().getDeclaredField("children");children.setAccessible(true); + for(var child:(Object[])children.get(node))leafOrder(child,out); + } + } + @SuppressWarnings("unchecked") + private static void indexProbe(int branching,String json,PrintWriter out) throws Exception { + var input=JsonParser.parseString(json).getAsJsonObject(); + var entries=new java.util.ArrayList>(); + for(var raw:input.getAsJsonArray("entries")) { + var entry=raw.getAsJsonObject();var coordinates=entry.getAsJsonArray("coordinates"); + var p=new net.minecraft.world.level.biome.Climate.Parameter[6]; + for(int i=0;i<6;i++){var coord=coordinates.get(i).getAsJsonArray();p[i]=new net.minecraft.world.level.biome.Climate.Parameter(coord.get(0).getAsLong(),coord.get(1).getAsLong());} + entries.add(com.mojang.datafixers.util.Pair.of(new net.minecraft.world.level.biome.Climate.ParameterPoint(p[0],p[1],p[2],p[3],p[4],p[5],entry.get("offset").getAsLong()),entries.size())); + } + // The Rust bounded API accepts branching 2..32. Other reference rebuild + // values can diverge or fail to terminate and are outside this transport. + if(branching<2 || branching>32){out.println("index error");return;} + var constructor=net.minecraft.world.level.biome.Climate.ParameterList.class.getDeclaredConstructor(java.util.List.class,int.class);constructor.setAccessible(true); + net.minecraft.world.level.biome.Climate.ParameterList index; + try{index=(net.minecraft.world.level.biome.Climate.ParameterList)constructor.newInstance(entries,branching);} + catch(java.lang.reflect.InvocationTargetException e){out.println("index error");return;} + var indexField=index.getClass().getDeclaredField("index");indexField.setAccessible(true);var tree=indexField.get(index); + var rootField=tree.getClass().getDeclaredField("root");rootField.setAccessible(true); + var lastField=tree.getClass().getDeclaredField("lastResult");lastField.setAccessible(true);var last=(ThreadLocal)lastField.get(tree); + out.println("index ok "+entries.size());leafOrder(rootField.get(tree),out); + for(var target:input.getAsJsonArray("targets")) { + var values=target.getAsJsonArray();var point=new net.minecraft.world.level.biome.Climate.TargetPoint(values.get(0).getAsLong(),values.get(1).getAsLong(),values.get(2).getAsLong(),values.get(3).getAsLong(),values.get(4).getAsLong(),values.get(5).getAsLong()); + int brute=index.findValueBruteForce(point);out.println("brute "+brute+" "+entries.get(brute).getFirst().fitness(point)); + try{int found=index.findValue(point);out.println("cached "+found+" "+entries.get(found).getFirst().fitness(point));} + catch(NullPointerException e){out.println("cached error");} + var previous=last.get();last.remove(); + try{int found=index.findValue(point);out.println("fresh "+found+" "+entries.get(found).getFirst().fitness(point));} + catch(NullPointerException e){out.println("fresh error");} + finally{if(previous==null)last.remove();else last.set(previous);} + } + } + private static void settingsProbe(net.minecraft.world.level.levelgen.NoiseSettings settings,PrintWriter out) { + out.println("settings "+settings.minY()+" "+settings.height()); + int[][] accessors={{-64,384},{0,128},{-2032,4064},{17,15},{2048,16},{Integer.MAX_VALUE,1},{Integer.MIN_VALUE,Integer.MAX_VALUE}}; + for(var accessor:accessors) { + var clamped=settings.clampToHeightAccessor(net.minecraft.world.level.LevelHeightAccessor.create(accessor[0],accessor[1])); + out.println("clamped "+clamped.minY()+" "+clamped.height()); + } + } + private static net.minecraft.world.level.block.state.BlockState fluidState(int label) { + return switch(label) { + case 0 -> net.minecraft.world.level.block.Blocks.WATER.defaultBlockState(); + case 1 -> net.minecraft.world.level.block.Blocks.LAVA.defaultBlockState(); + case 2 -> net.minecraft.world.level.block.Blocks.AIR.defaultBlockState(); + case 3 -> net.minecraft.world.level.block.Blocks.STONE.defaultBlockState(); + case 4 -> net.minecraft.world.level.block.Blocks.CAVE_AIR.defaultBlockState(); + case 5 -> net.minecraft.world.level.block.Blocks.VOID_AIR.defaultBlockState(); + case 6 -> net.minecraft.world.level.block.Blocks.WATER.defaultBlockState().setValue(net.minecraft.world.level.block.LiquidBlock.LEVEL,1); + case 7 -> net.minecraft.world.level.block.Blocks.LAVA.defaultBlockState().setValue(net.minecraft.world.level.block.LiquidBlock.LEVEL,1); + default -> throw new AssertionError("unknown fluid label"); + }; + } + private static int fluidLabel(net.minecraft.world.level.block.state.BlockState state) { + for(int label=0;label<8;label++)if(fluidState(label)==state)return label; + throw new AssertionError("unknown fluid state"); + } + private static void aquiferProbe(String line,PrintWriter out) throws Exception { + if(net.minecraft.SharedConstants.DEBUG_DISABLE_FLUID_GENERATION)throw new AssertionError("reference requires regular fluid generation"); + var args=line.split(" ");int sea=Integer.parseInt(args[1]),label=Integer.parseInt(args[2]),x=Integer.parseInt(args[3]),y=Integer.parseInt(args[4]),z=Integer.parseInt(args[5]); + double density=Double.longBitsToDouble(Long.parseUnsignedLong(args[6],16)); + var empty=new net.minecraft.world.level.levelgen.Aquifer.FluidStatus(-4064,fluidState(2)); + var lava=new net.minecraft.world.level.levelgen.Aquifer.FluidStatus(-54,fluidState(1)); + var fluid=new net.minecraft.world.level.levelgen.Aquifer.FluidStatus(sea,fluidState(label)); + var method=net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator.class.getDeclaredMethod("lambda$createFluidPicker$0",net.minecraft.world.level.levelgen.Aquifer.FluidStatus.class,int.class,net.minecraft.world.level.levelgen.Aquifer.FluidStatus.class,net.minecraft.world.level.levelgen.Aquifer.FluidStatus.class,int.class,int.class,int.class);method.setAccessible(true); + net.minecraft.world.level.levelgen.Aquifer.FluidPicker picker=(px,py,pz)->{ + try{return (net.minecraft.world.level.levelgen.Aquifer.FluidStatus)method.invoke(null,empty,sea,lava,fluid,px,py,pz);} + catch(ReflectiveOperationException e){throw new AssertionError(e);} + }; + var status=picker.computeFluid(x,y,z);out.println("fluid "+status.fluidLevel()+" "+fluidLabel(status.fluidType())+" "+fluidLabel(status.at(y))); + var calls=new java.util.concurrent.atomic.AtomicInteger(); + var aquifer=net.minecraft.world.level.levelgen.Aquifer.createDisabled((px,py,pz)->{calls.incrementAndGet();return picker.computeFluid(px,py,pz);}); + var substance=aquifer.computeSubstance(x,y,z,density); + out.println("substance "+(substance==null?"default_solid":Integer.toString(fluidLabel(substance)))+" "+aquifer.shouldScheduleFluidUpdate()+" "+calls.get()); + } + private static void noiseAquiferProbe(com.google.gson.JsonObject fixture,net.minecraft.world.level.levelgen.Aquifer.Config config,net.minecraft.world.level.levelgen.densityfunction.DensityFunctionCompiler compiler,net.minecraft.world.level.levelgen.RandomState state,java.lang.reflect.Field countField,PrintWriter out) throws Exception { + var functions=new net.minecraft.world.level.levelgen.densityfunction.DensityFunction[]{config.barrierNoise(),config.fluidLevelFloodednessNoise(),config.fluidLevelSpreadNoise(),config.lavaNoise(),config.exclusion(),config.surfaceLevel()}; + var samplers=new net.minecraft.world.level.levelgen.densityfunction.DensitySampler[6]; + try{for(int i=0;i<6;i++)samplers[i]=compiler.getSampler(functions[i]);} + catch(IllegalArgumentException | IllegalStateException e){out.println("aquifer compile error");return;} + out.println("aquifer compile ok "+countField.getInt(compiler)); + var events=new java.util.ArrayList();var context=createContext();var binding=new java.util.concurrent.atomic.AtomicInteger(); + net.minecraft.world.level.levelgen.densityfunction.DensitySamplerSet set=function->{ + int field=binding.getAndIncrement();var inner=samplers[field]; + if(fixture.has("overrides") && !fixture.getAsJsonArray("overrides").get(field).isJsonNull())inner=net.minecraft.world.level.levelgen.densityfunction.DensityFunctions.constant(Float.intBitsToFloat(Integer.parseUnsignedInt(fixture.getAsJsonArray("overrides").get(field).getAsString(),16))).compileSampler(null); + var source=inner; + return new net.minecraft.world.level.levelgen.densityfunction.DensitySampler(){ + private int calls; + private void enter(String event){events.add(event);calls++;if(fixture.has("fail") && fixture.getAsJsonArray("fail").get(0).getAsInt()==field && fixture.getAsJsonArray("fail").get(1).getAsInt()==calls){events.add("sample failure "+field);throw new IllegalStateException("injected sampler failure");}} + public float sampleValue(net.minecraft.world.level.levelgen.densityfunction.SamplerContext ctx,int x,int y,int z){ + enter("sample "+field+" value "+x+" "+y+" "+z); + try{float value=source.sampleValue(ctx,x,y,z);events.add("value "+bits(value));return value;} + catch(IllegalArgumentException | IllegalStateException e){events.add("value error");throw e;} + } + public void sampleVolume(net.minecraft.world.level.levelgen.densityfunction.SamplerContext ctx,net.minecraft.world.level.levelgen.densityfunction.DensityBuffer buffer,net.minecraft.world.level.levelgen.densityfunction.DensityVolume volume){ + enter("sample "+field+" volume "+volume.sizeX()+" "+volume.sizeY()+" "+volume.sizeZ()+" "+volume.minBlockX()+" "+volume.minBlockY()+" "+volume.minBlockZ()+" "+volume.stepBlockX()+" "+volume.stepBlockY()+" "+volume.stepBlockZ()); + String result="ok"; + try{source.sampleVolume(ctx,buffer,volume);}catch(IllegalArgumentException | IllegalStateException e){result="error";throw e;} + finally{events.add("sample volume "+result);for(int i=0;i{try{var result=(net.minecraft.world.level.levelgen.Aquifer.FluidStatus)method.invoke(null,empty,sea,lava,fluid,x,y,z);events.add("pick "+x+" "+y+" "+z+" "+result.fluidLevel()+" "+fluidLabel(result.fluidType()));return result;}catch(ReflectiveOperationException e){throw new AssertionError(e);}}; + var size=fixture.getAsJsonArray("sizes");var min=fixture.getAsJsonArray("minimum");var steps=fixture.getAsJsonArray("steps"); + var volume=new net.minecraft.world.level.levelgen.densityfunction.DensityVolume(size.get(0).getAsInt(),size.get(1).getAsInt(),size.get(2).getAsInt(),min.get(0).getAsInt(),min.get(1).getAsInt(),min.get(2).getAsInt(),steps.get(0).getAsInt(),steps.get(1).getAsInt(),steps.get(2).getAsInt()); + net.minecraft.world.level.levelgen.Aquifer aquifer; + try{aquifer=config.create(set,state.getOrCreateRandomFactory(net.minecraft.resources.Identifier.withDefaultNamespace("aquifer")),volume,picker);} + catch(IllegalArgumentException | IllegalStateException e){events.forEach(out::println);out.println("aquifer create error");return;} + events.forEach(out::println);events.clear(); + var skip=aquifer.getClass().getDeclaredField("skipSamplingAboveY");skip.setAccessible(true);out.println("aquifer ready "+skip.getInt(aquifer)); + for(var raw:fixture.getAsJsonArray("queries")){ + var query=raw.getAsJsonArray();String result; + try{var block=aquifer.computeSubstance(query.get(0).getAsInt(),query.get(1).getAsInt(),query.get(2).getAsInt(),Double.longBitsToDouble(Long.parseUnsignedLong(query.get(3).getAsString(),16)));result=block==null?"default_solid":Integer.toString(fluidLabel(block));} + catch(IllegalArgumentException | IllegalStateException | IndexOutOfBoundsException e){result="error";} + events.forEach(out::println);events.clear();out.println("aquifer result "+result+" "+aquifer.shouldScheduleFluidUpdate()); + } + var locationsField=aquifer.getClass().getDeclaredField("aquiferLocationCache");locationsField.setAccessible(true);var locations=(long[])locationsField.get(aquifer); + var statusesField=aquifer.getClass().getDeclaredField("aquiferCache");statusesField.setAccessible(true);var statuses=(net.minecraft.world.level.levelgen.Aquifer.FluidStatus[])statusesField.get(aquifer); + for(int i=0;i();surfaces.long2IntEntrySet().forEach(entry->sorted.put(entry.getLongKey(),entry.getIntValue())); + sorted.forEach((key,value)->out.println("aquifer surface "+key+" "+value)); + } + + private static void tagEntryProbe(String json,PrintWriter out){ + var decoded=net.minecraft.tags.TagEntry.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(json)).result(); + if(decoded.isEmpty())out.println("tag entry error");else out.println("tag entry "+decoded.get()); + } + private static void tagFileProbe(String json,PrintWriter out){ + var decoded=net.minecraft.tags.TagFile.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(json)).result(); + if(decoded.isEmpty()){out.println("tag file error");return;} + var file=decoded.get();out.println("tag file "+file.replace()+" "+file.entries().size()); + for(var entry:file.entries())out.println("tag entry "+entry); + } + private static void tagsProbe(com.google.gson.JsonObject fixture,PrintWriter out)throws Exception { + out.println("tags resources "+fixture.getAsJsonArray("files").size()); + var definitions=new java.util.HashMap>(); + for(var raw:fixture.getAsJsonArray("files")){ + var row=raw.getAsJsonArray();var name=net.minecraft.resources.Identifier.parse(row.get(0).getAsString());String source=row.get(1).getAsString(); + var json=JsonParser.parseString(row.get(2).getAsString());var entries=definitions.computeIfAbsent(name,ignored->new java.util.ArrayList<>()); + var decoded=net.minecraft.tags.TagFile.CODEC.parse(JsonOps.INSTANCE,json).result(); + if(decoded.isEmpty()){out.println("tag resource error "+name+" "+source);continue;} + var file=decoded.get();if(file.replace())entries.clear(); + for(var entry:file.entries())entries.add(new net.minecraft.tags.TagLoader.EntryWithSource(entry,source)); + } + var elements=fixture.getAsJsonObject("elements");var trace=new java.util.ArrayList(); + var loader=new net.minecraft.tags.TagLoader((id,required)->{ + trace.add("tag lookup "+id+" "+required); + return elements.has(id.toString())?java.util.Optional.of(elements.get(id.toString()).getAsString()):java.util.Optional.empty(); + },"tags/block"); + var result=loader.build(definitions);trace.forEach(out::println); + var sorted=new java.util.TreeMap>();result.forEach((key,value)->sorted.put(key.toString(),value)); + out.println("tags built "+sorted.size()); + for(var entry:sorted.entrySet()){out.println("tag members "+entry.getKey()+" "+entry.getValue().size());for(var value:entry.getValue())out.println("tag member "+value);} + definitions.keySet().stream().filter(name->!result.containsKey(name)).map(Object::toString).sorted().forEach(name->out.println("tag missing "+name)); + } + private static void tagRegistryProbe(String path,PrintWriter out)throws Exception { + var bundle=JsonParser.parseString(Files.readString(Path.of(path))).getAsJsonObject(); + var fixture=new com.google.gson.JsonObject();var files=new com.google.gson.JsonArray(); + var sorted=new java.util.TreeMap();bundle.getAsJsonObject("tags").entrySet().forEach(entry->sorted.put(entry.getKey(),entry.getValue())); + sorted.forEach((name,json)->{var row=new com.google.gson.JsonArray();row.add(name);row.add("vanilla");row.add(json);files.add(row);});fixture.add("files",files); + // This lookup table must agree with the actual reference registry. + var elements=bundle.getAsJsonObject("block_elements"); + if(elements.size()!=net.minecraft.core.registries.BuiltInRegistries.BLOCK.keySet().size())throw new AssertionError("block identifiers differ"); + for(var name:elements.keySet())if(!net.minecraft.core.registries.BuiltInRegistries.BLOCK.containsKey(net.minecraft.resources.Identifier.parse(name)))throw new AssertionError("unknown exported block"); + fixture.add("elements",elements);tagsProbe(fixture,out); + } + + private static String bits(float value) { return Integer.toUnsignedString(Float.floatToIntBits(value)); } + public static void main(String[] paths) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var octavesField=NormalNoise.class.getDeclaredField("octaves");octavesField.setAccessible(true); + var factorField=NormalNoise.class.getDeclaredField("normalizationFactor");factorField.setAccessible(true); + try(var reader=Files.newBufferedReader(Path.of(paths[0]),StandardCharsets.UTF_8); + var out=new PrintWriter(Files.newBufferedWriter(Path.of(paths[1]),StandardCharsets.UTF_8))) { + String line; + while((line=reader.readLine())!=null) { + if(line.startsWith("tag_entry ")){tagEntryProbe(line.substring(10),out);continue;} + if(line.startsWith("tag_file ")){tagFileProbe(line.substring(9),out);continue;} + if(line.startsWith("tag_registry ")){tagRegistryProbe(line.substring(13),out);continue;} + if(line.startsWith("tags ")){tagsProbe(JsonParser.parseString(line.substring(5)).getAsJsonObject(),out);continue;} + if(line.startsWith("noise_aquifer ")){var fields=line.split(" ",6);registryProbe(fields[3],Long.parseLong(fields[1]),fields[2].equals("1"),true,fields[4],fields[5],out);continue;} + if(line.startsWith("aquifer ")){aquiferProbe(line,out);continue;} + if(line.startsWith("noise_settings ")) { + var decoded=net.minecraft.world.level.levelgen.NoiseSettings.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(line.substring("noise_settings ".length()))).result(); + if(decoded.isEmpty())out.println("settings error");else settingsProbe(decoded.get(),out);continue; + } + if(line.startsWith("settings_create ")) { + var values=line.split(" "); + try{settingsProbe(net.minecraft.world.level.levelgen.NoiseSettings.create(Integer.parseInt(values[1]),Integer.parseInt(values[2])),out);} + catch(IllegalStateException e){out.println("settings error");}continue; + } + if(line.startsWith("climate_parameter ")) { + var decoded=net.minecraft.world.level.biome.Climate.Parameter.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(line.substring("climate_parameter ".length()))).result(); + if(decoded.isEmpty())out.println("parameter error");else{var p=decoded.get();out.println("parameter "+p.min()+" "+p.max());}continue; + } + if(line.startsWith("climate_point ")) { + var decoded=net.minecraft.world.level.biome.Climate.ParameterPoint.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(line.substring("climate_point ".length()))).result(); + if(decoded.isEmpty())out.println("parameterpoint error");else{ + var p=decoded.get();out.print("parameterpoint"); + for(var coordinate:new net.minecraft.world.level.biome.Climate.Parameter[]{p.temperature(),p.humidity(),p.continentalness(),p.erosion(),p.depth(),p.weirdness()})out.print(" "+coordinate.min()+" "+coordinate.max()); + out.println(" "+p.offset()); + }continue; + } + if(line.startsWith("index ")) {var fields=line.split(" ",3);indexProbe(Integer.parseInt(fields[1]),fields[2],out);continue;} + if(line.startsWith("quantize ")) { + var values=line.split(" ");out.print("quantized"); + for(int i=1;i<=6;i++)out.print(" "+net.minecraft.world.level.biome.Climate.quantizeCoord(Float.intBitsToFloat(Integer.parseUnsignedInt(values[i],16)))); + out.println();out.println("unquantized "+bits(net.minecraft.world.level.biome.Climate.unquantizeCoord(Long.parseLong(values[7]))));continue; + } + String[] args=line.split(" ",5); + if(args[0].equals("router")){var fields=args[4].split(" ",2);registryProbe(fields[0],Long.parseLong(args[1]),args[2].equals("1"),args[3].equals("1"),fields[1],out);continue;} + if(args[0].equals("registry")){registryProbe(args[4],Long.parseLong(args[1]),args[2].equals("1"),args[3].equals("1"),null,out);continue;} + if(!args[0].equals("noise"))throw new AssertionError("unknown command"); + long seed=Long.parseLong(args[1]);boolean legacy=args[2].equals("1"),nether=args[3].equals("1"); + var decoded=NormalNoise.DIRECT_CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(args[4])).result(); + if(decoded.isEmpty()){out.println("decode error");continue;} + var noise=decoded.get();var octaves=(java.util.List)octavesField.get(noise); + out.printf("decode %d %s %s %s%n",octaves.size(),Long.toUnsignedString(Double.doubleToLongBits(factorField.getDouble(noise))),bits(noise.range().min()),bits(noise.range().max())); + for(var octave:octaves) { + var index=octave.getClass().getDeclaredMethod("octaveIndex");index.setAccessible(true); + var frequency=octave.getClass().getDeclaredMethod("frequency");frequency.setAccessible(true); + var amplitude=octave.getClass().getDeclaredMethod("amplitude");amplitude.setAccessible(true); + out.printf("octave %d %s %s%n",index.invoke(octave),Long.toUnsignedString(Double.doubleToLongBits((Double)frequency.invoke(octave))),Long.toUnsignedString(Double.doubleToLongBits((Double)amplitude.invoke(octave)))); + } + net.minecraft.util.RandomSource random=legacy?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + net.minecraft.world.level.levelgen.synth.Noise sampler; + try { sampler=nether?noise.createForLegacyNetherBiome(random):noise.create(random); } + catch(IllegalArgumentException | IllegalStateException e){out.println("sample error "+random.nextLong());continue;} + double[][] points={{0,0,0},{-17.25,64.125,32.5},{30e6,-64,-30e6},{1.25,-.5,-3.75},{33554432,-2048,-33554433}}; + for(var point:points)out.printf("query %s %s%n",bits(sampler.get(point[0],point[2])),bits(sampler.get(point[0],point[1],point[2]))); + out.println("parent "+random.nextLong()); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenRandomOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenRandomOracle.java new file mode 100644 index 000000000..d074834d0 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenRandomOracle.java @@ -0,0 +1,50 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.levelgen.*; + +/** Native world-generation bit adapter, forks, counters and seeding methods. */ +public final class VanillaWorldgenRandomOracle { + public static void main(String[] args) throws Exception { + Path dir=Path.of(args[1]); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { + for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { + var f=JsonParser.parseString(line).getAsJsonObject();long seed=f.get("seed").getAsLong(); + RandomSource source=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + source.consumeCount(f.get("warmup").getAsInt()); + for(int i=1;i{random=root;out.println("root");} + case "bits"->out.println("bits "+root.next(op.get(1).getAsInt())); + case "decoration"->out.println("decoration "+root.setDecorationSeed(op.get(1).getAsLong(),op.get(2).getAsInt(),op.get(3).getAsInt())); + case "feature"->{root.setFeatureSeed(op.get(1).getAsLong(),op.get(2).getAsInt(),op.get(3).getAsInt());out.println("feature");} + case "large"->{root.setLargeFeatureSeed(op.get(1).getAsLong(),op.get(2).getAsInt(),op.get(3).getAsInt());out.println("large");} + case "salt"->{root.setLargeFeatureWithSalt(op.get(1).getAsLong(),op.get(2).getAsInt(),op.get(3).getAsInt(),op.get(4).getAsInt());out.println("salt");} + case "slime"->{var r=WorldgenRandom.seedSlimeChunk(op.get(1).getAsInt(),op.get(2).getAsInt(),op.get(3).getAsLong(),op.get(4).getAsLong());out.println("slime "+r.nextLong()+" "+r.nextInt(10));} + case "int"->out.println("int "+random.nextInt()); + case "long"->out.println("long "+random.nextLong()); + case "bool"->out.println("bool "+random.nextBoolean()); + case "float"->out.println("float "+Integer.toUnsignedString(Float.floatToRawIntBits(random.nextFloat()),16)); + case "double"->out.println("double "+Long.toUnsignedString(Double.doubleToRawLongBits(random.nextDouble()),16)); + case "bound"->{try{out.println("bound "+random.nextInt(op.get(1).getAsInt()));}catch(IllegalArgumentException e){out.println("bound error");}} + case "seed"->{random.setSeed(op.get(1).getAsLong());out.println("seed");} + case "consume"->{random.consumeCount(op.get(1).getAsInt());out.println("consume");} + case "fork"->{random=random.fork();out.println("fork");} + case "pos"->{random=random.forkPositional().at(op.get(1).getAsInt(),op.get(2).getAsInt(),op.get(3).getAsInt());out.println("pos");} + case "pos_seed"->{random=random.forkPositional().fromSeed(op.get(1).getAsLong());out.println("pos_seed");} + case "pos_hash"->{var values=op.get(1).getAsJsonArray();char[] units=new char[values.size()];for(int i=0;ithrow new AssertionError(kind); + } + out.println("count "+root.getCount()); + } + out.println("tail "+root.nextLong());out.println("count "+root.getCount()); + } + } + } +} diff --git a/packs/START-HERE.txt b/packs/START-HERE.txt index b563f2f05..225f8a086 100644 --- a/packs/START-HERE.txt +++ b/packs/START-HERE.txt @@ -1,4 +1,4 @@ -HORIZON LAB @PACK_VERSION@ — playable optimization experiments +HORIZON @PACK_VERSION@ — playable optimization experiments YOUR MAC 1. Extract this ZIP. Double-click Mac-Start.command. If macOS asks, use Open @@ -179,7 +179,7 @@ Only original project binaries are embedded. Mods, the game and assets download from their publishers with pinned hashes. No decompiled Minecraft is distributed. Source, build commands and measured validation: -https://github.com/ludovic111/minecraft-optimization-lab +https://github.com/ludovic111/Horizon TERRAIN / SHADER COMPARISONS Version 0.12 records actual DH radius/quality, worker count/duty cycle, Iris state diff --git a/tests/test_anchor_parity.py b/tests/test_anchor_parity.py new file mode 100644 index 000000000..a9df54cea --- /dev/null +++ b/tests/test_anchor_parity.py @@ -0,0 +1,22 @@ +import itertools +import json +import unittest +from tools import test_anchor_parity as anchor + + +class AnchorCorpusTests(unittest.TestCase): + def test_exclusive_alternatives_and_unrestricted_runtime_bounds(self): + fixtures=list(anchor.corpus()) + self.assertEqual(fixtures,list(anchor.corpus())) + self.assertEqual(len(fixtures),192) + self.assertEqual(sum('generator' in f for f in fixtures),96) + self.assertIn(-2**31,fixtures[0]['values']) + self.assertIn(2**31-1,fixtures[0]['values']) + decoded=[json.loads(s) for s in fixtures[0]['json']] + names=['absolute','above_bottom','below_top','relative_to_sea_level'] + for combination in itertools.product([None,0,2032,'bad'],repeat=4): + self.assertIn({k:v for k,v in zip(names,combination) if v is not None},decoded) + self.assertIn('{"absolute":1,"absolute":null}',fixtures[0]['json']) + + +if __name__=='__main__':unittest.main() diff --git a/tests/test_basic_feature_parity.py b/tests/test_basic_feature_parity.py new file mode 100644 index 000000000..a0744781c --- /dev/null +++ b/tests/test_basic_feature_parity.py @@ -0,0 +1,25 @@ +import json +import unittest +from tools import test_basic_feature_parity as features + + +class BasicFeatureCorpusTests(unittest.TestCase): + def test_native_feature_types_partial_mutations_and_wrapped_origins(self): + fixtures = list(features.corpus()) + self.assertEqual(fixtures, list(features.corpus())) + kinds = {v.get('type') for f in fixtures if isinstance(v := json.loads(f['definition']), dict)} + self.assertTrue({'void_start_platform', 'end_island', 'end_platform'} <= kinds) + self.assertEqual({f['legacy'] for f in fixtures}, {False, True}) + self.assertEqual({f['fail'] for f in fixtures}, {-1, 0, 7, 63}) + self.assertEqual({f['reject'] for f in fixtures}, {0, 3}) + self.assertTrue(any(f['origin'][0] == 2**31 - 1 for f in fixtures)) + self.assertTrue(any(f['origin'][1] == -2**31 for f in fixtures)) + self.assertTrue(any(f['repeats'] == 2 for f in fixtures)) + composed = [f for f in fixtures if 'placement' in f] + self.assertTrue(any(not f['placement'] for f in composed)) + self.assertTrue(any(len(f['placement']) > 1 and f['fail'] == 7 for f in composed)) + self.assertTrue(any(any(p['type'] == 'height_range' for p in f['placement']) for f in composed)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_biome_chunk_parity.py b/tests/test_biome_chunk_parity.py new file mode 100644 index 000000000..769ddc757 --- /dev/null +++ b/tests/test_biome_chunk_parity.py @@ -0,0 +1,23 @@ +import unittest +from tools import test_biome_chunk_parity as chunk + + +class BiomeChunkCorpusTests(unittest.TestCase): + def test_bounds_section_failure_and_query_coverage(self): + fixtures = list(chunk.corpus()) + self.assertEqual(fixtures, list(chunk.corpus())) + self.assertEqual(len(fixtures), 20) + self.assertTrue(any(f['height'] == 4064 for f in fixtures)) + self.assertTrue(any(f['cx'] == -(2**31) for f in fixtures)) + for f in fixtures: + self.assertEqual({op[2] for op in f['ops']}, {-1, 0, 63, 64, 65}) + self.assertTrue(any(op[3] % 16 != 0 for op in f['ops'])) + for op in f['ops']: + self.assertTrue(f['min'] <= op[3] <= op[4] < f['min'] + f['height']) + self.assertTrue(1 <= op[1] <= 512) + for q in f['queries']: + self.assertTrue(all(-(2**31) <= v < 2**31 for v in q)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_biome_generation_parity.py b/tests/test_biome_generation_parity.py new file mode 100644 index 000000000..2d7f35574 --- /dev/null +++ b/tests/test_biome_generation_parity.py @@ -0,0 +1,27 @@ +import json +import unittest +from tools import test_biome_generation_parity as generation + + +class BiomeGenerationCorpusTests(unittest.TestCase): + def test_router_preset_seed_and_clipped_generation_coverage(self): + bundle = {'settings': {'minecraft:overworld': json.dumps({'noise': {'min_y': -64, 'height': 384}})}, + 'presets': {'minecraft:overworld': '[]', 'minecraft:nether': '[]'}} + all_fixtures = list(generation.corpus(bundle)) + self.assertEqual({f.get('source', 'multi') for f in all_fixtures}, {'multi', 'fixed', 'checkerboard', 'end'}) + fixtures = [f for f in all_fixtures if 'source' not in f] + self.assertEqual(all_fixtures, list(generation.corpus(bundle))) + self.assertEqual(len(fixtures), 12) + self.assertEqual(sum(f['repeats'] for f in fixtures), 16) + self.assertEqual({f['preset'] for f in fixtures}, set(bundle['presets'])) + self.assertEqual({f['legacy'] for f in fixtures}, {False, True}) + self.assertTrue(any(f['write_min'] > f['min'] for f in fixtures)) + self.assertTrue(any(abs(f['cx']) > 1_000_000 for f in fixtures)) + for f in fixtures: + self.assertEqual(len(f['queries']), 180) + self.assertTrue(any(q[1] < f['min'] for q in f['queries'])) + self.assertTrue(any(q[1] >= f['min'] + f['height'] for q in f['queries'])) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_biome_placement_parity.py b/tests/test_biome_placement_parity.py new file mode 100644 index 000000000..11b1ce200 --- /dev/null +++ b/tests/test_biome_placement_parity.py @@ -0,0 +1,20 @@ +import unittest +from tools import test_biome_placement_parity as biome + + +class BiomePlacementCorpusTests(unittest.TestCase): + def test_context_membership_nested_placers_and_partial_failures(self): + fixtures = list(biome.corpus()) + self.assertEqual({f['top'] for f in fixtures}, {False, True}) + self.assertEqual({f['direct'] for f in fixtures}, {False, True}) + self.assertEqual({f['nested'] for f in fixtures}, {False, True}) + self.assertEqual({f['worldgen'] for f in fixtures}, {False, True}) + self.assertEqual({f['legacy'] for f in fixtures}, {False, True}) + self.assertEqual({mode for f in fixtures for mode in f['membership']}, {0, 1, 2, 3}) + self.assertTrue(all(f['placement'] == [{'type': 'biome'}] for f in fixtures if f['direct'])) + self.assertTrue(any(f['query_fail'] == 1 for f in fixtures)) + self.assertTrue(any(f['feature_fail'] == 2 for f in fixtures)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_biome_source_codec_parity.py b/tests/test_biome_source_codec_parity.py new file mode 100644 index 000000000..924f3d306 --- /dev/null +++ b/tests/test_biome_source_codec_parity.py @@ -0,0 +1,23 @@ +import json +import unittest +from tools import test_biome_source_codec_parity as codec + + +class BiomeSourceCodecCorpusTests(unittest.TestCase): + def test_registry_holders_fallbacks_and_numeric_boundaries(self): + bundle = {'biomes': {'minecraft:plains': ''}, 'biome_tags': {'minecraft:is_overworld': ''}} + fixtures = list(codec.corpus(bundle)) + self.assertEqual(fixtures, list(codec.corpus(bundle))) + values = [json.loads(f) for f in fixtures] + objects = [v for v in values if isinstance(v, dict)] + self.assertTrue({'fixed', 'checkerboard', 'the_end', 'multi_noise'} <= {v.get('type') for v in objects}) + self.assertTrue(any(v.get('biomes') == '#minecraft:is_overworld' for v in objects)) + self.assertTrue(any(v.get('biomes') == [] and v.get('preset') == 'overworld' for v in objects)) + self.assertTrue(any(v.get('preset') == {'preset': 'nether'} for v in objects)) + self.assertTrue(any('4294967298' in f for f in fixtures)) + self.assertTrue(any('"scale":-1,"scale":2' in f for f in fixtures)) + self.assertEqual(len(codec.positions()), 7) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_biome_source_parity.py b/tests/test_biome_source_parity.py new file mode 100644 index 000000000..40b62aa69 --- /dev/null +++ b/tests/test_biome_source_parity.py @@ -0,0 +1,23 @@ +import unittest +from tools import test_biome_source_parity as source + + +class BiomeSourceCorpusTests(unittest.TestCase): + def test_shift_threshold_failure_and_wrapped_coordinate_coverage(self): + fixtures = list(source.corpus()) + self.assertEqual(fixtures, list(source.corpus())) + self.assertEqual({f['kind'] for f in fixtures}, {'fixed', 'checkerboard', 'end'}) + checker = [f for f in fixtures if f['kind'] == 'checkerboard'] + self.assertTrue(set(range(63)) <= {f['scale'] for f in checker}) + self.assertTrue(any(not f['biomes'] for f in checker)) + self.assertTrue(any(len(f['biomes']) != len(set(f['biomes'])) for f in checker)) + self.assertTrue(any(len(f['biomes']) == 512 for f in checker)) + end = [f for f in fixtures if f['kind'] == 'end'] + self.assertTrue(any(f['fail'] for f in end)) + self.assertTrue({'3e800000', 'bd800000', 'be600000', '7fc00000'} <= {f['bits'] for f in end}) + self.assertIn([-(2**31), 0, 2**31-1], fixtures[0]['positions']) + self.assertIn([256, 0, 0], fixtures[0]['positions']) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_biome_temperature_parity.py b/tests/test_biome_temperature_parity.py new file mode 100644 index 000000000..5b356f383 --- /dev/null +++ b/tests/test_biome_temperature_parity.py @@ -0,0 +1,33 @@ +import unittest +import json +from tools import test_biome_temperature_parity as biome + + +class BiomeTemperatureCorpusTests(unittest.TestCase): + def test_temperature_edges_packed_aliases_and_cache_eviction(self): + fixtures=list(biome.corpus()) + self.assertEqual(fixtures,list(biome.corpus())) + self.assertEqual(len(fixtures),204) + self.assertEqual({(f['modifier'],f['precipitation']) for f in fixtures},{('NONE',False),('NONE',True),('FROZEN',False),('FROZEN',True)}) + self.assertTrue({'3e199999','3e19999a','3e19999b','7f800000','ff800000','7fc00000'}<={f['base'] for f in fixtures}) + isolated=[f for f in fixtures if any(op[0]=='thread' for op in f['ops'])] + self.assertEqual(len(isolated),12) + self.assertEqual({f['ops'][2][1] for f in isolated},{0,1023}) + self.assertTrue(all(f['ops'][0]==['fill',1024,0,63] for f in isolated)) + queries=[op[1:] for op in fixtures[0]['ops'] if op[0]=='query'] + self.assertIn([0,80,0,63],queries) + self.assertIn([0,81,0,63],queries) + self.assertIn([2**26,4032,-2**26,63],queries) + + def test_climate_codec_fields_and_float_rounding_edges(self): + fixtures=list(biome.codec_corpus({'horizon:test':'{"has_precipitation":false,"temperature":0,"downfall":1}'})) + self.assertEqual(fixtures,list(biome.codec_corpus({'horizon:test':'{"has_precipitation":false,"temperature":0,"downfall":1}'}))) + decoded=[json.loads(f['json']) for f in fixtures] + self.assertIn({'has_precipitation':True,'temperature':0.5,'downfall':0.5},decoded) + self.assertIn({'has_precipitation':True,'temperature':0.5,'downfall':0.5,'temperature_modifier':None},decoded) + self.assertTrue(any('1.000000059604644775390626' in f['json'] for f in fixtures)) + self.assertTrue(any('1e1000' in f['json'] for f in fixtures)) + self.assertTrue(any('"temperature":0.2,"temperature":null' in f['json'] for f in fixtures)) + + +if __name__=='__main__':unittest.main() diff --git a/tests/test_biome_zoom_parity.py b/tests/test_biome_zoom_parity.py new file mode 100644 index 000000000..9f792d79a --- /dev/null +++ b/tests/test_biome_zoom_parity.py @@ -0,0 +1,20 @@ +import unittest +from tools import test_biome_zoom_parity as zoom + + +class BiomeZoomCorpusTests(unittest.TestCase): + def test_seed_coordinate_and_double_boundary_coverage(self): + fixtures = list(zoom.corpus()) + self.assertEqual(fixtures, list(zoom.corpus())) + self.assertEqual({f[0] for f in fixtures}, {'s', 'b', 'p'}) + self.assertIn('s -9223372036854775808', fixtures) + self.assertIn('s 9223372036854775807', fixtures) + self.assertIn('b 0 -2147483648 0 2147483647', fixtures) + self.assertIn('b 1 -1 0 1', fixtures) + self.assertIn('p 7ff0000000000000 fff0000000000000 7ff8000000000000', fixtures) + self.assertIn('p 0000000000000001 8000000000000001 fff8000000000000', fixtures) + self.assertEqual(sum(f.startswith('s ') for f in fixtures), 4104) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_block_properties_parity.py b/tests/test_block_properties_parity.py new file mode 100644 index 000000000..9f1eacf3f --- /dev/null +++ b/tests/test_block_properties_parity.py @@ -0,0 +1,19 @@ +import unittest +from tools import test_block_properties_parity as properties + + +class BlockPropertiesCorpusTests(unittest.TestCase): + def test_cache_flags_empty_shapes_and_threshold_cases(self): + fixtures=list(properties.corpus()) + self.assertEqual(fixtures,list(properties.corpus())) + self.assertEqual({(f['on'],f['off'],f['cached']) for f in fixtures}, + {(a,b,c) for a in [False,True] for b in [False,True] for c in [False,True]}) + self.assertEqual({f['occludes'] for f in fixtures},{False,True}) + self.assertTrue(any(not f['shape'] for f in fixtures)) + self.assertTrue(any(len(f['shape'])>1 for f in fixtures)) + self.assertGreater(len(fixtures),8000) + for f in fixtures: + for box in f['shape']:self.assertEqual(len(box),6) + + +if __name__=='__main__':unittest.main() diff --git a/tests/test_block_state_codec_parity.py b/tests/test_block_state_codec_parity.py new file mode 100644 index 000000000..95777bc37 --- /dev/null +++ b/tests/test_block_state_codec_parity.py @@ -0,0 +1,19 @@ +import json +import unittest +from tools import test_block_state_codec_parity as block + + +class BlockStateCodecCorpusTests(unittest.TestCase): + def test_modes_property_defaults_and_integer_boundaries(self): + facts={'states':[{'id':'minecraft:stone'},{'id':'minecraft:water','properties':{'level':'0'}}], 'defaults':{'minecraft:stone':0,'minecraft:water':1},'integers':[['minecraft:water','level']]} + fixtures=list(block.corpus(facts)) + self.assertEqual(fixtures,list(block.corpus(facts))) + self.assertEqual({f[0] for f in fixtures},{False,True}) + values=[json.loads(f[1]) for f in fixtures] + for value in ['+01','-2147483649','\u0660\u0661','\uff10\uff11','\U0001d7d9']: + self.assertIn({'id':'minecraft:water','properties':{'level':value}},values) + self.assertIn({'id':'minecraft:stone','properties':False},values) + self.assertTrue(any('"level":"0","level":"1"' in f[1] for f in fixtures)) + + +if __name__=='__main__':unittest.main() diff --git a/tests/test_block_survival_parity.py b/tests/test_block_survival_parity.py new file mode 100644 index 000000000..13bd63b01 --- /dev/null +++ b/tests/test_block_survival_parity.py @@ -0,0 +1,72 @@ +import unittest +import tempfile +from pathlib import Path +from tools import test_block_survival_parity as survival + + +class SurvivalCheckpointTests(unittest.TestCase): + def test_resume_rejects_changed_sources_environment_inputs_and_executables(self): + with tempfile.TemporaryDirectory() as directory: + root=Path(directory);fixture=root/'fixture';binary=root/'binary';path=root/'checkpoint.json' + fixture.write_bytes(b'original input');binary.write_bytes(b'original executable') + sources={'source.rs':'original'};environment={'java':'pinned'} + checkpoint={'schema':1,'sources_sha256':sources,'environment':environment,'fixtures_sha256':{str(fixture):survival.lab.digest(fixture,'sha256')},'artifacts_sha256':{str(binary):survival.lab.digest(binary,'sha256')}} + survival.save_checkpoint(path,checkpoint) + self.assertEqual(survival.load_checkpoint(path,sources,environment),checkpoint) + for changed_sources,changed_environment in [({'source.rs':'edited'},environment),(sources,{'java':'different'})]: + with self.assertRaises(ValueError):survival.load_checkpoint(path,changed_sources,changed_environment) + for artifact in [fixture,binary]: + original=artifact.read_bytes();artifact.write_bytes(b'changed') + with self.assertRaises(ValueError):survival.load_checkpoint(path,sources,environment) + artifact.unlink() + with self.assertRaises(ValueError):survival.load_checkpoint(path,sources,environment) + artifact.write_bytes(original) + self.assertEqual(survival.load_checkpoint(path,sources,environment),checkpoint) + + +class BlockSurvivalCorpusTests(unittest.TestCase): + def test_definition_dispatch_preserves_virtual_support_methods(self): + classes = {'a': 'VegetationBlock', 'b': 'VegetationBlock', 'c': 'VegetationBlock', 'd': 'DoublePlantBlock', 'e': 'DoublePlantBlock'} + placement = {'a': 'VegetationBlock', 'b': 'StemBlock', 'c': 'UnknownVegetationBlock', 'd': 'VegetationBlock', 'e': 'UnknownPlantBlock'} + tags = {'b': {'stemSupportBlocks': 'minecraft:supports_melon_stem', 'fruitSupportBlocks': 'minecraft:wrong_for_survival'}} + rules = survival.bind_definitions(classes, placement, tags) + self.assertEqual(rules, {'a': 'TagBelow:minecraft:supports_vegetation', 'b': 'TagBelow:minecraft:supports_melon_stem', 'd': 'DoublePlant'}) + with self.assertRaises(KeyError): + survival.bind_definitions(classes, placement, {}) + + def test_branching_neighbor_sequences_and_candidate_properties(self): + names=['air','stone','end_stone','chorus_plant','chorus_flower','scaffolding','bell','pitcher_crop'] + states=[{'id':'minecraft:'+name,'properties':{}} for name in names] + states += [dict(states[-2],properties={'attachment':'ceiling','facing':'north'}),dict(states[-1],properties={'half':'upper'})] + facts={'states':states,'defaults':{'minecraft:'+name:index for index,name in enumerate(names)}} + definitions={states[i]['id']:rule for i,rule in [(3,'ChorusPlant'),(4,'ChorusFlower'),(5,'Scaffolding'),(6,'Bell'),(7,'PitcherCrop')]} + seen=set();long_failures=set();brightness=set();upper_brightness=set() + for fixture in survival.corpus(facts,definitions): + seen.add(fixture['state']) + if len(fixture['neighbors'])==10:long_failures.add(fixture['fail']) + if 'brightness' in fixture: + brightness.add(fixture['brightness']) + if fixture['state']==9:upper_brightness.add(fixture['brightness']) + self.assertEqual(seen,{3,4,5,6,7,8,9}) + self.assertEqual(long_failures,{-1,*range(10)}) + self.assertTrue({7,8,9}.issubset(brightness)) + self.assertEqual(upper_brightness,brightness) + + def test_supported_candidates_and_query_transitions(self): + names = ['minecraft:air', 'minecraft:stone', 'minecraft:shulker_box', 'minecraft:moving_piston', 'minecraft:pale_moss_carpet', 'minecraft:unsupported'] + facts = {'states': [{'id': name, 'properties': {'bottom': 'true'}} for name in names], 'defaults': dict(zip(names, range(len(names))))} + definitions = {names[0]: 'Always', names[1]: 'RigidOrCenterBelow', names[4]: 'MossCarpet'} + fixtures = list(survival.corpus(facts, definitions)) + self.assertEqual(fixtures, list(survival.corpus(facts, definitions))) + self.assertEqual({f['state'] for f in fixtures}, {0, 1, 4}) + self.assertEqual(len([f for f in fixtures if f['state'] == 0]), 1) + self.assertTrue(any(f['neighbors'] == [2, 3] for f in fixtures)) + self.assertTrue(any(f['fail'] == 1 and f['entity_fail'] == 0 for f in fixtures)) + self.assertEqual({f['entity'] for f in fixtures}, {'none', 'closed', 'opened'}) + self.assertTrue(any(-2147483648 in f['position'] for f in fixtures)) + for candidate in [1, 4]: + self.assertTrue(all(any(f['state'] == candidate and f['neighbors'] == [neighbor] and f['fail'] == -1 for f in fixtures) for neighbor in range(len(names)))) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_bulk_section_parity.py b/tests/test_bulk_section_parity.py new file mode 100644 index 000000000..6ef998d36 --- /dev/null +++ b/tests/test_bulk_section_parity.py @@ -0,0 +1,22 @@ +import unittest +from tools import test_bulk_section_parity as bulk + + +class BulkSectionCorpusTests(unittest.TestCase): + def test_all_state_cycles_cache_aliases_and_vertical_bounds(self): + facts = {'states': list(range(5)), 'defaults': {'minecraft:air': 0, 'minecraft:cave_air': 1, 'minecraft:void_air': 2, 'minecraft:stone': 3, 'minecraft:water': 4}} + fixtures = list(bulk.corpus(facts)) + self.assertEqual(fixtures, list(bulk.corpus(facts))) + self.assertEqual({f['min'] for f in fixtures}, {-2032, -64, 0, 1968}) + self.assertEqual({f['prime'] for f in fixtures}, {False, True}) + self.assertTrue(all([4194304, 0] in f['chunks'] for f in fixtures)) + self.assertTrue(all(['reset'] in f['ops'] for f in fixtures)) + for f in fixtures: + self.assertTrue(any(op[:2] == ['get', 67108864] for op in f['ops'])) + if f['min'] == -64: + inserted = {op[4] for op in f['ops'] if op[:4] == ['set', 0, -63, 0]} + self.assertEqual(inserted, set(range(5))) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_canyon_carver_parity.py b/tests/test_canyon_carver_parity.py new file mode 100644 index 000000000..0ae46fe16 --- /dev/null +++ b/tests/test_canyon_carver_parity.py @@ -0,0 +1,20 @@ +import json +import unittest +from tools import test_canyon_carver_parity as canyon + + +class CanyonCarverCorpusTests(unittest.TestCase): + def test_heights_custom_widths_and_failures(self): + config={'type':'minecraft:canyon','probability':0.01,'y':{'absolute':40},'vertical_rotation':0,'shape':{'width_smoothness':3,'distance_factor':1,'thickness':3,'horizontal_radius_factor':1,'vertical_radius_default_factor':1,'vertical_radius_center_factor':0,'y_scale':3}} + fixtures=list(canyon.corpus({'canyon':json.dumps(config)})) + self.assertEqual(fixtures,list(canyon.corpus({'canyon':json.dumps(config)}))) + self.assertEqual({f['context'][1] for f in fixtures},{16,128,384,4064}) + self.assertEqual({f['fail'] for f in fixtures},{-1,0,1,63}) + self.assertTrue(any(f['target']==[-2**31,2**31-1] for f in fixtures)) + definitions=[json.loads(f['definition']) for f in fixtures] + shapes=[d['shape'] for d in definitions if isinstance(d,dict) and isinstance(d.get('shape'),dict)] + self.assertTrue(any(s.get('width_smoothness')==2**31-1 for s in shapes)) + self.assertTrue(any(s.get('distance_factor')==0 for s in shapes)) + + +if __name__=='__main__':unittest.main() diff --git a/tests/test_carving_geometry_parity.py b/tests/test_carving_geometry_parity.py new file mode 100644 index 000000000..649a50f6c --- /dev/null +++ b/tests/test_carving_geometry_parity.py @@ -0,0 +1,22 @@ +import unittest +from tools import test_carving_geometry_parity as geometry + + +class CarvingGeometryCorpusTests(unittest.TestCase): + def test_shape_boundaries_ieee_values_and_output_failures(self): + fixtures = list(geometry.corpus()) + self.assertEqual(fixtures, list(geometry.corpus())) + self.assertEqual(len(fixtures), 15) + shapes = [e for f in fixtures for e in f['ellipsoids']] + self.assertEqual(len(shapes), 690) + self.assertEqual({e['skip'] for e in shapes}, {0, 1, 2, 3}) + self.assertEqual({e['fail'] for e in shapes}, {-1, 0, 1, 63}) + self.assertIn(geometry.bits(float('nan')), {e['horizontal'] for e in shapes}) + self.assertIn(geometry.bits(-0.), {e['vertical'] for e in shapes}) + reach = list(geometry.reach_corpus()) + self.assertEqual(reach, list(geometry.reach_corpus())) + self.assertTrue(any(q[4] == -2**31 and q[5] == 2**31 - 1 for q in reach)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_carving_mask_parity.py b/tests/test_carving_mask_parity.py new file mode 100644 index 000000000..29c19168e --- /dev/null +++ b/tests/test_carving_mask_parity.py @@ -0,0 +1,20 @@ +import unittest +from tools import test_carving_mask_parity as carving + + +class CarvingMaskCorpusTests(unittest.TestCase): + def test_sparse_dense_wrap_and_mutating_traversal_coverage(self): + fixtures = list(carving.corpus()) + self.assertEqual(fixtures, list(carving.corpus())) + self.assertTrue(any(f['max'] - f['min'] + 1 == 4064 for f in fixtures)) + self.assertTrue(any(f['min'] == -2**31 for f in fixtures)) + self.assertTrue(any(f['max'] == 2**31 - 1 for f in fixtures)) + ops = [op for f in fixtures for op in f['ops']] + self.assertEqual({op['kind'] for op in ops}, {'carve', 'fill', 'visit', 'read'}) + self.assertTrue(any(op.get('fail') == 0 and op.get('add') for op in ops)) + self.assertTrue(any(op.get('fail') == 63 for op in ops)) + self.assertTrue(any(op.get('pos', [0])[0] == -2**31 for op in ops)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_cave_carver_parity.py b/tests/test_cave_carver_parity.py new file mode 100644 index 000000000..1f25f850b --- /dev/null +++ b/tests/test_cave_carver_parity.py @@ -0,0 +1,21 @@ +import json +import unittest +from tools import test_cave_carver_parity as cave + + +class CaveCarverCorpusTests(unittest.TestCase): + def test_seeds_origin_neighborhoods_and_partial_failures(self): + config={'type':'minecraft:cave','count':0,'probability':0.15,'thickness':1,'y':{'absolute':40},'floor_level':-0.7} + resources={'cave':json.dumps(config),'nether_cave':json.dumps(config)} + fixtures=list(cave.corpus(resources)) + self.assertEqual(fixtures,list(cave.corpus(resources))) + self.assertEqual({f['legacy'] for f in fixtures},{False,True}) + self.assertEqual({f['fail'] for f in fixtures},{-1,0,1,63}) + self.assertTrue(any(f['target']==[-2**31,2**31-1] for f in fixtures)) + self.assertTrue(any(f['origin']==[8,-8] for f in fixtures)) + self.assertTrue(any(f['repeats']==2 for f in fixtures)) + definitions=[json.loads(f['definition']) for f in fixtures] + self.assertTrue(any(isinstance(v,dict) and v.get('thickness')==6 for v in definitions)) + + +if __name__=='__main__':unittest.main() diff --git a/tests/test_chunk_stage_parity.py b/tests/test_chunk_stage_parity.py new file mode 100644 index 000000000..20bd88cbf --- /dev/null +++ b/tests/test_chunk_stage_parity.py @@ -0,0 +1,22 @@ +import unittest +from tools import test_chunk_stage_parity as stages + + +class ChunkStageCorpusTests(unittest.TestCase): + def test_all_stages_state_writes_and_reverse_transitions(self): + names = ['air', 'cave_air', 'void_air', 'stone', 'water', 'lava', 'oak_leaves', 'oak_slab', 'seagrass', 'snow', 'powder_snow', 'glass', 'barrier'] + facts = {'states': names, 'defaults': {'minecraft:' + name: i for i, name in enumerate(names)}} + fixtures = list(stages.corpus(facts)) + self.assertEqual(fixtures, list(stages.corpus(facts))) + expected = {'empty', 'structure_starts', 'structure_references', 'biomes', 'terrain', 'features'} + self.assertEqual({op[1] for f in fixtures for op in f['ops'] if op[0] == 'stage'}, expected) + for f in fixtures[:2]: + self.assertEqual({op[4] for op in f['ops'] if op[0] == 'set'}, set(range(len(names)))) + self.assertTrue(any(f['height'] == 4064 for f in fixtures)) + self.assertTrue(any(op[0] == 'set' and op[2] < f['min'] for f in fixtures for op in f['ops'])) + self.assertTrue(any(op[0] == 'set' and op[2] >= f['min'] + f['height'] for f in fixtures for op in f['ops'])) + self.assertTrue(any([op[1] for op in f['ops'] if op[0] == 'stage'][-1] == 'empty' for f in fixtures[2:])) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_decoration_parity.py b/tests/test_decoration_parity.py new file mode 100644 index 000000000..ee73d3ec3 --- /dev/null +++ b/tests/test_decoration_parity.py @@ -0,0 +1,22 @@ +import unittest +from tools import test_decoration_parity as decoration + + +class DecorationCorpusTests(unittest.TestCase): + def test_global_indices_foreign_palettes_failures_and_reproducibility(self): + resources = {'a': [[], ['horizon:a', 'horizon:b']], 'b': [['horizon:c'], ['horizon:b']]} + fixtures = list(decoration.corpus(resources)) + self.assertEqual(fixtures, list(decoration.corpus(resources))) + self.assertTrue(any(f['biomes'] == [[[0, 1]], [[1, 0]]] for f in fixtures)) + self.assertTrue(any(len(b) > 12 for f in fixtures for b in f['biomes'])) + self.assertTrue(any(f['palettes'][:8] == [[3]] * 8 and f['palettes'][8] == [1] for f in fixtures)) + for key in ['feature_fail', 'query_fail', 'chunk_fail', 'notify_fail']: + self.assertTrue(any(f[key] >= 0 for f in fixtures)) + for f in fixtures: + self.assertEqual(len(f['palettes']), 9) + self.assertTrue(all(0 <= b <= len(f['biomes']) for p in f['palettes'] for b in p)) + self.assertTrue(all(0 <= feature < len(f['placements']) for b in f['biomes'] for step in b for feature in step)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_decoration_region_parity.py b/tests/test_decoration_region_parity.py new file mode 100644 index 000000000..395bb2d9e --- /dev/null +++ b/tests/test_decoration_region_parity.py @@ -0,0 +1,22 @@ +import unittest +from tools import test_decoration_region_parity as region + + +class DecorationRegionCorpusTests(unittest.TestCase): + def test_real_features_mixed_biomes_live_heights_and_partial_writes(self): + fixtures = list(region.corpus({})) + self.assertEqual(fixtures, list(region.corpus({}))) + self.assertEqual(len(fixtures), 240) + self.assertEqual({f['stage'] for f in fixtures}, {'empty', 'biomes', 'terrain'}) + self.assertEqual({f['write_fail'] for f in fixtures}, {-1, 7}) + self.assertTrue(any(f['palettes'] == [[0]] * 9 for f in fixtures)) + self.assertTrue(any(3 in p for f in fixtures for p in f['palettes'])) + for f in fixtures: + self.assertEqual(len(f['features']), 6) + self.assertEqual(len(f['placements']), len(f['features'])) + self.assertTrue(all(any(m['type'] == 'biome' for m in p) for p in f['placements'])) + self.assertTrue(all(0 <= feature < len(f['features']) for biome in f['biomes'] for step in biome for feature in step)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_density_parity.py b/tests/test_density_parity.py new file mode 100644 index 000000000..7b5a3824f --- /dev/null +++ b/tests/test_density_parity.py @@ -0,0 +1,254 @@ +from collections import Counter +from pathlib import Path +import tempfile +import unittest +from unittest import mock + +from tools import test_density_parity as parity + + +class DensityRunnerTests(unittest.TestCase): + def test_failed_reference_verification_removes_previous_success(self): + with tempfile.TemporaryDirectory() as temp: + report = Path(temp) / "rust-density-parity/report.json" + report.parent.mkdir() + report.write_text('{"previous_success":true}') + with mock.patch.object(parity.lab, "LOCAL", Path(temp)), mock.patch("sys.argv", ["parity"]), \ + mock.patch.object(parity.test_rust_parity, "verify_artifacts", side_effect=ValueError("corrupt artifact")): + with self.assertRaisesRegex(ValueError, "corrupt artifact"): + parity.main() + self.assertFalse(report.exists()) + + def test_corpus_replays_valid_graph_references_and_edge_cases(self): + commands = list(parity.corpus()) + self.assertEqual(commands, list(parity.corpus())) + counts = Counter(line.split()[0] for line in commands) + self.assertEqual(counts["gradient"], 2041) + self.assertEqual(counts["shift"], 1200) + self.assertGreater(counts["query"], 140000) + self.assertEqual(counts["bounds"], 41176) + self.assertEqual(counts["offset"], 816) + self.assertEqual(counts["blended"], 192) + self.assertEqual(counts["blendfail"], 10) + self.assertEqual(counts["blendfbm"], 256) + self.assertEqual(counts["counted"], 3120) + self.assertEqual(counts["context"], 34805) + self.assertEqual(counts["lookup"], 10000) + self.assertEqual(counts["slice"], 384) + self.assertEqual(counts["interpolate"], 384) + self.assertEqual(counts["surface"], 384) + self.assertEqual(counts["sppoints"], 768) + self.assertEqual(counts["spconstant"], 78) + self.assertEqual(counts["spsampler"] + counts["spfail"], 334) + self.assertGreaterEqual(counts["spfail"], 2) + self.assertEqual(counts["sprange"], 13536) + self.assertEqual(counts["greset"], 368) + self.assertEqual(counts["gcompile"], 18282) + self.assertEqual(counts["power"], 1456) + self.assertEqual(counts["gpow"], 1552) + self.assertEqual(counts["round"], 1576) + self.assertEqual(counts["ground"], 880) + self.assertEqual(counts["gsconstant"], 1120) + self.assertEqual(counts["gspoints"], 1456) + self.assertEqual(counts["gspline"], 2160) + self.assertEqual(counts["gseed"], 70) + self.assertEqual(counts["gready"], 70) + self.assertEqual(counts["gregister"], 326) + self.assertEqual(counts["gnoise"], 838) + self.assertEqual(counts["goffset"], 262) + self.assertEqual(counts["gblended"], 64) + self.assertEqual(counts["gend"], 128) + self.assertEqual(counts["gref"], 288) + self.assertEqual(counts["gnamed"], 224) + self.assertEqual(counts["glookup"], 64) + self.assertEqual(counts["wfield"], 96) + self.assertEqual(counts["blenddensity"], 96) + self.assertEqual(counts["gwfield"], 96) + self.assertEqual(counts["gblenddensity"], 176) + self.assertEqual(counts["wcontext"], 20416) + self.assertEqual(counts["ginstance"], 640) + self.assertEqual(counts["ginterval"], 1024) + self.assertEqual(counts["gdistance"], 128) + self.assertEqual({line.split()[1] for line in commands if line.startswith("bounds ")}, set("012345")) + samplers = noises = splines = graph_nodes = graph_splines = graph_noises = 0 + tilings = set() + noise_modes = set() + shift_modes = set() + graph_ready = False + named_functions = set() + for command in commands: + fields = command.split() + if fields[0] in ["greset", "gseed"]: + graph_nodes = 0 + graph_splines = 0 + graph_noises = 0 + graph_ready = False + named_functions.clear() + elif fields[0] in ["gref", "gnamed", "glookup"]: + if fields[0] == "gnamed": + self.assertNotIn(fields[1], named_functions) + self.assertLess(int(fields[2]), graph_nodes) + named_functions.add(fields[1]) + elif fields[0] == "glookup": + self.assertIn(fields[1], named_functions) + else: + self.assertLess(int(fields[1]), graph_nodes) + graph_nodes += 1 + elif fields[0] == "gregister": + self.assertFalse(graph_ready) + self.assertIn(":", fields[1]) + self.assertEqual(len(fields), 7 + int(fields[6])) + graph_noises += 1 + elif fields[0] == "gready": + self.assertFalse(graph_ready) + self.assertGreater(graph_noises, 0) + graph_ready = True + elif fields[0] == "ginstance": + self.assertTrue(graph_ready) + self.assertLess(int(fields[1]), graph_noises) + elif fields[0] == "gnoise": + self.assertTrue(graph_ready) + self.assertLess(int(fields[1]), graph_noises) + for reference in map(int,fields[4:7]): + self.assertLess(reference, graph_nodes) + graph_nodes += 1 + elif fields[0] == "goffset": + self.assertLess(int(fields[1]), graph_noises) + self.assertIn(fields[2], ["0", "1", "2"]) + graph_nodes += 1 + elif fields[0] == "gsconstant": + graph_splines += 1 + elif fields[0] == "gspoints": + self.assertLess(int(fields[1]), graph_nodes) + count = int(fields[2]) + self.assertEqual(len(fields), 3 + 3*count) + for reference in map(int, fields[5::3]): + self.assertLess(reference, graph_splines) + graph_splines += 1 + elif fields[0] == "gspline": + self.assertLess(int(fields[1]), graph_splines) + graph_nodes += 1 + elif fields[0] == "gbind": + self.assertLess(int(fields[1]), samplers) + graph_nodes += 1 + elif fields[0] in ["gconst", "ggradient", "gdistance", "gblended", "gend", "gwfield"]: + graph_nodes += 1 + elif fields[0] == "ginterval": + count = int(fields[2]) + self.assertEqual(len(fields), 4 + 2*count) + for reference in map(int, fields[1:2] + fields[3+count:]): + self.assertLess(reference,graph_nodes) + graph_nodes += 1 + elif fields[0] in ["gunary", "gbinary", "ground", "gpow", "gclamp", "gchoice", "glerp", "gslice", "gcache", "ginterp", "gsurface", "gblenddensity"]: + references = { + "gunary": fields[2:3], "gbinary": fields[2:4], "ground": fields[2:4], "gpow": fields[1:3], "gclamp": fields[1:2], + "gchoice": fields[1:2] + fields[4:6], "glerp": fields[1:4], "gslice": fields[3:4], + "gcache": fields[1:2], "gblenddensity": fields[1:2], "ginterp": fields[1:2], "gsurface": fields[1:3], + }[fields[0]] + for reference in map(int,references): + self.assertLess(reference,graph_nodes) + graph_nodes += 1 + elif fields[0] in ["gcompile", "gtry"]: + self.assertLess(int(fields[2]),graph_nodes) + elif fields[0] in ["ginfo", "gsame"]: + for reference in map(int,fields[1:]): + self.assertLess(reference,graph_nodes) + elif fields[0] in ["cache", "counted"]: + self.assertLess(int(fields[-1]), samplers) + elif fields[0] == "spconstant": + splines += 1 + elif fields[0] == "sppoints": + self.assertLess(int(fields[1]), samplers) + self.assertEqual(len(fields), 3 + int(fields[2])*3) + for reference in map(int, fields[5::3]): + self.assertLess(reference, splines) + splines += 1 + elif fields[0] in ["spsampler", "spfail", "sprange"]: + self.assertLess(int(fields[1]), splines) + elif fields[0] == "surface": + for reference in map(int, fields[2:4]): + self.assertLess(reference, samplers) + self.assertGreater(int(fields[5]), 0) + elif fields[0] == "interpolate": + self.assertLess(int(fields[1]), samplers) + self.assertGreater(int(fields[2]), 0) + self.assertGreater(int(fields[3]), 0) + elif fields[0] == "slice": + self.assertIn(fields[1], list("0123")) + self.assertLess(int(fields[2]), samplers) + elif fields[0] == "offset": + self.assertIn(fields[1], ["0", "1", "2"]) + self.assertLess(int(fields[2]), noises) + elif fields[0] == "interval": + count = int(fields[3]) + references = [fields[2]] + fields[4+count:] + self.assertEqual(len(references), count + 2) + if fields[1] == "1": + self.assertEqual(count, 1) + for reference in map(int, references): + self.assertGreaterEqual(reference, 0) + self.assertLess(reference, samplers) + elif fields[0] in ["choice", "lerp"]: + mode = int(fields[1]) + references = [fields[2]] + if fields[0] == "choice" and mode == 0: + references += fields[5:7] + elif fields[0] == "lerp": + if mode != 1: + references.append(fields[3]) + if mode != 2: + references.append(fields[4]) + for reference in map(int, references): + self.assertGreaterEqual(reference, 0) + self.assertLess(reference, samplers) + elif fields[0] == "wcontext": + self.assertIn(fields[1], ["0", "1"]) + self.assertIn(fields[5], ["0", "1"]) + for reference in map(int,fields[2:5]): + self.assertGreaterEqual(reference, -1) + self.assertLess(reference, samplers) + elif fields[0] == "wfield": + self.assertIn(fields[1], ["0", "1", "2"]) + self.assertGreaterEqual(int(fields[2]), -1) + self.assertLess(int(fields[2]), samplers) + elif fields[0] == "blenddensity": + self.assertLess(int(fields[1]), samplers) + elif fields[0] == "round": + self.assertIn(fields[1], ["0", "1", "2", "3"]) + self.assertGreaterEqual(int(fields[2]), 0) + self.assertLess(int(fields[2]), samplers) + self.assertGreaterEqual(int(fields[3]), -1) + self.assertLess(int(fields[3]), samplers) + elif fields[0] == "power": + self.assertIn(fields[1], ["0", "1", "2"]) + references = fields[2:4] if fields[1] == "0" else fields[3:4] if fields[1] == "1" else fields[2:3] + for reference in map(int,references): + self.assertGreaterEqual(reference, 0) + self.assertLess(reference, samplers) + elif fields[0] in ["unary", "binary"]: + references = fields[2:3] if fields[0] == "unary" else fields[2:4] + for reference in map(int, references): + self.assertGreaterEqual(reference, 0) + self.assertLess(reference, samplers) + elif fields[0] == "shift": + self.assertLess(int(fields[1]), noises) + for reference in map(int, fields[2:]): + self.assertGreaterEqual(reference, -1) + self.assertLess(reference, samplers) + shift_modes.add(int(fields[3]) >= 0) + elif fields[0] == "noise": + noise_modes.add(tuple(fields[1:3])) + noises += 1 + elif fields[0] == "gradient": + tilings.add(tuple(fields[1:3])) + elif fields[0] in ["volume", "query"]: + self.assertLess(int(fields[1]), samplers) + if fields[0] in ["constant", "gradient", "noise", "shift", "unary", "binary", "round", "power", "choice", "lerp", "interval", "offset", "blended", "distance", "cache", "counted", "slice", "interpolate", "surface", "spsampler", "gcompile", "wfield", "blenddensity"]: + samplers += 1 + self.assertEqual(shift_modes, {False, True}) + self.assertEqual(tilings, {(str(axis), str(mode)) for axis in range(3) for mode in range(3)}) + self.assertEqual(noise_modes, {(kind, stream) for kind in ["perlin", "simplex", "smeared", "normal"] for stream in ["legacy", "xoroshiro"]}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_dynamic_support_parity.py b/tests/test_dynamic_support_parity.py new file mode 100644 index 000000000..6fb189c33 --- /dev/null +++ b/tests/test_dynamic_support_parity.py @@ -0,0 +1,31 @@ +import unittest +from tools import test_dynamic_support_parity as support + + +class DynamicSupportCorpusTests(unittest.TestCase): + def test_entity_states_coordinate_boundaries_and_failures(self): + facts={'states':[{'id':name} for name in ['minecraft:bamboo','minecraft:shulker_box','minecraft:moving_piston','minecraft:stone']], 'defaults':{'minecraft:stone':3}} + fixtures=list(support.corpus(facts,[0,1,2])) + self.assertEqual(fixtures,list(support.corpus(facts,[0,1,2]))) + self.assertEqual({f['entity'] for f in fixtures if f['state']==0},{'none'}) + self.assertEqual({f['entity'] for f in fixtures if f['state']==1},{'none','other','closed','opening','opened','closing'}) + self.assertEqual({f['entity'] for f in fixtures if f['state']==2},{'none','other','piston'}) + self.assertEqual({f['fail'] for f in fixtures},{-1,0,1,5,18}) + self.assertTrue(any(2147483647 in f['position'] for f in fixtures)) + self.assertTrue(any(-2147483648 in f['position'] for f in fixtures)) + + + def test_collision_progress_corpus_preserves_support_cases(self): + facts={'states':[{'id':name} for name in ['minecraft:bamboo','minecraft:shulker_box']], 'defaults':{}} + original=list(support.corpus(facts,[0,1])) + fixtures=list(support.collision_corpus(facts,[0,1])) + self.assertEqual([f for f in fixtures if not f.get('collision')],original) + self.assertTrue(all(f.get('collision') for f in fixtures if 'shulker_progress' in f)) + progress={tuple(f['shulker_progress']) for f in fixtures if 'shulker_progress' in f} + self.assertIn(('00000000','3f800000'),progress) + self.assertIn(('3f800000','00000000'),progress) + self.assertIn(('80000000','00000001'),progress) + self.assertGreater(len(progress),2000) + + +if __name__=='__main__':unittest.main() diff --git a/tests/test_entity_obstruction_parity.py b/tests/test_entity_obstruction_parity.py new file mode 100644 index 000000000..6fb78d40b --- /dev/null +++ b/tests/test_entity_obstruction_parity.py @@ -0,0 +1,19 @@ +import unittest +from tools import test_entity_obstruction_parity as obstruction + + +class EntityObstructionCorpusTests(unittest.TestCase): + def test_shapes_flags_vehicle_chains_and_world_failures(self): + fixtures=list(obstruction.corpus()) + self.assertEqual(fixtures,list(obstruction.corpus())) + self.assertTrue(any(not f['shape'] and f['fail'] for f in fixtures)) + self.assertTrue(any(len(f['shape'])>1 for f in fixtures)) + self.assertTrue(any(f['exclude']>=0 for f in fixtures)) + flags={(e['building'],e['removed'],e['spectator']) for f in fixtures for e in f['entities']} + self.assertEqual(len(flags),8) + self.assertTrue(any(any(e['parent']>=0 for e in f['entities']) for f in fixtures)) + for f in fixtures: + for i,e in enumerate(f['entities']):self.assertTrue(-1<=e['parent']= 4 for chain in chains)) + fixtures = list(placement.corpus()) + self.assertEqual(len(fixtures), sum(36 if any(v.get("type") == "count_on_every_layer" for v in chain) else 72 for chain in chains)) + self.assertEqual({f['legacy'] for f in fixtures}, {False, True}) + self.assertEqual({f['fail'] for f in fixtures}, {-1, 0, 2, 5}) + self.assertEqual({f['result'] for f in fixtures}, {0, 1, 2}) + self.assertTrue(any(f['query_fail'] == 1 for f in fixtures)) + self.assertTrue(all(f['positions'][0] == f['positions'][1] for f in fixtures)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_feature_region_parity.py b/tests/test_feature_region_parity.py new file mode 100644 index 000000000..ac5618dc7 --- /dev/null +++ b/tests/test_feature_region_parity.py @@ -0,0 +1,21 @@ +import unittest +from tools import test_feature_region_parity as regions + + +class FeatureRegionCorpusTests(unittest.TestCase): + def test_resident_mutation_contexts_and_failures(self): + fixtures = list(regions.corpus({})) + self.assertEqual(fixtures, list(regions.corpus({}))) + self.assertEqual({f['worldgen'] for f in fixtures}, {False, True}) + self.assertEqual({f['legacy'] for f in fixtures}, {False, True}) + self.assertEqual({f['stage'] for f in fixtures}, {'empty', 'terrain'}) + self.assertEqual({f['fail'] for f in fixtures}, {-1, 7}) + self.assertEqual({f['reject'] for f in fixtures}, {0, 3}) + self.assertTrue(all(f['features'][3]['type'] == 'sequence' for f in fixtures)) + self.assertEqual(len(fixtures[0]['features'][3]['features']), 4) + kinds = {m['type'] for f in fixtures for m in f['placement']} + self.assertTrue({'heightmap', 'count_on_every_layer', 'in_square'} <= kinds) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_feature_sort_parity.py b/tests/test_feature_sort_parity.py new file mode 100644 index 000000000..5457bbcb0 --- /dev/null +++ b/tests/test_feature_sort_parity.py @@ -0,0 +1,18 @@ +import unittest +from tools import test_feature_sort_parity as sort + + +class FeatureSortCorpusTests(unittest.TestCase): + def test_identity_duplicates_step_gaps_and_resource_orderings(self): + resources = {'a': [[], ['horizon:a', 'horizon:b']], 'b': [['horizon:c'], ['horizon:a']]} + fixtures = list(sort.corpus(resources)) + self.assertEqual(fixtures, list(sort.corpus(resources))) + self.assertTrue(any(f['biomes'] == [[[0, 1]], [[1, 0]]] for f in fixtures)) + self.assertTrue(any(f['biomes'] == [[[0, 0]], [[]]] for f in fixtures)) + self.assertTrue(any(f['biomes'] == [] for f in fixtures)) + self.assertTrue(any(f['biomes'] == [[], [[], [], []]] for f in fixtures)) + self.assertTrue(any(len(f['biomes']) == 2 and f['biomes'][0] == [[], [0, 1]] and f['biomes'][1] == [[2], [0]] for f in fixtures)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_fill_layer_parity.py b/tests/test_fill_layer_parity.py new file mode 100644 index 000000000..e4988a300 --- /dev/null +++ b/tests/test_fill_layer_parity.py @@ -0,0 +1,20 @@ +import json +import unittest +from tools import test_fill_layer_parity as fill + + +class FillLayerCorpusTests(unittest.TestCase): + def test_exhaustive_states_and_column_failure_cases(self): + states = ['stone', {'id': 'oak_log', 'properties': {'axis': 'x'}}] + fixtures = list(fill.corpus({'states': states})) + decode = [f for f in fixtures if f['repeats'] == 0] + self.assertEqual([json.loads(f['definition'])['state'] for f in decode], states) + self.assertEqual({f['fail'] for f in fixtures}, {-1, 0, 1, 7, 63}) + self.assertEqual({f['legacy'] for f in fixtures}, {False, True}) + self.assertEqual({f['world_min'] for f in fixtures}, {-64, -2147483648, 2147483647}) + heights = {json.loads(f['definition'])['height'] for f in fixtures} + self.assertTrue({-1, 0, 4064, 4065, 4294967297}.issubset(heights)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_float_log_parity.py b/tests/test_float_log_parity.py new file mode 100644 index 000000000..0024cea8e --- /dev/null +++ b/tests/test_float_log_parity.py @@ -0,0 +1,37 @@ +from pathlib import Path +import tempfile +import unittest +from unittest import mock + +from tools import test_float_log_parity as parity + + +class FloatLogRunnerTests(unittest.TestCase): + def test_binary_comparison_rejects_difference_and_truncated_equal_outputs(self): + with tempfile.TemporaryDirectory() as temp: + reference, candidate = Path(temp)/"java.bin", Path(temp)/"rust.bin" + reference.write_bytes(bytes.fromhex("000000003f800000")) + candidate.write_bytes(bytes.fromhex("000000003f800001")) + with self.assertRaisesRegex(ValueError, "float bits 3f800001"): + parity.compare(reference, candidate, 0x3f800000, 2) + candidate.write_bytes(reference.read_bytes()) + self.assertEqual(parity.compare(reference, candidate, 0x3f800000, 2), 2) + with self.assertRaisesRegex(ValueError, "does not cover 3 floats"): + parity.compare(reference, candidate, 0x3f800000, 3) + + def test_exhaustive_range_covers_all_float_bits(self): + self.assertEqual(parity.ranges(True), [(0, 1 << 32)]) + for start, count in parity.ranges(False): + self.assertGreaterEqual(start, 0) + self.assertLessEqual(start + count, 1 << 32) + + def test_failed_verification_removes_old_report(self): + with tempfile.TemporaryDirectory() as temp: + report = Path(temp)/"rust-float-log-parity/report.json" + report.parent.mkdir() + report.write_text('{"old_success":true}') + with mock.patch.object(parity.lab, "LOCAL", Path(temp)), mock.patch("sys.argv", ["parity"]), \ + mock.patch.object(parity.test_rust_parity, "verify_artifacts", side_effect=ValueError("corrupt artifact")): + with self.assertRaisesRegex(ValueError, "corrupt artifact"): + parity.main() + self.assertFalse(report.exists()) diff --git a/tests/test_fluid_parity.py b/tests/test_fluid_parity.py new file mode 100644 index 000000000..0721679e8 --- /dev/null +++ b/tests/test_fluid_parity.py @@ -0,0 +1,17 @@ +import unittest +from tools import test_fluid_parity as fluid + + +class FluidCorpusTests(unittest.TestCase): + def test_liquid_levels_grate_sources_and_query_failures(self): + facts={'states':[{'id':'minecraft:air'},{'id':'minecraft:water','properties':{'level':'0'}},{'id':'minecraft:water','properties':{'level':'8'}},{'id':'minecraft:lava','properties':{'level':'1'}},{'id':'minecraft:copper_grate','properties':{'waterlogged':'true'}},{'id':'minecraft:stone'}]} + fixtures=list(fluid.corpus(facts)) + self.assertEqual(fixtures,list(fluid.corpus(facts))) + self.assertEqual({v['state'] for v in fixtures},set(range(5))) + self.assertEqual({v['above'] for v in fixtures},set(range(5))) + self.assertEqual({v['sturdy'] for v in fixtures},{False,True}) + self.assertEqual({v['fail'] for v in fixtures},{-1,0,1,2}) + self.assertTrue(any(v['position'][1]==2147483647 for v in fixtures)) + + +if __name__=='__main__':unittest.main() diff --git a/tests/test_geometry_parity.py b/tests/test_geometry_parity.py new file mode 100644 index 000000000..783d188dd --- /dev/null +++ b/tests/test_geometry_parity.py @@ -0,0 +1,41 @@ +from pathlib import Path +import tempfile +import unittest +from unittest import mock + +from tools import test_geometry_parity as geometry +from tools import test_collision_parity as collision + + +class GeometryRunnerTests(unittest.TestCase): + def test_bad_artifacts_remove_old_success_reports(self): + for module, name in [(geometry, "rust-geometry-parity"), (collision, "rust-collision-parity")]: + with self.subTest(name=name), tempfile.TemporaryDirectory() as temp: + local = Path(temp) + report = local / name / "report.json" + report.parent.mkdir() + report.write_text('{"previous_success":true}') + with mock.patch.object(module.lab, "LOCAL", local), mock.patch("sys.argv", ["parity"]), \ + mock.patch.object(module.test_rust_parity, "verify_artifacts", side_effect=ValueError("corrupt artifact")): + with self.assertRaisesRegex(ValueError, "corrupt artifact"): + module.main() + self.assertFalse(report.exists()) + + def test_collision_counts_reject_missing_partial_and_inconsistent_coverage(self): + for output in ["", "HORIZON_COLLISION_RESULT {}", 'HORIZON_COLLISION_RESULT {"registry_states":35723,"cached_states":1,"uncached_states":1,"queries":6,"unique_shapes":1}']: + with self.subTest(output=output), self.assertRaises((AssertionError, KeyError)): + collision.counts(output) + + def test_geometry_inputs_are_repeatable_and_include_ieee_boundaries(self): + commands = list(geometry.corpus()) + self.assertEqual(commands, list(geometry.corpus())) + joined = "\n".join(commands) + for value in ["8000000000000000", "7ff0000000000000", "fff0000000000000", "7ff8000000000000", "0000000000000001"]: + self.assertIn(value, joined) + operations = {line.split()[0] for line in commands} + self.assertEqual(operations, {"vec", "box", "block-box", "grid", "query", "many", "motion", "step-motion", "trig-table", "rotation", "traverse", "join", "make-box", "optimize", "join-optimized", "block-iterate", "box-iterate", "sweep", "floor-height"}) + self.assertEqual({int(line.split()[-1]) for line in commands if line.startswith("join-optimized ")}, set(range(16))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_height_provider_parity.py b/tests/test_height_provider_parity.py new file mode 100644 index 000000000..f9d28d594 --- /dev/null +++ b/tests/test_height_provider_parity.py @@ -0,0 +1,23 @@ +import json +import unittest +from tools import test_height_provider_parity as height + + +class HeightProviderCorpusTests(unittest.TestCase): + def test_anchor_variants_inner_plateaus_and_overflow_contexts(self): + definitions = list(height.definitions()) + self.assertEqual(definitions, list(height.definitions())) + values = [json.loads(raw) for raw in definitions] + objects = [v for v in values if isinstance(v, dict)] + self.assertTrue({'weighted_list', 'constant', 'uniform', 'biased_to_bottom', 'very_biased_to_bottom', 'trapezoid'} <= {v.get('type') for v in objects}) + self.assertTrue(any(v.get('absolute') == 5 and v.get('type') == 'uniform' for v in objects)) + self.assertTrue(any(v.get('inner') == 0 for v in objects)) + self.assertTrue(any(v.get('plateau') == -2**31 for v in objects)) + fixtures = list(height.corpus()) + self.assertEqual(len(fixtures), len(definitions) * 30) + self.assertEqual({f['legacy'] for f in fixtures}, {False, True}) + self.assertTrue(any(f['context'][0] == -2**31 for f in fixtures)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_heightmap_parity.py b/tests/test_heightmap_parity.py new file mode 100644 index 000000000..70c8ffb3b --- /dev/null +++ b/tests/test_heightmap_parity.py @@ -0,0 +1,39 @@ +import unittest +from tools import test_heightmap_parity as heightmap + + +class HeightmapCorpusTests(unittest.TestCase): + def facts(self): + names=["air","cave_air","void_air","stone","water","lava","oak_leaves","oak_slab","seagrass","snow","powder_snow","glass","barrier"] + return {"states":[["minecraft:"+name,name.endswith("air"),name in ["water","lava"],name] for name in names], + "defaults":{"minecraft:"+name:i for i,name in enumerate(names)}} + + def test_every_state_is_inserted_queried_and_removed(self): + facts=self.facts();fixtures=list(heightmap.corpus(facts)) + self.assertEqual(fixtures,list(heightmap.corpus(facts))) + ops=fixtures[0]["ops"] + for i in range(len(facts["states"])): + self.assertEqual(ops[i*3],["set",4,5,7,i,63]) + self.assertEqual(ops[i*3+1],["query",4,7]) + self.assertEqual(ops[i*3+2],["set",4,5,7,facts["defaults"]["minecraft:air"],63]) + + def test_corpus_keeps_vertical_edges_raw_fallbacks_and_traces(self): + fixtures=list(heightmap.corpus(self.facts())) + self.assertIn((-2032,4064),{(f["min"],f["height"]) for f in fixtures}) + for f in fixtures: + self.assertEqual(f["min"]%16,0) + self.assertEqual(f["height"]%16,0) + self.assertGreaterEqual(f["min"],-2032) + self.assertLessEqual(f["min"]+f["height"],2032) + for op in f["ops"]: + if op[0]=="set":self.assertTrue(f["min"]<=op[2] f['min'] for f in fixtures)) + self.assertTrue(any(f['noise_min'] != f['min'] for f in fixtures)) + self.assertTrue(any(f['cx'] < 0 for f in fixtures)) + for f in fixtures: + self.assertLessEqual(f['min'], f['write_min']) + self.assertLess(f['write_max'], f['min'] + f['height']) + for x, low, z, high, state in f['initial']: + self.assertTrue(0 <= x < 16 and 0 <= z < 16) + self.assertTrue(f['min'] <= low <= high < f['min'] + f['height']) + self.assertIn(state, facts['defaults'].values()) + + def test_generated_chunks_use_each_setting_and_share_the_router_surface_root(self): + names = ['stone', 'water', 'air', 'cave_air', 'void_air', 'oak_log', + 'oak_leaves', 'netherrack', 'end_stone'] + facts = {'defaults': {'minecraft:' + name: i for i, name in enumerate(names)}} + settings = {'minecraft:overworld': json.dumps({ + 'noise': {'min_y': -64, 'height': 384}, 'sea_level': 63, + 'default_block': 'minecraft:stone', 'default_fluid': 'minecraft:water', + 'material_rule': 'minecraft:overworld', + 'noise_router': {'chunk_surface_level': {'type': 'constant', 'argument': 64}}, + 'aquifers': {'barrier': 0}})} + generated = [f for f in stage.corpus(facts, {'minecraft:plains': ''}, settings) if 'router' in f] + self.assertEqual(len(generated), 6) + self.assertEqual(sum(f['repeats'] for f in generated), 8) + self.assertEqual({f['legacy'] for f in generated}, {False, True}) + self.assertTrue(any(abs(f['cx']) > 1_000_000 for f in generated)) + for f in generated: + self.assertEqual(f['preliminary'], f['router']['chunk_surface_level']) + self.assertEqual(f['initial'], []) + self.assertEqual(f['aquifers'], {'barrier': 0}) + self.assertTrue(f['biome_zoom']) + + def test_carving_masks_have_disjoint_runs_and_surface_restoration_inputs(self): + names = ['grass_block', 'mycelium', 'dirt', 'bedrock'] + facts = {'defaults': {'minecraft:' + name: i for i, name in enumerate(names)}} + f = {'min': -64, 'height': 384, 'sea': 63} + result = stage.carving_fixture(f, facts) + self.assertEqual(result['filters'], [0, 1]) + self.assertEqual({q[3] for q in result['initial']}, set(range(4))) + runs = [q for q in result['spans'] if q[:2] == [6, 0]] + self.assertEqual(len(runs), 2) + self.assertLess(runs[1][3] + 1, runs[0][2]) + for x, z, low, high in result['spans']: + self.assertTrue(0 <= x <= 15 and 0 <= z <= 15) + self.assertTrue(-63 <= low <= high <= 312) + + def test_top_queries_cover_water_and_gradient_boundaries(self): + f = {'cx': -1, 'cz': 1875000, 'min': -64, 'height': 384, 'sea': 63} + queries = stage.top_queries(f) + self.assertEqual(len(queries), 96) + self.assertEqual({q[3] for q in queries}, {False, True}) + self.assertEqual({q[1] for q in queries}, {-65, -64, 62, 63, 319, 320}) + self.assertTrue(any(q[0] == -16 and q[2] == 30000000 for q in queries)) + self.assertTrue(any(q[0] == -1 and q[2] == 30000015 for q in queries)) + + def test_generated_neighborhood_uses_preset_possible_biomes(self): + names = ['stone', 'water', 'air', 'cave_air', 'void_air', 'oak_log', 'oak_leaves', 'netherrack', 'end_stone'] + facts = {'defaults': {'minecraft:' + name: i for i, name in enumerate(names)}} + setting = {'noise': {'min_y': 0, 'height': 128}, 'sea_level': 63, + 'default_block': 'minecraft:stone', 'default_fluid': 'minecraft:water', + 'material_rule': 'minecraft:end', 'noise_router': {'chunk_surface_level': 0}} + presets = {'minecraft:overworld': json.dumps([{'biome': 'minecraft:plains'}])} + fixtures = list(stage.corpus(facts, {'minecraft:plains': ''}, {'minecraft:end': json.dumps(setting)}, presets)) + generated = [f for f in fixtures if 'biome_source' in f] + self.assertEqual(len(generated), 6) + self.assertTrue(all(f['biome_source'] == 'end' for f in generated)) + for f in generated: + if f['legacy']: + self.assertEqual(len(f['possible']), 5) + self.assertIn('minecraft:small_end_islands', f['possible']) + else: + self.assertIsNone(f['possible']) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_material_surface_parity.py b/tests/test_material_surface_parity.py new file mode 100644 index 000000000..85665b25f --- /dev/null +++ b/tests/test_material_surface_parity.py @@ -0,0 +1,21 @@ +import unittest +from tools import test_material_surface_parity as material + + +class MaterialSurfaceCorpusTests(unittest.TestCase): + def test_seeded_band_stream_modes_and_boundary_overrides(self): + fixtures=list(material.corpus()) + self.assertEqual(fixtures,list(material.corpus())) + real=[f for f in fixtures if f["overrides"]==[None]*3] + self.assertEqual(len(real),128) + self.assertEqual({(f["legacy"],f["child"]) for f in real},{(False,False),(False,True),(True,False),(True,True)}) + self.assertEqual({f["consume"] for f in real},{-1,0,1,17}) + values={f["overrides"][0] for f in fixtures if f["overrides"][0] is not None} + self.assertTrue({"3dffffff","3e000000","3e000001","be000000","7f800000","ff800000","7fc00001"}<=values) + points=fixtures[0]["points"] + self.assertIn([7,-193,-11],points) + self.assertIn([7,-192,-11],points) + self.assertIn([-2**31,-2**31,2**31-1],points) + + +if __name__=="__main__":unittest.main() diff --git a/tests/test_noise_parity.py b/tests/test_noise_parity.py new file mode 100644 index 000000000..b40d807fb --- /dev/null +++ b/tests/test_noise_parity.py @@ -0,0 +1,43 @@ +from collections import Counter +from pathlib import Path +import tempfile +import unittest +from unittest import mock + +from tools import test_noise_parity as parity + + +class NoiseRunnerTests(unittest.TestCase): + def test_failed_reference_verification_removes_previous_success(self): + with tempfile.TemporaryDirectory() as temp: + report = Path(temp) / "rust-noise-parity/report.json" + report.parent.mkdir() + report.write_text('{"previous_success":true}') + with mock.patch.object(parity.lab, "LOCAL", Path(temp)), mock.patch("sys.argv", ["parity"]), \ + mock.patch.object(parity.test_rust_parity, "verify_artifacts", side_effect=ValueError("corrupt artifact")): + with self.assertRaisesRegex(ValueError, "corrupt artifact"): + parity.main() + self.assertFalse(report.exists()) + + def test_corpus_replays_both_streams_offsets_and_accumulation_modes(self): + commands = list(parity.corpus()) + self.assertEqual(commands, list(parity.corpus())) + counts = Counter(line.split()[0] for line in commands) + self.assertGreater(counts["query"], 190000) + self.assertEqual(counts["local"], 38400) + creates = [line.split() for line in commands if line.startswith("create ")] + self.assertEqual({(line[1], line[2], line[4]) for line in creates}, + {(kind, stream, skip) for stream in ["legacy", "xoroshiro"] + for kind, skip in [("perlin", "0"), ("simplex", "0"), ("simplex", "1"), ("smeared", "0")]}) + self.assertEqual({line.split()[-1] for line in commands if line.startswith("volume ")}, {"0", "1", "2", "3"}) + wrapped = {line.split()[1] for line in commands if line.startswith("wrap ")} + self.assertTrue({"8000000000000000", "7ff0000000000000", "fff0000000000000", "7ff8000000000000", "0000000000000001"} <= wrapped) + normal = [line.split() for line in commands if line.startswith("normal ")] + self.assertEqual({line[1] for line in normal}, {"legacy", "xoroshiro"}) + self.assertEqual({line[3] for line in normal}, {"0", "1", "2", "3"}) + self.assertEqual({line[6] for line in normal}, {"0", "1", "2"}) + self.assertIn("stack 0 ", commands) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_packs.py b/tests/test_packs.py index 9b2e80b1e..a4fcde8f0 100644 --- a/tests/test_packs.py +++ b/tests/test_packs.py @@ -10,18 +10,34 @@ from tools import build_pack, compare_benchmarks, runtime class PackTests(unittest.TestCase): + def test_rebrand_upgrade_retires_legacy_and_current_names(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + mods = root / "instance/mods" + mods.mkdir(parents=True) + previous = [mods / "horizon-lab-0.20.0.jar", mods / "horizon-0.21.0.jar"] + for old in previous: + with zipfile.ZipFile(old, "w") as archive: + archive.writestr("fabric.mod.json", json.dumps({"id": "horizonlab"})) + new = root / "horizon-0.22.0.jar" + new.write_bytes(b"new original fixture") + runtime.install_original_mod(new, mods) + self.assertTrue(all(not old.exists() for old in previous)) + self.assertEqual(list(mods.iterdir()), [mods / new.name]) + self.assertEqual(len(list((mods.parent / ".horizon-mod-backups").glob("*.jar"))), 2) + def test_original_mod_upgrade_preserves_backup_and_other_mods(self): with tempfile.TemporaryDirectory() as temp: root = Path(temp) mods = root / "instance/mods" mods.mkdir(parents=True) - old = mods / "horizon-lab-0.2.0.jar" + old = mods / "horizon-0.2.0.jar" with zipfile.ZipFile(old, "w") as archive: archive.writestr("fabric.mod.json", json.dumps({"id": "horizonlab"})) old_bytes = old.read_bytes() other = mods / "other.jar" other.write_bytes(b"another mod") - new = root / "horizon-lab-0.3.0.jar" + new = root / "horizon-0.3.0.jar" new.write_bytes(b"new original fixture") runtime.install_original_mod(new, mods) self.assertFalse(old.exists()) @@ -34,9 +50,9 @@ class PackTests(unittest.TestCase): def test_original_mod_upgrade_refuses_unrelated_named_jar(self): with tempfile.TemporaryDirectory() as temp: root = Path(temp) - with zipfile.ZipFile(root / "horizon-lab-0.1.0.jar", "w") as archive: + with zipfile.ZipFile(root / "horizon-0.1.0.jar", "w") as archive: archive.writestr("fabric.mod.json", json.dumps({"id": "someoneelse"})) - new = root / "horizon-lab-0.3.0.jar" + new = root / "horizon-0.3.0.jar" new.write_bytes(b"new original fixture") with self.assertRaisesRegex(ValueError, "another mod"): runtime.install_original_mod(new, root) @@ -176,7 +192,7 @@ class PackTests(unittest.TestCase): with zipfile.ZipFile(pack) as archive: names = archive.namelist() self.assertEqual([n for n in names if n.endswith(".jar")], - [f"overrides/mods/horizon-lab-{build_pack.read_lock()['pack_version']}.jar"]) + [f"overrides/mods/horizon-{build_pack.read_lock()['pack_version']}.jar"]) index = json.loads(archive.read("modrinth.index.json")) self.assertEqual(index["dependencies"]["minecraft"], "26.3") options = dict(line.split(":", 1) for line in archive.read("overrides/options.txt").decode().splitlines()) diff --git a/tests/test_piston_shape_parity.py b/tests/test_piston_shape_parity.py new file mode 100644 index 000000000..b800e8c84 --- /dev/null +++ b/tests/test_piston_shape_parity.py @@ -0,0 +1,19 @@ +import unittest +from tools import test_piston_shape_parity as piston + + +class PistonShapeCorpusTests(unittest.TestCase): + def test_source_extension_thresholds_noclip_and_float_interpolation(self): + facts={'states':[{'id':name} for name in ['minecraft:stone','minecraft:piston','minecraft:shulker_box','minecraft:moving_piston']], 'defaults':{'minecraft:stone':0}} + fixtures=list(piston.corpus(facts)) + self.assertEqual(fixtures,list(piston.corpus(facts))) + self.assertEqual({f['noclip'] for f in fixtures},set(range(-1,6))) + self.assertEqual({f['direction'] for f in fixtures},set(range(6))) + self.assertEqual({(f['source'],f['extending']) for f in fixtures},{(s,e) for s in [False,True] for e in [False,True]}) + self.assertEqual(sum(f['kinematic'] for f in fixtures),10000) + self.assertTrue(any(f['fail']==0 for f in fixtures)) + for field in ['progress','previous','partial']: + self.assertTrue(all(len(f[field])==8 for f in fixtures)) + + +if __name__=='__main__':unittest.main() diff --git a/tests/test_placement_parity.py b/tests/test_placement_parity.py new file mode 100644 index 000000000..5b4d4412f --- /dev/null +++ b/tests/test_placement_parity.py @@ -0,0 +1,27 @@ +import json +import unittest +from tools import test_placement_parity as placement + + +class PlacementCorpusTests(unittest.TestCase): + def test_modifier_kinds_callback_failures_and_overflow(self): + definitions = list(placement.definitions()) + self.assertEqual(definitions, list(placement.definitions())) + values = [json.loads(raw) for raw in definitions] + kinds = {v.get('type') for v in values if isinstance(v, dict)} + self.assertTrue({'block_predicate_filter', 'environment_scan', 'count_on_every_layer', 'cuboid', 'noise_based_count', 'noise_threshold_count', 'heightmap', 'surface_relative_threshold_filter', 'surface_water_depth_filter', 'count', 'in_square', 'offset', 'height_range', 'rarity_filter', 'random_chance', 'fixed_placement', 'randomly_selected'} <= kinds) + fixtures = list(placement.corpus()) + self.assertEqual({f['legacy'] for f in fixtures}, {False, True}) + self.assertEqual({f['fail'] for f in fixtures}, {-1, 0, 2}) + self.assertEqual({f['draw'] for f in fixtures}, {False, True}) + self.assertEqual({f['height_mode'] for f in fixtures}, {0, 1}) + self.assertEqual({f['count_only'] for f in fixtures}, {False, True}) + self.assertTrue(any(f['query_fail'] == 1 for f in fixtures)) + self.assertTrue(any(f['world_min'] != f['context'][0] for f in fixtures)) + self.assertTrue(any(f['context'][0] == 2**31 - 1 for f in fixtures)) + self.assertTrue(any('4294967297' in f['definition'] for f in fixtures)) + self.assertTrue(all(len(f['positions']) == 4 for f in fixtures)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_replace_block_parity.py b/tests/test_replace_block_parity.py new file mode 100644 index 000000000..29f98b46c --- /dev/null +++ b/tests/test_replace_block_parity.py @@ -0,0 +1,20 @@ +import json +import unittest +from tools import test_replace_block_parity as replace + + +class ReplaceBlockCorpusTests(unittest.TestCase): + def test_ordered_targets_failures_and_repeated_world_state(self): + fixtures = list(replace.corpus({})) + self.assertEqual({f['legacy'] for f in fixtures}, {False, True}) + self.assertEqual({f['fail'] for f in fixtures}, {-1, 0, 1, 2, 4}) + self.assertEqual({f['reject'] for f in fixtures}, {0, 2}) + self.assertTrue(all(f['repeats'] == 3 for f in fixtures)) + definitions = [json.loads(f['definition']) for f in fixtures] + self.assertTrue(any(d['targets'] == [] for d in definitions)) + self.assertTrue(any(isinstance(d['targets'], list) and len(d['targets']) == 3 for d in definitions)) + self.assertTrue(any('random_block_match' in f['definition'] for f in fixtures)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_rule_test_parity.py b/tests/test_rule_test_parity.py new file mode 100644 index 000000000..7466fc26c --- /dev/null +++ b/tests/test_rule_test_parity.py @@ -0,0 +1,19 @@ +import json +import unittest +from tools import test_rule_test_parity as rules + + +class RuleTestCorpusTests(unittest.TestCase): + def test_registry_coverage_logic_and_random_modes(self): + facts = {'states': ['air', 'stone'], 'defaults': {'minecraft:air': 0, 'minecraft:stone': 1}} + fixtures = list(rules.corpus(facts, {'minecraft:test': '{}'})) + kinds = {json.loads(f['definition']).get('predicate_type') for f in fixtures if isinstance(json.loads(f['definition']), dict)} + self.assertTrue({'always_true', 'not', 'all_of', 'any_of', 'block_match', 'blockstate_match', 'tag_match', 'height_match', 'random_block_match', 'random_blockstate_match'} <= kinds) + self.assertEqual({f['legacy'] for f in fixtures}, {False, True}) + self.assertTrue(any('minecraft:test' in f['definition'] for f in fixtures)) + self.assertTrue(any('horizon:missing' in f['definition'] for f in fixtures)) + self.assertTrue(all(0 <= s < len(facts['states']) for f in fixtures for s in f['states'])) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_rust_parity.py b/tests/test_rust_parity.py new file mode 100644 index 000000000..3efc9de1c --- /dev/null +++ b/tests/test_rust_parity.py @@ -0,0 +1,72 @@ +import json +from pathlib import Path +import tempfile +import unittest +from unittest import mock + +from tools import test_rust_parity as parity + + +class ParityRunnerTests(unittest.TestCase): + def test_report_rejects_sources_changed_during_a_run(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + source = root / "source.rs" + source.write_text("before") + with mock.patch.object(parity.lab, "ROOT", root): + before = parity.source_hashes([source]) + parity.ensure_sources_unchanged([source], before) + source.write_text("after") + with self.assertRaisesRegex(RuntimeError, "source.rs"): + parity.ensure_sources_unchanged([source], before) + def test_comparison_rejects_changed_missing_extra_and_empty_results(self): + for reference, candidate in [("rng 0 1\n", "rng 0 2\n"), + ("rng 0 1\n", ""), + ("rng 0 1\n", "rng 0 1\nrng 1 2\n"), ("", "")]: + with self.subTest(reference=reference, candidate=candidate), tempfile.TemporaryDirectory() as temp: + left, right = Path(temp) / "reference", Path(temp) / "candidate" + left.write_text(reference) + right.write_text(candidate) + with self.assertRaises(AssertionError): + parity.compare(left, right) + + def test_comparison_counts_matching_lines(self): + with tempfile.TemporaryDirectory() as temp: + left, right = Path(temp) / "reference", Path(temp) / "candidate" + left.write_text("rng 0 1\nrng 1 -1\n") + right.write_text(left.read_text()) + self.assertEqual(parity.compare(left, right), 2) + + def test_failed_artifact_verification_removes_previous_success(self): + with tempfile.TemporaryDirectory() as temp: + local = Path(temp) + report = local / "rust-parity/report.json" + report.parent.mkdir() + report.write_text(json.dumps({"previous_success": True})) + with mock.patch.object(parity.lab, "LOCAL", local), mock.patch("sys.argv", ["parity"]), \ + mock.patch.object(parity, "verify_artifacts", side_effect=ValueError("corrupt artifact")): + with self.assertRaisesRegex(ValueError, "corrupt artifact"): + parity.main() + self.assertFalse(report.exists()) + + def test_corpus_is_repeatable_and_contains_rejection_and_word_boundaries(self): + commands = list(parity.corpus()) + self.assertEqual(commands, list(parity.corpus())) + self.assertIn("xoroshiro_state 0 0 2200", commands) + self.assertIn("legacy -9223372036854775808 2200", commands) + factories = [line.split() for line in commands if line.startswith("factory ")] + self.assertEqual(len(factories), 4400) + self.assertTrue({"-", "d800", "dc00", "d83dde00", "d8000061dc00"} <= {line[9] for line in factories}) + helpers = [line.split() for line in commands if line.startswith("helpers ")] + self.assertEqual(len(helpers), 5000) + for stream in ["legacy", "xoroshiro"]: + bounds = {(int(line[3]), int(line[4])) for line in helpers if line[1] == stream} + self.assertTrue({(-2147483648, 2147483647), (2147483647, -2147483648), (0, 0), (0, 1073741825)} <= bounds) + for bits in range(1, 33): + lengths = {int(line.split()[2]) for line in commands if line.startswith(f"storage {bits} ")} + per_word = 64 // bits + self.assertTrue({0, 1, per_word - 1, per_word, per_word + 1, 4096} <= lengths) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_scattered_ore_parity.py b/tests/test_scattered_ore_parity.py new file mode 100644 index 000000000..783632d6f --- /dev/null +++ b/tests/test_scattered_ore_parity.py @@ -0,0 +1,21 @@ +import json +import unittest +from tools import test_scattered_ore_parity as ore + + +class ScatteredOreCorpusTests(unittest.TestCase): + def test_exposure_directions_empty_targets_and_boundary_sizes(self): + fixtures = list(ore.corpus({})) + self.assertEqual({f['mode'] for f in fixtures}, set(range(8))) + self.assertEqual({f['legacy'] for f in fixtures}, {False, True}) + self.assertEqual({f['fail'] for f in fixtures}, {-1, 0, 7}) + definitions = [json.loads(f['definition']) for f in fixtures] + sizes = {d['size'] for d in definitions} + self.assertTrue({-1, 0, 1, 7, 8, 64, 65, 4294967297} <= sizes) + self.assertTrue(any(d['targets'] == [] for d in definitions)) + self.assertTrue(any(f['origin'][0] == 2147483647 for f in fixtures)) + self.assertTrue(any(f['origin'][0] == -2147483648 for f in fixtures)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_state_provider_parity.py b/tests/test_state_provider_parity.py new file mode 100644 index 000000000..e4241890a --- /dev/null +++ b/tests/test_state_provider_parity.py @@ -0,0 +1,32 @@ +import json +import unittest +from tools import test_state_provider_parity as provider + + +class StateProviderCorpusTests(unittest.TestCase): + def test_exclusive_decode_empty_fallback_rotations_and_shared_streams(self): + facts = {'states': [{'id': 'minecraft:stone'}, {'id': 'minecraft:water'}], 'defaults': {'minecraft:stone': 0, 'minecraft:water': 1}} + resources = {'horizon:provider': '{"id":"stone"}'} + fixtures = list(provider.corpus(facts, {'horizon:empty': '{"values":[]}'}, catalog_resources=resources, survival_rules={"minecraft:stone": "Always", "minecraft:water": "Always"})) + self.assertEqual(fixtures, list(provider.corpus(facts, {'horizon:empty': '{"values":[]}'}, catalog_resources=resources, survival_rules={"minecraft:stone": "Always", "minecraft:water": "Always"}))) + definitions = [json.loads(f['definition']) for f in fixtures] + self.assertTrue(any(isinstance(v, dict) and v.get('type') == 'simple' and v.get('id') == 'stone' for v in definitions)) + self.assertTrue(any(isinstance(v, dict) and v.get('type') == 'random_block' and v.get('blocks') == [] for v in definitions)) + self.assertEqual({f['typed'] for f in fixtures}, {False, True}) + self.assertEqual({(f['legacy'], f['worldgen']) for f in fixtures}, {(False, False), (True, False), (False, True), (True, True)}) + self.assertEqual({f['fail'] for f in fixtures}, {-1, 0, 1, 2}) + for kind in ['copy_properties', 'randomized_int', 'noise', 'noise_threshold', 'dual_noise', 'rule_based']: + self.assertTrue(any(isinstance(v, dict) and v.get('type') == kind for v in definitions)) + self.assertTrue(any([2147483647, -2147483648, 2147483647] in f.get('positions', []) for f in fixtures)) + self.assertEqual({f.get('query_fail', -1) for f in fixtures}, {-1, 0, 1, 2}) + self.assertTrue(any(f.get('bounds') == [2147483647, 2, 0] for f in fixtures)) + self.assertTrue(any(f.get("holder") and json.loads(f["definition"]) == "horizon:provider" for f in fixtures)) + conditions = [rule['if_true'] for v in definitions if isinstance(v, dict) and v.get('type') == 'rule_based' and isinstance(v.get('rules'), list) for rule in v['rules'] if isinstance(rule, dict) and isinstance(rule.get('if_true'), dict)] + for kind in ['matching_block_tag', 'matching_blocks', 'matching_fluids', 'matching_biomes', 'unobstructed', 'solid', 'replaceable', 'has_sturdy_face', 'would_survive', 'height_range', 'volume_match']: + self.assertTrue(any(v.get('type') == kind for v in conditions)) + for direction in ['down', 'up', 'north', 'south', 'west', 'east']: + self.assertTrue(any(isinstance(v, dict) and v.get('type') == 'rotated' and v.get('direction') == direction for v in definitions)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_structure_density_parity.py b/tests/test_structure_density_parity.py new file mode 100644 index 000000000..f29bfe470 --- /dev/null +++ b/tests/test_structure_density_parity.py @@ -0,0 +1,27 @@ +import unittest +from tools import test_structure_density_parity as structure + + +class StructureDensityCorpusTests(unittest.TestCase): + def test_modes_kernel_neighborhood_and_null_bounds_are_covered(self): + fixtures=list(structure.corpus()) + self.assertEqual(fixtures,list(structure.corpus())) + self.assertEqual({p[1] for f in fixtures for p in f["pieces"]},{"NONE","BURY","BEARD_THIN","BEARD_BOX","ENCAPSULATE"}) + kernel=fixtures[0] + self.assertEqual(kernel["junctions"],[[0,0,0]]) + self.assertIn([29,29,29,-14,-14,-14,1,1,1,3],kernel["volumes"]) + self.assertTrue(any(f["affected"] is None and f["pieces"] for f in fixtures)) + self.assertTrue(any(p[2]==-2**31 for f in fixtures for p in f["pieces"])) + self.assertTrue(any(p[2]==2**31-1 for f in fixtures for p in f["pieces"])) + + def test_clipped_stride_fixture_exercises_a_sample_below_bounds(self): + fixture=next(f for f in structure.corpus() if f["affected"]==[1,1,1,9,9,9]) + volume=fixture["volumes"][0] + for axis in range(3): + minimum=volume[axis+3];step=volume[axis+6];bound=fixture["affected"][axis] + first=minimum+max(0,bound-minimum)//step*step + self.assertLess(first,bound) + self.assertGreater(volume[9],0) + + +if __name__=="__main__":unittest.main() diff --git a/tests/test_terrain_parity.py b/tests/test_terrain_parity.py new file mode 100644 index 000000000..071b7cf65 --- /dev/null +++ b/tests/test_terrain_parity.py @@ -0,0 +1,37 @@ +import json +import unittest +from tools import test_terrain_parity as terrain + + +class TerrainCorpusTests(unittest.TestCase): + def inputs(self): + names=["air","void_air","cave_air","stone","water","lava","oak_leaves","glass","oak_slab"] + facts={"states":[["minecraft:"+name,name.endswith("air"),name in ["water","lava","oak_slab"]] for name in names], + "defaults":{"minecraft:"+name:i for i,name in enumerate(names)}} + setting={"noise":{"min_y":-64,"height":384},"default_block":"minecraft:stone","default_fluid":"minecraft:water","sea_level":63,"noise_router":{},"aquifers":{"barrier":0}} + return facts,{"settings":{"minecraft:overworld":json.dumps(setting)}} + + def test_corpus_retains_presets_seed_modes_and_repeat_fills(self): + facts,bundle=self.inputs();fixtures=list(terrain.corpus(facts,bundle)) + self.assertEqual(fixtures,list(terrain.corpus(facts,bundle))) + self.assertEqual(len(fixtures),66) + self.assertEqual({f["legacy"] for f in fixtures[:6]},{True,False}) + self.assertEqual({f["seed"] for f in fixtures[:6]},{0,-1,0x123456789abcdef}) + self.assertTrue(all(f["initial"] for f in fixtures)) + self.assertTrue(any(f["repeats"]==2 for f in fixtures[:6])) + self.assertTrue(any(f["aquifers"] is None for f in fixtures)) + self.assertTrue(any(f["aquifers"] is not None for f in fixtures)) + + def test_partial_fills_and_input_writes_stay_inside_chunk(self): + facts,bundle=self.inputs();fixtures=list(terrain.corpus(facts,bundle)) + self.assertTrue(any(f["min"] -Horizon Lab — Compare runs +Horizon — Compare runs
-
Horizon Lab
Offline · files stay on your device
+
Horizon
Offline · files stay on your device

Compare your runs.

Choose two Horizon benchmark JSON files from your instance’s horizon-benchmarks folder. Add each matching CSV to see frame spikes. Compare frames with frames, or server ticks with server ticks.

diff --git a/tools/build_mod.py b/tools/build_mod.py index faacf092e..f6a01aa52 100644 --- a/tools/build_mod.py +++ b/tools/build_mod.py @@ -17,7 +17,7 @@ except ImportError: import runtime ROOT = lab.ROOT -SOURCE = ROOT / "mods/horizon-lab/src" +SOURCE = ROOT / "mods/horizon/src" BUILD = ROOT / ".local/mod-build" @@ -106,11 +106,11 @@ def build(): "dev.horizonlab.metrics.ResidentMemoryTest"], check=True) subprocess.run(["java", "-cp", os.pathsep.join([str(adapter_tests), test_classpath]), "dev.horizonlab.geometry.RelativeTerrainPositionTest"], check=True) - output = ROOT / "dist" / f"horizon-lab-{lock['pack_version']}.jar" + output = ROOT / "dist" / f"horizon-{lock['pack_version']}.jar" output.parent.mkdir(exist_ok=True) entries = {path.relative_to(classes).as_posix(): path.read_bytes() for path in classes.rglob("*.class")} if any(not name.startswith("dev/horizonlab/") for name in entries): - raise ValueError("Only original Horizon Lab classes may be packaged") + raise ValueError("Only original Horizon classes may be packaged") resources = SOURCE / "main/resources" entries.update({path.relative_to(resources).as_posix(): path.read_bytes() for path in resources.rglob("*") if path.is_file()}) entries["LICENSE"] = (ROOT / "LICENSE").read_bytes() diff --git a/tools/build_pack.py b/tools/build_pack.py index cbbe2b49e..0900ab497 100644 --- a/tools/build_pack.py +++ b/tools/build_pack.py @@ -82,7 +82,7 @@ def options(profile): def overrides(profile_name, mod_bytes): profile = PROFILES[profile_name] - files = {f"mods/horizon-lab-{read_lock()['pack_version']}.jar": mod_bytes, + files = {f"mods/horizon-{read_lock()['pack_version']}.jar": mod_bytes, "config/horizon-profile.txt": (profile_name + "\n").encode(), "options.txt": options(profile).encode()} experiment = any(profile.get(key, False) for key in ["adaptive", "pacing", "queue_wait", "dispatch_retry", "tick_dedup", "culling_empty", "culling_rays", "terrain_position", "quad_reuse"]) @@ -138,7 +138,7 @@ def build(profile_name, mod_jar): files.append({"path": mod_path(entry), "hashes": entry["hashes"], "downloads": [entry["url"]], "fileSize": entry["size"], "env": {"client": "required", "server": "unsupported"}}) index = {"formatVersion": 1, "game": "minecraft", "versionId": lock["pack_version"], - "name": "Horizon Lab — " + profile["title"], + "name": "Horizon — " + profile["title"], "summary": "Vanilla mechanics, pinned performance mods, measured frame and tick timings.", "files": files, "dependencies": {"minecraft": lock["minecraft"], "fabric-loader": lock["fabric_loader"]}} entries = {"modrinth.index.json": json.dumps(index, indent=2).encode()} @@ -161,7 +161,7 @@ def prepare_instance(profile_name, destination, mod_jar): target = destination / mod_path(entry) target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(source, target) - runtime.install_original_mod(mod_jar, destination / "mods", f"horizon-lab-{lock['pack_version']}.jar") + runtime.install_original_mod(mod_jar, destination / "mods", f"horizon-{lock['pack_version']}.jar") for name, data in overrides(profile_name, mod_jar.read_bytes()).items(): if name.startswith("mods/"): continue @@ -175,7 +175,7 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--profile", choices=PROFILES) parser.add_argument("--instance", type=Path, help="Local demo smoke-test directory (no normal account launch)") - parser.add_argument("--mod", type=Path, default=ROOT / "dist" / f"horizon-lab-{read_lock()['pack_version']}.jar") + parser.add_argument("--mod", type=Path, default=ROOT / "dist" / f"horizon-{read_lock()['pack_version']}.jar") args = parser.parse_args() if not args.mod.exists(): parser.error("Build the original mod first: python3 tools/build_mod.py") diff --git a/tools/build_release.py b/tools/build_release.py index 8fe11fe55..00ded705b 100644 --- a/tools/build_release.py +++ b/tools/build_release.py @@ -15,7 +15,7 @@ ROOT = build_pack.ROOT def main(): lock = build_pack.read_lock() version = lock["pack_version"] - mod = ROOT / "dist" / f"horizon-lab-{version}.jar" + mod = ROOT / "dist" / f"horizon-{version}.jar" if not mod.exists(): raise FileNotFoundError("Run tools/build_mod.py first") packs = [build_pack.build(profile, mod) for profile in build_pack.PROFILES] diff --git a/tools/check_public_tree.py b/tools/check_public_tree.py index 26c47f4e8..7ca8b6217 100644 --- a/tools/check_public_tree.py +++ b/tools/check_public_tree.py @@ -16,8 +16,8 @@ def prohibited(path): # Original JDK-only tools are an exact allowlist; recovered game Java stays private. if path in ORIGINAL_JDK_TOOLS: return False - # Original Horizon Lab mod sources may also be tracked. - if parsed.suffix == ".java" and path.startswith("mods/horizon-lab/src/"): + # Original Horizon mod sources may also be tracked. + if parsed.suffix == ".java" and path.startswith(("mods/horizon/src/", "mods/horizon-lab/src/")): return not ("/dev/horizonlab/" in path) return bool(parsed.parts and parsed.parts[0] in PRIVATE_ROOTS) or parsed.suffix.lower() in PRIVATE_EXTENSIONS diff --git a/tools/lab.py b/tools/lab.py index c6c189aca..77d2b8a87 100644 --- a/tools/lab.py +++ b/tools/lab.py @@ -40,7 +40,7 @@ def download(url, destination, checksum, algorithm="sha1"): try: with tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) as stream: temporary = Path(stream.name) - request = urllib.request.Request(url, headers={"User-Agent": "minecraft-optimization-lab/0.1"}) + request = urllib.request.Request(url, headers={"User-Agent": "horizon/0.1"}) with urllib.request.urlopen(request, timeout=120) as response: shutil.copyfileobj(response, stream) actual = digest(temporary, algorithm) diff --git a/tools/runtime.py b/tools/runtime.py index 60cc4b37d..1a40378c8 100644 --- a/tools/runtime.py +++ b/tools/runtime.py @@ -27,7 +27,9 @@ def install_original_mod(source, mod_dir, filename=None): """Replace our own previous versions, retaining backups outside Fabric's mod scan.""" mod_dir.mkdir(parents=True, exist_ok=True) filename = filename or source.name - for old in mod_dir.glob("horizon-lab-*.jar"): + # Retire both current and pre-rebrand filenames to avoid duplicate mod IDs. + candidates = sorted({*mod_dir.glob("horizon-*.jar"), *mod_dir.glob("horizon-lab-*.jar")}) + for old in candidates: if old.name == filename: continue with zipfile.ZipFile(old) as archive: diff --git a/tools/server.py b/tools/server.py index 4191bf75a..d9d2facc7 100644 --- a/tools/server.py +++ b/tools/server.py @@ -37,7 +37,7 @@ def prepare(instance, baseline=False): source = runtime.fetch(entry["url"], ROOT / ".local/pack-cache" / entry["filename"], entry["hashes"]["sha512"], "sha512") shutil.copyfile(source, mod_dir / entry["filename"]) - original = ROOT / "dist" / f"horizon-lab-{pack_lock['pack_version']}.jar" + original = ROOT / "dist" / f"horizon-{pack_lock['pack_version']}.jar" if not original.exists(): raise FileNotFoundError("Build the original mod first with tools/build_mod.py, or use the server starter ZIP") runtime.install_original_mod(original, mod_dir) diff --git a/tools/test_anchor_parity.py b/tools/test_anchor_parity.py new file mode 100644 index 000000000..fbff1d7e6 --- /dev/null +++ b/tools/test_anchor_parity.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Compare vertical anchor codecs, resolution and generation bounds with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + rng=random.Random(0x484f52495a4f4e414e43484f52) + names=["absolute","above_bottom","below_top","relative_to_sea_level"] + edges=[-2**31,-2033,-2032,-64,-1,0,1,63,2031,2032,2**31-1] + values=edges+[rng.randrange(-2**31,2**31) for _ in range(128)] + encodings=['null','false','0','"absolute"','[]','{}'] + numbers=[str(v) for v in edges]+['0.9','-0.9','1e3','-1e3','4294967296','4294967295','-4294967296','1e100','-1e100','1e-100','2147483648.9','-2147483649.9','null','true','"12"','[]','{}'] + for name in names: + for value in numbers:encodings.append('{"'+name+'":'+value+'}') + encodings += ['{"'+name+'":0,"unknown":true}','{"'+name+'":0,"'+name+'":1}','{"'+name+'":1,"'+name+'":null}'] + import itertools + for combination in itertools.product([None,0,2032,"bad"],repeat=4): + encodings.append(json.dumps({name:value for name,value in zip(names,combination) if value is not None},separators=(",",":"))) + contexts=[[-64,384,63],[0,256,32],[-2032,4064,0],[100,0,-100],[0,-1,0]] + contexts += [[x,y,z] for x,y,z in itertools.product([-2**31,0,2**31-1],repeat=3)] + contexts += [[rng.randrange(-2**31,2**31) for _ in range(3)] for _ in range(64)] + for i,context in enumerate(contexts): + for generator in [None,contexts[(i+7)%len(contexts)]]: + fixture={"context":context,"values":values,"json":encodings} + if generator is not None:fixture["generator"]=generator + yield fixture + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-anchor-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java" + sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/anchor_fixture.rs"] + tested_sources=base.source_hashes(sources) + fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") + run(["cargo","build","--release","-p","horizon-world","--example","anchor_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("anchor_fixture.exe" if os.name=="nt" else "anchor_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaAnchorOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} anchor output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"codec_inputs":sum(len(f["json"]) for f in fixtures),"runtime_anchors":sum(3+4*len(f["values"]) for f in fixtures), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual VerticalAnchor.CODEC parsing and encoding, all four anchor kinds, constant helpers, runtime integer overflow and unrestricted constructor values. WorldGenerationContext.of uses a LevelAccessor proxy with verified method calls; the generator constructor uses a native NoiseBasedChunkGenerator with supplied minimum, height and sea level. Strict JSON transport covers range limits, numeric truncation/wrapping, null/wrong field types, duplicate fields and nested exclusive alternatives. Level access outside the three queried values, JSON syntax diagnostics and complete material conditions remain pending."} + lab.write_json(report_path,report);print(f"Scoped anchor parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_basic_feature_parity.py b/tools/test_basic_feature_parity.py new file mode 100644 index 000000000..001397965 --- /dev/null +++ b/tools/test_basic_feature_parity.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Compare basic feature algorithms and ordered world mutations with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + encode=lambda value:json.dumps(value,separators=(',',':')) + origins=[[cx*16,64,cz*16] for cx in [-1,0,1] for cz in [-1,0,1]]+[[8,64,8],[-32,0,0],[32,0,0],[2147483647,-2147483648,2147483647],[-2147483648,2147483647,-2147483648]] + for legacy in [False,True]: + for seed in [0,-1,0x123456789abcdef]: + for kind in ['void_start_platform','end_island','end_platform']: + for origin in origins: + for reject in [0,3]: + for fail in [-1,0,7,63]: + yield {'definition':encode({'type':kind}),'origin':origin,'legacy':legacy,'seed':seed,'reject':reject,'fail':fail,'repeats':2} + chains=[[], + [{'type':'count','count':2}], + [{'type':'count','count':2},{'type':'in_square'}], + [{'type':'in_square'},{'type':'count','count':2}], + [{'type':'count','count':{'type':'uniform','min_inclusive':0,'max_inclusive':3}}, + {'type':'offset','x':{'type':'uniform','min_inclusive':-2,'max_inclusive':2},'y':1,'z':-1}], + [{'type':'count','count':2},{'type':'height_range','height':{'type':'uniform','min_inclusive':{'above_bottom':0},'max_inclusive':{'below_top':0}}}], + [{'type':'random_chance','chance':0.5},{'type':'count','count':2}], + [{'type':'count','count':2},{'type':'random_chance','chance':0.5}], + [{'type':'cuboid','xz_size':1,'y_size':1},{'type':'random_chance','chance':0.5}], + [{'type':'fixed_placement','positions':[[0,64,0],[0,64,0],[1,64,1]]}], + [{'type':'noise_threshold_count','noise_level':0,'below_noise':1,'above_noise':2},{'type':'in_square'}]] + for legacy in [False,True]: + for seed in [0,-1,0x123456789abcdef]: + for kind in ['void_start_platform','end_island','end_platform']: + for chain in chains: + for fail in [-1,0,7,63]: + for reject in [0,3]: + yield {'definition':encode({'type':kind}),'placement':chain,'origin':[0,64,0], + 'legacy':legacy,'seed':seed,'reject':reject,'fail':fail,'repeats':2} + for definition in [None,False,0,[],{}, {'type':'missing'}, {'type':':end_island'}, {'type':'minecraft:end_platform','ignored':0}]: + yield {'definition':encode(definition),'origin':[0,64,0],'legacy':False,'seed':0,'reject':0,'fail':7,'repeats':1} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-basic-feature-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBasicFeatureOracle.java" + helper=oracle.with_name("VanillaPlacementOracle.java") + sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/basic_feature_fixture.rs"] + tested_sources=base.source_hashes(sources) + fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") + for side,jar in jars.items(): + path=build/f"facts-{side}.json" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaBasicFeatureOracle","export",path],side+"-export") + fixture_paths.append(path) + if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") + tested_fixtures=base.source_hashes(fixture_paths) + run(["cargo","build","--release","-p","horizon-world","--example","basic_feature_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("basic_feature_fixture.exe" if os.name=="nt" else "basic_feature_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaBasicFeatureOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} basic-feature output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"basic_features":3,"block_states":5,"composed_fixtures":sum("placement" in f for f in fixtures),"requested_placements":sum(f["repeats"] for f in fixtures), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual Feature.DIRECT_CODEC and native void-start-platform, End-island and End-platform feature algorithms. A mutable WorldGenLevel proxy logs ordered block reads, writes, update flags, rejected writes, thrown failures and accumulated stored states after repeated placements. Native LevelWriter.setBlockAndUpdate executes through its actual default method. Required default block-state IDs are independently exported and checked across both authenticated JARs. Direct calls and native FeaturePlacer modifier chains share the mutable world and random stream, including reused placer buffers after failures. Both random modes, multiple seeds, nearby/far chunks and extreme wrapped coordinates are compared, with nextLong values after every placement and at fixture end. The End-platform feature invokes its ordinary generation path without block destruction/drops. Actual chunk mutation, neighbor updates, lighting, entity/block drops, full feature registry behavior and complete generated worlds remain outside this comparison."} + + lab.write_json(report_path,report);print(f"Scoped basic-feature parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_biome_chunk_parity.py b/tools/test_biome_chunk_parity.py new file mode 100644 index 000000000..9dc484b54 --- /dev/null +++ b/tools/test_biome_chunk_parity.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Compare quart-biome chunk storage and section-atomic filling with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + rng=random.Random(0x484f52495a4f4e42494f4348) + for minimum,height in [(-64,384),(0,128),(-2032,4064),(2000,32),(-16,16)]: + for cx,cz in [(0,0),(-1,2),(1875000,-1875000),(-2**31,2**31-1)]: + maximum=minimum+height-1 + queries=[[x,y,z] for x,y,z in [(cx*4,minimum//4,cz*4),(cx*4+3,maximum//4,cz*4+3),(-2**31,-2**31,2**31-1),(2**31-1,2**31-1,-2**31)]] + queries=[[((v+2**31)%2**32)-2**31 for v in q] for q in queries] + queries += [[rng.randrange(-2**31,2**31) for _ in range(3)] for _ in range(128)] + ops=[[0,1,-1,minimum,maximum],[17,67,-1,minimum,maximum],[97,129,0,minimum,maximum],[5,2,63,minimum,maximum],[9,8,64,minimum,maximum],[123,512,65,minimum,maximum],[17,3,-1,minimum+1,maximum-1],[-2**31,67,-1,minimum,maximum]] + yield {'cx':cx,'cz':cz,'min':minimum,'height':height,'default':rng.randrange(512),'ops':ops,'queries':queries} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-biome-chunk-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeChunkOracle.java" + sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_chunk_fixture.rs"] + tested_sources=base.source_hashes(sources) + fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") + run(["cargo","build","--release","-p","horizon-world","--example","biome_chunk_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("biome_chunk_fixture.exe" if os.name=="nt" else "biome_chunk_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaBiomeChunkOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} biome-chunk output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"fills":sum(len(f["ops"]) for f in fixtures),"block_queries":sum(len(f["ops"])*len(f["queries"]) for f in fixtures), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual ChunkAccess.fillBiomesFromNoise, LevelChunkSection.fillBiomesFromNoise and chunk/section biome reads using synthetic registered holder identities. Ordered resolver queries, section contents and clamped/wrapped chunk lookups are compared after repeated fills and failures at section boundaries. Covers full supported aligned vertical bounds, generation bounds cutting through sections, negative/extreme chunk coordinates and 1..512 possible biome identities. Completed earlier sections survive failure while the failing section retains its previous values. This compares stored biome values, not native in-memory palette layout, wire encoding, biome-source generation, blending, retrogen or complete generated worlds."} + + lab.write_json(report_path,report);print(f"Scoped biome-chunk parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_biome_generation_parity.py b/tools/test_biome_generation_parity.py new file mode 100644 index 000000000..e0be3acb9 --- /dev/null +++ b/tools/test_biome_generation_parity.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Compare chunk generation for all four biome-source kinds with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base,test_worldgen_parity as worldgen +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + + +def corpus(bundle): + for setting,raw in sorted(bundle['settings'].items()): + value=json.loads(raw);minimum=value['noise']['min_y'];height=value['noise']['height'] + for preset in sorted(bundle['presets']): + for legacy in [False,True]: + for seed,cx,cz in [(0,0,0),(-1,-2,3),(0x123456789abcdef,1875000,-1875000)]: + queries=[[cx*16+x,y,cz*16+z] for x in [-1,0,2,7,15,16] for z in [-1,0,2,7,15,16] for y in [minimum-20,minimum,minimum+17,minimum+height-1,minimum+height+20]] + yield {'setting':setting,'preset':preset,'seed':seed,'legacy':legacy,'cx':cx,'cz':cz,'min':minimum,'height':height,'write_min':minimum+(17 if seed==-1 else 0),'write_max':minimum+height-1-(17 if seed==-1 else 0),'queries':queries,'repeats':2 if seed==0 else 1} + + + for source in ['fixed','checkerboard','end']: + for legacy in [False,True]: + for seed,cx,cz,scale in [(0,0,0,2),(-1,65,0,0),(2,-65,1,30),(-2**63,1875000,-1875000,62)]: + queries=[[cx*16+x,y,cz*16+z] for x in [-1,0,7,15,16] for z in [-1,0,7,15,16] for y in [minimum-1,minimum+17,minimum+height]] + yield {'setting':setting,'preset':'minecraft:overworld','source':source,'scale':scale,'seed':seed,'legacy':legacy,'cx':cx,'cz':cz,'min':minimum,'height':height,'write_min':minimum,'write_max':minimum+height-1,'queries':queries,'repeats':2 if seed==0 else 1} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-biome-generation-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeGenerationOracle.java" + exporter=oracle.with_name("VanillaBiomeExport.java") + sources=[oracle,exporter,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_generation_fixture.rs"] + tested_sources=base.source_hashes(sources) + classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,exporter],"compile-java") + bundle={} + for field,kind in [('noises','noise'),('densities','density_function'),('settings','noise_settings')]: + resources=worldgen.registry_resources(jars['server'],kind) + if not resources or resources!=worldgen.registry_resources(jars['client'],kind):raise ValueError('reference '+kind+' resources differ') + prefix='data/minecraft/worldgen/'+kind+'/' + bundle[field]={'minecraft:'+name[len(prefix):-5]:raw for name,raw in resources.items()} + exports=[] + for side,jar in jars.items(): + path=build/f'presets-{side}.json';exports.append(path) + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaBiomeExport',path],side+'-export') + presets=json.loads(path.read_text()) + if not presets or ('presets' in bundle and presets!=bundle['presets']):raise ValueError('reference biome preset tables differ') + bundle['presets']=presets + registries=build/'registries.json';registries.write_text(json.dumps(bundle,separators=(',',':')),encoding='utf-8') + fixtures=list(corpus(bundle));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') + fixture_paths=[inputs,registries,*exports];tested_fixtures=base.source_hashes(fixture_paths) + run(["cargo","build","--release","-p","horizon-world","--example","biome_generation_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("biome_generation_fixture.exe" if os.name=="nt" else "biome_generation_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaBiomeGenerationOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} biome-generation output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"fills":sum(f["repeats"] for f in fixtures),"biome_values":sum(f["repeats"]*f["height"]*4 for f in fixtures),"block_queries":sum(f["repeats"]*len(f["queries"]) for f in fixtures),"preset_entries":{name:len(json.loads(raw)) for name,raw in bundle["presets"].items()},"source_fixtures":{name:sum(f.get("source","multi")==name for f in fixtures) for name in ["multi","fixed","checkerboard","end"]}, + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual ChunkGenerator.doCreateBiomes through NoiseBasedChunkGenerator with empty Blender and no retrogen. Both bundled Overworld/Nether multi-noise preset tables are independently exported from authenticated JARs; Rust imports quantized tables and compiles climate routers itself. All seven bundled routers, both random modes, multiple seeds and distant positive/negative chunks are tested. Complete section biome values and subsequent BiomeManager block lookups are compared, including repeated generation with fresh density contexts and persistent previous-leaf search state, and generation bounds excluding top/bottom sections. Holders are identity placeholders; no biome properties are evaluated. Fixed, checkerboard and End source fixtures also run actual chunk generation through every bundled router, including real seeded End erosion, the central-island shortcut, distant coordinates and wrapped checkerboard shifts. Preset builders, complete biome-source codecs, blending, retrogen, terrain-stage linkage and complete generated worlds remain pending."} + + lab.write_json(report_path,report);print(f"Scoped biome-generation parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_biome_placement_parity.py b/tools/test_biome_placement_parity.py new file mode 100644 index 000000000..b32a0297b --- /dev/null +++ b/tools/test_biome_placement_parity.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Compare biome placement filtering, root context, nested placers and partial failures.""" +import argparse +import itertools +import json +import os +from pathlib import Path +import platform +import random +import subprocess +import zipfile +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + biome={'type':'biome'} + chains=[[biome],[{'type':'count','count':3},{'type':'in_square'},biome],[biome,{'type':'count','count':2},{'type':'offset','x':1,'y':0,'z':0},biome],[{'type':'random_chance','chance':0.5},biome,{'type':'count','count':2}],[{'type':'count','count':2},biome,{'type':'offset','x':1,'y':0,'z':0},biome]] + for legacy in [False,True]: + for worldgen in [False,True]: + for top in [False,True]: + for membership in [[0,0],[1,0],[0,1],[1,1],[2,3],[3,2]]: + for placement in chains: + for query_fail,feature_fail in [(-1,-1),(0,-1),(1,-1),(3,-1),(-1,0),(-1,2)]: + for nested in [False,True]: + for return_mode in [0,1,2]: + yield {'legacy':legacy,'worldgen':worldgen,'seed':-1 if nested else 0,'top':top,'direct':False,'membership':membership,'placement':placement,'query_fail':query_fail,'feature_fail':feature_fail,'nested':nested,'draw':return_mode!=1,'return_mode':return_mode,'origin':[15,-64,15]} + for legacy in [False,True]: + for top in [False,True]: + for membership in itertools.product(range(4),repeat=2): + for query_fail in [-1,0,1,2]: + for origin in [[0,0,0],[2147483647,-2147483648,2147483647]]: + yield {'legacy':legacy,'worldgen':False,'seed':0,'top':top,'direct':True,'membership':list(membership),'placement':[biome],'query_fail':query_fail,'feature_fail':-1,'nested':False,'draw':True,'return_mode':0,'origin':origin} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--prepare',action='store_true');args=parser.parse_args() + build=lab.LOCAL/'rust-biome-placement-parity';build.mkdir(parents=True,exist_ok=True) + report_path=build/'report.json';report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomePlacementOracle.java' + helper=oracle.with_name("VanillaPlacementOracle.java") + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/biome_placement_fixture.rs'] + tested_sources=base.source_hashes(sources) + fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') + fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) + classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,helper],'compile-java') + run(['cargo','build','--release','-p','horizon-world','--example','biome_placement_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) + binary=Path(metadata['target_directory'])/'release/examples'/('biome_placement_fixture.exe' if os.name=='nt' else 'biome_placement_fixture') + run([binary,build],'rust');references=[] + for side,jar in jars.items(): + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaBiomePlacementOracle',side,build],side) + reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') + references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) + print(f'{side}: {matched:,} biome-placement output lines match Rust',flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={'schema':1,'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'fixtures':len(fixtures),'random_modes':2,'requested_placements':len(fixtures)*3,'sources_sha256':tested_sources,'fixtures_sha256':tested_fixtures,'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references,'scope':'Actual BiomeFilter.modify and FeaturePlacer.place/placeWithBiomeCheck with native biome generation settings. Missing top features fail before biome lookup. Direct, absent, structurally equal and different placed-feature membership, query order, callback random draws/results/errors, dirty buffers across repeats and nested plain placers are compared. Direct and WorldgenRandom-wrapped legacy/xoroshiro streams execute modifier chains. Rust delegates biome resolution and generation-settings membership to the caller while isolating each placer invocation context. Full biome sampling/registry equality, complete decoration, crash-report text and gameplay remain pending.'} + lab.write_json(report_path,report);print(f'Scoped biome-placement parity passed: {report_path}') + + +if __name__=='__main__':main() diff --git a/tools/test_biome_source_codec_parity.py b/tools/test_biome_source_codec_parity.py new file mode 100644 index 000000000..58989d884 --- /dev/null +++ b/tools/test_biome_source_codec_parity.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +"""Compare registry-bound biome-source codecs and decoded runtime behavior.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base,test_worldgen_parity as worldgen,test_biome_temperature_parity as temperature,test_material_condition_parity as material +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + import test_biome_temperature_parity as temperature + import test_material_condition_parity as material + + +def corpus(bundle): + encode=lambda value:json.dumps(value,separators=(',',':')) + for value in [None,False,0,'fixed',[],{}, {'type':'missing'}, {'type':None}]:yield encode(value) + for name in sorted(bundle['biomes']): + yield encode({'type':'fixed','biome':name}) + yield encode({'type':'checkerboard','biomes':name}) + for name in sorted(bundle['biome_tags']):yield encode({'type':'checkerboard','biomes':'#'+name,'scale':3}) + for value in [None,False,0,[],{},'',':','missing','Minecraft:plains','#is_overworld',['plains'],['plains','desert','plains'],['#is_overworld']]: + yield encode({'type':'fixed','biome':value}) + yield encode({'type':'checkerboard','biomes':value}) + for token in ['null','false','"2"','{}','[]','-1','0','1','2','30','31','32','62','63','-0.0','2.9','-0.9','4294967296','4294967298','2147483648','-4294967296','1e100','-1e100','1e-100']: + yield '{"type":"checkerboard","biomes":["plains","desert"],"scale":'+token+'}' + yield '{"type":"checkerboard","biomes":"plains","scale":-1,"scale":2}' + yield '{"type":":fixed","biome":":plains","ignored":true}' + yield '{"type":"fixed","biome":"missing","biome":"plains"}' + for value in [{},{'biome':'missing'},{'preset':None}]:yield encode({'type':'the_end',**value}) + point={name:0 for name in ['temperature','humidity','continentalness','erosion','depth','weirdness','offset']} + good={'parameters':point,'biome':'plains'} + for preset in [None,False,0,[],{},'overworld','nether',':overworld','missing',{'preset':'overworld'},{'preset':'nether'},{'preset':'missing'},{'preset':None}]: + yield encode({'type':'multi_noise','preset':preset}) + yield encode({'type':'multi_noise','biomes':[good],'preset':preset}) + yield encode({'type':'multi_noise','biomes':[],'preset':preset}) + yield encode({'type':'multi_noise','biomes':[{'biome':'missing','parameters':point}],'preset':preset}) + for entries in [[],[good],[good,good],[good,{'parameters':point,'biome':'desert'}],[{}],[{'parameters':point}],[{'biome':'plains'}],None,'plains',0]:yield encode({'type':'multi_noise','biomes':entries}) + for field in point: + for value in [None,False,'0',[],{},[-1,1],{'min':-1,'max':1},[1,-1],[-0.0,0.0],[0.0,-0.0],-2,-2.0001,2,2.0001,-0.0,0.00009999,0.123456789,1e100]: + changed={**point,field:value} + yield encode({'type':'multi_noise','biomes':[{'parameters':changed,'biome':'plains'}]}) + for name in point: + changed={key:value for key,value in point.items() if key!=name} + yield encode({'type':'multi_noise','biomes':[{'parameters':changed,'biome':'plains'}]}) + yield encode({'type':'multi_noise','biomes':[{'parameters':{**point,'temperature':[-0.1111,0.2222],'offset':0.012345},'biome':'desert'}]}) + + + # Cover every quantized climate value in [-2,2], including interval encoding + # and every nonnegative offset increment. Input floats are parsed by each codec. + for step in range(-20000,20001): + changed={**point,'temperature':step/10000,'humidity':[-2,step/10000],'offset':abs(step)%10001/10000} + yield encode({'type':'multi_noise','biomes':[{'parameters':changed,'biome':'plains'}]}) + + +def positions(): + return [[0,0,0],[256,0,0],[260,-1,0],[-257,8,1],[7500000,79,-7500000],[-2**31,2**31-1,-1],[2**31-1,-2**31,17]] + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-biome-source-codec-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceCodecOracle.java" + exporter=oracle.with_name("VanillaBiomeExport.java") + helpers=[oracle.with_name(name+".java") for name in ["VanillaMaterialConditionOracle","VanillaAnchorOracle","VanillaBiomeTemperatureOracle"]] + sources=[oracle,exporter,*helpers,lab.ROOT/"tools/test_biome_temperature_parity.py",lab.ROOT/"tools/test_material_condition_parity.py",Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_source_codec_fixture.rs"] + tested_sources=base.source_hashes(sources) + classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,exporter,*helpers],"compile-java") + bundle={} + for field,getter in [('biomes',temperature.biome_resources),('biome_tags',material.biome_tag_resources)]: + bundle[field]=getter(jars['server']) + if not bundle[field] or bundle[field]!=getter(jars['client']):raise ValueError('reference '+field+' resources differ') + (build/(field+'.json')).write_text(json.dumps(bundle[field],separators=(',',':')),encoding='utf-8') + exports=[] + for side,jar in jars.items(): + path=build/f'presets-{side}.json';exports.append(path) + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaBiomeExport',path],side+'-export') + presets=json.loads(path.read_text()) + if not presets or ('presets' in bundle and presets!=bundle['presets']):raise ValueError('reference biome preset tables differ') + bundle['presets']=presets + (build/'presets.json').write_text(json.dumps(bundle['presets'],separators=(',',':')),encoding='utf-8') + fixtures=list(corpus(bundle));inputs=build/'inputs.txt';inputs.write_text('\n'.join(fixtures)+'\n',encoding='utf-8') + (build/'positions.json').write_text(json.dumps(positions(),separators=(',',':')),encoding='utf-8') + fixture_paths=[inputs,*exports,build/'positions.json',*[build/(name+'.json') for name in bundle]];tested_fixtures=base.source_hashes(fixture_paths) + run(["cargo","build","--release","-p","horizon-world","--example","biome_source_codec_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("biome_source_codec_fixture.exe" if os.name=="nt" else "biome_source_codec_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaBiomeSourceCodecOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} biome-source codec output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"query_positions":len(positions()),"climate_grid_cases":40001,"biomes":len(bundle['biomes']),"biome_tags":len(bundle['biome_tags']), + + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual BiomeSource.CODEC parsing and encoding for fixed, checkerboard, End and multi-noise sources bound to pinned biome/tag registries and preset holders. Named biome holders, direct/tag holder sets, canonical identifiers, scale defaults/bounds/numeric narrowing, inline climate parameter lists, named/inline preset holders, inline-list preference/fallback, malformed fields and duplicate keys are compared. Canonical serialized JSON is compared as sorted structures with numeric double-bit values; possible-biome sets are sorted and compared, followed by source queries against zero climate/erosion. Rust imports independently authenticated preset tables. Full inline biome definitions, live registry ownership/reloads and complete source/world generation remain outside this scoped codec comparison."} + + lab.write_json(report_path,report);print(f"Scoped biome-source codec parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_biome_source_parity.py b/tools/test_biome_source_parity.py new file mode 100644 index 000000000..093c92427 --- /dev/null +++ b/tools/test_biome_source_parity.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""Compare fixed, checkerboard and End biome sources with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + rng=random.Random(0x484f52495a4f4e534f55524345) + edges=[-2**31,-2**31+1,-536870913,-536870912,-260,-257,-256,-255,-4,-1,0,1,4,255,256,257,260,536870911,536870912,2**31-1] + positions=[[x,y,z] for x in edges for z in edges for y in [-2**31,-1,0,79,2**31-1]] + positions += [[rng.randrange(-2**31,2**31) for _ in range(3)] for _ in range(512)] + yield {'kind':'fixed','positions':positions} + for scale in [-2**31,-65,-34,-33,-32,-3,-2,-1,*range(63),63,64,65,2**31-1]: + for biomes in [[],[0],[3,1,3,2],list(range(67)),list(range(512))]:yield {'kind':'checkerboard','scale':scale,'biomes':biomes,'positions':positions} + bits=['00000000','80000000','3e800000','3e7fffff','3e800001','bd800000','bd800001','bd7fffff','be600000','be600001','be5fffff','7f800000','ff800000','7fc00000','7f800001','ffc00000'] + bits += [f'{rng.getrandbits(32):08x}' for _ in range(64)] + for value in bits:yield {'kind':'end','bits':value,'fail':False,'positions':positions} + yield {'kind':'end','bits':'00000000','fail':True,'positions':positions} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-biome-source-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceOracle.java" + sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_source_fixture.rs"] + tested_sources=base.source_hashes(sources) + fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") + run(["cargo","build","--release","-p","horizon-world","--example","biome_source_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("biome_source_fixture.exe" if os.name=="nt" else "biome_source_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaBiomeSourceOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} biome-source output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"queries":sum(len(f["positions"]) for f in fixtures),"sources":{name:sum(f["kind"]==name for f in fixtures) for name in ["fixed","checkerboard","end"]}, + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual FixedBiomeSource, CheckerboardColumnBiomeSource and TheEndBiomeSource runtime queries using synthetic holder identities. Fixed results, checkerboard empty/duplicate/large lists, all codec-valid scales plus unrestricted runtime scales, Java masked shifts and wrapping sums are compared. End central-circle shortcuts, erosion sampler coordinates, exact threshold boundaries, nonfinite float samples, sampler failures and integer coordinate wrapping are compared through actual Climate.Sampler bindings. End density inputs in this suite are supplied constants; real seeded End density, biome-source codecs, registry/preset loading, possible-biome metadata and generated-world integration remain separate work."} + + lab.write_json(report_path,report);print(f"Scoped biome-source parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_biome_temperature_parity.py b/tools/test_biome_temperature_parity.py new file mode 100644 index 000000000..1edec516e --- /dev/null +++ b/tools/test_biome_temperature_parity.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Compare biome temperature sampling, precipitation and cache behavior with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +import zipfile +try: + from . import lab,test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + rng=random.Random(0x484f52495a4f4e54454d50) + bases=[0,0x80000000,1,0x80000001,0x3dcccccc,0x3dcccccd,0x3dccccce,0x3e199999,0x3e19999a,0x3e19999b,0x3e4ccccd,0x3f000000,0x3f800000,0xbf800000,0x7f7fffff,0xff7fffff,0x7f800000,0xff800000,0x7fc00000,0xffc00001] + bases += [rng.getrandbits(32) for _ in range(28)] + edges=[-2**31,-33554433,-33554432,-16777217,-16777216,-4097,-4096,-64,-1,0,1,63,64,79,80,81,4095,4096,16777216,16777217,33554431,33554432,2**31-1] + wrap=lambda value:(value+2**31)%2**32-2**31 + points=[[0,y,0,63] for y in [-64,0,63,79,80,81,82,319,4096]] + points += [[rng.choice(edges),rng.choice(edges),rng.choice(edges),rng.choice(edges)] for _ in range(96)] + points += [[rng.randrange(-30000000,30000001),rng.randrange(-64,321),rng.randrange(-30000000,30000001),63] for _ in range(96)] + # Reuse packed keys while varying the source coordinates and sea level. + for x,y,z,sea in list(points[:32]): + points += [[x,y,z,wrap(sea+500)],[wrap(x+2**26),wrap(y+4096),wrap(z-2**26),sea]] + for base in bases: + for modifier in ['NONE','FROZEN']: + for precipitation in [False,True]: + ops=[['query',*p] for p in points] + ops += [['fill',1100,-10000,63],['dump'],['query',-8901,1099&255,1099*31,-64],['query',-10000,0,0,63],['dump']] + yield {'base':f'{base:x}','modifier':modifier,'precipitation':precipitation,'ops':ops} + for base in [0x3e4ccccd,0x7fc00000,0xffc00001]: + for modifier in ['NONE','FROZEN']: + for first in [0,1023]: + ops=[['fill',1024,0,63],['dump'],['query',first,first&255,first*31,-64],['dump'],['fill',1,5000,63],['dump']] + child=[['dump'],['query',first,first&255,first*31,-1000],['query',0,4096,0,0],['dump']] + ops += [['thread',child],['dump'],['query',first,first&255,first*31,-64],['dump']] + yield {'base':f'{base:x}','modifier':modifier,'precipitation':True,'ops':ops} + + +def biome_resources(jar): + prefix='data/minecraft/worldgen/biome/' + with zipfile.ZipFile(jar) as archive: + return {'minecraft:'+name[len(prefix):-5]:archive.read(name).decode('utf-8') for name in sorted(archive.namelist()) if name.startswith(prefix) and name.endswith('.json')} + + +def codec_corpus(biomes): + cases=list(biomes.values())+['null','false','0','[]','{}'] + template={'has_precipitation':True,'temperature':0.5,'downfall':0.5,'temperature_modifier':'none'} + tokens=['null','true','false','0','-0.0','0.1','0.15','0.2','1','-1','1.000000059604644775390625','1.000000059604644775390626','1e40','-1e40','1e1000','-1e1000','1e-1000','"none"','"frozen"','"NONE"','"minecraft:none"','"NaN"','"Infinity"','"0.1"','[]','{}'] + for key in template: + cases.append(json.dumps({k:v for k,v in template.items() if k!=key})) + for token in tokens: + cases.append('{'+','.join(json.dumps(k)+':'+(token if k==key else json.dumps(v)) for k,v in template.items())+'}') + cases += [json.dumps(dict(template,unknown={'anything':True})), + '{"has_precipitation":true,"temperature":0.2,"temperature":-0.0,"downfall":0.0}', + '{"has_precipitation":true,"temperature":0.2,"temperature":null,"downfall":0.0}'] + operations=[['query',0,y,0,63] for y in [-64,0,63,79,80,81,319]]+[['query',12345,100,-9876,63],['query',12345,100,-9876,-1000],['dump']] + for value in cases:yield {'json':value,'ops':operations} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-biome-temperature-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + biomes=biome_resources(jars['server']) + if not biomes or biomes!=biome_resources(jars['client']):raise ValueError('client/server biome resources differ') + (build/'biomes.json').write_text(json.dumps(biomes,separators=(',',':')),encoding='utf-8') + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java" + sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_temperature_fixture.rs"] + tested_sources=base.source_hashes(sources) + fixtures=[*corpus(),*codec_corpus(biomes)];inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + fixture_paths=[inputs,build/"biomes.json"];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") + run(["cargo","build","--release","-p","horizon-world","--example","biome_temperature_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("biome_temperature_fixture.exe" if os.name=="nt" else "biome_temperature_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaBiomeTemperatureOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} biome-temperature output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"biome_resources":len(biomes),"codec_inputs":sum("json" in f for f in fixtures),"operations":sum(len(f["ops"]) for f in fixtures),"thread_isolation_fixtures":sum(any(op[0]=="thread" for op in f["ops"]) for f in fixtures), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual Biome temperature methods, warm/cold/iceberg-melt predicates and precipitation selection, with both temperature modifiers and arbitrary base float bits. Native private climate/biome constructors provide explicit temperature inputs; unrelated biome fields are null and never queried. Fixed seeded simplex/stack sources, float/double conversion and arithmetic order, height adjustment and sea-level overflow, packed-position aliases, repeated queries with changed sea levels, cache capacity/order/content, NaN recomputation and eviction, and actual native thread-local isolation versus independently owned Rust workers. ClimateSettings map-codec parsing additionally covers all independently authenticated bundled biome definitions, direct float conversion, nonfinite overflow, modifier defaults/null handling, field types, duplicates and missing fields. Full biome data codecs, climate encoding, complete weather placement/freezing, material condition integration and automatic migration of shared biome instances between threads remain outside this scope."} + lab.write_json(report_path,report);print(f"Scoped biome-temperature parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_biome_zoom_parity.py b/tools/test_biome_zoom_parity.py new file mode 100644 index 000000000..4dc5cea0c --- /dev/null +++ b/tools/test_biome_zoom_parity.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Compare biome zoom, quart lookup and seed obfuscation with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + rng=random.Random(0x484f52495a4f4e42494f4d45) + seeds=[-2**63,-2**63+1,-987654321,-1,0,1,987654321,2**63-1] + for seed in seeds+[rng.randrange(-2**63,2**63) for _ in range(4096)]: + yield f's {seed}' + edges=[-2**31,-2**31+1,-2**31+2,-30000000,-17,-16,-5,-4,-3,-2,-1,0,1,2,3,4,5,15,16,17,30000000,2**31-2,2**31-1] + import itertools + for seed in seeds: + for x,y,z in itertools.product(edges,repeat=3):yield f'b {seed} {x} {y} {z}' + for x,y,z in itertools.product(range(-8,9),repeat=3):yield f'b {seed} {x} {y} {z}' + for _ in range(32768): + seed=rng.randrange(-2**63,2**63);x,y,z=[rng.randrange(-2**31,2**31) for _ in range(3)] + yield f'b {seed} {x} {y} {z}' + import struct + float_values=[float(v) for v in edges]+[-0.,0.1,-0.1,3.9999999999999996,-4.000000000000001,1e100,-1e100,float('inf'),-float('inf'),float('nan')] + bits=[struct.pack('>d',v).hex() for v in float_values]+['0000000000000001','8000000000000001','7ff0000000000001','fff8000000000000'] + for a,b,c in itertools.product(bits,repeat=3):yield f'p {a} {b} {c}' + for _ in range(32768):yield 'p '+' '.join(f'{rng.getrandbits(64):016x}' for _ in range(3)) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-biome-zoom-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeZoomOracle.java" + sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-core/examples/biome_zoom_fixture.rs"] + tested_sources=base.source_hashes(sources) + fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("\n".join(fixtures)+"\n",encoding="utf-8") + fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") + run(["cargo","build","--release","-p","horizon-core","--example","biome_zoom_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("biome_zoom_fixture.exe" if os.name=="nt" else "biome_zoom_fixture") + run([binary,build],"rust") + import hashlib + with (build/"rust.txt").open() as output: + for fixture in fixtures: + result=output.readline().strip() + if fixture.startswith('s '): + seed=int(fixture[2:]);digest=hashlib.sha256(seed.to_bytes(8,'little',signed=True)).digest() + if result!='s '+str(int.from_bytes(digest[:8],'little',signed=True)):raise AssertionError('seed SHA-256 disagrees with hashlib') + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaBiomeZoomOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} biome-zoom output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"seed_hashes":sum(f.startswith("s ") for f in fixtures),"block_queries":sum(f.startswith("b ") for f in fixtures),"position_queries":sum(f.startswith("p ") for f in fixtures), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual BiomeManager seed obfuscation, block-position eight-corner jitter selection, direct block/double-to-quart queries, and source replacement preserving the zoom seed. Captured resolver coordinates are compared, including dense local grids, signed coordinate overflow, negative boundaries, distant blocks, long-seed boundaries, random seeds/positions, double infinities/NaNs/subnormals and saturating conversion. SHA-256 seed transforms are also compared against Python hashlib independently. Biome storage/source generation, blending, chunk integration and gameplay remain separate work."} + + lab.write_json(report_path,report);print(f"Scoped biome-zoom parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_block_properties_parity.py b/tools/test_block_properties_parity.py new file mode 100644 index 000000000..4b284f345 --- /dev/null +++ b/tools/test_block_properties_parity.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Compare block-definition flags and calculated solidity with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import subprocess +import random +import struct +import math +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + def box(values):return [struct.pack('>d',float(v)).hex() for v in values] + shapes=[[],[[0,0,0,1,1,1]],[[0,0,0,0.1,1,0.1]],[[0,0,0,1,0.1,1]],[[0,0,0,0.01,0.01,0.01],[0.99,0.99,0.99,1,1,1]]] + threshold=0.7291666666666666 + for x in [0.0,0.125,0.5,threshold,1.0,2.0]: + for y in [0.0,1e-8,0.125,0.5,math.nextafter(1.0,0.0),1.0,math.nextafter(1.0,2.0)]: + z=3*threshold-x-y + for extent in [math.nextafter(z,-math.inf),z,math.nextafter(z,math.inf)]:shapes.append([[0,0,0,x,y,extent]]) + rng=random.Random(0x534f4c4944) + for _ in range(1000): + shape=[] + for _ in range(rng.randrange(1,5)): + low=[rng.uniform(-1,1) for _ in range(3)];high=[v+rng.choice([1e-8,1e-7,0.125,0.5,1.0,2.0]) for v in low];shape.append([*low,*high]) + shapes.append(shape) + for shape in shapes: + for on in [False,True]: + for off in [False,True]: + for cached in [False,True]: + for occludes in [False,True]:yield {'shape':[box(v) for v in shape],'on':on,'off':off,'cached':cached,'occludes':occludes} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--prepare',action='store_true');args=parser.parse_args() + build=lab.LOCAL/'rust-block-properties-parity';build.mkdir(parents=True,exist_ok=True) + report_path=build/'report.json';report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPropertiesOracle.java' + helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java' + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_properties_fixture.rs'] + tested_sources=base.source_hashes(sources) + classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,helper],'compile-java') + def java(side,mode,path): + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockPropertiesOracle',mode,path],side+'-'+mode) + java('server','export',build) + fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') + fixture_paths=[inputs,build/'block-registry.nbt',build/'cached-collision.nbt',build/'block-properties.nbt'];tested_fixtures=base.source_hashes(fixture_paths) + run(['cargo','build','--release','-p','horizon-world','--example','block_properties_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) + binary=Path(metadata['target_directory'])/'release/examples'/('block_properties_fixture.exe' if os.name=='nt' else 'block_properties_fixture') + run([binary,build],'rust');references=[] + for side,jar in jars.items(): + java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') + references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) + print(f'{side}: {matched:,} block-properties output lines match Rust',flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={'schema':1,'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'registry_states':35723,'fixtures':len(fixtures),'sources_sha256':tested_sources,'fixtures_sha256':tested_fixtures,'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references,'scope':'All pinned block-definition force-solid, replaceability, liquid and occlusion flags and raw occlusion geometry are imported privately; Rust computes legacy solidity from cached collision shapes and solid rendering from occlusion geometry. Actual native BlockState isSolid, liquid, canOcclude, isSolidRender and no-context canBeReplaced are compared for every state, together with raw cached bounds and synthetic force-flag/cache/shape threshold combinations using the private native solidity calculator and native full-shape test. Item/fluid replacement, block support, survival, dynamic collision and full gameplay remain pending.'} + lab.write_json(report_path,report);print(f'Scoped block-properties parity passed: {report_path}') + + +if __name__=='__main__':main() diff --git a/tools/test_block_state_codec_parity.py b/tools/test_block_state_codec_parity.py new file mode 100644 index 000000000..7073f4bc8 --- /dev/null +++ b/tools/test_block_state_codec_parity.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Compare pinned vanilla compact/full block-state JSON codecs.""" +import argparse +import json +import os +from pathlib import Path +import platform +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(facts): + states=facts['states'];defaults=facts['defaults'] + for state in states: + for full in [False,True]:yield [full,json.dumps(state,separators=(',',':'))] + for name,index in sorted(defaults.items()): + default=states[index] + for value in [name,name.removeprefix('minecraft:'),':'+name.removeprefix('minecraft:'),{'id':name},{'id':name,'properties':default.get('properties',{})}]: + for full in [False,True]:yield [full,json.dumps(value)] + for properties in [None,False,0,1.5,'unknown',[],[{}],{}, {'unknown':'unknown'}]: + for full in [False,True]:yield [full,json.dumps({'id':name,'properties':properties})] + for key,original in default.get('properties',{}).items(): + for value in [None,True,False,0,1.0,[],{},'',original.upper(),'unknown',original]: + changed=dict(default['properties']);changed[key]=value;changed['unknown']='ignored' + for full in [False,True]:yield [full,json.dumps({'id':name,'properties':changed})] + zeroes=[0x30,0x660,0x6f0,0x7c0,0x966,0x9e6,0xa66,0xae6,0xb66,0xbe6,0xc66,0xce6,0xd66,0xde6,0xe50,0xed0,0xf20,0x1040,0x1090,0x17e0,0x1810,0x1946,0x19d0,0x1a80,0x1a90,0x1b50,0x1bb0,0x1c40,0x1c50,0xa620,0xa8d0,0xa900,0xa9d0,0xa9f0,0xaa50,0xabf0,0xff10] + for name,key in facts['integers']: + for value in ['+0','-0','00','+01','-01','1.0','1e0',' 1','1 ','2147483647','2147483648','-2147483648','-2147483649','9'*80,'0'*80+'1','+','--1','+-1','\u00b2','\U0001d7d9',*[str(i) for i in range(-2,34)],*[chr(z)+chr(z+1) for z in zeroes]]: + for full in [False,True]:yield [full,json.dumps({'id':name,'properties':{key:value}})] + invalid=[None,False,1,[],{}, {'Name':'minecraft:stone'}, {'id':None}, {'id':True}, {'id':1}, {'id':[]}, {'id':{}},'minecraft:unknown','minecraft:',':','Minecraft:stone','minecraft:stone:foo','mine craft:stone',{'id':'minecraft:unknown','properties':{}}] + for value in invalid: + for full in [False,True]:yield [full,json.dumps(value)] + for text in ['{"id":"minecraft:stone","id":"minecraft:water"}','{"id":"minecraft:water","properties":{"level":"0","level":"1"}}','{"id":"minecraft:water","properties":{"level":"1"},"properties":null}']: + for full in [False,True]:yield [full,text] + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--prepare',action='store_true');args=parser.parse_args() + build=lab.LOCAL/'rust-block-state-codec-parity';build.mkdir(parents=True,exist_ok=True) + report_path=build/'report.json';report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java' + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_state_codec_fixture.rs'] + tested_sources=base.source_hashes(sources) + classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle],'compile-java') + def java(side,mode,path): + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockStateCodecOracle',mode,path],side+'-'+mode) + for side in jars:java(side,'export',build/f'facts-{side}.json') + facts=json.loads((build/'facts-server.json').read_text()) + if facts!=json.loads((build/'facts-client.json').read_text()):raise ValueError('client/server registry metadata differs') + if len(facts['states'])!=35723:raise ValueError('incomplete pinned state registry') + fixtures=list(corpus(facts));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') + fixture_paths=[inputs,build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) + run(['cargo','build','--release','-p','horizon-world','--example','block_state_codec_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) + binary=Path(metadata['target_directory'])/'release/examples'/('block_state_codec_fixture.exe' if os.name=='nt' else 'block_state_codec_fixture') + run([binary,build],'rust');references=[] + for side,jar in jars.items(): + java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') + references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) + print(f'{side}: {matched:,} block-state codec output lines match Rust',flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={'schema':1,'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'block_states':len(facts['states']),'blocks':len(facts['defaults']),'integer_properties':len(facts['integers']),'codec_inputs':len(fixtures),'sources_sha256':tested_sources,'fixtures_sha256':tested_fixtures,'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references,'scope':'Actual BlockState.CODEC and FULL_CODEC, every pinned runtime block state, compact/default versus full encoding, canonical object keys, namespaces, property omission/invalid fallback, unknown fields, malformed property containers, Java integer-property parsing including signs/leading zeroes/BMP decimal digits and overflow, invalid identifiers/types, duplicate fields. Registry identities, defaults and integer property kinds are imported from both authenticated JARs and must agree. This ports codec behavior over that metadata, not block gameplay. Native warning text, arbitrary malformed JSON/unpaired surrogate text, registry lifecycle/ownership and full material-rule codecs remain pending.'} + lab.write_json(report_path,report);print(f'Scoped block-state codec parity passed: {report_path}') + + +if __name__=='__main__':main() diff --git a/tools/test_block_support_parity.py b/tools/test_block_support_parity.py new file mode 100644 index 000000000..fd7646a39 --- /dev/null +++ b/tools/test_block_support_parity.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Compare registered cached block support with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import subprocess +import random +import struct +import math +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--prepare',action='store_true');args=parser.parse_args() + build=lab.LOCAL/'rust-block-support-parity';build.mkdir(parents=True,exist_ok=True) + report_path=build/'report.json';report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSupportOracle.java' + helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java' + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_support_fixture.rs'] + tested_sources=base.source_hashes(sources) + classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,helper],'compile-java') + def java(side,mode,path): + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockSupportOracle',mode,path],side+'-'+mode) + java('server','export',build) + fixture_paths=[build/'block-registry.nbt',build/'cached-support.nbt'];tested_fixtures=base.source_hashes(fixture_paths) + run(['cargo','build','--release','-p','horizon-world','--example','block_support_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) + binary=Path(metadata['target_directory'])/'release/examples'/('block_support_fixture.exe' if os.name=='nt' else 'block_support_fixture') + run([binary,build],'rust');references=[] + for side,jar in jars.items(): + java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') + references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) + print(f'{side}: {matched:,} block-support output lines match Rust',flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={'schema':1,'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'registry_states':35723,'cached_states':35524,'uncached_states':199,'support_queries':35524*18,'sources_sha256':tested_sources,'fixtures_sha256':tested_fixtures,'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references,'scope':'All 35,524 cached block-state support shapes are imported privately and Rust derives FULL/CENTER/RIGID face-support masks. These are compared with actual BlockState.isFaceSturdy cache results across all six directions; all 199 uncached states remain explicitly unsupported. Registry/DataVersion/kind validation, shared shape identities, exact face geometry and full-state queries are covered. Dynamic support selection, block survival and full gameplay remain pending.'} + lab.write_json(report_path,report);print(f'Scoped block-support parity passed: {report_path}') + + +if __name__=='__main__':main() diff --git a/tools/test_block_survival_parity.py b/tools/test_block_survival_parity.py new file mode 100644 index 000000000..1300d3bd8 --- /dev/null +++ b/tools/test_block_survival_parity.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Compare initial block survival rules with pinned vanilla.""" +import argparse +import json +import itertools +import random +import struct +import os +from pathlib import Path +import platform +import subprocess +import zipfile +try: + from . import lab, test_rust_parity as base, test_worldgen_parity as worldgen +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + + +CLASS_RULES={ + 'FireBlock':'Fire', + 'CactusBlock':'Cactus', + 'PathBlock':'Path', + 'MushroomBlock':'Mushroom', + + 'MultifaceBlock':'Multiface', + 'VineBlock':'Vine', + 'HangingMossBlock':'HangingMoss', + 'SeaPickleBlock':'SeaPickle', + 'SnowLayerBlock':'SnowLayer', + + 'BellBlock':'Bell','ShelfMushroomBlock':'FullBehind', + 'GrowingPlantBlock':'GrowingPlant', + 'MangrovePropaguleBlock':'MangrovePropagule', + 'SpeleothemBlock':'Speleothem', + 'ScaffoldingBlock':'Scaffolding', + 'PistonHeadBlock':'PistonHead', + 'ChorusPlantBlock':'ChorusPlant', + 'ChorusFlowerBlock':'ChorusFlower', + 'PitcherCropBlock':'PitcherCrop', + + 'BigDripleafBlock':'BigDripleaf','BigDripleafStemBlock':'BigDripleafStem','FarmlandBlock':'Farmland','CocoaBlock':'Cocoa', + 'SugarCaneBlock':'SugarCane','SporeBlossomBlock':'SporeBlossom','FrogspawnBlock':'Frogspawn','SmallDripleafBlock':'SmallDripleaf','TallSeagrassBlock':'TallSeagrass', + 'DoorBlock':'Door', + 'BaseRailBlock':'RigidBelow','LeafLitterBlock':'FullBelow','WallSignBlock':'SolidBehind','GrindstoneBlock':'Always','RedstoneWallTorchBlock':'FullBehind','BubbleColumnBlock':'BubbleColumn','RedstoneWireBlock':'RedstoneWire','SoulFireBlock':'TagBelow:minecraft:soul_fire_base_blocks', + 'BlockBehaviour':'Always','CakeBlock':'SolidBelow','CandleCakeBlock':'SolidBelow','BannerBlock':'SolidBelow','StandingSignBlock':'SolidBelow', + 'WallBannerBlock':'SolidBehind','CarpetBlock':'NonAirBelow','MossyCarpetBlock':'MossCarpet','BaseTorchBlock':'CenterBelow','CandleBlock':'CenterBelow','LanternBlock':'Lantern', + 'HangingRootsBlock':'FullAbove','LadderBlock':'FullBehind','AmethystClusterBlock':'FullBehind','TripWireHookBlock':'FullBehind','BaseCoralWallFanBlock':'FullBehind','WallTorchBlock':'FullBehind', + 'BasePressurePlateBlock':'RigidOrCenterBelow','DiodeBlock':'RigidBelow','BaseCoralPlantTypeBlock':'FullBelow','CeilingHangingSignBlock':'CenterAbove', + 'FaceAttachedHorizontalDirectionalBlock':'FaceAttached','BambooSaplingBlock':'SupportsBamboo','BambooStalkBlock':'SupportsBamboo', +} + +VEGETATION_RULES={ + 'LilyPadBlock':'LilyPad', + 'VegetationBlock':'TagBelow:minecraft:supports_vegetation', + 'AzaleaBlock':'TagBelow:minecraft:supports_azalea', + 'DryVegetationBlock':'TagBelow:minecraft:supports_dry_vegetation', + 'NetherSproutsBlock':'TagBelow:minecraft:supports_nether_sprouts', + 'NetherWartBlock':'TagBelow:minecraft:supports_nether_wart', + 'WitherRoseBlock':'TagBelow:minecraft:supports_wither_rose', + 'CactusFlowerBlock':'CactusFlower','SeagrassBlock':'Seagrass', +} + +def bind_definitions(classes,placement,support_tags): + definitions={name:CLASS_RULES[owner] for name,owner in classes.items() if owner in CLASS_RULES} + for name,owner in classes.items(): + if owner=='CropBlock' and placement.get(name)=='CropBlock':definitions[name]='Crop' + if owner=='DoublePlantBlock' and placement.get(name)=='VegetationBlock':definitions[name]='DoublePlant' + if owner!='VegetationBlock':continue + method=placement[name] + if method in VEGETATION_RULES:definitions[name]=VEGETATION_RULES[method] + elif method in ['AttachedStemBlock','StemBlock','NetherFungusBlock','NetherRootsBlock']: + field='stemSupportBlocks' if method=='StemBlock' else 'supportBlocks' + definitions[name]='TagBelow:'+support_tags[name][field] + return definitions + + +def fluid_tag_resources(jar): + with zipfile.ZipFile(jar) as archive: + prefix='data/minecraft/tags/fluid/' + return {'minecraft:'+name[len(prefix):-5]:archive.read(name).decode('utf-8') for name in sorted(archive.namelist()) if name.startswith(prefix) and name.endswith('.json')} + + +def behavior_key(rule,value): + properties=value.get('properties',{}) + return (rule,properties.get('facing') if rule in ['FullBehind','SolidBehind','Cocoa','PistonHead','Bell'] or rule=='FaceAttached' and properties.get('face')=='wall' else None,properties.get('hanging') if rule in ['Lantern','MangrovePropagule'] else None,properties.get('bottom') if rule=='MossCarpet' else None,properties.get('face') if rule=='FaceAttached' else None,properties.get('half') if rule in ['Door','DoublePlant','SmallDripleaf','TallSeagrass','PitcherCrop'] else None,properties.get('vertical_direction') if rule=='Speleothem' else None,properties.get('type') if rule=='PistonHead' else None,value['id'] if rule in ['GrowingPlant','Speleothem'] else None,properties.get('attachment') if rule=='Bell' else None,tuple(properties.get(face) for face in ['down','up','north','south','west','east']) if rule in ['Multiface','Vine'] else None) + +def corpus(facts,definitions): + positions=[[0,0,0],[2147483647,-2147483648,2147483647],[-17,2147483647,-33]] + def case(state,neighbors,position=0,**kwargs): + f={'state':state,'neighbors':neighbors,'position':positions[position%3],'entity':'none','fail':-1,'entity_fail':-1};f.update(kwargs);return f + defaults=facts['defaults'];samples=[defaults[name] for name in ['minecraft:air','minecraft:stone','minecraft:water','minecraft:pale_moss_carpet'] if name in defaults] + representatives={} + for state,value in enumerate(facts['states']): + rule=definitions.get(value['id']) + if rule is None:continue + yield case(state,samples or [0],state,fail=0) + if rule=='Always':continue + for neighbor in [*samples,state,defaults[value['id']]]:yield case(state,[neighbor],state) + key=behavior_key(rule,value) + representatives.setdefault(key,state) + special=[defaults[name] for name in ['minecraft:shulker_box','minecraft:moving_piston','minecraft:scaffolding','minecraft:oak_slab','minecraft:stone','minecraft:air','minecraft:pale_moss_carpet','minecraft:bamboo'] if name in defaults] or [0] + for candidate in representatives.values(): + rule=definitions[facts['states'][candidate]['id']] + for neighbor in range(len(facts['states'])):yield case(candidate,[neighbor],neighbor) + extra=['big_dripleaf','big_dripleaf_stem','clay','dirt'] if rule=='BigDripleafStem' else ['oak_fence_gate','dirt','oak_trapdoor'] if rule=='Farmland' else ['farmland','dirt'] if rule in ['Crop','PitcherCrop'] else [] + neighbors=[*special,*[defaults['minecraft:'+name] for name in extra if 'minecraft:'+name in defaults]] + if rule in ['Crop','PitcherCrop']: + for brightness in [-2147483648,-1,0,7,8,9,15,2147483647]: + for neighbor in neighbors: + for fail in [-1,0]: + for light_fail in [-1,0]:yield case(candidate,[neighbor],candidate,brightness=brightness,fail=fail,light_fail=light_fail) + if rule in ['LilyPad','Frogspawn','SporeBlossom','SmallDripleaf','TallSeagrass','SugarCane']: + fluid_states=[index for index,state in enumerate(facts['states']) if state['id'] in ['minecraft:water','minecraft:lava','minecraft:air']] + supporting=[defaults['minecraft:'+name] for name in ['stone','dirt','clay','ice','big_dripleaf','small_dripleaf','tall_seagrass','sugar_cane','oak_leaves'] if 'minecraft:'+name in defaults] + for first in fluid_states: + for second in [defaults[name] for name in ['minecraft:air','minecraft:water','minecraft:lava'] if name in defaults]: + for neighbor in supporting: + for fail in [-1,0,1,4]: + for fluid_fail in [-1,0,1,3]: + yield case(candidate,[neighbor],candidate,fluid_states=[first,second],fail=fail,fluid_fail=fluid_fail) + if rule=='Fire': + air=defaults['minecraft:air'] + # An empty first support query forces the ignition lookup even when + # the subsequent neighbor has a full supporting face. + for neighbor in range(len(facts['states'])): + yield case(candidate,[air,neighbor],neighbor) + if rule=='Mushroom': + for brightness in [-2147483648,0,12,13,14,2147483647]: + for neighbor in range(len(facts['states'])): + yield case(candidate,[neighbor],neighbor,brightness=brightness) + for neighbor in range(0,len(facts['states']),7): + for fail in [-1,0]: + yield case(candidate,[neighbor],neighbor,brightness=12,fail=fail,light_fail=0) + if rule=='Cactus': + air=defaults['minecraft:air'];cactus=defaults['minecraft:cactus'] + for neighbor in range(len(facts['states'])): + yield case(candidate,[air,air,air,air,cactus,neighbor],neighbor,fluid_states=[air]) + supports=[defaults['minecraft:'+name] for name in ['air','sand','red_sand','cactus','stone'] if 'minecraft:'+name in defaults] + fluid_states=[index for index,state in enumerate(facts['states']) if state['id'] in ['minecraft:air','minecraft:water','minecraft:lava']] + for support in supports: + for fluid in fluid_states: + for slot in range(4): + fluids=[air]*4;fluids[slot]=fluid + for fail in [-1,*range(6)]: + for fluid_fail in [-1,*range(4)]: + yield case(candidate,[air,air,air,air,support,air],slot,fluid_states=fluids,fail=fail,fluid_fail=fluid_fail) + if rule in ['Multiface','Vine','HangingMoss','SnowLayer','SeaPickle']: + shulkers=[index for index,state in enumerate(facts['states']) if state['id']=='minecraft:shulker_box'] + for neighbor in shulkers: + for old,current in [(0,0),(0,1),(1,0),(0.1,0.2),(0.7,0.8),(1,1)]: + for entity in ['closed','opened']: + for entity_fail in [-1,0,1,2,3]: + yield case(candidate,[neighbor],candidate,entity=entity,entity_fail=entity_fail,shulker_progress=[struct.pack('>f',v).hex() for v in [old,current]]) + if rule in ['ChorusPlant','ChorusFlower','Scaffolding','Multiface','Vine','HangingMoss','SnowLayer','SeaPickle','Fire','Cactus']: + # Long read sequences expose directional order, early exits and failures + # beyond the two alternating neighbors used by the general corpus. + names=['air','stone','end_stone','chorus_plant','chorus_flower','vine','pale_hanging_moss','shulker_box','scaffolding','oak_slab','oak_planks','sand','cactus','water'] + palette=[defaults['minecraft:'+name] for name in names if 'minecraft:'+name in defaults] + if rule=='Scaffolding': + palette.extend(index for index,state in enumerate(facts['states']) if state['id']=='minecraft:scaffolding') + rng=random.Random(0x484f52495a4f4e+candidate) + sequences=(tuple(rng.choice(palette) for _ in range(10)) for _ in range(4096 if rule in ["ChorusPlant","ChorusFlower","Scaffolding"] else 512)) + for index,sequence in enumerate(sequences): + for fail in [-1,*range(10)]:yield case(candidate,list(sequence),index,fail=fail) + if rule in ['ChorusPlant','ChorusFlower']: + for index,sequence in enumerate(itertools.product(palette[:5],repeat=5)): + yield case(candidate,list(sequence),index) + for first in neighbors: + for second in neighbors: + for fail in [-1,0,1]: + for entity_fail in [-1,0]: + for entity in ['none','closed','opened']:yield case(candidate,[first,second],candidate,fail=fail,entity_fail=entity_fail,entity=entity) + + +def save_checkpoint(path, checkpoint): + temporary=path.with_suffix('.tmp') + temporary.write_text(json.dumps(checkpoint,indent=2)+'\n',encoding='utf-8') + temporary.replace(path) + + +def load_checkpoint(path, sources, environment): + if not path.exists():return None + checkpoint=json.loads(path.read_text(encoding='utf-8')) + if checkpoint.get('schema')!=1 or checkpoint['sources_sha256']!=sources or checkpoint['environment']!=environment: + raise ValueError('checkpoint source/environment changed; run again without --resume') + for group in ['fixtures_sha256','artifacts_sha256']: + for name,digest in checkpoint[group].items(): + artifact=Path(name) + if not artifact.is_file() or lab.digest(artifact,'sha256')!=digest: + raise ValueError(f'checkpoint artifact changed: {artifact}; run again without --resume') + return checkpoint + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare',action='store_true') + parser.add_argument('--resume',action='store_true',help='Reuse completed stages only when all recorded input and executable hashes still match') + args=parser.parse_args() + build=lab.LOCAL/'rust-block-survival-parity';build.mkdir(parents=True,exist_ok=True) + report_path=build/'report.json';report_path.unlink(missing_ok=True) + checkpoint_path=build/'run-state.json' + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSurvivalOracle.java' + helpers=[oracle.with_name(name+'.java') for name in ['VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle','VanillaHeightmapOracle']] + sources=[oracle,*helpers,lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_survival_fixture.rs'] + tested_sources=base.source_hashes(sources) + environment={'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'dependencies':{str(path):lab.digest(path,'sha256') for path in [*jars.values(),*libraries]}} + checkpoint=load_checkpoint(checkpoint_path,tested_sources,environment) if args.resume else None + classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,stdout=log,stderr=subprocess.STDOUT,timeout=3600) + dependency_path=os.pathsep.join(map(str,libraries)) + def java(side,mode,path): + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockSurvivalOracle',mode,path],side+'-'+mode) + if checkpoint is None: + checkpoint_path.unlink(missing_ok=True) + tags=worldgen.tag_resources(jars['server']) + if tags!=worldgen.tag_resources(jars['client']):raise ValueError('client/server tags differ') + (build/'tags.json').write_text(json.dumps(tags,separators=(',',':'))) + fluid_tags=fluid_tag_resources(jars['server']) + if fluid_tags!=fluid_tag_resources(jars['client']):raise ValueError('client/server fluid tags differ') + (build/'fluid-tags.json').write_text(json.dumps(fluid_tags,separators=(',',':'))) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,*helpers],'compile-java') + java('server','export',build) + facts=json.loads((build/'facts.json').read_text());definition_classes=json.loads((build/'survival-classes.json').read_text()) + definitions=bind_definitions(definition_classes,json.loads((build/'survival-placement-classes.json').read_text()),json.loads((build/'survival-support-tags.json').read_text())) + if len(facts['states'])!=35723:raise ValueError('incomplete pinned registry') + if len(definitions)!=len(facts['defaults']):raise ValueError('incomplete pinned survival definitions') + (build/'survival-rules.json').write_text(json.dumps(definitions,separators=(',',':'))) + inputs=build/'inputs.txt';fixture_count=0 + with inputs.open('w',encoding='utf-8') as output: + for fixture in corpus(facts,definitions): + output.write(json.dumps(fixture,separators=(',',':'))+'\n');fixture_count+=1 + fixture_paths=[inputs,build/'survival-extra-definitions.json',build/'fluid-tags.json',build/'survival-placement-classes.json',build/'survival-support-tags.json',build/'facts.json',build/'survival-classes.json',build/'survival-rules.json',build/'tags.json',build/'block-registry.nbt',build/'cached-collision.nbt',build/'block-properties.nbt',build/'cached-support.nbt'] + tested_fixtures=base.source_hashes(fixture_paths) + run(['cargo','build','--release','-p','horizon-world','--example','block_survival_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) + binary=Path(metadata['target_directory'])/'release/examples'/('block_survival_fixture.exe' if os.name=='nt' else 'block_survival_fixture') + base.ensure_sources_unchanged(sources,tested_sources) + checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':{'supported_blocks':len(definitions),'supported_states':sum(state['id'] in definitions for state in facts['states']),'survival_rules':len(set(definitions.values())),'survival_rule_kinds':len({rule.split(':',1)[0] for rule in definitions.values()}),'fluid_tag_files':len(fluid_tags),'fixtures':fixture_count},'outputs':{}} + save_checkpoint(checkpoint_path,checkpoint) + print('Verified inputs and compiled executables checkpointed',flush=True) + def stage(name, action): + output=build/(name+'.txt') + previous=checkpoint['outputs'].get(name) + if previous is None or not output.exists() or lab.digest(output,'sha256')!=previous: + action() + checkpoint['outputs'][name]=lab.digest(output,'sha256') + save_checkpoint(checkpoint_path,checkpoint) + print(f'{name}: completed output checkpointed',flush=True) + stage('rust',lambda:run([checkpoint['binary'],build],'rust')) + references=[] + for side,jar in jars.items(): + stage(side,lambda:java(side,side,build)) + reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') + references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) + print(f'{side}: {matched:,} block-survival output lines match Rust',flush=True) + base.ensure_sources_unchanged(sources,tested_sources) + load_checkpoint(checkpoint_path,tested_sources,environment) + report={'schema':1,**{key:value for key,value in environment.items() if key!='dependencies'},**checkpoint['counts'],'sources_sha256':tested_sources,'fixtures_sha256':{str(Path(name).relative_to(lab.ROOT)):digest for name,digest in checkpoint['fixtures_sha256'].items()},'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references,'scope':'Version-pinned block survival rules are assigned from privately inspected native definition classes and executed in Rust against solid/air/tag tests and unified support geometry. Actual native canSurvive evaluates every supported candidate state, each neighbor state against behavior representatives, changing repeated reads, world-coordinate wrapping, absent/closed/open shulker snapshots, brightness thresholds, independent fluid state sequences and block/entity/light/fluid query failures. All pinned survival families are included; full block placement/update behavior, world/entity lifecycle and full gameplay remain pending.'} + lab.write_json(report_path,report);print(f'Scoped block-survival parity passed: {report_path}') + + +if __name__=='__main__':main() diff --git a/tools/test_bulk_section_parity.py b/tools/test_bulk_section_parity.py new file mode 100644 index 000000000..414613067 --- /dev/null +++ b/tools/test_bulk_section_parity.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Compare resident bulk-section caching, raw mutations and unchanged heightmaps.""" +import argparse +from collections import Counter +import json +import os +from pathlib import Path +import platform +import random +import subprocess + +try: + from . import lab, test_rust_parity as base, test_worldgen_parity as worldgen +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + + +def corpus(facts): + ids=facts['defaults'];count=len(facts['states']);rng=random.Random(6541) + for minimum in [-2032,-64,0,1968]: + for prime in [False,True]: + ops=[] + for x,y,z in [[0,minimum,0],[0,minimum+16,0],[16,minimum+31,-1],[-1,minimum+63,16],[0,minimum-1,0],[2147483647,2147483647,-2147483648],[1600,minimum,1600]]: + ops += [['has',x,y,z],['get',x,y,z],['set',x,y,z,ids['minecraft:cave_air']],['get',x,y,z],['world',x,y,z]] + selected=range(count) if minimum==-64 else [rng.randrange(count) for _ in range(64)] + for state in selected: + ops += [['set',0,minimum+1,0,state],['get',0,minimum+1,0],['world',0,minimum+1,0]] + for state in [ids['minecraft:air'],ids['minecraft:stone'],ids['minecraft:void_air'],ids['minecraft:cave_air']]: + ops += [['set',1,minimum+48,1,state],['get',1,minimum+48,1],['world',1,minimum+48,1],['height','WORLD_SURFACE',1,1]] + # These X positions alias in the native 22-bit packed section key. + for x in [0,67108864,0]: + ops += [['set',x,minimum+2,0,ids['minecraft:stone']],['get',x,minimum+2,0],['world',x,minimum+2,0]] + ops += [['reset']] + for x in [67108864,0,67108864]: + ops += [['set',x,minimum+2,0,ids['minecraft:water']],['get',x,minimum+2,0],['world',x,minimum+2,0]] + yield {'min':minimum,'height':64,'prime':prime,'chunks':[[0,0],[1,-1],[-1,1],[4194304,0]],'ops':ops} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepare",action="store_true") + args=parser.parse_args() + build=lab.LOCAL/"rust-bulk-section-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + tags=worldgen.tag_resources(jars["server"]) + if not tags or tags!=worldgen.tag_resources(jars["client"]):raise ValueError("client/server block tags differ or are empty") + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBulkSectionOracle.java" + helper=oracle.with_name("VanillaHeightmapOracle.java") + sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", + lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/bulk_section_fixture.rs"] + tested_sources=base.source_hashes(sources) + classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") + def java(side,mode,path): + run(["java","-Xmx1G","-cp",os.pathsep.join([str(classes),str(jars[side]),dependency_path]),"dev.horizonlab.parity.VanillaBulkSectionOracle",mode,path],side+"-"+mode) + for side in jars:java(side,"export",build/f"facts-{side}.json") + facts=json.loads((build/"facts-server.json").read_text()) + if facts!=json.loads((build/"facts-client.json").read_text()):raise ValueError("client/server state facts differ") + if len(facts["states"])!=35723:raise ValueError("incomplete pinned state table") + fixtures=list(corpus(facts));inputs=build/"inputs.txt" + inputs.write_text("".join(json.dumps(value,separators=(",",":"))+"\n" for value in fixtures),encoding="utf-8") + (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") + fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] + tested_fixtures=base.source_hashes(fixture_paths) + run(["cargo","build","--release","-p","horizon-world","--example","bulk_section_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("bulk_section_fixture.exe" if os.name=="nt" else "bulk_section_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + java(side,side,build) + reference=build/f"{side}.txt";matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} bulk-section output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "block_states":len(facts["states"]),"block_tag_files":len(tags),"fixtures":len(fixtures),"resident_chunks_per_fixture":4,"operations":dict(Counter(op[0] for f in fixtures for op in f["ops"])), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual BulkSectionAccess over resident ProtoChunks: raw reads/writes, all-air chunk-read collapse, outside-height AIR, absent sections, missing neighbors, packed-key caching and aliasing, cache reset and complete final raw sections/heightmap words. Every pinned block state is inserted and read with both preprimed and lazy heightmaps. Rust holds an exclusive region borrow instead of Java section acquire/release locks. Concurrent ownership, ordinary ore geometry, region side effects and complete gameplay remain pending."} + + lab.write_json(report_path,report);print(f"Scoped bulk-section parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_canyon_carver_parity.py b/tools/test_canyon_carver_parity.py new file mode 100644 index 000000000..81d281a4c --- /dev/null +++ b/tools/test_canyon_carver_parity.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Compare decoded canyon paths, height-dependent widths and random state with vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base,test_worldgen_parity as worldgen +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + + +def corpus(resources): + encode=lambda value:json.dumps(value,separators=(',',':')) + wrap=lambda value:((value+2**31)%2**32)-2**31 + config=next(json.loads(raw) for raw in resources.values() if json.loads(raw)['type']=='minecraft:canyon') + for context in [[-64,384,63],[0,128,32],[-2032,4064,0],[0,16,8]]: + for legacy in [False,True]: + for seed in [0,1,2,3,17,-1,-987654321,0x123456789abcdef]: + for cx,cz,dx,dz in [(0,0,0,0),(-1,2,1,-1),(107,-59,-4,3),(1875000,-1875000,0,0),(-2**31,2**31-1,0,0),(0,0,8,-8)]: + yield {'definition':encode(config),'context':context,'legacy':legacy,'seed':seed,'target':[cx,cz],'origin':[wrap(cx+dx),wrap(cz+dz)],'repeats':2,'fail':-1} + for mode in range(32): + shape={**config['shape'],'width_smoothness':[1,2,3,2**31-1][mode%4], + 'vertical_radius_center_factor':[-1,0,0.5,2][mode%4], + 'distance_factor':[-1,0,0.001,0.5,1,2,4,0.75][mode%8], + 'horizontal_radius_factor':[0,0.1,1,3][mode%4], + 'thickness':[-1,0,1,6][mode%4],'y_scale':[-1,0,1,4][mode%4]} + custom={**config,'shape':shape,'vertical_rotation':[-0.5,0,0.5,1][mode%4],'y':{'absolute':40}} + yield {'definition':encode(custom),'context':[-64,384,63],'legacy':bool(mode%2),'seed':mode*971,'target':[0,0],'origin':[0,0],'repeats':2,'fail':[-1,0,1,63][mode//8]} + bad=[None,False,0,[],{}, {'type':'missing'}, {**config,'type':':canyon'}] + for field in config: + bad.append({k:v for k,v in config.items() if k!=field}) + for value in [None,False,[],{},'0']:bad.append({**config,field:value}) + for field in config['shape']: + bad.append({**config,'shape':{k:v for k,v in config['shape'].items() if k!=field}}) + for value in [None,False,[],{},'0']:bad.append({**config,'shape':{**config['shape'],field:value}}) + for value in [-1,-0.0,0,1,2,1e100,-1e100,-1e-100]:bad.append({**config,'probability':value}) + for value in [-1,0,1,2**31-1,4294967296]:bad.append({**config,'shape':{**config['shape'],'width_smoothness':value}}) + for value in bad: + yield {'definition':encode(value),'context':[-64,384,63],'legacy':False,'seed':0,'target':[0,0],'origin':[0,0],'repeats':1,'fail':63} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-canyon-carver-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCanyonCarverOracle.java" + helper=oracle.with_name("VanillaAnchorOracle.java") + sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/canyon_carver_fixture.rs"] + tested_sources=base.source_hashes(sources) + resources=worldgen.registry_resources(jars['server'],'carver') + if not resources or resources!=worldgen.registry_resources(jars['client'],'carver'):raise ValueError('reference carver resources differ') + resources_path=build/'carvers.json';resources_path.write_text(json.dumps(resources,separators=(',',':')),encoding='utf-8') + fixtures=list(corpus(resources));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + fixture_paths=[inputs,resources_path];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") + run(["cargo","build","--release","-p","horizon-world","--example","canyon_carver_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("canyon_carver_fixture.exe" if os.name=="nt" else "canyon_carver_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaCanyonCarverOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} canyon-carver output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"carve_attempts":sum(f["repeats"] for f in fixtures),"bundled_canyon_definitions":1, + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual WorldCarver.DIRECT_CODEC, CanyonWorldCarver.isStartChunk and CanyonWorldCarver.carve using the independently authenticated bundled canyon definition. Compares ordered output cells including duplicates, partial output failures, resulting mask intervals and subsequent random longs across repeated invocations. Covers both outer random modes, local legacy streams, height-dependent width factors, horizontal/vertical radius variation, four generation heights, negative/distant/extreme coordinates and adjacent/far origin chunks. Custom shapes exercise width smoothness, path length, degenerate radii and failure branches; malformed selected codec fields are tested. Gaussian/weighted provider codecs, neighbor-carver seeding/biome selection, blending and complete worlds remain outside this scope. Rust bounds paths to 4096 steps, height to 4064 and total candidates to 2^24 per invocation."} + + lab.write_json(report_path,report);print(f"Scoped canyon-carver parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_carving_geometry_parity.py b/tools/test_carving_geometry_parity.py new file mode 100644 index 000000000..0ad9e6da0 --- /dev/null +++ b/tools/test_carving_geometry_parity.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Compare shared cave/canyon geometry and path reachability with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +import struct +import math +try: + from . import lab,test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def bits(value): + return struct.pack('>d',value).hex() + + +def corpus(): + rng=random.Random(0x484f52495a4f4e454c4c4950) + wrap=lambda value:((value+2**31)%2**32)-2**31 + for cx,cz in [(0,0),(-1,2),(1875000,-1875000),(-2**31,2**31-1),(134217727,-134217728)]: + bx,bz=wrap(cx<<4),wrap(cz<<4) + for minimum,height in [(-64,384),(0,128),(-2032,4064)]: + ellipsoids=[] + for index in range(16): + center=[bx+rng.uniform(-8,24),rng.uniform(minimum-8,minimum+height+8),bz+rng.uniform(-8,24)] + horizontal=[0.1,1,4,8,16,32,64,0][index%8] + vertical=[0.1,0.5,1,4,32,64,512,0][index%8] + ellipsoids.append({'center':list(map(bits,center)),'horizontal':bits(horizontal),'vertical':bits(vertical),'skip':index%4,'fail':[-1,0,1,63][index//4]}) + # Exact boundary and IEEE inputs, bounded by real output height. + for index,value in enumerate([0.,-0.,-1.,math.inf,-math.inf,math.nan,2**31,-2**31,1e300,5e-324]): + ellipsoids += [ + {'center':list(map(bits,[bx+8,minimum+height/2,bz+8])),'horizontal':bits(value),'vertical':bits(4),'skip':index%4,'fail':63}, + {'center':list(map(bits,[bx+8,minimum+height/2,bz+8])),'horizontal':bits(4),'vertical':bits(value),'skip':index%4,'fail':63}, + {'center':list(map(bits,[value,minimum+height/2,bz+8])),'horizontal':bits(4),'vertical':bits(4),'skip':index%4,'fail':63}] + yield {'chunk':[cx,cz],'min':minimum,'max':minimum+height-1,'ellipsoids':ellipsoids} + + +def reach_corpus(): + rng=random.Random(0x434152565245414348) + wrap=lambda value:((value+2**31)%2**32)-2**31 + fbits=lambda value:struct.pack('>f',value).hex() + for cx,cz in [(0,0),(-1,2),(1875000,-1875000),(-2**31,2**31-1)]: + bx,bz=wrap(cx<<4)+8,wrap(cz<<4)+8 + for thickness in [0,1,-18,-20,math.inf,-math.inf,math.nan,1e30,0.00001]: + for dx in [0,1,18,19,100,math.inf,-math.inf,math.nan]: + for start,end in [(0,0),(0,112),(111,112),(-2**31,2**31-1),(2**31-1,-2**31)]: + yield [cx,cz,bits(bx+dx),bits(bz+dx),start,end,fbits(thickness)] + for _ in range(1024): + yield [cx,cz,bits(bx+rng.uniform(-300,300)),bits(bz+rng.uniform(-300,300)),rng.randrange(-100,100),rng.randrange(-100,100),fbits(rng.uniform(-20,50))] + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-carving-geometry-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingGeometryOracle.java" + sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/carving_geometry_fixture.rs"] + tested_sources=base.source_hashes(sources) + fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + reach=list(reach_corpus());reach_path=build/'reach.txt';reach_path.write_text(''.join(json.dumps(q,separators=(',',':'))+'\n' for q in reach),encoding='utf-8') + fixture_paths=[inputs,reach_path];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") + run(["cargo","build","--release","-p","horizon-world","--example","carving_geometry_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("carving_geometry_fixture.exe" if os.name=="nt" else "carving_geometry_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaCarvingGeometryOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} carving-geometry output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"ellipsoids":sum(len(f["ellipsoids"]) for f in fixtures),"reach_queries":len(reach), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual WorldCarver.carveEllipsoid and canReach methods. Compares ordered normalized-coordinate skip queries, output cells, partial output on callback failure and resulting mask column runs; canReach includes Java float thickness arithmetic and signed step overflow. Corpus covers negative/extreme/distant chunk coordinates, output-height clipping, small/large/zero/negative radii, boundaries and IEEE NaNs/infinities/subnormals. NaN trace values are canonicalized. This validates shared geometric primitives, not randomized cave/canyon paths, codecs, provider sampling, biome carver selection or complete worlds."} + + lab.write_json(report_path,report);print(f"Scoped carving-geometry parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_carving_mask_parity.py b/tools/test_carving_mask_parity.py new file mode 100644 index 000000000..a3d4e375c --- /dev/null +++ b/tools/test_carving_mask_parity.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Compare packed carving-mask runs, callback mutations and failure state with vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + rng=random.Random(0x484f52495a4f4e4341525645) + carve=lambda x,y,z:{'kind':'carve','pos':[x,y,z]} + fill=lambda x0,x1,y0,y1,z0,z1:{'kind':'fill','box':[x0,x1,y0,y1,z0,z1]} + visit=lambda fail=-1,add=None:{'kind':'visit','fail':fail,'add':add or {}} + wrap=lambda value:((value+2**31)%2**32)-2**31 + for minimum,height in [(0,1),(-1,2),(-64,3),(-64,63),(0,64),(10,65),(-64,384),(-2032,4064),(-2**31,65),(2**31-65,65)]: + maximum=minimum+height-1 + # Isolated cells, duplicate insertions, packed word/column boundaries, + # Java-wrapped coordinate aliases, negative indices and positive growth. + ops=[visit(),{'kind':'read'}] + points=[[0,minimum,0],[15,maximum,15],[0,maximum,0],[0,minimum,1],[1,minimum,0]] + points += [[rng.randrange(16),minimum+rng.randrange(height),rng.randrange(16)] for _ in range(512)] + for x in [-2**31,-2**31+1,-268435456,-1,0,15,16,2**31-1]: + for y in [wrap(minimum-1),minimum,maximum,wrap(maximum+1)]: + for z in [-17,-1,0,16,17]: + index=wrap(wrap(y-minimum)+wrap(wrap(z+wrap(x<<4))*height)) + if index<0 or index<2**20:points.append([x,y,z]) + for i,(x,y,z) in enumerate(points): + ops += [carve(x,y,z)] + if i%97==0:ops += [visit()] + ops += [visit(0),visit(63),visit(),{'kind':'read'}] + yield {'min':minimum,'max':maximum,'ops':ops} + # Runs spanning all columns and word boundaries, duplicate dense writes. + yield {'min':minimum,'max':maximum,'ops':[fill(0,15,minimum,maximum,0,15),visit(),fill(0,1,minimum,maximum,0,1),{'kind':'read'}]} + if height>=3: + # Mutation behind/ahead of the cursor, extending its current run, + # joining runs, and a failing visitor retaining its added bits. + yield {'min':minimum,'max':maximum,'ops':[ + carve(0,minimum,1),carve(0,minimum+2,1),carve(2,minimum,0), + visit(-1,{'0':[[0,minimum,0],[0,minimum+1,1],[0,minimum+2,1],[1,maximum,0]],'1':[[3,maximum,15]],'2':[[4,minimum,1]]}), + visit(0,{'0':[[5,maximum,1]]}),{'kind':'read'},visit()]} + + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-carving-mask-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingMaskOracle.java" + sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/carving_mask_fixture.rs"] + tested_sources=base.source_hashes(sources) + fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") + run(["cargo","build","--release","-p","horizon-world","--example","carving_mask_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("carving_mask_fixture.exe" if os.name=="nt" else "carving_mask_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaCarvingMaskOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} carving-mask output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"operations":sum(len(f["ops"]) for f in fixtures), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual CarvingMask construction, carve, isEmpty and visit methods. Compares packed vertical-run traversal, splitting across columns, dense/sparse masks, duplicate writes, word boundaries, coordinate overflow and positive aliases, negative index failures, callback additions during traversal and mutations retained after visitor failures. Rust bounds height to 1..4064 and positive index growth to 2^24 bits; corpus indices remain below 2^20. This validates masks, not cave/canyon generation, mask application, aquifers, blending or complete terrain generation."} + + lab.write_json(report_path,report);print(f"Scoped carving-mask parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_cave_carver_parity.py b/tools/test_cave_carver_parity.py new file mode 100644 index 000000000..863dd15d4 --- /dev/null +++ b/tools/test_cave_carver_parity.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Compare decoded cave-carver paths, ordered mask writes and random state with vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base,test_worldgen_parity as worldgen +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + + +def corpus(resources): + encode=lambda value:json.dumps(value,separators=(',',':')) + wrap=lambda value:((value+2**31)%2**32)-2**31 + configs=[(name,json.loads(raw)) for name,raw in sorted(resources.items()) if json.loads(raw)['type']=='minecraft:cave'] + for name,config in configs: + context=[0,128,32] if 'nether' in name else [-64,384,63] + for legacy in [False,True]: + for seed in [0,1,2,3,17,-1,-987654321,0x123456789abcdef]: + for cx,cz,dx,dz in [(0,0,0,0),(-1,2,1,-1),(107,-59,-4,3),(1875000,-1875000,0,0),(-2**31,2**31-1,0,0),(0,0,8,-8)]: + yield {'definition':encode(config),'context':context,'legacy':legacy,'seed':seed,'target':[cx,cz],'origin':[wrap(cx+dx),wrap(cz+dz)],'repeats':2,'fail':-1} + for mode in range(12): + custom={**config,'count':3,'thickness':6 if mode%3==0 else 1,'weird_thickness_bias':bool(mode%2),'y':{'absolute':40},'floor_level':[-1,-0.7,0,1][mode%4]} + yield {'definition':encode(custom),'context':context,'legacy':bool(mode%2),'seed':mode*971,'target':[0,0],'origin':[0,0],'repeats':2,'fail':[-1,0,1,63][mode//3]} + base={**configs[0][1],'count':0} + bad=[None,False,0,[],{}, {'type':'missing'}, {**base,'type':':cave'}] + for field in list(base): + bad.append({k:v for k,v in base.items() if k!=field}) + for value in [None,False,[],{},'0']: + bad.append({**base,field:value}) + for field in ['probability','thickness','floor_level']: + for value in [-1,-0.0,0,1,2,1e100,-1e100,-1e-100]:bad.append({**base,field:value}) + for value in bad: + yield {'definition':encode(value),'context':[-64,384,63],'legacy':False,'seed':0,'target':[0,0],'origin':[0,0],'repeats':1,'fail':63} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-cave-carver-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCaveCarverOracle.java" + helper=oracle.with_name("VanillaAnchorOracle.java") + sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/cave_carver_fixture.rs"] + tested_sources=base.source_hashes(sources) + resources=worldgen.registry_resources(jars['server'],'carver') + if not resources or resources!=worldgen.registry_resources(jars['client'],'carver'):raise ValueError('reference carver resources differ') + resources_path=build/'carvers.json';resources_path.write_text(json.dumps(resources,separators=(',',':')),encoding='utf-8') + fixtures=list(corpus(resources));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + fixture_paths=[inputs,resources_path];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") + run(["cargo","build","--release","-p","horizon-world","--example","cave_carver_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("cave_carver_fixture.exe" if os.name=="nt" else "cave_carver_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaCaveCarverOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} cave-carver output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"carve_attempts":sum(f["repeats"] for f in fixtures),"bundled_cave_definitions":3, + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual WorldCarver.DIRECT_CODEC, CaveWorldCarver.isStartChunk and CaveWorldCarver.carve using all three independently authenticated bundled cave definitions. Compares ordered output cells including duplicates, partial output failures, resulting mask intervals and subsequent random longs across repeated invocations. Covers both outer random modes, local legacy tunnel streams, rooms, branching, thickness bias, floor thresholds, negative/distant/extreme target coordinates and adjacent/far origin chunks. Explicit custom distributions force path and failure branches; malformed selected codec fields are tested. Gaussian/weighted provider codecs, canyon paths, neighbor-carver seeding/biome selection, blending and complete generated worlds remain outside this scope. Rust bounds count to 4096 and total candidates to 2^24 per invocation."} + + lab.write_json(report_path,report);print(f"Scoped cave-carver parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_chunk_stage_parity.py b/tools/test_chunk_stage_parity.py new file mode 100644 index 000000000..6e055f631 --- /dev/null +++ b/tools/test_chunk_stage_parity.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Compare pre-light chunk status transitions and native ProtoChunk writes.""" +import argparse +from collections import Counter +import json +import os +from pathlib import Path +import platform +import random +import subprocess + +try: + from . import lab, test_rust_parity as base, test_worldgen_parity as worldgen +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + + +def corpus(facts): + defaults=facts['defaults'];air=defaults['minecraft:air'] + stages=['empty','structure_starts','structure_references','biomes','terrain','features'] + choices=[defaults['minecraft:'+name] for name in ['air','cave_air','void_air','stone','water','lava','oak_leaves','oak_slab','seagrass','snow','powder_snow','glass','barrier']] + for stage in ['empty','terrain']: + ops=[['stage',stage]] + for state in range(len(facts['states'])): + ops.extend([['set',4,5,7,state],['get',4,5,7],['query',4,7],['set',4,5,7,air],['query',4,7]]) + yield {'chunk':[0,0],'min':0,'height':16,'ops':ops+[['dump']]} + rng=random.Random(0x484f52495a4f4e5354414745) + for minimum,height in [(-64,384),(0,16),(-16,32),(-2032,4064),(2016,16)]: + for initial_stage in stages: + ops=[['stage',initial_stage],['set',0,minimum,0,air],['query',0,0]] + for index,stage in enumerate(stages+list(reversed(stages))): + ops.extend([['stage',stage],['query',0,0]]) + for i in range(24): + x,z=rng.choice([(0,0),(15,15),(-1,16),(2147483647,-2147483648)]) + y=minimum+rng.choice([-1,0,height//2,height-1,height]) + state=rng.choice(choices) + ops.extend([['set',x,y,z,state],['get',x,y,z],['query',x,z]]) + if index%3==0:ops.append(['prime',rng.randrange(64)]) + yield {'chunk':[-3,7],'min':minimum,'height':height,'ops':ops+[['dump']]} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepare",action="store_true") + args=parser.parse_args() + build=lab.LOCAL/"rust-chunk-stage-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + tags=worldgen.tag_resources(jars["server"]) + if not tags or tags!=worldgen.tag_resources(jars["client"]):raise ValueError("client/server block tags differ or are empty") + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkStageOracle.java" + helper=oracle.with_name("VanillaHeightmapOracle.java") + sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", + lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/chunk_stage_fixture.rs"] + tested_sources=base.source_hashes(sources) + classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") + def java(side,mode,path): + run(["java","-Xmx1G","-cp",os.pathsep.join([str(classes),str(jars[side]),dependency_path]),"dev.horizonlab.parity.VanillaChunkStageOracle",mode,path],side+"-"+mode) + for side in jars:java(side,"export",build/f"facts-{side}.json") + facts=json.loads((build/"facts-server.json").read_text()) + if facts!=json.loads((build/"facts-client.json").read_text()):raise ValueError("client/server state facts differ") + if len(facts["states"])!=35723:raise ValueError("incomplete pinned state table") + fixtures=list(corpus(facts));inputs=build/"inputs.txt" + inputs.write_text("".join(json.dumps(value,separators=(",",":"))+"\n" for value in fixtures),encoding="utf-8") + (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") + fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] + tested_fixtures=base.source_hashes(fixture_paths) + run(["cargo","build","--release","-p","horizon-world","--example","chunk_stage_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("chunk_stage_fixture.exe" if os.name=="nt" else "chunk_stage_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + java(side,side,build) + reference=build/f"{side}.txt";matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} chunk-stage output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "block_states":len(facts["states"]),"block_tag_files":len(tags),"fixtures":len(fixtures),"operation_counts":dict(Counter(op[0] for fixture in fixtures for op in fixture["ops"])), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual ProtoChunk.setBlockState, direct section reads, heightmap presence/packed data and pre-light persisted-status assignments for empty, structure starts, structure references, biomes, terrain and features. Every pinned block state is inserted/removed under both heightmap groups. Forward/backward status assignments, untouched stale maps, missing-map priming, explicit priming, empty-section AIR writes, cave/void-air collapse, outside-height writes and wrapped X/Z coordinates are compared. Facts are independently exported from both authenticated JARs; block tags are resolved in Rust. This covers stage-dependent mutation and map selection, not the scheduler, persisted metadata, retro-generation, block entities, lighting, whole region behavior or a complete generated world."} + + lab.write_json(report_path,report);print(f"Scoped chunk-stage parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_client_graphics.py b/tools/test_client_graphics.py index 5db6a130a..a23040843 100644 --- a/tools/test_client_graphics.py +++ b/tools/test_client_graphics.py @@ -111,7 +111,7 @@ def main(): 'dev.horizonlab.metrics.ClientGraphicsIntegration', fixture_mixins=['GraphicsBackendTraceMixin'], fixture_dependencies={}) version = build_pack.read_lock()['pack_version'] - mod = root / 'dist' / f'horizon-lab-{version}.jar' + mod = root / 'dist' / f'horizon-{version}.jar' original_hash = hashlib.sha256(mod.read_bytes()).hexdigest() results = [] for profile in args.profile or (['cinematic'] if args.shaders else ['core-performance', 'm2-balanced']): diff --git a/tools/test_collision_parity.py b/tools/test_collision_parity.py new file mode 100644 index 000000000..3794fa642 --- /dev/null +++ b/tools/test_collision_parity.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Validate registry-backed cached collisions against the pinned vanilla binaries.""" +import argparse +import json +import os +from pathlib import Path +import platform +import subprocess +import tempfile + +try: + from . import lab, test_rust_parity +except ImportError: + import lab + import test_rust_parity + + +def counts(output): + marker = "HORIZON_COLLISION_RESULT " + found = [json.loads(line.split(marker, 1)[1]) for line in output.splitlines() if marker in line] + if len(found) != 1: + raise AssertionError(f"Missing collision counts: {found}") + result = found[0] + if result["registry_states"] != 35723 or result["cached_states"] + result["uncached_states"] != result["registry_states"] or result["queries"] != result["cached_states"] * 6 or result["unique_shapes"] <= 0: + raise AssertionError(f"Incomplete collision coverage: {result}") + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepare", action="store_true") + args = parser.parse_args() + directory = lab.LOCAL / "rust-collision-parity" + directory.mkdir(parents=True, exist_ok=True) + report_path = directory / "report.json" + report_path.unlink(missing_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = test_rust_parity.verify_artifacts() + base = Path(tempfile.mkdtemp(prefix="run-", dir=directory)) + oracle = lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java" + sources = [oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/collision_fixture.rs"] + tested_sources = test_rust_parity.source_hashes(sources) + classes = base / "classes" + classes.mkdir() + dependency_path = os.pathsep.join(map(str, libraries)) + test_rust_parity.run(["javac", "--release", "25", "-proc:none", "-cp", os.pathsep.join([str(jars["server"]), dependency_path]), "-d", str(classes), str(oracle)]) + def java(side, mode): + result = subprocess.run(["java", "-Xmx1G", "-cp", os.pathsep.join([str(classes), str(jars[side]), dependency_path]), "dev.horizonlab.parity.VanillaCollisionOracle", mode, str(base)], cwd=lab.ROOT, capture_output=True, text=True, timeout=300) + (base / f"{side}-{mode}.log").write_text(result.stdout + result.stderr, encoding="utf-8") + result.check_returncode() + return result.stdout + expected = counts(java("server", "generate")) + test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "collision_fixture"]) + metadata = json.loads(subprocess.check_output(["cargo", "metadata", "--no-deps", "--format-version", "1"], cwd=lab.ROOT, text=True)) + binary = Path(metadata["target_directory"]) / "release/examples" / ("collision_fixture.exe" if os.name == "nt" else "collision_fixture") + actual = counts(subprocess.check_output([str(binary), str(base)], cwd=lab.ROOT, text=True)) + if actual != expected: + raise AssertionError(f"Collision coverage differs: vanilla={expected}, Rust={actual}") + references = [] + for side, jar in jars.items(): + java(side, side) + reference = base / f"vanilla-{side}.txt" + matched = test_rust_parity.compare(reference, base / "rust.txt") + references.append({"side": side, "jar_sha256": lab.digest(jar, "sha256"), "output_sha256": lab.digest(reference, "sha256"), "matched_output_lines": matched, **expected}) + print(f"{side}: {matched:,} cached collision output lines match", flush=True) + test_rust_parity.ensure_sources_unchanged(sources, tested_sources) + report = {"schema": 1, "minecraft": lock["minecraft"]["version"], "manifest_sha1": lock["minecraft"]["manifest_sha1"], "platform": platform.platform(), + "java": subprocess.check_output(["java", "--version"], text=True).splitlines()[0], "rustc": subprocess.check_output(["rustc", "--version"], text=True).strip(), + "inputs_sha256": lab.digest(base / "inputs.txt", "sha256"), "rust_output_sha256": lab.digest(base / "rust.txt", "sha256"), "sources_sha256": tested_sources, "references": references, + "scope": "Pinned no-context cached collision branch only. Registry identity validation, resident section lookup, grids, discrete extrema including empty shapes, greedy boxes, bounds, translated collide, ray hits, closest points and moved cell lookup. Uncached states and entity-context behavior remain unsupported."} + lab.write_json(report_path, report) + lab.write_json(base / "report.json", report) + print(f"Cached collision comparison passed: {report_path}") + + +if __name__ == "__main__": + main() diff --git a/tools/test_culling_empty.py b/tools/test_culling_empty.py index fd278733b..d2bcbbc39 100644 --- a/tools/test_culling_empty.py +++ b/tools/test_culling_empty.py @@ -22,7 +22,7 @@ def main(): args = parser.parse_args() root = build_pack.ROOT fixture = build_mod.build_culling_empty_fixture() - mod = root / "dist" / f"horizon-lab-{build_pack.read_lock()['pack_version']}.jar" + mod = root / "dist" / f"horizon-{build_pack.read_lock()['pack_version']}.jar" results = [] for enabled in [False, True]: instance = root / ".local/runtime" / ("culling-empty-fixture-patched" if enabled else "culling-empty-fixture-upstream") diff --git a/tools/test_culling_rays.py b/tools/test_culling_rays.py index 2fc43ca29..b0dfba84b 100644 --- a/tools/test_culling_rays.py +++ b/tools/test_culling_rays.py @@ -56,7 +56,7 @@ def main(): args = parser.parse_args() root = build_pack.ROOT fixture = build_mod.build_integration_fixture("culling-rays", "dev.horizonlab.dispatch.CullingRayIntegration", ["entityculling"], ["CullingRayAccess"]) - mod = root / "dist" / f"horizon-lab-{build_pack.read_lock()['pack_version']}.jar" + mod = root / "dist" / f"horizon-{build_pack.read_lock()['pack_version']}.jar" original_sha256 = hashlib.sha256(mod.read_bytes()).hexdigest() results = [] for enabled in [False, True]: diff --git a/tools/test_decoration_parity.py b/tools/test_decoration_parity.py new file mode 100644 index 000000000..ea693b6a1 --- /dev/null +++ b/tools/test_decoration_parity.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Compare the feature branch of native chunk biome decoration.""" +import argparse +import itertools +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab, test_rust_parity as base, test_feature_sort_parity as sort +except ImportError: + import lab + import test_rust_parity as base + import test_feature_sort_parity as sort + + +def fixture(biomes, seed=0, mode=0, present=None): + count=max((v for b in biomes for s in b for v in s),default=-1)+1 + chains=[[],[{'type':'count','count':3},{'type':'in_square'}],[{'type':'count','count':3},{'type':'in_square'},{'type':'biome'}],[{'type':'biome'},{'type':'random_chance','chance':0.5},{'type':'count','count':2}]] + if present is None:present=list(range(len(biomes)+1)) + if not present:present=[len(biomes)] + return {'biomes':biomes,'placements':[chains[mode%len(chains)] for _ in range(count)],'palettes':[present[i%len(present):]+present[:i%len(present)] for i in range(9)],'seed':seed,'cx':0,'cz':0,'min':-64,'height':32,'biome_offset':0,'chunk_fail':-1,'notify_fail':-1,'query_fail':-1,'feature_fail':-1,'return_mode':0} + + +def corpus(resources): + graphs=[[],[[]],[[[],[],[]]],[[[0,1,2]]],[[[0,2]],[[1,2]]],[[[0],[],[1,2]],[[1],[],[2,3]]],[[[0,0]]],[[[0,1]],[[1,0]]],[[[0]],[[1]]],[[[],[2]],[[],[0,1]]],[[[0],[],[0]],[[1],[2],[3]]],[[[0]]+[[] for _ in range(12)]+[[1]],[[1]]]] + policies=[{}, {'feature_fail':0},{'feature_fail':3},{'query_fail':0},{'query_fail':2},{'chunk_fail':0},{'chunk_fail':4},{'notify_fail':0},{'notify_fail':2},{'return_mode':1},{'return_mode':2}] + for graph,mode,seed,policy in itertools.product(graphs,range(4),[0,-1,2**63-1],policies): + f=fixture(graph,seed,mode);f.update(policy) + f['cx']=[0,-1,1874999,134217728][mode];f['cz']=[0,-1875000,1,-134217729][mode] + f['min']=[-64,0,-2032,1968][mode];f['height']=[16,32,64,16][mode];f['biome_offset']=mode + yield f + # Resident palettes can contain only an excluded biome, only a neighbor's + # feature, or duplicates. Selection must retain global ordering and indices. + graph=[[[0,3]],[[1,3]],[[2,3]]] + for present in [[],[0],[1],[2],[0,2],[3],[0,0,3],[2,1,0]]: + for mode in range(4): + f=fixture(graph,-9223372036854775808,mode,present) + f['palettes']=[([3] if i!=8 else present or [3]) for i in range(9)] + yield f + names=sorted({name for steps in resources.values() for step in steps for name in step}) + if any(not isinstance(name,str) or name.startswith('#') for name in names):raise ValueError('unsupported fixture holder form') + identity={name:i for i,name in enumerate(names)} + biomes=[[[identity[name] for name in step] for step in steps] for steps in resources.values()] + rng=random.Random(8845) + for mode in range(4): + for selected in [list(range(len(biomes))),[],*[ [i] for i in range(len(biomes))],*[rng.sample(range(len(biomes)),rng.randrange(len(biomes)+1)) for _ in range(24)]]: + f=fixture(biomes,rng.randrange(-2**63,2**63),mode,selected) + f['cx']=rng.randrange(-1875000,1875000);f['cz']=rng.randrange(-1875000,1875000) + yield f + for _ in range(200): + # Shared order avoids cycles while exercising sparse high step indices. + biomes=[[[i for i in range(12) if rng.randrange(5)==0] for _ in range(rng.randrange(15))] for _ in range(rng.randrange(8))] + f=fixture(biomes,rng.randrange(-2**63,2**63),rng.randrange(4));f.update(rng.choice(policies));yield f + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--prepare',action='store_true');args=parser.parse_args() + build=lab.LOCAL/'rust-decoration-parity';build.mkdir(parents=True,exist_ok=True) + report_path=build/'report.json';report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + resources=sort.biome_features(jars['server']) + if len(resources)!=67 or resources!=sort.biome_features(jars['client']):raise ValueError('pinned biome feature resources differ') + oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationOracle.java';helper=oracle.with_name('VanillaPlacementOracle.java') + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_feature_sort_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/decoration_fixture.rs'] + tested_sources=base.source_hashes(sources) + fixtures=list(corpus(resources));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') + resource_path=build/'biome-features.json';resource_path.write_text(json.dumps(resources,separators=(',',':')),encoding='utf-8') + fixture_paths=[inputs,resource_path];tested_fixtures=base.source_hashes(fixture_paths) + classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,helper],'compile-java') + run(['cargo','build','--release','-p','horizon-world','--example','decoration_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) + binary=Path(metadata['target_directory'])/'release/examples'/('decoration_fixture.exe' if os.name=='nt' else 'decoration_fixture') + run([binary,build],'rust');references=[] + for side,jar in jars.items(): + run(['java','-Xmx768M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaDecorationOracle',side,build],side) + reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') + references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) + print(f'{side}: {matched:,} decoration output lines match Rust',flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={'schema':1,'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'fixtures':len(fixtures),'biomes':len(resources),'requested_decorations':len(fixtures)*2,'sources_sha256':tested_sources,'fixtures_sha256':tested_fixtures,'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references,'scope':'Actual ChunkGenerator.applyBiomeDecoration with structure generation disabled, native ProtoChunk biome palettes, native FeatureSorter and WorldgenRandom, and traced feature sinks. Nine-chunk query order, possible-biome intersection, sorted global feature indices, decoration/feature seeds, biome-check placement, repeated calls, ignored false results, progress markers and partial failures are compared. All 67 bundled biome feature lists participate with synthetic payloads. Rust owns immutable generation settings and delegates resident palette transport and feature callbacks. Structure decoration, complete registry/world region integration, all feature algorithms, crash-report formatting and full gameplay remain pending.'} + lab.write_json(report_path,report);print(f'Scoped decoration parity passed: {report_path}') + + +if __name__=='__main__':main() diff --git a/tools/test_decoration_region_parity.py b/tools/test_decoration_region_parity.py new file mode 100644 index 000000000..583545c25 --- /dev/null +++ b/tools/test_decoration_region_parity.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Compare biome decoration, resident biome zoom, feature writes and heightmaps.""" +import argparse +from collections import Counter +import json +import os +from pathlib import Path +import platform +import random +import subprocess + +try: + from . import lab, test_rust_parity as base, test_worldgen_parity as worldgen, test_feature_region_parity as region, test_decoration_parity as decoration +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + import test_feature_region_parity as region + import test_decoration_parity as decoration + + +def corpus(facts): + template=next(region.corpus(facts)) + biomes=[[[0],[1,2],[3,4,5]],[[0],[2],[3,5]],[[1],[2],[4,5]]] + chains=[ + [{'type':'count','count':2},{'type':'in_square'},{'type':'heightmap','heightmap':'MOTION_BLOCKING'},{'type':'biome'}], + [{'type':'count_on_every_layer','count':1},{'type':'offset','x':0,'y':1,'z':0},{'type':'biome'}], + [{'type':'biome'},{'type':'count','count':2},{'type':'heightmap','heightmap':'WORLD_SURFACE'},{'type':'offset','x':1,'y':0,'z':1}], + [{'type':'count','count':3},{'type':'in_square'},{'type':'heightmap','heightmap':'MOTION_BLOCKING'},{'type':'block_predicate_filter','predicate':{'type':'matching_biomes','biomes':['horizon:b0','horizon:b1']}},{'type':'biome'}], + [{'type':'biome'},{'type':'block_predicate_filter','predicate':{'type':'volume_match','min':[-1,0,-1],'max':[1,0,1],'match':{'type':'not','predicate':{'type':'matching_biomes','biomes':['horizon:b3']}}}}], + ] + for seed in [0,-1]: + for stage in ['empty','biomes','terrain']: + for fail in [-1,7]: + for reject in [0,3]: + for placement in chains: + for mixed in [False,True]: + f=decoration.fixture(biomes,seed,present=[0,1,2,3] if mixed else [0]) + f.update(features=template['features'],placements=[placement]*len(template['features']),min=-64,height=64,stage=stage,write_fail=fail,reject=reject) + yield f + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepare",action="store_true") + args=parser.parse_args() + build=lab.LOCAL/"rust-decoration-region-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + tags=worldgen.tag_resources(jars["server"]) + if not tags or tags!=worldgen.tag_resources(jars["client"]):raise ValueError("client/server block tags differ or are empty") + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationRegionOracle.java" + helper=oracle.with_name("VanillaHeightmapOracle.java") + placement_helper=oracle.with_name("VanillaPlacementOracle.java") + sources=[oracle,helper,placement_helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_feature_region_parity.py",lab.ROOT/"tools/test_decoration_parity.py",lab.ROOT/"tools/test_feature_sort_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", + lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/decoration_region_fixture.rs",lab.ROOT/"crates/horizon-world/examples/support/decoration_storage.rs"] + tested_sources=base.source_hashes(sources) + classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper,placement_helper],"compile-java") + def java(side,mode,path): + run(["java","-Xmx1G","-cp",os.pathsep.join([str(classes),str(jars[side]),dependency_path]),"dev.horizonlab.parity.VanillaDecorationRegionOracle",mode,path],side+"-"+mode) + for side in jars:java(side,"export",build/f"facts-{side}.json") + facts=json.loads((build/"facts-server.json").read_text()) + if facts!=json.loads((build/"facts-client.json").read_text()):raise ValueError("client/server state facts differ") + if len(facts["states"])!=35723:raise ValueError("incomplete pinned state table") + fixtures=list(corpus(facts));inputs=build/"inputs.txt" + inputs.write_text("".join(json.dumps(value,separators=(",",":"))+"\n" for value in fixtures),encoding="utf-8") + (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") + fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] + tested_fixtures=base.source_hashes(fixture_paths) + run(["cargo","build","--release","-p","horizon-world","--example","decoration_region_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("decoration_region_fixture.exe" if os.name=="nt" else "decoration_region_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + java(side,side,build) + reference=build/f"{side}.txt";matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} decoration-region output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "block_states":len(facts["states"]),"block_tag_files":len(tags),"fixtures":len(fixtures),"biome_zoom":True,"resident_chunks_per_fixture":9,"requested_decorations":len(fixtures)*2, + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual ChunkGenerator.applyBiomeDecoration with structures disabled executes three native basic features, configured fill-layer sequences, replacements and scattered ore into nine ProtoChunks. Biome palettes, native BiomeManager zoom, possible-biome selection, FeatureSorter order, WorldgenRandom seeding, biome filters, registry-bound matching-biome predicates, ordered volume predicates and graph composition share resident terrain. Both pre-light heightmap groups, mixed/uniform biome neighborhoods, count/square/heightmap/layered chains, repeated decoration, rejected writes and partial failures are compared. Ordered writes, current-feature markers, complete final raw sections and all heightmap presence/data are checked. Rust uses resident BiomeRegion and TerrainRegion with caller-owned biome membership/write effects. Actual WorldGenRegion write-zone policy, POIs, block entities, postprocessing, lighting, structures, remaining feature algorithms, complete noise-to-decoration lifecycle and gameplay remain pending."} + + + lab.write_json(report_path,report);print(f"Scoped decoration-region parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_density_parity.py b/tools/test_density_parity.py new file mode 100644 index 000000000..aeb319e0f --- /dev/null +++ b/tools/test_density_parity.py @@ -0,0 +1,1100 @@ +#!/usr/bin/env python3 +"""Compare 26.3 compiled density samplers with checksum-pinned vanilla JARs.""" +import argparse +from collections import Counter +import json +import math +import os +from pathlib import Path +import platform +import random +import struct +import subprocess + +try: + from . import lab, test_rust_parity +except ImportError: + import lab + import test_rust_parity + + +def number(value): + return struct.pack(">d", value).hex() + + +def corpus(): + rng = random.Random(0x484f52495a4f4e44454e53495459) + edges = [-2147483648, -2147483647, -65536, -64, -1, 0, 1, 64, 65536, 2147483646, 2147483647] + floats = ["00000000", "80000000", "00000001", "80000001", "3f000000", "bf000000", "3f800000", "bf800000", "7f7fffff", "ff7fffff", "7f800000", "ff800000", "7fc00000", "7fa00001"] + def probes(index, points=32, exact=False): + for value in edges: + yield f"query {index} {value} {value} {value}" + for _ in range(points): + position = [rng.choice(edges) if rng.randrange(3) == 0 else rng.randrange(-2**31, 2**31) for _ in range(3)] + yield f"query {index} " + " ".join(map(str, position)) + for iteration in range(5): + sizes = [rng.randrange(1, 5), rng.randrange(1, 9), rng.randrange(1, 5)] + minimum = [rng.choice(edges) for _ in range(3)] + steps = [rng.choice([1, 4, 16, 65536, 2147483647]) for _ in range(3)] + yield f"volume {index} " + " ".join(map(str, sizes+minimum+steps)) + f" {0 if exact else iteration % 3} {rng.randrange(-2**63, 2**63)} 2" + index = 0 + good_children = [] + all_children = [] + for value in floats + [f"{rng.getrandbits(32):08x}" for _ in range(64)]: + yield f"constant {value}" + yield from probes(index) + all_children.append(index) + good_children.append(index) + index += 1 + for scenario in range(1800): + axis, tiling = scenario % 3, (scenario // 3) % 3 + if scenario % 4 == 0: + start, end = rng.choice(edges), rng.choice(edges) + elif scenario % 4 == 1: + start, end = rng.randrange(-2**31, 2**31), rng.randrange(-2**31, 2**31) + else: + start, end = rng.randrange(-128, 128), rng.randrange(-128, 128) + if scenario % 37 == 0: + end = start + if scenario % 41 == 0: + start, end = 0, -1 # MIN / -1 overflow in repeating paths. + low, high = (rng.choice(floats) if scenario % 3 == 0 else f"{rng.getrandbits(32):08x}" for _ in range(2)) + yield f"gradient {axis} {tiling} {start} {end} {low} {high}" + for coordinate in [start, end, max(-2**31, start-1), min(2**31-1, end+1)]: + yield f"query {index} {coordinate} {coordinate} {coordinate}" + yield from probes(index) + all_children.append(index) + if tiling == 0 or start != end: + good_children.append(index) + index += 1 + scales = [0.0, -0.0, .001, -.001, .125, .5, 1.0, 4.0, 1e100, float("inf"), float("-inf"), float("nan")] + noise_children = [] + for scenario in range(240): + kind = ["perlin", "simplex", "smeared"][scenario % 3] + stream = ["legacy", "xoroshiro"][(scenario // 3) % 2] + scale = rng.choice(scales) + xz, y = (rng.choice(scales) if scenario % 3 == 0 else rng.uniform(-2, 2) for _ in range(2)) + noise_children.append(index) + yield f"noise {kind} {stream} {rng.randrange(-2**63, 2**63)} {number(scale)} {number(xz)} {number(y)}" + yield from probes(index) + good_children.append(index) + all_children.append(index) + index += 1 + nested = [] + for scenario in range(1200): + choices = all_children if scenario % 9 == 0 else good_children + choices = choices + [i for i, depth in nested if depth < 4] + x, y, z = (rng.choice(choices) for _ in range(3)) + if scenario % 2 == 0: + y = -1 + yield f"shift {scenario % 240} {x} {y} {z}" + yield from probes(index) + depth = 1 + max([d for i, d in nested if i in [x, y, z]], default=0) + nested.append((index, depth)) + index += 1 + unary_kinds = ["abs", "negate", "square", "cube", "sqrt", "reciprocal", "sign", "squeeze", "leaky", "add", "sub", "mul", "div", "min", "max", "clamp"] + arithmetic = [] + for scenario in range(2400): + kind = unary_kinds[scenario % len(unary_kinds)] + choices = all_children + [i for i, depth in nested if depth <= 2] + [i for i, depth in arithmetic if depth < 4] + child = rng.choice(choices) + a, b = (rng.choice(floats) if scenario % 3 == 0 else f"{rng.getrandbits(32):08x}" for _ in range(2)) + yield f"unary {kind} {child} {a} {b}" + yield from probes(index) + depth = 1 + max([d for i, d in arithmetic if i == child], default=0) + arithmetic.append((index, depth)) + index += 1 + binary = [] + for scenario in range(2400): + kind = ["add", "sub", "mul", "div", "min", "max"][scenario % 6] + choices = all_children + [i for i, depth in arithmetic if depth <= 2] + [i for i, depth in binary if depth < 4] + left, right = (rng.choice(choices) for _ in range(2)) + if scenario % 7 == 0: + left = scenario % len(floats) # Force scalar shortcuts and exceptional values. + bound = rng.choice(floats) if scenario % 3 == 0 else f"{rng.getrandbits(32):08x}" + yield f"binary {kind} {left} {right} {bound}" + yield from probes(index, exact=True) + depth = 1 + max([d for i, d in binary if i in [left, right]], default=0) + binary.append((index, depth)) + index += 1 + + selections = [] + for scenario in range(2400): + choices = all_children + [i for i, depth in arithmetic+binary+selections if depth < 3] + selected = rng.choice(choices) if scenario % 3 else scenario % len(floats) + if scenario % 2 == 0: + mode = (scenario // 2) % 2 + a, b = (rng.choice(floats) if scenario % 3 == 0 else f"{rng.getrandbits(32):08x}" for _ in range(2)) + inside, outside = (rng.choice(floats) if mode else str(rng.choice(choices)) for _ in range(2)) + yield f"choice {mode} {selected} {a} {b} {inside} {outside}" + children = [selected] + ([] if mode else [int(inside), int(outside)]) + else: + mode = (scenario // 2) % 3 + first = rng.choice(floats) if mode == 1 else str(rng.choice(choices)) + second = rng.choice(floats) if mode == 2 else str(rng.choice(choices)) + yield f"lerp {mode} {selected} {first} {second}" + children = [selected] + ([] if mode == 1 else [int(first)]) + ([] if mode == 2 else [int(second)]) + yield from probes(index, exact=True) + depth = 1 + max([d for i, d in arithmetic+binary+selections if i in children], default=0) + selections.append((index, depth)) + index += 1 + # Known failure nodes make skipped branches, bulk evaluation order and + # partial writes directly observable at scalar branch endpoints. + failure = index + yield "gradient 0 1 0 0 00000000 3f800000" + index += 1 + for zero in [0, 1, 6, 12]: + for operation in [f"binary mul {zero} {failure} 00000000", f"binary div {zero} {failure} 00000000", + f"choice 0 {zero} 00000000 3f800000 6 {failure}", f"choice 0 {zero} 00000000 3f800000 {failure} 6", + f"lerp 0 {zero} 6 {failure}", f"lerp 0 {zero} {failure} 6", + f"lerp 1 {zero} 80000000 {failure}", f"lerp 2 {zero} {failure} 80000000"]: + yield operation + yield from probes(index, points=1, exact=True) + index += 1 + for source in range(14): + for minimum, maximum in [("00000000", "3f800000"), ("80000000", "00000000"), ("7fc00000", "3f800000")]: + yield f"choice 1 {source} {minimum} {maximum} 80000000 3f800000" + yield from probes(index, points=1) # Constant-choice logical tails. + index += 1 + + interval_nodes = [] + for scenario in range(1000): + choices = all_children + [i for i, depth in arithmetic+binary+selections+interval_nodes if depth < 3] + source = rng.choice(choices) if scenario % 3 else scenario % len(floats) + mode = scenario % 2 + count = 1 if mode else rng.choice([0, 1, 2, 3, 4, 8, 16]) + thresholds = [rng.choice(floats) if scenario % 3 == 0 else f"{rng.getrandbits(32):08x}" for _ in range(count)] + branches = [rng.choice(choices) for _ in range(count+1)] + if scenario % 13 == 0: + branches[scenario % len(branches)] = failure + yield f"interval {mode} {source} {count} " + " ".join(thresholds + list(map(str, branches))) + yield from probes(index, exact=True) + depth = 1 + max([d for i, d in arithmetic+binary+selections+interval_nodes if i in [source]+branches], default=0) + interval_nodes.append((index, depth)) + index += 1 + + # Range propagation is independently checked on bit-pattern endpoints. + for a in floats: + for b in floats: + for mode in range(6): + yield f"bounds {mode} {a} {b} {a} {b} {a} {b}" + for scenario in range(24000): + values = [rng.choice(floats) if scenario % 3 == 0 else f"{rng.getrandbits(32):08x}" for _ in range(6)] + yield f"bounds {scenario % 6} " + " ".join(values) + + for scenario in range(32): + stream = ["legacy", "xoroshiro"][scenario % 2] + yield f"noise normal {stream} {rng.randrange(-2**63,2**63)} {number(0)} {number(.25)} {number(.125)}" + yield from probes(index) + index += 1 + for noise_id in range(272): + for kind in range(3): + yield f"offset {kind} {noise_id}" + yield from probes(index) + index += 1 + for scenario in range(192): + stream = ["legacy", "xoroshiro"][scenario % 2] + # The first cases include the actual overworld/nether and End parameters. + if scenario < 4: + parameters = [.25 if scenario < 2 else 1.0, .125 if scenario < 2 else 1.0, 80.0, 160.0, 8.0 if scenario < 2 else 4.0] + elif scenario % 3 == 0: + parameters = [rng.choice([0.0, -0.0, .001, .25, 1.0, -1.0, 1000.0, 1e100, float("inf")]), rng.choice([0.0, -0.0, .001, .125, 1.0, -1.0, 1000.0]), rng.choice([0.0, -0.0, 80.0, -80.0, 1e100, float("inf")]), rng.choice([160.0, -160.0, 1e100, float("inf")]), rng.choice([0.0, -0.0, 1.0, 4.0, 8.0, -8.0, 1e100])] + else: + parameters = [rng.uniform(.001,1000), rng.uniform(.001,1000), rng.uniform(.001,1000), rng.uniform(.001,1000), rng.uniform(1,8)] + yield f"blended {stream} {rng.randrange(-2**63,2**63)} " + " ".join(map(number,parameters)) + yield from probes(index, points=96, exact=True) + yield f"volume {index} 3 9 3 -32 -64 16 4 8 4 0 {scenario} 2" + index += 1 + for scenario in range(320): + point = [rng.choice(edges) if scenario % 2 == 0 else rng.randrange(-2**31,2**31) for _ in range(3)] + yield f"distance {scenario % 4} " + " ".join(map(str,point)) + yield f"query {index} " + " ".join(map(str,point)) + yield from probes(index) + index += 1 + for scenario in range(12000): + values = [rng.choice(floats) if scenario % 3 == 0 else f"{rng.getrandbits(32):08x}" for _ in range(3)] + yield "metric " + " ".join(values) + for stream in ["legacy", "xoroshiro"]: + for parameters in [[1,float("nan"),80,160,8], [1,1,80,float("nan"),8], [1,0,80,0,8], [1,1,80,160,float("nan")], [1,0,80,160,float("inf")]]: + yield f"blendfail {stream} -1 " + " ".join(map(number,parameters)) + for scenario in range(256): + stream = ["legacy", "xoroshiro"][scenario % 2] + octave = rng.choice([0,-1,-7,-15,-31,-63,-127,1]) + smear = rng.choice([0.0,-0.0,.125,1.0,-1.0,1000.0,1e100,float("inf"),float("nan")]) + amplitude = rng.choice([0.0,-0.0,1.0,-1.0,.9999847412109375,12.75,1e100,float("inf"),float("nan")]) + yield f"blendfbm {stream} {rng.randrange(-2**63,2**63)} {octave} {number(smear)} {number(amplitude)}" + + for scenario in range(192): + source = rng.choice(noise_children) if scenario % 4 == 1 else (rng.choice(all_children) if scenario % 4 else scenario % len(floats)) + yield f"counted {source}" + counted = index + index += 1 + # Some nested caches share a node; IDs remain distinct on every path. + if scenario % 3 == 0: + yield f"cache {scenario + 256} {counted}" + counted = index + index += 1 + yield f"cache {scenario} {counted}" + cached = index + index += 1 + for enabled in [0, 1]: + yield f"context {enabled}" + for point in [[0,0,0], [0,0,0], [2**26,4096,-2**26], [-17,-64,32], [-17,-64,32]]: + yield f"query {cached} " + " ".join(map(str,point)) + yield f"counts {scenario}" + for minimum in [[-17,-64,32], [-17,-64,32], [2147483647,-2147483648,0], [-17,-64,32]]: + yield f"volume {cached} 2 3 2 " + " ".join(map(str,minimum)) + f" 4 1 4 0 {scenario} 2" + yield f"counts {scenario}" + for offset in [[0,0,0],[0,0,0],[4,1,4],[1,0,0],[0,3,0]]: + point = [((a+b+2**31) % 2**32)-2**31 for a,b in zip(minimum,offset)] + yield f"query {cached} " + " ".join(map(str,point)) + yield f"counts {scenario}" + for scenario in range(10000): + sizes = [rng.randrange(1,9) for _ in range(3)] + minimum = [rng.choice(edges) for _ in range(3)] + steps = [rng.choice([1,4,16,65536,2147483647]) for _ in range(3)] + offsets = [rng.randrange(-1, sizes[i]+1)*steps[i] + (1 if scenario % 5 == 0 else 0) for i in range(3)] + point = [((a+b+2**31) % 2**32)-2**31 for a,b in zip(minimum,offsets)] + yield "lookup " + " ".join(map(str,sizes+minimum+steps+point)) + + sliced = [] + for scenario in range(384): + mode = (scenario // 8) % 4 + a, b = rng.choice(edges), rng.choice(edges) + # Force buffer tails on primitive inputs, and nested/cached graphs on + # exact buffers. IDs are never reused for different cached functions. + tails = scenario % 8 == 0 + choices = all_children + [i for i, depth in binary if depth < 3] + [i for i, depth in sliced if depth < 3] + source = scenario % len(floats) if tails else rng.choice(choices) + depth = 1 + max([d for i, d in sliced if i == source], default=0) + yield f"counted {source}" + child = index + counter = 192 + scenario + index += 1 + if scenario % 8 == 1: + yield f"cache {1024 + scenario} {child}" + child = index + index += 1 + yield f"slice {mode} {child} {a} {b}" + sampler = index + sliced.append((sampler, depth)) + index += 1 + for enabled in [0, 1]: + yield f"context {enabled}" + for command in probes(sampler, points=8, exact=not tails): + yield command + yield f"counts {counter}" + for match_minimum in [False, True]: + for match_size in [False, True]: + sizes = [2, 5, 3] + minimum = [-17, -64, 32] + fixed = [(mode, a)] if mode < 3 else [(0, a), (2, b)] + for axis, value in fixed: + sizes[axis] = 1 if match_size else sizes[axis] + minimum[axis] = value if match_minimum else (value ^ 1) + yield f"volume {sampler} " + " ".join(map(str, sizes+minimum+[4,8,16])) + f" {2 if tails else 0} {scenario} 2" + yield f"counts {counter}" + + for scenario in range(384): + xz = [1, 2, 3, 4, 7, 8, 16, 31][scenario % 8] + cell_y = [1, 2, 3, 4, 7, 8, 16, 31][(scenario // 8) % 8] + source = rng.choice(all_children + [i for i, d in binary if d < 3] + [i for i, d in sliced if d < 3]) + if scenario % 3 == 0: + source = rng.choice(noise_children) + elif scenario % 3 == 1: + source = (scenario // 3) % len(floats) + yield f"counted {source}" + counter = 576 + scenario + child = index + index += 1 + if scenario % 5 == 0: + yield f"cache {2048 + scenario} {child}" + child = index + index += 1 + yield f"interpolate {child} {xz} {cell_y}" + sampler = index + index += 1 + for enabled in [0, 1]: + yield f"context {enabled}" + for value in edges + [rng.randrange(-2**31, 2**31) for _ in range(8)]: + yield f"query {sampler} {value} {value} {value}" + yield f"counts {counter}" + for point in [[0,0,0],[-xz,-cell_y,xz],[xz,cell_y,-xz],[-1,-1,-1]]: + yield f"query {sampler} " + " ".join(map(str,point)) + yield f"counts {counter}" + for iteration in range(12): + sizes = [rng.randrange(1,6),rng.randrange(1,17),rng.randrange(1,6)] + minimum = [rng.choice([-2147479552,-65,-64,-33,-17,-1,0,1,16,32,2147479551]) for _ in range(3)] + steps = [1,1,1] if iteration < 4 else ([xz,cell_y,xz] if iteration < 8 else [2,3,4]) + if iteration in [4,5]: + minimum = [-xz,-cell_y,xz] + if iteration == 6: + sizes = [1,1,1] + minimum = [0,0,0] + steps = [1,1,1] + if iteration == 7: + sizes = [2,1,3] + minimum = [0,0,0] + steps = [xz,1,xz] + yield f"volume {sampler} " + " ".join(map(str,sizes+minimum+steps)) + f" {2 if scenario % 3 == 1 and scenario % 5 != 0 else 0} {scenario} 2" + yield f"counts {counter}" + + for scenario in range(384): + lower = [-128,-64,-63,0,64][scenario % 5] + height = [1,2,3,4,8,16,31][scenario % 7] + density = rng.choice(all_children) + if scenario % 2 == 0: + upper_bits = (floats + [struct.pack(">f",v).hex() for v in [-128,-64,-1,1,64,256,384,100.5]])[(scenario // 2) % 22] + upper_value = struct.unpack(">f",bytes.fromhex(upper_bits))[0] + if not (-512 <= upper_value <= 512): + density = 6 # Positive density makes extreme-height searches terminate immediately. + if scenario % 4 == 0: + height = 2147483647 + yield f"constant {upper_bits}" + else: + end = -64 if scenario % 17 == 0 else 64 + yield f"gradient {(scenario // 2) % 3} {(scenario // 6) % 3} -64 {end} c3000000 43800000" + upper = index + index += 1 + yield f"counted {density}" + density = index + index += 1 + yield f"counted {upper}" + upper = index + index += 1 + if scenario % 7 == 0: + yield f"cache {4096 + scenario} {density}" + density = index + index += 1 + mode = (scenario // 2) % 2 + yield f"surface {mode} {density} {upper} {lower} {height}" + sampler = index + index += 1 + for enabled in [0,1]: + yield f"context {enabled}" + for value in edges + [-129,-65,-63,63,127,128,255,256]: + yield f"query {sampler} {value} {value} {value}" + yield f"counts {960 + scenario * 2}" + yield f"counts {961 + scenario * 2}" + for iteration in range(6): + sizes = [rng.randrange(1,5),1 if iteration < 4 else 3,rng.randrange(1,5)] + minimum = [rng.choice(edges),0 if iteration % 2 else -64,rng.choice(edges)] + steps = [rng.choice([1,4,65536,2147483647]),8,rng.choice([1,4,65536,2147483647])] + yield f"volume {sampler} " + " ".join(map(str,sizes+minimum+steps)) + f" {iteration % 3} {scenario} 2" + yield f"counts {960 + scenario * 2}" + yield f"counts {961 + scenario * 2}" + + yield "context 0" + spline_index = 0 + for value in floats + [f"{rng.getrandbits(32):08x}" for _ in range(64)]: + yield f"spconstant {value}" + if math.isnan(struct.unpack(">f",bytes.fromhex(value))[0]): + yield f"spfail {spline_index}" + else: + yield f"spsampler {spline_index}" + yield from probes(index, points=8) + index += 1 + spline_index += 1 + for scenario in range(256): + sources = [rng.choice(all_children),rng.choice(noise_children),rng.choice(all_children)] + if scenario % 4 in [0,1]: + sources[0] = 12 if scenario % 4 == 0 else 4 + coordinates = [] + for source in sources: + yield f"counted {source}" + coordinates.append(index) + index += 1 + nodes = [] + for node in range(3): + coordinate = coordinates[0 if node == 2 or (node == 0 and scenario % 2 == 0) else node+1] + count = [1,2,3,8][(scenario+node) % 4] + locations = [float(i)-count*.5 for i in range(count)] + if scenario % 7 == 0: + locations = [struct.unpack(">f",bytes.fromhex(rng.choice(floats)))[0] for _ in locations] + elif scenario % 7 == 1: + locations = [0.0 for _ in locations] + fields = [] + for point, location in enumerate(locations): + derivative = rng.choice(floats) if scenario % 3 == 0 else struct.pack(">f",rng.uniform(-2,2)).hex() + value = rng.randrange(78) if node < 2 else rng.choice(nodes) + if node == 2 and point == count-1: + value = nodes[0] # Force repeated NaN coordinate reads in scalar queries. + fields += [struct.pack(">f",location).hex(),derivative,str(value)] + yield f"sppoints {coordinate} {count} " + " ".join(fields) + nodes.append(spline_index) + spline_index += 1 + yield f"spsampler {nodes[-1]}" + sampler = index + index += 1 + for enabled in [0,1]: + yield f"context {enabled}" + for command in probes(sampler, points=8, exact=True): + yield command + for counter in range(1728+scenario*3,1731+scenario*3): + yield f"counts {counter}" + + for spline in range(spline_index): + for scenario in range(16): + values = [rng.choice(floats) if scenario % 2 else struct.pack(">f",rng.uniform(-4,4)).hex() for _ in range(6)] + if scenario == 0: + values = ["ff800000","7f800000"] * 3 + if scenario == 1: + values = ["7fc00000"] * 6 + yield f"sprange {spline} " + " ".join(values) + + for scenario in range(128): + yield "greset" + for value in ["00000000","80000000","3f800000","bf800000","42000000",rng.choice(floats[:12])]: + yield f"gconst {value}" + yield f"ggradient {scenario % 3} {(scenario // 3) % 3} -64 {(-64 if scenario % 17 == 0 else 64)} bf800000 3f800000" + for slot, source in enumerate([rng.choice(noise_children),rng.choice(all_children)]): + yield f"counted {source}" + counted = index + index += 1 + yield f"gbind {counted} bf800000 3f800000 {(scenario+slot) % 8}" + yield "gcache 6" + yield "gcache 6" + yield "gsame 9 10" + yield "gcache 9" + yield f"gslice {0 if scenario % 2 else 2} {-17 if scenario % 3 else 0} 7" + yield f"gslice {2 if scenario % 2 else 0} {32 if scenario % 3 else 0} 12" + yield f"gunary {scenario % 9} 9" + yield f"gbinary {scenario % 6} {5 if scenario % 4 == 0 else 14} {5 if scenario % 4 == 1 else 8}" + yield "gclamp 15 bf800000 3f800000" + yield "gchoice 7 bf000000 3f000000 16 14" + yield f"glerp 16 {2 if scenario % 3 == 0 else 17} {5 if scenario % 3 == 1 else 14}" + yield "ginterp 18 4 8" + yield "gsurface 18 4 -64 8" + yield "gbinary 5 19 20" + yield "gcache 21" + yield "gbinary 0 22 11" + for node in range(24): + yield f"ginfo {node}" + yield "gtry 0 9" + for mode, roots in [(0,[5,6,13]),(1,[5,6,9,11,13,14,15,16,17,18,19,20,21,22,23])]: + for root in roots: + yield f"gcompile {mode} {root}" + sampler = index + index += 1 + for enabled in [0,1]: + yield f"context {enabled}" + for point in [[0,0,0],[-17,-64,32],[1,7,-1],[1,7,-1],[-2147483648,0,2147483647],[2147483647,-1,-2147483648]]: + yield f"query {sampler} " + " ".join(map(str,point)) + for counter in [2496+scenario*2,2497+scenario*2]: + yield f"counts {counter}" + for sizes, minimum, steps in [([2,5,3],[-17,-64,32],[1,1,1]),([2,5,3],[-16,-64,32],[4,8,4]),([1,3,1],[0,0,0],[1,1,1])]: + yield f"volume {sampler} " + " ".join(map(str,sizes+minimum+steps)) + f" {2 if root == 5 else 0} {scenario} 2" + for counter in [2496+scenario*2,2497+scenario*2]: + yield f"counts {counter}" + yield "gconst 7fc00000" + yield "gcache 24" + yield "gcache 25" + for root in [26,26,25]: + yield f"gtry 1 {root}" + yield "gtry 0 25" + yield "ginfo 24" + yield "ginfo 25" + yield "gconst 7fa00001" + yield "gsame 24 27" + yield "gconst 80000000" + yield "gsame 1 28" + yield "gsame 0 28" + yield f"gdistance {-2147483648 if scenario % 3 == 0 else -17} {scenario-64} {2147483647 if scenario % 3 == 1 else 32} {scenario % 4}" + yield f"ginterval 7 1 {floats[scenario % len(floats)]} 8 29" + thresholds = [[], ["00000000"], ["7fc00000"], ["80000000", "00000000", "7f800000"], ["3f800000", "bf800000", "7fc00000"]][scenario % 5] + branches = [29, 13, 7, 2][:len(thresholds)+1] + yield f"ginterval 8 {len(thresholds)} " + " ".join(thresholds + list(map(str,branches))) + yield "gcache 30" + yield "ginterval 9 1 00000000 30 29" + yield "ginterval 24 1 00000000 29 2" + yield "ginterval 7 1 7fc00000 8 29" + yield "ginterval 7 1 7fa00001 8 29" + yield "gsame 35 36" + yield "ginterval 7 1 00000000 8 29" + yield "ginterval 7 1 80000000 8 29" + yield "gsame 37 38" + yield "gcache 35" + yield "gcache 36" + yield "gtry 1 39" + yield "gtry 1 40" + yield "gbinary 0 37 37" + yield "gbinary 0 38 38" + yield "gsame 41 42" + yield "gcache 41" + yield "gcache 42" + yield "gtry 1 43" + yield "gtry 1 44" + for node in range(29,41): + yield f"ginfo {node}" + for mode, roots in [(0,[29,30,31,34]),(1,[29,30,31,32,33,34])]: + for root in roots: + yield f"gcompile {mode} {root}" + sampler = index + index += 1 + for enabled in [0,1]: + yield f"context {enabled}" + for point in [[0,0,0],[-17,-64,32],[1,7,-1],[-2147483648,0,2147483647],[2147483647,-1,-2147483648]]: + yield f"query {sampler} " + " ".join(map(str,point)) + for counter in [2496+scenario*2,2497+scenario*2]: + yield f"counts {counter}" + for sizes, minimum, steps in [([2,5,3],[-17,-64,32],[1,1,1]),([2,5,3],[-16,-64,32],[4,8,4])]: + yield f"volume {sampler} " + " ".join(map(str,sizes+minimum+steps)) + f" {2 if root == 29 else 0} {scenario} 2" + for counter in [2496+scenario*2,2497+scenario*2]: + yield f"counts {counter}" + for value in ["00000000", "80000000", "3f800000", "bf800000", "7fc00000", "7f800000"]: + yield f"gsconstant {value}" + for spline in [0,1,2,4,5]: + yield f"gspline {spline}" + # Shared and structurally equal coordinates, including zero-hash variants. + coordinate = [7,8,13][scenario % 3] + point_fields = [] + for point, location in enumerate(["bf800000", "00000000", "3f800000"]): + derivative = rng.choice(floats) if scenario % 4 == 0 else struct.pack(">f",rng.uniform(-2,2)).hex() + value = rng.randrange(6) if scenario % 4 == 0 else point % 4 + point_fields += [location, derivative, str(value)] + yield f"gspoints {coordinate} 3 " + " ".join(point_fields) + yield f"gspoints {[7,8,13][(scenario+1)%3]} 2 bf000000 00000000 6 3f000000 00000000 6" + yield f"gspoints {9 if scenario % 2 else 29} 3 bf800000 00000000 7 00000000 3f000000 6 3f800000 00000000 7" + for spline in [6,7,8,8]: + yield f"gspline {spline}" + yield "gsame 52 53" + yield f"gspoints {coordinate} 3 " + " ".join(point_fields) + yield "gspline 9" + yield "gsame 50 54" + for coordinate in [37,38]: + yield f"gspoints {coordinate} 2 bf800000 00000000 0 3f800000 00000000 2" + yield "gspline 10" + yield "gspline 11" + yield "gsame 55 56" + yield "gcache 55" + yield "gcache 56" + yield "gtry 1 57" + yield "gtry 1 58" + yield "gcache 52" + yield "gtry 1 59" + yield "gtry 1 59" + yield "gspoints 24 1 00000000 00000000 0" + yield "gspline 12" + yield "gspoints 48 1 00000000 00000000 0" + yield "gspline 13" + yield f"gbind {counted} 7fc00000 7fc00000 2" + yield "gspoints 62 1 00000000 00000000 12" + yield "gspline 14" + for node in range(45,64): + yield f"ginfo {node}" + for mode in [0,1]: + for root in [48,60,61,63]: + yield f"gtry {mode} {root}" + for mode, roots in [(0,[45,46,47,49,50,54,55,56]),(1,[45,46,47,49,50,51,52,53,54,55,56,57,58])]: + for root in roots: + yield f"gcompile {mode} {root}" + sampler = index + index += 1 + for enabled in [0,1]: + yield f"context {enabled}" + for point in [[0,0,0],[-17,-64,32],[1,7,-1],[1,7,-1],[-2147483648,0,2147483647],[2147483647,-1,-2147483648]]: + yield f"query {sampler} " + " ".join(map(str,point)) + for counter in [2496+scenario*2,2497+scenario*2]: + yield f"counts {counter}" + for sizes, minimum, steps in [([2,5,3],[-17,-64,32],[1,1,1]),([2,5,3],[-16,-64,32],[4,8,4]),([1,3,1],[0,0,0],[1,1,1])]: + yield f"volume {sampler} " + " ".join(map(str,sizes+minimum+steps)) + f" {2 if root in [45,46,47,49] else 0} {scenario} 2" + for counter in [2496+scenario*2,2497+scenario*2]: + yield f"counts {counter}" + + for scenario in range(64): + seed = [0, 1, -1, -9223372036854775808, 9223372036854775807][scenario % 5] if scenario < 10 else rng.randrange(-2**63,2**63) + yield f"gseed {seed} {scenario % 2}" + definitions = [ + ("horizon:primary", -7, 1.0, 4, scenario % 3, [1.0,0.0,-0.5,1.0] if scenario % 4 == 0 else []), + ("minecraft:nether/temperature", -7, 1.0, 4, 2, []), + ("minecraft:nether/vegetation", -8, 1.0, 4, 2, [1.0,0.0,0.5,1.0]), + ("horizon:empty", 0, 1.0, 0, 1, []), + ("horizon:secondary", -3, 0.75, 3, 0, [1.0,-0.5,0.0]), + ] + for name, base, amplitude, count, normalization, modifiers in definitions: + yield f"gregister {name} {base} {number(amplitude)} {count} {normalization} {len(modifiers)} " + " ".join(number(v) for v in modifiers) + yield "gready" + for noise in range(5): + yield f"ginstance {noise}" + for value in ["00000000", "80000000", "3f800000"]: + yield f"gconst {value}" + yield "ggradient 1 0 -64 320 bf800000 3f800000" + yield "ggradient 0 0 -32 32 bf800000 3f800000" + for kind in range(3): + yield f"goffset 0 {kind}" + yield "gcache 6" + yield f"gnoise 0 {number(.125)} {number(.25)} 0 0 0" + yield f"gnoise 0 {number(.125)} {number(.25)} 6 0 7" + yield f"gnoise 0 {number(.125)} {number(.25)} 6 1 7" + yield f"gnoise 0 {number(.125)} {number(.25)} 6 3 7" + yield f"gnoise 3 {number(1)} {number(0)} 0 0 0" + yield f"gnoise 1 {number(.25)} {number(0)} 0 0 0" + yield f"gnoise 2 {number(.25)} {number(0)} 0 0 0" + yield f"gnoise 4 {number(-0.0)} {number(0)} 0 0 0" + scale = [0.0, -0.0, .125, 1.0, float('inf'), float('nan'), -.5][scenario % 7] + yield f"gnoise 4 {number(scale)} {number(scale)} 4 3 2" + yield f"gnoise 0 {number(.125)} {number(.25)} 8 0 7" + yield "gcache 12" + parameters = [(.25,.125,80.,160.,8.), (.25,.375,80.,60.,8.), (.25,.25,80.,160.,4.)][scenario % 3] + yield "gblended " + " ".join(number(v) for v in parameters) + yield "gbinary 0 19 20" + yield "gsconstant 00000000" + yield "gsconstant 3f800000" + yield "gspoints 9 2 bf800000 00000000 0 3f800000 00000000 1" + yield "gspoints 12 2 bf800000 00000000 2 3f800000 00000000 2" + yield "gspline 3" + yield "ginterp 21 4 8" + yield "gcache 23" + yield "gclamp 22 bf800000 3f800000" + yield f"gnoise 0 {number(.125)} {number(.25)} 0 0 0" + yield "gsame 9 26" + yield f"gnoise 0 {number(.125)} {number(.25)} 1 0 0" + yield "goffset 3 1" + yield f"gnoise 4 {number(0)} {number(0)} 0 0 0" + yield "gend" + yield "gend" + yield "gsame 30 31" + yield "gcache 30" + yield "gbinary 0 30 12" + yield "gclamp 33 bf800000 3f800000" + yield "ginterp 33 4 8" + yield "gspoints 30 2 bf800000 00000000 0 3f800000 00000000 1" + yield "gspline 4" + yield "gsurface 33 2 -64 8" + for node in range(38): + yield f"ginfo {node}" + yield "gtry 0 8" + for mode, roots in [(0,[5,6,7,9,10,11,12,13,14,15,16,17,20,22,25,27,28,29,30,31,33,34,35,36,37]),(1,[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37])]: + for root in roots: + yield f"gcompile {mode} {root}" + sampler = index + index += 1 + for enabled in [0,1]: + yield f"context {enabled}" + points = [[0,0,0],[-17,-64,32],[1,7,-1],[1,7,-1],[-2147483648,0,2147483647],[2147483647,-1,-2147483648]] + if root >= 30: + points += [[1024,80,1024],[-1025,-64,1024],[2048,256,-4096]] + for point in points: + yield f"query {sampler} " + " ".join(map(str,point)) + volumes = [([2,5,3],[-17,-64,32],[1,1,1]),([2,5,3],[-16,-64,32],[4,8,4]),([1,3,1],[0,0,0],[1,1,1])] + if root >= 30: + volumes.append(([3,2,3],[1024,-64,1024],[16,64,16])) + for sizes, minimum, steps in volumes: + yield f"volume {sampler} " + " ".join(map(str,sizes+minimum+steps)) + f" 0 {scenario} 2" + for noise in range(5): + yield f"ginstance {noise}" + + for scenario in range(6): + yield f"gseed {-9223372036854775808 if scenario % 2 else 9223372036854775807} {scenario % 2}" + base, count = [(0,3), (1,1), (-1,8)][scenario // 2] + yield f"gregister minecraft:nether/temperature {base} {number(1)} {count} 1 0" + yield "gready" + yield "gconst 00000000" + yield f"gnoise 0 {number(.25)} {number(0)} 0 0 0" + yield "goffset 0 1" + yield "gcache 1" + for root in [1,2,3]: + yield f"ginfo {root}" + for mode in [0,1,1]: + yield f"gtry {mode} {root}" + + # Rounding is appended so the established corpus keeps its original inputs. + rounding_values = floats + ["3effffff","3f000001","beffffff","bf000001", + "3fbfffff","3fc00000","3fc00001","bfbfffff","bfc00000","bfc00001", + "4affffff","4b000000","4effffff","4f000000","ceffffff","cf000000"] + rounding_inputs = [] + for value in rounding_values: + yield f"constant {value}" + rounding_inputs.append(index) + index += 1 + multiples = [-1] + [rounding_inputs[i] for i in [0,1,2,4,5,6,7,10,11,12]] + for kind in range(4): + for input in rounding_inputs: + for multiple in multiples: + yield f"round {kind} {input} {multiple}" + yield f"query {index} -17 -64 32" + yield f"volume {index} 2 3 2 -17 -64 32 4 8 4 {2 if multiple < 0 else 0} {index} 2" + index += 1 + for scenario in range(256): + input = rng.choice(all_children) + multiple = -1 if scenario % 5 == 0 else rng.choice(all_children) + yield f"round {scenario % 4} {input} {multiple}" + yield from probes(index, points=8, exact=multiple >= 0) + index += 1 + + for scenario in range(64): + yield "greset" + for value in ["00000000","80000000","3f800000","bf800000","7fc00000","7f800000",rounding_values[scenario % len(rounding_values)]]: + yield f"gconst {value}" + yield "ggradient 1 0 -64 64 bf800000 3f800000" + for slot, source in enumerate([rng.choice(noise_children),rng.choice(all_children)]): + yield f"counted {source}" + counted = index + index += 1 + yield f"gbind {counted} bf800000 3f800000 {7 if slot == 0 else scenario % 8}" + yield "gcache 8" + for input, multiple, offset in [(8,2,0),(8,9,1),(7,0,2),(7,1,3),(9,6,0),(6,3,1),(10,9,2)]: + yield f"ground {(scenario+offset) % 4} {input} {multiple}" + yield "gcache 12" + yield f"ground {(scenario+3) % 4} 18 11" + yield f"ground {scenario % 4} 6 4" + yield f"ground {scenario % 4} 6 5" + yield f"gbind {rounding_inputs[6]} 3f800000 3f800000 0" + yield f"ground {scenario % 4} 9 22" + for node in range(24): + yield f"ginfo {node}" + for mode, roots in [(0,[11,12,13,14,15,16,20,21,23]),(1,list(range(11,22))+[23])]: + for root in roots: + yield f"gcompile {mode} {root}" + sampler = index + index += 1 + for enabled in [0,1]: + yield f"context {enabled}" + for point in [[0,0,0],[-17,-64,32],[1,7,-1],[-2147483648,0,2147483647],[2147483647,-1,-2147483648]]: + yield f"query {sampler} " + " ".join(map(str,point)) + for counter in [2752+scenario*2,2753+scenario*2]: + yield f"counts {counter}" + for sizes, minimum, steps in [([2,5,3],[-17,-64,32],[1,1,1]),([2,5,3],[-16,-64,32],[4,8,4])]: + yield f"volume {sampler} " + " ".join(map(str,sizes+minimum+steps)) + f" 0 {scenario} 2" + for counter in [2752+scenario*2,2753+scenario*2]: + yield f"counts {counter}" + yield "gcache 6" + yield f"ground {scenario % 4} 24 2" + for root in [24,25]: + for mode in [0,1,1]: + yield f"gtry {mode} {root}" + + for scenario in range(768): + child = rounding_inputs[scenario % len(rounding_inputs)] if scenario < 128 else rng.choice(all_children) + yield f"unary log {child} 00000000 00000000" + yield from probes(index, points=8) + index += 1 + + power_values = floats + ["40000000","c0000000","40400000","c0400000","3fc00000","bfc00000"] + for base in power_values: + for first in power_values: + for last in power_values: + yield f"bounds 2 {base} {base} {first} {last} 00000000 3f800000" + yield f"bounds 3 {first} {last} {base} {base} 00000000 3f800000" + + for scenario in range(64): + yield "greset" + for value in ["00000000","80000000","3f800000","bf800000","7fc00000","7f800000",rounding_values[scenario % len(rounding_values)]]: + yield f"gconst {value}" + yield "ggradient 1 0 -64 64 00000000 40800000" + yield "ggradient 0 0 -32 32 bf800000 3f800000" + yield f"counted {rng.choice(all_children)}" + counted = index + index += 1 + low, high = [("00000000","40800000"),("bf800000","3f800000"),("ff800000","7f800000"),("80000000","80000000"),("bf800000","bf000000"),("7fc00000","7fc00000")][scenario % 6] + yield f"gbind {counted} {low} {high} {scenario % 8}" + yield "gcache 9" + for kind, input in [(9,7),(10,7),(9,8),(10,8),(9,9),(10,9),(9,10),(10,10)]: + yield f"gunary {kind} {input}" + yield "gcache 11" + yield "gbinary 0 17 18" + yield "gclamp 20 bf800000 3f800000" + yield "ground 1 21 2" + yield "gcache 20" + yield "gunary 9 6" + yield "gunary 10 6" + yield "gunary 9 3" + for node in range(27): + yield f"ginfo {node}" + for mode, roots in [(0,[11,12,13,14,15,16,24,25,26]),(1,list(range(11,27)))]: + for root in roots: + yield f"gcompile {mode} {root}" + sampler = index + index += 1 + for enabled in [0,1]: + yield f"context {enabled}" + for point in [[0,0,0],[-17,-64,32],[1,7,-1],[-2147483648,0,2147483647],[2147483647,-1,-2147483648]]: + yield f"query {sampler} " + " ".join(map(str,point)) + yield f"counts {2880+scenario}" + for sizes, minimum, steps in [([2,5,3],[-17,-64,32],[1,1,1]),([2,5,3],[-16,-64,32],[4,8,4]),([1,3,1],[0,0,0],[1,1,1])]: + yield f"volume {sampler} " + " ".join(map(str,sizes+minimum+steps)) + f" 0 {scenario} 2" + yield f"counts {2880+scenario}" + + power_inputs = [] + for value in power_values: + yield f"constant {value}" + power_inputs.append(index) + index += 1 + for mode in range(3): + for base, base_bits in zip(power_inputs, power_values): + for exponent, exponent_bits in zip(power_inputs, power_values): + base_constant = number(struct.unpack(">f", bytes.fromhex(base_bits))[0]) + exponent_constant = number(struct.unpack(">f", bytes.fromhex(exponent_bits))[0]) + fields = [str(base),str(exponent)] if mode == 0 else [base_constant,str(exponent)] if mode == 1 else [str(base),exponent_constant] + yield f"power {mode} " + " ".join(fields) + yield f"query {index} -17 -64 32" + yield f"volume {index} 2 3 2 -17 -64 32 4 8 4 {0 if mode == 0 else 2} {index} 2" + index += 1 + for scenario in range(256): + mode = scenario % 3 + child = rng.choice(all_children) + constant = rng.choice(scales + [2.,-2.,3.,-3.,4.,-4.]) if scenario % 2 else struct.unpack(">d",rng.getrandbits(64).to_bytes(8,"big"))[0] + fields = [str(child),str(rng.choice(all_children))] if mode == 0 else [number(constant),str(child)] if mode == 1 else [str(child),number(constant)] + yield f"power {mode} " + " ".join(fields) + yield from probes(index, points=8, exact=mode == 0) + index += 1 + + for scenario in range(64): + yield "greset" + for value in ["00000000","80000000","3f800000","bf800000","3f000000","bf000000","40000000","c0000000","40400000","c0400000","40800000","c0800000","7fc00000","7f800000","ff800000",power_values[scenario % len(power_values)]]: + yield f"gconst {value}" + yield "ggradient 1 0 -64 64 bf800000 3f800000" + for slot, source in enumerate([rng.choice(noise_children),rng.choice(all_children)]): + yield f"counted {source}" + counted = index + index += 1 + yield f"gbind {counted} bf800000 3f800000 {7 if slot == 0 else scenario % 8}" + yield "gcache 17" + yield "gpow 17 18" + yield "gpow 15 18" + for exponent in [4,5,2,3,6,7,8,9,10,11,12,13,14,0,1]: + yield f"gpow 17 {exponent}" + yield "gpow 15 15" + yield "gpow 19 18" + yield "gpow 18 19" + yield "gcache 20" + yield "gpow 40 21" + yield "gclamp 41 bf800000 3f800000" + yield "ginterp 42 4 8" + yield "gsconstant 00000000" + yield "gsconstant 3f800000" + yield "gspoints 42 2 bf800000 00000000 0 3f800000 00000000 1" + yield "gspline 2" + yield "gsurface 42 2 -64 8" + yield "gpow 12 19" + yield "gcache 46" + for node in range(48): + yield f"ginfo {node}" + for mode, roots in [(0,list(range(20,38))),(1,list(range(20,47)))]: + for root in roots: + if root == 44 and power_values[scenario % len(power_values)] in ["7fc00000","7fa00001"]: + yield f"gtry {mode} {root}" + continue + yield f"gcompile {mode} {root}" + sampler = index + index += 1 + for enabled in [0,1]: + yield f"context {enabled}" + for point in [[0,0,0],[-17,-64,32],[1,7,-1],[-2147483648,0,2147483647],[2147483647,-1,-2147483648]]: + yield f"query {sampler} " + " ".join(map(str,point)) + for counter in [2944+scenario*2,2945+scenario*2]: + yield f"counts {counter}" + for sizes, minimum, steps in [([2,5,3],[-17,-64,32],[1,1,1]),([2,5,3],[-16,-64,32],[4,8,4])]: + yield f"volume {sampler} " + " ".join(map(str,sizes+minimum+steps)) + f" 0 {scenario} 2" + for counter in [2944+scenario*2,2945+scenario*2]: + yield f"counts {counter}" + for root in [46,47]: + for mode in [0,1,1]: + yield f"gtry {mode} {root}" + + + # Context fields are resolved at evaluation time. Deliberately bind values + # outside declared ranges and axes to retain vanilla's compiler behavior. + for scenario in range(16): + sources = [] + for field in range(3): + yield f"gradient {(scenario+field) % 3} {1 if scenario % 5 == 0 else 0} {-17 if scenario % 5 else 0} {32 if scenario % 5 else 0} {floats[(scenario+field) % len(floats)]} {floats[(scenario+field+5) % len(floats)]}" + source = index + index += 1 + yield f"counted {source}" + sources.append(index) + index += 1 + yield f"constant {floats[scenario % len(floats)]}" + fallback = index + index += 1 + roots = [] + for field in range(3): + for default in [-1, fallback]: + yield f"wfield {field} {default}" + roots.append(index) + index += 1 + for source in roots[:6]: + yield f"blenddensity {source}" + roots.append(index) + index += 1 + for slot, source in enumerate(roots[:6]): + yield f"cache {slot} {source}" + roots.append(index) + index += 1 + for root in roots: + for cached in [0,1]: + for blender in [0,1]: + for mask in [0,1,2,4,7]: + bindings = [str(sources[field] if mask & (1<f',progress).hex(),'noclip':noclip} + f={'state':state,'position':[-17,-64,30000000],'entity':'piston','piston':piston,'fail':-1} + yield f + if progress==0.5 and noclip==-1:yield dict(f,fail=1) + + +def collision_corpus(facts,states): + for fixture in corpus(facts,states): + yield fixture + yield dict(fixture,collision=True) + shulkers=[state for state in states if facts['states'][state]['id']=='minecraft:shulker_box'] + rng=random.Random(0x5348554c4b4552) + progress=[0.0,-0.0,1.0,0.1,0.2,0.3,0.5,0.7,0.9,struct.unpack('>f',bytes.fromhex('3f7fffff'))[0],struct.unpack('>f',bytes.fromhex('00000001'))[0]] + progress_pairs=[(old,current) for old in progress for current in progress] + progress_pairs.extend((rng.random(),rng.random()) for _ in range(2048)) + for state in shulkers: + for old,current in progress_pairs: + yield {'state':state,'position':[-17,2147483647,-33],'entity':'opened','fail':-1,'collision':True,'shulker_progress':[struct.pack('>f',v).hex() for v in [old,current]]} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--prepare',action='store_true');args=parser.parse_args() + build=lab.LOCAL/'rust-dynamic-support-parity';build.mkdir(parents=True,exist_ok=True) + report_path=build/'report.json';report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDynamicSupportOracle.java' + helpers=[oracle.with_name(name+'.java') for name in ['VanillaFaceSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle']] + sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/dynamic_support_fixture.rs'] + tested_sources=base.source_hashes(sources) + classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,*helpers],'compile-java') + def java(side,mode,path): + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaDynamicSupportOracle',mode,path],side+'-'+mode) + java('server','export',build) + facts=json.loads((build/'facts.json').read_text());states=json.loads((build/'uncached-states.json').read_text()) + if len(states)!=199:raise ValueError('incomplete uncached support registry') + fixtures=list(collision_corpus(facts,states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') + fixture_paths=[inputs,build/'facts.json',build/'uncached-states.json',build/'block-registry.nbt',build/'cached-collision.nbt'];tested_fixtures=base.source_hashes(fixture_paths) + run(['cargo','build','--release','-p','horizon-world','--example','dynamic_support_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) + binary=Path(metadata['target_directory'])/'release/examples'/('dynamic_support_fixture.exe' if os.name=='nt' else 'dynamic_support_fixture') + run([binary,build],'rust');references=[] + for side,jar in jars.items(): + java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') + references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) + print(f'{side}: {matched:,} dynamic-support output lines match Rust',flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={'schema':1,'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'uncached_states':len(states),'collision_fixtures':sum(bool(f.get('collision')) for f in fixtures),'shulker_progress_fixtures':sum('shulker_progress' in f for f in fixtures),'active_piston_fixtures':sum(f['entity']=='piston' for f in fixtures),'fixtures':len(fixtures),'sources_sha256':tested_sources,'fixtures_sha256':tested_fixtures,'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references,'scope':'Actual native support-shape and no-entity-context collision selection, block offsets and all support directions/types for the 199 uncached states. Bamboo, speleothem thickness/direction, scaffolding, powder snow and shulker support are compared over coordinate boundaries and privately allocated block-entity snapshots, including animation state, absent/wrong entity types and failures. Collision checks additionally cover exact shulker bounds and shape representation over progress interpolation boundaries and deterministic finite progress pairs. Moving-piston selection also delegates to actual native entity collision generation for active snapshots; Rust composes the independently tested piston algorithm with registry collision shapes across extension/retraction, source heads, progress boundaries, noclip directions and world-query failures. Entity lifecycle, ticking/pushing and full gameplay remain pending.'} + lab.write_json(report_path,report);print(f'Scoped dynamic-support parity passed: {report_path}') + + +if __name__=='__main__':main() diff --git a/tools/test_entity_obstruction_parity.py b/tools/test_entity_obstruction_parity.py new file mode 100644 index 000000000..9024ccb75 --- /dev/null +++ b/tools/test_entity_obstruction_parity.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Compare entity obstruction queries and shape intersection with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import subprocess +import random +import struct +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + def box(values):return [struct.pack('>d',float(v)).hex() for v in values] + def entity(bounds,building=True,removed=False,spectator=False,parent=-1): + return {'box':box(bounds),'building':building,'removed':removed,'spectator':spectator,'parent':parent} + unit=[0,0,0,1,1,1] + shapes=[[],[unit],[[0,0,0,1,0.5,1]],[[0,0,0,1,0.25,1],[0,0.75,0,1,1,1]],[[0,0,0,1e-8,1,1]],[[1,1,1,0,0,0]],[[2147483647,0,-2147483648,2147483648,1,-2147483647]]] + boxes=[unit,[0.2,0.4,0.2,0.8,0.6,0.8],[1,0,0,2,1,1],[0.5,0.5,0.5,0.5,0.75,0.75],[-1e-8,0,0,1e-8,1,1],[1-1e-8,0,0,2,1,1],[1-2e-7,0,0,2,1,1],[2,2,2,3,3,3],[2147483647,0,-2147483648,2147483648,1,-2147483647]] + variants=[[]] + for bounds in boxes: + for flags in range(8):variants.append([entity(bounds,bool(flags&1),bool(flags&2),bool(flags&4))]) + for parent in [-1,0]: + variants.append([entity(unit),entity(unit,parent=parent),entity([0.2,0.4,0.2,0.8,0.6,0.8],parent=1)]) + variants.append([entity(unit,False),entity(unit,parent=parent),entity(unit,removed=True,parent=1)]) + for shape in shapes: + for entities in variants: + for exclude in range(-1,len(entities)): + for fail in [False,True]:yield {'shape':[box(v) for v in shape],'entities':entities,'exclude':exclude,'fail':fail} + rng=random.Random(0x484f52495a4f4e) + extents=[-1.0,0.0,1e-8,1e-7,2e-7,0.125,0.5,1.0,2.0] + def random_box(): + low=[rng.choice([-2.0,-1e-8,0.0,0.5,1.0-1e-8,1.0,2.0]) for _ in range(3)] + return [*low,*[v+rng.choice(extents) for v in low]] + for index in range(3000): + shape=[box(random_box()) for _ in range(rng.randrange(1,5))] + entities=[entity(random_box(),rng.choice([True,True,False]),rng.randrange(4)==0,rng.randrange(4)==0,rng.randrange(-1,i) if i else -1) for i in range(rng.randrange(1,13))] + yield {'shape':shape,'entities':entities,'exclude':rng.randrange(-1,len(entities)),'fail':index%17==0} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--prepare',action='store_true');args=parser.parse_args() + build=lab.LOCAL/'rust-entity-obstruction-parity';build.mkdir(parents=True,exist_ok=True) + report_path=build/'report.json';report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityObstructionOracle.java' + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_obstruction_fixture.rs'] + tested_sources=base.source_hashes(sources) + classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle],'compile-java') + def java(side,mode,path): + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityObstructionOracle',mode,path],side+'-'+mode) + fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') + fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) + run(['cargo','build','--release','-p','horizon-world','--example','entity_obstruction_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) + binary=Path(metadata['target_directory'])/'release/examples'/('entity_obstruction_fixture.exe' if os.name=='nt' else 'entity_obstruction_fixture') + run([binary,build],'rust');references=[] + for side,jar in jars.items(): + java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') + references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) + print(f'{side}: {matched:,} entity-obstruction output lines match Rust',flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={'schema':1,'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'fixtures':len(fixtures),'sources_sha256':tested_sources,'fixtures_sha256':tested_fixtures,'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references,'scope':'Actual EntityGetter.isUnobstructed, its default non-spectator query, Entity removal/root-vehicle methods and voxel intersection execute over privately allocated entity snapshots. Empty shapes, excluded identities, spectators, removed/non-building entities, same-root vehicle exclusions, ordered broad-phase queries and selected candidates, thin boxes, boundary contacts, composite shapes and query failures are compared. Entity construction, lifecycle, spatial indexing, vehicle maintenance and full gameplay remain pending.'} + lab.write_json(report_path,report);print(f'Scoped entity-obstruction parity passed: {report_path}') + + +if __name__=='__main__':main() diff --git a/tools/test_face_support_parity.py b/tools/test_face_support_parity.py new file mode 100644 index 000000000..662504fec --- /dev/null +++ b/tools/test_face_support_parity.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Compare face slicing and support geometry with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import subprocess +import random +import struct +import math +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + def nums(v):return [struct.pack('>d',float(x)).hex() for x in v] + for cube in [False,True]: + for mask in range(256):yield {'coords':[nums([0,0.5,1])]*3,'cube':cube,'occupied':[bool(mask&(1<d", value).hex() + + +def numbers(values): + return " ".join(map(number, values)) + + +def corpus(): + rng = random.Random(0x484f52495a4f4e47454f) + special = [0.0, -0.0, 1.0, -1.0, 1e-7, -1e-7, + math.nextafter(1e-7, 0), math.nextafter(1e-7, math.inf), + 9.999999747378752e-6, math.nextafter(9.999999747378752e-6, 0), + float.fromhex("0x0.0000000000001p-1022"), 1e-200, 1e200, + float("inf"), float("-inf"), float("nan")] + def component(): + return rng.choice(special) if rng.randrange(5) == 0 else rng.uniform(-32, 32) + def vector(): + return [component() for _ in range(3)] + boundaries = [-1.0, -0.0, 0.0, 1e-8, .5, math.nextafter(1.0, 0.0), 1.0, math.nextafter(1.0, math.inf)] + for start in boundaries: + for end in boundaries: + for axes in range(1, 8): + a = [start if axes & (1 << i) else 0.0 for i in range(3)] + b = [end if axes & (1 << i) else 0.0 for i in range(3)] + yield "traverse " + numbers(a + b) + " 0" + for step in range(8000): + base = rng.choice([0, -30_000_000, 30_000_000, -2147483648, 2147483647]) + start = [base + rng.choice([rng.uniform(-4, 4), -1, 0, .5, 1]) for _ in range(3)] + end = [v + rng.choice([-16, -1, 0, 1, 16, rng.uniform(-16, 16)]) for v in start] + if step % 13 == 0: + end = start[:] + yield "traverse " + numbers(start + end) + f" {rng.choice([0, 1, 2, 3, 10, 1000])}" + yield "trig-table" + for step in range(16000): + angle = component() if step % 3 == 0 else rng.uniform(-100000, 100000) + pitch, yaw = rng.uniform(-90, 90), rng.uniform(-360, 360) + if step % 11 == 0: + pitch, yaw = rng.choice(special), rng.choice(special) + yield "rotation " + numbers(vector() + [angle, pitch, yaw]) + f" {rng.randrange(8)} {rng.randrange(3)} {rng.randrange(6)} " + number(component()) + for a in special: + for b in special: + yield "vec " + numbers([a, a, a, b, b, b, rng.choice(special)]) + for _ in range(7000): + a = vector() + b = a if rng.randrange(7) == 0 else vector() + yield "vec " + numbers(a + b + [component()]) + for _ in range(7000): + yield "box " + numbers(vector() + vector() + vector() + vector() + vector() + vector() + vector()) + f" {rng.randrange(3)} " + number(component()) + # Direct ray ties, strict endpoint exclusion, inside and epsilon thresholds. + for start, end in [([-1, -1, -1], [2, 2, 2]), ([2, 2, 2], [-1, -1, -1]), + ([-1, .5, .5], [0, .5, .5]), ([0, .5, .5], [1, .5, .5]), + ([.5, .5, .5], [2, .5, .5]), ([-1e-7, .5, .5], [1e-7, .5, .5])]: + yield "box " + numbers([0, 0, 0, 1, 1, 1] * 2 + start + end + [0, 0, 0]) + " 0 " + number(0) + integers = [-2147483648, -2147483647, -16, -1, 0, 1, 15, 16, 2147483646, 2147483647] + for a in integers: + for b in integers: + yield f"block-box {a} {b} {a} {b} {a} {b}" + shape_id = 0 + for scenario in range(180): + cube = scenario % 3 == 0 + sizes = [rng.randrange(1, 7) for _ in range(3)] if scenario else [0, 0, 0] + if scenario == 0: + cube = False + coords = [] + for size in sizes: + if cube: + coords.append([i / size for i in range(size + 1)]) + else: + coords.append(sorted(rng.sample(range(-16, 33), size + 1))) + coords[-1] = [v / 16 for v in coords[-1]] + if scenario == 1: + sizes = [1, 1, 1] + coords = [[0.0, 1.0] for _ in range(3)] + density = rng.choice([0, .15, .5, .85, 1]) if scenario != 1 else 1 + occupied = "".join("1" if rng.random() < density else "0" for _ in range(math.prod(sizes))) or "-" + yield f"grid {int(cube)} {' '.join(map(str, sizes))} " + numbers(sum(coords, [])) + " " + occupied + for step in range(250): + # Collision boxes lie outside, touch, or overlap individual boundaries. + lower, upper = [], [] + for axis in range(3): + edge = rng.choice(coords[axis]) + offset = rng.choice([0, 1e-7, -1e-7, 1e-8, -1e-8, .3, -.3, -1, 1]) + lower.append(edge + offset) + upper.append(edge + offset + rng.choice([0, 1e-8, 1e-7, .2, .6, 1.8])) + point = [rng.choice(coords[axis] + special + [rng.uniform(-3, 3)]) for axis in range(3)] + block = rng.choice([(0, 0, 0), (-17, -64, -1), (30_000_000, 64, -30_000_000)]) + start = [rng.uniform(-3, 3) + v for v in block] + end = [rng.uniform(-3, 3) + v for v in block] + if step % 13 == 0: + start = [.5 + v for v in block] + if step % 17 == 0: + end = start[:] + if step % 19 == 0: + end = [v + 1e-5 for v in start] + amount = rng.choice(special) if step % 4 == 0 else rng.uniform(-4, 4) + yield f"query {shape_id} " + numbers(lower + upper + start + end + point) + f" {' '.join(map(str, block))} {rng.randrange(3)} " + number(amount) + shape_id += 1 + for _ in range(2500): + count = rng.randrange(9) + selected = [rng.randrange(shape_id) for _ in range(count)] + yield "many " + numbers(vector() + vector()) + f" {rng.randrange(3)} " + number(component()) + f" {count}" + (" " + " ".join(map(str, selected)) if selected else "") + for step in range(12000): + count = rng.randrange(12) + selected = [rng.randrange(shape_id) for _ in range(count)] + movement = vector() if step % 3 == 0 else [rng.choice([0.0, -0.0, 1e-8, -1e-8, .3, -.3, 1.0, -1.0]) for _ in range(3)] + lower = [rng.choice([-1.0, -.6, -.5, -0.0, 0.0, .5, 1.0]) for _ in range(3)] if step % 4 else vector() + upper = [v + rng.choice([0.0, .6, 1.0, 1.8]) for v in lower] + max_step = rng.choice([0.0, -0.0, .5, .6, 1.0, 2.0, float("nan"), float("inf")]) + current_y = rng.choice([0.0, -0.0, -.5, .5, -.6, .6, float("nan")]) + yield "motion " + numbers(lower + upper + movement + [max_step, current_y]) + f" {count}" + (" " + " ".join(map(str, selected)) if selected else "") + epsilon_shapes = [] + for offset in [0.0, -0.0, 1e-8, -1e-8, 1e-7, math.nextafter(1e-7, 0), math.nextafter(1e-7, math.inf), -1e-7, 1.0-1e-7, 1.0, 1.0+1e-7, 2.0]: + epsilon_shapes.append(shape_id) + shape_id += 1 + yield "grid 0 1 1 1 " + numbers([offset, offset+1, 0, 1, 0, 1]) + " 1" + for first in epsilon_shapes: + for second in epsilon_shapes: + for operation in range(0, 16, 2): + yield f"join {first} {second} {operation}" + shape_id += 1 + # Joined shapes feed subsequent joins and collision queries. Sparse and empty + # results retain merged coordinate metadata, which affects later operations. + for step in range(4500): + first = rng.randrange(shape_id) + second = first if step % 7 == 0 else rng.randrange(shape_id) + operation = step % 16 + yield f"join {first} {second} {operation}" + if operation & 1: + continue + new_id = shape_id + shape_id += 1 + for axis in range(3): + lower = [rng.uniform(-2, 2) for _ in range(3)] + upper = [v + rng.choice([.2, .6, 1.8]) for v in lower] + start, end = [rng.uniform(-2, 2) for _ in range(3)], [rng.uniform(-2, 2) for _ in range(3)] + point = [rng.choice([0, .5, 1, rng.uniform(-2, 2), float("nan")]) for _ in range(3)] + yield f"query {new_id} " + numbers(lower + upper + start + end + point) + f" 0 0 0 {axis} " + number(rng.uniform(-3, 3)) + for step in range(600): + lower = [rng.choice([0, -0.0, -.5, .125, .25, .5, .875, 1, 1e-8, -1e-8, 1e-7, -1e-7]) for _ in range(3)] + upper = [v + rng.choice([0, 1e-8, 1e-7, math.nextafter(1e-7, math.inf), .125, .25, .5, 1, .3333333333333333]) for v in lower] + if step % 31 == 0: + lower, upper = [0.0] * 3, [1.0] * 3 + yield "make-box " + numbers(lower + upper) + shape_id += 1 + for step in range(1000): + first = rng.randrange(shape_id) + if step % 2: + second = rng.randrange(shape_id) + operation = (step // 2) % 16 + yield f"join-optimized {first} {second} {operation}" + if operation & 1: + continue + else: + yield f"optimize {first}" + new_id = shape_id + shape_id += 1 + lower, upper = [-.6, 0, .2], [-.2, 1.8, .8] + yield f"query {new_id} " + numbers(lower + upper + [-1, .5, .5, 2, .5, .5, .5, .5, .5]) + " 0 0 0 0 " + number(1) + + + yield from step_corpus(rng, shape_id, vector) + yield from sweep_corpus(rng, vector) + for _ in range(12000): + yield f"floor-height {rng.randrange(shape_id)} {rng.randrange(shape_id)}" + + +def sweep_corpus(rng, vector): + for step in range(2400): + base = rng.choice([-2147483648, -30000000, -17, -1, 0, 16, 30000000, 2147483640]) + a = [base + rng.randrange(4) for _ in range(3)] + b = [base + rng.randrange(7) for _ in range(3)] + direction = vector() if step % 5 == 0 else [rng.choice([-2, -1, -0.0, 0.0, 1, 2]) for _ in range(3)] + limit = rng.choice([0, 1, 3, 10, 1000]) + yield f"block-iterate {' '.join(map(str, a+b))} " + numbers(direction) + f" {limit}" + lower = [v + rng.choice([0.0, -0.0, .25, .5, .99999999]) for v in a] + upper = [v + rng.choice([0.0, .25, .6, 1.0, 1.8]) for v in lower] + yield "box-iterate " + numbers(lower + upper + direction) + f" {limit}" + float_epsilon = struct.unpack(">f", struct.pack(">f", 1e-5))[0] + epsilon = math.sqrt(struct.unpack(">f", struct.pack(">f", float_epsilon * float_epsilon))[0]) + for axis in range(3): + for sign in [-1, 1]: + for value in [epsilon, math.nextafter(epsilon, 0), math.nextafter(epsilon, math.inf)]: + end = [0.0] * 3 + end[axis] = sign * value + yield "sweep " + numbers([0.0] * 3 + end + [-1.0] * 3 + [1.0] * 3) + " 0" + for step in range(9000): + base = rng.choice([-30000000, -17, -1, 0, 16, 30000000]) + start = [base + rng.choice([-1.0, -0.0, 0.0, .5, 1.0, rng.uniform(-3, 3)]) for _ in range(3)] + delta = [rng.choice([-4, -1, -1e-5, -1e-8, -0.0, 0.0, 1e-8, 1e-5, 1, 4, rng.uniform(-5, 5)]) for _ in range(3)] + if step % 19 == 0: + delta = [rng.choice([0.0, 1e-200, epsilon, math.nextafter(epsilon, 0), math.nextafter(epsilon, math.inf)]), 0.0, 0.0] + end = [a+b for a, b in zip(start, delta)] + lower = [end[i] + rng.choice([-1.0, -.3, -0.0, 0.0]) for i in range(3)] + upper = [v + rng.choice([0.0, .3, .6, 1.0, 1.8, 2.0]) for v in lower] + yield "sweep " + numbers(start + end + lower + upper) + f" {rng.choice([0, 1, 2, 4, 10, 1000])}" + # Packed-position identity aliases Y every 4096 blocks. The initial loop + # still visits all cells; subsequent footprints use the packed dedup set. + for delta in [0.0, 1e-8, 1.0, -1.0]: + yield "sweep " + numbers([0, 0, 0, delta, 0, 0, delta, -2048, 0, delta+.3, 2048, .3]) + " 0" + + +def step_corpus(rng, shape_id, vector): + def selected(ids): + return str(len(ids)) + (" " + " ".join(map(str, ids)) if ids else "") + # Controlled shape selection invokes the real Entity.collide, including its + # second query. Ledges, floors and ceilings exercise success and failure. + ledges = [] + for height in [.125, .5, .6, 1.0, 1.5, math.nextafter(.5, 0), math.nextafter(.5, math.inf)]: + ledges.append(shape_id) + yield "grid 0 1 1 1 " + numbers([0, 1, 0, height, 0, 1]) + " 1" + shape_id += 1 + floor = shape_id + yield "grid 0 1 1 1 " + numbers([-8, 8, -1, 0, -8, 8]) + " 1" + shape_id += 1 + ceiling = shape_id + yield "grid 0 1 1 1 " + numbers([-8, 8, 2.1, 3, -8, 8]) + " 1" + shape_id += 1 + for ledge in ledges: + for height in [0.0, .5, .6, 1.0, 2.0]: + for y in [0.0, .2, 1.0]: + for dy in [0.0, -.1, -2.0, .1]: + for grounded in [0, 1]: + for overhang in [False, True]: + blocks = [floor, ledge] + ([ceiling] if overhang else []) + bounds = [-.6, y, .2, -.2, y+1.8, .8] + yield "step-motion " + numbers(bounds + [1.0, dy, 0.0, height]) + f" {grounded} 0 " + selected(blocks) + " " + selected(blocks) + " -1" + for step in range(16000): + def random_shapes(): + return [rng.randrange(shape_id) for _ in range(rng.randrange(9))] + entities, initial, stepping = random_shapes(), random_shapes(), random_shapes() + if step % 3 == 0: + initial = stepping = [floor, rng.choice(ledges)] + lower = [rng.choice([-1.0, -.6, -.5, -0.0, 0.0, .5, 1.0]) for _ in range(3)] + if step % 11 == 0: + lower = vector() + upper = [v + rng.choice([0.0, .6, 1.0, 1.8]) for v in lower] + movement = vector() if step % 4 == 0 else [rng.choice([0.0, -0.0, 1e-200, 1e-8, -1e-8, .3, -.3, 1.0, -1.0]) for _ in range(3)] + height = rng.choice([0.0, -0.0, -.6, .5, .6, 1.0, 2.0, float("nan"), float("inf")]) + border = rng.randrange(shape_id) if step % 5 == 0 else -1 + yield "step-motion " + numbers(lower + upper + movement + [height]) + f" {rng.randrange(2)} " + " ".join(map(selected, [entities, initial, stepping])) + f" {border}" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepare", action="store_true") + args = parser.parse_args() + directory = lab.LOCAL / "rust-geometry-parity" + directory.mkdir(parents=True, exist_ok=True) + report_path = directory / "report.json" + report_path.unlink(missing_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = test_rust_parity.verify_artifacts() + base = Path(tempfile.mkdtemp(prefix="run-", dir=directory)) + commands = list(corpus()) + inputs = base / "inputs.txt" + inputs.write_text("\n".join(commands) + "\n", encoding="utf-8") + oracle = lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGeometryOracle.java" + sources = [oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs"))] + tested_sources = test_rust_parity.source_hashes(sources) + classes = base / "classes" + classes.mkdir() + dependency_path = os.pathsep.join(map(str, libraries)) + test_rust_parity.run(["javac", "--release", "25", "-proc:none", "-cp", os.pathsep.join([str(jars["server"]), dependency_path]), "-d", str(classes), str(oracle)]) + test_rust_parity.run(["cargo", "build", "--release", "--bin", "horizon-geometry-parity"]) + metadata = json.loads(subprocess.check_output(["cargo", "metadata", "--no-deps", "--format-version", "1"], cwd=lab.ROOT, text=True)) + binary = Path(metadata["target_directory"]) / "release" / ("horizon-geometry-parity.exe" if os.name == "nt" else "horizon-geometry-parity") + candidate = base / "rust.txt" + with inputs.open("rb") as stdin, candidate.open("wb") as stdout: + test_rust_parity.run([str(binary)], stdin=stdin, stdout=stdout) + references = [] + for side, jar in jars.items(): + reference = base / f"vanilla-{side}.txt" + with (base / f"vanilla-{side}.log").open("wb") as log: + test_rust_parity.run(["java", "-Xmx512M", "-cp", os.pathsep.join([str(classes), str(jar), dependency_path]), "dev.horizonlab.parity.VanillaGeometryOracle", str(inputs), str(reference)], stdout=log, stderr=subprocess.STDOUT) + matched = test_rust_parity.compare(reference, candidate) + references.append({"side": side, "jar_sha256": lab.digest(jar, "sha256"), "output_sha256": lab.digest(reference, "sha256"), "matched_output_lines": matched}) + print(f"{side}: {matched:,} geometry output lines match", flush=True) + test_rust_parity.ensure_sources_unchanged(sources, tested_sources) + report = {"schema": 1, "minecraft": lock["minecraft"]["version"], "manifest_sha1": lock["minecraft"]["manifest_sha1"], "platform": platform.platform(), + "java": subprocess.check_output(["java", "--version"], text=True).splitlines()[0], "rustc": subprocess.check_output(["rustc", "--version"], text=True).strip(), + "commands": dict(Counter(command.split()[0] for command in commands)), "inputs_sha256": lab.digest(inputs, "sha256"), "rust_output_sha256": lab.digest(candidate, "sha256"), + "sources_sha256": tested_sources, "references": references, + "scope": "Selected Vec3/AABB operations, sine table entries, quantized trig, rotations and look directions; finite block-ray traversal; bounded inclusive/directional block iteration and finite swept-block visits with step indices; immutable cube/array voxel-grid bounds, column minima/maxima, greedy boxes, collide, ray hits, closest points and cell lookup; lazy floor-height selection; box quantization, optimized/unoptimized Boolean joins, alias identity and joinIsNotEmpty; Entity.collideWithShapes, candidate step heights and Entity.collide step-up decisions/query bounds with caller-controlled block/entity/border shape lists. No live entities, actual world shape selection, grounding/velocity side effects, fluids or block behavior."} + lab.write_json(report_path, report) + lab.write_json(base / "report.json", report) + print(f"Geometry comparison passed: {report_path}") + + +if __name__ == "__main__": + main() diff --git a/tools/test_height_provider_parity.py b/tools/test_height_provider_parity.py new file mode 100644 index 000000000..a14b7f8ca --- /dev/null +++ b/tools/test_height_provider_parity.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Compare anchored height-provider decoding and seeded samples with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def definitions(): + encode=lambda value:json.dumps(value,separators=(',',':')) + anchors=[{'absolute':-64},{'absolute':0},{'absolute':1},{'absolute':2031},{'above_bottom':8},{'below_top':1},{'relative_to_sea_level':-8}] + for value in [None,False,0,[],{},*anchors,{'absolute':2032},{'absolute':0,'above_bottom':1}]: + yield encode(value);yield encode({'type':'constant','value':value}) + for minimum in anchors: + for maximum in anchors: + for kind in ['uniform','biased_to_bottom','very_biased_to_bottom','trapezoid']: + yield encode({'type':kind,'min_inclusive':minimum,'max_inclusive':maximum}) + for kind in ['biased_to_bottom','very_biased_to_bottom','trapezoid']: + field='plateau' if kind=='trapezoid' else 'inner' + for token in ['null','false','"1"','{}','[]','-1','0','1','2','4','14','100','2147483647','-2147483648','4294967297','1e100']: + yield '{"type":"'+kind+'","min_inclusive":{"absolute":0},"max_inclusive":{"absolute":14},"'+field+'":'+token+'}' + yield '{"type":"uniform","absolute":5,"min_inclusive":{"absolute":0},"max_inclusive":{"absolute":1}}' + yield '{"type":"constant","value":{"absolute":0},"value":{"relative_to_sea_level":0}}' + yield '{"type":"trapezoid","min_inclusive":{"absolute":-7},"max_inclusive":{"absolute":7}}' + yield '{"type":":uniform","min_inclusive":{"above_bottom":8},"max_inclusive":{"below_top":1}}' + + + # Zero-weight entries remain part of declared bounds, but are never sampled. + constant = (lambda n: {'absolute': n}) if True else (lambda n: n) + weighted = lambda entries: {'type': 'weighted_list', 'distribution': entries} + entry = lambda value, weight: {'data': value, 'weight': weight} + choices = [constant(-7), constant(19), {'type': 'uniform', 'min_inclusive': constant(0), 'max_inclusive': constant(31)}] + for weights in [(1,), (0,), (0, 1), (1, 0), (1, 1), (1, 62), (1, 63), (1, 64), (0, 3, 7), (2147483647,), (2147483646, 1), (2147483647, 1), (-1, 2), (4294967297, 2), (0.9, 1.9)]: + value = weighted([entry(choices[i % len(choices)], weight) for i, weight in enumerate(weights)]) + yield encode(value) + nested = weighted([entry(constant(5), 1), entry(constant(-9), 4)]) + yield encode(weighted([entry(nested, 3), entry(choices[-1], 2)])) + for distribution in [None, {}, [], [entry(constant(0), 0), entry(constant(1), 0)], [entry(None, 0), entry(constant(1), 1)], [{'data': constant(1)}], [{'weight': 1}], [entry(constant(1), '1')], [entry(constant(1), None)]]: + yield encode(weighted(distribution)) + + +def corpus(): + definitions_list=list(definitions()) + contexts=[[-64,384,63],[0,128,32],[-2032,4064,0],[2**31-1,-2**31,2**31-1],[-2**31,2**31-1,-2**31]] + for legacy in [False,True]: + for seed in [0,-1,0x123456789abcdef]: + for context in contexts: + for definition in definitions_list:yield {'definition':definition,'context':context,'legacy':legacy,'seed':seed,'samples':32} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-height-provider-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightProviderOracle.java" + helper=oracle.with_name("VanillaAnchorOracle.java") + sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/height_provider_fixture.rs"] + tested_sources=base.source_hashes(sources) + fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") + run(["cargo","build","--release","-p","horizon-world","--example","height_provider_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("height_provider_fixture.exe" if os.name=="nt" else "height_provider_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaHeightProviderOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} height-provider output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"definitions":len(list(definitions())),"samples_per_valid_fixture":32, + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual HeightProvider.CODEC decoding and sampled heights with interleaved nextLong values, using actual WorldGenerationContext and all four vertical-anchor kinds. Covers constant, uniform, biased-to-bottom, very-biased-to-bottom trapezoid and weighted-list providers, both random modes, empty/equal ranges, inner/plateau defaults and bounds, numeric narrowing, relative coordinate overflow, malformed fields and anchor-versus-dispatch preference. Warning logs are excluded. Weighted lists include zero weights, singleton draws, nested providers, 63/64/65 weight totals, maximum/overflow totals and malformed entries; native constructor rejections count as decode errors. Encoding, cave/canyon paths and complete generation remain outside this scope."} + + lab.write_json(report_path,report);print(f"Scoped height-provider parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_heightmap_parity.py b/tools/test_heightmap_parity.py new file mode 100644 index 000000000..86368997c --- /dev/null +++ b/tools/test_heightmap_parity.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""Compare packed heightmaps with the pinned Java chunk and heightmap runtime.""" +import argparse +from collections import Counter +import json +import os +from pathlib import Path +import platform +import random +import subprocess + +try: + from . import lab, test_rust_parity as base, test_worldgen_parity as worldgen +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + + +def corpus(facts): + states, defaults = facts["states"], facts["defaults"] + air, stone = defaults["minecraft:air"], defaults["minecraft:stone"] + choices = [defaults["minecraft:"+name] for name in ["air", "cave_air", "void_air", "stone", "water", "lava", "oak_leaves", "oak_slab", "seagrass", "snow", "powder_snow", "glass", "barrier"]] + rng = random.Random(0x484f52495a4f4e484549474854) + def fixture(minimum, height, initial, ops, trace=False): + return {"min": minimum, "height": height, "initial": initial, "ops": ops, "trace": trace} + # Every state participates in insertion and removal, not just predicate export. + ops=[] + for state in range(len(states)): + ops.extend([["set", 4, 5, 7, state, 63], ["query", 4, 7], ["set", 4, 5, 7, air, 63]]) + yield fixture(0, 16, [], [*ops, ["dump"]]) + # Exercise section boundaries, the full codec height bound and all bit widths. + for minimum, height in [(-64,384),(0,256),(0,128),(-2032,4064),(2016,16),(-2032,16),(0,16),(0,32),(0,64),(0,512),(0,1024),(0,2032)]: + initial=[[x,minimum+(x*97+z*13)%height,z,choices[(x+z)%len(choices)]] for x in range(16) for z in range(16)] + ops=[["prime",63],["dump"]] + for x in range(16): + for z in range(16):ops.append(["query",x,z]) + for x,y,z,_ in initial:ops.extend([["set",x,y,z,air,63],["query",x,z]]) + ops.extend([["prime",63],["dump"]]) + yield fixture(minimum,height,initial,ops,height==16) + # Re-priming empty columns retains old values; invalid lengths take that path. + for height in [16,32,128,256,384,1024,2032]: + bits=height.bit_length();words=(256+(64//bits)-1)//(64//bits) + for fill in ["0","ffffffffffffffff","a55a00ff55ff00aa"]: + ops=[] + for t in range(6):ops.append(["raw",t,[fill]*words]) + ops.extend([["prime",0],["dump"],["prime",63],["dump"]]) + for t in range(6):ops.extend([["raw",t,[]],["raw",t,["0"]*(words+1)]]) + for x,z in [(0,0),(15,15),(16,0),(-1,1),(0,16),(-1,0),(2**31-1,2**31-1)]:ops.append(["query",x,z]) + ops.extend([["update",0,2**31-1,0,stone,0],["update",0,-2**31,0,air,0],["dump"]]) + yield fixture(0,height,[[2,height-1,3,stone]],ops,height==16 and fill=="a55a00ff55ff00aa") + # Mutation and raw edits interleave; repeated columns force downward rescans. + for scenario in range(64): + minimum,height=rng.choice([(-64,384),(0,16),(-16,32),(0,128)]) + initial=[] + for i in range(64):initial.append([rng.randrange(16),minimum+rng.randrange(height),rng.randrange(16),rng.choice(choices)]) + ops=[["prime",63]] + for i in range(192): + x,z=rng.choice([(0,0),(15,15),(3,9)]) + y=minimum+rng.choice([0,height-1,rng.randrange(height)]) + state=rng.choice(choices) if i%3 else rng.randrange(len(states)) + ops.extend([["set",x,y,z,state,63],["query",x,z]]) + if i%47==0:ops.extend([["prime",rng.randrange(64)],["dump"]]) + ops.extend([["prime",63],["dump"]]) + yield fixture(minimum,height,initial,ops,scenario<2) + # All-air sections collapse cave/void air to AIR when read through ProtoChunk. + for other in [air,stone]: + initial=[[2,7,3,defaults["minecraft:cave_air"]],[3,7,3,defaults["minecraft:void_air"]],[15,0,15,other]] + yield fixture(0,16,initial,[["prime",63],["query",2,3],["query",3,3],["dump"]],True) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepare",action="store_true") + args=parser.parse_args() + build=lab.LOCAL/"rust-heightmap-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + tags=worldgen.tag_resources(jars["server"]) + if not tags or tags!=worldgen.tag_resources(jars["client"]):raise ValueError("client/server block tags differ or are empty") + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java" + sources=[oracle,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", + lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/heightmap_fixture.rs"] + tested_sources=base.source_hashes(sources) + classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") + def java(side,mode,path): + run(["java","-Xmx1G","-cp",os.pathsep.join([str(classes),str(jars[side]),dependency_path]),"dev.horizonlab.parity.VanillaHeightmapOracle",mode,path],side+"-"+mode) + for side in jars:java(side,"export",build/f"facts-{side}.json") + facts=json.loads((build/"facts-server.json").read_text()) + if facts!=json.loads((build/"facts-client.json").read_text()):raise ValueError("client/server state facts differ") + if len(facts["states"])!=35723:raise ValueError("incomplete pinned state table") + fixtures=list(corpus(facts));inputs=build/"inputs.txt" + inputs.write_text("".join(json.dumps(value,separators=(",",":"))+"\n" for value in fixtures),encoding="utf-8") + (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") + fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] + tested_fixtures=base.source_hashes(fixture_paths) + run(["cargo","build","--release","-p","horizon-world","--example","heightmap_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("heightmap_fixture.exe" if os.name=="nt" else "heightmap_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + java(side,side,build) + reference=build/f"{side}.txt";matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} heightmap output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "block_states":len(facts["states"]),"block_tag_files":len(tags),"fixtures":len(fixtures),"operation_counts":dict(Counter(op[0] for fixture in fixtures for op in fixture["ops"])), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Six heightmap types, client/persistence flags and predicates for every pinned block state. Air/fluid facts are imported independently from both authenticated JARs and required to agree; block-tag membership is resolved in Rust from bundled resources. State behavioral methods are not ported by that import. Actual vanilla ProtoChunk and Heightmap APIs compare insertion/removal, downward rescans, repeated priming, empty-column retention, raw packed words including padding/unused slots, invalid-length fallback, wrapped column indexing, height queries, errors and selected exact block-read traces. Positive aligned vertical ranges are bounded to the NoiseSettings codec domain; arbitrary height accessors, chunk lifecycle integration, complete terrain/gameplay and rendering remain pending."} + lab.write_json(report_path,report);print(f"Scoped heightmap parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_material_condition_parity.py b/tools/test_material_condition_parity.py new file mode 100644 index 000000000..43e0fa48b --- /dev/null +++ b/tools/test_material_condition_parity.py @@ -0,0 +1,316 @@ +#!/usr/bin/env python3 +"""Compare numeric material conditions and cache transitions with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +import zipfile +try: + from . import lab,test_rust_parity as base,test_worldgen_parity as worldgen,test_biome_temperature_parity as biome +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + import test_biome_temperature_parity as biome + + +def corpus(): + rng=random.Random(0x484f52495a4f4e434f4e444954494f4e) + edges=[-2**31,-2032,-64,-21,-20,-5,-4,-3,-1,0,1,3,4,5,20,21,63,2031,2**31-1] + conditions=[["hole"],["steep"]] + for multiplier in [-2**31,-20,-1,0,1,20,2**31-1]: + for add in [False,True]: + for kind in range(4):conditions.append(["y",[kind,[-64,0,63,2**31-1][kind]],multiplier,add]) + conditions.append(["water",edges[(multiplier+3)%len(edges)],multiplier,add]) + for secondary in [-2**31,-100,-1,0,1,2,12,2**31-1]: + for add in [False,True]: + for ceiling in [False,True]:conditions.append(["stone",edges[(secondary+7)%len(edges)],add,secondary,ceiling]) + for name in ["bedrock_floor","minecraft:bedrock_floor",":bedrock_roof","horizon:test",""]: + for low,high in [([0,-64],[0,64]),([1,0],[1,5]),([2,5],[2,0]),([3,-5],[3,5]),([0,0],[0,0]),([0,64],[0,-64]),([0,-2**31],[0,2**31-1])]: + conditions.append(["gradient",name,low,high]) + conditions += [["not",["hole"]],["not",["not",["stone",0,True,12,False]]]] + secondary_bits=[0,0x80000000,1,0x80000001,0x3f000000,0xbf000000,0x3f800000,0xbf800000,0x40000000,0xc0000000,0x7f7fffff,0xff7fffff,0x7f800000,0xff800000,0x7fc00000]+[rng.getrandbits(32) for _ in range(81)] + seeds=[0,1,-1,-2**63,2**63-1]+[rng.randrange(-2**63,2**63) for _ in range(19)] + for fixture,seed in enumerate(seeds): + ops=[["eval"],["eval"],["secondary"]] + for i,bits in enumerate(secondary_bits): + depth=edges[(i+fixture)%len(edges)] + x,z=[rng.choice(edges) if i%3==0 else rng.randrange(-30000000,30000001) for _ in range(2)] + above,below,water=[rng.choice(edges) for _ in range(3)] + y=[-65,-64,-63,-1,0,1,62,63,64,65][i%10] if i%2 else rng.choice(edges) + ops += [["input",depth,f"{bits:x}"],["xz",x,z,edges[i%len(edges)],edges[(i+9)%len(edges)]],["y",above,below,water,y],["eval"],["eval"]] + # Changing source values alone does not invalidate cached results. + ops += [["input",depth^1,f"{secondary_bits[(i+7)%len(secondary_bits)]:x}"],["secondary"],["y",below,above,water,y],["eval"],["secondary"]] + if i%12==0: + ops += [["add",["not",["gradient","horizon:late",[0,-64],[0,64]]]],["eval"]] + for legacy in [False,True]: + yield {"seed":seed,"legacy":legacy,"context":[[-64,384,63],[0,256,32],[-2032,4064,0],[2**31-1,-2**31,-2**31]][fixture%4],"conditions":conditions,"ops":ops} + + +def condition_resources(jar): + prefix="data/minecraft/worldgen/material_condition/" + with zipfile.ZipFile(jar) as archive: + return {"minecraft:"+name[len(prefix):-5]:archive.read(name).decode("utf-8") for name in sorted(archive.namelist()) if name.startswith(prefix) and name.endswith(".json")} + + +def codec_corpus(definitions): + templates=[ + {"type":"hole"},{"type":"steep"},{"type":"temperature"}, + {"type":"biome","biome_is":["minecraft:plains"]}, + {"type":"noise_threshold","noise":"surface","min_threshold":-1.0,"max_threshold":1.0,"is_3d":False}, + {"type":"y_above","anchor":{"absolute":0},"surface_depth_multiplier":0,"add_stone_depth":False}, + {"type":"water","offset":0,"surface_depth_multiplier":0,"add_stone_depth":False}, + {"type":"stone_depth","offset":0,"add_surface_depth":False,"secondary_depth_range":0,"surface_type":"floor"}, + {"type":"vertical_gradient","random_name":"bedrock_floor","true_at_and_below":{"above_bottom":0},"false_at_and_above":{"above_bottom":5}}, + {"type":"not","invert":{"type":"hole"}}, + ] + cases=['null','false','0','[]','{}','"minecraft:unknown"'] + cases += list(definitions.values())+[json.dumps(name) for name in definitions] + cases += [json.dumps({"type":"not","invert":name}) for name in definitions] + tokens=['null','true','false','0','1','-1','-21','-20','20','21','2147483647','-2147483648','4294967296','4294967295','0.99','-0.99','1e100','1e1000','-1e1000','1e-100','""','"floor"','"ceiling"','"FLOOR"','"true"','"a:b:c"','[]','{}','{"absolute":0}','{"above_bottom":0,"below_top":0,"relative_to_sea_level":0}'] + for template in templates: + cases.append(json.dumps(template,separators=(",",":"))) + for key in template: + cases.append(json.dumps({k:v for k,v in template.items() if k!=key})) + for token in tokens: + fields=[json.dumps(k)+":"+(token if k==key else json.dumps(v,separators=(",",":"))) for k,v in template.items()] + cases.append("{"+",".join(fields)+"}") + for prefix in ["minecraft:",":","other:","Minecraft:"]: + cases.append(json.dumps(dict(template,type=prefix+template["type"]))) + cases.append(json.dumps(dict(template,unknown=[1,2,3]))) + cases += ['{"type":"hole","type":"steep"}','{"type":"hole","type":null}'] + base=next(corpus()) + for context in [[-64,384,63],[0,256,32],[-2032,4064,0],[2**31-1,-2**31,-2**31]]: + for legacy in [False,True]: + yield {"seed":-1,"legacy":legacy,"context":context,"conditions":[],"json":cases,"ops":base["ops"][:166]} + + +def rule_corpus(definitions): + rng=random.Random(0x484f52495a4f4e52554c45) + base=next(corpus()) + choices=base["conditions"]+[["json",json.dumps(name)] for name in sorted(definitions)] + def tree(depth): + kind=rng.randrange(4 if depth else 2) + if kind==0:return ["block",rng.randrange(10)] + if kind==1:return ["band"] + if kind==2:return ["if",rng.choice(choices),tree(depth-1)] + return ["sequence",[tree(depth-1) for _ in range(rng.randrange(4))]] + rules=[["block",i] for i in range(10)]+[["band"],["sequence",[]],["sequence",[["block",8]]],["sequence",[["sequence",[]]]]] + rules += [["if",c,["block",7]] for c in choices] + rules += [["sequence",[["block",8],["if",["stone",0,False,12,False],["block",7]],["band"]]], + ["sequence",[["if",["hole"],["block",0]],["if",["not",["hole"]],["band"]]]], + ["if",["stone",0,True,12,False],["sequence",[["if",["steep"],["block",1]],["block",9]]]]] + rules += [tree(3) for _ in range(48)] + edges=[-2**31,-1000,-193,-192,-65,-64,-1,0,1,63,64,191,192,319,2**31-1] + for fixture in range(12): + ops=[["apply",0,0,0],["apply",0,0,0]] + for i in range(64): + x,y,z=[rng.choice(edges) for _ in range(3)] + a,b,w=[rng.choice(edges) for _ in range(3)] + ops += [["input",[-1,0,1,4,12,2**31-1][i%6],["0","3f800000","bf800000","7f800000","7fc00000"][i%5]], + ["xz",x,z,[-5,-4,-3,0,3,4,5][i%7],[5,4,3,0,-3,-4,-5][i%7]],["y",a,b,w,y], + ["apply",x,y,z],["apply",x,y,z],["apply",z,edges[(i+7)%len(edges)],x]] + if i%16==0:ops += [["rule",tree(3)]] + for legacy in [False,True]: + yield {"seed":[0,1,-1,-2**63,2**63-1,987654321][fixture%6],"legacy":legacy,"context":[-64,384,63],"conditions":[],"rules":rules,"ops":ops} + + +def noise_corpus(noises): + import struct + bits=lambda value:struct.pack('>d',value).hex() + bounds=[(-1.,1.),(0.,0.),(-0.,0.),(1.,-1.),(float('-inf'),float('inf')),(float('nan'),1.),(-1.,float('nan'))] + conditions=[] + for name in ['surface','minecraft:surface',':surface_secondary','minecraft:clay_bands_offset']: + for is3d in [False,True]: + for low,high in bounds:conditions.append(['noise',name,bits(low),bits(high),is3d]) + conditions += [['not',c] for c in conditions[:14]] + random=__import__('random').Random(0x484f52495a4f4e4e4f495345) + noise_bits=[0,0x80000000,0x3f800000,0xbf800000,0x3f800001,0xbf800001,0x3f7fffff,0xbf7fffff,0x7f800000,0xff800000,0x7fc00000]+[random.getrandbits(32) for _ in range(85)] + edges=[-2**31,-1000,-64,-1,0,1,63,319,2**31-1] + for real in [False,True]: + selected=conditions if not real else [['noise',name,bits(-0.25),bits(0.25),is3d] for name in sorted(noises) for is3d in [False,True]] + for seed in [0,1,-1,-2**63,2**63-1,87654321]: + operations=[['eval'],['eval']] + for i,b in enumerate(noise_bits): + x,y,z=[random.choice(edges) for _ in range(3)] + operations += [['input',0,f'{b:x}'],['xz',x,z,0,0],['y',0,0,0,y],['eval'],['eval'],['input',0,f'{noise_bits[(i+7)%len(noise_bits)]:x}'],['eval'],['y',0,0,0,y],['eval'],['xz',x,z,0,0],['eval']] + if i%16==0:operations += [['add',selected[i%len(selected)]],['eval']] + for legacy in [False,True]: + yield {'seed':seed,'legacy':legacy,'context':[-64,384,63],'conditions':selected,'real_noise':real,'ops':operations} + + +def biome_corpus(biomes): + names=sorted(biomes) + conditions=[['temperature'],['not',['temperature']],['biome',[]],['biome',names]] + conditions += [['biome',[name]] for name in names] + conditions += [['not',['biome',[name]]] for name in names[::7]] + conditions += [['biome',['minecraft:plains','minecraft:plains','minecraft:desert']]] + choices=[None,[],['minecraft:plains'],['minecraft:desert'],['minecraft:plains','minecraft:desert'],names] + ops=[['eval'],['eval']] + for i,name in enumerate(names): + ops += [['biome',name],['xz',i*31,i*-17,(i%9)-4,4-(i%9)],['eval'],['y',0,0,0,[-64,0,63,80,81,120,319][i%7]],['eval'],['eval']] + if i%9==0:ops += [['add',['biome',[name]]],['eval']] + # Errors after a previous result preserve that result on a same-revision + # retry. Null biome results are queried again by uncached conditions. + ops += [['biome','#throw'],['y',0,0,0,0],['eval'],['eval'],['add',['biome',['minecraft:plains']]],['eval'],['eval'], + ['biome','minecraft:plains'],['eval'],['y',0,0,0,0],['eval'],['biome',None],['y',0,0,0,81],['eval'],['eval'], + ['biome','minecraft:desert'],['xz',7,9,0,0],['eval'],['y',0,0,0,81],['eval']] + for possible in choices: + for sea in [63,-1000,2**31-1]: + yield {'seed':0,'legacy':False,'context':[-64,384,sea],'possible_biomes':possible,'conditions':conditions,'ops':ops} + + +def biome_tag_resources(jar): + prefix='data/minecraft/tags/worldgen/biome/' + with zipfile.ZipFile(jar) as archive: + return {'minecraft:'+name[len(prefix):-5]:archive.read(name).decode('utf-8') for name in sorted(archive.namelist()) if name.startswith(prefix) and name.endswith('.json')} + + +def biome_tag_corpus(biomes,tags): + conditions=[['json',json.dumps({'type':'biome','biome_is':'#'+name})] for name in sorted(tags)] + conditions += [['not',c] for c in conditions[:8]] + invalid=[{'type':'biome','biome_is':value} for value in ['#minecraft:unknown','#',['#minecraft:is_badlands'],'##minecraft:is_badlands']] + aliases=[{'type':'biome','biome_is':'#'+name.removeprefix('minecraft:')} for name in sorted(tags)] + rules=[['sequence',[['if',c,['block',7]],['block',8]]] for c in conditions] + for possible in [None,[],['minecraft:plains'],['minecraft:badlands'],sorted(biomes)]: + ops=[['eval'],['eval']] + for i,name in enumerate(sorted(biomes)): + ops += [['biome',name],['xz',i,i*-3,0,0],['y',0,0,0,i],['eval'],['apply',i,i,i*-3]] + ops += [['biome','#throw'],['y',0,0,0,80],['eval'],['eval'],['biome',None],['y',0,0,0,81],['eval'],['eval'],['biome','minecraft:plains'],['eval']] + yield {'seed':0,'legacy':False,'context':[-64,384,63],'possible_biomes':possible,'conditions':conditions,'json':[json.dumps(v) for v in [*invalid,*aliases]],'rules':rules,'ops':ops} + + +def preliminary_corpus(): + def wrap(v): return (v+2**31)%2**32-2**31 + volumes=[[4,3,5,0,-64,0,1,1,1],[5,7,3,-17,32,19,4,8,4], + [1,1,1,1024,0,-1024,1,1,1],[4,2,4,2**31-2,1,-2**31,3,2,5]] + bit_values=['00000000','80000000','3f000000','bf000000','3f7fffff','bf800001','42810000', + 'c2810000','4effffff','4f000000','cf000000','cf000001','7f800000','ff800000','7fc00000','00000001','80000001'] + conditions=[['above'],['not',['above']],['not',['not',['above']]]] + rules=[['if',['above'],['block',7]],['sequence',[['if',['not',['above']],['block',8]],['block',9]]]] + for volume in volumes: + sx,_,sz,x,_,z,_,_,_=volume + for failure in [-1,0,1,3,19]: + for first in ['minimum','eval','apply']: + # Inside-plane allocation and failed retries, or initial scalar + # lookup before the first allocation, vary independently. + initial=[first] if first!='apply' else ['apply',0,200,0] + ops=[['density','42810000',failure],['input',3,'0'],['xz',x,z,0,0],initial,['minimum'],['eval'],['apply',7,11,13]] + ops += [['density','43400000',-1],['minimum'],['eval'],['y',0,0,0,80],['minimum'],['eval']] + for iz in range(sz): + for ix in range(sx): + ops += [['xz',wrap(x+ix),wrap(z+iz),0,0],['minimum'],['y',0,0,0,(ix+iz)*31-8],['eval'],['apply',-17,90,31]] + for i,bits in enumerate(bit_values): + depth=[-2**31,-9,0,3,8,2**31-1][i%6] + # Scalar fallback: floor/conversion, wrapping, cache reuse, + # failure after a previous successful minimum, and recovery. + ox,oz=wrap(x-1-i),wrap(z-1-i) + ops += [['density',bits,-1],['input',depth,'0'],['xz',ox,oz,0,0],['minimum']] + for y in [-2**31,-65,-8,-1,0,56,64,65,2**31-1]: + ops += [['y',0,0,0,y],['eval'],['apply',0,0,0]] + ops += [['density','0',0],['minimum'],['xz',ox,oz,0,0],['eval'],['minimum'],['eval'],['density',bits,-1],['minimum'],['xz',ox,oz,0,0],['minimum']] + ops += [['add',['above']],['eval']] + yield {'seed':failure,'legacy':first=='eval','context':[-64,384,63], 'volume':volume,'conditions':conditions,'rules':rules, + 'json':['{"type":"above_preliminary_surface"}','{"type":"minecraft:above_preliminary_surface","ignored":null}'], 'ops':ops} + # A scalar lookup outside the plane must not allocate or populate it. + yield {'seed':0,'legacy':False,'context':[-64,384,63],'volume':[2,1,2,10,0,10,1,1,1], + 'conditions':conditions,'rules':rules,'ops':[['density','42810000',-1],['minimum'],['density','43400000',-1],['xz',10,10,0,0],['minimum'],['xz',0,0,0,0],['minimum']]} + + +def ore_corpus(): + def wrap(v): return (v+2**31)%2**32-2**31 + rng=random.Random(0x484f52495a4f4e4f5245) + bits=['0','80000000','00000001','3e4ccccd','3f000000','3f333333','3f7fffff','3f800000', + '3f800001','bf800000','7f800000','ff800000','7fc00000'] + volumes=[[3,4,2,-1,-2,5,1,1,1],[3,2,3,-10,-5,-15,4,8,4],[2,2,2,2**31-1,-2**31,2**31-1,2,3,2]] + chances=['0','3ca3d70a','3f000000','3f800000','bf800000','7f800000','7fc00000'] + rules=[['ore',chance] for chance in chances] + rules += [['sequence',[['block',0],['ore','3f800000']]],['if',['not',['hole']],['ore','0']]] + for volume in volumes: + sx,sy,sz,x,y,z,dx,dy,dz=volume + positions=[[wrap(x+ix*dx),wrap(y+iy*dy),wrap(z+iz*dz)] for iz in range(sz) for ix in range(sx) for iy in range(sy)] + positions += [[wrap(x-1),y,z],[x,wrap(y-1),z],[x,y,wrap(z-1)],[wrap(x+1),wrap(y+1),wrap(z+1)]] + ops=[['apply',0,0,0]] + for i in range(180): + if iI",struct.pack(">f",value))[0]:x}' + triples=[['0','3f800000','0'],['3f800000','bf800000','3f800000'],['3f800000','0','3f800000'],['3f000000','3f000000','0'],['3f800000','3f800000','3f800000'],['7fc00000','3f800000','3f800000'],['3f800000','7fc00000','3f800000'],['3f800000','3f800000','7fc00000'],['7f800000','7f800000','0'],['7f800000','7f800000','7f800000'],['80000000','80000000','80000000']] + threshold=struct.unpack('>I',struct.pack('>f',1.8/15))[0] + triples += [[bits(1.0),f'{threshold+step:x}',bits(1.0)] for step in [-1,0,1]] + for i,triple in enumerate(triples): + for pattern in range(5): + for legacy in [False,True]: + name=sorted(biomes)[(i*5+pattern)%len(biomes)] + ops=[['badlands',17,-31,64,-64],['badlands',17,-31,64,-64],['frozen',17,-31,64,-64],['frozen',17,-31,64,-64],['frozen',-1000,3001,100,50]] + yield {'seed':-2**63 if legacy else 2**63-1,'legacy':legacy,'sea':[63,-17,127][pattern%3],'default':[3,8,3,8,4][pattern],'biome':name,'min':-64,'initial':column(pattern),'noise_bits':triple+triple,'limit':4096,'ops':ops} + for sea in [-2**31,2**31-1]: + yield {'seed':0,'legacy':False,'sea':sea,'default':3,'biome':sorted(biomes)[0],'min':-64,'initial':column(0),'noise_bits':['3f800000']*6,'limit':32,'ops':[['badlands',2**31-1,-2**31,2**31-1,-64],['frozen',2**31-1,-2**31,2**31-1,-64]]} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--prepare',action='store_true');args=parser.parse_args() + build=lab.LOCAL/'rust-material-extension-parity';build.mkdir(parents=True,exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + resources=worldgen.noise_resources(jars['server']) + if not resources or resources!=worldgen.noise_resources(jars['client']):raise ValueError('reference noise resources differ') + prefix='data/minecraft/worldgen/noise/';noises={'minecraft:'+name[len(prefix):-5]:raw for name,raw in resources.items()} + biomes=biome.biome_resources(jars['server']) + if not biomes or biomes!=biome.biome_resources(jars['client']):raise ValueError('reference biome resources differ') + for name,data in [('noises',noises),('biomes',biomes)]:(build/(name+'.json')).write_text(json.dumps(data,separators=(',',':')),encoding='utf-8') + folder=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[folder/(name+'.java') for name in ['VanillaMaterialExtensionOracle','VanillaBiomeTemperatureOracle']] + sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/material_extension_fixture.rs'] + tested_sources=base.source_hashes(sources);fixtures=list(corpus(biomes));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') + fixture_paths=[inputs,build/'noises.json',build/'biomes.json'];tested_fixtures=base.source_hashes(fixture_paths);classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependencies=os.pathsep.join(map(str,libraries)) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,*oracles],'compile-java') + run(['cargo','build','--release','-p','horizon-world','--example','material_extension_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('material_extension_fixture.exe' if os.name=='nt' else 'material_extension_fixture');run([binary,build],'rust');references=[] + for side,jar in jars.items(): + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]),'dev.horizonlab.parity.VanillaMaterialExtensionOracle',side,build],side) + reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt');references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched});print(f'{side}: {matched:,} material-extension output lines match Rust',flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={'schema':1,'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'fixtures':len(fixtures),'extension_calls':sum(len(f['ops']) for f in fixtures),'biome_resources':len(biomes),'noise_resources':len(noises),'constant_noise_fixtures':sum('noise_bits' in f for f in fixtures),'sources_sha256':tested_sources,'fixtures_sha256':tested_fixtures,'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references,'scope':'Actual private MaterialSystem erodedBadlandsExtension and frozenOceanExtension methods, with ordered noise-coordinate/block-read/block-write traces and complete resulting columns. Both positional random modes, actual seeded bundled noises, all biome climate settings, same-block identity across state properties, air variants, flowing water, waterlogged nonwater blocks, snow/ice thresholds, repeated calls and height clipping by supplied column providers. Constant overrides cover thresholds, signed zero, NaN/infinity, sea-level integer extremes and bounded provider read failures. Native exception class/message and full chunk/heightmap/postprocessing integration are not compared here. Rust caps extension loops to 1,048,576 iterations; oversized synthetic scans hit the fixture provider limit in both implementations. Full surface-stage and playable parity remain pending.'} + lab.write_json(report_path,report);print(f'Scoped material-extension parity passed: {report_path}') + + +if __name__=='__main__':main() diff --git a/tools/test_material_rule_library_parity.py b/tools/test_material_rule_library_parity.py new file mode 100644 index 000000000..b5f4dde58 --- /dev/null +++ b/tools/test_material_rule_library_parity.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Compare bundled material-rule loading and evaluation with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import subprocess +try: + from . import lab,test_rust_parity as base,test_worldgen_parity as worldgen,test_material_condition_parity as material,test_biome_temperature_parity as biome +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + import test_material_condition_parity as material + import test_biome_temperature_parity as biome + + +def codec_inputs(rules): + values=[json.loads(raw) for raw in rules.values()] + bases=[{'type':'block','result_state':'minecraft:stone'}, {'type':'sequence','sequence':[]}, {'type':'condition','if_true':{'type':'hole'},'then_run':{'type':'bandlands'}}, {'type':'ore_vein','ore_block':'minecraft:copper_ore','raw_ore_block':'minecraft:raw_copper_block','filler_block':'minecraft:granite','raw_ore_chance':0.02,'density':1,'richness':0.5,'filler_gap':-1}] + for base in bases: + values += [base,dict(base,ignored=None)] + for key in base: + missing=base.copy();del missing[key];values.append(missing) + for value in [None,[],False]:values.append(dict(base,**{key:value})) + values += [None,False,0,[],{},'minecraft:overworld',{'type':'bandlands'},{'type':'bandlands','unused':False},{'type':'condition','if_true':{'type':'hole'},'then_run':'minecraft:unknown'}, {'type':'block','result_state':{'id':'minecraft:water','properties':{'level':'+01'}}}, {'type':'block','result_state':{'id':'minecraft:oak_log','properties':{'axis':'invalid'}}}] + for chance in [-1,0,1,1.01,'0.02']: + values.append(dict(bases[-1],raw_ore_chance=chance)) + for field in ['density','richness','filler_gap']: + for value in ['minecraft:unknown',{'type':'minecraft:constant','argument':0},True,None]:values.append(dict(bases[-1],**{field:value})) + return [json.dumps(value,separators=(',',':')) for value in values] + + +def corpus(rules,biomes): + names=sorted(rules);biome_names=sorted(biomes) + for legacy in [False,True]: + for seed in [0,-1,87654321]: + for case in range(2): + ops=[] + for i,name in enumerate(biome_names): + for j,y in enumerate([-64,-48,-32,-8,-1,0,16,32,48,63,64,80,120,200,319]): + x=[0,1,-1,15,16,17,2**24+3,-2**24-3][(i+j)%8];z=(i%17)-8 + ops += [['biome',name],['input',[0,1,3,7][(i+j)%4],['0','3f000000','bf000000','3f800000'][(i+j)%4]],['xz',x,z,[-5,0,5][i%3],[-5,0,5][j%3]],['y',(j%6)+1,(i%8)+1,63 if j%2 else -2**31,y],['apply',x,y,z]] + if j%5==0:ops += [['apply',x+13,y-17,z+27]] + fixture={'seed':seed,'legacy':legacy,'context':[-64,384,63],'conditions':[],'real_noise':True,'library_rules':names,'volume':[3,4,3,0,-64,0,2,1,2] if case==0 else [4,8,2,-17,24,7,1,2,1], 'possible_biomes':None if case==0 else biome_names,'ops':ops} + if not legacy and seed==0 and case==0:fixture['library_json']=codec_inputs(rules) + yield fixture + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--prepare',action='store_true');args=parser.parse_args() + build=lab.LOCAL/'rust-material-rule-library-parity';build.mkdir(parents=True,exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + bundle={} + for field,kind in [('noises','noise'),('densities','density_function'),('rules','material_rule')]: + resources=worldgen.registry_resources(jars['server'],kind) + if not resources or resources!=worldgen.registry_resources(jars['client'],kind):raise ValueError('reference '+kind+' resources differ') + prefix='data/minecraft/worldgen/'+kind+'/' + bundle[field]={'minecraft:'+name[len(prefix):-5]:raw for name,raw in resources.items()} + for field,getter in [('conditions',material.condition_resources),('biomes',biome.biome_resources),('biome_tags',material.biome_tag_resources)]: + bundle[field]=getter(jars['server']) + if not bundle[field] or bundle[field]!=getter(jars['client']):raise ValueError('reference '+field+' resources differ') + counts={key:len(value) for key,value in bundle.items()} + bundle['rules'].update({'horizon:a_forward':'{"type":"condition","if_true":{"type":"hole"},"then_run":"horizon:z_leaf"}','horizon:z_leaf':'{"type":"block","result_state":{"id":"minecraft:oak_log","properties":{"axis":"x"}}}','horizon:empty':'{"type":"sequence","sequence":[]}','horizon:constant_ore':'{"type":"ore_vein","ore_block":"minecraft:copper_ore","raw_ore_block":"minecraft:raw_copper_block","filler_block":"minecraft:granite","raw_ore_chance":0.02,"density":1,"richness":0.5,"filler_gap":-1}'}) + for field,value in bundle.items():(build/(field+'.json')).write_text(json.dumps(value,separators=(',',':')),encoding='utf-8') + folder=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity' + oracles=[folder/(name+'.java') for name in ['VanillaMaterialConditionOracle','VanillaAnchorOracle','VanillaBiomeTemperatureOracle','VanillaBlockStateCodecOracle']] + sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_material_condition_parity.py','test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/material_condition_fixture.rs'] + tested_sources=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependencies=os.pathsep.join(map(str,libraries)) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,*oracles],'compile-java') + def java(side,oracle,mode,path):run(['java','-Xmx1G','-cp',os.pathsep.join([str(classes),str(jars[side]),dependencies]),'dev.horizonlab.parity.'+oracle,mode,path],side+'-'+mode) + for side in jars:java(side,'VanillaBlockStateCodecOracle','export',build/f'facts-{side}.json') + facts=json.loads((build/'facts-server.json').read_text()) + if facts!=json.loads((build/'facts-client.json').read_text()):raise ValueError('reference block metadata differs') + fixtures=list(corpus(bundle['rules'],bundle['biomes']));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') + fixture_paths=[inputs,build/'facts-client.json',build/'facts-server.json',*[build/(field+'.json') for field in bundle]];tested_fixtures=base.source_hashes(fixture_paths) + run(['cargo','build','--release','-p','horizon-world','--example','material_condition_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('material_condition_fixture.exe' if os.name=='nt' else 'material_condition_fixture') + run([binary,build],'rust');references=[] + for side,jar in jars.items(): + java(side,'VanillaMaterialConditionOracle',side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') + references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched});print(f'{side}: {matched:,} material-rule library output lines match Rust',flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={'schema':1,'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'resources':counts,'fixtures':len(fixtures),'codec_inputs':sum(len(f.get('library_json',[])) for f in fixtures),'rule_applications':sum(sum(op[0]=='apply' for op in f['ops'])*len(f['library_rules']) for f in fixtures),'sources_sha256':tested_sources,'fixtures_sha256':tested_fixtures,'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references,'scope':'All bundled material-rule definitions loaded against authenticated condition, biome/tag, block-state, noise and density registries, then compiled/evaluated for both world random modes. Forward/nested rule holders, all five rule kinds, malformed/omitted fields and property fallback, actual seeded density/richness/gap sources, strided chunk-volume caching, scalar fallback and independent context/application positions are covered. Surface depth and secondary noise remain supplied context inputs; preliminary density is zero for isolation. All bundled biome climates are used, with unrestricted or complete possible-biome sets. Rust library definitions are immutable and atomically loaded, with typed cycle/resource-bound errors. Rule/density encoding, live reload/registry owner validation, complete surface-stage chunks and gameplay remain pending.'} + lab.write_json(report_path,report);print(f'Scoped material-rule library parity passed: {report_path}') + + +if __name__=='__main__':main() diff --git a/tools/test_material_stage_parity.py b/tools/test_material_stage_parity.py new file mode 100644 index 000000000..8fbfdac5b --- /dev/null +++ b/tools/test_material_stage_parity.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Compare full surface-stage chunk application with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import subprocess +try: + from . import lab,test_rust_parity as base,test_worldgen_parity as worldgen,test_material_condition_parity as material,test_biome_temperature_parity as biome +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + import test_material_condition_parity as material + import test_biome_temperature_parity as biome + + +def synthetic_rules(): + block=lambda name:{'type':'block','result_state':'minecraft:'+name} + conditional=lambda condition,name:{'type':'condition','if_true':condition,'then_run':block(name)} + rules={'horizon:water':block('water'),'horizon:air':block('air'),'horizon:stone':block('stone')} + rules['horizon:probe']={'type':'sequence','sequence':[ + conditional({'type':'stone_depth','offset':0,'add_surface_depth':False,'secondary_depth_range':0,'surface_type':'ceiling'},'gravel'), + conditional({'type':'steep'},'air'), + conditional({'type':'water','offset':0,'surface_depth_multiplier':1,'add_stone_depth':True},'sand'), + conditional({'type':'stone_depth','offset':1,'add_surface_depth':True,'secondary_depth_range':4,'surface_type':'floor'},'dirt'),block('stone')]} + return {name:json.dumps(value,separators=(',',':')) for name,value in rules.items()} + + +def corpus(facts,biomes,settings=None,presets=None): + defaults=facts['defaults'];all_biomes=sorted(biomes) + scenes=[('overworld','stone',['minecraft:plains'],-64,256,63),('overworld','stone',['minecraft:eroded_badlands'],-64,256,63),('overworld','stone',['minecraft:frozen_ocean'],-64,256,63),('overworld','stone',['minecraft:deep_frozen_ocean','minecraft:eroded_badlands','minecraft:desert','minecraft:grove','minecraft:sulfur_caves'],-64,256,63),('overworld','stone',all_biomes,-64,256,63),('nether','netherrack',['minecraft:basalt_deltas','minecraft:crimson_forest','minecraft:soul_sand_valley','minecraft:nether_wastes','minecraft:warped_forest'],0,128,32),('end','end_stone',['minecraft:the_end','minecraft:end_highlands'],0,128,63)] + def initial(minimum,height,sea,default,pattern): + spans=[] + for x in range(16): + for z in range(16): + top=minimum+height//2+(x*7+z*11)%27-13 + spans.append([x,minimum,z,top,default]) + if topd", value).hex() + + +def numbers(values): + return " ".join(map(number, values)) + + +def corpus(): + rng = random.Random(0x484f52495a4f4e4e4f495345) + half = math.nextafter(2**24, 0) + specials = [0.0, -0.0, 1.0, -1.0, .5, -.5, 1e-7, -1e-7, + float.fromhex("0x0.0000000000001p-1022"), 1e-200, -1e-200, + 2**24, -(2**24), half, -half, math.nextafter(half, 0), + math.nextafter(-half, -math.inf), 2**25, -(2**25), + 2147483647.0, -2147483648.0, 1e100, -1e100, + float("inf"), float("-inf"), float("nan")] + for value in specials: + yield "wrap " + number(value) + for _ in range(12000): + yield "wrap " + (f"{rng.getrandbits(64):016x}" if rng.randrange(2) else number(rng.uniform(-1e10, 1e10))) + seeds = [-(2**63), -1, 0, 1, 2**63 - 1, *[rng.randrange(-2**63, 2**63) for _ in range(19)]] + scales = [0.0, -0.0, .001, .125, .5, 1.0, 4.0, -.125, -4.0, 1e-200, 1e200, math.inf, -math.inf, math.nan] + derivative_edges = ["00000000", "80000000", "3f800000", "bf800000", "7f800000", "ff800000", "7fc00000", "00000001", "7f7fffff"] + sampler_id = 0 + valid_bases = [] + invalid_ranges = [] + for stream, (kind, skip), scenario in itertools.product(["legacy", "xoroshiro"], [("perlin", 0), ("simplex", 0), ("simplex", 1), ("smeared", 0)], range(48)): + seed = seeds[scenario % len(seeds)] + scale = scales[scenario % len(scales)] + (invalid_ranges if kind == "smeared" and math.isnan(scale) else valid_bases).append(sampler_id) + yield f"create {kind} {stream} {seed} {skip} {number(scale)}" + for value in specials: + # Axis-specific extremes as well as all coordinates equal. + for axis in range(4): + coords = [value if i == axis or axis == 3 else 0.0 for i in range(3)] + yield f"query {sampler_id} " + numbers(coords) + " 00000000 80000000 3f800000" + for step in range(400): + if step % 5 == 0: + coords = [rng.choice(specials) for _ in range(3)] + elif step % 7 == 0: + value = rng.uniform(-2, 2) + coords = [value, value, value] # Ties in skipped-offset simplex. + else: + magnitude = rng.choice([1, 16, 10000, 30_000_000, 2**31, 1e100]) + coords = [rng.uniform(-magnitude, magnitude) for _ in range(3)] + initial = [rng.choice(derivative_edges) if step % 3 == 0 else f"{rng.getrandbits(32):08x}" for _ in range(3)] + yield f"query {sampler_id} " + numbers(coords) + " " + " ".join(initial) + local_edges = [-1.0, math.nextafter(-1.0, -math.inf), -0.0, 0.0, math.nextafter(0.0, math.inf), + .125, .5, math.nextafter(1.0, 0.0), 1.0, math.nextafter(1.0, math.inf)] + for x, y in itertools.product(local_edges, repeat=2): + yield f"local {sampler_id} " + numbers([x, y, x]) + " 00000000 80000000 3f800000" + if kind in ["perlin", "smeared", "simplex"]: + for step in range(32): + sizes = [rng.randrange(1, 6), rng.randrange(1, 17), rng.randrange(1, 6)] + steps = [rng.choice([1, 4, 16, 2147483647]) for _ in range(3)] + minimum = [rng.choice([-2147483648, 2147483647, -64, 0, 16]) for _ in range(3)] + xz_scale, y_scale = (rng.choice([0.0, -0.0, .001, -.001, .5, 1.0, 4.0, 1e100, math.inf, -math.inf, math.nan]) for _ in range(2)) + amplitude = rng.choice(derivative_edges) + seed = rng.randrange(-2**63, 2**63) + if step % 11 == 0: + sizes[step % 3] = 0 if step == 0 else -1 + if step % 13 == 0: + steps[step % 3] = 0 if step == 0 else -1 + yield f"volume {sampler_id} " + " ".join(map(str, sizes + minimum + steps)) + f" {numbers([xz_scale,y_scale])} {amplitude} {seed} {step % 4}" + sampler_id += 1 + stacks = [] + amplitudes = ["00000000", "80000000", "3f800000", "bf800000", "3e800000", "1e3ce508", "7f7fffff", "7f800000", "ff800000"] + for scenario in range(640): + layers = [] + layer_count = 0 + depth = 1 + for _ in range(scenario % 7): + eligible = [entry for entry in stacks if entry[1] <= 24 and entry[2] <= 3] + if eligible and rng.randrange(3) == 0: + selected, count, previous_depth = rng.choice(eligible) + flatten = rng.randrange(2) + depth = max(depth, previous_depth + (1 - flatten)) + layer_count += count if flatten else 1 + else: + selected, flatten = rng.choice(valid_bases), 0 + layer_count += 1 + frequency = rng.choice(specials) if scenario % 4 == 0 else rng.uniform(-8, 8) + # Keep generated success IDs stable: flattening 0 * infinity would + # itself create a NaN layer amplitude and reject the build. + amplitude = rng.choice(amplitudes[2:7] if flatten else amplitudes) + layers.extend([str(flatten), str(selected), number(frequency), amplitude]) + yield f"stack {scenario % 7} " + " ".join(layers) + stacks.append((sampler_id, layer_count, depth)) + for step in range(64): + point = [rng.choice(specials) if step % 5 == 0 else rng.uniform(-1000, 1000) for _ in range(3)] + yield f"query {sampler_id} " + numbers(point) + " 00000000 00000000 00000000" + for step in range(3): + scale = [rng.choice([0.0, .001, .5, -2.0, 1e100, math.inf, math.nan]) for _ in range(2)] + yield f"volume {sampler_id} 2 4 2 -17 -64 2147483647 4 1 16 " + numbers(scale) + f" {rng.choice(amplitudes)} {scenario} {step + 1}" + sampler_id += 1 + # Failed builds do not append a sampler. Zero amplitude does not bypass + # checking a layer's invalid range; NaN frequency is allowed instead. + if scenario % 16 == 0: + yield f"stack 1 0 {rng.choice(valid_bases)} {number(1.0)} 7fc00000" + yield f"stack 1 0 {rng.choice(invalid_ranges)} {number(1.0)} 00000000" + yield f"stack 1 0 0 {number(1.0)} 00000000" + yield f"stack 1 1 {sampler_id} {number(1.0)} 7f800000" # Flattened zero times infinity rejects. + yield f"stack 1 0 {sampler_id} {number(1.0)} 7f800000" # Nested range remains zero; samples are NaN. + yield f"query {sampler_id + 1} " + numbers([1.0, 2.0, 3.0]) + " 00000000 00000000 00000000" + bases = [-(2**31), 2**31-1, -1075, -1074, -1023, -1022, -32, -16, -8, 0, 16, 32, 1022, 1023, 1024] + base_amplitudes = [0.0, -0.0, 1.0, 2.0, .5, 1e-6, 1e-160, 1e160, 1e200, 1e-200, -1.0, math.inf, -math.inf, math.nan] + for scenario in range(1800): + parity = int(scenario % 5 == 0) + count = rng.choice([0, 1, 2, 3, 4, 8, 16, 32, 33, 64, -1]) + base = rng.choice(bases) if scenario % 3 == 0 else rng.randrange(-32, 33) + amplitude = rng.choice(base_amplitudes) if scenario % 3 == 0 else rng.uniform(.0001, 100) + normalization = scenario % 3 + if scenario >= 1400: + parity |= 2 + base = rng.choice([-64, -16, -8, -1, 0, 1, 2, 4]) + modifiers = [] + if parity & 1 or scenario % 4 != 0: + for _ in range(max(0, count)): + choices = [0.0, -0.0, 1.0, .5, -1.0, rng.uniform(0, 4), 1e-16, 1e16] + if scenario % 17 == 0: + choices.extend([1e200, 1e-200, math.inf, math.nan]) + modifiers.append(rng.choice(choices)) + if scenario % 31 == 0: + modifiers = [0.0] * max(0, count) + if scenario % 37 == 0 and not (parity & 1): + modifiers.append(1.0) # Also check the builder's modifier-index failure. + points = [[0, 0, 0], [-17.25, 64.125, 32.5], *[[rng.uniform(-1000, 1000) for _ in range(3)] for _ in range(16)]] + if scenario % 7 == 0: + points.extend([[value, value, value] for value in specials]) + for stream in ["legacy", "xoroshiro"]: + yield f"normal {stream} {seeds[scenario % len(seeds)]} {parity} {base} {count} {normalization} {number(amplitude)} {len(modifiers)} " + numbers(modifiers) + f" {len(points)} " + numbers(sum(points, [])) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepare", action="store_true") + args = parser.parse_args() + build = lab.LOCAL / "rust-noise-parity" + build.mkdir(parents=True, exist_ok=True) + report_path = build / "report.json" + report_path.unlink(missing_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = test_rust_parity.verify_artifacts() + commands = list(corpus()) + inputs = build / "inputs.txt" + inputs.write_text("\n".join(commands) + "\n", encoding="utf-8") + source = lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNoiseOracle.java" + sources = [source, Path(__file__), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "tools/lab.py", + *sorted((lab.ROOT / "crates/horizon-core").rglob("*.rs")), + lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock"] + tested_sources = test_rust_parity.source_hashes(sources) + classes = build / "classes" + classes.mkdir(exist_ok=True) + dependency_path = os.pathsep.join(map(str, libraries)) + run = test_rust_parity.run + run(["javac", "--release", str(lock["minecraft"]["java_major"]), "-proc:none", + "-cp", os.pathsep.join([str(jars["server"]), dependency_path]), "-d", str(classes), str(source)]) + run(["cargo", "build", "--release", "--bin", "horizon-noise-parity"]) + metadata = json.loads(subprocess.check_output(["cargo", "metadata", "--no-deps", "--format-version", "1"], cwd=lab.ROOT, text=True)) + binary = Path(metadata["target_directory"]) / "release" / ("horizon-noise-parity.exe" if os.name == "nt" else "horizon-noise-parity") + candidate = build / "rust.txt" + with inputs.open("rb") as stdin, candidate.open("wb") as stdout: + run([str(binary)], stdin=stdin, stdout=stdout) + references = [] + for side, jar in jars.items(): + reference = build / f"vanilla-{side}.txt" + run(["java", "-Xmx512M", "-cp", os.pathsep.join([str(classes), str(jar), dependency_path]), + "dev.horizonlab.parity.VanillaNoiseOracle", str(inputs), str(reference)]) + matched = test_rust_parity.compare(reference, candidate) + references.append({"side": side, "jar_sha256": lab.digest(jar, "sha256"), + "output_sha256": lab.digest(reference, "sha256"), "matched_output_lines": matched}) + print(f"{side}: {matched:,} noise output lines match Rust", flush=True) + test_rust_parity.ensure_sources_unchanged(sources, tested_sources) + report = {"schema": 1, "minecraft": lock["minecraft"]["version"], "platform": platform.platform(), + "java": subprocess.check_output(["java", "--version"], text=True).splitlines()[0], + "rustc": subprocess.check_output(["rustc", "--version"], text=True).strip(), + "manifest_sha1": lock["minecraft"]["manifest_sha1"], "commands": dict(Counter(line.split()[0] for line in commands)), + "inputs_sha256": lab.digest(inputs, "sha256"), "rust_output_sha256": lab.digest(candidate, "sha256"), + "sources_sha256": tested_sources, "references": references, + "scope": "26.3 gradient offsets, permutation tables, constructor RNG consumption, ranges, coordinate wrap, Perlin 2D/3D and derivative accumulation, simplex 2D/3D with both offset modes, smeared Perlin 2D/3D and inherited unsmeared derivatives; bounded strided density volumes, wrapped block coordinates, flat indices, cached and scalar bulk accumulation with preserved buffer tails; nested and flattened noise stacks; normal-noise octave construction, enabled/disabled/legacy normalization, parity factory, modern positional seeding, legacy Nether biome initialization, failure draw state, scalar and bulk sampling. Finite outputs and signed zeros compared by bits; NaNs canonicalized. No serialized noise definitions, density-function graphs, generated terrain, gameplay, rendering or performance claim."} + lab.write_json(report_path, report) + print(f"Scoped noise parity passed: {report_path}") + + +if __name__ == "__main__": + main() diff --git a/tools/test_piston_shape_parity.py b/tools/test_piston_shape_parity.py new file mode 100644 index 000000000..aca667fe5 --- /dev/null +++ b/tools/test_piston_shape_parity.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Compare moving-piston collision shapes and interpolation with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import subprocess +import random +import struct +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(facts): + def bits(value):return struct.pack('>f',float(value)).hex() + steps=[bits(v) for v in [-1,-0.0,0,0.25,0.5,0.75,1,2]]+['3e7fffff','3e800001','3f3fffff','3f400001'] + positions=[[0,0,0],[-17,-64,30000000],[2147483647,-2147483648,-2147483648]] + partials=[bits(v) for v in [-1,0,0.5,1,2]]+['7fc00001','7f800000','ff800000'] + def fixture(state,index=0,**kwargs): + result={'state':state,'position':positions[index%3],'direction':index%6,'extending':index%2==0,'source':False,'progress':steps[index%len(steps)],'previous':bits(0.25),'partial':partials[index%len(partials)],'noclip':-1,'fail':-1,'kinematic':False};result.update(kwargs);return result + for state in range(len(facts['states'])):yield fixture(state,state) + for state,value in enumerate(facts['states']): + if value['id'] in ['minecraft:piston','minecraft:sticky_piston']: + for direction in range(6): + for extending in [False,True]: + for source in [False,True]: + for progress in steps: + for noclip in range(-1,6):yield fixture(state,direction,extending=extending,source=source,progress=progress,noclip=noclip) + if value['id'].endswith('shulker_box') or value['id']=='minecraft:moving_piston': + for extending in [False,True]: + for direction in range(6): + for noclip in [-1,direction,direction^1]: + for fail in [-1,0]:yield fixture(state,direction,extending=extending,progress=bits(0.5),noclip=noclip,fail=fail) + rng=random.Random(0x504953544f4e) + stone=facts['defaults'].get('minecraft:stone',0) + for index in range(10000): + yield fixture(stone,index,kinematic=True,progress=f'{rng.getrandbits(32):08x}',previous=f'{rng.getrandbits(32):08x}',partial=f'{rng.getrandbits(32):08x}') + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--prepare',action='store_true');args=parser.parse_args() + build=lab.LOCAL/'rust-piston-shape-parity';build.mkdir(parents=True,exist_ok=True) + report_path=build/'report.json';report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonShapeOracle.java' + helpers=[oracle.with_name(name+'.java') for name in ['VanillaFaceSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle']] + sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/piston_shape_fixture.rs'] + tested_sources=base.source_hashes(sources) + classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,*helpers],'compile-java') + def java(side,mode,path): + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPistonShapeOracle',mode,path],side+'-'+mode) + java('server','export',build) + facts=json.loads((build/'facts.json').read_text()) + if len(facts['states'])!=35723:raise ValueError('incomplete pinned registry') + fixtures=list(corpus(facts));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') + fixture_paths=[inputs,build/'facts.json',build/'block-registry.nbt',build/'cached-collision.nbt'];tested_fixtures=base.source_hashes(fixture_paths) + run(['cargo','build','--release','-p','horizon-world','--example','piston_shape_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) + binary=Path(metadata['target_directory'])/'release/examples'/('piston_shape_fixture.exe' if os.name=='nt' else 'piston_shape_fixture') + run([binary,build],'rust');references=[] + for side,jar in jars.items(): + java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') + references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) + print(f'{side}: {matched:,} piston-shape output lines match Rust',flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={'schema':1,'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'block_states':len(facts['states']),'kinematic_cases':sum(f['kinematic'] for f in fixtures),'fixtures':len(fixtures),'sources_sha256':tested_sources,'fixtures_sha256':tested_fixtures,'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references,'scope':'Actual moving-piston entity collision shape, interpolation/offset float bits, movement direction and collision-related block-state selection. Every registered moved state is sampled, piston-base/source/extension/head thresholds and all noclip directions are crossed, and dynamic block-entity query failures are compared. Cached collision geometry is imported privately; uncached moved blocks use Rust support selection only in the tested empty-collision-context, absent-block-entity world. Piston ticking, entity pushes, live block entities, networking and full gameplay remain pending.'} + lab.write_json(report_path,report);print(f'Scoped piston-shape parity passed: {report_path}') + + +if __name__=='__main__':main() diff --git a/tools/test_placement_parity.py b/tools/test_placement_parity.py new file mode 100644 index 000000000..8ac2f9247 --- /dev/null +++ b/tools/test_placement_parity.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Compare placement-modifier decoding and ordered emissions with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def definitions(): + encode=lambda value:json.dumps(value,separators=(',',':')) + for value in [None,False,0,[],{}, {'type':'missing'}, {'type':'in_square'}, {'type':':in_square'}]:yield encode(value) + for count in [-1,0,1,3,17,4096,4097,4294967297, {'type':'uniform','min_inclusive':0,'max_inclusive':5}, {'type':'clamped','source':10,'min_inclusive':0,'max_inclusive':3}, {'type':'weighted_list','distribution':[{'data':0,'weight':1},{'data':4,'weight':3}]}]:yield encode({'type':'count','count':count}) + for field in ['x','y','z']: + for value in [-17,-16,-1,0,1,16,17,4294967297, {'type':'uniform','min_inclusive':-16,'max_inclusive':16}, {'type':'trapezoid','min':-7,'max':7,'plateau':0}]: + definition={'type':'offset','x':0,'y':0,'z':0};definition[field]=value;yield encode(definition) + for chance in [None,False,'1',-1,-0.,0,1e-100,0.1,0.5,1,2,3,7,16777217,2147483647,4294967297]: + for kind in ['rarity_filter','random_chance']:yield encode({'type':kind,'chance':chance}) + for height in [{'absolute':0},{'above_bottom':7},{'relative_to_sea_level':-3}, {'type':'uniform','min_inclusive':{'above_bottom':0},'max_inclusive':{'below_top':0}}, {'type':'trapezoid','min_inclusive':{'absolute':-7},'max_inclusive':{'absolute':7}}, {'type':'weighted_list','distribution':[{'data':{'absolute':1},'weight':2},{'data':{'below_top':1},'weight':3}]}]:yield encode({'type':'height_range','height':height}) + fixed=[[0,7,0],[15,20,15],[-1,-64,-1],[-16,99,16],[2147483647,-2147483648,2147483647],[0,7,0]] + for positions in [[],fixed,[[1,2]],[[1,2,3,4]],[[0,False,0]],[[4294967297,0,-4294967297]]]:yield encode({'type':'fixed_placement','positions':positions}) + for placements in [[],[{'type':'in_square'}],[{'type':'in_square'},{'type':'count','count':3},{'type':'fixed_placement','positions':fixed}],[{'type':'randomly_selected','placements':[{'type':'in_square'},{'type':'count','count':0}]}]]:yield encode({'type':'randomly_selected','placements':placements}) + for kind,field in [('count','count'),('height_range','height'),('offset','y'),('rarity_filter','chance'),('random_chance','chance'),('fixed_placement','positions'),('randomly_selected','placements')]: + for value in [None,{},[]]:yield encode({'type':kind,field:value}) + + + for heightmap in ['WORLD_SURFACE_WG','WORLD_SURFACE','OCEAN_FLOOR_WG','OCEAN_FLOOR','MOTION_BLOCKING','MOTION_BLOCKING_NO_LEAVES','world_surface','missing',None,0]: + yield encode({'type':'heightmap','heightmap':heightmap}) + yield encode({'type':'surface_relative_threshold_filter','heightmap':heightmap}) + for low,high in [(-3,3),(1,0),(-2147483648,2147483647),(2147483647,2147483647),(-2147483648,-2147483648),(None,None)]: + yield encode({'type':'surface_relative_threshold_filter','heightmap':heightmap,'min_inclusive':low,'max_inclusive':high}) + for depth in [-2147483648,-1,0,1,7,2147483647,4294967297,None,False,'0']: + yield encode({'type':'surface_water_depth_filter','max_water_depth':depth}) + + for ratio in [-2147483648,-9,-1,0,1,5,16,2147483647]: + for factor in [-1e300,-200,-0.,0,1e-300,1,80,200,1e300]: + yield encode({'type':'noise_based_count','noise_to_count_ratio':ratio,'noise_factor':factor}) + for offset in [None,-1,0,0.1,1,1e300,'0',False]: + yield encode({'type':'noise_based_count','noise_to_count_ratio':7,'noise_factor':80,'noise_offset':offset}) + for level in [-1e300,-1,-0.,0,0.1,0.7,1,1e300]: + for below,above in [(-1,3),(0,0),(1,7),(17,2),(-2147483648,2147483647)]: + yield encode({'type':'noise_threshold_count','noise_level':level,'below_noise':below,'above_noise':above}) + + for xz,y in [(1,1),(2,3),(3,4),(16,16),(0,2),(2,17),({'type':'uniform','min_inclusive':1,'max_inclusive':5},{'type':'uniform','min_inclusive':1,'max_inclusive':3})]: + for edges,interior in [(True,True),(True,False),(False,True),(False,False),(None,None),(0,True),(True,'false')]: + yield encode({'type':'cuboid','xz_size':xz,'y_size':y,'include_edges':edges,'include_interior':interior}) + + for count in [-1,0,1,3,7,257, {'type':'uniform','min_inclusive':0,'max_inclusive':5}, {'type':'weighted_list','distribution':[{'data':0,'weight':1},{'data':4,'weight':3}]}]: + yield encode({'type':'count_on_every_layer','count':count}) + + truth={'type':'true'};false={'type':'not','predicate':truth};inside={'type':'inside_world_bounds'} + predicates=[truth,false,inside,{'type':'all_of','predicates':[]},{'type':'any_of','predicates':[]}] + for offset in [None,[],[0,0],[0,0,0,0],[0,-17,0],[16,16,-16],[0,-16,0],[0,1,0],[-2147483648,-2147483648,-2147483648],[4294967296,4294967297,-4294967297],[0,False,0]]: + predicates.append({'type':'inside_world_bounds','offset':offset}) + for kind in ['all_of','any_of']: + for values in [[truth,inside],[false,inside],[inside,truth],[inside,false],[inside,{'type':'not','predicate':inside}],None,False]: + predicates.append({'type':kind,'predicates':values}) + predicates += [None,False,{},{'type':'not'},{'type':'not','predicate':None},{'type':'missing'}] + for predicate in predicates:yield encode({'type':'block_predicate_filter','predicate':predicate}) + for direction in ['up','down','north','UP',None]: + for steps in [0,1,4,32,33]: + for target in [truth,false,{'type':'not','predicate':{'type':'inside_world_bounds','offset':[0,-16,0]}}]: + yield encode({'type':'environment_scan','direction_of_search':direction,'target_condition':target,'max_steps':steps}) + for allowed in [None,truth,false,inside,{'type':'inside_world_bounds','offset':[0,16,0]}, {'type':'all_of','predicates':[inside,inside]}]: + for target in [inside,{'type':'not','predicate':{'type':'inside_world_bounds','offset':[0,-16,0]}}]: + for direction in ['up','down']: + yield encode({'type':'environment_scan','direction_of_search':direction,'target_condition':target,'allowed_search_condition':allowed,'max_steps':32}) + + +def corpus(): + positions=[[0,0,0],[-1,63,-1],[-16,-64,16],[2147483647,-2147483648,2147483647]] + for legacy in [False,True]: + for seed in [0,-1,0x123456789abcdef]: + for context in [[-64,384,63],[2147483647,-2147483648,2147483647]]: + for index,definition in enumerate(definitions()): + for fail,draw in [(-1,False),(0,False),(2,True)]: + # Limit successful 4096-repeat output; a failing consumer still checks the bound. + if '4096' in definition and fail==-1:continue + value=json.loads(definition) + layer=isinstance(value,dict) and value.get('type')=='count_on_every_layer' + if layer and context[0]!=-64:continue + noise=isinstance(value,dict) and value.get('type') in ['noise_based_count','noise_threshold_count'] + unsafe=noise and (abs(value.get('noise_to_count_ratio',0))>16 or not isinstance(value.get('noise_offset',0),(int,float)) or abs(value.get('noise_offset',0))>2 or abs(value.get('below_noise',0))>17 or abs(value.get('above_noise',0))>17) + for count_only in ([True] if unsafe else [False,True] if noise else [False]): + yield {'layer_world':layer,'count_only':count_only,'definition':definition,'context':context,'legacy':legacy,'seed':seed,'positions':positions,'fail':fail,'draw':draw,'height_mode':index%2,'query_fail':1 if index%5==0 and fail==2 else -1,'world_min':max(-2**31,min(2**31-1,context[0]+[-8,0,8][index%3]))} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-placement-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java" + sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/placement_fixture.rs",lab.ROOT/"crates/horizon-world/examples/support/placement_queries.rs"] + tested_sources=base.source_hashes(sources) + fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") + run(["cargo","build","--release","-p","horizon-world","--example","placement_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("placement_fixture.exe" if os.name=="nt" else "placement_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaPlacementOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} placement output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"modifier_kinds":17,"predicate_kinds":5,"definitions":len(list(definitions())),"requested_modifications":sum(len(f["positions"]) for f in fixtures if not f["count_only"]),"requested_counts":sum(len(f["positions"]) for f in fixtures if f["count_only"]), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual PlacementModifier.CODEC parsing and modify callbacks for count, in-square, offset, height-range, rarity, random-chance, fixed-position randomly-selected, heightmap, surface-relative-threshold and surface-water-depth modifiers, plus native noise-based and noise-threshold repeating counts and cuboid placement with edge/interior controls and count-on-every-layer scans, predicate filters and environment scans. Logical and inside-world-bounds predicates preserve short-circuiting and offset wrapping; traced world-bound queries expose scan termination, final target tests and failures. Layer scanning uses traced synthetic block strata containing air variants, water/lava, ordinary ground, bubble columns and bedrock; callbacks and injected height/block failures preserve query order and random consumption. Both random modes, repeated calls, zero counts, inclusive provider bounds, nested random choices, anchored and overflowing coordinates, same-chunk fixed filtering, duplicates, malformed fields and failing consumers. Consumer callbacks optionally draw from the shared random stream; subsequent nextLong values verify exact consumption. Contexts use an actual PlacementContext with a traced WorldGenLevel proxy and native noise generator. Heightmap queries use traced synthetic world responses, ordinary/extreme heights and injected query failures; world minimum and generation minimum can differ. Noise count-only calls include extreme ratios, factors, offsets and thresholds without expanding huge position lists. Additional block predicates, biome filtering, configured features, provider encoders, Gaussian providers and complete world generation remain pending."} + + lab.write_json(report_path,report);print(f"Scoped placement parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_quad_reuse.py b/tools/test_quad_reuse.py index e4ed5d995..baa95c387 100644 --- a/tools/test_quad_reuse.py +++ b/tools/test_quad_reuse.py @@ -29,7 +29,7 @@ def main(): args = parser.parse_args() root = build_pack.ROOT fixture = build_mod.build_integration_fixture("quad-reuse", "dev.horizonlab.dispatch.QuadReuseIntegration") - mod = root / "dist" / f"horizon-lab-{build_pack.read_lock()['pack_version']}.jar" + mod = root / "dist" / f"horizon-{build_pack.read_lock()['pack_version']}.jar" original_sha256 = hashlib.sha256(mod.read_bytes()).hexdigest() results = [] for enabled in [False, True]: diff --git a/tools/test_quad_sizes.py b/tools/test_quad_sizes.py index 485f5af6f..51650e373 100644 --- a/tools/test_quad_sizes.py +++ b/tools/test_quad_sizes.py @@ -42,7 +42,7 @@ def main(): root = build_pack.ROOT agent = build_agent() fixture = build_mod.build_integration_fixture("quad-size", "dev.horizonlab.dispatch.QuadSizeIntegration") - mod = root / "dist" / f"horizon-lab-{build_pack.read_lock()['pack_version']}.jar" + mod = root / "dist" / f"horizon-{build_pack.read_lock()['pack_version']}.jar" mod_hash = hashlib.sha256(mod.read_bytes()).hexdigest() results = [] for headers in [False, True]: diff --git a/tools/test_replace_block_parity.py b/tools/test_replace_block_parity.py new file mode 100644 index 000000000..8ca916b07 --- /dev/null +++ b/tools/test_replace_block_parity.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Compare ordered block replacements and rule-driven mutations with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base,test_worldgen_parity as worldgen +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + + +def corpus(facts): + yes={'predicate_type':'always_true'} + no={'predicate_type':'not','rule':yes} + rules=[yes,no,{'predicate_type':'tag_match','tag':'leaves'}, {'predicate_type':'tag_match','tag':'horizon:missing'}, {'predicate_type':'height_match','min_inclusive':-64,'max_inclusive':63}] + for name in ['air','cave_air','void_air','stone','water','oak_leaves','dirt']: + for kind,field in [('block_match','block'),('blockstate_match','block_state')]: + rules.append({'predicate_type':kind,field:name}) + rules += [{'predicate_type':'random_block_match','block':name,'probability':p} for p in [0,0.5,1,2]] + rules += [{'predicate_type':'any_of','rules':rules[5:12]}, {'predicate_type':'all_of','rules':[no,yes]}] + definitions=[{'type':'replace_single_block','targets':[]}] + for rule in rules: + targets=[{'target':rule,'state':{'id':'oak_log','properties':{'axis':'x'}}}] + definitions += [{'type':'replace_single_block','targets':targets}, {'type':'replace_single_block','targets':[{'target':no,'state':'air'},*targets,{'target':yes,'state':'water'}]}] + for value in [None,False,'stone',{},[{}],[{'target':yes,'state':'missing'}],[{'target':yes,'state':'stone'},{'target':{'predicate_type':'missing'},'state':'air'}]]: + definitions.append({'type':'replace_single_block','targets':value}) + for legacy in [False,True]: + for definition in definitions: + for x in range(7): + for fail in [-1,0,1,2,4]: + for reject in [0,2]: + yield {'definition':json.dumps(definition,separators=(',',':')),'origin':[x,-64+x*32,0],'world_min':-64,'legacy':legacy,'seed':-1 if legacy else 0,'reject':reject,'fail':fail,'repeats':3} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-replace-block-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaReplaceBlockOracle.java" + helper=oracle.with_name("VanillaBlockStateCodecOracle.java") + tag_helper=oracle.with_name("VanillaHeightmapOracle.java") + tags=worldgen.tag_resources(jars['server']) + if not tags or tags!=worldgen.tag_resources(jars['client']):raise ValueError('client/server tags differ') + (build/'tags.json').write_text(json.dumps(tags,separators=(',',':')),encoding='utf-8') + sources=[oracle,helper,tag_helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/replace_block_fixture.rs"] + tested_sources=base.source_hashes(sources) + fixture_paths=[build/"tags.json"];classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper,tag_helper],"compile-java") + for side,jar in jars.items(): + path=build/f"facts-{side}.json" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaReplaceBlockOracle","export",path],side+"-export") + fixture_paths.append(path) + if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") + facts=json.loads((build/"facts-server.json").read_text()) + if len(facts['states'])!=35723:raise ValueError('incomplete pinned registry') + fixtures=list(corpus(facts));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + fixture_paths.append(inputs) + tested_fixtures=base.source_hashes(fixture_paths) + run(["cargo","build","--release","-p","horizon-world","--example","replace_block_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("replace_block_fixture.exe" if os.name=="nt" else "replace_block_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaReplaceBlockOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} replace-block output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"block_states":len(facts["states"]),"integer_properties":len(facts["integers"]),"requested_placements":sum(f["repeats"] for f in fixtures), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual replace_single_block feature codecs and native ReplaceBlockFeature.place. Ordered target rules re-read the origin state, short-circuit on the first match, preserve random draw order and write flags, ignore rejected writes, retain partial mutations and stop on injected read/write failures. Bound block/tag/state/height/random/logical targets and malformed unselected entries are compared across both random modes and repeated calls. Full region side effects, structure processors, ore clusters and complete gameplay remain pending."} + + + lab.write_json(report_path,report);print(f"Scoped replace-block parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_rule_test_parity.py b/tools/test_rule_test_parity.py new file mode 100644 index 000000000..0937e10b1 --- /dev/null +++ b/tools/test_rule_test_parity.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Compare all pinned replacement-rule codecs and ordered evaluation.""" +import argparse +import json +import os +from pathlib import Path +import platform +import subprocess +try: + from . import lab, test_rust_parity as base, test_worldgen_parity as worldgen +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + + +def corpus(facts, tags): + defaults=list(facts['defaults'].values()) + all_states=list(range(len(facts['states']))) + heights=[-2147483648,-2032,-65,-64,-1,0,1,63,64,319,2031,2147483647] + def cases(definition, states=defaults, repeats=1): + for legacy in [False,True]: + yield {'definition':json.dumps(definition,separators=(',',':')),'states':states,'heights':heights,'legacy':legacy,'seed':-1 if legacy else 0x123456789abcdef,'repeats':repeats} + yes={'predicate_type':'always_true'} + no={'predicate_type':'not','rule':yes} + for value in [yes,no,{'predicate_type':'all_of','rules':[]},{'predicate_type':'any_of','rules':[]}]:yield from cases(value,all_states) + for name in sorted(tags):yield from cases({'predicate_type':'tag_match','tag':name}) + for name in ['minecraft:logs','minecraft:leaves','minecraft:stone_ore_replaceables','horizon:missing']: + yield from cases({'predicate_type':'tag_match','tag':name},all_states) + for name, state in facts['defaults'].items(): + yield from cases({'predicate_type':'block_match','block':name},[0,state,(state+1)%len(all_states),all_states[-1]]) + for i,state in enumerate(facts['states']): + yield from cases({'predicate_type':'blockstate_match','block_state':state},[i,(i+1)%len(all_states)]) + for low,high in [(-2147483648,2147483647),(-64,319),(64,63),(0,0),(4294967297,-4294967295),(0.9,1.9)]: + yield from cases({'predicate_type':'height_match','min_inclusive':low,'max_inclusive':high},defaults[:24],2) + for kind,field in [('random_block_match','block'),('random_blockstate_match','block_state')]: + for block in ['air','water','oak_log',{'id':'water','properties':{'level':'+01'}}]: + for probability in [-1,-0.0,0,1e-50,0.25,0.5,1,2,1e100,None,False,'0.5']: + rule={'predicate_type':kind,field:block,'probability':probability} + yield from cases(rule,all_states[0:160],2) + for wrapper in [{'predicate_type':'all_of','rules':[rule,yes,rule]}, {'predicate_type':'any_of','rules':[rule,no,rule]}, {'predicate_type':'all_of','rules':[no,rule]}, {'predicate_type':'any_of','rules':[yes,rule]}, {'predicate_type':'not','rule':rule}]: + yield from cases(wrapper,all_states[0:160],2) + invalid=[None,False,0,[],{}, {'predicate_type':'unknown'}, {'predicate_type':False}] + for kind,field in [('block_match','block'),('blockstate_match','block_state'),('tag_match','tag'),('not','rule'),('all_of','rules'),('any_of','rules')]: + invalid += [{'predicate_type':kind,field:value} for value in [None,False,0,[],{},'missing','Minecraft:stone',':']] + invalid.append({'predicate_type':kind}) + for value in invalid:yield from cases(value,defaults[:4]) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--prepare',action='store_true');args=parser.parse_args() + build=lab.LOCAL/'rust-rule-test-parity';build.mkdir(parents=True,exist_ok=True) + report_path=build/'report.json';report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRuleTestOracle.java' + helpers=[oracle.with_name('VanillaBlockStateCodecOracle.java'),oracle.with_name('VanillaHeightmapOracle.java')] + tags=worldgen.tag_resources(jars['server']) + if not tags or tags!=worldgen.tag_resources(jars['client']):raise ValueError('client/server tags differ') + (build/'tags.json').write_text(json.dumps(tags,separators=(',',':')),encoding='utf-8') + sources=[oracle,*helpers,lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/rule_test_fixture.rs'] + tested_sources=base.source_hashes(sources) + classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,*helpers],'compile-java') + def java(side,mode,path): + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaRuleTestOracle',mode,path],side+'-'+mode) + for side in jars:java(side,'export',build/f'facts-{side}.json') + facts=json.loads((build/'facts-server.json').read_text()) + if facts!=json.loads((build/'facts-client.json').read_text()):raise ValueError('client/server registry metadata differs') + if len(facts['states'])!=35723:raise ValueError('incomplete pinned state registry') + fixtures=list(corpus(facts,tags));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') + fixture_paths=[inputs,build/'tags.json',build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) + run(['cargo','build','--release','-p','horizon-world','--example','rule_test_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) + binary=Path(metadata['target_directory'])/'release/examples'/('rule_test_fixture.exe' if os.name=='nt' else 'rule_test_fixture') + run([binary,build],'rust');references=[] + for side,jar in jars.items(): + java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') + references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) + print(f'{side}: {matched:,} replacement-rule output lines match Rust',flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={'schema':1,'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'block_states':len(facts['states']),'blocks':len(facts['defaults']),'integer_properties':len(facts['integers']),'codec_inputs':len(fixtures),'rule_types':10,'block_tag_files':len(tags),'requested_tests':sum(len(f['states'])*f['repeats'] for f in fixtures),'sources_sha256':tested_sources,'fixtures_sha256':tested_fixtures,'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references,'scope':'Actual RuleTest.CODEC and all ten registered replacement-rule types. Every block and block-state identity, all bundled block tags, absent tags, inclusive and reversed height ranges, unrestricted random probabilities, logical short-circuit evaluation, malformed inputs, both random modes and subsequent draws are compared. Registry metadata and tag resources independently agree across authenticated JARs. Bound tags are immutable snapshots. Replacement feature mutations, structure processors, reload ownership and complete gameplay remain outside this standalone comparison.'} + lab.write_json(report_path,report);print(f'Scoped replacement-rule parity passed: {report_path}') + + +if __name__=='__main__':main() diff --git a/tools/test_rust_parity.py b/tools/test_rust_parity.py new file mode 100644 index 000000000..21b013b57 --- /dev/null +++ b/tools/test_rust_parity.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""Compare Horizon core operations with both checksum-pinned vanilla game JARs.""" + +import argparse +from collections import Counter +import itertools +import json +import os +from pathlib import Path +import platform +import random +import subprocess +import zipfile + +try: + from . import lab +except ImportError: + import lab + + +def corpus(): + """Stable inputs; Java supplies expected results instead of a second port.""" + rng = random.Random(0x484F52495A4F4E) + edges = [-2147483648, -33554433, -33554432, -2097152, -2049, -2048, + -1025, -1024, -513, -512, -33, -32, -17, -16, -1, 0, 1, + 15, 16, 31, 32, 511, 512, 2047, 2048, 2097151, 33554431, 33554432, 2147483647] + for axis in range(3): + for edge in edges: + p = [0, 0, 0] + p[axis] = edge + yield f"position {' '.join(map(str, p))} 1 -1 2147483647" + for x, y, z in itertools.product(range(16), repeat=3): + yield f"position {x - 16} {y - 16} {z - 16} 0 0 0" + for _ in range(8192): + values = [rng.randrange(-2147483648, 2147483648) for _ in range(6)] + yield "position " + " ".join(map(str, values)) + seeds = [-9223372036854775808, -281474976710656, -1, 0, 1, 281474976710656, + 9223372036854775807, *[rng.randrange(-2**63, 2**63) for _ in range(16)]] + for kind in ["legacy", "xoroshiro"]: + for seed in seeds: + yield f"{kind} {seed} 2200" + for lo, hi in [(0, 0), (0, 1), (1, 0), (-1, -1), (-9223372036854775808, 9223372036854775807)]: + yield f"xoroshiro_state {lo} {hi} 2200" + for bits in range(1, 33): + per_word = 64 // bits + for length in sorted({0, 1, per_word - 1, per_word, per_word + 1, 63, 64, 65, 4096}): + yield f"storage {bits} {length} {rng.randrange(-2**63, 2**63)}" + names = [[], [0], [0xffff], [0xd800], [0xdc00], [0xd800, 0x61, 0xdc00], [0xd83d, 0xde00], [0xdbff, 0xdfff], + *[[ord(c) for c in text] for text in ["minecraft:temperature", "octave_-3", "Aa", "BB", "Horizon", "àé中"]], + *[[0x61] * n for n in [55, 56, 63, 64, 65, 119, 120, 127, 128, 129, 1024]]] + for scenario in range(2200): + name = names[scenario % len(names)] if scenario % 3 else [rng.randrange(65536) for _ in range(rng.randrange(160))] + encoded = "".join(f"{unit:04x}" for unit in name) or "-" + lo = seeds[scenario % len(seeds)] if scenario % 3 else rng.randrange(-2**63, 2**63) + hi = lo if scenario % 11 == 0 else rng.randrange(-2**63, 2**63) + position = [rng.choice(edges) if scenario % 4 else rng.randrange(-2**31, 2**31) for _ in range(3)] + seed = lo if scenario % 7 == 0 else rng.randrange(-2**63, 2**63) + for kind in ["legacy", "xoroshiro"]: + yield f"factory {kind} {scenario % 2} {lo} {hi} {' '.join(map(str, position))} {seed} {encoded} 24" + double_edges = [0, 1, 0x8000000000000000, 0x3ff0000000000000, 0xbff0000000000000, + 0x7fefffffffffffff, 0x7ff0000000000000, 0xfff0000000000000, 0x7ff8000000000000] + float_edges = [0, 1, 0x80000000, 0x3f800000, 0xbf800000, 0x7f7fffff, 0x7f800000, 0xff800000, 0x7fc00000] + interval_edges = [-(2**31), -(2**31)+1, -1, 0, 1, 2, 16, 2**30+1, 2**31-2, 2**31-1] + intervals = [*itertools.product(interval_edges, repeat=2), + *[(rng.randrange(-2**31,2**31),rng.randrange(-2**31,2**31)) for _ in range(2400)]] + for scenario, (minimum, maximum) in enumerate(intervals): + d = [rng.choice(double_edges) if scenario % 3 else rng.getrandbits(64) for _ in range(2)] + f = [rng.choice(float_edges) if scenario % 3 else rng.getrandbits(32) for _ in range(2)] + for kind in ["legacy", "xoroshiro"]: + yield f"helpers {kind} {seeds[scenario % len(seeds)]} {minimum} {maximum} {d[0]:016x} {d[1]:016x} {f[0]:08x} {f[1]:08x}" + + +def verify_artifacts(): + """Authenticate against the lock and the bundled checksums, not generated reports.""" + lock, directory = lab.config() + manifest_path = directory / "manifest.json" + if lab.digest(manifest_path, "sha1") != lock["minecraft"]["manifest_sha1"]: + raise ValueError("Manifest checksum changed; run tools/lab.py prepare") + manifest = json.loads(manifest_path.read_text()) + if manifest["id"] != lock["minecraft"]["version"]: + raise ValueError("Manifest version differs from the lock") + jars = {} + for side in ["client", "server"]: + jar = directory / "jars" / f"{side}.jar" + if lab.digest(jar, "sha1") != manifest["downloads"][side]["sha1"]: + raise ValueError(f"{side} artifact checksum changed; run tools/lab.py prepare") + jars[side] = jar + libraries = [] + with zipfile.ZipFile(jars["server"]) as archive: + versions = list(lab.bundle_entries(archive, "META-INF/versions.list")) + if len(versions) != 1 or versions[0][1] != manifest["id"]: + raise ValueError("Unexpected server bundle") + checksum, _, _ = versions[0] + jars["server"] = directory / "jars/server-game.jar" + if lab.digest(jars["server"], "sha256") != checksum: + raise ValueError("Inner server artifact checksum changed") + for checksum, _, relative in lab.bundle_entries(archive, "META-INF/libraries.list"): + library = directory / "libraries/server" / relative + if lab.digest(library, "sha256") != checksum: + raise ValueError(f"Dependency checksum changed: {relative}") + libraries.append(library) + return lock, jars, libraries + + +def compare(reference, candidate): + count = 0 + with reference.open(encoding="utf-8") as expected, candidate.open(encoding="utf-8") as actual: + for count, (left, right) in enumerate(itertools.zip_longest(expected, actual), 1): + if left != right: + raise AssertionError(f"Parity mismatch at output line {count}: vanilla={left!r}, Rust={right!r}") + if count == 0: + raise AssertionError("Empty output cannot establish parity") + return count + + +def run(command, **kwargs): + subprocess.run(command, cwd=lab.ROOT, check=True, timeout=300, **kwargs) + + +def source_hashes(sources): + return {str(Path(path).resolve().relative_to(lab.ROOT)): lab.digest(Path(path), "sha256") for path in sources} + + +def ensure_sources_unchanged(sources, expected): + actual = source_hashes(sources) + changed = sorted(key for key in expected.keys() | actual.keys() if expected.get(key) != actual.get(key)) + if changed: + raise RuntimeError("Sources changed during validation: " + ", ".join(changed)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepare", action="store_true", help="Download and verify the pinned reference artifacts first") + args = parser.parse_args() + build = lab.LOCAL / "rust-parity" + build.mkdir(parents=True, exist_ok=True) + # Remove a previous success marker before any build or comparison can fail. + report_path = build / "report.json" + report_path.unlink(missing_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = verify_artifacts() + commands = list(corpus()) + inputs = build / "inputs.txt" + inputs.write_text("\n".join(commands) + "\n", encoding="utf-8") + source = lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCoreOracle.java" + sources = [source, Path(__file__), *sorted((lab.ROOT / "crates/horizon-core").rglob("*.rs")), + lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock"] + tested_sources = source_hashes(sources) + classes = build / "classes" + classes.mkdir(exist_ok=True) + dependency_path = os.pathsep.join(map(str, libraries)) + run(["javac", "--release", str(lock["minecraft"]["java_major"]), "-proc:none", + "-cp", os.pathsep.join([str(jars["server"]), dependency_path]), "-d", str(classes), str(source)]) + run(["cargo", "build", "--release", "--bin", "horizon-parity"]) + # Ask Cargo for its artifact path so custom target directories work too. + metadata = json.loads(subprocess.check_output(["cargo", "metadata", "--no-deps", "--format-version", "1"], cwd=lab.ROOT, text=True)) + binary = Path(metadata["target_directory"]) / "release" / ("horizon-parity.exe" if os.name == "nt" else "horizon-parity") + candidate = build / "rust.txt" + with inputs.open("rb") as stdin, candidate.open("wb") as stdout: + run([str(binary)], stdin=stdin, stdout=stdout) + references = [] + for side, jar in jars.items(): + reference = build / f"vanilla-{side}.txt" + run(["java", "-Xmx512M", "-cp", os.pathsep.join([str(classes), str(jar), dependency_path]), + "dev.horizonlab.parity.VanillaCoreOracle", str(inputs), str(reference)]) + matched = compare(reference, candidate) + references.append({"side": side, "jar_sha256": lab.digest(jar, "sha256"), + "output_sha256": lab.digest(reference, "sha256"), "matched_output_lines": matched}) + print(f"{side}: {matched:,} output lines match the Rust implementation", flush=True) + ensure_sources_unchanged(sources, tested_sources) + report = {"schema": 1, "minecraft": lock["minecraft"]["version"], "platform": platform.platform(), + "java": subprocess.check_output(["java", "--version"], text=True).splitlines()[0], + "rustc": subprocess.check_output(["rustc", "--version"], text=True).strip(), + "manifest_sha1": lock["minecraft"]["manifest_sha1"], "commands": dict(Counter(line.split()[0] for line in commands)), + "inputs_sha256": lab.digest(inputs, "sha256"), "rust_output_sha256": lab.digest(candidate, "sha256"), + "sources_sha256": tested_sources, + "references": references, + "scope": "Selected integer positions, seeded RNG operations including inclusive/exclusive integer intervals and float/double triangular draws, positional factories, UTF-16 Java string hashing, MD5-derived seeds and packed-storage operations. Floating-point helper NaNs canonicalized; finite results and signed zeros compared by bits. No gameplay, rendering or performance claim."} + lab.write_json(report_path, report) + print(f"Scoped parity checks passed: {report_path}") + + +if __name__ == "__main__": + main() diff --git a/tools/test_scattered_ore_parity.py b/tools/test_scattered_ore_parity.py new file mode 100644 index 000000000..b6bbd5aa7 --- /dev/null +++ b/tools/test_scattered_ore_parity.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""Compare scattered-ore attempts, air exposure and rule-driven mutations.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base,test_worldgen_parity as worldgen +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + + +def corpus(facts): + yes={'predicate_type':'always_true'} + no={'predicate_type':'not','rule':yes} + targets=[[],[{'target':yes,'state':'gold_ore'}],[{'target':no,'state':'air'},{'target':{'predicate_type':'random_block_match','block':'stone','probability':0.5},'state':'iron_ore'},{'target':yes,'state':'copper_ore'}]] + def fixture(definition,legacy=False,seed=0,mode=0,fail=-1,reject=0,origin=None): + return {'definition':json.dumps(definition,separators=(',',':')),'origin':origin or [15,-64,15],'world_min':-64,'legacy':legacy,'seed':seed,'mode':mode,'reject':reject,'fail':fail,'repeats':2} + for size in [0,1,7,8,64]: + for chance in [0,0.25,0.5,1]: + for values in targets: + definition={'type':'scattered_ore','targets':values,'size':size,'discard_chance_on_air_exposure':chance} + for legacy in [False,True]: + for seed in [0,-1,9223372036854775807]: + for mode in range(8): + for fail,reject in [(-1,0),(-1,3),(0,0),(7,0)]: + yield fixture(definition,legacy,seed,mode,fail,reject) + for field,values in [('size',[-1,65,4294967297,None,False,'1',0.9]),('discard_chance_on_air_exposure',[-0.0,-1e-100,-0.1,1.01,1e100,None,False,'0.5']),('targets',[None,False,{},'stone',[{}]])]: + for value in values: + definition={'type':'scattered_ore','targets':targets[1],'size':8,'discard_chance_on_air_exposure':0.5};definition[field]=value + yield fixture(definition) + for p in [[2147483647,2147483647,2147483647],[-2147483648,-2147483648,-2147483648]]: + for legacy in [False,True]: + yield fixture({'type':'scattered_ore','targets':targets[1],'size':64,'discard_chance_on_air_exposure':1},legacy=legacy,origin=p) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-scattered-ore-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaScatteredOreOracle.java" + helper=oracle.with_name("VanillaBlockStateCodecOracle.java") + tag_helper=oracle.with_name("VanillaHeightmapOracle.java") + tags=worldgen.tag_resources(jars['server']) + if not tags or tags!=worldgen.tag_resources(jars['client']):raise ValueError('client/server tags differ') + (build/'tags.json').write_text(json.dumps(tags,separators=(',',':')),encoding='utf-8') + sources=[oracle,helper,tag_helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/scattered_ore_fixture.rs"] + tested_sources=base.source_hashes(sources) + fixture_paths=[build/"tags.json"];classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper,tag_helper],"compile-java") + for side,jar in jars.items(): + path=build/f"facts-{side}.json" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaScatteredOreOracle","export",path],side+"-export") + fixture_paths.append(path) + if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") + facts=json.loads((build/"facts-server.json").read_text()) + if len(facts['states'])!=35723:raise ValueError('incomplete pinned registry') + fixtures=list(corpus(facts));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + fixture_paths.append(inputs) + tested_fixtures=base.source_hashes(fixture_paths) + run(["cargo","build","--release","-p","horizon-world","--example","scattered_ore_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("scattered_ore_fixture.exe" if os.name=="nt" else "scattered_ore_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaScatteredOreOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} scattered-ore output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"block_states":len(facts["states"]),"integer_properties":len(facts["integers"]),"requested_placements":sum(f["repeats"] for f in fixtures), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual scattered_ore feature codec and native ScatteredOreFeature.place. Attempt counts, six float draws per offset, Java rounding, wrapped coordinates, state capture per attempt, ordered target predicates, conditional air-exposure draws, directional neighbor reads, early air detection and mutation flags/results/errors are compared. Both random modes, size/discard boundaries, empty targets, repeated calls, solid/mixed/directional-air worlds and partial failures are included. Complete ore veins, region side effects, chunk decoration and gameplay remain pending."} + + + lab.write_json(report_path,report);print(f"Scoped scattered-ore parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_server_graphics.py b/tools/test_server_graphics.py index 9e894a229..ac30c0680 100644 --- a/tools/test_server_graphics.py +++ b/tools/test_server_graphics.py @@ -25,7 +25,7 @@ def main(): fixture = build_mod.build_integration_fixture('server-graphics', 'dev.horizonlab.metrics.ServerGraphicsIntegration', fixture_dependencies={}) version = build_pack.read_lock()['pack_version'] - mod = root / 'dist' / f'horizon-lab-{version}.jar' + mod = root / 'dist' / f'horizon-{version}.jar' digest = hashlib.sha256(mod.read_bytes()).hexdigest() instance = root / '.local/runtime' / ('server-graphics-' + (args.backend or 'default')) if instance.exists(): diff --git a/tools/test_state_provider_parity.py b/tools/test_state_provider_parity.py new file mode 100644 index 000000000..693fa3fd5 --- /dev/null +++ b/tools/test_state_provider_parity.py @@ -0,0 +1,400 @@ +#!/usr/bin/env python3 +"""Compare initial state-provider codecs, choices and optional sampling.""" +import argparse +import json +import os +from pathlib import Path +import platform +import subprocess +import random +import zipfile +try: + from . import lab, test_rust_parity as base, test_worldgen_parity as worldgen, test_biome_temperature_parity as temperature, test_material_condition_parity as material, test_block_survival_parity as survival +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + import test_biome_temperature_parity as temperature + import test_material_condition_parity as material, test_block_survival_parity as survival + + +def corpus(facts,tags,provider_resources=None,catalog_resources=None,fluid_tags=None,biomes=None,biome_tags=None,support_states=None,survival_rules=None): + def cases(definition,states=None,repeats=1,wide=False): + if states is None:states=list(facts['defaults'].values())[:6] + for typed in [False,True]: + for legacy,worldgen in ([(False,False),(True,False),(False,True),(True,True)] if wide else [(False,False)]): + yield {'definition':json.dumps(definition,separators=(',',':')),'typed':typed,'legacy':legacy,'worldgen':worldgen,'seed':-1 if legacy else 0x123456789abcdef,'states':states,'repeats':repeats,'fail':-1} + for index,state in enumerate(facts['states']): + yield from cases(state,[index]) + yield from cases({'type':'simple','state':state},[index]) + for name in facts['defaults']: + for value in [name,{'type':'simple','state':name},{'type':'random_block','blocks':name},{'type':'random_block','blocks':[name]}]: + yield from cases(value,[0],wide=False) + for name in sorted(tags): + yield from cases({'type':'random_block','blocks':'#'+name},wide=True) + for blocks in [[],['water','stone','water'],['air'],['oak_log','redstone_wire','water'],['#minecraft:logs'],'#horizon:missing',['missing'],False,{},None]: + for f in cases({'type':'random_block','blocks':blocks},repeats=3,wide=True): + yield f + yield dict(f,fail=0) + yield dict(f,fail=2) + entries=lambda weights:[{'data':state,'weight':weight} for state,weight in zip(['stone','water','oak_log'],weights)] + for weights in [[],[0],[1],[100],[0,0,0],[0,1,0],[1,0,2],[2147483647],[2147483647,1],[-1],[1.9],[4294967297],[True],[None]]: + yield from cases({'type':'weighted','entries':entries(weights)},repeats=5,wide=True) + for state in ['missing','stone',{'id':'water','properties':{'level':'+01'}},{'id':'oak_log','properties':{'axis':'z'}},None,False,1,[],{}]: + yield from cases({'type':'simple','state':state},wide=True) + for typed in [{'type':'simple','state':'water'},{'type':'weighted','entries':entries([1,2,3])},{'type':'random_block','blocks':['water']},{'type':'missing'}]: + for name in ['stone','missing']: + yield from cases(dict(typed,id=name),wide=True) + all_states=list(range(len(facts['states']))) + for direction in ['down','up','north','south','west','east']: + yield from cases({'type':'rotated','state':{'type':'random_block','blocks':[]},'direction':direction},all_states) + yield from cases({'type':'rotated','state':{'type':'random_block','blocks':[]}},all_states,wide=True) + sources=[{'id':'oak_log'},{'type':'weighted','entries':[{'data':'oak_log','weight':2},{'data':'piston','weight':3},{'data':'hopper','weight':1}]},{'type':'random_block','blocks':['furnace','stone','oak_stairs']},{'type':'random_block','blocks':[]},{'type':'random_block','blocks':'#horizon:empty'},'oak_log',None] + for source in sources: + for direction in [None,'up','west','UP','missing',False,1]: + for f in cases({'type':'rotated','state':source,'direction':direction},repeats=4,wide=True): + yield f + yield dict(f,fail=0) + for depth in [1,2,8,64]: + source={'type':'weighted','entries':[{'data':'oak_log','weight':1},{'data':'piston','weight':1}]} + for _ in range(depth):source={'type':'rotated','state':source} + yield from cases(source,repeats=2,wide=True) + # One representative per property-family value covers every compatible + # property update for each target state without a quadratic all-state matrix. + integers={tuple(v) for v in facts.get('integers',[])} + domains={} + for state in facts['states']: + for name,value in state.get('properties',{}).items():domains.setdefault((state['id'],name),set()).add(value) + signatures={key:(key[1],key in integers,tuple(sorted(values))) for key,values in domains.items()} + representatives={} + for index,state in enumerate(facts['states']): + for name,value in state.get('properties',{}).items():representatives.setdefault(signatures[(state['id'],name)],{}).setdefault(value,index) + for index,state in enumerate(facts['states']): + targets={0,index} + for name in state.get('properties',{}):targets.update(representatives[signatures[(state['id'],name)]].values()) + f=next(cases({'type':'copy_properties','source':state},sorted(targets))) + yield f + for source in sources: + for f in cases({'type':'copy_properties','source':source},repeats=3,wide=True): + yield f + yield dict(f,fail=0) + yield dict(f,fail=1) + for block,property_name in sorted(integers): + values=sorted(map(int,domains[(block,property_name)])) + for value in [values[0],values[-1],values[0]-1,values[-1]+1,{'type':'uniform','min_inclusive':values[0]-1,'max_inclusive':values[-1]+1}]: + source={'type':'weighted','entries':[{'data':{'id':block},'weight':1},{'data':'stone','weight':1},{'data':'water','weight':1}]} + yield from cases({'type':'randomized_int','source':source,'property':property_name,'values':value},repeats=3,wide=True) + for name in ['missing','axis','level','age','power','distance','',None,False]: + for value in [0,1,-1,{'type':'uniform','min_inclusive':0,'max_inclusive':31}]: + for f in cases({'type':'randomized_int','source':{'type':'random_block','blocks':[]},'property':name,'values':value},list(facts['defaults'].values()),wide=True): + yield f + yield dict(f,fail=0) + for depth in [1,2,8,32]: + source={'type':'random_block','blocks':[]} + for i in range(depth):source={'type':'copy_properties','source':{'type':'randomized_int','source':source,'property':'level','values':{'type':'uniform','min_inclusive':0,'max_inclusive':15}}} + yield from cases(source,wide=True) + positions=[[0,0,0],[1,1,1],[-1,-64,-1],[17,-63,-33],[30000000,319,-30000000],[2147483647,-2147483648,2147483647],[16777217,65,-16777217]] + rng=random.Random(7581) + positions += [[rng.randrange(-30000000,30000000),rng.randrange(-2032,2032),rng.randrange(-30000000,30000000)] for _ in range(9)] + def noise_cases(definition,wide=True): + for f in cases(definition,[0]*len(positions),wide=wide): + yield dict(f,positions=positions) + parameters=[{'base_octave':-3,'octave_count':3},{'base_octave':-32},{'base_octave':32},{'base_octave':0,'base_amplitude':1000,'normalize':False},{'base_octave':-1,'octave_count':2,'amplitude_modifiers':[0,0]}] + for kind in ['noise','noise_threshold','dual_noise']: + for noise in parameters: + for scale in [0.01,0.5,1.0,1e-45,3.4028234663852886e38]: + for seed in [0,-1,9223372036854775807]: + f={'type':kind,'seed':seed,'noise':noise,'scale':scale} + if kind=='noise_threshold':f.update(threshold=0.0,high_chance=0.5,default_state='stone',low_states=['water','dirt'],high_states=['oak_log','poppy','piston']) + else:f['states']=['stone','water','dirt','oak_log','poppy','piston','furnace'] + if kind=='dual_noise':f.update(variety=[1,5],slow_noise={'base_octave':-4,'octave_count':2},slow_scale=scale) + yield from noise_cases(f) + template={'type':'noise','seed':0,'noise':{'base_octave':0},'scale':0.1,'states':['stone','water','oak_log']} + for seed in [18446744073709551617,-18446744073709551617,1e100,-1e100,1.9,-1.9,0.9,-0.9,True,None,'1']: + yield from noise_cases(dict(template,seed=seed)) + for scale in [0,-0.0,-1,1e-50,1e100,None,True,'0.1']: + yield from noise_cases(dict(template,scale=scale),False) + for noise in [{'base_octave':33},{'base_octave':-33},{'base_octave':0,'normalize':'legacy'},{'base_octave':0,'octave_count':0},None,False]: + yield from noise_cases(dict(template,noise=noise),False) + for states in [[],['missing'],None,False,'stone',[{'id':'water','properties':{'level':'1'}}]]: + yield from noise_cases(dict(template,states=states),False) + for variety in [1,64,[1,1],[64,64],[1,64],{'min_inclusive':2,'max_inclusive':7},[0,2],[2,1],[1,65],[],[1],False,None]: + yield from noise_cases(dict(template,type='dual_noise',variety=variety,slow_noise={'base_octave':0,'normalize':False,'base_amplitude':1000},slow_scale=0.25),False) + for threshold in [-1,-0.0,0,1,-1.1,1.1,None]: + for chance in [-0.0,0,0.5,1,2,None]: + yield from noise_cases(dict(template,type='noise_threshold',threshold=threshold,high_chance=chance,default_state='stone',low_states=['water'],high_states=['poppy']),False) + for definition in (provider_resources or {}).values():yield from noise_cases(definition) + true={'type':'true'} + false={'type':'not','predicate':true} + inside={'type':'inside_world_bounds'} + predicates=[true,false,inside,{'type':'all_of','predicates':[]},{'type':'any_of','predicates':[]}, + {'type':'all_of','predicates':[false,inside]}, {'type':'all_of','predicates':[inside,false]}, + {'type':'any_of','predicates':[true,inside]}, {'type':'any_of','predicates':[inside,true]}] + predicates += [{'type':'inside_world_bounds','offset':[0,y,0]} for y in [-2147483648,-16,-1,1,16,17]] + empty={'type':'random_block','blocks':[]} + choices=[empty,{'id':'water'}, {'type':'weighted','entries':entries([1,2,3])}, + {'type':'copy_properties','source':empty}, template, + {'type':'randomized_int','source':{'id':'water'},'property':'level','values':{'type':'uniform','min_inclusive':0,'max_inclusive':16}}] + positions=[[17,y,-33] for y in [-2147483648,-65,-64,-63,0,318,319,320,2147483647]] + for predicate in predicates: + for choice in choices: + for fallback in [None,empty,{'id':'oak_log'}]: + definition={'type':'rule_based','fallback':fallback,'rules':[ + {'if_true':predicate,'then':choice}, {'if_true':inside,'then':empty}, + {'if_true':false,'then':{'type':'copy_properties','source':empty}}]} + for f in cases(definition,[0]*len(positions),wide=True): + f=dict(f,positions=positions) + yield f + yield dict(f,query_fail=0) + yield dict(f,query_fail=2) + yield dict(f,fail=0) + for rules in [[],None,False,[{}],[{'if_true':true}],[{'then':empty}], + [{'if_true':false,'then':{'type':'missing'}}], [{'if_true':{'type':'missing'},'then':empty}]]: + for fallback in [None,empty,{'id':'stone'},'stone',{'type':'missing'}]: + yield from cases({'type':'rule_based','rules':rules,'fallback':fallback},wide=True) + for depth in [1,2,8,32]: + source=empty + for _ in range(depth):source={'type':'rule_based','fallback':source,'rules':[{'if_true':true,'then':empty}]} + yield from cases(source,wide=True) + def predicate_cases(predicate, states=None, wide=True): + if states is None:states=[0]*len(positions) + definition={'type':'rule_based','rules':[{'if_true':predicate,'then':{'id':'stone'}}],'fallback':empty} + for f in cases(definition,states,wide=wide): + f=dict(f,positions=positions) + yield f + yield dict(f,query_fail=1,fail=1) + anchors=[{kind:v} for kind in ['absolute','above_bottom','below_top','relative_to_sea_level'] for v in [-2032,-64,0,63,2031]] + for minimum in anchors: + for maximum in anchors: + yield from predicate_cases({'type':'height_range','min_inclusive':minimum,'max_inclusive':maximum},wide=False) + for invalid in [None,1,{}, {'absolute':2032}, {'below_top':-2033}, {'absolute':0,'above_bottom':0}]: + yield from predicate_cases({'type':'height_range','min_inclusive':invalid,'max_inclusive':{'absolute':0}},wide=False) + for tag in [*sorted(tags),'missing',':','#minecraft:logs','UPPERCASE',None,False]: + yield from predicate_cases({'type':'matching_block_tag','tag':tag},list(facts['defaults'].values()),wide=False) + for name in facts['defaults']: + matching=[i for i,state in enumerate(facts['states']) if state['id']==name] + states=sorted(set(matching+[0,len(facts['states'])-1])) + for blocks in [name,[name]]: + yield from predicate_cases({'type':'matching_blocks','blocks':blocks},states,wide=False) + for blocks in [*['#'+name for name in sorted(tags)], [], ['stone','water','stone'], '#missing', ['#minecraft:logs'], ['missing'], ['stone',None], None, False, {}]: + yield from predicate_cases({'type':'matching_blocks','blocks':blocks},list(facts['defaults'].values()),wide=False) + for fluids in ['empty','flowing_water','water','flowing_lava','lava',*['#'+name for name in sorted(fluid_tags or {})],[],['water','water','flowing_lava'],'missing','#missing',['#minecraft:water'],False,None]: + yield from predicate_cases({'type':'matching_fluids','fluids':fluids},all_states,wide=False) + biome_indices=list(range(len(biomes or {'minecraft:plains':{}}))) + for selected in [*sorted(biomes or {}),*['#'+name for name in sorted(biome_tags or {})],[],['plains','desert','plains'],'plains','missing','#missing',['#minecraft:is_badlands'],False,None]: + predicate={'type':'matching_biomes','biomes':selected} + for condition in [predicate,{'type':'not','predicate':predicate}, {'type':'volume_match','min':[0,0,0],'max':[1,0,1],'match':predicate}]: + for f in predicate_cases(condition,[0]*len(biome_indices),wide=False):yield dict(f,biomes=biome_indices) + for selected in ['plains','#horizon:ordered',[]]: + for f in predicate_cases({'type':'any_of','predicates':[{'type':'matching_biomes','biomes':selected},inside]},[0]*len(biome_indices)): + yield dict(f,biomes=biome_indices) + for offset in [None,[0,0,0],[1,-1,16],[17,18,-19],[2147483647,-2147483648,2147483647],[4294967297,0,0],[1.9,-1.9,0],[],[1],[1,2,3,4],False,{}]: + predicate={'type':'unobstructed','offset':offset} + for condition in [predicate,{'type':'not','predicate':predicate},{'type':'volume_match','min':[-1,0,-1],'max':[1,0,1],'match':predicate}]: + for f in predicate_cases(condition): + yield dict(f,unobstructed=True) + yield dict(f,unobstructed=False) + for offset in [[0,0,0],[16,-16,1],[-2147483648,0,-2147483648],[17,0,0],[],None]: + yield from predicate_cases({'type':'matching_block_tag','tag':'minecraft:logs','offset':offset}) + for minimum,maximum in [([0,0,0],[0,0,0]),([-1,-1,-1],[1,1,1]),([-16,0,0],[16,1,1]),([1,0,0],[0,0,0]),([-17,0,0],[0,0,0]),([-2147483648,0,0],[-2147483648,0,0])]: + for child in [true,false,inside,{'type':'height_range','min_inclusive':{'above_bottom':0},'max_inclusive':{'below_top':0}}, {'type':'matching_block_tag','tag':'minecraft:logs'}, {'type':'not','predicate':{'type':'matching_block_tag','tag':'minecraft:logs'}}]: + yield from predicate_cases({'type':'volume_match','min':minimum,'max':maximum,'match':child}) + for depth in [1,2,3]: + child={'type':'not','predicate':{'type':'matching_block_tag','tag':'minecraft:logs'}} + for _ in range(depth):child={'type':'volume_match','min':[0,0,0],'max':[1,1,1],'match':child} + yield from predicate_cases(child) + for definition in (provider_resources or {}).values(): + if definition.get('type') == 'minecraft:rule_based': + yield from cases(definition,all_states,wide=True) + for bounds in [[0,1,0],[2147483647,2,0],[-2147483648,384,63]]: + for f in cases({'type':'rule_based','rules':[{'if_true':inside,'then':{'id':'stone'}}]},[0]*len(positions),wide=True): + yield dict(f,bounds=bounds,positions=positions) + for kind in ['solid','replaceable']: + for offset in [None,[0,0,0],[16,-16,1],[-2147483648,0,0],[17,0,0],[],[0,0],False,[1.9,0,0]]: + predicate={'type':kind,'offset':offset} + definition={'type':'rule_based','fallback':{'id':'water'},'rules':[{'if_true':predicate,'then':{'id':'stone'}}]} + for f in cases(definition,all_states,wide=True):yield dict(f,positions=positions) + for f in cases(definition,[0,1],wide=True): + yield dict(f,fail=0,positions=positions) + yield dict(f,fail=1,positions=positions) + for condition in [{'type':'all_of','predicates':[false,{'type':kind}]},{'type':'any_of','predicates':[true,{'type':kind}]},{'type':'not','predicate':{'type':kind}},{'type':'volume_match','min':[-1,0,-1],'max':[1,0,1],'match':{'type':kind}}]: + definition={'type':'rule_based','fallback':empty,'rules':[{'if_true':condition,'then':empty},{'if_true':{'type':kind},'then':{'id':'stone'}}]} + for f in cases(definition,list(facts['defaults'].values()),wide=True): + yield f + yield dict(f,fail=0) + yield dict(f,fail=2) + if survival_rules: + representatives={} + neighbors=[facts['defaults'][name] for name in ['minecraft:air','minecraft:stone','minecraft:pale_moss_carpet','minecraft:shulker_box','minecraft:moving_piston'] if name in facts['defaults']] + def survival_provider(condition): + return {'type':'rule_based','fallback':{'id':'water'},'rules':[{'if_true':condition,'then':{'id':'stone'}}]} + for state in facts['states']: + rule=survival_rules.get(state['id']) + if rule is None:continue + key=survival.behavior_key(rule,state) + representatives.setdefault(key,state) + yield from cases(survival_provider({'type':'would_survive','state':state}),neighbors) + for state in representatives.values(): + yield from cases(survival_provider({'type':'would_survive','state':state}),all_states) + if survival_rules[state['id']] in ['Crop','PitcherCrop','Mushroom']: + for brightness in [-2147483648,-1,0,7,8,9,12,13,14,15,2147483647]: + for f in cases(survival_provider({'type':'would_survive','state':state}),all_states[::7],wide=True): + yield dict(f,brightness=brightness) + yield dict(f,brightness=brightness,query_fail=0) + yield dict(f,brightness=brightness,fail=0) + for offset in [[-16,0,16],[16,-16,0],[17,0,0],[-17,0,0],[0,0],None,'bad']: + condition={'type':'would_survive','state':state,'offset':offset} + for f in cases(survival_provider(condition),neighbors,wide=True): + yield dict(f,positions=positions) + yield dict(f,positions=positions,fail=0) + yield dict(f,positions=positions,query_fail=0) + condition={'type':'would_survive','state':state} + for combined in [{'type':'all_of','predicates':[false,condition]},{'type':'any_of','predicates':[true,condition]},{'type':'not','predicate':condition},{'type':'volume_match','min':[-1,0,-1],'max':[1,0,1],'match':condition}]: + definition={'type':'rule_based','rules':[{'if_true':combined,'then':empty},{'if_true':condition,'then':{'id':'stone'}}]} + for f in cases(definition,neighbors,wide=True): + yield f + yield dict(f,fail=1) + for state in ['stone','minecraft:water',{'id':'ladder','properties':{'facing':'east'}},{'id':'water','properties':{'level':'+01'}},'missing',{},None,False,[],{'id':'pale_moss_carpet','properties':{'bottom':'bad'}}]: + yield from cases(survival_provider({'type':'would_survive','state':state}),neighbors,wide=True) + yield from cases(survival_provider({'type':'would_survive'}),neighbors) + support_states = all_states if support_states is None else support_states + support_ids=set(support_states) + dynamic_support_states=[state for state in all_states if state not in support_ids] + for direction in ['down','up','north','south','west','east','UP','missing',None,False,1]: + for offset in [None,[0,0,0],[16,-16,1],[-2147483648,0,0],[17,0,0],[],[1.9,0,0]]: + condition={'type':'has_sturdy_face','direction':direction,'offset':offset} + definition={'type':'rule_based','fallback':{'id':'water'},'rules':[{'if_true':condition,'then':{'id':'stone'}}]} + valid=direction in ['down','up','north','south','west','east'] and offset not in [[17,0,0],[]] + for f in cases(definition,all_states if valid else [0],wide=False):yield dict(f,positions=positions) + for f in cases(definition,[0,1],wide=True):yield dict(f,positions=positions,fail=0) + for direction in ['down','up','north','south','west','east']: + definition={'type':'rule_based','fallback':{'id':'water'},'rules':[{'if_true':{'type':'has_sturdy_face','direction':direction},'then':{'id':'stone'}}]} + if dynamic_support_states: + for f in cases(definition,dynamic_support_states,wide=True): + for failure in [0,1,2]:yield dict(f,query_fail=failure,positions=positions) + for condition in [{'type':'all_of','predicates':[false,{'type':'has_sturdy_face','direction':direction}]},{'type':'any_of','predicates':[true,{'type':'has_sturdy_face','direction':direction}]},{'type':'not','predicate':{'type':'has_sturdy_face','direction':direction}}]: + definition={'type':'rule_based','rules':[{'if_true':condition,'then':empty},{'if_true':{'type':'has_sturdy_face','direction':direction},'then':{'id':'stone'}}]} + for f in cases(definition,support_states[::17],wide=True): + yield f + yield dict(f,fail=1) + for name in [*(catalog_resources or {}),'horizon:unknown','minecraft:stone','STONE',':']: + for f in cases(name,repeats=2,wide=True): + yield f + yield dict(f,holder=True) + for wrapper in [{'type':'copy_properties','source':name},{'type':'rotated','state':name}, + {'type':'randomized_int','source':name,'property':'age','values':1}, + {'type':'rule_based','fallback':name,'rules':[]}, + {'type':'rule_based','rules':[{'if_true':true,'then':name}]}]: + for f in cases(wrapper,repeats=2,wide=True): + yield f + yield dict(f,holder=True,fail=0) + for f in cases({'id':'stone','type':'copy_properties','source':name},wide=True): + yield f + yield dict(f,holder=True) + for definition in (provider_resources or {}).values(): + for f in cases(definition,list(facts['defaults'].values()),wide=True):yield dict(f,holder=True) + for value in [None,False,1,[],{}, {'type':'unknown'}, {'id':'missing'}, {'type':False}, {'type':'simple'}, {'type':'random_block'}, {'type':'weighted'}]: + yield from cases(value) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare',action='store_true') + parser.add_argument('--resume',action='store_true',help='Reuse stages only after verifying input, executable and output hashes') + args=parser.parse_args() + build=lab.LOCAL/'rust-state-provider-parity';build.mkdir(parents=True,exist_ok=True) + report_path=build/'report.json';report_path.unlink(missing_ok=True) + checkpoint_path=build/'run-state.json' + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStateProviderOracle.java' + helpers=[oracle.with_name(name+'.java') for name in ['VanillaBlockStateCodecOracle','VanillaHeightmapOracle','VanillaMaterialConditionOracle','VanillaBiomeTemperatureOracle','VanillaAnchorOracle','VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockSurvivalOracle','VanillaCollisionOracle']] + sources=[oracle,*helpers,lab.ROOT/'tools/test_block_survival_parity.py',lab.ROOT/'tools/test_biome_temperature_parity.py',lab.ROOT/'tools/test_material_condition_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/state_provider_fixture.rs'] + tested_sources=base.source_hashes(sources) + environment={'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'dependencies':{str(path):lab.digest(path,'sha256') for path in [*jars.values(),*libraries]}} + checkpoint=survival.load_checkpoint(checkpoint_path,tested_sources,environment) if args.resume else None + classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,stdout=log,stderr=subprocess.STDOUT,timeout=3600) + dependency_path=os.pathsep.join(map(str,libraries)) + def java(side,mode,path): + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStateProviderOracle',mode,path],side+'-'+mode) + if checkpoint is None: + checkpoint_path.unlink(missing_ok=True) + tags=worldgen.tag_resources(jars['server']) + if not tags or tags!=worldgen.tag_resources(jars['client']):raise ValueError('client/server tags differ') + tags.update({'horizon:empty':json.dumps({'values':[]}), 'horizon:ordered':json.dumps({'values':['minecraft:water','minecraft:stone','minecraft:water']})}) + (build/'tags.json').write_text(json.dumps(tags,separators=(',',':')),encoding='utf-8') + def fluid_tag_resources(jar): + with zipfile.ZipFile(jar) as archive: + prefix='data/minecraft/tags/fluid/' + return {'minecraft:'+name[len(prefix):-5]:archive.read(name).decode('utf-8') for name in sorted(archive.namelist()) if name.startswith(prefix) and name.endswith('.json')} + fluid_tags=fluid_tag_resources(jars['server']) + if fluid_tags!=fluid_tag_resources(jars['client']):raise ValueError('client/server fluid tags differ') + fluid_tags['horizon:empty']='{"values":[]}' + (build/'fluid-tags.json').write_text(json.dumps(fluid_tags,separators=(',',':')),encoding='utf-8') + biomes=temperature.biome_resources(jars['server']);biome_tags=material.biome_tag_resources(jars['server']) + if biomes!=temperature.biome_resources(jars['client']) or biome_tags!=material.biome_tag_resources(jars['client']):raise ValueError('client/server biome resources differ') + biome_tags['horizon:empty']='{"values":[]}' + biome_tags['horizon:ordered']='{"values":["minecraft:plains","minecraft:desert","minecraft:plains"]}' + for name,data in [('biomes',biomes),('biome_tags',biome_tags)]: + (build/(name+'.json')).write_text(json.dumps(data,separators=(',',':')),encoding='utf-8') + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,*helpers],'compile-java') + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars['server']),dependency_path]),'dev.horizonlab.parity.VanillaBlockPropertiesOracle','export',build],'properties-export') + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars['server']),dependency_path]),'dev.horizonlab.parity.VanillaBlockSupportOracle','export',build],'support-export') + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars['server']),dependency_path]),'dev.horizonlab.parity.VanillaBlockSurvivalOracle','definitions',build],'survival-export') + survival_classes=json.loads((build/'survival-classes.json').read_text()) + survival_rules=survival.bind_definitions(survival_classes,json.loads((build/'survival-placement-classes.json').read_text()),json.loads((build/'survival-support-tags.json').read_text())) + (build/'survival-rules.json').write_text(json.dumps(survival_rules,separators=(',',':'))) + support_states=json.loads((build/'support-cached-states.json').read_text()) + if len(support_states)!=35524:raise ValueError('incomplete support state cache') + for side in jars:java(side,'export',build/f'facts-{side}.json') + facts=json.loads((build/'facts-server.json').read_text()) + if facts!=json.loads((build/'facts-client.json').read_text()):raise ValueError('client/server registry metadata differs') + if len(facts['states'])!=35723:raise ValueError('incomplete pinned state registry') + def resources(jar): + with zipfile.ZipFile(jar) as archive: + return {name:json.loads(archive.read(name)) for name in sorted(archive.namelist()) if name.startswith('data/minecraft/worldgen/block_state_provider/') and name.endswith('.json')} + provider_resources=resources(jars['server']) + if provider_resources!=resources(jars['client']):raise ValueError('bundled noise provider resources differ') + (build/'providers.json').write_text(json.dumps(provider_resources,separators=(',',':')),encoding='utf-8') + catalog_resources={name.removeprefix('data/minecraft/worldgen/block_state_provider/').removesuffix('.json'):json.dumps(value,separators=(',',':')) for name,value in provider_resources.items()} + catalog_resources={'minecraft:'+name:value for name,value in catalog_resources.items()} + catalog_resources['horizon:empty']=json.dumps({'type':'random_block','blocks':[]}) + catalog_resources['horizon:tagged']=json.dumps({'type':'rule_based','rules':[{'if_true':{'type':'matching_block_tag','tag':'minecraft:logs'},'then':'minecraft:cave_vines_head'}],'fallback':'horizon:empty'}) + for depth in range(12): + catalog_resources['horizon:chain_'+str(depth)]=json.dumps({'type':'copy_properties','source':'horizon:chain_'+str(depth-1) if depth else 'horizon:tagged'}) + (build/'catalog.json').write_text(json.dumps(catalog_resources,separators=(',',':')),encoding='utf-8') + inputs=build/'inputs.txt';fixture_count=0;requested_samples=0 + with inputs.open('w',encoding='utf-8') as output: + for fixture in corpus(facts,tags,provider_resources,catalog_resources,fluid_tags,biomes,biome_tags,support_states,survival_rules): + output.write(json.dumps(fixture,separators=(',',':'))+'\n') + fixture_count+=1;requested_samples+=len(fixture['states'])*fixture['repeats']*2 + fixture_paths=[inputs,build/'survival-extra-definitions.json',build/'survival-placement-classes.json',build/'survival-support-tags.json',build/'survival-classes.json',build/'survival-rules.json',build/'cached-support.nbt',build/'support-cached-states.json',build/'block-properties.nbt',build/'cached-collision.nbt',build/'biomes.json',build/'biome_tags.json',build/'fluid-tags.json',build/'catalog.json',build/'providers.json',build/'tags.json',build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) + run(['cargo','build','--release','-p','horizon-world','--example','state_provider_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) + binary=Path(metadata['target_directory'])/'release/examples'/('state_provider_fixture.exe' if os.name=='nt' else 'state_provider_fixture') + counts={'block_states':len(facts['states']),'blocks':len(facts['defaults']),'integer_properties':len(facts['integers']),'codec_inputs':fixture_count,'provider_types':10,'named_providers':len(catalog_resources),'rule_predicate_types':16,'survival_supported_blocks':len(survival_rules),'survival_supported_states':sum(s['id'] in survival_rules for s in facts['states']),'support_cached_states':len(support_states),'support_dynamic_states':len(facts['states'])-len(support_states),'biomes':len(biomes),'biome_tag_files':len(biome_tags),'fluid_tag_files':len(fluid_tags),'bundled_provider_definitions':len(provider_resources),'block_tag_files':len(tags),'requested_samples':requested_samples} + base.ensure_sources_unchanged(sources,tested_sources) + checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':counts,'outputs':{}} + survival.save_checkpoint(checkpoint_path,checkpoint) + print('Verified inputs and compiled executables checkpointed',flush=True) + def stage(name,action): + output=build/(name+'.txt');previous=checkpoint['outputs'].get(name) + if previous is None or not output.exists() or lab.digest(output,'sha256')!=previous: + action() + checkpoint['outputs'][name]=lab.digest(output,'sha256') + survival.save_checkpoint(checkpoint_path,checkpoint) + print(f'{name}: completed output checkpointed',flush=True) + stage('rust',lambda:run([checkpoint['binary'],build],'rust'));references=[] + for side,jar in jars.items(): + stage(side,lambda:java(side,side,build));reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') + references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) + print(f'{side}: {matched:,} state-provider output lines match Rust',flush=True) + base.ensure_sources_unchanged(sources,tested_sources) + survival.load_checkpoint(checkpoint_path,tested_sources,environment) + report={'schema':1,**{key:value for key,value in environment.items() if key!='dependencies'},**checkpoint['counts'],'sources_sha256':tested_sources,'fixtures_sha256':{str(Path(name).relative_to(lab.ROOT)):digest for name,digest in checkpoint['fixtures_sha256'].items()},'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references,'scope':'Actual BlockStateProvider DIRECT_CODEC/TYPED_CODEC and simple, weighted, random_block, rotated, copy_properties, randomized_int three noise-based providers and rule_based over the pinned state registry. All states and block defaults, full-state versus typed exclusive decoding, ordered holder sets/tags, duplicates, empty optional results versus world-state fallback, zero/overflow weights, query failures, every state across six fixed rotations, nested random rotations, property copying for every target state against representatives of every compatible property value, integer-property ranges/missing properties, composed transforms and subsequent random consumption. Native property equality families are checked for ambiguity; Rust validates Cartesian state tables and uses compact property strides. Both legacy/xoroshiro streams execute directly and through WorldgenRandom. Noise comparisons include every bundled provider definition, independent legacy seeding, float/double scaling, dual-noise variety selection, threshold draw order and coordinate/codec boundaries. Rule-based comparisons cover true/not/all_of/any_of/inside_world_bounds/height_range/volume_match/matching_block_tag/matching_blocks/matching_fluids/matching_biomes/unobstructed/solid/replaceable/has_sturdy_face/would_survive predicates, ordered optional results, fallbacks, nested rules and world-query failures. Every pinned block-state fluid identity, amount, falling/source flag and own-height bits are derived from descriptors and compared. Fluid-holder sets and all bundled fluid tags are tested against every state. Biome-holder membership and all bundled biome tags are compared across every pinned biome identity, including empty sets, missing names, ordered world queries and short-circuit composition. Unobstructed predicates compare null excluded entities, exact translated unit-shape bounds, ignored-but-validated offsets, true/false world results and failures. Named holder versus direct/typed decoding, nested named providers, missing names, inline ambiguity, ordered resource registration and all bundled named definitions are compared. Solidity and replacement predicates cover every block state, offset wrapping/validation, empty-child fallthrough, composed predicates and query failures using privately imported definition flags and Rust-calculated collision solidity. Has-sturdy-face predicates cover all 35,723 states through unified cached/dynamic support dispatch across six directions, native offset rules, failed state reads, block-entity query failures and ordered optional-child/boolean composition. Block entities are absent in this integration corpus; shulker animation-state shape selection is separately tested and active moving-piston shape generation is tested separately. Would-survive decodes candidate states and bounded offsets, evaluates all supported candidate states and each rule against every neighbor state, and preserves world read/entity failures and short-circuit/optional-child behavior. All pinned survival families are bound through the recorded definition inputs. Complete registry loading/reloading, full block placement behavior and full feature generation remain pending.'} + lab.write_json(report_path,report);print(f'Scoped state-provider parity passed: {report_path}') + + +if __name__=='__main__':main() diff --git a/tools/test_structure_density_parity.py b/tools/test_structure_density_parity.py new file mode 100644 index 000000000..75094c3e6 --- /dev/null +++ b/tools/test_structure_density_parity.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Compare structure terrain-adaptation samplers with pinned vanilla bytecode.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + rng=random.Random(0x484f52495a4f4e4245415244) + kinds=["NONE","BURY","BEARD_THIN","BEARD_BOX","ENCAPSULATE"] + volumes=[[29,29,29,-14,-14,-14,1,1,1,3],[8,9,7,-17,-20,-19,4,5,6,7], + [3,2,4,100,200,300,1,1,1,5],[1,1,1,0,0,0,1,1,1,1]] + points=[[0,0,0],[-12,-12,-12],[11,11,11],[12,12,12],[-13,-13,-13],[-2**31,0,2**31-1],[2**31-1,-2**31,0]] + def fixture(pieces,junctions,affected,pts=None,vol=None): + return {"pieces":pieces,"junctions":junctions,"affected":affected,"points":points if pts is None else pts,"volumes":volumes if vol is None else vol} + # The full junction neighborhood spans every position in the 24-cubed kernel. + yield fixture([],[[0,0,0]],[-100,-100,-100,100,100,100]) + for affected in [None,[-1,-1,-1,1,1,1],[0,0,0,0,0,0]]: + yield fixture([],[],affected) + yield fixture([[[0,0,0,7,8,9],"BURY",0]],[[0,0,0]],affected) + for kind in kinds: + for delta in [-2**31,-33,-12,-1,0,1,12,33,2**31-1]: + yield fixture([[[0,0,0,7,8,9],kind,delta]],[],[-100,-100,-100,100,100,100]) + # Bulk floor clipping intentionally differs from scalar containment. + for affected in [[1,1,1,9,9,9],[-9,-9,-9,-1,-1,-1],[3,5,7,3,5,7]]: + yield fixture([[[0,0,0,7,8,9],"ENCAPSULATE",0]],[[0,0,0]],affected,vol=[[9,9,9,-16,-16,-16,4,4,4,9]]) + for scenario in range(96): + pieces=[];junctions=[] + for i in range(scenario%17): + low=[rng.randrange(-32,33) for _ in range(3)];high=[v+rng.randrange(17) for v in low] + pieces.append([low+high,rng.choice(kinds),rng.randrange(-32,33)]) + for i in range(scenario%11):junctions.append([rng.randrange(-32,33) for _ in range(3)]) + affected=None if scenario%13==0 else [-48,-48,-48,48,48,48] + pts=[[rng.randrange(-60,61) for _ in range(3)] for _ in range(256)] + vol=[[rng.randrange(1,13),rng.randrange(1,15),rng.randrange(1,13),rng.randrange(-60,0),rng.randrange(-60,0),rng.randrange(-60,0),rng.randrange(1,9),rng.randrange(1,9),rng.randrange(1,9),rng.randrange(8)]] + f=fixture(pieces,junctions,affected,pts,vol);yield f + if scenario%8==0:yield fixture(list(reversed(pieces)),list(reversed(junctions)),affected,pts,vol) + # Wrapped relative arithmetic, volume intersections and extreme ground deltas. + for coordinate in [-2**31,-2**31+32,2**31-33,2**31-1]: + low=[coordinate]*3;high=[min(2**31-1,coordinate+8)]*3 + for kind in kinds: + yield fixture([[low+high,kind,2**31-1]],[[coordinate,coordinate,coordinate]],[-2**31]*3+[2**31-1]*3, + [[coordinate]*3,[0,0,0],[-1,-1,-1]],[[3,3,3,coordinate,coordinate,coordinate,16,16,16,2]]) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-structure-density-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureDensityOracle.java" + sources=[oracle,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/structure_density_fixture.rs"] + tested_sources=base.source_hashes(sources) + fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + tested_fixtures=base.source_hashes([inputs]);classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") + run(["cargo","build","--release","-p","horizon-world","--example","structure_density_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("structure_density_fixture.exe" if os.name=="nt" else "structure_density_fixture") + run([binary,inputs,build/"rust.txt"],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaStructureDensityOracle",inputs,reference],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} structure-density output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged([inputs],tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"scalar_queries":sum(len(f["points"]) for f in fixtures),"volumes":sum(len(f["volumes"]) for f in fixtures), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual vanilla Beardifier constructor and scalar/bulk samplers from supplied ordered rigid pieces, jigsaw junctions and normalized affected bounds. Five terrain-adjustment modes, the full 24-cubed junction kernel neighborhood, ground-level offsets and extreme wrapping arithmetic, ordered accumulation, nullable/empty affected bounds, clipped strided volumes including scalar/bulk floor-clipping differences and oversized output tails. Floating outputs compared as canonical-NaN raw bits. Live structure discovery/filtering, invalid bounding-box repair, structure placement and terrain integration remain pending. Local Math.pow-derived kernel results do not establish cross-platform math parity."} + lab.write_json(report_path,report);print(f"Scoped structure-density parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_terrain_parity.py b/tools/test_terrain_parity.py new file mode 100644 index 000000000..3bd4dbcc6 --- /dev/null +++ b/tools/test_terrain_parity.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Compare noise-stage terrain filling with pinned vanilla client/server bytecode.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab, test_rust_parity as base, test_worldgen_parity as worldgen +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + + +def corpus(facts,bundle): + defaults=facts["defaults"] + rng=random.Random(0x484f52495a4f4e46494c4c) + def fixture(minimum,height,cx,cz,seed,legacy,block,fluid,sea,router,aquifers,repeats=1): + return {"min":minimum,"height":height,"noise_min":minimum,"noise_height":height,"cx":cx,"cz":cz,"seed":seed,"legacy":legacy, + "block":block,"fluid":fluid,"sea":sea,"router":router,"aquifers":aquifers,"initial":[],"repeats":repeats} + for setting,text in bundle["settings"].items(): + s=json.loads(text) + for legacy in [False,True]: + for seed,cx,cz in [(0,0,0),(-1,-2,3),(0x123456789abcdef,1875000,-1875000)]: + f=fixture(s["noise"]["min_y"],s["noise"]["height"],cx,cz,seed,legacy,defaults[s["default_block"]],defaults[s["default_fluid"]],s["sea_level"],s["noise_router"],s.get("aquifers"),2 if seed==0 else 1) + for i in range(16):f["initial"].append([i,f["min"]+(i*17)%f["height"],15-i,defaults["minecraft:glass"]]) + yield f + fields=["temperature","vegetation","continents","erosion","depth","ridges","chunk_surface_level","final_density"] + config={"barrier":0,"fluid_level_floodedness":1,"fluid_level_spread":0,"lava":0,"exclusion":0,"surface_level":64} + wet_slab=next(i for i,state in enumerate(facts["states"]) if state[0]=="minecraft:oak_slab" and state[2]) + states=[defaults["minecraft:"+name] for name in ["air","cave_air","void_air","stone","water","lava","oak_leaves"]]+[wet_slab] + for scenario in range(48): + router=dict.fromkeys(fields,0) + router["final_density"]=[0,1,-1,{"type":"gradient","axis":"y","from_coordinate":-64,"to_coordinate":0,"from_value":1,"to_value":-1}][scenario%4] + f=fixture(-64,64,scenario%5-2,scenario//5-4,rng.randrange(-2**63,2**63),bool(scenario%2),states[(scenario//4)%len(states)],states[scenario%len(states)],[-54,-20,0,64][scenario%4],router,config if scenario%3 else None,2) + # Fill only the middle of an extended chunk; prefilled areas must survive. + if scenario%5==0:f.update(min=-80,height=96) + f["initial"]=[[rng.randrange(16),f["min"]+rng.randrange(f["height"]),rng.randrange(16),rng.choice(states)] for _ in range(48)] + yield f + + + # Real structure-density bindings through both aquifer and final-density roots. + for _,text in bundle["settings"].items(): + setting=json.loads(text) + for legacy in [False,True]: + y=max(setting["noise"]["min_y"]+16,min(setting["sea_level"],setting["noise"]["min_y"]+setting["noise"]["height"]-16)) + f=fixture(setting["noise"]["min_y"],setting["noise"]["height"],0,0,123,legacy,defaults[setting["default_block"]],defaults[setting["default_fluid"]],setting["sea_level"],setting["noise_router"],setting.get("aquifers"),2) + f["initial"]=[[1,y,1,defaults["minecraft:glass"]]] + f["structure"]={"pieces":[[[2,y-4,2,10,y+8,10],"BEARD_BOX",2],[[8,y-2,8,15,y+2,15],"BURY",0]],"junctions":[[3,y,4],[11,y+1,13]],"affected":[-32,y-32,-32,48,y+40,48]} + yield f + for kind in ["NONE","BURY","BEARD_THIN","BEARD_BOX","ENCAPSULATE"]: + for enabled in [False,True]: + router=dict.fromkeys(fields,0);router["final_density"]={"type":"cache","input":{"type":"beardifier"}} + aq=dict(config);aq["barrier"]={"type":"beardifier"};aq["surface_level"]={"type":"add","left":-16,"right":{"type":"beardifier"}} + f=fixture(-64,96,-1,1,17,False,defaults["minecraft:stone"],defaults["minecraft:water"],-16,router,aq if enabled else None,2) + f["initial"]=[[0,0,0,defaults["minecraft:glass"]]] + f["structure"]={"pieces":[[[-14,-24,18,-3,-8,28],kind,3]],"junctions":[[-6,-18,23]],"affected":[-40,-48,-8,16,24,56]} + yield f + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepare",action="store_true") + args=parser.parse_args() + build=lab.LOCAL/"rust-terrain-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + tags=worldgen.tag_resources(jars["server"]) + if not tags or tags!=worldgen.tag_resources(jars["client"]):raise ValueError("client/server block tags differ or are empty") + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTerrainOracle.java" + exporter=oracle.with_name("VanillaHeightmapOracle.java") + sources=[oracle,exporter,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", + lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/terrain_fixture.rs"] + tested_sources=base.source_hashes(sources) + classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,exporter],"compile-java") + def java(side,mode,path): + run(["java","-Xmx1G","-cp",os.pathsep.join([str(classes),str(jars[side]),dependency_path]),"dev.horizonlab.parity."+("VanillaHeightmapOracle" if mode=="export" else "VanillaTerrainOracle"),mode,path],side+"-"+mode) + for side in jars:java(side,"export",build/f"facts-{side}.json") + facts=json.loads((build/"facts-server.json").read_text()) + if facts!=json.loads((build/"facts-client.json").read_text()):raise ValueError("client/server state facts differ") + if len(facts["states"])!=35723:raise ValueError("incomplete pinned state table") + bundle={"tags":tags} + for field,kind in [("noises","noise"),("densities","density_function"),("settings","noise_settings")]: + resources=worldgen.registry_resources(jars["server"],kind) + if not resources or resources!=worldgen.registry_resources(jars["client"],kind):raise ValueError("client/server "+kind+" resources differ") + prefix="data/minecraft/worldgen/"+kind+"/" + bundle[field]={"minecraft:"+name[len(prefix):-5]:text for name,text in resources.items()} + fixtures=list(corpus(facts,bundle));inputs=build/"inputs.txt" + inputs.write_text("".join(json.dumps(value,separators=(",",":"))+"\n" for value in fixtures),encoding="utf-8") + (build/"registries.json").write_text(json.dumps(bundle,separators=(",",":")),encoding="utf-8") + fixture_paths=[inputs,build/"registries.json",build/"facts-client.json",build/"facts-server.json"] + tested_fixtures=base.source_hashes(fixture_paths) + run(["cargo","build","--release","-p","horizon-world","--example","terrain_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("terrain_fixture.exe" if os.name=="nt" else "terrain_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + java(side,side,build) + reference=build/f"{side}.txt";matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} terrain-fill output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "block_states":len(facts["states"]),"block_tag_files":len(tags),"fixtures":len(fixtures),"fill_calls":sum(f["repeats"] for f in fixtures),"noise_aquifer_fixtures":sum(f["aquifers"] is not None for f in fixtures),"structure_density_fixtures":sum("structure" in f for f in fixtures), + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Noise-stage filling only, using actual vanilla NoiseBasedChunkGenerator.doFill and NoiseChunk with empty blending and empty or supplied rigid-piece/junction structure fields. Independently authenticated client/server registry resources and exported block identities/properties/air/fluid facts must agree. Rust compiles the final density and optional aquifer through a shared compiler/context, writes resident block sections, updates ocean-floor/world-surface worldgen heightmaps and records ordered per-section fluid postprocessing offsets. Comparisons cover every raw section state, heightmap word and postprocessing offset after each fill, all bundled routers/aquifers, both seeded random factories, synthetic roots, prefilled chunks, partial vertical volumes, repeated fills and structure-density bindings in final-density/aquifer graphs. Block behavior facts remain imported; actual biome properties and material rules are not evaluated. Surface/material/carver/feature/structure stages, nonempty blending and live structure discovery, complete generated worlds and gameplay/rendering remain pending."} + lab.write_json(report_path,report);print(f"Scoped terrain-fill parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_terrain_position.py b/tools/test_terrain_position.py index e067f577f..af4c8b642 100644 --- a/tools/test_terrain_position.py +++ b/tools/test_terrain_position.py @@ -29,7 +29,7 @@ def main(): args = parser.parse_args() root = build_pack.ROOT fixture = build_mod.build_integration_fixture("terrain-position", "dev.horizonlab.dispatch.PositionIntegration") - mod = root / "dist" / f"horizon-lab-{build_pack.read_lock()['pack_version']}.jar" + mod = root / "dist" / f"horizon-{build_pack.read_lock()['pack_version']}.jar" original_sha256 = hashlib.sha256(mod.read_bytes()).hexdigest() results = [] for enabled in [False, True]: diff --git a/tools/test_terrain_read.py b/tools/test_terrain_read.py index eaccf2199..b829d572e 100644 --- a/tools/test_terrain_read.py +++ b/tools/test_terrain_read.py @@ -23,7 +23,7 @@ def main(): args = parser.parse_args() root = build_pack.ROOT fixture = build_mod.build_integration_fixture("terrain-read", "dev.horizonlab.dispatch.TerrainReadIntegration") - mod = root / "dist" / f"horizon-lab-{build_pack.read_lock()['pack_version']}.jar" + mod = root / "dist" / f"horizon-{build_pack.read_lock()['pack_version']}.jar" original_sha256 = hashlib.sha256(mod.read_bytes()).hexdigest() results = [] for enabled in [False, True]: diff --git a/tools/test_tick_dedup.py b/tools/test_tick_dedup.py index 94153b614..4a518e062 100644 --- a/tools/test_tick_dedup.py +++ b/tools/test_tick_dedup.py @@ -22,7 +22,7 @@ def main(): args = parser.parse_args() root = build_pack.ROOT fixture = build_mod.build_tick_dedup_fixture() - mod = root / "dist" / f"horizon-lab-{build_pack.read_lock()['pack_version']}.jar" + mod = root / "dist" / f"horizon-{build_pack.read_lock()['pack_version']}.jar" results = [] for enabled in [False, True]: instance = root / ".local/runtime" / ("tick-dedup-fixture-patched" if enabled else "tick-dedup-fixture-upstream") diff --git a/tools/test_tick_parity.py b/tools/test_tick_parity.py new file mode 100644 index 000000000..4efcc93e9 --- /dev/null +++ b/tools/test_tick_parity.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Compare Rust scheduled-tick traces with checksum-pinned vanilla bytecode.""" +import argparse +from collections import Counter +import json +import os +from pathlib import Path +import platform +import random +import subprocess +import tempfile + +try: + from . import lab, test_rust_parity +except ImportError: + import lab + import test_rust_parity + + +def corpus(): + # Priority versus overdue time, first-request deduplication, and callback deferral. + yield "reset" + yield "add 0 0" + yield "add 1 0" + for command in ["schedule 0 0 64 0 1 3 10", "schedule 1 1 64 0 2 -3 11", + "schedule 2 16 64 0 3 0 12", "schedule 0 0 64 0 -100 -3 -99", + "save 0 0 0", "tick 10 1 0 1 1 64 0 100", "chunk 0 0", + "tick 10 20 1 0 0 64 0 100", "query 0 0 64 0", + "tick 10 20 0 0 0 64 0 100"]: + yield command + # Saved-list duplicates, negative load order, integer narrowing and time overflow. + for base in [-9223372036854775808, -2147483648, 0, 2147483647, 9223372036854775807]: + yield "reset" + yield "load -1 -1 4 0 -1 64 -1 -2147483648 -100 0 -1 64 -1 2147483647 100 1 -2 65 -2 -1 0 2 -3 66 -3 0 0" + yield "query 0 -1 64 -1" + yield "schedule 0 -1 64 -1 0 0 1" + yield f"save -1 -1 {base}" + yield f"unpack -1 -1 {base}" + yield "chunk -1 -1" + yield f"save -1 -1 {base}" + yield "tick 9223372036854775807 100 0 0 -1 64 -1 0" + yield "chunk -1 -1" + # Equal-key heads, map growth/shrink, chunk removal and heap tie behavior. + chunks = [(x, z) for x in range(-8, 9) for z in range(-4, 5)] + for reverse in [False, True]: + yield "reset" + for cx, cz in reversed(chunks) if reverse else chunks: + yield f"add {cx} {cz}" + for i in range(3): + yield f"schedule {i} {cx * 16 + i} 64 {cz * 16} {i % 2} 0 0" + for step in range(18): + yield f"tick 10 23 0 0 0 64 0 {step}" + if step % 3 == 0: + for cx, cz in chunks[step:step + 5]: + yield f"remove {cx} {cz}" + if step % 4 == 0: + for cx, cz in chunks[step:step + 8]: + yield f"restore {cx} {cz}" + yield "tick 100 10000 0 0 0 64 0 0" + # Force wraparound probe clusters in the deadline index. + def mix(key): + value = key * 0x9e3779b97f4a7c15 & ((1 << 64) - 1) + value ^= value >> 32 + return value ^ (value >> 16) + collisions = [x for x in range(1, 2000) if mix(x) & 31 == 31][:18] + yield "reset" + for x in collisions: + yield f"add {x} 0" + yield f"schedule 0 {x * 16} 64 0 0 0 0" + for _ in collisions: + yield "tick 0 1 0 0 0 64 0 0" + # Active membership, clear/copy, unload and eligibility changes in callbacks. + for action in range(6): + yield "reset" + for cx in range(-2, 4): + yield f"add {cx} 0" + for i in range(8): + yield f"schedule {i % 3} {cx * 16 + i} 64 0 0 {i % 7 - 3} {i}" + yield f"tick 0 35 {action} 1 1 64 0 9223372036854775806" + yield "query 1 1 64 0" + yield "tick 0 100 0 1 1 64 0 0" + yield "copy -32 0 0 15 100 15 16 0 0" + yield "clear -30 0 0 -1 100 0" + for cx in range(-2, 4): + yield f"chunk {cx} 0" + yield f"save {cx} 0 -1" + rng = random.Random(0x484F52495A4F4E5449434B) + positions = [(x, z) for x in range(-3, 4) for z in range(-3, 4)] + for scenario in range(8): + yield "reset" + for cx, cz in positions: + yield f"add {cx} {cz}" + for step in range(2500): + cx, cz = rng.choice(positions) + x, y, z = cx * 16 + rng.randrange(8), rng.randrange(-2, 3), cz * 16 + rng.randrange(8) + kind = rng.randrange(8) + order = rng.choice([step, -step, 0, -9223372036854775808, 9223372036854775807]) + operation = rng.randrange(100) + if operation < 55: + yield f"schedule {kind} {x} {y} {z} {rng.randrange(-5, 50)} {rng.randrange(-7, 8)} {order}" + if step % 7 == 0: + yield f"schedule {kind} {x} {y} {z} {rng.randrange(-10, 100)} 0 {order}" + elif operation < 65: + yield f"tick {rng.randrange(-5, 55)} {rng.choice([-1, 0, 1, 2, 7, 17, 100])} {rng.randrange(6)} {kind} {x} {y} {z} {order}" + elif operation < 70: + yield f"query {kind} {x} {y} {z}" + elif operation < 75: + yield f"enable {cx} {cz} {rng.randrange(2)}" + elif operation < 80: + yield f"remove {cx} {cz}" + yield f"restore {cx} {cz}" + elif operation < 84: + yield f"add {cx} {cz}" + elif operation < 88: + yield f"reload {cx} {cz} {rng.randrange(-10, 50)} {rng.randrange(-10, 50)}" + elif operation < 92: + yield f"save {cx} {cz} {rng.choice([step, -step, -9223372036854775808, 9223372036854775807])}" + elif operation < 95: + yield f"chunk {cx} {cz}" + elif operation < 98: + yield f"clear {x} -2 {z} {x + rng.randrange(20)} 2 {z + rng.randrange(20)}" + else: + yield f"copy {x} -2 {z} {x + 7} 2 {z + 7} 16 0 0" + for cx, cz in positions: + yield f"enable {cx} {cz} 1" + yield "tick 9223372036854775807 100000 0 0 0 0 0 0" + for cx, cz in positions: + yield f"chunk {cx} {cz}" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepare", action="store_true") + args = parser.parse_args() + directory = lab.LOCAL / "rust-tick-parity" + directory.mkdir(parents=True, exist_ok=True) + report_path = directory / "report.json" + report_path.unlink(missing_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = test_rust_parity.verify_artifacts() + base = Path(tempfile.mkdtemp(prefix="run-", dir=directory)) + commands = list(corpus()) + inputs = base / "inputs.txt" + inputs.write_text("\n".join(commands) + "\n", encoding="utf-8") + oracle = lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTickOracle.java" + data_oracle = oracle.with_name("VanillaTickDataOracle.java") + sources = [oracle, data_oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/tick_fixture.rs"] + tested_sources = test_rust_parity.source_hashes(sources) + classes = base / "classes" + classes.mkdir() + dependency_path = os.pathsep.join(map(str, libraries)) + test_rust_parity.run(["javac", "--release", "25", "-proc:none", "-cp", os.pathsep.join([str(jars["server"]), dependency_path]), "-d", str(classes), str(oracle), str(data_oracle)]) + test_rust_parity.run(["cargo", "build", "--release", "--bin", "horizon-tick-parity"]) + metadata = json.loads(subprocess.check_output(["cargo", "metadata", "--no-deps", "--format-version", "1"], cwd=lab.ROOT, text=True)) + binary = Path(metadata["target_directory"]) / "release" / ("horizon-tick-parity.exe" if os.name == "nt" else "horizon-tick-parity") + candidate = base / "rust.txt" + with inputs.open("rb") as stdin, candidate.open("wb") as stdout: + test_rust_parity.run([str(binary)], stdin=stdin, stdout=stdout) + def data_java(side, mode): + completed = subprocess.run(["java", "-Xmx512M", "-cp", os.pathsep.join([str(classes), str(jars[side]), dependency_path]), "dev.horizonlab.parity.VanillaTickDataOracle", mode, str(base)], cwd=lab.ROOT, capture_output=True, text=True, timeout=300) + (base / f"data-{side}-{mode}.log").write_text(completed.stdout + completed.stderr, encoding="utf-8") + completed.check_returncode() + return completed.stdout + data_java("server", "generate") + test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "tick_fixture"]) + fixture = Path(metadata["target_directory"]) / "release/examples" / ("tick_fixture.exe" if os.name == "nt" else "tick_fixture") + test_rust_parity.run([str(fixture), str(base)]) + references = [] + for side, jar in jars.items(): + reference = base / f"vanilla-{side}.txt" + with (base / f"vanilla-{side}.log").open("wb") as log: + test_rust_parity.run(["java", "-Xmx512M", "-cp", os.pathsep.join([str(classes), str(jar), dependency_path]), "dev.horizonlab.parity.VanillaTickOracle", str(inputs), str(reference)], stdout=log, stderr=subprocess.STDOUT) + matched = test_rust_parity.compare(reference, candidate) + output = data_java(side, "verify") + marker = "HORIZON_TICK_DATA_RESULT " + counts = [json.loads(line.split(marker, 1)[1]) for line in output.splitlines() if marker in line] + if len(counts) != 1 or counts[0] != {"block_ticks": 251, "fluid_ticks": 251, "region_chunks": 1}: + raise AssertionError(f"Incomplete tick save fixture: {counts}") + references.append({"side": side, "jar_sha256": lab.digest(jar, "sha256"), "output_sha256": lab.digest(reference, "sha256"), "matched_output_lines": matched, **counts[0]}) + print(f"{side}: {matched:,} scheduled-tick output lines match", flush=True) + test_rust_parity.ensure_sources_unchanged(sources, tested_sources) + report = {"schema": 1, "minecraft": lock["minecraft"]["version"], "manifest_sha1": lock["minecraft"]["manifest_sha1"], "platform": platform.platform(), + "java": subprocess.check_output(["java", "--version"], text=True).splitlines()[0], "rustc": subprocess.check_output(["rustc", "--version"], text=True).strip(), + "commands": dict(Counter(command.split()[0] for command in commands)), "inputs_sha256": lab.digest(inputs, "sha256"), "rust_output_sha256": lab.digest(candidate, "sha256"), + "sources_sha256": tested_sources, "references": references, + "scope": "Scheduled tick ordering, deduplication, save packing, chunk eligibility/loading and callback mutations only. Block/fluid behavior is not implemented."} + lab.write_json(report_path, report) + lab.write_json(base / "report.json", report) + print(f"Scheduled-tick comparison passed: {report_path}") + + +if __name__ == "__main__": + main() diff --git a/tools/test_value_provider_parity.py b/tools/test_value_provider_parity.py new file mode 100644 index 000000000..f276e4f31 --- /dev/null +++ b/tools/test_value_provider_parity.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Compare scalar value-provider decoding and seeded samples with pinned vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab,test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def definitions(): + encode=lambda value:json.dumps(value,separators=(',',':')) + for kind in ['float','int']: + for token in ['null','false','true','[]','{}','"0"','0','-0.0','1','-1','0.123456789','2.9','-2.9','4294967296','-4294967297','1e100','-1e100','1e-100','-1e-100']: + yield kind,token + yield kind,'{"type":"constant","value":'+token+'}' + for value in [{},{'type':'missing'},{'type':None},{'type':'constant'},{'type':'Constant','value':0},{'type':':constant','value':17}]:yield kind,encode(value) + for minimum,maximum in [(0,1),(-1,1),(-0.,0.),(1,1),(2,1),(-1e100,1e100),(1e100,1e100),(-1e-100,1e-100),(-0.7,1.3),(-1e30,1e30)]: + yield 'float',encode({'type':'uniform','min_inclusive':minimum,'max_exclusive':maximum}) + for plateau in [-1,0,0.1,1,3,1e100]:yield 'float',encode({'type':'trapezoid','min':minimum,'max':maximum,'plateau':plateau}) + ranges=[(0,0),(0,1),(-1,1),(1,1),(2,1),(-7,13),(0,14),(0,9),(-2**31,2**31-1),(0,2**31-1),(-2**31,-2**31+100),(2**31-100,2**31-1),(0,4294967297)] + for minimum,maximum in ranges: + for kind in ['uniform','biased_to_bottom','very_biased_to_bottom']: + value={'type':kind,'min_inclusive':minimum,'max_inclusive':maximum};yield 'int',encode(value) + for low,high in [(0,3),(-100,-50),(50,100),(1,0)]:yield 'int',encode({'type':'clamped','source':value,'min_inclusive':low,'max_inclusive':high}) + for plateau in [-2**31,-10,-1,0,1,3,maximum-minimum,2**31-1]:yield 'int',encode({'type':'trapezoid','min':minimum,'max':maximum,'plateau':plateau}) + for kind in ['float','int']: + yield kind,'{"type":"constant","value":0,"value":-0.0}' + for field in ['min_inclusive','max_exclusive' if kind=='float' else 'max_inclusive']: + for token in ['null','false','"1"','{}','[]']: + yield kind,'{"type":"uniform","min_inclusive":0,"'+('max_exclusive' if kind=='float' else 'max_inclusive')+'":1,"'+field+'":'+token+'}' + + + # Zero-weight entries remain part of declared bounds, but are never sampled. + constant = (lambda n: {'absolute': n}) if False else (lambda n: n) + weighted = lambda entries: {'type': 'weighted_list', 'distribution': entries} + entry = lambda value, weight: {'data': value, 'weight': weight} + choices = [constant(-7), constant(19), {'type': 'uniform', 'min_inclusive': constant(0), 'max_inclusive': constant(31)}] + for weights in [(1,), (0,), (0, 1), (1, 0), (1, 1), (1, 62), (1, 63), (1, 64), (0, 3, 7), (2147483647,), (2147483646, 1), (2147483647, 1), (-1, 2), (4294967297, 2), (0.9, 1.9)]: + value = weighted([entry(choices[i % len(choices)], weight) for i, weight in enumerate(weights)]) + yield 'int', encode(value) + nested = weighted([entry(constant(5), 1), entry(constant(-9), 4)]) + yield 'int', encode(weighted([entry(nested, 3), entry(choices[-1], 2)])) + for distribution in [None, {}, [], [entry(constant(0), 0), entry(constant(1), 0)], [entry(None, 0), entry(constant(1), 1)], [{'data': constant(1)}], [{'weight': 1}], [entry(constant(1), '1')], [entry(constant(1), None)]]: + yield 'int', encode(weighted(distribution)) + + +def corpus(): + definitions_list=list(definitions()) + for legacy in [False,True]: + for seed in [0,-1,0x123456789abcdef,-2**63,2**63-1]: + for kind,definition in definitions_list:yield {'kind':kind,'definition':definition,'legacy':legacy,'seed':seed,'samples':64} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument("--prepare",action="store_true");args=parser.parse_args() + build=lab.LOCAL/"rust-value-provider-parity";build.mkdir(parents=True,exist_ok=True) + report_path=build/"report.json";report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaValueProviderOracle.java" + sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/value_provider_fixture.rs"] + tested_sources=base.source_hashes(sources) + fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") + fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") + run(["cargo","build","--release","-p","horizon-world","--example","value_provider_fixture"],"compile-rust") + metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary=Path(metadata["target_directory"])/"release/examples"/("value_provider_fixture.exe" if os.name=="nt" else "value_provider_fixture") + run([binary,build],"rust") + references=[] + for side,jar in jars.items(): + reference=build/f"{side}.txt" + run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaValueProviderOracle",side,build],side) + matched=base.compare(reference,build/"rust.txt") + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched}) + print(f"{side}: {matched:,} value-provider output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={"schema":1,"minecraft":lock["minecraft"]["version"],"manifest_sha1":lock["minecraft"]["manifest_sha1"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "fixtures":len(fixtures),"definitions":len(list(definitions())),"samples_per_valid_fixture":64, + "sources_sha256":tested_sources,"fixtures_sha256":tested_fixtures,"rust_output_sha256":lab.digest(build/"rust.txt","sha256"),"references":references, + "scope":"Actual FloatProviders.CODEC and IntProviders.CODEC decoding, declared ranges, seeded samples and interleaved subsequent nextLong values. Covers constant/uniform/trapezoid floats and constant/uniform/biased-to-bottom/very-biased-to-bottom/trapezoid/clamped/weighted-list integers, both random modes, numeric narrowing, signed zeros, overflow, equal/reversed bounds, negative plateaus, missing fields, duplicate keys and sampling failures. Float NaNs are canonicalized. Weighted lists include zero weights, singleton draws, nested providers, 63/64/65 weight totals, maximum/overflow totals and malformed entries; native constructor rejections count as decode errors. Gaussian providers, encoding, height providers and complete generation remain outside this scope."} + + lab.write_json(report_path,report);print(f"Scoped value-provider parity passed: {report_path}") + + +if __name__=="__main__":main() diff --git a/tools/test_world_parity.py b/tools/test_world_parity.py new file mode 100644 index 000000000..9f4bb5d52 --- /dev/null +++ b/tools/test_world_parity.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Exercise Rust NBT, palette, registry and region I/O with pinned vanilla bytecode.""" +import argparse +import json +import os +from pathlib import Path +import platform +import subprocess +import tempfile + +try: + from . import lab, test_rust_parity +except ImportError: + import lab + import test_rust_parity + + +def run(command, log=None): + result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, capture_output=True, text=True, timeout=300) + if log: + log.write_text(result.stdout + result.stderr, encoding="utf-8") + if result.returncode: + raise RuntimeError(f"Command failed ({result.returncode}): {command[0]}\n{result.stdout[-3000:]}\n{result.stderr[-3000:]}") + return result.stdout + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepare", action="store_true") + args = parser.parse_args() + directory = lab.LOCAL / "rust-world-parity" + directory.mkdir(parents=True, exist_ok=True) + report_path = directory / "report.json" + report_path.unlink(missing_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = test_rust_parity.verify_artifacts() + base = Path(tempfile.mkdtemp(prefix="run-", dir=directory)) + classes = base / "classes" + classes.mkdir() + oracle = lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldOracle.java" + sources = [oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-world/Cargo.toml", + *sorted((lab.ROOT / "crates/horizon-world").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs"))] + tested_sources = test_rust_parity.source_hashes(sources) + dependency_path = os.pathsep.join(map(str, libraries)) + run(["javac", "--release", "25", "-proc:none", "-cp", os.pathsep.join([str(jars["server"]), dependency_path]), "-d", classes, oracle], base / "compile-java.log") + + def java(side, mode): + return run(["java", "-Xmx1G", "-cp", os.pathsep.join([str(classes), str(jars[side]), dependency_path]), + "dev.horizonlab.parity.VanillaWorldOracle", mode, base], base / f"{side}-{mode}.log") + + print("Generating vanilla world-data fixtures...", flush=True) + print(java("server", "generate").split("HORIZON_WORLD_GENERATED")[-1].strip(), flush=True) + run(["cargo", "build", "--release", "-p", "horizon-world", "--bin", "horizon-world", "--example", "world_fixture"], base / "compile-rust.log") + metadata = json.loads(run(["cargo", "metadata", "--no-deps", "--format-version", "1"])) + target = Path(metadata["target_directory"]) / "release" + suffix = ".exe" if os.name == "nt" else "" + binary = target / ("horizon-world" + suffix) + run([target / "examples" / ("world_fixture" + suffix), base], base / "rust-fixture.log") + for network in [False, True]: + kind = "network" if network else "nbt" + output = base / "rust" / kind + output.mkdir(parents=True) + for source in range(1, 5): + for destination in range(1, 5): + run([binary, "nbt-network-copy" if network else "nbt-copy", base / kind / f"{source}.bin", + output / f"{source}-{destination}.bin", source, destination]) + for source in range(1, 5): + original = base / "regions" / str(source) / "r.-1.0.mca" + for variant in ["copy", "1", "2", "3", "4"]: + output = base / "rust/regions" / f"{source}-{variant}" / original.name + command = [binary, "copy-region", original, output] + if variant != "copy": + command.append(variant) + run(command) + output = base / "rust/regions" / f"{source}-edited" / original.name + run([binary, "edit-block-data", original, output, -512, -64, 0, "minecraft:stone"]) + actual = run([binary, "get-block", output, -512, -64, 0]).strip() + if actual != "minecraft:stone": + raise AssertionError(f"CLI returned unexpected edited block: {actual}") + # A second export must fail without changing the existing output. + before = lab.digest(output, "sha256") + attempt = subprocess.run([str(binary), "copy-region", str(original), str(output)], capture_output=True, timeout=30) + if attempt.returncode == 0 or lab.digest(output, "sha256") != before: + raise AssertionError("Existing region output was not protected") + references = [] + for side in ["server", "client"]: + print(f"Checking Rust-written world data in vanilla {side}...", flush=True) + output = java(side, "verify") + marker = "HORIZON_WORLD_RESULT " + results = [json.loads(line.split(marker, 1)[1]) for line in output.splitlines() if marker in line] + expected = {"nbt_pairs": 32, "palettes": 44, "palette_values": 123776, + "region_chunks": 48, "registry_states": 35723, "resident_values": 8192} + if len(results) != 1 or any(results[0].get(key) != value for key, value in expected.items()): + raise AssertionError(f"Incomplete world fixture: {results}") + references.append({"side": side, "jar_sha256": lab.digest(jars[side], "sha256"), **results[0]}) + print(json.dumps(references[-1]), flush=True) + test_rust_parity.ensure_sources_unchanged(sources, tested_sources) + report = {"schema": 1, "minecraft": lock["minecraft"]["version"], "data_version": 5023, + "platform": platform.platform(), "java": run(["java", "--version"]).splitlines()[0], + "rustc": run(["rustc", "--version"]).strip(), "references": references, + "sources_sha256": tested_sources, + "notes": ["Synthetic NBT and region fixtures serialized and verified by pinned vanilla classes.", + "Includes all four region codecs, external oversized chunks, UTF-16 edge cases, mixed lists, palette mutation, and the full exported block-state ID registry.", + "Storage-only edits; no world generation, simulation, lighting, live multiplayer, renderer, FPS or whole-game parity claim."]} + lab.write_json(report_path, report) + lab.write_json(base / "report.json", report) + print(f"World-data interoperability passed: {report_path}") + + +if __name__ == "__main__": + main() diff --git a/tools/test_worldgen_parity.py b/tools/test_worldgen_parity.py new file mode 100644 index 000000000..134a9cec8 --- /dev/null +++ b/tools/test_worldgen_parity.py @@ -0,0 +1,394 @@ +#!/usr/bin/env python3 +"""Compare world-generation JSON decoding with the pinned vanilla codecs.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +from collections import Counter +import platform +import random +import subprocess +import zipfile + +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(resources): + rng = random.Random(0x484f52495a4f4e4a534f4e) + seeds = [0,1,-1,-2**63,2**63-1,0x123456789abcdef] + for text in resources.values(): + compact = " ".join(text.splitlines()) + for seed in seeds: + for legacy,nether in [(0,0),(1,0),(0,1),(1,1)]: + yield f"noise {seed} {legacy} {nether} {compact}" + fields = { + "base_octave": ["-33","-32","0","32","33","4294967295","4294967296","-4294967297.9","1.9999999999999999999","12e1","123e-1","-123e-3","123e99","null","true",'"-7"'], + "octave_count": ["0","1","32","33","-1","null","false","1.9999999999999999999","4294967297"], + "base_amplitude": ["0","0.000009999999747378751","0.000009999999747378752","1","1000000","1000000.0000000001","null","true"], + "normalize": ["true","false",'"legacy"',"0","1","0.5","4294967296","null",'"true"','"LEGACY"',"{}"], + "amplitude_modifiers": ["[]","[0]","[-0]","[-0.0]","[1]","[1000000]","[1000001]","[-1]","[null]","null","[1,2]","{}"], + } + for name,values in fields.items(): + for value in values: + text = '{"base_octave":-7,"'+name+'":'+value+'}' if name != "base_octave" else '{"base_octave":'+value+'}' + yield f"noise 0 0 0 {text}" + for text in ['{}','[]','null','42','true','{"base_octave":-7,"unknown":{}}','{"base_octave":-7,"base_octave":-8}']: + yield f"noise 0 0 0 {text}" + for scenario in range(512): + count = 1 + scenario % 8 + parameters = {"base_octave":rng.randrange(-16,1),"octave_count":count} + if scenario % 3: + parameters["base_amplitude"] = rng.choice([.00001,.125,1.,1e6,rng.uniform(.00001,1e6)]) + if scenario % 4: + parameters["normalize"] = [True,False,"legacy"][scenario % 3] + if scenario % 5: + parameters["amplitude_modifiers"] = [rng.choice([0.,.125,1.,1e6,rng.uniform(0,1e6)]) for _ in range(count)] + yield f"noise {rng.randrange(-2**63,2**63)} {(scenario//2)%2} {scenario%2} "+json.dumps(parameters,separators=(",",":")) + + +def registry_resources(jar, kind): + prefix = f"data/minecraft/worldgen/{kind}/" + with zipfile.ZipFile(jar) as archive: + return {name:archive.read(name).decode("utf-8") for name in sorted(archive.namelist()) if name.startswith(prefix) and name.endswith(".json")} + + +def tag_resources(jar): + prefix="data/minecraft/tags/block/" + with zipfile.ZipFile(jar) as archive: + return {"minecraft:"+name[len(prefix):-5]:archive.read(name).decode("utf-8") for name in sorted(archive.namelist()) if name.startswith(prefix) and name.endswith(".json")} + + +def tag_corpus(resources): + entry_values=['"stone"','"#leaves"','""','"#"','":stone"','"minecraft:"','"Minecraft:stone"','"STONE"','"a:b:c"','"a/b:stone"','"#minecraft:leaves"','"##leaves"','42','true','null','[]','{}','{"id":"stone"}','{"id":"#leaves","required":false}','{"id":"stone","required":null}','{"id":null}','{"required":true}'] + for value in entry_values:yield "tag_entry "+value + for required in ['true','false','null','0','1','0.5','4294967296','"true"','{}','[]']: + yield 'tag_entry {"id":"stone","required":'+required+'}' + for text in resources.values():yield "tag_file "+" ".join(text.splitlines()) + for value in entry_values:yield 'tag_file {"values":['+value+']}' + for value in ['true','false','null','0','1','"false"','{}']: + yield 'tag_file {"values":[],"replace":'+value+'}' + for text in ['{}','[]','null','{"values":null}','{"values":true}','{"values":[],"replace":true,"replace":false}']: + yield 'tag_file '+text + def command(files,elements):return "tags "+json.dumps({"files":files,"elements":elements},separators=(",",":")) + def file(name,values,replace=False):return [name,"fixture",json.dumps({"values":values,"replace":replace},separators=(",",":"))] + elements={"minecraft:a":"a","minecraft:b":"b","minecraft:c":"c","minecraft:alias":"a"} + yield command([file("first",["b","a","b","alias"]),file("second",["#first","c","a"])],elements) + yield command([file("a",["a","b"]),file("a",["c"],True),file("a",["a"]),file("empty",[])],elements) + yield command([["a","broken","{}"],file("a",["a"]),["a","broken","{\"replace\":true,\"values\":[true]}"],["empty","broken","null"]],elements) + yield command([file("a",["missing","a"]),file("b",["#a","b"]),file("c",[{"id":"#a","required":False},"c"])],elements) + for mandatory in [True,False]: + yield command([file("a",[{"id":"#b","required":mandatory},"a"]),file("b",[{"id":"#a","required":mandatory},"b"])],elements) + # Required dependencies are processed globally before optional ones. + yield command([file("a",[{"id":"#b","required":False},"a"]),file("b",["#a","b"])],elements) + # Canonicalize unordered missing-tag output by full string, not Identifier's + # path-first comparator; lookup/dependency iteration remains observable. + yield command([file("z:first",["missing"]),file("a:last",["#z:first"]),file("example:child",[{"id":"#z:first","required":False},"a"])],elements) + rng=random.Random(0x484f52495a4f4e54414753) + for scenario in range(192): + count=1+scenario%48;files=[] + for i in range(count): + values=[] + for j in range(rng.randrange(9)): + if i and j%3==0: + # Later dependency names make arbitrary cycles possible. + child=rng.randrange(count) if scenario%4==0 else rng.randrange(i) + if child==i:child=(child+1)%count + values.append({"id":f"#tag_{child}","required":j%2==0}) + else:values.append({"id":rng.choice(["a","b","c","alias","missing"]),"required":j%3!=0}) + files.append(file(f"tag_{i}",values)) + if i%11==0:files.append(file(f"tag_{i}",["c"],scenario%3==0)) + yield command(files,elements) + + +def noise_resources(jar): + return registry_resources(jar,"noise") + + +def climate_corpus(): + rng = random.Random(0x484f52495a4f4e434c494d) + edges = [0,0x80000000,1,0x80000001,0x007fffff,0x00800000, + 0x3f800000,0xbf800000,0x38d1b717,0xb8d1b717, + 0x58612e12,0xd8612e12,0x7f7fffff,0xff7fffff, + 0x7f800000,0xff800000,0x7f800001,0xff800001,0x7fc00000,0xffc00000] + longs = [0,1,-1,-2**63,2**63-1,-10000,10000,16777217,-16777217] + for scenario in range(len(edges)+4096): + values = [edges[(scenario+i)%len(edges)] for i in range(6)] if scenario < len(edges) else [rng.getrandbits(32) for _ in range(6)] + value = longs[scenario%len(longs)] if scenario < len(edges) else rng.randrange(-2**63,2**63) + yield "quantize "+" ".join(f"{value:08x}" for value in values)+f" {value}" + + +def climate_codec_corpus(): + values = ["-2.0000002","-2","-0.0001","-0","0","0.0001","1","2","2.0000001","2.0000001192092895507812500000000001","2.0000002","1e100","null","true",'"1"',"[]","[0]","[0,0,0]","[-2,2]","[1,-1]","[-0,0]","[0,-0]",'{"min":-2,"max":2}','{"min":0}', '{"min":0,"max":0,"ignored":1}'] + for value in values: + yield "climate_parameter "+value + fields = ["temperature","humidity","continentalness","erosion","depth","weirdness","offset"] + for field in fields: + for value in values: + yield "climate_point {"+",".join('"'+name+'":'+(value if field == name else "0") for name in fields)+"}" + yield "climate_point {"+",".join('"'+name+'":0' for name in fields if field != name)+"}" + yield 'climate_point {"temperature":0,"humidity":0,"continentalness":0,"erosion":0,"depth":0,"weirdness":0,"offset":0,"offset":1}' + + +def settings_corpus(resources): + for text in resources.values(): + # The noise member contains integers in bundled resources. Keep all + # synthetic numeric tokens below raw for Gson integer conversion cases. + yield "noise_settings "+json.dumps(json.loads(text)["noise"],separators=(",",":")) + minima = [-2**31,-2033,-2032,-2031,-65,-64,-16,-1,0,1,16,2031,2032,2**31-1] + heights = [-2**31,-16,-1,0,1,15,16,128,384,4063,4064,4065,2**31-1] + for minimum in minima: + for height in heights: + yield f'noise_settings {{"min_y":{minimum},"height":{height}}}' + yield f"settings_create {minimum} {height}" + for field in ["min_y","height"]: + for value in ["null","true",'"16"',"4294967296","4294967312","-4294967312.999999999999","15.9999999999999999999","16.9999999999999999999","16e0","16e-1","16e99"]: + yield 'noise_settings {"'+field+'":'+value+','+('"height":16' if field == "min_y" else '"min_y":0')+'}' + for text in ['{}','[]','null','{"min_y":0}','{"height":0}','{"min_y":0,"height":16,"height":32,"ignored":0}']: + yield "noise_settings "+text + + +def aquifer_corpus(): + rng = random.Random(0x484f52495a4f4e464c554944) + bits = [0,0x8000000000000000,1,0x8000000000000001,0x3ff0000000000000,0xbff0000000000000,0x7fefffffffffffff,0xffefffffffffffff,0x7ff0000000000000,0xfff0000000000000,0x7ff0000000000001,0xfff8000000000000] + for sea in [-2**31,-64,-54,0,63,2**31-1]: + for fluid in range(5): + for y in [-2**31,-4065,-4064,-65,-64,-55,-54,-53,-1,0,62,63,64,2**31-1]: + for value in bits: + yield f"aquifer {sea} {fluid} 0 {y} 0 {value:016x}" + for _ in range(4096): + sea,x,y,z = [rng.randrange(-2**31,2**31) for _ in range(4)] + yield f"aquifer {sea} {rng.randrange(5)} {x} {y} {z} {rng.getrandbits(64):016x}" + + +def noise_aquifer_corpus(bundle, resources): + """Stateful original transport, with vanilla samplers and fault injection.""" + rng = random.Random(0x484f52495a4f4e41515549) + density_bits = ["0000000000000000","8000000000000000","bff0000000000000","bfb999999999999a","0000000000000001","8000000000000001","7ff0000000000000","fff0000000000000","7ff0000000000001","fff8000000000000"] + def emit(seed, legacy, setting, fixture): + return f"noise_aquifer {seed} {legacy} {bundle} {setting} "+json.dumps(fixture,separators=(",",":")) + def fixture(minimum, sizes=(16,128,16), steps=(1,1,1), count=128): + queries=[] + for i in range(count): + # Exercise strided volume extents, not just density lattice samples. + p=[minimum[a]+rng.randrange(sizes[a]*steps[a]) for a in range(3)] + queries.append([*p,density_bits[i%len(density_bits)]]) + queries += queries[:16] + list(reversed(queries[:16])) + return {"sizes":sizes,"minimum":minimum,"steps":steps,"sea":63,"fluid":0,"queries":queries} + for setting in sorted(resources): + for seed in [0,1,-1,-2**63,2**63-1,0x123456789abcdef]: + for legacy in [0,1]: + f=fixture([-16,-64,32]) + yield emit(seed,legacy,setting,f) + def gradient(axis, low, high, start, end): + return {"type":"gradient","axis":axis,"from_coordinate":low,"to_coordinate":high,"from_value":start,"to_value":end} + base={"barrier":0,"fluid_level_floodedness":gradient("x",-96,96,-1,1),"fluid_level_spread":gradient("y",-4,4,-1,1),"lava":gradient("z",-4,4,-1,1),"exclusion":0,"surface_level":96} + origins=[[0,-64,0],[-16,-80,32],[33554416,-64,-33554432],[2147483600,-64,-2147483600]] + float_bits=["00000000","80000000","00000001","80000001","3f800000","bf800000","3f19999a","3f4ccccd","7f800000","ff800000","7fc00000","7f800001","7f7fffff","ff7fffff"] + for scenario in range(160): + f=fixture(origins[scenario%len(origins)],count=192) + config=dict(base) + if scenario%5==0: config["fluid_level_floodedness"]=[-1,0,.4,.6,.8,1][scenario%6] + if scenario%7==0: config["surface_level"]=[-96,-64,-20,0,64,96,256][scenario%7] + if scenario%9==0: config["exclusion"]=1 + f["config"]=json.dumps(config,separators=(",",":")) + f["sea"]=[-2**31,-64,-54,-10,0,63,2**31-1][scenario%7] + f["fluid"]=scenario%8 + if scenario%3==0: + f["overrides"]=[None]*6 + f["overrides"][(scenario//3)%6]=float_bits[(scenario//3)%len(float_bits)] + if scenario%11==0: + f["steps"]=[4,2,4]; f["sizes"]=[4,64,4] + if scenario%13==0: + # Preserve the scheduling flag after a failed array access. + f["queries"] += [[f["minimum"][0]+512,0,f["minimum"][2],"bff0000000000000"]] + yield emit(rng.randrange(-2**63,2**63),scenario%2,"minecraft:overworld",f) + for field in range(6): + for value in float_bits: + f=fixture([0,-54,0],sizes=(16,64,16),count=128) + config=dict(base);config["fluid_level_floodedness"]=.6 + config["fluid_level_spread"]=gradient("x",-4,4,-1,1) + f["config"]=json.dumps(config,separators=(",",":")) + f["overrides"]=[None]*6;f["overrides"][field]=value + yield emit(0,field%2,"minecraft:overworld",f) + # Fail once at each binding's first/second evaluation, then retry the same + # ordered queries. This also exercises constructor surface-volume failure. + for field in range(6): + for occurrence in [1,2,8]: + f=fixture([0,-54,0],sizes=(16,64,16),count=0) + config=dict(base);config["fluid_level_floodedness"]=.6 + config["fluid_level_spread"]=gradient("x",-4,4,-1,1) + f["config"]=json.dumps(config,separators=(",",":"));f["fail"]=[field,occurrence] + f["queries"]=[[x,y,z,"bfb999999999999a"] for x in range(16) for y in [-40,-30,-20,-10,0] for z in [0,7,15]] + if field==0: + f["sizes"]=[32,96,32] + f["queries"]=[[x,y,z,"bfb999999999999a"] for x in range(32) for y in [-40,-30,-20,-10,0,10,20,30] for z in range(0,32,3)] + f["queries"] += f["queries"][:64] + yield emit(0,field%2,"minecraft:overworld",f) + # Required-field codecs and malformed roots are validated before binding. + configs=["null","[]","{}"] + for field in base: + for value in [None,True,{},"minecraft:missing"]: + config=dict(base);config[field]=value;configs.append(json.dumps(config,separators=(",",":"))) + config=dict(base);del config[field];configs.append(json.dumps(config,separators=(",",":"))) + for config in configs: + f=fixture([0,-64,0],count=0);f["config"]=config + yield emit(0,0,"minecraft:overworld",f) + + +def index_corpus(): + rng = random.Random(0x484f52495a4f4e54524545) + def command(branching, entries, targets): + return f"index {branching} "+json.dumps({"entries":entries,"targets":targets},separators=(",",":")) + def entry(coordinates, offset=0): + return {"coordinates":coordinates,"offset":offset} + # Warm ties deliberately differ from a fresh index and brute list order. + ties = [entry([[x,x]]+[[0,0]]*5) for x in [-10,10]] + yield command(19,ties,[[x]+[0]*5 for x in [10,0,-10,0,10,0]]) + for branching in [2,19,32]: + yield command(branching,[entry([[0,0]]*6) for _ in range(40)],[[0]*6,[1]*6,[0]*6]) + yield command(19,[],[[0]*6]) + for branching in range(2,33): + counts = sorted({1,branching-1,branching,branching+1,branching**2-1,branching**2,branching**2+1}) + for count in counts: + entries = [] + for i in range(count): + coordinates = [] + for _ in range(6): + low = rng.randrange(-20000,20001) + coordinates.append([low,low+rng.randrange(0,4001)]) + if i and i%7 == 0: + entries.append(dict(entries[i-1])) + else: + entries.append(entry(coordinates,rng.randrange(0,10001))) + targets = [[rng.randrange(-30000,30001) for _ in range(6)] for _ in range(32)] + targets += targets[:8] + yield command(branching,entries,targets) + for count in [6858,6859,6860,65536]: + entries = [entry([[0,0]]*6) if count == 65536 else entry([[i%17-8,i%17-8]]*6,i%3) for i in range(count)] + yield command(19,entries,[[x]*6 for x in [-10,0,10,0]]) + extremes = [-2**63,-2**63+1,-2**31,-1,0,1,2**31-1,2**63-2,2**63-1] + for count in [1,2,19,20,362]: + entries = [entry([[rng.choice(extremes),rng.choice(extremes)] for _ in range(6)],rng.choice(extremes)) for _ in range(count)] + yield command(19,entries,[[rng.choice(extremes) for _ in range(6)] for _ in range(128)]) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepare",action="store_true") + args = parser.parse_args() + build = lab.LOCAL/"rust-worldgen-parity" + build.mkdir(parents=True,exist_ok=True) + report_path = build/"report.json" + report_path.unlink(missing_ok=True) + if args.prepare: lab.prepare() + lock,jars,libraries = base.verify_artifacts() + resources = noise_resources(jars["server"]) + if not resources: raise ValueError("pinned noise registry is empty") + if resources != noise_resources(jars["client"]): raise ValueError("client/server noise registry resources differ") + densities = registry_resources(jars["server"],"density_function") + if not densities or densities != registry_resources(jars["client"],"density_function"): + raise ValueError("client/server density registry resources differ or are empty") + settings = registry_resources(jars["server"],"noise_settings") + if not settings or settings != registry_resources(jars["client"],"noise_settings"): + raise ValueError("client/server noise settings resources differ or are empty") + tags = tag_resources(jars["server"]) + if not tags or tags != tag_resources(jars["client"]): + raise ValueError("client/server block tag resources differ or are empty") + def named(resources, kind): + prefix = f"data/minecraft/worldgen/{kind}/" + return {"minecraft:"+name[len(prefix):-5]:text for name,text in resources.items()} + bundle = build/"registries.json" + named_settings = named(settings,"noise_settings") + source = lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenOracle.java" + exporter = source.with_name("VanillaBiomeExport.java") + tag_exporter = source.with_name("VanillaTagExport.java") + sources = [source,exporter,tag_exporter,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py", + *sorted((lab.ROOT/"crates/horizon-core").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world").rglob("*.rs")), + lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock"] + tested_sources = base.source_hashes(sources) + classes = build/"classes" + classes.mkdir(exist_ok=True) + dependency_path = os.pathsep.join(map(str,libraries)) + base.run(["javac","--release",str(lock["minecraft"]["java_major"]),"-proc:none","-cp",os.pathsep.join([str(jars["server"]),dependency_path]),"-d",str(classes),str(source),str(exporter),str(tag_exporter)]) + preset_files = {} + preset_tables = None + for side,jar in jars.items(): + exported = build/f"biome-presets-{side}.json" + base.run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaBiomeExport",str(exported)]) + tables = json.loads(exported.read_text(encoding="utf-8")) + if not tables: raise ValueError("built-in biome parameter tables are empty") + if preset_tables is not None and tables != preset_tables: raise ValueError("client/server built-in biome parameter tables differ") + preset_tables = tables + preset_files[side] = exported + block_elements = None + tag_export_files = {} + for side,jar in jars.items(): + exported = build/f"blocks-{side}.json" + base.run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaTagExport",str(exported)]) + elements = json.loads(exported.read_text(encoding="utf-8")) + if not elements: raise ValueError("block identifiers are empty") + if block_elements is not None and elements != block_elements: raise ValueError("client/server block identifiers differ") + block_elements = elements + tag_export_files[side] = exported + bundle.write_text(json.dumps({"tags":tags,"block_elements":block_elements,"noises":named(resources,"noise"),"densities":named(densities,"density_function"),"settings":named_settings,"presets":preset_tables},separators=(",",":")),encoding="utf-8") + commands = list(corpus(resources)) + commands.extend(climate_corpus()) + commands.extend(index_corpus()) + commands.extend(climate_codec_corpus()) + commands.extend(settings_corpus(settings)) + commands.extend(tag_corpus(tags)) + commands.append(f"tag_registry {bundle}") + commands.extend(aquifer_corpus()) + commands.extend(noise_aquifer_corpus(bundle,named_settings)) + for seed in [0,1,-1,-2**63,2**63-1,0x123456789abcdef]: + for legacy in [0,1]: + for optimized in [0,1]: + commands.append(f"registry {seed} {legacy} {optimized} {bundle}") + for name in named_settings: + commands.append(f"router {seed} {legacy} {optimized} {bundle} {name}") + inputs = build/"inputs.txt" + inputs.write_text("\n".join(commands)+"\n",encoding="utf-8") + fixture_paths = [bundle,inputs,*preset_files.values(),*tag_export_files.values()] + tested_fixtures = base.source_hashes(fixture_paths) + base.run(["cargo","build","--release","--bin","horizon-worldgen-parity"]) + metadata = json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) + binary = Path(metadata["target_directory"])/"release"/("horizon-worldgen-parity.exe" if os.name == "nt" else "horizon-worldgen-parity") + candidate = build/"rust.txt" + with inputs.open("rb") as stdin,candidate.open("wb") as stdout: base.run([str(binary)],stdin=stdin,stdout=stdout) + injected_failures = Counter() + aquifer_outcomes = Counter() + with candidate.open(encoding="utf-8") as stream: + for line in stream: + if line.startswith("sample failure "): injected_failures[line.strip().split()[-1]] += 1 + elif line.startswith("aquifer result "): aquifer_outcomes[line.strip()[len("aquifer result "):]] += 1 + if dict(injected_failures) != {str(field):3 for field in range(6)}: + raise ValueError(f"Aquifer failure corpus did not hit every injected failure: {injected_failures}") + references = [] + for side,jar in jars.items(): + reference = build/f"vanilla-{side}.txt" + base.run(["java","-Xmx512M","-cp",os.pathsep.join([str(classes),str(jar),dependency_path]),"dev.horizonlab.parity.VanillaWorldgenOracle",str(inputs),str(reference)]) + matched = base.compare(reference,candidate) + references.append({"side":side,"jar_sha256":lab.digest(jar,"sha256"),"output_sha256":lab.digest(reference,"sha256"),"matched_output_lines":matched,"biome_export_sha256":lab.digest(preset_files[side],"sha256"),"block_export_sha256":lab.digest(tag_export_files[side],"sha256")}) + print(f"{side}: {matched:,} world-generation codec output lines match Rust",flush=True) + base.ensure_sources_unchanged(sources,tested_sources) + base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report = {"schema":1,"minecraft":lock["minecraft"]["version"],"platform":platform.platform(), + "java":subprocess.check_output(["java","--version"],text=True).splitlines()[0],"rustc":subprocess.check_output(["rustc","--version"],text=True).strip(), + "manifest_sha1":lock["minecraft"]["manifest_sha1"],"commands":len(commands),"command_counts":dict(Counter(line.split()[0] for line in commands)),"noise_aquifer_injected_failures":dict(injected_failures),"noise_aquifer_outcomes":dict(aquifer_outcomes),"block_tag_entries":len(tags),"block_identifier_entries":len(block_elements),"block_tag_resources_sha256":{name:hashlib.sha256(text.encode("utf-8")).hexdigest() for name,text in tags.items()},"noise_registry_entries":len(resources),"density_registry_entries":len(densities),"noise_settings_entries":len(settings),"biome_parameter_entries":{name:len(json.loads(text)) for name,text in preset_tables.items()}, + "biome_tables_sha256":{name:hashlib.sha256(text.encode("utf-8")).hexdigest() for name,text in preset_tables.items()},"fixtures_sha256":tested_fixtures, + "noise_resources_sha256":{name:hashlib.sha256(text.encode("utf-8")).hexdigest() for name,text in resources.items()}, + "density_resources_sha256":{name:hashlib.sha256(text.encode("utf-8")).hexdigest() for name,text in densities.items()}, + "noise_settings_resources_sha256":{name:hashlib.sha256(text.encode("utf-8")).hexdigest() for name,text in settings.items()}, + "inputs_sha256":lab.digest(inputs,"sha256"),"rust_output_sha256":lab.digest(candidate,"sha256"),"sources_sha256":tested_sources,"references":references, + "scope":"Direct normal-noise JSON decoding using the actual pinned vanilla CODEC. Every bundled noise registry resource, explicit/default parameters, empty and full amplitude modifiers, normalization modes, inclusive field bounds with signed-zero comparator ordering, malformed types, null fields, duplicate and ignored keys, decimal/exponent integer truncation and wrapping, signed zero, seeded modern/legacy and Nether construction, octave metadata, range and normalization bits, scalar noise values and parent random state. JSON resource contents stay private. Strict JSON parsing; no claim for Gson's permissive non-JSON syntax. Bundled density registries are also decoded with actual vanilla registry-aware CODECs: named forward references, all bundled function kinds, declared range/axes, raw compilation errors, seeded optimized roots, cache allocation, scalar values, strided bulk values, repeated cache hits and surface-volume errors are compared using RandomState's actual compile context. All seven bundled noise-setting resources contribute their actual eight-field NoiseRouter.CODEC objects to RandomState. Router fields are compiled in declaration order with a shared compiler/context; cache allocation, raw/optimized scalar and repeated strided volume values, successful single-layer surface volumes and invalid surface-volume shapes are compared. Actual RandomState climate sampler binding and quart-to-block coordinate wrapping are checked at ordinary and extreme positions. Float-to-long climate quantization and long-to-float conversion include subnormals, signed zeros, NaNs, infinities, cast saturation and seeded random bit patterns. Actual vanilla Climate.Parameter and ParameterPoint JSON codecs compare scalar, two-element list and min/max object intervals, float endpoint bounds/ordering, required coordinate/offset fields, negative zero, precision-sensitive float parsing, malformed types and duplicate keys. Climate parameter distances, wrapping squared fitness, stable search-tree leaf order and nearest lookup are compared across every supported branching value 2..32, sizes around branch powers, the 65536-entry API bound, duplicates, warm ties, fresh lookups, brute-force lookup and extreme signed-long endpoints/targets. The Rust tree is immutable with per-worker search state instead of hidden thread locals; invalid or degenerate searches return typed errors. Inline arbitrary distance metrics and behavior outside the bounded API are not covered. Built-in Overworld and Nether quantized biome parameter tables are exported independently by each authenticated JAR and required to agree before Rust consumes them. The Rust multi-noise resolver and actual vanilla MultiNoiseBiomeSource compare biome identities through scalar climate queries and prepared bulk quart volumes, including forward/reverse/repeated query order, wrapped extreme origins and shared previous-result state. Biome holder keys in the reference are registration placeholders; no biome property or gameplay behavior is evaluated. The Rust loader reads a Horizon quantized table format, not the vanilla biome codec, and the preset builders themselves have not been ported. Source and private fixture mutations during validation invalidate the report. The two-field 26.3 NoiseSettings codec, create helper and LevelHeightAccessor clamping are also compared across bundled noise members, dimension/alignment bounds, zero/negative runtime heights, disjoint ranges, wrapped integer arithmetic and decimal/exponent integer conversion. Global fluid cutoff selection and the actual disabled Aquifer implementation are compared with original default block-state identities, extreme sea levels/coordinates, signed-zero/subnormal/nonfinite density and counted picker calls; developer fluid-disable behavior is outside the regular-mode corpus. The actual noise-based Aquifer.Config codec and runtime are compared across bundled aquifer settings, modern/legacy world-seeded aquifer factories, synthetic density roots, nondefault water/lava states, cave/void air, nonfinite sampler overrides, strided volume extents, wrapped coordinates, repeated and reversed queries, counted picker calls, sampler call order/values, injected failures and retry state, scheduling flags, populated location/status caches and sorted surface-cache entries. Oversized or wrapped-invalid grid allocations and developer fluid-disable behavior are outside the bounded regular-mode API. Terrain filling is not yet validated. Router, vertical noise and optional aquifer members are decoded from each noise-setting resource; complete NoiseGeneratorSettings, material rules, nonempty world fields, biome registry/codecs and complete chunk biome assignment, generated chunks, gameplay and rendering remain pending. TagEntry and TagFile codecs, ordered resource-stack replacement, first-occurrence member deduplication, required/optional dependency cycle pruning, lookup order and flags, missing-reference partial results and all bundled block tag members are also compared with actual vanilla TagLoader. Block identifier tables are exported independently by authenticated client/server JARs and required to agree. The bounded tag API supports at most 8192 tags, dependency depth 256 and Java hash buckets without tree nodes; hash-tree ordering and pathological self-cycle failures remain pending. No heightmap or complete terrain integration follows from tag resolution. Inline noise holders and general codec behavior beyond the covered fixtures remain pending."} + lab.write_json(report_path,report) + print(f"Scoped world-generation codec parity passed: {report_path}") + + +if __name__ == "__main__": + main() diff --git a/tools/test_worldgen_random_parity.py b/tools/test_worldgen_random_parity.py new file mode 100644 index 000000000..e0ba5942b --- /dev/null +++ b/tools/test_worldgen_random_parity.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Compare the native world-generation random adapter, counters, forks and seeds.""" +import argparse +import itertools +import json +import os +from pathlib import Path +import platform +import random +import subprocess +import zipfile +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + rng=random.Random(78336) + integers=[-2147483648,-10001,-1,0,1,16,214748,214749,2147483647] + longs=[-9223372036854775808,-1,0,1,9223372036854775807]+[rng.randrange(-2**63,2**63) for _ in range(20)] + sample=[['int'],['long'],['bool'],['float'],['double']] + for legacy in [False,True]: + for layers in [1,2,3]: + for warmup in [0,7]: + for seed in longs: + ops=[] + for bits in [-2147483648,-65,-64,-33,-1,0,1,24,26,27,31,32,33,48,63,64,65,2147483647]:ops.append(['bits',bits]) + ops+=sample + for bound in [-2147483648,-1,0,1,2,3,7,16,1073741825,2147483647]:ops += [['bound',bound],*sample] + for x,z in zip(integers,reversed(integers)): + ops += [['decoration',seed,x,z],*sample,['feature',seed,z,x],*sample,['large',seed,x,z],*sample,['salt',seed,x,z,x],*sample,['slime',x,z,seed,seed^0x123456789abcdef]] + for operation in [['fork'],['pos',-2147483648,2147483647,-1],['pos_seed',seed],['pos_hash',[0,65,0xd800,0xdfff,0x20ac]]]: + ops += [['root'],operation,*sample,['fork'],*sample,['seed',seed],['consume',17],*sample] + ops += [['root'],['consume',-1],['consume',0],['consume',129],*sample] + yield {'legacy':legacy,'layers':layers,'warmup':warmup,'seed':seed,'ops':ops} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--prepare',action='store_true');args=parser.parse_args() + build=lab.LOCAL/'rust-worldgen-random-parity';build.mkdir(parents=True,exist_ok=True) + report_path=build/'report.json';report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts() + oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenRandomOracle.java' + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/worldgen_random_fixture.rs'] + tested_sources=base.source_hashes(sources) + fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') + fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) + classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle],'compile-java') + run(['cargo','build','--release','-p','horizon-world','--example','worldgen_random_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) + binary=Path(metadata['target_directory'])/'release/examples'/('worldgen_random_fixture.exe' if os.name=='nt' else 'worldgen_random_fixture') + run([binary,build],'rust');references=[] + for side,jar in jars.items(): + run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaWorldgenRandomOracle',side,build],side) + reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') + references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) + print(f'{side}: {matched:,} worldgen-random output lines match Rust',flush=True) + base.ensure_sources_unchanged(sources,tested_sources);base.ensure_sources_unchanged(fixture_paths,tested_fixtures) + report={'schema':1,'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'fixtures':len(fixtures),'random_modes':2,'wrapper_depths':[1,2,3],'operations':sum(len(f['ops']) for f in fixtures),'sources_sha256':tested_sources,'fixtures_sha256':tested_fixtures,'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references,'scope':'Actual WorldgenRandom bit sampling over legacy and xoroshiro sources, nested wrappers, signed bit-width shifts, draw counters, valid/invalid bounds, reseeding, fork and positional-factory delegation. Decoration, per-feature, large-feature, salt and slime-chunk seeds exercise signed int/long overflow, extreme coordinates and inherited legacy multi-draw behavior. Gaussian samples, concurrent access and full chunk decoration remain pending.'} + lab.write_json(report_path,report);print(f'Scoped worldgen-random parity passed: {report_path}') + + +if __name__=='__main__':main()