Клиент: начальный импорт кодовой базы

Основа — Horizon (MIT). История апстрима не переносится: этот репозиторий ведёт свою.
This commit is contained in:
SashegDev committed 2026-10-29 22:04:28 +03:00
commit 874b6f20c2
3414 files changed
+1071219

No files matched your search

+182
View File
@@ -0,0 +1,182 @@
# Block behaviours and ticking: parity status
Area: random and scheduled block ticks, growth, bone meal, TNT and
explosions, hoppers, dispensers and droppers, comparators reading
containers, weather-driven blocks. The library code lives in
`crates/horizon-world/src/level/`. The client glue lives in
`crates/horizon-client/src/game/` (`growth.rs`, `tnt.rs`, `explosion.rs`,
`machines.rs`, `blockctl.rs`).
## Implemented (ported from the 26.3 sources)
- **Growth through live feature placement.** `worldgen/live.rs` decodes
configured and placed features by name from the worldgen bundle. It shares
the generator's `GeneratorData`. `level/feature_world.rs` runs features on
the live level as a `FeatureWorld` and `PlacementContext`, and writes
blocks through `Behaviours::set_block` with the feature's flags. Tree
placement also calls `updateShapeAtEdge`.
- **`TreeGrower.growTree`** (`level/growth.rs`) covers every vanilla grower:
oak and its bee variants (with the flower check), spruce, birch, jungle,
acacia, cherry, mangrove, azalea and poplar. It also covers the 2×2 forms:
dark oak, pale oak, mega spruce and pine, and mega jungle. It keeps the
random draw order: mega feature, then flowers, then feature. Saplings are
removed with flags 818 and restored with flags 260 when the tree does not
fit. Saplings, propagules and azaleas grow both on random ticks and with
bone meal.
- **Bone meal** (`level/bonemeal.rs`) ports `BoneMealItem.useOn`,
`growCrop` and `growWaterPlant`, including coral from bone meal in warm
ocean biomes. It also ports every vanilla `BonemealableBlock`:
- saplings, propagules, mushrooms, fungi and azaleas
- grass (with the biome's `getBoneMealFeatures`), nylium, netherrack and
moss
- rooted dirt, mangrove leaves, crops (including beetroot and torchflower
increments) and stems
- pitcher, bamboo and bamboo sapling, cocoa and sweet berries
- tall grass and fern, tall flowers, bush and firefly bush, flower beds
- kelp, twisting and weeping vines, cave vines (head and body), seagrass
and sea pickles
- big and small dripleaf, glow lichen (`MultifaceSpreader`), hanging moss
and pale moss carpet
- short and tall dry grass, and shelf mushroom
Level event 1505 plays the bone meal sound.
- **Fixes to existing ticks.** Torchflower crops now mature into
torchflowers. Kelp grows into any water block, as in vanilla.
- **Primed TNT** (`game/tnt.rs`):
- It has an 80-tick fuse, gravity 0.04, 0.98 drag and the 0.7/−0.5 ground
bounce.
- It explodes with power 4 at `y + 0.06125`.
- It renders with the `TntRenderer` swell and a white flash every 5 ticks
(entity overlay 4 in `entity.wgsl`).
- TNT is primed by redstone, fire, flint and steel or fire charges
(`TntBlock.useItemOn`), and by players breaking unstable TNT.
- Explosions prime TNT with a random short fuse (chain reactions).
- Dispensers prime TNT too.
- **`ServerExplosion`** (`game/explosion.rs`):
- It marches 1352 rays through a Java `HashSet<BlockPos>`
(`java_hash_map`), so iteration and the `Util.shuffle` draws match
vanilla.
- Each block costs `max(block, fluid)` resistance.
- Damage and knockback scale with exposure for the player, mobs, items
and TNT. Creative players take no damage.
- TNT explosions drop every block. Mob explosions use drop decay.
- Drops merge in stacks of up to 16. Container contents spill.
- **Hoppers** (`game/machines.rs`):
- They push and pull through `HopperBlockEntity.tryMoveItems`.
- The 8-tick cooldown applies, with the transfer cooldown hand-off between
hoppers.
- They insert into furnace faces (`WorldlyContainer` slots, fuel and
bucket rules) and into double chests (right half first).
- They respect `does_not_block_hoppers` and pick up item entities from the
suck box.
- The `enabled` property stops them.
- **Dispensers and droppers.** They use `getRandomSlot` and the drop
position and velocity from `DefaultDispenseItemBehavior.spawnItem`. The
dispense behaviours are:
- bone meal
- TNT
- flint and steel (fire, TNT, campfires and candles)
- water and lava buckets (including waterlogging)
- empty buckets (fluids, waterlogged blocks and powder snow)
- arrows (power 1.1, uncertainty 6)
Droppers insert into containers. Clicks and failure sounds play.
- **Comparators reading containers.** `GameLevel` answers
`block_entity_analog_signal` with
`AbstractContainerMenu.getRedstoneSignalFromContainer`. Chests blocked by
a conductor read 0. Double chests are combined. Container changes from
hoppers, dispensers and the player call `container_changed`, which runs
`updateNeighbourForOutputSignal`.
- **Weather** (`level/weather.rs`) uses biome temperatures from the worldgen
bundle, with the height adjustment and frozen noise. They feed
`ServerLevel.tickPrecipitation`: ice formation, snow accumulation, and
cauldrons filling with water or powder snow. They also feed
`Level.isRainingAt`, which drives farmland moisture and fire going out in
rain.
- **Day-timeline blocks** (`level/timeline.rs`):
- Eyeblossoms open and close, and potted eyeblossoms follow. Neighbours are
scheduled in the `BlockScanUtils` scan order.
- Turtle eggs crack and hatch on sand, using the dawn hatch chance.
- Dried ghasts hydrate while waterlogged.
- **Landing writes.** Farmland trampling and turtle eggs crushed by landing
now run neighbour and shape updates, so crops on trampled farmland pop.
- **Smaller fixes.**
- Hopper, dispenser and dropper block entities save with their own ids.
Barrels and trapped chests do too.
- Their screens use the vanilla hopper and dispenser layouts.
- `GameLevel::max_y` is exclusive, as `LevelAccess` documents.
- **Block entity removal** (`level/removal.rs`, `game/spill.rs`):
`LevelChunk.setBlockState` runs `BlockEntity.preRemoveSideEffects` when a
block's block entity goes with it. Containers spill through
`Containers.dropItemStack`, jukeboxes and lecterns pop their item, shulker
boxes keep theirs, copper chests and statues keep theirs across weathering.
`Block.dropResources` draws when the behaviour calls it and awards ore,
sculk and spawner experience; the item entities join the world before the
behaviour returns.
- **Copper golems** (`mobs/copper_golem.rs`, `game/copper_golems.rs`): built
from a pumpkin on a copper block (`CopperChestBlock.getFromCopperBlock`),
sheared and equipped by dispensers, weathering, waxing, statues.
## Verification
- `tools/test_block_removal_parity.py`: 4,000 replacements, destructions and
removals of block entity holders with contents match vanilla. The dispenser
harness builds, shears and equips copper golems (6,000 cases match).
- Unit tests in `crates/horizon-world/src/level/growth_tests.rs` cover:
- every sapling kind, including the 2×2 trees
- azalea and mangrove growth
- random-tick stage advance followed by growth
- grass bone meal with flowers
- huge mushrooms and crimson fungi
- crop ages, torchflowers, ferns and tall flowers
- snow, ice and rain answers
- eyeblossoms and turtle eggs
They need the feature block exports in `worldgen/blocks`
(`block-properties.nbt`). The shared `.local` bundle lacks those files, so
run the tests with `HORIZON_RESOURCES` pointing at a complete prepared
bundle. Without one, the tests skip.
- Client tests cover the Java `Vec3i` hash and compare order and the
explosion stack merging.
- In the game on the virtual screen, driven by `horizon-ctl`:
- Bone meal on oak, birch, cherry, 2×2 dark oak, spruce and jungle
saplings grew all of them.
- Flint and steel on a TNT cluster: the TNT flashed white and chain
exploded, leaving a crater with drops.
- A redstone block primed TNT.
- A chest drained through a hopper chain into a chest at 2.5 items/s. The
comparator lit a lamp.
- A dispenser bone-mealed a sapling into a tree. A dropper ejected an item.
- Landing on farmland turned it to dirt and popped the wheat.
- The hopper screen shows the vanilla layout.
New `horizon-ctl` commands drive these checks: `setblock`, `fill`,
`getblock` and `container`.
## Known gaps
- **Random draws.**
- Features placed from block behaviour draw from a copy of the level
random. Their `next_world_*` draws and any draws in neighbour updates
during placement do not reach the real stream.
- The client picks randomly ticking sections from their palettes, so a
section whose palette still lists a ticking state no block uses any more
gets random ticks that vanilla's exact counts would skip.
- **Explosion details.** Exposure uses full-collision blocks only.
`getEntities` order is approximate. Experience orbs, falling blocks and
arrows are not pushed.
- **Missing entities.**
- Dispensers have no behaviour for fire charges, other projectiles,
armour, shulker boxes, boats, minecarts or spawn eggs. Fire charges and
most other items drop instead; projectiles, boats, minecarts and spawn
eggs are not entities in Horizon.
- Turtle hatchlings and happy ghastlings are reported as `BlockEvent`s and
not spawned.
- Hoppers do not see minecart containers. Item entities do not trigger the
hopper's `entityInside`; suction covers the same box on the hopper tick.
- **Not implemented.** The sculk vibration system (sensors, shriekers,
catalyst spread) and creaking hearts. Lightning (`tickThunder`).
Particles for bone meal, explosions and TNT smoke.
- **Not saved.** Primed TNT and hopper cooldowns (`TransferCooldown`).
+149
View File
@@ -0,0 +1,149 @@
# Section meshing parity
`tools/test_section_mesh_parity.py` compares the vertices Horizon's section
mesher (`crates/horizon-client/src/mesher.rs`, with `mesher/lighting.rs` and
`mesher/fluid.rs`) emits with the vertices the pinned client's own renderers
emit for the same scenes.
## What is compared
- **Vanilla side**: `VanillaSectionMeshOracle` bootstraps the game, binds the
prepared block tags, parses the jar's blockstate definitions and block
models, and bakes `BlockStateModel`s through the real `ModelDiscovery`,
`UnbakedRoot.bake` and `FaceBakery` path. Every texture becomes a real sprite
(its PNG from the jar) alone in a unit atlas, so UVs stay in sprite-local
[0,1] space; the five fluid sprites share one strip with gaps so the fluid
vertex stream still identifies them. A fixed `BlockAndTintGetter` serves the
scene's block states, per-cell sky/block light, constant biome colours per
`ColorResolver` and the overworld or Nether `CardinalLighting`. Blocks of one
section are visited like `SectionCompiler.compile`: fluids through
`FluidRenderer.tesselate`, then `RenderShape.MODEL` blocks through
`ModelBlockRenderer.tesselateBlock` with smooth lighting on, culling on,
cutout leaves, `BlockColors.createDefault()` and `state.getSeed(pos)`.
- **Horizon side**: `crates/horizon-client/examples/probe/section_mesh_fixture.rs`
loads the prepared resources (`Assets`, `BlockFacts`, `Biomes`,
`load_visibility`, `MeshTables`), builds the same blocks and light in real
client `Chunk`s (a 3x3 chunk region), sets every biome's colours to the
scene constants (or, for the biome-blend scenes, keeps the real biome
definitions and fills the chunks' quart biome arrays) and runs `Mesher::mesh`.
- **Comparison**: quads are matched as multisets per scene, keyed by sprite,
render-layer class (translucent vs. solid/cutout) and geometry rounded to
1/1000 after binary32 normalisation, with a winding-preserving rotation.
Matched quads compare per vertex: positions and UVs within 1e-4, ARGB colour
and light coordinates (sky and block, 1/16 steps) exactly.
- **Per-state facts**: a second gate compares, for all 35,723 states, the facts
the Rust tables derive from prepared resources with the client's accessors:
`getShadeBrightness`, `emissiveRendering`, `isSolid`, `isLightPermeable`,
`isSolidRender`, `isCollisionShapeFullBlock`, light emission, the water
overlay classes (`HalfTransparentBlock`/`LeavesBlock`), tint source counts
and `getOffset` at five columns.
The corpus (112 sections, ~1.0M quads, ~206k of them fluid quads) has full
cubes in open air, corners, cavities and overhangs; slabs, stairs, walls,
fences, panes, bars, torches, flowers and grasses with XZ/XYZ offsets, tall
plants, tinted blocks (grass, leaves, stems, redstone, lily pad, petals, leaf
litter, cauldrons), snow layers, carpets, farmland, paths, hoppers, anvils,
chains, lanterns, dripleaf, dripstone; water and lava sources, flowing levels,
falling columns, waterlogged blocks, water against glass/leaves/slabs/ice;
section edges with neighbours in other chunks and sections; a cave with
emissive and light-emitting blocks (magma, glowstone, sea lantern, active
sculk sensor, glow lichen); Nether shading; every block's default state; every
`RenderShape.MODEL` state of the registry on a sparse grid; and dense random
scenes mixing all model states with fluids under propagated or random light.
Biome tint blending is compared against the client's real
`ClientLevel.calculateBlockTint`: the oracle builds a `BiomeManager` (the
eight-corner zoom with a random hashed seed) over a fixed noise-biome map of
real `Biome` objects from the registry bootstrap (colormap sampling, colour
overrides, the dark-forest and swamp grass modifiers), initialises
`GrassColor`/`FoliageColor`/`DryFoliageColor` from the jar's colormaps, and
averages the resolver over the blend radius at each block's own height. The
`biome_blend_r*` scenes (radius 0, 1, 2, 3, 5, 7) put tinted blocks (grass,
leaves, water, leaf litter, cane, ferns, vines) at four heights on every
column of a Voronoi patchwork of 16 common biomes that shifts with height;
the `biome_each_*` scenes cover all 67 biomes. Option scenes (`options_*`)
cover flat lighting (`ao` off), opaque leaves (`cutoutLeaves` off, which
`SectionCompiler` draws in the solid layer and `LeavesBlock.skipRendering`
joins) and both together.
With `biomeBlendRadius` 0 the client takes the resolver's colour as is. Biome
colours given as plain RGB (all water colours, most grass/foliage overrides)
have alpha 0 there, so the client's tinted vertices come out fully
transparent, which the terrain shader would discard. Horizon keeps them
opaque and the gate compares RGB for radius-0 scenes.
## Running
```sh
python3 tools/test_section_mesh_parity.py # full corpus
python3 tools/test_section_mesh_parity.py --quick # skip the all-states catalogue
python3 tools/test_section_mesh_parity.py --strict # exit 1 on any difference
python3 tools/test_section_mesh_parity.py --only fluids
```
It needs the pinned jars (`tools/lab.py prepare`) and prepared client resources
(`cargo run --release -p horizon-prepare -- --prepare`). Outputs, logs and
`report.json` go to `target/section-mesh-parity/`; nothing is written under
`.local/`. The fixture is built with `--profile fast` and reports its
meshing time.
## Results
Before the port (commit `2940b5a`, first 18 scenes): 25,391 of 55,017 vanilla
quads identical (46%); 7,685 fluid quads missing, 9,231 extra quads, and
light/colour differences on most of the rest.
After: all 841,775 quads of the 94 scenes match and are identical, and all
per-state facts match. Meshing cost is unchanged within noise: the fixture
meshes the 94 (dense) corpus sections in about 3 ms each with both the old and
the ported mesher (`--profile fast`, loaded 24-thread desktop).
What was ported to get there:
- `BlockModelLighter`: quad shape (`faceCubic`/`facePartial`), the corner,
diagonal and centre samples (diagonals only through light-permeable blocks,
the centre from the neighbour unless it is solid-render), shade brightness
overrides, emissive full-bright samples, `smoothBlend` (zero samples take the
centre, sky-less samples borrow its sky, only when the centre is above 2),
the partial-face weights with `smoothWeightedBlend`'s int narrowing, and the
vertex remap. The padded section border grew to two blocks because cubic
faces sample two blocks out along their normal.
- `ModelBlockRenderer`: flat lighting for light-emitting blocks or when the
first model part disables AO (culled quads read light from the cull
neighbour, others from the neighbour only when flush), `ARGB.gray`/
`scaleRGB`/`multiply` integer arithmetic, cardinal shading including
`NETHER`, shade-direction overrides, per-element light emission, tint source
counts (layer indices past the list are untinted; water and bubble columns
are untinted in the world) and `getOffset` for XZ/XYZ blocks.
- `FluidRenderer`: face culling against the neighbour's occlusion face shape
for the fluid box height, self occlusion, `isSolid` corner heights, the
weighted corner averages in vanilla order, the 0.001 insets (also feeding the
side faces), `FlowingFluid.getFlow` with `Mth.atan2` and the sine table, the
water overlay beside half-transparent and leaf blocks, back faces,
`max(self, above)` light, bottom light from below, and cardinal shading.
- `UnbakedCuboidGeometry.bake`: elements flat along an axis draw no faces
across it (`bake_block_model` in horizon-assets; the raw
`bake_model_transformed` used by the model-baking gate is unchanged).
Exported facts used: `block-behaviours.json` (class chains, `isSolid`, full
face sturdiness), `gameplay-facts.json` (`offset` flag, emission, shapes),
the `#minecraft:blocks_fluid_flow` tag and the occlusion faces already loaded
for face visibility. Offset types and maximum offsets, shade-brightness and
emissive overrides are keyed by class or block name and checked by the facts
gate.
## What remains different or untested
- Changing `biomeBlendRadius`, `ao` or `cutoutLeaves` in the options does not
remesh resident sections; new and edited sections use the new values.
- Model variant seeds: `DoublePlantBlock`, `DoorBlock` and `AbstractBedBlock`
override `getSeed`; Horizon seeds every block from its own position. No
vanilla block among those has weighted variants, so output is unaffected.
- Opaque leaves: the vertex layer carries a flag (`OPAQUE_LAYER`) that makes
the terrain shader ignore the texture's alpha; the shader side is not
compared (GPU pixels).
- Layers: vanilla's solid and cutout layers are compared as one class because
Horizon draws both in its opaque pass.
- Not compared: block entities and their renderers, animated sprite frames,
translucent sorting, chunk-border light outside loaded chunks and GPU
pixels.