Compare commits

...
Author SHA1 Message Date
piexel ed44db5497 Stop fractured noise from mirroring across x = z
- Read each composite fracture axis from its own reseeded generator at unswapped coordinates in IrisNoiseGenerator and the batched NoiseLayerProgram
- Read the datapack exporter's z warps at unswapped coordinates
- Add a mirror test for the composite fracture and move the fracture test reference to per-axis seeds
- Retake NoiseSeedCohesionTest (Linux/Windows digest), IrisCaveCarver3DCellKernelTest PACK_SHARED and three IrisMathNoiseHotPathParityTest values
2026-11-14 17:32:08 +01:00
Brian Fopiano 832070cd69 Fix foundation cell lookup
- Call lowestFoundationCells in NMS surface terrain tests
- Match the renamed VolmLib occupancy method
2026-11-11 01:08:33 -05:00
Brian Fopiano ed037ea40b Remove GitHub release builds
- Delete the release workflow and its helper scripts
2026-11-07 16:20:47 -05:00
Brian Fopiano 589ed4e09a V+
Version 4.3.8
- Iris version is 4.3.8 in gradle.properties
- Root build defaults to version 4.3.8
- Fabric, Forge and NeoForge builds default to version 4.3.8
2026-11-07 15:48:14 -05:00
Brian Fopiano 743120df7d Skip unresolved structure captures
- Skip structure placements that fail to resolve in history capture
- Pass underground step to the structure river check
- Update planner tests for the new river check signature
2026-11-06 19:28:39 -05:00
Brian Fopiano 335b02f276 Merge lane B
- Land force place, unknown hydrology key warnings and the river fluid warning
- Rename dryDrawdown, minHeadKeep and waterfallMinDrop across new code
- Drop minCliffHeight with the old sea inlet passages
- Keep per-placement failure containment on forced and replaced pieces
- Repin the schema digest
2026-11-04 10:50:16 -05:00
Brian Fopiano 0274b72f92 Disable signing in test repo
- Keeps the noise artifact test working with signed commits configured
2026-11-04 03:22:37 -05:00
Brian Fopiano f4f7e92a4c Keep generating past failures
- REPLACE_SOURCE failures no longer stop the chunk: skip the piece or structure and warn once per structure and cause
- Replace requirePlacementOutput with placementOutput and remove requireAppliedPieces
- Key structure piece warnings on the structure, not the object
- Register the VolmLib placement failure hook from IrisEngine, using the engine failure rule
- Add HydrologyPlanException so a failed plan read inside a placement scope stops the chunk
- Add modded containment tests, with source rules for the 26.2 and 1.21.1 test sources
2026-11-04 03:08:58 -05:00
Brian Fopiano d0923de181 Merge gen-crash 2026-11-04 02:38:50 -05:00
Brian Fopiano 0c5d453b24 Merge cave-stilt 2026-11-04 02:38:50 -05:00
Brian Fopiano 04649aedbc Merge tiling 2026-11-04 02:38:38 -05:00
Brian Fopiano 78a521769a Merge mouths 2026-11-04 02:38:37 -05:00
Brian Fopiano 1df8f6040f Merge f2g 2026-11-04 02:38:37 -05:00
Brian Fopiano 7b38f75846 Name skip origin frame
- Name the first Iris frame in skip warnings instead of the library frame that threw
2026-11-04 02:34:38 -05:00
Brian Fopiano ebe4aa1e41 Contain failed placements
- Only touch vine faces in getAllowedFaces, so a ceiling vine never asks Bukkit for DOWN
- Add GenerationFailures.skipPlacement: engine failures rethrow, anything else is one warning per 60s per key with a suppressed count
- Count generation sessions, IOException and UncheckedIOException as engine failures
- Contain decorators, water plants, deposits, post and perfection columns, custom blocks, waterlogging fixes and structure pieces at their own scope
- Move object, floating, rotation and surface layer catches to the terse warning
- REPLACE_SOURCE structure failures still fail the chunk
- Add probeFaultSurface to generationOrderProbe for skip determinism runs
2026-11-04 02:24:46 -05:00
Brian Fopiano 6043c4fcaf Seat cave objects on ground
- Add IObjectPlacer.caveCell, answered from the carve by CaveObjectPlacementTransaction
- Move ORGANIC_STILT and CEILING_HANG cave objects until they touch the floor or roof
- Seat flora on its stem or trunk and ignore buried cap rims
- Drop cave placements with no floor or roof in reach or only fluid beneath
- Close gaps up to 8 blocks with rock and give longer drops a short ragged root
- Never repeat ore or flora; ore in a rock bottom uses the layer's rock
- Key cave jitter and scratch on CellHash
- Add CaveStiltProbe for vertical runs, seating, ore lines and column digests
- Recapture the schema digest for the new mode descriptions
2026-11-04 02:16:16 -05:00
Brian Fopiano 4bf7ef22d8 Organic cuts and fills
- Supply structure fits with IrisStructureStrata in Bukkit and modded policies
- Paint bank and inlet cuts with the biome layers from their new surface
- Delete strataIndex, the tidal bank cut limit and isTidalBank
- Add uncutTerrainDigest probe for uncut columns and the cut mask
2026-11-04 01:21:09 -05:00
Brian Fopiano 0a863e6ed9 Lower rivers toward the sea
- Add SeaApproach: lowers the last stretch above an estuary in small steps after planning
- Plan arms and grottos against the network before the approach
- Keep inland falls, high coasts and water beside ponds
- Add mouthProbe with sea drop metrics, sections and reach digests
2026-11-04 01:11:51 -05:00
Brian Fopiano 343da05e3d Add organic sea grottos
- Plan winding sea-level passages into tall coastal rock, one per site cell, owned by the mouth's window
- Keep walks out of rivers, ponds, own arms, and ground other windows' arms could reach
- Shape them with a warped path and a 3D radial function keyed on plan data and CellHash, with caverns, hanging rock, shelves and skylights
- Rasterize own-chunk into mantle WET_SOURCE, DRY_AIR and SEAL_GUARD; guards only at or below sea level
- Persist grottos in window plans, plugging cut-off wet cells at plan time
- Add IrisGrottos to settings, fingerprint, schema and pack validation; recapture pins
- Add /iris find river grotto, Studio map drawing, recorded mouths and an export limit
- Add grottoProbe and arm lines in the tidal rivers digest
2026-11-03 23:52:18 -05:00
Brian Fopiano 5df42fc49e Merge tidal inlets
- Sea inlets become tidal reaches on the river pipeline
- Recaptures the schema digest for the merged lane
2026-11-03 20:46:08 -05:00
Brian Fopiano 70cf63bf4e Resurface deeper tidal cuts
- Raise the tidal bank resurface limit from 6 to 16 blocks of cut
- Choose the surface layers at the natural height, then paint from the top
2026-11-03 20:34:51 -05:00
Brian Fopiano 5a1d743ea0 Default inlet spacing 160
- Set the engine default to 160 so packs need nothing beyond enabled
- Describe inlets as tidal arms in the settings and export notes
- Recapture the pinned fingerprint and schema digest
2026-11-03 19:50:50 -05:00
Brian Fopiano 78b4c88961 Delete grotto remnants
- Remove SealedPassage, PassageRasterizer, PassageSpace and HydrologyRuntime.passages
- Remove the passage loop, passage space and headroom plumbing from mantle and carve
- Keep WET_SOURCE and DRY_AIR readable for mantle data already written
2026-11-03 19:50:50 -05:00
Brian Fopiano ab3e22c619 Resurface shallow tidal banks
- Keep the biome surface layer on tidal bank cuts of 6 blocks or less
2026-11-03 19:50:33 -05:00
Brian Fopiano 8189215328 Count inlets in structure veto
- Treat sea inlet columns as river water for the 10% surface structure rule
2026-11-03 19:50:33 -05:00
Brian Fopiano 8d18e0de7a Meet river banks at midline
- End a tidal bank halfway to any other water within its band
- Ease it up to that water's own bank height, so the two sides join
- Leave river, pond and lake banks unchanged
2026-11-03 19:50:32 -05:00
Brian Fopiano f4cd64ee33 Reject arms facing walls
- Honour the reject from the bank and head checks instead of dropping it in the max
- Remove the mouth suppression rule, which territories already make redundant
- Raise the meander scale to keep arms winding after the stricter rule
- Measure head walls and added steps across feature boundaries in the probe
- Pin rejects, cliffs in the band and close mouths with tests
2026-11-03 19:50:32 -05:00
Brian Fopiano 54aaf28987 Grade arms through hills
- Route walks around ground too tall for the bank band and stop short of it
- Scan bank profiles and head rays for tall ground and cliffs, and trim the head
- Widen the default bank band so banks grade back like a river valley
- Measure the steepest bank rise, slot runs and head walls in the probe
- Add a sections mode rendering real block cross sections of chosen arms
2026-11-03 17:51:51 -05:00
Brian Fopiano 1ddda75efb Merge stream lowering
- Streams go down with structure cuts
- Recaptures the schema digest for F1 and F3 together
2026-11-03 16:39:27 -05:00
Brian Fopiano c17e5d9c9a Report unlinked reach water
- Add unlinkedWater to the hydrology raster metrics: wet cells along a reach polyline that the stream link radius cannot join
- Print it per window from hydrologyProbe, without failing the run
2026-11-03 16:29:47 -05:00
Brian Fopiano 5c14b34179 Separate amethyst decor in probe
- Report chunk order mismatches with and without amethyst cave decoration
- List what covers or replaces sea level water on tidal arm columns
2026-11-03 16:22:30 -05:00
Brian Fopiano fdfc378676 Tidal reach probe
- Replace the sea inlet probe with metrics, blocks, digest and rivers modes
- Measure edge steps, path shape, funnel, connection, overlap and cuts per arm
- Render plan and real block images per seed
- Compare river plans and block hashes across chunk order, threads and window order
2026-11-03 15:44:15 -05:00
Brian Fopiano a27d3b7972 Land inlet searches near mouths
- Offer tidal reach points in the half toward the sea, short of the open sea
- Keep tidal reaches out of river mouth searches
2026-11-03 15:42:18 -05:00
Brian Fopiano 4132db5f8b Remove inlet passage
- Delete SeaInlet, its rasterizer, space and footprint, and the old inlet probe
- Keep the mantle cells, old chunk seal and cave headroom behind SealedPassage
- Keep their tests on a test passage so grottos can build on them
- Report tidal arm counts from the plan in the hydrology probe
2026-11-03 15:42:18 -05:00
Brian Fopiano 848226c6f3 Tune tidal arm shape
- Find the lowest monotone path inland with a wander term, replacing the greedy walk
- Scale the meander to arm length and skip slope damping, since arms are cut flat
- Remove the steep-ray cone from tidal banks, which made the spiky bank teeth
- Round heads, damp width wobble inland and tune the funnel defaults
- Narrow territories to the water while keeping mouths apart
2026-11-03 15:41:58 -05:00
Brian Fopiano 2da2f760e0 Streams follow structure cuts
- Restate flattenKeepsDryBanksAtTheWaterSurface for water going down with its banks, with the SOURCE case, on v26_3_R1 and v26_2_R1
- Pass StructureWater to prepareSurfaceStructures in the adapter tests
- Expect the 64-block hold reach in FLATTEN references
- Describe stream lowering on IrisStructureTerrain and recapture the schema digest
- Add the waterPerchCensus probe, which reads copied region files and counts perched source water by flatten blend
2026-11-03 15:34:50 -05:00
Brian Fopiano 79a566cf07 Tidal reach planner
- Replace SeaInletPlanner with TidalPlanner, planned only in the owner window
- Walk up a distance-from-coast field and keep clear of rivers, ponds and lakes
- Decide conflicts from hashed site anchors and territories, not from drainage
- Trim or reject arms on tall banks, inland low ground and shores beside the sea
- Share the river fit and smoothing through ReachShaper.smooth
2026-11-03 14:50:26 -05:00
Brian Fopiano 5d127baac9 Tidal reach plan format
- Add ReachStyle.TIDAL with code 6, rastered as WaterRole.INLET with sea fluid
- Add a tidal tier to the settings, built from the river tier and the inlet bank knobs
- Remove the inlet section from WindowPlan, HydrologyPlanCodec and HydrologyPlanPreview
- Require tidal reaches to be whole, at sea level and draining to the sea
- Record, search and draw inlets from tidal reaches
2026-11-03 14:24:50 -05:00
Brian Fopiano 10fccd68f3 Tidal inlet settings
- Replace cliff, width, headroom, roof and chamber knobs with funnel, bank and meander knobs
- Bound the new knobs at compile, with a reach guard against the window size
- Add them to the fingerprint and recapture the pinned fingerprint and schema digest
- Hold the old planner's retired values as constants until the planner is replaced
2026-11-03 14:18:44 -05:00
Brian Fopiano b0747d7483 Merge underground lava
- Deep lava pools, cave springs and the cave fluid probe from hydro/f3
- Recaptured the settings fingerprint and schema digest for the combined code
2026-11-03 14:01:25 -05:00
Brian Fopiano ab2a448775 Step warning, seed tests
- Warn in the stepHeight description that 1 is experimental and terraces can rise
- Recapture the pinned schema digest for that description
- Test the world seed at the window, region and pond D8 callers
- Test that the plunge flare stops at the sea
- Test that the plunge flare stays out of the running maximum
- Open ReachShaper.widths to the package for that test
2026-11-03 13:54:29 -05:00
Brian Fopiano 891aaa13b4 Skip springs under transforms
- Dimensions with a terrain transform place no cave springs
- The structure query no longer re-enters the transform during terrain
2026-11-03 12:46:17 -05:00
Brian Fopiano bf30f8c75b Veto springs near structures
- Drop a spring when an imported structure piece lies within 32 blocks, from world minimum to one block above the seep
- Pass the seep position to the carved terrain structure check
- Clear the block update when a pool wall replaces a spring
- Pin the spring guards with behaviour tests across several seeds
- Pin startsNear reach and the springs-only component and runtime gates
2026-11-03 12:33:53 -05:00
Brian Fopiano f809bacd29 Step height knob
- Add tier stepHeight 1..2, default 2, in the settings fingerprint
- Snap channel heads by tier and keep ponds, lakes and inlets at 2
- Key riffle crests on any lower neighbour, falls unchanged
- Start one-block outlets at their pond's surface
- Reject tiers with a larger step than the next larger tier
- Recapture the fingerprint and schema digest
2026-11-03 12:17:28 -05:00
Brian Fopiano 750bade003 Hashed D8 ties
- Break equal-slope D8 ties with a world-keyed hash of seed and cell
- Pass the settings seed from window, region and pond planners
- Replace the scan-order test with world-hash tie tests
2026-11-03 11:58:41 -05:00
Brian Fopiano 52450fbc72 Plunge flare
- Compute reach styles before widths
- Widen channels by half at waterfall feet, fading over the plunge length
- Keep the flare within the tier maximum and out of running widths
- Skip reach ends, protected outlet stretches and estuaries
- Test widths against channel maxima outside plunge pools
2026-11-03 11:46:21 -05:00
Brian Fopiano 1bdd03c18f Guard T8 companion test
- Run T8's assertions through TongueGuard on ground that keeps tongues
2026-11-03 11:46:21 -05:00
Brian Fopiano ac9b4abfe2 Fix biome test registries
- BukkitBiomeVisibleResolverTest initialised org.bukkit.block.Biome with no registries, which failed the class for its whole test JVM
- ObjectStudioGeometryTest then failed whenever the two shared a fork, as they do with the new test classes at four forks
- The test now sets the registries up first
2026-11-03 11:16:58 -05:00
Brian Fopiano f9be56ab6b Validate deep fluid line
- Pack validation rejects a deepFluidMaxY outside the dimension's height while deepFluid is set
- The check is the same one the filler applies when generating
2026-11-03 10:24:14 -05:00
Brian Fopiano 117191a479 Add cave fluid probe
- caveFluidProbe generates 8 by 8 chunk patches spaced 64 chunks apart
- Reports pools, lava pools, lava bodies, bodies 32 or more wide and springs per 1000 chunks by depth band
- Sets bottom-of-the-world cave lava apart from the counted lava bodies
2026-11-03 10:22:10 -05:00
Brian Fopiano b64845dfed Add cave springs
- IrisCaveSprings: enabled false, density 0.05, fluid lava, minDepthBelowSurface 16, under hydrology.underground.caveSprings
- CaveSpringPlacer picks a seep in a rock wall of its own chunk with a hash of the seed and coordinates, reading only carved cells
- A seep holds one SPRING_SOURCE cell with UpdateMatter.ON, so the game's fluid ticks move it
- A spring is dropped when its opening is unroofed, or its flow within 15 blocks meets a foreign cell, an older chunk or ground closer than minDepthBelowSurface to the surface
- A structure placement that starts within 8 chunks drops the spring
- Pool walls replace a spring cell in either write order, so pools stay sealed
- A cave policy fluid replaces the spring fluid, unknown names fail the chunk, and settings reject bad knobs
- Default fingerprint and schema digest recaptured
2026-11-03 10:16:35 -05:00
Brian Fopiano c76339df4e Deep cave pool fluid
- cavePools.deepFluid fills pools at or below cavePools.deepFluidMaxY, default world Y -128, unset by default
- A cave policy fluid still wins over the deep fluid
- The mixed-fluid check stops a pool rising past the line, so no pool straddles it
- CavePoolFiller takes the world minimum Y to place the line, and throws when the line is outside the world
- Settings reject an unknown or seam deepFluid, and both knobs join the fingerprint
- Default fingerprint and schema digest recaptured
2026-11-03 10:11:48 -05:00
Brian Fopiano f1834327c3 Guard tongues at cliffs
- Stop a tongue at plan time where its bed would pass maxFill over natural ground
- Store stopped falls on the reach and in the plan codec
- Keep settlement and raster on the same geometry rule
- Test the cliff fixture on seeds 1..24 from half-width 3 to 18
2026-11-03 10:09:14 -05:00
Brian Fopiano 6e2cb959dd Plan curves across windows
- Decide which falls curve from the plan reach, so every chunk and settlement agree
- Keep a clamped drop under the curve minimum straight
- Test feeder falls across a window line on 24 seeds
2026-11-03 09:52:42 -05:00
Brian Fopiano c4a076b587 Finish curved brinks
- Keep a horseshoe tip off the outlet zone end and reach start
- Scan segments upstream of a fall for horseshoe water in settlement
- Measure the brink cap from the real brink and pin it at 11
- Replace the angled 1.25 bound with rule and square-on checks
- Add behaviour tests for every ReachGeometry guard and use site
2026-11-03 07:31:45 -05:00
Brian Fopiano 855c2e7f61 Rebaseline river length
- RIVER_LENGTH 384 to 352, owner sign-off R100
2026-11-02 21:11:48 -05:00
Brian Fopiano 6458b2331c Task 19 WIP
- Add ReachGeometry and the shared curved brink head rule
- Use it in RasterComposer and PondChannelSettlement
- Add T8, T9 and multi-seed brink tests
- Unfinished: see task-19-report.md
2026-11-02 21:11:48 -05:00
Brian Fopiano 6c0c42cd8c Gradual meander damping
- Ease slope damping over 8 stations, so a cliff no longer jerks the line sideways and tilts the brink
- Guard the brink, chord tilt and centreline over seeds 1 to 24 and cliff edges 193 to 199
- Recapture the edge 199 brink pin and run the edge overhang test over 8 shape seeds
- Run the wall cut test over 8 seeds with a per-case cap and a pooled mean cap
- Check that every pond beyond the sliver is kept, and skip only the level check on its downstream chain
2026-11-02 20:47:10 -05:00
Brian Fopiano 22e4775a5f Task 18 test fixes
- Exempt only ponds on the sliver's downstream chain, so far pond loss and level changes fail again
- Add a 30-block mean cap over the nine wall feet beside the 35-block per-foot cap
2026-11-02 20:18:11 -05:00
Brian Fopiano 75567295c0 Fail broken forced structures
- Remove the catch around assembly so a forced-mode structure with a broken graph fails on a submerged start as on a dry one
- Keep returning null for blank and missing keys on a submerged start
- Test that an unforced structure returns null on a submerged start without reaching assembly
2026-11-02 20:01:45 -05:00
Brian Fopiano bad795f9a7 Narrow force place scope
- Stop treating underground ORGANIC_STILT and CEILING_HANG pieces as forced, so they keep the veto and submerged check
- Return null for broken references on a submerged start, as before force place
- State force placement in the placeMode, underwater and allowWater descriptions and recapture the schema digest
- Pin static objects writing every block over planned river and pond water
- Add tests for forced pieces on open sea, unforced multi-piece starts on sea columns and underground pieces in water
2026-11-02 19:51:52 -05:00
Brian Fopiano 07e4d9cd8b Cliff edge review fixes
- Read centreline columns for every land point, so a cliff between lattice nodes lowers the read even where the node gate stays shut
- Close the trim where the channel edge at the next midpoint or the bank is below it, so an angled cliff gains no extra overhang
- Test station phases and fractional edges, angled cliffs and uniform slope 1 directly
- Assert the gate position directly instead of only against a mirror
- Pin the brink for each on-lattice edge instead of a range
2026-11-02 19:21:51 -05:00
Brian Fopiano b2255d6bf9 Warn on unknown hydrology keys
- Report keys under hydrology and hydrologyPolicy that the config classes do not declare as warnings on every validation path
- Keep the reflection walk and the full path, and word the message as a warning
- Stop treating collections, interfaces and abstract classes as having declared keys
- Rename the rejects tests and expect warnings with no errors
- Cover validate, validateForPackaging and validateForDatapackBootstrap
2026-11-02 19:10:36 -05:00
Brian Fopiano 4ddbcc9c97 Force place ignores water
- Add ObjectWaterRule with KEEP_OUT, ENTERS_WATER and FORCED, carried through placers, mutation logs and source plans
- Skip the whole hydrology veto for forced placements in MantleWriter, ObjectDestinationTransaction and FloatingObjectPlacementTransaction
- Skip the hydrology-support and uneven-water rejections for every forcePlace placement
- Admit forced Iris pieces past the 10% limit and the submerged start check in IrisStructureLocator
- Decide piece mode and forcing once in IrisStructurePlacement so locate and generation agree
- Remove forcedByStructure, now covered by forcePlace
- Update tests to the new behaviour, including a piece inside a river and a forced object over a channel
2026-11-02 19:01:55 -05:00
Brian Fopiano 5450fa1ef1 Organic steep channels
- Add Taubin relaxation of the resampled D8 line, with a 4-block shift limit and 4-block re-spacing
- Scale meander amplitude and wavelength by half-width and keep 40 percent of it on steep ground
- Use a smoothstep end envelope so short reaches keep their curve with exact endpoints
- Soften Viterbi offsets by half a node and pull back where the neighbouring node is blocked
- Move meander and Viterbi offsets along the relaxed line's normals so meander cannot tilt the valley read
- Hold meander to zero where a pond lies within its swing, so outlets stay on the shore
- Add steep-channel, reduced-meander, blocked-node and translation guard tests
- Revise fixture assumptions that required straight lines or one station phase
2026-11-02 19:01:52 -05:00
Brian Fopiano d6a3456024 Reject unknown hydrology keys
- Report keys under hydrology and hydrologyPolicy that the config classes do not declare, with the full JSON path, as blocking errors
- Derive known keys by reflection over the fields Gson reads, and treat map keys as data while checking the objects inside
- Check a disabled hydrology block too, so a misspelt enabled flag is caught
- Follow snippet references from hydrology into their files
- Replace the tests that pinned unknown keys as ignored
- Pin the no-sea warning on both sides of its boundary, fluidHeight -64 and -63
2026-11-02 18:06:17 -05:00
Brian Fopiano 1f581164a2 Falls at cliff edges
- ReachFitter reads ground with lowestCoveredGround, dropping nodes more than 2.5 blocks ahead only at a cliff edge
- Exact columns from a point to the midpoint of its next segment cap the trimmed read, so water never overhangs a cliff between lattice nodes
- T5 second case and cliffBetweenLatticeNodesKeepsWaterBelowTheGround cover the brink position and the centreline
- stepsBelowTheWaterfallMinimumKeepTheFullGroundRead pins the waterfall minimum gate
- cascades description separates cascade-start and waterfall-start steps; schema digest recaptured
2026-11-02 17:49:49 -05:00
Brian Fopiano 90fdd980e0 Rename hydrology config fields
- Rename climateDrawdown to dryDrawdown
- Rename minimumHeadKeep to minHeadKeep
- Rename minimumCliffHeight to minCliffHeight
- Rename waterfallMinimumDrop to waterfallMinDrop
- Repin the schema digest for the new names
2026-11-02 17:49:34 -05:00
Brian Fopiano 8d235e7757 Warn on unsealed river fluids
- Warn when a non-water river fluid without a seam can meet the sea or another river fluid
- Resolve river fluids from tiers and surface biome, region and dimension policies
- Compare fluids by palette blocks and skip fluids already lined by a seam
- Give the full hydrology test fixture a lava seam
- Cover the warning and its silent cases in validator tests
2026-11-02 17:39:53 -05:00
Brian Fopiano 64049fd964 Round two review follow-ups
- WaterInvariants.held holds a fed start only above MAX_START_LOWERING, as LinkBlend.fixed does
- Test that a lake outlet is not held along its lip across a window line, unlike a pond outlet
- Test tailouts across chunk borders with a diagonal and a jogged next step
- Share the chunk-border comparison between the plunge and tailout tests
- Parity test maps roles to palettes with a switch
- Parity test asserts some trials have open water under a fall
2026-11-02 17:37:41 -05:00
Brian Fopiano fcc2157d17 Fix structure river findings
- End object placements in a finally at all four MantleObjectComponent sites
- Split recordObjectPlacement for accepted ranges from endObjectPlacement for the water flag
- Place forced single-piece structures after admission and let the MantleWriter veto protect the water
- Drop the allowWater parameter from piecePlacement
- Validate allowWater as a boolean and add it to anonymous grid identity when true
- Add placement exit, forced piece, REPLACE_SOURCE, world Y -1 and placePieces failure tests
- Add modded stage river start and policy water tests
- Rename the misleading planner river test
2026-11-02 17:29:25 -05:00
Brian Fopiano 618a52952d Step-pool review fixes
- Floor non-estuary pools at the lowest grade whose snapped head is above the sea
- Add WaterHeads.lowestAboveSea beside the snap rule it follows
- Restore the strict delta branch check on grouped settings
- Assert grouping moves no sea-level head upstream on the delta fixture
- Update the cascades schema description and recapture the schema digest
- Measure pools by arc on a gentler run
- Test close falls stay separate when the lower lands on the end level
2026-11-02 17:27:15 -05:00
Brian Fopiano 394eb6b8c1 Step-pool grouping
- Add StepPools to group drops into level pools on cascading tiers
- Pass the seed through ReachGrader and record each point's floor
- Stop a waterfall absorbing the run-out at one waterfall's depth, so falls never merge
- Hold non-estuary points above sea level so no pool pulls the sea upstream of the estuary
- Protect pond outlet starts and every held point from grouping
- Test step pools, plunge reaches, tall-fall rollover and pond outlet zones
- Check the short-pit lock on ungrouped grades and bound grouped grades by one pool length
- Count visible drops in the gradeNeverRisesDownstream ratio
- Check the delta branch water on ungrouped grades and within one pool length when grouped
2026-11-02 16:35:57 -05:00
Brian Neumann-Fopiano 2130c1984d Modded jars drop NoiseNatives
- Only the Bukkit bootstrap calls it, and modded jars bundle their natives
- It references the excluded SlimJar, which failed all 12 modded verifiers
- Remove a test import left unused by the noise pin
2026-11-02 14:31:11 -05:00
Brian Neumann-Fopiano 1838d62965 Pin merged schema and noise
- Schema digest for the merged lanes
- Noise pin accepts the Windows and Mac rounded hashes
- Noise output is unchanged: the original raw-bit pin still passes on this line
2026-11-02 14:19:40 -05:00
Brian Neumann-Fopiano 5769b0d4e8 Restore language sync
- Bring back 5 commits a force push dropped from GitHub master (0aad88c30)
- Keep the thin Bukkit entry; port language sync into IrisRuntime
- Fetch guides through GitHubLanguageSource instead of the removed catalog
2026-11-02 14:15:44 -05:00
Brian Neumann-Fopiano 52dae154bb Merge master into hydrology 2026-11-02 14:11:01 -05:00
Brian Neumann-Fopiano b08d181823 Merge lane B structures 2026-11-02 14:11:01 -05:00
SwiftSwamp 0aad88c301 Fixed Windows build
- Purity ratchet compares source paths with forward slashes
- Hydrology plan reads and saves share a striped file lock
- Offline region generator skips directory sync on Windows
- Noise seed pin hashes samples rounded to 9 decimal places
- Language guide test ignores line endings
- Language hotload test uses the VolmLib size limit
- Region snapshot tests skip without file keys
- Region snapshot test covers reads without file keys
- Open region replacement test skips on Windows
- Attach signal test links sigaction after the Windows check
- Offline publication test expects only file syncs on Windows
2026-11-02 11:00:24 -07:00
SwiftSwamp 7efd51de3e Language sync
- Branch-tracking language source on Bukkit and modded
- 57 unused keys removed, translations corrected
- Consolidated saved-pack field warning
2026-11-02 09:39:04 -07:00
Brian Neumann-Fopiano e4efd7800d Native structures respect rivers
- Supply hydrology water to the native structure stages through IrisStructureWater on the Bukkit and modded policies
- Carry each native placement's allowWater on its start plan
- Judge native placements by the columns their assembled pieces cover in the stage instead of by the start chunk at plan time
- Apply the same start rule in the headless probe planner
- Move Iris structure footprints and carves onto the shared StructureWaterRules and remove StructureWaterFootprint and StructureCarveWater
- Add allowWater to the content-derived placement identity when set, so deduplicated native starts do not depend on list order
- Pass dry water to native terrain integrator calls in the adapter tests
2026-11-02 07:47:58 -05:00
Brian Neumann-Fopiano a21e59f53b Fall and estuary check fixes
- missingSurface: a sea-floor head under sea layers or sea decoration holds its cover or its own planned fluid, so a wrong fluid at a frozen estuary or inlet head fails again (R76).
- Column parity test mirrors the open-water-under-a-fall rule with a random 4-neighbour of its own head and role, guarding the actuator against drift from the mantle fall rule.
- An inlet mouth under a fall keeps open sea water, and one without a fall keeps its sea layers.
- bermOverCap still counts an over-cap wall beside a lake's outlet, which is never held.
2026-11-02 07:36:04 -05:00
Brian Neumann-Fopiano 6f3b96cfb3 Plunge pool tailout
- The plunge bowl ends at the next step's brink when that brink is nearer than the pool radius, so the pool rises back to the crest and the brink keeps 1-block water (R78).
- A brink distance field over the foot level, seeded at cells with a 4-neighbour at least 2 lower, sets each cell's span to the smaller of the radius and its foot-plus-brink distance; without a brink in reach the span is the radius, as before.
- The depth under the fall foot is unchanged; with no cell between the foot and the brink only the brink keeps its sill, and a foot that is itself a brink keeps the sill.
- Removes the 4 tick conversion cells at 146..148,329,-2826..-2828 and 489,329,-2182 where corner falls sat beside deep brink water.
2026-11-02 07:19:53 -05:00
Brian Neumann-Fopiano ba0bb1a2c0 Structures respect rivers
- Add the allowWater structure placement field and recapture the schema digest
- Skip surface Iris structures whose piece footprint is more than 10% channel, pond, cascade or waterfall water
- Skip surface native placements whose start chunk is more than 10% of that water
- Fail closed on a provisional water answer off the server thread
- Keep BORE and FORCE_CARVE out of water columns from two blocks below the floor and out of the two-block bank up to the water surface
- Run structure pieces and stilts inside a MantleWriter object placement that applies the object water veto unless the placement allows water
- Let forced single pieces of allowWater structures enter water like an object's own forcePlace
- Apply the object water veto to floating-island object transactions
- Share the veto between the destination transaction, MantleWriter and floating transactions
- Reset the destination transaction's water flag when an object placement ends
2026-11-02 07:16:22 -05:00
Brian Neumann-Fopiano f4bd105157 Tongue scan holds outlet zone steps
- WaterInvariants.held mirrors LinkBlend.fixed after R72: a CASCADE whose 1-block drop leaves a held point stays held, and a fed start feeds that chain.
- Seed 4 on lane B's cup layout has a CHAINED pond outlet zone that steps 56 to 55 (shown 56 to 54, restyled CASCADE by Task 15) and continues held at 55 before cascading into the junction; the scan flagged that one step point as a tongue.
- PlannedSceneTest.outletZoneStepThatShowsAsTwoBlocksStaysHeld pins the styled zone step as held and the same step left unstyled as a tongue.
2026-11-02 06:47:48 -05:00
Brian Neumann-Fopiano f76bb19597 Integrate lane A plunge pools
- Merge lane A Task 15 (6aafec196, 90205dc5f): plunge pools below falls, junction seam and tongue fixes, outlet zone step hold.
- No textual conflicts; ConfluenceIncisionTest keeps the integration MAX_WALL_CUT of 29 beside lane A's shared valley scene and tongue test.
- Pinned constants unchanged: schema digest, hydrology fingerprint and golden hashes pass as merged.
2026-11-02 06:36:21 -05:00
Brian Neumann-Fopiano e050f50ac7 Wall cut baseline
- MAX_WALL_CUT is 29: the integrated cup layout cuts 25 at foot 16 with confluence grading off and on, plus the 4-block margin the old cap had
2026-11-02 06:30:26 -05:00
Brian Neumann-Fopiano ecbd177360 Probe gates know estuaries
- missingSurface lets mouth columns take the biome sea layers like inlet columns, as the terrain stage paints them
- missingSurface accepts the biome's own decoration at the head of mouth and inlet columns, which are decorated like the sea they join
- missingSurface expects each column's effective fluid, so seam columns expect their seam
- risingWaterSegments compares reach heads with the pond's snapped head instead of its raw level
- bermOverCap spares the containment wall of pond outlet water held at its pond's head, the accepted perched flume
2026-11-02 06:30:26 -05:00
Brian Neumann-Fopiano 2ed13f9b7f Open water under falls
- Estuary and inlet columns that a higher neighbouring water column falls into skip the sea layers, so falling water lands in open sea water instead of spreading over sea ice
- Fall check compares the unclamped water head with the 4-neighbour wet heads, the rule the mantle uses to place falls
- IrisTerrainNormalActuatorHydrologyTest.aFallIntoAFrozenMouthLandsInOpenWater pins the open plunge and keeps ice beside level water and dry banks
2026-11-02 06:30:26 -05:00
Brian Neumann-Fopiano cabfca700a Drop unreachable plan waits
- Sapling growth, Bukkit and modded object paste and Bukkit structure place no longer catch ProvisionalAnswerException, since explicit-Y placement never reaches the provisional guard
- The three retry messages are removed from the message catalogs and every bundled language
- Bukkit structure place records its changes for /iris object undo after a successful placement, as the modded command does
- The sapling test that reached the catch through a throwing tree is removed
2026-11-02 06:21:42 -05:00
Brian Neumann-Fopiano e15dcceca0 Rafts keep their deck
- IrisObjectPlacement.entersWater is true for underwater, onwater and an object's own forcePlace, not for forced structure pieces
- Object placements pass entersWater to the destination transaction, so onwater and self-forced objects keep solid blocks in channel and pond water
- The water surface support gate reads the same predicate
- The mutation log and source plans carry the flag as entersWater
- Tests cover a one-block onwater raft and a self-forced block kept on a river, a forced structure piece still vetoed, and replay
2026-11-02 06:21:42 -05:00
Brian Neumann-Fopiano 90205dc5fe Outlet zone step hold
- LinkBlend holds a cross-window feeder point that steps one block down as a CASCADE out of a held point, so the restyled last point of an outlet zone keeps its grade as in-window grading does
- Plunge distance fields stop at the bowl radius instead of LIMIT, with identical beds
- Test: cross-window settling keeps a one-block step at the end of an outlet zone
2026-11-02 06:21:21 -05:00
Brian Neumann-Fopiano 6041077c8a Structure place waits for plans
- Bukkit structure place catches ProvisionalAnswerException around the piece loop
- Pieces already written are recorded for /iris object undo, as the modded command does
- The player gets a retry message with the placement position
- The new message is translated in every bundled language
2026-11-02 06:08:09 -05:00
Brian Neumann-Fopiano 9f0615a975 Explicit Y below zero
- Automatic placement is a context flag set by the IrisObject x,z overloads instead of any negative Y
- An explicit world Y below zero places at that Y and skips the provisional guard, so saplings, pastes and structure pieces in -64 worlds land where asked
- Mantle surface, procedural, floating and single-piece structure placements call the automatic overloads
- A structure piece at world Y -1 places at its own height instead of a sampled one
- Tests cover explicit negative Y, the provisional guard on automatic placements only, and saplings growing below zero
- The sapling provisional test throws from the tree placement since explicit growth never reaches the guard
2026-11-02 06:06:09 -05:00
Brian Neumann-Fopiano 6aafec196b Plunge pools below falls
- RiffleProfile carves a plunge pool at the foot of every head step of 6 or more blocks in channel water: depth round(0.5 x drop x (0.85 + 0.15 x variation)) clamped to 2..8, radius clamp(0.75 x drop, 3, 12), one distance field per foot and top head pair that spreads only through the foot level, LIMIT kept at 160
- Riffle crests at least 5 blocks above a cell's sill no longer raise its bed, so the foot of a large fall stays deep while the brink keeps its head-1 sill
- Plunge pools never seed in or carve pond, lake, sea inlet or mouth columns
- The riffle raise below a step between two different channel reaches leaves the lower channel's bed alone (spec 11 design D); fields are keyed by crest level, feature and flowing role
- RiffleProfile samples head, feature and role per column through a Water sampler; WaterRole.flowing names the channel, cascade and waterfall roles
- RasterComposer styles a channel column below another channel reach's water 2 or more blocks higher as CASCADE, or WATERFALL from the higher reach's waterfallMinimumDrop
- ReachShaper.styles takes the sea level and styles a one-block drop out of an outlet zone or held lip as CASCADE when the head snap shows it as a two-block step; LinkBlend restyles with the same rule
- LinkBlend.settleInto holds a cross-window feeder's start only for a pond lip, a pond outlet or a fed start more than one block above the junction, the in-window p0cap1 rule
- Tests: plunge pool, chunk-border and standing-water RiffleProfile cases, receiving bed below a joining cascade, styled lower-channel edges, falls into ponds and mouths keep their floors, cross-window fed start, held-lip step styles, and no confluence tongues on the cached 2x2 openFractal and sloping valley scenes
2026-11-02 06:02:09 -05:00
Brian Neumann-Fopiano 7574e39f39 Copies keep structure force
- IrisObjectPlacement.toPlacement copies forcedByStructure, so slope-turned structure pieces keep the river and pond exclusion
- Tests cover the copied marker and a slope-turned forced piece over a river
2026-11-02 05:49:25 -05:00
Brian Neumann-Fopiano 0c7b0b7b80 Objects stop filling channels
- Wet hydrology columns reject solid object blocks between the bed and the surface unless the object is underwater
- The column role, head and bed come from the water role, water head and height streams
- Object placements tell the destination transaction whether they are underwater
- The mutation log and source plans carry the underwater flag so destination replay applies the same rule
- Tests cover canopies over channels and ponds, underwater exemptions, replay, piers and sea inlet slots
2026-11-02 05:46:52 -05:00
Brian Neumann-Fopiano 65d06ae83c Water objects need flat water
- Single-piece structures stay forced but keep the river and pond exclusion
- Water-flagged objects skip footprints on dams, cascades, waterfalls or water at another head
- The provisional guard runs before any bore and throws an engine failure
- Saplings stay when a tree override is rejected or the terrain is still being planned
- Object paste reports a retry when the terrain is still being planned
- Tests cover structures over rivers, flat water, lava, bore ordering, explicit Y and saplings
2026-11-02 05:19:02 -05:00
Brian Neumann-Fopiano 2ddc9f1106 Integrate lane B
- Merge lane B (sea surface, sea inlets, cave pools, wetness, persisted codes, scheduling knobs) onto lane A
- PackHydrologyValidatorTest keeps lane A's loadHydrology helper and lane B's validation tests
- Recapture HydrologySettingsTest.DEFAULT_FINGERPRINT and SchemaBuilderIdentityTest.EXPECTED_SCHEMA_DIGEST for the combined settings and schema
2026-11-02 05:11:09 -05:00
Brian Neumann-Fopiano 2edf610e8b Fed start riffle fix
- Hold a fed feeder's start only when it stands more than 1 block above its junction, so 1-block riffle starts join the receiving water
- Keep a fed start in the tongue invariant's pool zone as a held point that must cascade into its junction
- Drop the held-lip riffle tolerance and assert no tongues on the seeds again
- Stop the junction-level and led-in pool walks only at a styled fall from a held start or from more than 5 blocks beside the bank
- Cover 1-block fed starts in grader unit tests and riffling held starts in the scene invariant tests
2026-11-02 05:00:56 -05:00
Brian Neumann-Fopiano 2d52cc409e Water objects use hydrology
- Hydrology support gate applies only to land placements; underwater, onwater and forcePlace skip it
- Underwater and onwater anchors use the hydrology bed and head through the existing sea checks
- Automatic placements throw when any height or water answer before the block pass was provisional
- PlacementModuleSurfaceSupportTest covers ponds, rivers, forcePlace, dry columns and provisional water
- Drop the test that kept forcePlace out of river water
2026-11-02 04:43:11 -05:00
Brian Neumann-Fopiano 06b7001132 Inland hollow box cap
- Treat an inland hollow as open when its basin box would pass 2^20 cells, decided from the whole hollow
- Mark a classified hollow's cells inside the window as seen so its other pieces are not classified again
- Test a long diagonal trench classified open from two windows without sampling its basin box
2026-11-02 04:19:56 -05:00
Brian Neumann-Fopiano e108bd3c58 Junction pools stay local
- Fix a feeder's start in confluence grading when other reaches feed it, matching cross-window settling
- Pool feeder points outside every receiving channel only when they sit at most 5 blocks above the junction level
- Keep larger steps beside the receiving bank as a styled cascade or waterfall, in-window and across window lines
- Add valley trench, wall tributary and window copy regression tests plus grader unit tests
- Move the junction level, seam fall and led-in pool tests to the bank limit and fixed fed starts
- Mirror the fixed fed start and bank limit in the tongue invariant and classify held outlet lip riffles
2026-11-02 04:19:49 -05:00
Brian Neumann-Fopiano 217da03ef6 Descriptions match behaviour
- Policy fluid describes the per-stretch rule keyed on the upstream end, cave pools and the seam limit
- Policy class description covers region inheritance, whole-object wetness and cave-pool fluid order
- Wetness descriptions state that the bounded wetness also sets pond and lake drawdown
- Cave pool radius describes the square box around the site column
- Lake-borrowed pond fields name lakes: freeboard, climateDrawdown, materials, shore roundness, natural minDepth
- Lakes and ponds class descriptions list the pond settings lakes share
- Structure FLATTEN and SOURCE cuts beneath water or lava keep that fluid
- Studio Rivers view lists the water it draws instead of grottos
- Recapture the schema digest
2026-11-02 04:14:23 -05:00
Brian Neumann-Fopiano 408ac5e6b0 Fingerprint skips scheduling knobs
- prefetchRings and persist leave the hydrology settings fingerprint, since they only choose which windows are prepared ahead and whether plans are saved
- Compile checks drainage.fillEpsilon as the compiled float, rejecting values that round to 0 or overflow to infinity
- DEFAULT_FINGERPRINT recaptured
2026-11-02 04:00:20 -05:00
Brian Neumann-Fopiano ca431452fe Shore lists need a width
- Warn in pack validate when a hydrologyPolicy.shoreBiomes list has no shoreBiomeWidth above 0 applying to it, naming the dimension, region or biome that lists it
- Resolve the shore band through IrisHydrologyPolicy.shoreBand for both runtime placement and reachability
- Walk region biome lineages in ShoreBiomeLineages so reachable biomes include only shore biomes a width places
- Make HydrologyShoreTargets.placesAny use the placed shore biomes, so the locator ignores lists without a width
- Take the dimension in IrisRegion.getAllBiomeIds and getAllBiomes and gate their shore biomes on hydrology
- Drop region biome additions the package compilers already get from the dimension's reachable biomes
- Seed unset region colours from the natural biome ids
- State in the shoreBiomes description that a width is required, and recapture the schema digest
2026-11-02 03:43:29 -05:00
Brian Neumann-Fopiano 0a082f76ee Window-independent inland hollows
- InlandHollows classifies below-sea land from the shared height lattice, following each hollow past the planning area, so every window that sees a hollow treats it the same way
- A hollow is inland only when it is ringed by land, touches no ocean and stays under 16384 cells; anything else, or a hollow held by a region lake, is left open
- The basin draining into a hollow is flooded in a box set by the hollow itself, not by the planning area
- Burned trunks are never dragged to sea level through ground more than deformation.maxFill above the sea; the trunk link is cut there and the trunk restarts at its own height
- BasinExtractor loses the window-local inland and draining scans
- Tests: hollow cut by a grid edge, lowland open to the sea, hollow held by a lake, trunk floor on high ground, and a hollow on a window line planned alike by both neighbouring windows
2026-11-02 03:25:53 -05:00
Brian Neumann-Fopiano 5ef47f016e Enforce hydrology ranges at compile
- Compile rejects prefetchRings outside 0..4, fillEpsilon not above 0 and seeded cup density outside 0..64
- Compile rejects negative tier widthFactor and depthRatio, waterfallMinimumDrop below 2 and shoreDepth below 1
- Compile rejects negative maxFill, lakes.maxArea above 2048 squared and seaInlets.spacing below 1
- Compile rejects enabled cave pools whose freeboard max reaches maxDepth or whose maxArea exceeds 961
- Lake and cave pool area schema maxima match the compiled bounds; schema digest recaptured
- Engine start checks dimension, region and biome policy fluids whether or not cave pools are enabled
- Pack validation warns on written tiers without halfWidth or bankBand and on useMantle false or RIVER_HYDROLOGY disabled
2026-11-02 03:05:32 -05:00
Brian Neumann-Fopiano c0f2c10c1d Inland hollow review fixes
- Trunks are cut where they cross the natural basin draining into an inland hollow, so the major restarts beyond the rim instead of descending through it at sea level
- Lowland channels never climb more than 2 blocks above the lowest ground they crossed or the sea, in a new LowlandChannels helper
- Inland hollow ponds skip dams
- Hollow planner tests assert no reach is held at the sea under high ground and the valley past the rim matches the hollow-free valley
- Pondless inland hollows end streams at their edge
- One shared SeaCells test helper replaces the two copies
2026-11-02 02:42:35 -05:00
Brian Neumann-Fopiano 720b9ac967 Drawdown follows zone wetness
- Carry each column's bounded zone wetness and whether climate zones apply to it as wetness and climateZoned sample channels, copied by HeightLattice
- Draw pond and lake surfaces down by climateDrawdown times one minus the bounded zone wetness at the floor inside climate zones, and by one minus rainfall where the zones are off or climateZones is false
- Test the drawdown in wet, dry and transition zones and outside them, and that two windows give a pond the same level
- Test that a policy wetness min keeps a dry-zone pond from drawing down, from the terrain source through the planner
- Describe the rainfall policy as lowering ponds only where the climate zones do not apply
- Recapture the schema digest
2026-11-02 02:38:59 -05:00
Brian Neumann-Fopiano fa43b276f4 Bound policy multipliers
- Reject a policy rainfall or pondDensity outside 0..16 when a column resolves it, naming the biome and region
- Report a policy rainfall or pondDensity outside 0..16 at every scope in pack validation
- Share the 0..16 bound between the schema, the terrain source and the validator through IrisHydrologyPolicy.MAX_MULTIPLIER
- Size the window cup grid from a double product of seeded density and peak pond density
2026-11-02 02:15:34 -05:00
Brian Neumann-Fopiano 4000dfe659 Pond density scales cups
- Size each window's seeded cup grid from ponds.seeded.density times the window's peak pondDensity
- Give each site the chance density times its column's pondDensity over the grid area, so cup counts follow pondDensity above 1
- Key site jitter and rolls on the grid split, and cup radius and depth on the site position, so grids of different sizes stay independent
- Test that pondDensity 3 seeds more ponds than 1.6 and that cups agree across overlapping windows where pondDensity varies
- Slope pond test plans a margin around its window and checks the ponds the window owns
2026-11-02 01:59:47 -05:00
Brian Neumann-Fopiano 30865031ba Inland lowlands not mouths
- Reach chains end at the sea only where the receiver has ocean intent
- Channels continue across non-ocean lowland below sea level toward the sea
- Fitted ocean flags stay only on the trailing run of chains that drain to the sea
- Ground reads off the sea run ignore sub-cell ocean slivers, so a sliver no longer trenches a reach or drops ponds below it
- Inland hollows below sea level hold an outlet-free pond at sea level; oversized ones sink instead of being breached
- Burned trunks neither descend nor drain through inland hollows
- Sea-head check keys on the trailing mouth run and fails closed on mouths inside a reach or draining into another reach
- Inland water keeps the land biome at any head; mouths and inlets keep the sea biome
- Tests for inland hollows, crater rims, sea slivers, inland pond outlets, coastal delta ownership and the sea-level river biome
2026-11-02 01:57:09 -05:00
Brian Neumann-Fopiano 0245a10c95 Per-area wetness clamp
- Add hydrologyPolicy wetness with min and max bounds, inherited like the other policy fields
- Clamp the climate zone wetness to the area's bounds before it scales rainfall and pond density
- Reject wetness bounds outside 0..1 or with min above max at sampling and in pack validation
- Report non-neutral wetness bounds as a RIVER_CLIMATE export limit on the owning policy
- Recapture the schema digest
2026-11-02 01:35:10 -05:00
Brian Neumann-Fopiano f7ddd68d26 Child lineage review fixes
- Terrain source test samples a self-cycle and a two-cycle child graph and checks every lineage link and inherited value
- Shore biome lookups skip the lineage unless some policy sets a positive shoreBiomeWidth
- IrisBiome.CHILD_HOPS is the one child hop limit for implosion and datapack river areas
- A missing shore biome error names the biome, region or dimension that lists it
2026-11-02 01:15:37 -05:00
Brian Neumann-Fopiano ff0a95a6fd Inherit parent biome policy
- IrisHydrologyPolicy.inherited walks the column's biome lineage (child, then the parents it grew inside), then region, then dimension
- IrisComplex.baseBiomeLineage recovers the per-column child chain from the implosion and fails closed if it disagrees with the base biome
- BiomeLineages limits chain recovery to biomes a policy-bearing biome can implode into and interns lineages for identity caches
- Terrain source, shore biomes and water decorators resolve by lineage; cave pools keep the cave biome alone
- Datapack river areas enumerate each region's child chains and RiverLimits attributes inherited values to the parent
- Policy description names the parent step; schema digest recaptured
2026-11-02 00:57:34 -05:00
Brian Neumann-Fopiano d61b5c3041 Delta planner split
- Move delta planning out of ReachShaper into a package-private DeltaPlanner that ReachShaper calls once
- Drop the redundant tier parameter from the distributary methods
- Test delta crossings through a new raster ChannelCoverage built on ReachSegments and ReachCursor, limited to segments near the channel
- Keep DELTA_STEP in HydrologySettings beside its extent guard
- Share the delta coast fixture through testsupport and split the pond, hill and neighbouring-river cases into their own tests
- Cover delta rendering: MOUTH sea-fluid water at sea level, no dry gap or leak at the branch, and the river above its estuary keeping its head
2026-11-02 00:19:04 -05:00
Brian Neumann-Fopiano 95fa3ce105 Resolve medieval engine late
- MedievalPregenMethod re-resolves its engine on each call until one exists, then caches it
- Hydrology prefetch opens its epoch at the first prepare that sees the engine, with the stored region bounds
- MedievalPregenMethodTest covers a null first prepare followed by concurrent prepares opening the epoch once
2026-11-02 00:18:58 -05:00
Brian Neumann-Fopiano 6cbe4b2c09 Remove studio render paths
- Drop IrisRenderer.renderStudio, renderStudioBase and refineStudioBiome with their adaptive, height and river atlases
- Drop RenderType.RIVER and the test-only WaterMap.draw
- Port the river renderer tests to the live WaterTile path
- Use a settled WaterTile as the map overlay test oracle
2026-11-02 00:00:10 -05:00
Brian Neumann-Fopiano 490016b56a Remove transition hydrology weight
- Drop test-only TransitionGenerationPlan.hydrologyWeightAt
- Drop TerrainSample.hydrologyWeight and its validation
2026-11-02 00:00:10 -05:00
Brian Neumann-Fopiano df7aa2ef16 Remove dead cave cell code
- Drop HydrologyCaveAction.FALLING_FLUID; saved code 2 stays reserved and loads as WET_SOURCE
- Drop the flooded biome key from cave cells, Engine.floodedCaveBiome and the sea inlet rasterizer argument
- Write the retired biome slot empty and skip it on read so saved plates keep loading
- Drop the constant protectsPlacement check from every caller
- Drop the test-only of() factories and the default fluid key; tests use real keys
- Drop the unused falling-fluid carve state and isFalling
2026-11-02 00:00:10 -05:00
Brian Neumann-Fopiano d3b364fa15 Seeded river deltas
- Add the tier delta {channels 0 or 2..4, spreadDegrees 35, length 64}, validated in HydrologySettings with messages naming the tier and fingerprinted
- Guard the delta extent so a delta channel and its banks stay within the 512-block window span
- Emit delta channels after grading as ordinary sea-level MOUTH reaches that branch below the estuary start and fan out by seeded angles to the sea
- Size each delta channel at the estuary-start half-width over sqrt(channels) and taper its depth to one block at the sea
- Leave out delta channels over ground above sea level plus maxFill, across ponds, lakes, other reaches or the river's above-sea water, or short of the sea within length
- Recapture DEFAULT_FINGERPRINT and EXPECTED_SCHEMA_DIGEST
- Cover seeded, grid-independent deltas and their obstacles, the delta bounds, and inlets keeping clear of sea-level delta channels
2026-11-01 23:53:17 -05:00
Brian Neumann-Fopiano b195582259 Unplanned single reads unavailable
- Return the unavailable result from single-column reads that read a provisional answer
- Share the provisional revision check between single reads and sampleColumns
- Test each single-read family before and after its column is planned
- Test that a final column after a provisional one is final
- Test that a sink that reads provisionally does not mark later columns
2026-11-01 23:30:23 -05:00
Brian Neumann-Fopiano 2b6612501a Mark provisional column samples
- Add a provisional component to IrisColumnSample
- Set it in sampleColumns when a column read a provisional answer (ProvisionalSampling revision changed)
- Test server-thread unplanned columns are provisional and planned columns are final
2026-11-01 23:19:38 -05:00
Brian Neumann-Fopiano 549eaa7e20 Report seams and defer areas
- RIVER_FLUID reports the seam of a river fluid whose blocks match the exported dimension fluid
- River export areas are built only after the hydrology enabled and density checks pass
- Tests cover matching-fluid seams, an unknown policy fluid failing the export, deferred area building, and the stage's exported-biome filter with child traversal
2026-11-01 23:09:43 -05:00
Brian Neumann-Fopiano 904c889c2f Seamed lava falls
- Add FluidSeams.fallingFluid: a fluid with a seam falls as its seam where it lands on a different fluid
- Take the falling fluid in MantleHydrologyComponent from that rule, so lava stepping into its estuary or a water river falls as its seam
- Cover the rule, the mantle falls onto sea, water and lava, and a lava reach dropping into its estuary
2026-11-01 23:00:50 -05:00
Brian Neumann-Fopiano 8e048944ec Report datapack hydrology limits
- Datapack export warns with RIVER_FLUID when a tier or hydrology policy fluid differs from the dimension fluid, naming its seam
- Hydrology policy rainfall and streams BLOCK report RIVER_POLICY on the dimension, region or biome that sets them
- Wet and dry climate zones report RIVER_CLIMATE unless every exported area opts out
- Shore biomes with a width report RIVER_SHORE_BIOME, and tier or policy water decorators report RIVER_DECORATOR
- Enabled sea inlets and cave pools report SEA_INLET and CAVE_POOL
- River stage resolves policies per region and exported surface biome, reporting each limit once per scope in a fixed order
- Dimension stage shares its fluid block resolution with the river limits
2026-11-01 22:54:48 -05:00
Brian Neumann-Fopiano b17ad570ca Estuary review fixes
- Taper estuary depth to the minimum depth at the mouth so the bed hands over to the natural seabed
- Stop the estuary walk at an outlet's first point so lake outlets leave the lake at its level
- Return a closed estuary opening for length 0 or a zero-length estuary instead of NaN widths
- Record mouth river features with their reach's own fluid through HydrologyRuntime.channelFluid and the shared ChannelFluids.reachFluid
- Pin the bank-height stop, the held pond lip, the lake outlet start and the degenerate opening
- Use a neutral unknown tier key in the pack compatibility test
- Recapture EXPECTED_SCHEMA_DIGEST for the flare description
2026-11-01 22:52:35 -05:00
Brian Neumann-Fopiano 81b47a8f9b Refresh recorded cave pools
- Generation history keeps a river revision that moves after recorded river features or cave pools become readable
- Studio water tiles reload cave pools when that revision moves instead of the hydrology preview revision
- Water tiles at 4 blocks per pixel or closer keep their water state and base colors after completion, counted in the cache weight
- The Vision controller re-renders those completed tiles when the river revision moves, after the first retry delay, redrawing only their water
- Tests cover the revision counter, completed and coarse tiles through the controller and pools recorded after a raster lands
2026-11-01 22:27:50 -05:00
Brian Neumann-Fopiano aef674f206 Estuaries replace deltas
- Replace the tier deltas flag with estuary {length 48, flare 2.5}, validated in HydrologySettings and added to the fingerprint
- Grade ocean-ending reaches to sea level over the estuary while the lower bank lies within maxFill of the sea, stopping at held pond outlet points
- Style estuary points MOUTH and flare their half-width by 1 + (flare - 1) * s^2 toward the mouth, keeping the channel depth
- Fill MOUTH columns with the sea fluid so lava rivers meet the sea through their seam
- Paint MOUTH columns with the sea layers and ice of the sea floor, like INLET slots
- Stop bank levees from raising ground below sea level
- Recapture DEFAULT_FINGERPRINT and EXPECTED_SCHEMA_DIGEST
- Cover the estuary flare, mouth sea fluid, lava mouth seam, frozen mouth ice, the strict no-berm coastal fall and the coastal sea-floor scene
- Pin that tiers written with an unknown key load with the default estuary
2026-11-01 22:23:36 -05:00
Brian Neumann-Fopiano 0c59e698cd Rank studio water features
- Plan-mode pond and lake masks keep the strongest feature per pixel instead of overwriting channels and falls
- Water map ranks come from an explicit switch per feature type, with ponds above lakes
- Studio water tiles redraw recorded cave pools when the hydrology preview revision changes
- Tests cover channels over ponds, ponds over lakes and cave pool refresh on a completed tile
2026-11-01 22:11:42 -05:00
Brian Neumann-Fopiano c0169d6dcd Bound planned search by recorded
- nearestRiver limits the planned search to the recorded water's distance, rounded up, when generated chunks hold a match
- Explored areas end with a confirmed Found instead of waiting out the 30 s timeout; nearer planned water inside the bound still wins
- Tests cover the bounded radius in queries and a bounded search that finishes under a short timeout when nothing near is eligible
2026-11-01 21:57:14 -05:00
Brian Neumann-Fopiano 9afd70e69f Report stopped river searches
- A timed-out hydrology search throws HydrologySearchTimeoutException carrying the nearest feature found so far
- nearestRiver answers RiverSearch.Stopped with the nearer of that feature and recorded water, and a message saying a nearer one may exist
- Bukkit and modded find river print the stopped message and never teleport on a stopped search
- Both commands catch every throwable while delivering a result and log it before telling the player
- Modded logs a result that cannot reach the server thread instead of dropping it
- The four-argument nearestFeature is removed; tests call the six-argument form
2026-11-01 21:48:10 -05:00
Brian Neumann-Fopiano 11ce906e5b Lead-ins before confluence grading
- Pond outlets are led in from their pond before confluence grading, so a feeder joining at an outlet's exit node pools against the lead-in segment too
- A feeder at a led-in outlet's exit sits at the junction level wherever it comes within its pool margin of the lead-in
2026-11-01 21:30:25 -05:00
Brian Neumann-Fopiano 474b1e873a Bound find river search
- HydrologyFeatureSearch stops after its timeout or when the caller cancels, waiting on plans in 50 ms slices
- Types the dimension cannot form answer at once without planning, naming the setting that turns them off
- channelType reads the tier name (stream, river, major or major_river) and falls back to rank, so one-tier packs match stream
- HydrologyRuntime adds unavailable(type) and passes FEATURE_SEARCH_TIMEOUT (30 s) and a running check to the search
- nearestRiver returns a RiverSearch outcome, reports disabled and timed-out searches, and keeps recorded water on timeout
- startRiverSearch keeps one search per player; a new search cancels the previous one without a message
- Bukkit and modded find river run through the shared per-player search
- Tier name description and schema digest follow the new tier naming
- HydrologyFeatureSearchTest plus new query, Bukkit and modded cases cover the bounds
2026-11-01 21:27:50 -05:00
Brian Neumann-Fopiano 98d69e503c Lake outlets keep width
- Cross-window links treat a reach whose first point is styled as a pond outlet as an outlet, so lake outlets skip the junction width blend
- A lake outlet below a narrow tributary across a window line keeps its own width
2026-11-01 21:15:19 -05:00
Brian Neumann-Fopiano 5948c5b5f4 Fixed outlet points styled
- Every point the grader holds fixed, in the outlet zone or on the held lip, is styled as the pond outlet, so the reach carries its own fixed set
- The tongue check exempts an outlet column only on a fixed point, only when the outlet itself ends at the junction head and only when every step down is a cascade or waterfall
- Held outlet tests sit on a real pond lip, and an outlet with a perched unheld tail or an end above the junction is reported
- A shore-held outlet test covers the outlet style past the 8-block outlet zone
2026-11-01 21:15:19 -05:00
Brian Neumann-Fopiano 358f7218f8 Junction errors name window
- Reach indexes take their window key and name it when a reach id appears twice in one plan
- Window planning passes its key through reach shaping, pond-channel settlement and confluence grading
- A downstream reach starting above its feeder's end fails closed naming the window
- Index, grader and plan-cache tests check that each failure names its window
2026-11-01 20:48:08 -05:00
Brian Neumann-Fopiano 41e38debad Outlets keep their width
- Pond outlets skip the junction width flare, so an outlet whose exit node takes a tributary leaves its pond at its own width
- Cross-window links into a pond outlet clamp its grade without rebasing its width or depth
- The cross-window width blend always measures from the downstream reach's first vertex
- Planner and cross-window tests cover narrow and wide tributaries at an outlet's exit node
2026-11-01 20:43:39 -05:00
Brian Neumann-Fopiano 75d28d16b2 Gate pool and inlet leaks
- Count sea inlet added leaks as leak cells present only with inlets on
- Fail the cave pool gate on pool cells that are not still sources of their fluid
- Compare pool sources against the fluid each cell resolves to
2026-11-01 20:42:33 -05:00
Brian Neumann-Fopiano 1ae68646b4 Seal inlets and headroom
- Seal covered inlet passages with rock where they come within two blocks of a historical chunk
- Add inlet headroom bands from the water up to the passage ceiling plus roofClearance to CaveCeilingMask
- Join the headroom bands into the carver and orphan sweep protection
- Keep subterrain cells out of the headroom bands in carving, the carve resolver and preserveSubterrain
- Apply seal guards inside upper-dimension and dimension-stack protected ranges
- Add old-chunk seal, headroom mask, carving wiring, subterrain and protected-range tests
2026-11-01 20:42:33 -05:00
Brian Neumann-Fopiano 1827ec1cc6 Confluence pool invariant
- Confluence tongues are feeder columns in the junction pool zone standing above the junction head, which the old receiving-grade check could never report under lowest-water ownership
- Pond outlets may stand above the junction in the pool only when every head step down to it is a cascade or waterfall
- The tongue scan clips its box to the scene interior instead of skipping feeders near the edge margin
- Unsettled hand-built feeders, sibling channels, held outlets and an edge-straddling pool are positive and negative controls
- Pond outlets and confluences are checked on one planning pass over seven open fractal seeds
2026-11-01 20:40:14 -05:00
Brian Neumann-Fopiano de62c76807 Sea head review fixes
- The mouth sea-level check covers only the trailing mouth run of reaches that end in the ocean
- Ocean-flagged points inside a reach no longer fail planning closed
- Reach checks are split into a below-sea pass and a trailing-mouth pass with one failure message builder
- Reflooded ponds stop lowering at the sea surface and drop instead of standing below it
- A sea-strip slope fixture reproduces mid-reach mouth points above sea
2026-11-01 20:12:45 -05:00
Brian Neumann-Fopiano 0ca3a61046 Resolve cut-off inlet competitors
- Let a cut-off inlet still make a later conflicting inlet yield, and never list it
- Throw when a window's own inlet reaches the edge of its planning span
- Check the planner's chamber and step lookups against the sea-inlet extent guard
- Remove the reach ownership filter, which never removed a span reach
- Plan inlet tests on window spans and add bay, guard, edge and fail-closed tests
2026-11-01 19:56:27 -05:00
Brian Neumann-Fopiano d341e114b5 Sea heads fail closed
- Window plans reject sea inlets off sea level, reaches graded below sea level, mouths not at sea level and ponds below sea level, naming the window and feature
- Coastal fractal and cliff coast scenes pin inlet levels, mouth grades, minimum grades and raster mouth and inlet heads at sea level with no sub-sea air
- Hand-built plans with off-sea mouths, sub-sea runs and sunken ponds fail closed
- The coastal fall raster test also runs with a 32-block bank band
- Planned scenes expose their sea inlets and synthetic terrain can be lowered
2026-11-01 19:50:10 -05:00
Brian Neumann-Fopiano 1cdc30e1ca Confluence settling review fixes
- Look reaches and outlet ponds up through ReachIndex.reach and ReachIndex.outletPonds, built once per plan, instead of per-chunk maps in ChunkFeatures.Links
- Find a feeder's downstream reach across the loaded windows and fail closed when two windows own it
- Clamp a no-lead-in shared outlet to the last pond with its id in its own plan when every sharing pond is in that plan, matching ReachGrader.outletPonds
- Rebuild an outlet's held lip with the shared ReachShaper.nearLip rule and keep it fixed when the outlet settles across a window line
- Rename the feederLink local that shadowed the owned-reach lookup
- Add ChunkWaterRasterTest cases for the downstream outlet pond level, a fully pooled stub, the held lip, the same-plan shared outlet and the duplicate owner
2026-11-01 19:27:01 -05:00
Brian Neumann-Fopiano 21ed677bf4 Agree sea inlets across windows
- Pass the planning window to SeaInletPlanner from WindowPlanner
- Mark a site clipped when its candidate area or any trace, cover, mouth or chamber lookup reaches the span edge
- Keep clipped inlets out of separation and the planned list unless the planning window owns them
- Avoid only reaches owned by the planning window or its 8 neighbours
- Add InletTerrain span views and an open-coast 3x3 window agreement test
2026-11-01 19:07:41 -05:00
Brian Neumann-Fopiano e62585b450 Cross-window confluence settling
- Track every reach owned by the nine loaded windows in ChunkFeatures.Links.owned
- Settle a feeder whose downstream reach has another owner window into L = min(raw downstream start, raw feeder ends, downstream outlet pond level) through LinkBlend.settleInto
- Delegate LinkBlend.settleInto to ConfluenceGrader.settle with vertex 0 and outlet-zone vertices fixed, spreading the junction on tiers without cascades
- Restyle every grade change made by link clamping or settling with ReachShaper.styles, so seam drops become cascades and waterfalls
- Rebase the cross-window width and depth blend on the junction width so an already flared downstream reach is unchanged
- Clamp a led-in pond outlet to the pond it leads out of instead of the lowest pond sharing it
- Make ConfluenceGrader.spreadJunction and ReachShaper.styles public
- Add ChunkWaterRasterTest cases for cross-window settling in both window orders, styled seam drops, spread junctions, flare rebasing and shared outlets
2026-11-01 19:04:05 -05:00
Brian Neumann-Fopiano b6166bc6fa Junction width flare
- Blend a downstream reach's half-width over its first 16 blocks from the widest feeder end to the width law in ReachShaper.widths
- Move the blend math into the shared LinkBlend.blend(from, to, along) used by both the planner flare and cross-window links
- Measure the cross-window width blend from the junction vertex, so led-in pond outlets blend from their real junction
- Add ReachShaperTest.junctionWidthBlendsOverSixteenBlocks and ChunkWaterRasterTest.ledInOutletWidthBlendsFromItsJunctionAcrossAWindowLine
- Skip reaches whose end lies inside the junction flare in widthFollowsSqrtCatchment
2026-11-01 18:34:34 -05:00
Brian Neumann-Fopiano 9c95e7901c Pin persisted enum codes
- Give HydrologyFeatureType, ReachStyle and PondKind explicit codes equal to their old ordinals
- Add PersistedCodes lookup tables that reject duplicate, out-of-range and unknown codes
- Write and read codes in HydrologyPlanCodec; unknown codes decode as malformed plans
- Write and read codes in GenerationSemanticIndex shard records and region summaries
- Order summary river types and the river feature comparator by code
- Pin the code tables and a captured plan byte fixture in tests
2026-11-01 18:31:01 -05:00
Brian Neumann-Fopiano 52761e1784 Confluence review fixes
- Spread the junction step of feeders on tiers without cascades through the grader's spread rule, never moving outlet zone or held points
- Extract ReachGrader.spreadPoint from the spread pass and clamp it so it only lowers
- Throw when a downstream reach starts above its feeder's end, naming both reach ids and the junction
- Restore the per-reach waterfall check in gradeNeverRisesDownstream, excluding drops that land at or below the stepped twin's junction level
- Add ConfluenceGraderTest for spread junction steps, the fixed-point exception and the fail-closed junction
- Describe junction spreading in the cascades setting and recapture the schema digest
2026-11-01 18:18:40 -05:00
Brian Neumann-Fopiano f6fbf9147f Keep reserved subterrain over transforms
- Let reserved subterrain cells without hydrology answer before a transformed column in every post-transform reader
- Move the transformed override into CarveOwnership.carved so the five readers share one order
- Read the natural opening and the cavern only when hydrology and subterrain leave the cell open
- Cover reserved passages and the reserved-solid transform case in the ownership tests
2026-11-01 18:15:28 -05:00
Brian Neumann-Fopiano b11ff94737 Restore transformed carve override
- Rank CarveOwnership as hydrology over subterrain over natural opening over cavern
- Share the subterrain claim predicate and the carved answer through CarveOwnership
- Let a transformed column override MantleWriter point and column readers and EngineMantle.isCarved again
- Resolve the untransformed MantleWriter column readers per block through CarveOwnership
- Keep IrisCarveModifier.carveOwner package-private and test it in its own package
2026-11-01 18:04:26 -05:00
Brian Neumann-Fopiano 4cf141b97b Confluence grading
- Add ConfluenceGrader: feeder tails touching the receiving channel or a sibling settle to the junction level, capped at 64 blocks of arc
- Grade small junction differences over an approach ramp of one block per four, and keep larger ones as one fall at the receiving bank
- Never move pond outlet zone or held outlet points while grading confluences
- Run confluence grading after the finish pass in ReachShaper and restyle the reaches it lowers
- Add ReachShaperTest cases for feeders meeting the junction level and a hanging tributary falling at the receiving bank
- Compare drop counts by size instead of cascade and waterfall point styles in gradeNeverRisesDownstream
- Assert no confluence tongues on openFractal seeds 1 to 3 in WindowPlannerTest
2026-11-01 17:58:33 -05:00
Brian Neumann-Fopiano ccd5551854 Share carve ownership rule
- Add CarveOwnership, ranking hydrology over subterrain over transformed over natural
- Resolve IrisCarveModifier cell ownership through IrisCarveModifier.carveOwner and CarveOwnership
- Let hydrology win over subterrain rooms and transformed columns in MantleWriter isCarved and isPrerequisiteCarved
- Check subterrain rooms in EngineMantle.isCarved and let hydrology win over transformed columns
- Add CarveOwnershipTest running every reader over every flag combination
2026-11-01 17:48:15 -05:00
Brian Neumann-Fopiano 6f38d98e9e Check reachable biome fluids
- Engine start validates every reachable biome policy fluid while cave pools are enabled
- caveFluidPolicies stays computed from cave biomes, regions and the dimension only
2026-11-01 17:30:19 -05:00
Brian Neumann-Fopiano 50839c4833 Outlet review fixes
- Treat an outlet as led in only when its first vertex lies inside its source pond mask, so links and corner blocks keep the first vertex as the junction when the lead-in was skipped
- Hold and lead in each outlet draft once, from the pond the grader uses as its source, through the new ReachGrader.outletPonds
- Let ocean points keep the sea cap on held outlet stretches
- Add tests for a skipped lead-in junction, two ponds sharing an exit, and a held outlet running into the sea
- Plan the openFractal outlet scenes inline and count only the outlets that detachedOutlets checks, through the new WaterInvariants.checkedPonds
- Reuse the WaterInvariants segment geometry helpers in WindowPlannerTest
2026-11-01 17:29:53 -05:00
Brian Neumann-Fopiano 1e41c9eca0 Inherit cave pool fluids
- Cave pools resolve fluid from the cave biome, then region, then dimension
- Engine.getCaveBiomeBelowSurface returns no biome where caves fall back to the surface
- caveFluidPolicies turns on only for cave biome, region or dimension fluids
- IrisDimension.getReachableCaveBiomes lists region cave biomes and carving bands
- Recapture the schema digest for the cavePools.fluid description
2026-11-01 17:19:24 -05:00
Brian Neumann-Fopiano 0dabc54e88 Outlets start on the shore
- Hold the leading outlet points near the pond at the pond level in ReachGrader, and keep spread from lowering them
- Prepend a lead-in from the nearest pond mask node to each non-lake outlet, unless the anchor would fold the reach back on itself
- Give held outlet points at least a one-block half-width and carry the held flags through chaikin and unfold
- Add PondMask.Cell and PondMask.nearest
- Link led-in outlets to their feeders at the junction vertex in ChunkFeatures, falling back to the first vertex's window
- Count equal-head water inside the outlet footprint as outlet water in WaterInvariants.detachedOutlets
- Add tests for the lip outlet, the tributary junction, the fallback exit, the swallowed outlet and the cross-window led-in feeder
- Assert connected outlets on openFractal seeds 1-7 and in the planned scene, and tighten the settled-pond shore check
- Check outlet exits at the junction vertex in ReachShaperTest
2026-11-01 17:15:27 -05:00
Brian Neumann-Fopiano 028c3e322f Merge branch 'size-bootstrap' into size-natives-guides 2026-11-01 17:00:50 -05:00
Brian Neumann-Fopiano c89bec2850 Thin Bukkit entry classes
- Move plugin lifecycle, static state and logging helpers from Iris into the payload-only IrisRuntime
- Keep Iris as one-line forwarders through the IrisPluginRuntime bridge interface
- Move the Paper bootstrap body into the payload-only IrisBootstrapSequence
- Read the world reconciler, replacement manager, debug dump and chunk tickets through IrisRuntime.require()
- Pass the world generator resolver to BukkitWorldReconciler instead of the plugin
- Replace KList and IO uses in VolmitPlugin with JDK code
- Remove the unused sync job queue, Java version helpers, addPanic, imsg and the onCommand passthrough
- Keep generation kernel revisions, map view icons and the datapack icon only in the packed payload
- Cap the packed bootstrap at 90 classes
- Point entry-class tests at IrisRuntime and IrisBootstrapSequence
2026-11-01 16:59:36 -05:00
Brian Neumann-Fopiano 701b3191eb Supply structure sea surface
- GenerationWritePolicy.seaSurface returns minHeight + fluidHeight and the first fluid of the dimension fluidPalette
- Dimensions with no sea fluid or a sea at the world floor return StructureSeaSurface.NONE
- Bukkit and modded structure stage policies supply the sea surface to native structure fitting
- Native fitter tests pass SeaSurface.NONE to keep their expectations
- FLATTEN descriptions state the sea-surface clamp and sea-fluid fill
- Schema digest recaptured for the description change
2026-11-01 16:50:57 -05:00
Brian Neumann-Fopiano 06bd50d1a0 Lowest water owns confluences
- Add ReachCursor.Waters, which keeps the nearest covering segment per reach and resolves the channel owner by planned head, then wider half-width, distance, id and segment
- Offer covering segments to Waters in ReachSegments.evaluate and resolve the owner at the end of every nearest lookup
- Prune channel candidates by segment radius once the scope is CHANNEL or any water covers the column
- Cut channel and trench beds to the deepest bed among covering reaches whose snapped head equals the owner's head
- Add ChunkWaterRasterTest.receivingRiverOwnsItsFootprintAtAConfluence
- Flip the PlannedSceneTest confluence tongue cases to expect no tongue
- Expect the wider equal-level channel in ReachIndexTest and the lowest covering channel in PondChannelSettlementTest
2026-11-01 16:41:40 -05:00
Brian Neumann-Fopiano 714b4499b0 Download noise natives and language guides instead of bundling them in the Bukkit jar 2026-11-01 16:29:20 -05:00
Brian Neumann-Fopiano 1d23587b90 Match LWJGL natives jars by file name in GpuLibraryTest 2026-11-01 16:29:20 -05:00
Brian Neumann-Fopiano a06f487279 Scene invariant fixes
- Check confluence tongues against the downstream reach and every sibling feeder
- Skip features within 32 blocks of the planned block edge in all three invariants
- Split the detached outlet controls into shore-gap and lower-start cases
- Plan the cached openFractal scene with rainfall 0.5 so pond drawdown applies
- Clear the cached scene after the test class
2026-11-01 16:25:35 -05:00
Brian Neumann-Fopiano 8bc1ed760e Key cave pool walls
- Cave pool walls carry the pool's fluid key instead of the unknown default profile
- A wall shared by two pools keeps the lowest fluid key, whatever the chunk order
- The carve waterlogging pass resolves a fluid only for wet hydrology cells
- Tests cover unknown-fluid logging for pool walls and shared-wall chunk-order independence
2026-11-01 16:25:32 -05:00
Brian Neumann-Fopiano 118c64b50b Planned scene fixture
- Add PlannedScene, which plans a block of windows with RegionPlanner and WindowPlanner and rasterizes it with ChunkRasterizer
- Add WaterInvariants with detachedOutlets, confluenceTongues and subSeaAir
- Add PlannedSceneTest, which characterizes today's detached pond outlets on openFractal(1) over 2x2 windows
- Add hand-built checks for each invariant
- Rename SyntheticTerrain.fractal to openFractal and update its call sites
2026-11-01 16:11:07 -05:00
Brian Neumann-Fopiano bb6f3ca40b Gate hydrology probes
- Count roof breaches as sea inlet check failures
- Count raised berms over the fill cap as hydrology probe failures
- Exit the sea inlet gate with 1 on failed checks, order mismatches, inlets off sea level or leaks the inlets add
- Exit sea inlet inventory with 1 when a window fails to plan
- Exit the cave pool probe with 1 on containment failures or order mismatches
- Print a gate status line for both probes
- Cover the failure counting in the probe unit tests
2026-11-01 16:02:46 -05:00
Brian Neumann-Fopiano 69416c235c One water-head rule
- Add WaterHeads.snap as the single sea-level parity rule for water heads
- Route RasterComposer heads through WaterHeads.snap and drop its private level helper
- Route PondChannelSettlement heads through WaterHeads.snap and drop its private head helper
- Route ChunkFeatures and ReachSegments hasOnlyLevel checks through WaterHeads.snap
2026-11-01 15:53:59 -05:00
Brian Neumann-Fopiano 30c7492679 Keep Engine API in release shrink 2026-11-01 14:58:37 -05:00
SwiftSwamp 8b99f0b75f Merge remote-tracking branch 'origin/master' 2026-11-01 10:16:11 -07:00
Brian Neumann-Fopiano 8734c38361 BTA 2026-10-31 22:42:16 -04:00
Brian Neumann-Fopiano 2d4ede41dd Merged pack authoring features
- Biome effects choose their sound category on every platform
- Hanging vines keep supported authored side faces on every platform
- Inland water above sea level keeps its land biome
- River reaches take the policy fluid of their upstream end
- Fluid profiles can name a seam that lines their edge against other fluids
2026-10-31 22:27:31 -04:00
Brian Neumann-Fopiano bd44272802 Schema digest
- Studio schema digest covers seam and sound category fields
2026-10-31 22:07:15 -04:00
Brian Neumann-Fopiano 31da551c04 Merged effect sound and vine fixes 2026-10-31 22:03:58 -04:00
Brian Neumann-Fopiano 067fffe066 Ceiling vine curtains
- A vine under a sturdy ceiling keeps its authored side faces
- Vines below it hold those faces through the vine above
- The vine-above check reads the facing before the material key
2026-10-31 22:03:49 -04:00
Brian Neumann-Fopiano c2eb8b5f42 Fixed effect sounds and vines
- Store the effect sound category as a vanilla category name
- Resolve the sound category to a Bukkit category when an effect plays
- Send modded effect sounds on the authored category
- Skip the sound and warn once for an unknown sound category
- Keep authored vine side faces only where a sturdy block or the vine above holds them
- Attach kept vine faces upward under a sturdy block
- Reattach multi-face blocks with no holdable side face to sturdy neighbours
- Cover sound category and vine face rules on Bukkit and modded
- Repin the studio schema digest
2026-10-31 21:58:58 -04:00
Brian Neumann-Fopiano f686ec84f8 Merged fluid seam fixes 2026-10-31 21:42:45 -04:00
Brian Neumann-Fopiano 52989ce88d Fluid seam fixes
- Fluid seams seal from the 3x3 neighbour rasters in the effective water stage
- Seam bands spread across chunk edges like any other column
- Raw rasters keep their fluid so falls and history capture see the real fluid
- Seams no longer change the hydrology fingerprint
- Seam profiles may hold solid blocks but cannot fill tiers, ponds, cave pools or policies
- A seam profile cannot name a seam of its own
- Pack validation reports a policy fluid that names a seam profile
- Inland water skips columns outside the transition seam weight
- Channel fluid test covers the per-reach rule
2026-10-31 21:42:35 -04:00
Brian Neumann-Fopiano 64dc22025e Merged pack authoring features
- Rivers take the hydrology policy fluid of the area where each reach starts
- Policy fluid lookups for reach starts run in a sparse bake scope
- Effects, vine faces, inland water biomes and fluid seams come from the contributed branch
2026-10-31 21:26:16 -04:00
SwiftSwamp 55bc7365f1 Merge remote-tracking branch 'origin/master' 2026-10-31 17:42:51 -06:00
Brian Neumann-Fopiano b0860f94fc Gap-free object rotation
- Rotations off the right angles fill every target cell from the nearest source block
- Source blocks that no target cell samples still place at their rotated position
- Right-angle rotations keep the direct transform
- Markers, canopy and tile data follow their resampled source blocks
- Datapack export bakes off-angle variants with the same resampler
- The unused rotateCopy paths are removed
- Placement goldens match the resampled output
2026-10-31 19:23:25 -04:00
Brian Neumann-Fopiano 2462330787 Transition water caps
- Saved and blended columns find solid layers that cap water at the water head
- Surface search passes over a water cap to the ground below it
- A capped column keeps its fluid height at the top of the cap
- A painted cap counts only where the blended column keeps the same blocks
- Saved terrain sources report their water surface
- Displacement fluid keys come from the first fluid at or below the fluid height
- Empty fluid keys never win the fluid blend
2026-10-31 19:23:25 -04:00
Brian Neumann-Fopiano c2eca3e6bd Hydrology climate zones
- Hydrology climate splits the land into wet and dry zones with a noise style
- Dry zones keep only the dryRainfall share of rainfall and pond density
- Zone edges ease across the transition band
- Policy climateZones exempts an area from the dry zones
- Policy fluid also fills streams and rivers that flow through the area
- Bank steepness reads the steepest natural ground between the bank and the water
- Bank edges roughen with smooth noise
- Natural ground heights reach the rasterizer at full precision
- Settings reject climate values outside 0..1
- Hydrology probes read the full precision natural heights
2026-10-31 19:23:25 -04:00
Brian Neumann-Fopiano 304e66b74b Version 4.3.7
- Iris version is 4.3.7 in gradle.properties
- Root build defaults to version 4.3.7
- Fabric, Forge and NeoForge builds default to version 4.3.7
2026-10-31 19:13:08 -04:00
Brian Neumann-Fopiano f1c82e8cec Saved world on create
- /iris create saves a new world before spawn preparation
- A crash before the first autosave keeps the world's seed
2026-10-31 13:22:37 -04:00
Brian Neumann-Fopiano 9339c0869e Saved world on create
- /iris create saves a new world before spawn preparation
- A crash before the first autosave keeps the world's seed
2026-10-31 12:39:29 -04:00
Brian Neumann-Fopiano bb32ea9d25 Datapack export
- /iris datapack export compiles a pack dimension into a 26.3 worldgen datapack
- Bukkit and mod loaders share the export arguments
- Pack compiler stages lower noise, terrain, caves, biomes, decoration, objects and structures to 26.3 resources
- Every approximation reports an export limit diagnostic
- Decorators and objects follow Iris placement rules for water, slope, height and support
- Procedural objects export their pre-built variants as templates
- Jigsaw exports share the template encoder and publisher with the worldgen export
- Both platforms expose vanilla data from the server classpath
- GoldenHashEngine and the export probes share one chunk spiral scan
- Headless 26.3 probes measure export cost and likeness against Iris
2026-10-31 03:41:40 -04:00
Brian Neumann-Fopiano 7ff4292013 Datapack export fidelity fixes
- Aquatic decorators place on the sea floor in water only
- Decorator waterlogging follows the placement site
- Templates never bake waterlogged blocks
- Object blocks outside the nominal box stay in the template
- Procedural objects export their pre-built variants as content-keyed templates
- Surface objects anchor on the ocean floor heightmap
- Surface objects reject leaf, log, or fluid ground under the origin
- Surface support checks test base corners with a slope-scaled drop
- Support ground search covers the full 16 block window
- MIN_HEIGHT, MAX_HEIGHT, and stilt modes sample terrain across every allowed rotation
- Procedural tree roots extend down to the ground
- Underwater objects need water and stay below the surface
- On-water objects anchor at the fluid surface
- Unsupported coral, sea pickles, and wall fans are left out of templates
- Object placements honor slopeCondition
- Two-block plants place both halves
- Shore decorators need solid ground below
- Decorator coverage matches the Iris style density
- Patchy decorator styles export as noise threshold patches
- Palette end weights round to the nearest count
- Ores in deepslate place their deepslate variants
- Pack description tells players to keep the Default pack selected
- Aquifer floods open sea cells near the fluid height
2026-10-31 03:36:32 -04:00
Michael 4a499c18c4 Let a fluid set the block that forms where it meets another fluid
World generation places fluids without updates, so where lava meets water or the sea the two sit
side by side instead of reacting. A fluid profile can now name a seam: another fluid profile that
fills its edge where it touches a different fluid or the sea (a dry column whose ground is below
sea level). A profile used as a seam may hold solid blocks, e.g. lava with a seam of obsidian,
magma and basalt gets a cooled crust where it meets water. Every touching cell (diagonals included)
seals, plus about 60% of the cells next to those, picked by a world-position hash, so the seam is a
ragged band rather than a straight line. Without a seam nothing changes.
2026-10-31 02:12:22 -05:00
Michael 09d6e4b720 Let hydrology policies set the fluid of rivers
A hydrology policy's fluid filled ponds and lakes, but channels always used their tier's fluid, so a
volcanic region could have lava lakes but only water rivers. Each reach now takes the fluid its
policy (biome, then region, then dimension) names where the reach starts, its upstream end, falling
back to the tier's fluid when no policy names one, and keeps it to its downstream end. Deciding per
reach rather than per column keeps a river one fluid from source to confluence, so two fluids only
meet where streams join or flow into a lake, not along every border a river crosses. River plans
and the plan cache are unchanged.
2026-10-31 02:12:13 -05:00
Michael 6ed70b3856 Keep the land biome under inland water above sea level
The surface biome is typed from the ground height, so a pond or stream whose floor dips below the
dimension's fluid height became the region's sea biome (ocean colours and ocean spawns in a small
pond on low land). When the hydrology raster marks the column as inland water (pond, channel,
cascade or waterfall; not a mouth or sea inlet) whose surface is above sea level, and the base biome
is a land biome, keep that land biome.
2026-10-31 02:12:01 -05:00
Michael 6d6bd4f054 Keep a pack's side faces on hanging vines
DecoratorCore.fixFacesForHunk cleared every face of a placed vine and re-attached it to solid
neighbours, falling back to UP. A ceiling decorator that stacks vines downward therefore made a flat
sheet under every block instead of a hanging curtain, whatever faces the pack set. When the pack
already gives a vine a side face, keep it (the vine above holds it, as in vanilla) and add UP only
where a solid ceiling is directly above. Vines without authored side faces are fixed as before.
2026-10-31 02:12:01 -05:00
Michael bce7efaa72 Let biome effects choose their sound category
IrisEffect played its sound with Player.playSound(location, sound, volume, pitch), which Paper
sends on SoundCategory.MASTER, so packs that use effects for biome music or ambience could only be
turned down with the master slider. A new soundCategory field (default MASTER, so existing packs
sound the same) picks the category: music can follow the music slider, moods the ambient slider.
2026-10-31 02:12:01 -05:00
Brian Neumann-Fopiano 1ed1044474 Datapack export
- /iris datapack export compiles one pack dimension into a worldgen datapack for Minecraft 26.3 and later
- Bukkit and mod loaders take the same version, mode, namespace, output, format, objects and replace arguments
- The default overworld mode replaces the Overworld of a new world with the default world type
- Preset and dimension modes write a selectable world preset or a separate dimension
- The export runs in the background and publishes the zip or folder atomically
- Pack compiler stages turn noise, terrain, caves, subterrain, biomes, surface, decoration, objects and structures into a version-neutral IR
- Capability lowering fits every field to 26.3 density function ranges
- Disjoint min and max nodes fold to the input that always wins
- The 26.3 writer emits density functions, noise settings, biomes, features, structures, presets and dimensions
- Every export carries the Iris logo as its pack.png
- Unused objects, templates and features are pruned from the output
- The pruner keeps pack.png without reading references from its bytes
- Imported pack datapacks are bundled into the export
- Every approximation reports an export limit diagnostic
- Generation cost is counted against a node budget and reported as a warning
- Cave biomes over the wall palette limit use the closest kept palette
- Jigsaw exports share the template encoder, block states, destinations and publisher with the worldgen export
- DataVersion carries the pack format minor and world data version
- Both platforms expose vanilla data from the server classpath
- GoldenHashEngine and the export probes share one chunk spiral scan
- Headless 26.3 probes measure export cost and compare column and chunk likeness against Iris
- Real-codec tests decode the exported resources with the 26.3 registries
- Paper registry tests run in isolated registry scopes
- Command help and messages cover the export in every language file
2026-10-30 22:59:04 -04:00
Brian Neumann-Fopiano b00e28e42e Modded terrain write tests
- Tests cover fresh section writes in the modded chunk generator
2026-10-30 22:50:49 -04:00
Brian Neumann-Fopiano b61d2f305b Modded structure state key
- Modded biome policy supplies the structure state key from the generator
- History worlds key structure state by the active epoch
- Studio worlds get a fresh transient key
- Tests cover the key binding and the structure state codec
2026-10-30 22:50:49 -04:00
Brian Neumann-Fopiano 618bb28591 Fixed lattice eviction race
- Lattice eviction sorts a snapshot of tile access stamps
- Concurrent tile use during eviction no longer breaks the sort
- Test covers eviction under concurrent fills
2026-10-30 22:47:20 -04:00
Brian Neumann-Fopiano 6ceda7c53b Pregen optimization pass
- Hydrology height lattice stores samples in tiles with least-recently-used eviction
- Evicted lattice cells are no longer sampled twice
- Pond rim columns go through the lattice column cache
- Window planning reads its coarse nodes from the fine lattice
- Prefetch stays inside the pregeneration area while a pregeneration runs
- Sea inlet splat compares squared distances
- Bounds sampling answers a column from region constants when every reachable biome shares the bounds
- Base terrain heights are shared through a per-column memo
- Chunk water rasters use per-chunk palettes and a larger cache
- Raster channel lookups use a 4-block segment grid
- Chunks with no water in reach return the empty raster directly
- Riffle spreads stop at cells that cannot reach the chunk
- Cave pool terrain is built only for chunks with a pool site
- Concurrent raster builds for one chunk share a single build
- Section buffers resolve air once and support bulk column reads
- Cave decoration, perfection and transition capture read bounded column windows
- Generation history claims and saved biome writes elect one writer per batch
2026-10-30 22:34:31 -04:00
Brian Neumann-Fopiano b475d20aec Merge branch 'perf-gen' into perf-review 2026-10-30 21:42:42 -04:00
Brian Neumann-Fopiano e9c18cdc08 Merge branch 'perf-raster' into perf-review 2026-10-30 21:29:13 -04:00
Brian Neumann-Fopiano b10966af47 Merge branch 'perf-dem' into perf-review 2026-10-30 21:29:13 -04:00
Brian Neumann-Fopiano 8e625d4547 Merge branch 'perf-plan' into perf-review 2026-10-30 21:29:13 -04:00
Brian Neumann-Fopiano 0d148c69b5 Shared concurrent raster builds
- Made concurrent demands for one chunk wait for a single water raster build
- Added a test that a second demand reuses the build already running
2026-10-30 21:02:36 -04:00
Brian Neumann-Fopiano 806e847e90 Bounded column rereads
- Natural cave decoration reads columns in sixteen-row windows and drops the window after each decorated zone
- Perfection reads cells directly after a spike is normalized instead of rereading the column below it
2026-10-30 21:02:23 -04:00
Brian Neumann-Fopiano ed83c6fdeb Unqueued history claim waits
- Semantic claims and saved biome writes elect one writer per batch instead of queueing every caller on the monitor
- Waiting callers park until their batch settles and wake the next queued caller when the writer leaves
- Admission tests count parked followers as queued behind the history writer
2026-10-30 20:55:54 -04:00
Brian Neumann-Fopiano b2990104d2 Sped up hydrology sampling
- Bounds sampling answers a column from its region, land or sea type, or noise-picked biome when every biome it can still become shares the group bounds
- Base terrain heights are kept in a shared per-column memo for hydrology batches, terrain3D anchors and scalar sampling
- Hydrology height batches skip columns whose base height is already known
- The per-batch base height map and its thread local are removed
- The four inferred biome streams share one context region stream
- BakedStream exposes a baked-plane lookup without falling back to the source
- Tests cover region constants, the base height memo and bit-exact heights with and without region constants
2026-10-30 20:54:55 -04:00
Brian Neumann-Fopiano def73cff96 Clipped pregen prefetch
- Limited chunk prefetch rings to the windows a bounded pregeneration still needs
- Forwarded pregeneration region bounds from the async, medieval and modded methods
- Restored unclipped prefetch when the pregeneration closes
- Added a runtime test for clipped and restored prefetch
2026-10-30 20:54:55 -04:00
Brian Neumann-Fopiano ca33273d17 Sped up inlet splat
- Compared squared distances in SeaInletPlanner.splat and kept hypot for cells inside the rounding band
2026-10-30 20:54:54 -04:00
Brian Neumann-Fopiano 8773d4b008 Tiled hydrology lattice
- Stored lattice samples in compact 32x32 tiles with least-recently-used tile eviction
- Cached sampled pond rim columns in a block-resolution tile cache
- Read window coarse nodes from the fine lattice at stride 2
- Removed the window lattice and FineLatticeSource
- Sized the fine lattice for an eleven-window span and the region lattice for a seven-region span
- Updated lattice, planner and probe harness callers for the single fine lattice
2026-10-30 20:54:41 -04:00
Brian Neumann-Fopiano 1a914a404a Sped up column scans
- Section buffers resolve air once per buffer instead of on every empty read
- Section buffer writes remember the last palette entry they resolved
- Added bulk column reads to section buffers and the update-listening hunk
- Natural cave decoration, perfection and transition geometry capture read whole columns at once
- Iris execution contexts bind through a thread slot table instead of a ThreadLocal
- Semantic capture tracks resolved cave cells in a fixed bitmap instead of a BitSet
- Added tests for bulk column reads and for contexts when threads outnumber the slot table
2026-10-30 20:25:50 -04:00
Brian Neumann-Fopiano 1899de7f3d Deferred cave pool terrain
- Opened the cave pool terrain view only for chunks that draw a pool site
- Added a test that chunks without a pool site never open their caves
2026-10-30 20:09:02 -04:00
Brian Neumann-Fopiano 3c39092cc7 Pruned riffle distance spreads
- Stopped riffle distance spreads at cells that cannot reach the chunk
2026-10-30 20:09:02 -04:00
Brian Neumann-Fopiano 0c7adc5da4 Indexed raster channel lookups
- Indexed reach segments into a channel grid around each rasterized chunk
- Skipped sea inlet column checks outside each inlet's bounds
- Returned the empty raster for chunks with no water features in reach
- Added a test that covered channel lookups match the full segment scan
2026-10-30 20:09:02 -04:00
Brian Neumann-Fopiano a879985875 Cached more water rasters
- Stored raster tiers fluids and feature ids as per-chunk palettes
- Derived cave ceilings from terrain heights and water heads
- Raised the water raster cache from 1024 to 8192 chunks
2026-10-30 20:09:02 -04:00
SwiftSwamp f999728d61 Windows path fixes in tests
- Registry verification tests build expected paths with the platform separator
- Probe tests use platform absolute paths
- God, Windows... PLEASE.
2026-10-30 10:04:13 -06:00
Brian Neumann-Fopiano c700138b66 Native provider loading
- Native provider classes load from the provider jars before the plugin class loader
- Another plugin bundling VolmLib natives no longer supplies Iris native capabilities on Spigot
- Tests cover provider jar classes taking precedence over the plugin loader
2026-10-29 01:49:27 -04:00
Brian Neumann-Fopiano 21ab5baf27 Fixed Spigot agent attach
- Iris restores the JVM SIGQUIT handler when the server console replaced it
- The Java agent attaches on Spigot servers with a terminal console
- Tests cover restoring the handler after a console resets it
2026-10-29 01:09:16 -04:00
Brian Neumann-Fopiano 58ab3fcbbe Smaller jar libraries
- LWJGL downloads through the server library loaders
- The VolmLib stamp records a commit only for its own Git repository
2026-10-28 22:58:34 -04:00
Brian Neumann-Fopiano b6e9f8a14d Fixed VolmLib commit stamp
- The VolmLib stamp records a commit only when the checkout is its own Git repository
- A VolmLib copy inside another repository stamps an unknown commit
2026-10-28 22:58:20 -04:00
Brian Neumann-Fopiano 0d76d81dab Downloaded LWJGL libraries
- LWJGL is no longer shaded into the Bukkit jar
- plugin.yml lists the LWJGL jars and Linux natives as Spigot libraries
- The Paper loader resolves the same plugin.yml list through the Maven Central mirror
- The packed payload no longer reserves the LWJGL natives prefix
- Tests cover reading the library list from the plugin jar
2026-10-28 21:55:09 -04:00
Brian Neumann-Fopiano aec8f5be8e Updated Bukkit purity allowlist
- Jigsaw connector tools are included in the Bukkit allowlist
- Jigsaw floor painting is included in the Bukkit allowlist
- MantleWriter no longer needs a Bukkit allowance
- The removed IrisPack class no longer has an allowance
2026-10-28 21:31:46 -04:00
Brian Neumann-Fopiano 0f9c045524 Merge remote-tracking branch 'origin/master' 2026-10-28 21:30:18 -04:00
Brian Fopiano 1d4f95829b Fixed entity spawn deadlock
- Rise-enabled spawning prepares its starting position inline on the primary thread
- Asynchronous callers keep scheduled preparation
2026-10-28 21:27:01 -04:00
Brian Neumann-Fopiano ce4771b609 Version 4.3.6
- Iris version is 4.3.6 in gradle.properties
- Root build defaults to version 4.3.6
- Fabric, Forge and NeoForge builds default to version 4.3.6
2026-10-28 18:41:17 -04:00
Brian Neumann-Fopiano 7d73c4d150 Jigsaw junctions and studio tools
- Rotatable jigsaw candidates try their rotations in random order
- Candidate connectors are tried by priority within each rotation
- Planar candidates must agree with every occupied neighbor socket
- Planar assembly falls back to source-only matching before it fails
- Connectors whose branch placed nothing stay open
- Spatial default kit covers all 24 Y-rotation topologies
- Planar start pool includes Blank at weight 1
- Vanilla spatial projects omit Iris themes and placement caps
- Vanilla spatial projects use max depth 4
- 1.21.1 export derives the vertical distance from the structure
- Workcell floors map the active variant's connectors
- Floor froglights mark up, down and up-down connectors
- Connector Tool places, moves, re-orients and removes spatial connectors
- Connector Tool re-seats planar face-center sockets
- Main menu pages workcells five at a time
- Spatial variants can be deleted while another variant remains
- Tool sticks act on the variant they were made for
- Destructive tool confirmation needs two separate clicks
- Pistons cannot extend into protected cells
- Autosave capture failures back off and notify the owner
- Autosave plays the save bell
- Hidden-connector air final states are stored as air
- Reset Connector Blocks clears unsaved markers
- Folia logout releases reset and resize reservations
- Spatial workcell rename relabels its variant
- Workcell teleports land inside the focused workcell
- Replacement layouts keep rendering and hydration working
- Container preview probes stay out of chat
- Non-owners can run commands that are not recognized as mutating
- Spatial resize or rotation past the workcell volume limit is refused
- Tests cover default kit assembly, connector placement, floor glyphs and menu paging
2026-10-28 17:14:14 -04:00
Brian Neumann-Fopiano b3579e623a Added Studio hotload command
- /iris studio hotload and its refresh alias reload the open Studio pack on Bukkit
- Bukkit hotload refuses while Studio entry, pause or close is pending
- Modded servers register the same hotload and refresh commands
- Modded hotload reports busy while that Studio is already hotloading
- Hotload messages and help entries are localized in every language file
- Bukkit artifact verification reads the jar task output
- Multiplexor takes the Bukkit artifact from the packedJar task
- BukkitTestServer shares one-time registry setup across tests
- Tests and a gameplay scenario cover both hotload commands
2026-10-28 13:32:33 -04:00
Brian Neumann-Fopiano 300ecbfc8b Fixed container memory pressure
- Container pressure excludes committed heap the JVM is not using
- Reclaim, pregen gating and status text use the adjusted figure
- Tests cover the committed heap subtraction
2026-10-28 13:15:35 -04:00
Michael 0c760d9256 Fix main thread deadlock when spawning rise-out-of-ground entities
IrisEntity.spawn waited on J.sfut(...).get() to move the spawn point below
ground. J.sfut schedules the task for the next main thread tick, so when spawn
already runs on the main thread (ambient spawning in WorldEntitySpawner) the
future can never complete and the server stops ticking. Run the check inline
when already on the main thread.
2026-10-28 03:56:54 -05:00
Brian Neumann-Fopiano 3dc958edcf Stabilized shutdown and Studio
- Shutdown protection initializes before enable and drains inline when retention fails
- Cleanup preserves class loader retention and closes native providers in order
- Error reports retain context and handle empty stack traces
- Studio maps retain partial coverage and suspend hidden views
- Hydrology previews refresh when plans and rasters complete
- Terrain scratch hashing spreads lattice samples across cache slots
- Plugin and probe artifacts include LWJGL libraries and native resources
- Regression tests cover shutdown, error reporting, map progress, and terrain scratch
2026-10-26 23:29:21 -04:00
SwiftSwamp f64a7c6753 Fixed wandering trader spawning
- World injection attaches vanilla event spawners for NORMAL dimension environments
- Covers worlds loaded at server start, Studio worlds and Folia worlds
- Binding test covers overworld and nether environments
2026-10-26 18:05:45 -06:00
Brian Neumann-Fopiano 7756598057 Integrated hydrology updates
- Riverbed generation includes upstream shutdown fixes
2026-10-26 18:02:26 -04:00
Brian Neumann-Fopiano 75837d757b Improved riverbed generation
- Pond levels follow intersecting lower channels
- Pond sampling covers requested flood margins
- Water steps align with sea level
- River crests grade into surrounding beds
- Riverbeds include varied cross sections and finer noise
- Submerged soils use stable block types
- Hydrology probes inspect wet bed geometry
2026-10-26 18:01:26 -04:00
SwiftSwamp 2690e0878b Fixed shutdown teardown and shutdown staging wait
- Server stop defers teardown only while the plugin class loader close is held
- Shutdown with no Iris world loaded tears down during plugin disable
- Pre-unload hook drains generators inline when the class loader close cannot be held
- INMSBinding reports whether the class loader close is held
- Shutdown tests cover the held and unheld pre-unload paths
- Shutdown waits for an in-progress world replacement to finish staging
- Replacements started after shutdown begins are refused
- Admission tests cover the shutdown wait and the refusal
2026-10-26 09:26:30 -06:00
Brian Neumann-Fopiano 494cdb1a5c Refine hydrology and Studio
- Add dimension-wide hydrology density controls.
- Validate pond containment and shorelines at block resolution.
- Prioritize requested water plans and deduplicate prefetch work.
- Keep completed water previews visible while details load.
- Add pregeneration map navigation and Studio theme controls.
- Reject pack mutations during generation-registry capture.
2026-10-26 00:08:25 -04:00
Brian Neumann-Fopiano 1d182769d8 Merge object placement
- Integrate PR #1255 placement lifecycle modules.
- Preserve dry-anchor rejection for water-surface objects.
- Verify the merged placement guards and output reference.
2026-10-25 23:46:48 -04:00
Brian Neumann-Fopiano 584e8758a7 Update Studio previews
- Merge the eight additional commits from PR #1254.
- Preserve closure guards while refreshing object and hidden 3D views.
- Stop hidden crossfade timers and verify frame retention.
2026-10-25 17:25:18 -04:00
piexel 3766a40256 Well.. not for now at least let me just remove that- 2026-10-25 22:21:33 +01:00
piexel b7499d23f2 Sample terrain height for ERODE_STILT 2026-10-25 22:21:33 +01:00
piexel 46d458e6e4 Rewrite object placement as resolved lifecycle modules 2026-10-25 22:21:33 +01:00
Brian Neumann-Fopiano 9f49d29e2b Integrate Iris Studio
- Merge the unified Studio interface and command entry points.
- Adapt water views and provisional sampling to basin hydrology.
- Restore diagnostic estimates and the biome water overlay.
- Fix render cancellation, preview closure, and platform position callbacks.
- Fall back to software rendering when native bindings are unavailable.
- Cover renderer, lifecycle, and scheduler regressions.
2026-10-25 16:56:49 -04:00
piexel e3bc27d50c Keep hidden 3D views from covering the open view
A 3D view asked for a frame while its card was hidden, for example when
the sidebar resized, showed its GPU window again. AWT maps a shown
canvas even under a hidden parent, so the window covered the open view
in black. Frames only go into the window while the view is on screen.

Model used: Opus 5.5
2026-10-25 21:49:03 +01:00
piexel 6900f270ee Shorten the palette crossfade to 70 ms
The 150 ms fade made switching feel sluggish.

Model used: Opus 5.5
2026-10-25 21:42:44 +01:00
Brian Neumann-Fopiano db0f98d103 Basin hydrology
- The route-and-reject hydrology system and its probes are removed
- Hydrology is configured under dimension hydrology and per biome, region and dimension hydrologyPolicy
- riverPolicy and the old hydrology config types are gone
- Grid kernels cover priority flood, D8 routing, flow accumulation, basin extraction, breaching and stream burning
- A basin spills at its pour point and an interior bump can never be the spill
- Region plans cover 4096-block regions on a 64-block grid for major rivers and lakes
- Window plans cover 512-block windows on an 8-block grid for reaches and ponds
- Plans are cached in memory, persisted per world under iris/hydrology and keyed by pack, seed, world height and settings
- Only the main runtime of an engine persists plans and stores swap on hotload and default runtime change
- Demand rasters outrank prefetch and stopping pregen withdraws its queued prefetch
- Ponds come from natural basins, seeded cups and chained cups with strictly falling levels
- A pond level never exceeds its rim plus maxFill or the end grade of any inflow
- Pond outlet loops are opened at their lowest pond
- Reaches split at junctions, pond outlets and 256-block grid lines
- Reaches meander, fit the valley, grade to a running minimum and smooth with Chaikin passes
- Drops of two blocks or more get a lip and one-block corner steps become dry rim ledges
- Cascades and waterfalls write falling fluid from the mantle at level eight
- Inflows into region lakes end at the lake level
- River mouths and water beside the sea sit at the sea surface
- The per-chunk raster gives terrain height, water head, role, tier, fluid, cave ceiling and shore distance
- WaterRole codes are stable and exposed to packs through the WATER_ROLE engine stream
- WATER_HEAD replaces the old river engine streams and an unknown stream name fails the pack load
- Banks take SMOOTH, LINEAR, CONCAVE, TERRACED or CLIFF profiles
- Containment berms grow as tall as the water needs
- Columns within two blocks of water stay solid and keep no Terrain3D overhang
- Seam dams hold water where new chunks meet chunks generated earlier
- The transition blend skips hydrology-owned columns
- Caves stay at least two blocks below river and pond beds
- The painter is the only writer of still water
- Objects cannot open water, falls or bank ground and solid objects may stand in water
- On-water objects need fluid at their anchor column
- Floating child islands stay out of channels
- Sea inlets run inland from cliff coasts at sea level and end in a chamber pool
- Inlet passages are sealed against carvers, subterrain features and the post pass
- Cave pools settle into carved lows, keep one fluid and stay out of inlet space
- Pool and inlet cells use their own cave actions in mantle data
- Water vegetation lists sit on tiers, ponds and hydrologyPolicy with SEA_FLOOR, SEA_SURFACE and SHORE_LINE parts
- Pack validation compiles hydrology settings and rejects empty or water-holding palettes
- Chunk generation fails closed when its 3x3 water rasters are not planned
- /iris find covers stream, river, major river, cascade, waterfall, mouth, pond, lake, dam, sea inlet and cave pool
- Generation history records the new feature types and drops old hydrology entries
- The studio map draws water from rasters up close and from plans when zoomed out
- Pregen prepares the current region and one region ahead
- hydrologyProbe, riverTransectProbe, hydrologyBlockProbe, seaInletProbe and cavePoolProbe report containment, rises, seams, tick conversion and missing surface
- Test forks run with a 2 GB heap, a 60-minute timeout and the Mockito agent loaded explicitly
- Generation with hydrology off is unchanged
2026-10-25 15:28:26 -04:00
piexel 547c52540a Crossfade between palettes instead of flashing empty
Switching source kept nothing on screen until the new one drew. The old
frame now stays until the first new frame lands, then fades out over it
in 150 ms.

Model used: Claude Opus 5.5
2026-10-25 20:06:30 +01:00
piexel 806a33976a Stop palette switches flashing a magnified texture
Switching palettes dropped the last frame's timing, so the first frame
fell back to one sample per ~29 pixels and drew a texture pixel in each
square. The first frame is now sized from the previous source's speed,
and coarse frames use block colours instead of texture pixels.

Model used: Claude Opus 5.5
2026-10-25 19:58:08 +01:00
piexel 065c6fed1d Draw small decoration tops in palette previews
Icons now show each box's top above its front, half as deep and lit as
Minecraft lights each side, so sea pickles, candles and eggs show caps.

Model used: Claude Opus 5.5
2026-10-25 19:39:01 +01:00
piexel 360f38a819 Show a newly picked object without moving the cursor
A frame asked for while the last one was being taken, like the one that
ends a load, was drawn and swapped before the earlier frame's swap, so
the window kept the old object until something else redrew it.

Model used: Claude Opus 5.5
2026-10-25 19:39:01 +01:00
piexel 5204d94ebe Draw small decorations from the front in palette previews
- Sea pickles, candles, lanterns, turtle eggs and potted plants show their shape instead of their whole unfolded texture
- Flat decorations like pressure plates, rails and lily pads keep their top view

Model used: Claude Opus 5.5
2026-10-25 19:22:02 +01:00
piexel 48bfa7d15b Call the cave biome view Cave land again
- The map's cave view shows the 2D cave biome stream, not the biomes caves get per block, so it goes back to v4's name

Model used: Claude Opus 5.5
2026-10-25 19:22:02 +01:00
piexel 2acfac36fc Show 3D frames only once panels over them are painted
- A frame drawn into a 3D view's window waits until Swing has painted what lies behind the floating panels, so the ground behind the height slider no longer trails the view while it moves

Model used: Claude Opus 5.5
2026-10-25 18:56:25 +01:00
piexel 54213d4b62 Keep coarser ground in 3D views until new backdrop arrives
- Backdrop not sampled yet borrows the nearest sampled tile up to four levels coarser, so zooming in leaves no gap
2026-10-25 16:43:27 +01:00
piexel ff6668a48b Fix decorator palettes and stale theme on swapped panels
- Decorator palettes no longer look up a layer they don't have
- Sidebar and inspector panels pick up a theme switch made while they were off screen
2026-10-25 16:00:17 +01:00
piexel 29cca99947 Port the v3 map as iris std map
- iris std map opens the v3 map window; noise, palettes, objects, procedural and image maps are views in it
- Rivers view draws v4 hydrology, with an empty state when the pack has rivers off
- 3D views fall back to software when LWJGL isn't on the classpath; modded jars use the game's LWJGL
- FlatLaf and LWJGL join core; v4's separate studio windows are removed
2026-10-25 16:00:17 +01:00
Brian Neumann-Fopiano 2d211cf106 B+ 2026-10-23 10:41:36 -04:00
Brian Neumann-Fopiano 3240d57a3b Merged Iris turbo
- Columnar terrain bake, compiled generator and cave density programs, batched lattice noise

- Carve cell kernel, object bake, section buffer output, placement reach bound

- Lock-free history scope and subterrain caches, caller-run mantle components, hydrology halo and trial batching

- Cave apply, deposit, perfection and platform glue trims; probe parity oracle
2026-10-22 19:15:08 -04:00
Brian Neumann-Fopiano 908dbcf4cc Merged hydrology cold start trials
- Idle-aware fallback trial batches shorten the cold plan
2026-10-22 17:26:19 -04:00
Brian Neumann-Fopiano 4703d473cc Idle-aware fallback trial batches
- Fallback trials budget a measured 128 MB each instead of 1 GB

- Trial batches grow with idle hydrology workers up to the trial limit
2026-10-22 17:26:18 -04:00
Brian Neumann-Fopiano c3b3f1d8aa Waited for occupied dispatcher in test
- Concurrency test starts generation only after every burst worker is blocked
2026-10-22 12:11:48 -04:00
Brian Neumann-Fopiano 60eec4e2ee Updated volume index test reflection
- Volume index tests read entries through the concurrent volume cache
2026-10-22 11:59:13 -04:00
Brian Neumann-Fopiano c6d7a814e0 Merged hydrology cold start
- Shared bounds-biome memo and erosion raster without per-visit lookups
2026-10-22 11:47:20 -04:00
Brian Neumann-Fopiano 45e00f4794 Merged small stages
- Single-pass deposit footprints with balanced preparation, cached perfection and placement state checks, run-scanned history receipts
2026-10-22 11:36:07 -04:00
Brian Neumann-Fopiano 9d4c55d11a Merged carve field reads
- Batched baked carve field reads, per-thread bake chunk memory, terminal carving roots return early
2026-10-22 11:29:26 -04:00
Brian Neumann-Fopiano c62a31e16b Merged platform diet
- Per-chunk biome stage resolver, subterrain candidate gate, section-walk heightmaps, reused history compressors

# Conflicts:
#	core/src/main/java/art/arcane/iris/generation/runtime/Engine.java
2026-10-22 11:29:26 -04:00
Brian Neumann-Fopiano 18ba6e32ac Probe history digest
- Adds an opt-in digest of semantic and saved biome records per chunk
2026-10-22 11:05:58 -04:00
Brian Neumann-Fopiano f7f9f5f651 History capture fast paths
- Natural terrain capture scans columns as block state runs
- Biome samples reuse the palette index of an identical key
- Cave biome capture samples the subterrain planner directly when live
- Repeated object markers skip decoding
- Saved biome encoding hashes each distinct column once
2026-10-22 11:05:58 -04:00
Brian Neumann-Fopiano d9c5d00be3 Perfection and ore lookups
- Perfection memoizes solid and spike flags per block state identity
- Terrain painting resolves the ore chance engine once per chunk
2026-10-22 11:05:58 -04:00
Brian Neumann-Fopiano 97c67b794b Subterrain lookup check order
- Subterrain cell lookup resolves the dimension only after the complex is present
2026-10-22 10:55:21 -04:00
Brian Neumann-Fopiano c6e9f5a1ee Merged cave apply
- Per-chunk subterrain sampler, memoized dimension feature gate, bitmask walls, cached floor and ceiling layers
2026-10-22 10:11:34 -04:00
Brian Neumann-Fopiano 1fe26e6288 Shared bounds biomes and paged erosion raster
- Bounds starcasts share whole-column base biome samples across threads through a heap-sized lock-free memo
- Erosion raster geometry tracks station owners in paged local arrays and builds its index map in first-visit order
2026-10-22 10:02:53 -04:00
Brian Neumann-Fopiano 0b4d860ff4 Native noise packaging
- Default artifacts carry the CPU native noise libraries inside the packed payload

- Java 21 modded jars exclude Java 25 native classes
2026-10-22 08:58:32 -04:00
Brian Neumann-Fopiano 9d9acc7a3a Restore semantic cave sampling
- Semantic capture samples subterrain cave biomes per voxel as before
2026-10-22 07:32:35 -04:00
Brian Neumann-Fopiano 04f2798c06 Lock-free volume reads
- Structure volume caches read through concurrent maps and publish only current builds
- Natural terrain receipts reuse a per-thread deflater with the platform gzip framing
- Tests pin receipt and saved biome bytes across reused compressors
2026-10-22 07:29:53 -04:00
Brian Neumann-Fopiano 9cd470c7c8 Deposit clump fast paths
- Clump randoms use a plain-field LCG with the RNG sequence and a step jump
- Single-block palettes build footprints from row masks and jump the pick draws
- Ellipsoid nodes, row offsets and node sines reuse thread scratch and size tables
- Terrain-scoped footprint plans that cannot reach the chunk surface are skipped
- Above-terrain plans are skipped when no solid host sits above the surface
- Preparation runs as at most four balanced slices with one join per chunk
- Placement caches target, bedrock and replaceable checks per block state
2026-10-22 07:28:34 -04:00
Brian Neumann-Fopiano 8fbc006781 Hide subterrain gate accessors
- The memoized subterrain dimension gate no longer gets generated getter and setter methods
2026-10-22 07:22:46 -04:00
Brian Neumann-Fopiano e38f956d66 Terminal carving roots
- Roots without selectable children resolve to themselves before the per-column child cache
- Selection plans build through one shared helper for root checks and child selection
2026-10-22 07:19:57 -04:00
Brian Neumann-Fopiano 67fd9046ba Baked carve field reads
- ChunkBakeCache.fillColumns batches the missing requested columns of one chunk plane and publishes them
- BakedDoubleStream and BakedStream expose fillColumns with the per-column fallback when memoization is not allowed
- Carve profile field reads heights, regions, surface and cave biomes from the nine overlapped chunk planes
- Fluid presence samples the fluid plane only for columns below the fluid height
- Carving reuses one dimension carving resolver state per thread scratch
- Bake recent-entry memo holds a 16-slot per-thread chunk table instead of one entry
2026-10-22 07:14:09 -04:00
Brian Neumann-Fopiano 0bdb022f56 Chunk-scoped cave lookups
- Subterrain cells for carve and decoration resolve through a per-chunk sampler with a column height hull instead of per-block engine dispatch
- IrisEngine subterrain lookups read the thread frame and runtime once and memoize the dimension gate, removing the per-call disabled-component list scan
- Unrouted workers resolve cave biomes through the captured carving snapshot and column cache with subterrain biomes checked first
- Captured cave biome lookups bypass the per-voxel hash cache
- Internal carve walls come from word-level column masks instead of hashed neighbor puts, painted after cheap solidity and surface checks
- Floor and ceiling layers are memoized per column when the biome layers do not depend on the zone height
- Zone scanning walks carved runs, the decoration scan memoizes block solidity and reuses the previous block, and waterlogging normalization skips snapshots without hydrology
- Boundary walls read own cells straight from the snapshot; the unused snapshot face builder and face accessors are removed
2026-10-22 06:42:35 -04:00
Brian Neumann-Fopiano 0fe2363feb Platform glue diet
- Chunk-scoped visible biome resolver without global cache, per-quart RNG or repeated runtime lookups
- Subterrain probe skips per-sample subterrain lookups in chunks without candidates
- Striped structure volume caches
- Saved biome store reuses deflaters and remembers ready region files
- Semantic journal skips repeated storage and journal stat checks
2026-10-22 06:40:12 -04:00
Brian Neumann-Fopiano af90765a92 Restored burst parallelism in test
- Burst parallelism test restores the shared pool so later concurrency tests see the default size
2026-10-22 04:49:45 -04:00
Brian Neumann-Fopiano a25d8ec367 Merged review fixes
- Heap-sized terrain bake, bounded object rotation bakes, generation-counted bake thread locals, unused bake assembly removed
2026-10-22 04:48:46 -04:00
Brian Neumann-Fopiano fea9aa4f19 Narrowed bake sizing constants
- Bake sizing constants other than the floor are package-private
2026-10-22 04:29:08 -04:00
Brian Neumann-Fopiano 5c4bce0c1a Merged wave1 into FIX1 2026-10-22 04:28:00 -04:00
Brian Neumann-Fopiano 23637beb0c Merged parallel waits
- Caller-run mantle components when the window is full, barrier help, generation scope propagated to component tasks
2026-10-22 04:18:16 -04:00
Brian Neumann-Fopiano b712cbf93d Hydrology pool host cap
- Hydrology planner pool minimum never exceeds the host core count (floor 2)
2026-10-22 04:08:14 -04:00
Brian Neumann-Fopiano ae1a84702c Scratch resets and gated counters
- Terrain batch scratch marks reset in finally blocks so a failing kernel cannot grow the scratch
- Generator evaluation counters only count when generation counters are enabled
- Core tests run with generation counters enabled
2026-10-22 04:08:14 -04:00
Brian Neumann-Fopiano 6582d9d14d Heap-sized terrain bake
- Bake capacity derived from the heap (13 KB per entry against 1/32 of maxMemory, 2048 to 32768 entries); detached runtimes use the floor
- Pregeneration profile no longer raises the global noise cache size or the bake; it only raises burst parallelism
- Removed the hydrology bake reservation, noise cache budget, expansion machinery and the tile cache terrain preparation hook
- Bake thread recents compare a generation counter; clear empties retired entries
- Removed unused column bake, bake registry and bake accessors
2026-10-22 04:08:07 -04:00
Brian Neumann-Fopiano bf9e65252c Shared object placement layout
- Object placement bakes split into one per-object layout (palette, tiles, canopy) and per-variant offsets
- Variants beyond the per-object limit are built transiently instead of clearing the variant map
- High-variant golden and no-rebuild tests
2026-10-22 04:00:16 -04:00
Brian Neumann-Fopiano d7cad729e4 Merged warped lattice batching
- Cave lattice corners evaluated through batched point noise per pass
2026-10-22 03:08:40 -04:00
Brian Neumann-Fopiano cb008b6428 Merged wave1 into parallel waits
- Terrain bake and object bake from turbo/wave1
2026-10-22 02:56:35 -04:00
Brian Neumann-Fopiano e91eb258aa Mantle window helping
- A caller whose submission window is full runs the next component itself instead of parking
- Pass barriers run still-queued component tasks in reverse order before waiting
- Queued component tasks reopen the submitting generation's runtime scope on whichever thread runs them
- Helpers only run queued tasks bound to their own runtime or when they hold none
- A finished submission no longer reports a task as dropped once a helper started it
- Burst worker scope test keeps one stage on a worker while the caller helps
2026-10-22 02:56:23 -04:00
Brian Neumann-Fopiano 544707f5d6 Merged object bake
- Baked rotated object variants, packed transactions, non-blocking source plan builds
2026-10-22 02:49:58 -04:00
Brian Neumann-Fopiano aa929290c0 Merged terrain bake
- Per-chunk columnar bake with compiled generator programs replaces the height, biome and region stream caches
2026-10-22 02:24:24 -04:00
Brian Neumann-Fopiano a2e4ec7070 Batched warped lattice noise
- Cell lattice passes gather every missing corner sample of the pass and evaluate base, detail and modules through NoiseProgram.fillPoints3D
- Warp B samples and single-row warp A samples are evaluated as one point batch per pass; longer warp A runs keep fillColumn3D
- Module bands compact their points before the batch call and scatter back in the original accumulation order
- Lattice batch buffers and their NoiseScratch live in a per-thread CaveLatticeBatch chain that nested carves acquire separately
- Lattice test compares pass-wide point batches against scalar plane density bit for bit
2026-10-22 02:20:35 -04:00
Brian Neumann-Fopiano d2106806a5 Merged wave1 into terrain bake
# Conflicts:
#	core/src/main/java/art/arcane/iris/generation/runtime/IrisComplex.java
#	probe/src/main/java/art/arcane/iris/probe/GenerationProbe.java
2026-10-22 02:16:40 -04:00
Brian Neumann-Fopiano ab51822fd4 Single subterrain check per write
- Drop the repeated subterrain protection lookup inside MantleWriter.setData; the same position was already rejected before the chunk lock
2026-10-22 01:32:15 -04:00
Brian Neumann-Fopiano d7a2a52c72 Planner bake reservation
- Hydrology planner height reads reserve bake capacity up to the hydrology cache target from the shared budget
- Planner reservation is released when the complex closes
2026-10-22 01:21:41 -04:00
Brian Neumann-Fopiano 024214d7f0 Merged carve noise batching
- Compiled cave density fields with batched per-pass lattices and shared warp fields
2026-10-22 01:18:30 -04:00
Brian Neumann-Fopiano ad73c33480 Columnar object mutation log
- Log transaction writes in parallel arrays instead of mutation records
- Replay source plans straight from their packed cells without decoding records
- Build source plans from a log slice
- Journal commit originals in a packed-key set instead of a linked map
- Buffer cave object writes in parallel arrays
- Drop the now-unused import in the runner
2026-10-22 01:04:22 -04:00
Brian Neumann-Fopiano e8f8546b8a Merged section output
- Palette-indexed section buffer, run-length terrain painting, padded column tops
2026-10-22 00:49:32 -04:00
Brian Neumann-Fopiano fd47240db9 Marker placement golden
- Record 480 marked placements (exact and loose markers, 4 rotations) recorded on the pre-bake runner
2026-10-22 00:37:37 -04:00
Brian Neumann-Fopiano be2fe12524 Hold object lock per placement
- Keep the object read lock across the bake lookup, block pass, grounding and stilt pass so a placement reads one consistent snapshot
2026-10-22 00:29:39 -04:00
Brian Neumann-Fopiano e376e1f59a Purity allowlist successor
- ChunkDataOutput replaces ChunkDataHunkHolder as the Bukkit-coupled chunk data writer
2026-10-22 00:25:11 -04:00
Brian Neumann-Fopiano b9409fb5ec Smaller warp column cache
- Warp lattice columns keep a quarter of the density column capacity
2026-10-22 00:20:25 -04:00
Brian Neumann-Fopiano d3defa5563 Merged GPU noise packaging
- Exclude GPU noise classes from the default plugin artifact
2026-10-22 00:18:20 -04:00
Brian Neumann-Fopiano 81f2d2332f Planner reads memoize in bake
- Hydrology planner height and natural samples memoize columns in the bake like other reads
- Batched planner base heights publish into the base plane
- Removed the direct-mapped sparse base height memo
- Only bounds lattice biome reads stay out of the bake
2026-10-22 00:12:25 -04:00
Brian Neumann-Fopiano 14da077ce1 Exclude GPU noise classes
- Java 21 runtime jars skip the Java 25 GpuNoise classes like the other native noise classes
2026-10-22 00:05:15 -04:00
Brian Neumann-Fopiano be30285718 Leaner object transactions
- Memoize the last subterrain protection verdict in object destination transactions
- Key buffered cave object blocks by packed positions and check each position once at commit
- Build every free source plan before waiting on plans other threads are building
- Reuse TreeBlockMaterial values per block state
2026-10-22 00:03:34 -04:00
Brian Neumann-Fopiano a25233edbc Compiled scalar group heights
- Layer and generator programs sample single points through NoiseProgram.sample2D
- Scalar interpolator group means use the compiled programs when the seed matches
- Single-point program heights are property-tested against the generator path
2026-10-21 23:57:11 -04:00
Brian Neumann-Fopiano 4d2e52bcc7 Palette section buffer
- Add SectionBuffer: chunk palette of written instances and short[4096] ids per section in y, z, x order
- Column tops are indexed per x-slice and padded so fan-out slices do not share a cache line
- Add ColumnRunHunk and forward column runs through the listening hunk and block update listener
- Terrain painter emits column runs and evaluates ores only inside the column's ore bands
- Bukkit generation writes into SectionBuffer and applies it through ChunkDataOutput
- Remove ChunkDataHunkHolder and the probe's ProductionBlockHunk copy
- Probe production buffers use SectionBuffer
2026-10-21 23:54:58 -04:00
Brian Neumann-Fopiano 943c8d67e5 Baked object placement
- Bake rotated block offsets, palette indexes, tiles and canopy bits per object and spin kernel
- Resolve decay, rotation, waterlog and air facts once per palette entry per placement
- Skip the destination read for waterloggable states that cannot become waterlogged
- Move SpinKernel to its own file
2026-10-21 23:50:55 -04:00
Brian Neumann-Fopiano fa996a2e24 Recent bake entry fast path
- Facade reads reuse the thread's last chunk entry instead of probing the bake map
- Stores and full-chunk fills refresh that entry from the map
- Surface lattice lookups reuse the previous point's cell indices
2026-10-21 23:48:07 -04:00
Brian Neumann-Fopiano 2bfa9c4528 Trimmed bake accessors
- Removed facade and plane accessors nothing reads
2026-10-21 23:38:09 -04:00
Brian Neumann-Fopiano b526b480a7 Object placement golden test
- Record 4000 placements (200 objects x 4 rotations x 5 seeds) as one block-stream hash with RNG draw state
2026-10-21 23:30:46 -04:00
Brian Neumann-Fopiano ab69be59c7 Rarity and capacity checks
- Rarity stream picks are property-tested against the VolmLib rarity selection
- Pregen capacity growth scales the bake by the same factor as engine start
2026-10-21 23:29:29 -04:00
Brian Neumann-Fopiano b510f0dbfe Batched shared cave lattice
- Cell kernel passes fill a per-pass density lattice in field-major batches before classifying rows
- Lattice density columns are shared between profiles with identical density fields
- Warp samples are shared between profiles with the same warp field and batch along lattice columns
- Added lattice read, sample and warp counters
- Added bit-exact lattice column and field sharing tests
2026-10-21 23:28:01 -04:00
Brian Neumann-Fopiano 7408d02bbe Unboxed biome selection
- Rarity selection streams pick from precomputed cumulative tables
- Implode and surface biome fixes take primitive coordinates
- Child selection reuses one derived child seed instead of a new RNG per level
- Base biome selection reads bridge and inferred streams directly
2026-10-21 23:27:01 -04:00
Brian Neumann-Fopiano 1acda886b3 Memoized bake planes
- Planes fill lazily per column with ready bits and batch only missing columns on full-chunk requests
- Natural fills batch only the base heights Terrain3D still needs and reuse the sparse memo
- Bounds lattice and hydrology planner reads stay out of the bake
- Bake capacity is eight times the noise cache, covering the measured working set
- Generator evaluation counters and a bake census print from the probe
- Parity test compares batched chunk base heights and evaluation counts with the scalar path
2026-10-21 23:22:16 -04:00
Brian Neumann-Fopiano 4dec940311 Compiled cave density programs
- Carver base, detail, warp and module fields evaluate through compiled noise programs
- Near-parity tests inject replacement densities as compiled programs
2026-10-21 23:21:45 -04:00
Brian Neumann-Fopiano df11ad2db0 Pack style carve golden
- Added a four-profile golden scenario with pack cave styles sharing warp and density fields
2026-10-21 23:15:40 -04:00
Brian Neumann-Fopiano f283d482a4 Merged threads and hydrology
- Bounded hydrology halo, performance-core pools
2026-10-21 23:14:43 -04:00
Brian Neumann-Fopiano 3f07db2b9e Merged mantle infrastructure
- Sliding mantle submissions and deferred in-flight neighbour waits
2026-10-21 23:14:43 -04:00
Brian Neumann-Fopiano 391d5346ae Merged native noise packaging
- Probe and build wiring for the optional native noise library
2026-10-21 23:06:10 -04:00
Brian Neumann-Fopiano 78de23e461 Merged carve kernel
- Cell-bound cave carve classification with exact mixed-cell evaluation

# Conflicts:
#	probe/src/main/java/art/arcane/iris/probe/GenerationProbe.java
2026-10-21 23:04:20 -04:00
Brian Neumann-Fopiano 6cc3adf76b Merged bench harness
- Probe stage timings, counters, hydrology preplan, router and production buffer options

# Conflicts:
#	core/src/main/java/art/arcane/iris/generation/context/ChunkContext.java
2026-10-21 23:03:48 -04:00
Brian Neumann-Fopiano 35e4e30ecd Performance core pools
- Generation pool sized to performance cores
- Pregen burst raise sized from performance cores
- Hydrology planner pool sized to performance cores, at least four
2026-10-21 23:03:20 -04:00
Brian Neumann-Fopiano 393ea10cdf Pregen hydrology reach
- Pregen tile speculation limited to the generation reach around the area instead of a 512-block halo
2026-10-21 21:58:31 -04:00
Brian Neumann-Fopiano 037156ab7d Added chunk terrain bake
- Compiled generator programs evaluate layer trees in batches through NoiseProgram
- TerrainProgram accumulates interpolator group means over chunk columns
- ChunkBakeCache holds compute-once per-chunk planes with provisional results never published
- Height, biome, region, rock, fluid and cave streams read the bake as thin facades
- Sparse hydrology and bounds reads stay scalar with a direct-mapped base height memo
- ColumnBake assembles id planes, heights, fluid surface, columns and the apron on demand
2026-10-21 21:52:07 -04:00
Brian Neumann-Fopiano 29e7e0384d Merged placement reach
- True object placement reach bounds shrink the carve window from 13 to 8 chunks
2026-10-21 21:47:25 -04:00
Brian Neumann-Fopiano 2d60898744 Native noise packaging
- Exclude native noise classes and libraries from Java 21 runtime jars
- Map the probe native library and policy properties to the native noise loader
2026-10-21 21:35:06 -04:00
Brian Neumann-Fopiano 6c7896f2a4 Merged locks and caches
- Lock-free history scope, shared subterrain plan caches, stateless cave biome hash, custom biome key cache
2026-10-21 21:15:07 -04:00
Brian Neumann-Fopiano b34e5e7676 Bound slope placement rotation
- Use the radial three-dimensional bound whenever rotateTowardsSlope is set, including placements whose configured rotation is disabled
- Group the support read margin helper with the other static factories
2026-10-21 21:09:57 -04:00
Brian Neumann-Fopiano 2471066937 Merged pipeline hygiene
- Lazy shore-band noise, zero interpolator groups dropped, inline prefill, dead streams removed
2026-10-21 21:03:22 -04:00
Brian Neumann-Fopiano ab468a198d Guarded nested corner blocks
- Fell back to per-group grid sampling when a height sample nests inside another on the same thread
- Covered nested sampling with a bit-exact parity test
2026-10-21 20:41:10 -04:00
Brian Neumann-Fopiano 7aaf346ce3 True placement reach bound
- Add PlacementReach: centered half-extent reach from loaded object keys, scale and shrink chains, enumerated rotation kernels, translate, warp and vacuum
- Size the object pass write radius and read radius from PlacementReach instead of full object width
- Size floating reach from scaled and shrunk object spans
- Count cave profile vacuum modes and upper-dimension effective rotation in the object reach
- Keep the transition-band footprint check on its existing footprint
- Add runner-backed and pack-wide reach tests
2026-10-21 20:24:46 -04:00
Brian Neumann-Fopiano 65542be8d6 Tightened mixed cave cells
- Classify mixed cells without fade, boost or protection through a branch-light column loop
- Hoist the per-row bilinear terms shared by every column of a cell row
- Mark open cells from the pass bitset when every pass column is active
2026-10-21 20:16:21 -04:00
Brian Neumann-Fopiano dcfadc8d1d Merged content trim
- Single-pass deposit ellipsoids, run-classified perfection scans, gated cave markers
2026-10-21 20:01:22 -04:00
Brian Neumann-Fopiano b03f1c90e1 Streamlined chunk prefill
- Read interpolator corner bounds through a per-thread chunk block and skip groups whose cell corners are all zero
- Prefilled chunk context caches inline on generation threads with heights ahead of biomes
- Kept the burst-pool prefill only for the platform main thread, with heights and biomes in one task
- Painted surface fluid from the chunk context cache instead of re-sampling the fluid stream
2026-10-21 19:53:23 -04:00
Brian Neumann-Fopiano e39e59699e Restore deposit clump RNG
- Return deposit clumps to the standard RNG; the unsynchronized generator measured no gain
2026-10-21 19:48:15 -04:00
Brian Neumann-Fopiano 13730f207a Drop deposit scan comment
- Remove the explanatory block comment added on the pack scan
2026-10-21 19:46:03 -04:00
Brian Neumann-Fopiano 217ed04f45 Split probe helpers
- Move chunk generation and buffer selection into ProbeChunkGenerator
- Move measured-window stage and counter lines into ProbeWindowMetrics
- Move hydrology pre-planning into ProbeHydrologyPreplan
2026-10-21 19:45:12 -04:00
Brian Neumann-Fopiano e3135d8b01 Unsynchronized deposit clump random
- Draw deposit clump randomness from a single-owner generator with the java.util.Random sequence
2026-10-21 19:37:27 -04:00
Brian Neumann-Fopiano 6ebb700be0 Reuse cave biome cache
- Carve scratch keeps one cave biome cache per thread, cleared per chunk
2026-10-21 19:29:37 -04:00
Brian Neumann-Fopiano 7c4a5e1937 Added cave cell kernel
- Decide whole 8x8 adaptive cells as solid or open from lattice corner bounds with an ulp guard
- Evaluate only mixed cells per column with the original bilinear arithmetic
- Share the row kernel between serial and parallel adaptive classification
- Count solid, open and mixed cells and exact rows, printed by the generation probe
- Pin carve write sequences for eight carver configurations with golden hashes
2026-10-21 19:26:52 -04:00
Brian Neumann-Fopiano 62d7c7e18a Sliding mantle submissions
- Replaced the barrier after every 8 component submissions with a per-caller cap that frees a slot as each component finishes and stops on the first failure
- Inline windows claim components without waiting and run components another generation holds after the rest of the pass
- Prefetched only the radius of passes that generate in the current phase
- Added straggler and held-claim tests and modeled claims in the locking chunk fixture
2026-10-21 19:24:44 -04:00
Brian Neumann-Fopiano c1732d50be Trimmed height pipeline work
- Removed the unused decoration, derivative and identity streams and Engine.getBiomeID
- Skipped the shore-height noise when a column sits outside the proven shore band
- Dropped interpolator groups whose bounds are zero in every base-capable biome
2026-10-21 19:21:49 -04:00
Brian Neumann-Fopiano 1821fedb24 Trim cave decoration markers
- Stop writing cave ceiling markers, which nothing reads
- Write cave floor markers only when the dimension has cave spawners
- Reuse the zone floor subterrain cell for zone decoration
2026-10-21 19:21:46 -04:00
Brian Neumann-Fopiano 41142ee5b5 Memoize perfection block classes
- Classify column blocks once per state run during perfection scans
2026-10-21 19:21:46 -04:00
Brian Neumann-Fopiano b6b01c88f5 Probe fidelity options
- Print measured-window stage totals from EngineMetrics as IRIS_GENPROBE_STAGES
- Time each context prefill task into its prefill timer
- Add gated generation counters for generator evaluations, corner starcasts and hydrology lookups
- Add -PprobeHydrologyPreplan to plan the probe area's hydrology tiles before warmup
- Add -PprobeHistoryRouter to generate through a generation-history router and registry contract
- Add -PprobeProductionBuffers to generate into production-equivalent block and biome hunks
- Print the mantle radius as IRIS_GENPROBE_MANTLE
2026-10-21 19:20:17 -04:00
Brian Neumann-Fopiano 3bd76d47a9 Single-pass deposit clumps
- Place ellipsoid deposit clumps from the footprint cells instead of rebuilding the clump object
- Skip ore cave-biome lookups when no pack biome scales ore deposits
- Reject terrain-limited clumps before biome work when scaling cannot apply
- Compute the chunk terrain limit once per chunk
- Draw the exposure discard roll only when the discard chance is positive
2026-10-21 19:16:57 -04:00
Brian Neumann-Fopiano 7282a46a26 Lock-free scopes and caches
- History coordinate scopes read the router and routing flag lock-free
- Subterrain planner shares bounded plan and chunk candidate caches
- Cave blend roll uses a stateless hash identical to the parallel RNG
- Custom biome resource keys are cached per dimension and biome identity
2026-10-21 19:15:01 -04:00
Brian Neumann-Fopiano e2430500cf Added probe parity oracle
- Dump every genProbe chunk as palette-indexed blocks and biomes with -PprobeDumpFile
- Add genDiff task comparing two dumps by coordinate with block, surface, biome and category parity
- Generate measured chunks on N threads in spiral order with -PprobeThreads and report wall-clock cps
- Mirror pregeneration with -PprobePregenProfile (pregen performance profile and hydrology prefetch scope)
- Print the measured window for JFR attribution and accept -PprobeJfrSettings
- Keep chunk hashes and the run signature byte-identical to the sequential probe
2026-10-21 18:47:25 -04:00
1836 changed files with 204306 additions and 119195 deletions

No files matched your search

+2
View File
@@ -81,3 +81,5 @@ BUILDS/
/docs/
/.perf/
/.codegraph/
.superpowers/
@@ -1,5 +1,7 @@
package art.arcane.iris.nativegen;
import art.arcane.volmlib.nativelib.terrain.structure.StructureWater;
import art.arcane.volmlib.nativelib.terrain.structure.StructurePalette;
import art.arcane.volmlib.nativelib.terrain.structure.StructureTerrainSettings;
@@ -90,7 +92,7 @@ public class NativeStructurePostProcessorEncaseTest {
.setHorizontalPadding(1)
.setCeilingPadding(1)
.setFloorPadding(1),
null);
null, StructureWater.DRY);
assertEquals(Blocks.DIRT.defaultBlockState(),
state(blocks, bounds.minX(), bounds.minY(), bounds.minZ()));
@@ -111,7 +113,7 @@ public class NativeStructurePostProcessorEncaseTest {
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), bounds, "minecraft:stronghold", start,
new IrisStructureTerrain().setMode(StructureTerrainMode.ENCASE),
null);
null, StructureWater.DRY);
assertEquals(-1, bounds.minY());
assertEquals(Blocks.DEEPSLATE.defaultBlockState(),
@@ -222,7 +224,7 @@ public class NativeStructurePostProcessorEncaseTest {
new IrisStructureTerrain()
.setMode(StructureTerrainMode.ENCASE)
.setEncasePalette(palette),
NativeStructurePostProcessorEncaseTest::tuffBlock);
NativeStructurePostProcessorEncaseTest::tuffBlock, StructureWater.DRY);
assertEquals(Blocks.TUFF.defaultBlockState(),
state(blocks, bounds.minX(), bounds.minY(), bounds.minZ()));
@@ -250,7 +252,7 @@ public class NativeStructurePostProcessorEncaseTest {
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), area, "test:bury", start,
new IrisStructureTerrain().setMode(StructureTerrainMode.SOURCE), null);
new IrisStructureTerrain().setMode(StructureTerrainMode.SOURCE), null, StructureWater.DRY);
assertEquals(Blocks.STONE.defaultBlockState(),
state(blocks, bounds.minX() - 5, groundY, bounds.minZ()));
@@ -277,7 +279,7 @@ public class NativeStructurePostProcessorEncaseTest {
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), area, "test:encapsulate", start,
new IrisStructureTerrain().setMode(StructureTerrainMode.SOURCE), null);
new IrisStructureTerrain().setMode(StructureTerrainMode.SOURCE), null, StructureWater.DRY);
assertEquals(Blocks.STONE.defaultBlockState(),
state(blocks, bounds.minX() - 11, bounds.minY(), bounds.minZ()));
@@ -1,5 +1,8 @@
package art.arcane.iris.nativegen;
import art.arcane.volmlib.nativelib.terrain.structure.StructureWater;
import art.arcane.volmlib.nativelib.terrain.structure.StructureWaterColumn;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureVerticalPlacer;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureReferenceEnvelope;
@@ -11,6 +14,7 @@ import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureFoundat
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceSupportBuilder;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceFitter;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceFitter.SeaSurface;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureVegetationClearer;
@@ -238,7 +242,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)),
(x, z) -> x < 2 ? groundY - 32 : groundY + 32);
(x, z) -> x < 2 ? groundY - 32 : groundY + 32, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int x = 0; x <= 3; x++) {
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, x, groundY, 0));
@@ -266,10 +270,11 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
put(blocks, 0, groundY - 19, 0, Blocks.DIRT.defaultBlockState());
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int y = groundY - 19; y <= groundY; y++) {
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, y, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, groundY - 19, 0));
for (int y = groundY - 18; y <= groundY; y++) {
assertEquals(PlainSurfaceStrata.at(groundY, y), state(blocks, 0, y, 0));
}
assertTrue(state(blocks, 0, groundY + 1, 0).isAir());
}
@@ -292,7 +297,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureTerrainIntegrator.TerrainTarget target = surfaceTarget(start, StructureTerrainMode.FLATTEN);
((IrisStructureTerrain) target.terrain()).setHorizontalPadding(24).setFlattenRange(64);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(target), (px, pz) -> groundY);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(target), (px, pz) -> groundY, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int y = groundY - 34; y <= groundY - 13; y++) {
assertEquals("Cave at " + y, Blocks.CAVE_AIR.defaultBlockState(), state(blocks, x, y, z));
@@ -315,10 +320,10 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
}
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int y = groundY - 8; y < groundY; y++) {
assertEquals("Foundation at " + y, Blocks.STONE.defaultBlockState(), state(blocks, 0, y, 0));
assertEquals("Foundation at " + y, PlainSurfaceStrata.at(groundY, y), state(blocks, 0, y, 0));
}
for (int y = groundY - 20; y <= groundY - 12; y++) {
assertEquals("Cave at " + y, Blocks.CAVE_AIR.defaultBlockState(), state(blocks, 0, y, 0));
@@ -337,9 +342,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
Map<BlockPos, BlockState> originalSubmerged = new HashMap<>(submerged);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(buried), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> 100);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> 100, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(submerged), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY - 8);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY - 8, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(originalBuried, buried);
assertEquals(originalSubmerged, submerged);
@@ -386,14 +391,62 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
return method.invoke(delegate, arguments);
});
NativeStructureSurfaceFitter.prepareSurfaceStructures(bounded, area, List.of(target), (x, z) -> 127);
NativeStructureSurfaceFitter.prepareSurfaceStructures(bounded, area, List.of(target), (x, z) -> 127, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GOLD_BLOCK.defaultBlockState(), state(blocks, 0, 94, 0));
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 95, 0));
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 127, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 127, 0));
assertTrue(state(blocks, 0, 128, 0).isAir());
}
@Test
public void flattenKeepsDryBanksAtTheWaterSurface() {
StructureStart start = desertStart();
int groundY = start.getBoundingBox().minY() - 1;
int streamX = start.getBoundingBox().maxX() + 6;
NativeStructureTerrainIntegrator.TerrainTarget target = new NativeStructureTerrainIntegrator.TerrainTarget(
"minecraft:village_plains", start,
new IrisStructureTerrain().setMode(StructureTerrainMode.FLATTEN).setHorizontalPadding(24).setFlattenRange(64));
assertStreamStaysBetweenItsBanks(target, streamX, start.getBoundingBox().minZ(), groundY + 8);
}
@Test
public void sourceFittingKeepsDryBanksAtTheWaterSurface() {
StructureStart start = desertStart(TerrainAdjustment.BEARD_THIN);
BoundingBox piece = start.getPieces().getFirst().getBoundingBox();
assertStreamStaysBetweenItsBanks(surfaceTarget(start, StructureTerrainMode.SOURCE), piece.maxX() + 3,
piece.minZ(), piece.minY() + 7);
}
private static void assertStreamStaysBetweenItsBanks(
NativeStructureTerrainIntegrator.TerrainTarget target, int streamX, int z, int bedY) {
int waterY = bedY + 1;
BoundingBox area = new BoundingBox(streamX - 1, 0, z, streamX + 1, 127, z);
Map<BlockPos, BlockState> blocks = new HashMap<>();
for (int x = streamX - 1; x <= streamX + 1; x++) {
for (int y = 0; y <= (x == streamX ? bedY : waterY); y++) {
put(blocks, x, y, z, Blocks.STONE.defaultBlockState());
}
}
put(blocks, streamX, bedY, z, Blocks.SAND.defaultBlockState());
put(blocks, streamX, waterY, z, Blocks.WATER.defaultBlockState());
StructureWater water = (x, columnZ) -> x == streamX && columnZ == z
? new StructureWaterColumn(true, true, bedY, waterY) : StructureWaterColumn.DRY;
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(target),
(x, columnZ) -> x == streamX && columnZ == z ? bedY : waterY, SeaSurface.NONE, water, PlainSurfaceStrata.STRATA);
int top = waterY;
while (top >= 0 && state(blocks, streamX, top, z).getFluidState().isEmpty()) {
top--;
}
assertTrue("the stream goes down with its banks", top >= 0 && top < waterY);
assertEquals(Blocks.SAND.defaultBlockState(), state(blocks, streamX, top - 1, z));
assertTrue("nothing stands above the lowered water", state(blocks, streamX, waterY, z).isAir());
assertFalse("west bank holds the water", state(blocks, streamX - 1, top, z).isAir());
assertFalse("east bank holds the water", state(blocks, streamX + 1, top, z).isAir());
}
@Test
public void flattenReferencesIncludeTheMaximumConfiguredFeather() throws Exception {
PoolElementStructurePiece piece = rigidTemplatePiece(new InlineSinglePoolElement(template(List.of(
@@ -406,9 +459,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
BoundingBox references = NativeStructureReferenceEnvelope.referenceBounds(start, start.getStructure(), terrain);
assertEquals(-128, references.minX());
assertEquals(128, references.maxX());
assertEquals(143, references.maxX());
assertEquals(-128, references.minZ());
assertEquals(128, references.maxZ());
assertEquals(143, references.maxZ());
NativeStructureSurfaceFitter.FlattenAnchor anchor = new NativeStructureSurfaceFitter.FlattenAnchor(
new NativeStructureSurfaceFitter.SurfaceAnchor(0, 0, 0, 0, 64, 2), 128, 128);
assertTrue(NativeStructureSurfaceFitter.resolveFlattenSurface(List.of(anchor), 127, 0, 100).range() > 0);
@@ -477,7 +530,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)),
(x, z) -> x == footprint.minX() ? 80 : 112);
(x, z) -> x == footprint.minX() ? 80 : 112, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(81, piece.getBoundingBox().minY());
assertTrue(piece.attemptVanillaAlignment());
@@ -511,13 +564,13 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
WorldGenLevel world = world(blocks);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world, area, List.of(target),
(x, z) -> x == 0 || x == 8 ? 64 : 96);
(x, z) -> x == 0 || x == 8 ? 64 : 96, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureTemplateOccupancy.OccupancyResult occupancy = NativeStructureTemplateOccupancy.resolve(
world, path, BlockPos.ZERO, area,
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertTrue(state(blocks, 4, 96, 0).isAir());
assertEquals(1, pathGround.size());
@@ -555,7 +608,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, area, List.of(target), (x, z) -> x < 4 ? 96 : 32);
world, area, List.of(target), (x, z) -> x < 4 ? 96 : 32, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(96, chunk.getHeight(Heightmap.Types.WORLD_SURFACE_WG, 0, 0));
assertEquals(32, chunk.getHeight(Heightmap.Types.WORLD_SURFACE_WG, 8, 0));
@@ -566,7 +619,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertEquals(2, pathGround.size());
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
@@ -615,14 +668,14 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, area, List.of(target), (x, z) -> x == 0 || x == 8 ? 64 : 96);
world, area, List.of(target), (x, z) -> x == 0 || x == 8 ? 64 : 96, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
plan.primeHeightmaps(chunk);
NativeStructureTemplateOccupancy.OccupancyResult occupancy = NativeStructureTemplateOccupancy.resolve(
world, path, BlockPos.ZERO, area,
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertEquals(2, pathGround.size());
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
@@ -670,7 +723,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
}
NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(target),
(x, z) -> (x == 0 || x == 8) && (z == 0 || z == 8) ? 64 : 96);
(x, z) -> (x == 0 || x == 8) && (z == 0 || z == 8) ? 64 : 96, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int x = 0; x <= 8; x++) {
for (int z = 0; z <= 8; z++) {
@@ -740,7 +793,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> 64);
(x, z) -> 64, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(before, blocks);
}
@@ -866,13 +919,13 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
new IrisStructureTerrain().setMode(StructureTerrainMode.SOURCE)));
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, targets,
(x, z) -> 65);
(x, z) -> 65, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 71, 1));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 11, 71, 1));
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 11, 70, 1));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 2, 65, 2));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 12, 65, 2));
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 2, 65, 2));
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 12, 65, 2));
}
@Test
@@ -891,7 +944,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> 64);
(x, z) -> 64, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 68, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 64, 0));
@@ -912,7 +965,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> 40);
(x, z) -> 40, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 46, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 47, 0));
@@ -944,7 +997,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> x == 0 ? 60 : x == 30 ? 72 : 64);
(x, z) -> x == 0 ? 60 : x == 30 ? 72 : 64, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 61, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 30, 71, 0));
@@ -972,7 +1025,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 64, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 63, 0));
@@ -997,7 +1050,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 64, 0));
@@ -1018,7 +1071,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 80);
(x, z) -> 80, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int y = 61; y <= 74; y++) {
assertFalse(state(blocks, 0, y, 0).isAir());
@@ -1043,7 +1096,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 79);
(x, z) -> 79, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int y = 61; y <= 74; y++) {
assertFalse(state(blocks, 0, y, 0).isAir());
@@ -1075,7 +1128,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int y = 61; y <= 64; y++) {
put(blocks, 0, y, 0, Blocks.CAVE_AIR.defaultBlockState());
}
@@ -1086,7 +1139,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
BlockState authoredAirSupport = state(blocks, 2, 66, 0);
NativeStructureSurfaceFitter.repairVacuumFoundations(
world(blocks), area, plan);
world(blocks), area, plan, PlainSurfaceStrata.STRATA);
for (int y = 61; y <= 64; y++) {
assertFalse(state(blocks, 0, y, 0).isAir());
@@ -1115,11 +1168,11 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
put(blocks, 0, 65, 0, Blocks.COBBLESTONE.defaultBlockState());
NativeStructureSurfaceFitter.repairVacuumFoundations(
world(blocks), area, plan);
world(blocks), area, plan, PlainSurfaceStrata.STRATA);
for (int y = 61; y <= 64; y++) {
assertTrue(state(blocks, 0, y, 0).isAir());
@@ -1145,13 +1198,13 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.SurfaceTerrainPlan widePlan =
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60);
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.SurfaceTerrainPlan westPlan =
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), westArea, List.of(target), (x, z) -> 60);
world(splitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.SurfaceTerrainPlan eastPlan =
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60);
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int x = 15; x <= 16; x++) {
for (int y = 61; y <= 64; y++) {
put(wideBlocks, x, y, 0, Blocks.CAVE_AIR.defaultBlockState());
@@ -1162,11 +1215,11 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
}
NativeStructureSurfaceFitter.repairVacuumFoundations(
world(wideBlocks), wideArea, widePlan);
world(wideBlocks), wideArea, widePlan, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.repairVacuumFoundations(
world(splitBlocks), eastArea, eastPlan);
world(splitBlocks), eastArea, eastPlan, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.repairVacuumFoundations(
world(splitBlocks), westArea, westPlan);
world(splitBlocks), westArea, westPlan, PlainSurfaceStrata.STRATA);
assertEquals(wideBlocks, splitBlocks);
}
@@ -1186,7 +1239,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(originalBlocks, blocks);
}
@@ -1207,7 +1260,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(originalBlocks, blocks);
}
@@ -1231,7 +1284,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 66, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 1, 67, 0));
@@ -1256,7 +1309,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(originalBlocks, blocks);
}
@@ -1276,7 +1329,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 66, 0));
@@ -1301,7 +1354,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(originalBlocks, blocks);
}
@@ -1322,7 +1375,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 4, 61, 4));
}
@@ -1340,7 +1393,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 50);
(x, z) -> 50, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(originalBlocks, blocks);
}
@@ -1359,7 +1412,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60, 1);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA, 1);
assertEquals(originalBlocks, blocks);
}
@@ -1383,7 +1436,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int y = 61; y <= 65; y++) {
assertFalse(state(blocks, 10, y, 0).isAir());
@@ -1411,15 +1464,15 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
Map<BlockPos, BlockState> reverseSplitBlocks = flatTerrain(wideArea, 60);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60);
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), westArea, List.of(target), (x, z) -> 60);
world(splitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60);
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(reverseSplitBlocks), eastArea, List.of(target), (x, z) -> 60);
world(reverseSplitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(reverseSplitBlocks), westArea, List.of(target), (x, z) -> 60);
world(reverseSplitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(wideBlocks, splitBlocks);
assertEquals(wideBlocks, reverseSplitBlocks);
@@ -1883,7 +1936,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
List<NativeStructureTerrainIntegrator.TerrainTarget> targets =
List.of(surfaceTarget(start));
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, area, targets, (x, z) -> 60);
world, area, targets, (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 2, 62, 2));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 2, 65, 2));
@@ -1937,9 +1990,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(lowered), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.STONE.defaultBlockState(), state(lowered, 0, 61, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(lowered, 0, 61, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(lowered, 0, 62, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(lowered, 0, 63, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(lowered, 0, 64, 0));
@@ -1952,9 +2005,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(raised), new BlockPos.MutableBlockPos(),
0, 0, 64, 68, -64, 319);
0, 0, 64, 68, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 65, 0));
assertEquals(Blocks.STONE.defaultBlockState(), state(raised, 0, 65, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 66, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 67, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(raised, 0, 68, 0));
@@ -1971,10 +2024,10 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 99, 83, -64, 319);
0, 0, 99, 83, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 82, 0));
assertEquals(Blocks.SNOW_BLOCK.defaultBlockState(), state(blocks, 0, 83, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 82, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 83, 0));
for (int y = 84; y <= 100; y++) {
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, y, 0));
}
@@ -1993,7 +2046,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 62, 0));
for (int y = 63; y <= 68; y++) {
@@ -2015,7 +2068,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 62, 0));
for (int y = 63; y <= 65; y++) {
@@ -2034,9 +2087,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 64, -64, 319, true);
0, 0, 64, 64, -64, 319, true, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 64, 0));
}
@@ -2047,10 +2100,10 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 64, -64, 319, true);
0, 0, 64, 64, -64, 319, true, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 64, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 64, 0));
}
@Test
@@ -2059,9 +2112,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, -64, -64, -64, 319, true);
0, 0, -64, -64, -64, 319, true, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, -64, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, -64, 0));
}
@Test
@@ -2076,7 +2129,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 68, -64, 319);
0, 0, 64, 68, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(log, state(blocks, 0, 66, 0));
assertEquals(leaves, state(blocks, 0, 68, 0));
@@ -2098,9 +2151,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
world, chunk, area, List.of(desertStart()));
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(),
0, 0, 64, 68, -64, 319);
0, 0, 64, 68, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 65, 0)));
assertEquals(Blocks.STONE.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 65, 0)));
assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 66, 0)));
assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 67, 0)));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 68, 0)));
@@ -2116,12 +2169,12 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 64, 0));
assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 65, 0));
assertEquals(Blocks.GRAVEL.defaultBlockState(), state(blocks, 0, 62, 0));
assertEquals("a surface under the fluid takes submerged soil", Blocks.DIRT.defaultBlockState(), state(blocks, 0, 62, 0));
}
@Test
@@ -2184,7 +2237,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), bounds, "minecraft:desert_pyramid", start,
new IrisStructureTerrain().setMode(StructureTerrainMode.VACUUM), null);
new IrisStructureTerrain().setMode(StructureTerrainMode.VACUUM), null, StructureWater.DRY);
assertEquals(Blocks.STONE.defaultBlockState(),
state(blocks, bounds.minX(), bounds.minY(), bounds.minZ()));
@@ -2208,7 +2261,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
new IrisStructureTerrain()
.setMode(StructureTerrainMode.FORCE_CARVE)
.setHorizontalPadding(1)
.setCeilingPadding(1), null);
.setCeilingPadding(1), null, StructureWater.DRY);
assertEquals(Blocks.AIR.defaultBlockState(),
state(blocks, bounds.maxX() + 1, bounds.minY(), bounds.maxZ()));
@@ -2240,7 +2293,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), area, "minecraft:ancient_city", start,
new IrisStructureTerrain().setMode(StructureTerrainMode.FORCE_CARVE), null);
new IrisStructureTerrain().setMode(StructureTerrainMode.FORCE_CARVE), null, StructureWater.DRY);
assertEquals(Blocks.AIR.defaultBlockState(),
state(blocks, firstBounds.minX(), y, z));
@@ -2381,7 +2434,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
bounds.maxX() + 6, bounds.maxY() + 12, bounds.maxZ() + 6);
Map<BlockPos, BlockState> blocks = fill(area);
NativeStructureTerrainIntegrator.carveOrganicColumns(world(blocks), area, carve);
NativeStructureTerrainIntegrator.carveOrganicColumns(world(blocks), area, StructureWater.DRY, carve);
int centerX = bounds.minX() + bounds.getXSpan() / 2;
int centerZ = bounds.minZ() + bounds.getZSpan() / 2;
@@ -2406,9 +2459,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
Map<BlockPos, BlockState> lobedBlocks = fill(area);
NativeStructureTerrainIntegrator.carveOrganicColumns(
world(uniformBlocks), area, organicCarve(start, 10, 0D));
world(uniformBlocks), area, StructureWater.DRY, organicCarve(start, 10, 0D));
NativeStructureTerrainIntegrator.carveOrganicColumns(
world(lobedBlocks), area, organicCarve(start, 10, 0.85D));
world(lobedBlocks), area, StructureWater.DRY, organicCarve(start, 10, 0.85D));
int uniform = 0;
int lobed = 0;
@@ -2456,9 +2509,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
// Each chunk context rebuilds its own noise channels from the shared start identity.
NativeStructureTerrainIntegrator.carveOrganicColumns(
world(wideBlocks), wide, organicCarve(start, 6));
world(wideBlocks), wide, StructureWater.DRY, organicCarve(start, 6));
NativeStructureTerrainIntegrator.carveOrganicColumns(
world(narrowBlocks), narrow, organicCarve(start, 6));
world(narrowBlocks), narrow, StructureWater.DRY, organicCarve(start, 6));
int carved = 0;
for (int x = narrow.minX(); x <= narrow.maxX(); x++) {
@@ -2495,7 +2548,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
.setCeilingPadding(8)
.setFloorPadding(0)
.setErosionStrength(1D)
.setErosionFrequency(0.05D), null);
.setErosionFrequency(0.05D), null, StructureWater.DRY);
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, centerX, bounds.minY(), centerZ));
assertEquals(Blocks.STONE.defaultBlockState(),
@@ -2813,7 +2866,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
SLAB_WIDTH - 1 + SLAB_PADDING, transectY, SLAB_DEPTH - 1);
Map<BlockPos, BlockState> blocks = fill(area);
NativeStructureTerrainIntegrator.carveOrganicColumns(world(blocks), area,
NativeStructureTerrainIntegrator.carveOrganicColumns(world(blocks), area, StructureWater.DRY,
NativeStructureTerrainIntegrator.organicCarve(
footprint, terrain, StructureCarveShape.ERODED, TEST_SEED));
@@ -3,6 +3,7 @@ package art.arcane.iris.nativegen;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureVerticalPlacer;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceFitter;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceFitter.SeaSurface;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureVegetationClearer;
@@ -206,9 +207,9 @@ public class NativeStructurePostProcessorVegetationTest {
write(chunk, 4, 106, 4, Blocks.CACTUS_FLOWER.defaultBlockState());
NativeStructureSurfaceFitter.applySurfaceColumn(
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 102, 93, MIN_Y, MAX_Y);
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 102, 93, MIN_Y, MAX_Y, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.SAND.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 93, 4)));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 93, 4)));
for (int y = 94; y <= 106; y++) {
assertTrue("Unsupported decoration at " + y, chunk.getBlockState(new BlockPos(4, y, 4)).isAir());
}
@@ -227,9 +228,9 @@ public class NativeStructurePostProcessorVegetationTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertTrue(chunk.getBlockState(new BlockPos(4, 65, 4)).isAir());
assertTrue(chunk.getBlockState(new BlockPos(4, 66, 4)).isAir());
@@ -249,7 +250,7 @@ public class NativeStructurePostProcessorVegetationTest {
write(chunk, 4, 67, 4, Blocks.CACTUS_FLOWER.defaultBlockState());
NativeStructureSurfaceFitter.applySurfaceColumn(
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y);
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(boundary, chunk.getBlockState(new BlockPos(4, 65, 4)));
assertEquals(Blocks.CACTUS.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 66, 4)));
@@ -271,11 +272,11 @@ public class NativeStructurePostProcessorVegetationTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.SAND.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 60, 4)));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 60, 4)));
for (int y = 61; y <= 67; y++) {
assertTrue(chunk.getBlockState(new BlockPos(4, y, 4)).isAir());
}
@@ -0,0 +1,31 @@
package art.arcane.iris.nativegen;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceFitter;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
final class PlainSurfaceStrata {
static final NativeStructureSurfaceFitter.SurfaceStrata STRATA = (x, z, surfaceY, submerged) ->
new NativeStructureSurfaceFitter.SurfaceStrata.Column() {
@Override
public BlockState block(int y) {
int depth = surfaceY - y;
if (depth == 0) {
return submerged ? Blocks.DIRT.defaultBlockState() : Blocks.GRASS_BLOCK.defaultBlockState();
}
return depth <= 2 ? Blocks.DIRT.defaultBlockState() : Blocks.STONE.defaultBlockState();
}
@Override
public int soilDepth() {
return 3;
}
};
static BlockState at(int surfaceY, int y) {
return STRATA.column(0, 0, surfaceY, false).block(y);
}
private PlainSurfaceStrata() {
}
}
@@ -1,5 +1,7 @@
package art.arcane.iris.platform.bukkit.nms.v26_2_R1;
import art.arcane.volmlib.nativelib.terrain.structure.StructureWater;
import art.arcane.volmlib.nativelib.v26_2_R1.terrain.NativeStructureWorldgenAccess;
import art.arcane.iris.structure.placement.IrisStructureTerrain;
@@ -94,13 +96,13 @@ public class NativeStructureWorldgenAccessTest {
unbounded.rejectDistantTerrainReads = true;
assertThrows(IllegalStateException.class, () -> NativeStructurePostProcessor.prepareTerrain(
unbounded.world(), area, targets, (palette, rng, x, y, z) -> Blocks.STONE.defaultBlockState()));
unbounded.world(), area, targets, (palette, rng, x, y, z) -> Blocks.STONE.defaultBlockState(), StructureWater.DRY));
RecordingDelegate recording = new RecordingDelegate();
recording.rejectDistantTerrainReads = true;
NativeStructureWorldgenAccess access = access(recording);
NativeStructurePostProcessor.prepareTerrain(
access, area, targets, (palette, rng, x, y, z) -> Blocks.STONE.defaultBlockState());
access, area, targets, (palette, rng, x, y, z) -> Blocks.STONE.defaultBlockState(), StructureWater.DRY);
assertEquals(0, recording.heightReads);
assertEquals(0, recording.chunkReads);
@@ -497,7 +497,13 @@ public class NativeStructureVolumeIndexTest {
private static Map<?, ?> cache(NativeStructureVolumeIndex index, String name) throws Exception {
Field field = NativeStructureVolumeIndex.class.getDeclaredField(name);
field.setAccessible(true);
return (Map<?, ?>) field.get(index);
Object value = field.get(index);
if (value instanceof Map<?, ?> map) {
return map;
}
Field entries = value.getClass().getDeclaredField("entries");
entries.setAccessible(true);
return (Map<?, ?>) entries.get(value);
}
private static StructureStart swampHut(int chunkX, int chunkZ, int x, int z) {
@@ -0,0 +1,563 @@
package art.arcane.iris.probe;
import art.arcane.iris.pack.datapack.export.WorldgenDatapackExporter;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.WorldgenExportRequest;
import art.arcane.iris.pack.datapack.export.WorldgenExportResult;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.levelgen.Aquifer;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.NoiseRouter;
import net.minecraft.world.level.levelgen.densityfunction.DensityFunction;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public final class DatapackCostProbe {
private static final String LOG_PREFIX = "[datapack-cost]";
static final String VANILLA_PRESET = "minecraft:normal";
private static final int WARMUP_ORIGIN = -4096;
private static final int MINIMUM_CALLS = 8;
private static final int TOP_OFFENDERS = 10;
private static final long ANALYSIS_STACK_BYTES = 1L << 30;
private static final double MEGABYTE = 1024.0 * 1024.0;
private static final double NANOS_PER_SECOND = 1_000_000_000.0;
private DatapackCostProbe() {
}
public static void main(String[] arguments) {
PrintStream diagnostics = System.err;
try {
execute(Configuration.parse(arguments));
} catch (Throwable failure) {
failure.printStackTrace(diagnostics);
diagnostics.flush();
System.exit(1);
}
System.out.flush();
System.exit(0);
}
private static void execute(Configuration configuration) throws Exception {
HeadlessNativeBootstrap.initialize();
Files.createDirectories(configuration.work());
Path work = Files.createTempDirectory(configuration.work(), "run-");
List<HeadlessNativeRegistries> loaded = new ArrayList<>(2);
try {
log("exporting " + configuration.dimension() + " from " + configuration.pack());
ExportRun export = export(configuration, work);
log(String.format(Locale.ROOT, "exported in %.1f s: %d files, %d density functions", export.stats().seconds(),
export.stats().files(), export.stats().densityFunctions()));
DensityJsonBreakdown.Report densityJson = onLargeStack("density-json",
() -> DensityJsonBreakdown.analyze(export.files(), configuration.dimension()).report());
Path datapack = work.resolve("datapack");
writeFiles(export.files(), datapack);
Path vanillaPack = Files.createDirectories(work.resolve("vanilla"));
ExportStats exportStats = export.stats();
export.files().clear();
long baseline = settledHeap();
long loadStarted = System.nanoTime();
HeadlessNativeRegistries vanilla = isolatedLoad(vanillaPack);
double vanillaLoad = (System.nanoTime() - loadStarted) / NANOS_PER_SECOND;
loaded.add(vanilla);
long vanillaHeap = settledHeap();
loadStarted = System.nanoTime();
HeadlessNativeRegistries exported = isolatedLoad(datapack);
double exportLoad = (System.nanoTime() - loadStarted) / NANOS_PER_SECOND;
loaded.add(exported);
long exportHeap = settledHeap();
log(String.format(Locale.ROOT, "registries loaded: vanilla %.2f s, export %.2f s", vanillaLoad, exportLoad));
WorldgenStageBench vanillaBench = new WorldgenStageBench(new WorldgenStageBench.Options("vanilla",
presetOverworld(vanilla.registries(), VANILLA_PRESET), vanilla.registries(), configuration.seed()));
warm(vanillaBench, configuration);
long vanillaSamplers = settledHeap();
WorldgenStageBench exportBench = new WorldgenStageBench(new WorldgenStageBench.Options("export",
exportedOverworld(exported.registries()), exported.registries(), configuration.seed()));
warm(exportBench, configuration);
long exportSamplers = settledHeap();
double loadStart = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
Measurement vanillaMeasurement = new Measurement(vanillaBench);
Measurement exportMeasurement = new Measurement(exportBench);
measure(List.of(vanillaMeasurement, exportMeasurement), configuration);
double loadEnd = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
Map<String, GeneratorStats> generators = new LinkedHashMap<>();
generators.put("vanilla", vanillaMeasurement.stats(vanillaLoad, vanillaHeap - baseline, vanillaSamplers - exportHeap));
generators.put("export", exportMeasurement.stats(exportLoad, exportHeap - vanillaHeap, exportSamplers - vanillaSamplers));
log("analyzing density function graphs");
Map<String, List<DensityCostAnalysis.RootCost>> roots = new LinkedHashMap<>();
roots.put("vanilla", onLargeStack("density-cost-vanilla", () -> analyzeRoots(vanillaBench.settings(), configuration.dimension())));
roots.put("export", onLargeStack("density-cost-export", () -> analyzeRoots(exportBench.settings(), configuration.dimension())));
Report report = new Report(configuration.pack().toString(), configuration.dimension(), configuration.seed(),
configuration.rounds() * configuration.side() * configuration.side(), configuration.warmup() * configuration.warmup(),
configuration.rounds(), new MachineLoad(Runtime.getRuntime().availableProcessors(), loadStart, loadEnd),
"single thread for chunk stages and calls, vanilla and export interleaved per round; registry load uses HeadlessNativeRegistries' 4-thread loader; export uses Iris's own pools",
"feature decoration not measured: Paper's applyBiomeDecoration needs a live ServerLevel and the headless feature world lives in test fixtures",
exportStats, generators, densityJson, roots, definitions());
writeReport(report, configuration.output());
System.out.println(table(report));
log("report written to " + configuration.output());
} finally {
for (HeadlessNativeRegistries registries : loaded) {
registries.close();
}
deleteTree(work);
}
}
private static ExportRun export(Configuration configuration, Path work) throws Exception {
Path exportRoot = Files.createDirectories(work.resolve("exports"));
StageClock clock = new StageClock();
WorldgenExportResult result;
long started;
long finished;
try (RealPackProbeSupport.Workspace workspace = RealPackProbeSupport.openWorkspace(new RealPackProbeSupport.WorkspaceOptions(
configuration.pack().toFile(), configuration.dimension(), LOG_PREFIX, new HeadlessNativeRuntime(), work))) {
WorldgenExportRequest request = WorldgenExportRequest.builder()
.pack(workspace.pack().toPath())
.dimension(configuration.dimension())
.exportRoot(exportRoot)
.objects(true)
.build();
started = System.nanoTime();
clock.start(started);
result = WorldgenDatapackExporter.create().export(request, clock);
finished = System.nanoTime();
}
if (!result.isSuccess()) {
throw new IllegalStateException("Export failed: " + result.message() + " " + result.diagnostics());
}
SortedMap<String, byte[]> files = zipEntries(result.output());
ExportStats stats = new ExportStats((finished - started) / NANOS_PER_SECOND, clock.seconds(finished), Files.size(result.output()),
files.size(), count(files, "/worldgen/density_function/"), bytes(files, "/worldgen/density_function/"),
count(files, "/worldgen/noise/"), count(files, "/worldgen/biome/"), result.diagnostics().size());
Files.delete(result.output());
return new ExportRun(stats, files);
}
private static void warm(WorldgenStageBench bench, Configuration configuration) {
long started = System.nanoTime();
bench.chunks(WARMUP_ORIGIN, WARMUP_ORIGIN, configuration.warmup(), new WorldgenStageBench.ChunkSamples());
WorldgenStageBench.CallBudget budget = new WorldgenStageBench.CallBudget(MINIMUM_CALLS * 4, MINIMUM_CALLS,
TimeUnit.SECONDS.toNanos(configuration.callSeconds()) / 4);
bench.uncachedBiome(budget, new WorldgenStageBench.CallSamples());
bench.baseHeight(budget, Heightmap.Types.WORLD_SURFACE_WG, new WorldgenStageBench.CallSamples());
bench.baseColumn(budget, new WorldgenStageBench.CallSamples());
log(String.format(Locale.ROOT, "%s warmed in %.1f s", bench.label(), (System.nanoTime() - started) / NANOS_PER_SECOND));
}
private static void measure(List<Measurement> measurements, Configuration configuration) {
int stride = configuration.side() + 4;
WorldgenStageBench.CallBudget budget = new WorldgenStageBench.CallBudget(
Math.max(1, configuration.calls() / configuration.rounds()), Math.max(1, MINIMUM_CALLS / configuration.rounds()),
TimeUnit.SECONDS.toNanos(configuration.callSeconds()) / configuration.rounds());
for (int round = 0; round < configuration.rounds(); round++) {
for (int index = 0; index < measurements.size(); index++) {
Measurement measurement = measurements.get((index + round) % measurements.size());
long started = System.nanoTime();
measurement.bench.chunks(round * stride, round * stride, configuration.side(), measurement.chunks);
measurement.bench.uncachedBiome(budget, measurement.uncachedBiome);
measurement.bench.baseHeight(budget, Heightmap.Types.WORLD_SURFACE_WG, measurement.surfaceHeight);
measurement.bench.baseHeight(budget, Heightmap.Types.OCEAN_FLOOR_WG, measurement.floorHeight);
measurement.bench.baseColumn(budget, measurement.column);
log(String.format(Locale.ROOT, "%s round %d measured in %.1f s", measurement.bench.label(), round,
(System.nanoTime() - started) / NANOS_PER_SECOND));
}
}
}
private static List<DensityCostAnalysis.RootCost> analyzeRoots(NoiseGeneratorSettings settings, String dimension) {
DensityCostAnalysis analysis = new DensityCostAnalysis(id -> DensityJsonBreakdown.category(dimension, id), TOP_OFFENDERS);
Map<String, DensityFunction> roots = new LinkedHashMap<>();
NoiseRouter router = settings.noiseRouter();
roots.put("temperature", router.temperature());
roots.put("vegetation", router.vegetation());
roots.put("continents", router.continents());
roots.put("erosion", router.erosion());
roots.put("depth", router.depth());
roots.put("ridges", router.ridges());
roots.put("chunk_surface_level", router.chunkSurfaceLevel());
roots.put("final_density", router.finalDensity());
if (settings.aquifers().isPresent()) {
Aquifer.Config aquifer = settings.aquifers().get();
roots.put("aquifer.barrier", aquifer.barrierNoise());
roots.put("aquifer.fluid_level_floodedness", aquifer.fluidLevelFloodednessNoise());
roots.put("aquifer.fluid_level_spread", aquifer.fluidLevelSpreadNoise());
roots.put("aquifer.lava", aquifer.lavaNoise());
roots.put("aquifer.exclusion", aquifer.exclusion());
roots.put("aquifer.surface_level", aquifer.surfaceLevel());
}
List<DensityCostAnalysis.RootCost> costs = new ArrayList<>(roots.size());
for (Map.Entry<String, DensityFunction> root : roots.entrySet()) {
costs.add(analysis.analyze(root.getKey(), root.getValue()));
}
return costs;
}
static LevelStem presetOverworld(RegistryAccess registries, String preset) {
return registries.lookupOrThrow(Registries.WORLD_PRESET)
.getOrThrow(ResourceKey.create(Registries.WORLD_PRESET, Identifier.parse(preset))).value().overworld()
.orElseThrow(() -> new IllegalStateException("World preset " + preset + " has no overworld"));
}
static LevelStem exportedOverworld(RegistryAccess registries) {
return registries.lookupOrThrow(Registries.LEVEL_STEM).getOrThrow(LevelStem.OVERWORLD).value();
}
private static HeadlessNativeRegistries isolatedLoad(Path directory) {
try (PaperRegistryScope scope = PaperRegistryScope.open()) {
return HeadlessNativeRegistries.load(directory);
}
}
private static long settledHeap() throws InterruptedException {
for (int pass = 0; pass < 4; pass++) {
System.gc();
Thread.sleep(200L);
}
return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
}
private static <T> T onLargeStack(String name, Callable<T> work) throws Exception {
AtomicReference<T> result = new AtomicReference<>();
AtomicReference<Throwable> failure = new AtomicReference<>();
Thread thread = new Thread(null, () -> {
try {
result.set(work.call());
} catch (Throwable problem) {
failure.set(problem);
}
}, name, ANALYSIS_STACK_BYTES);
thread.start();
thread.join();
if (failure.get() instanceof Exception exception) {
throw exception;
}
if (failure.get() instanceof Error error) {
throw error;
}
return result.get();
}
private static SortedMap<String, byte[]> zipEntries(Path zip) throws IOException {
SortedMap<String, byte[]> files = new TreeMap<>();
try (ZipFile archive = new ZipFile(zip.toFile())) {
Enumeration<? extends ZipEntry> entries = archive.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (!entry.isDirectory()) {
files.put(entry.getName(), archive.getInputStream(entry).readAllBytes());
}
}
}
return files;
}
private static void writeFiles(SortedMap<String, byte[]> files, Path directory) throws IOException {
Files.createDirectories(directory);
for (Map.Entry<String, byte[]> file : files.entrySet()) {
Path target = directory.resolve(file.getKey()).normalize();
if (!target.startsWith(directory)) {
throw new IllegalArgumentException("Export file escapes the datapack root: " + file.getKey());
}
Files.createDirectories(target.getParent());
Files.write(target, file.getValue());
}
}
private static int count(SortedMap<String, byte[]> files, String folder) {
int count = 0;
for (String path : files.keySet()) {
if (path.contains(folder) && path.endsWith(".json")) {
count++;
}
}
return count;
}
private static long bytes(SortedMap<String, byte[]> files, String folder) {
long bytes = 0;
for (Map.Entry<String, byte[]> file : files.entrySet()) {
if (file.getKey().contains(folder) && file.getKey().endsWith(".json")) {
bytes += file.getValue().length;
}
}
return bytes;
}
private static void writeReport(Report report, Path output) throws IOException {
Files.createDirectories(output.getParent());
Gson gson = new GsonBuilder().setPrettyPrinting().serializeSpecialFloatingPointValues().create();
Files.writeString(output, gson.toJson(report), StandardCharsets.UTF_8);
}
private static Map<String, String> definitions() {
Map<String, String> definitions = new LinkedHashMap<>();
definitions.put("chunks", "per stage: wall ms and current-thread CPU ms per chunk; rounds of side x side chunks alternate vanilla and export");
definitions.put("chunks.biomes", "ChunkGenerator.createBiomes on a fresh ProtoChunk, ms per chunk over the grid plus a one-chunk ring");
definitions.put("chunks.noise", "NoiseChunk construction (aquifer init) plus NoiseBasedChunkGenerator.doFill, ms per chunk");
definitions.put("chunks.surface", "MaterialSystem.buildSurface with the fill's NoiseChunk and a region biome manager, ms per chunk");
definitions.put("chunks.carverBiome", "one uncached BiomeSource lookup at the chunk origin, as ChunkAccess.carverBiome memoizes per chunk, ms per chunk");
definitions.put("uncachedBiome", "BiomeSource.createUncachedResolver(...).getNoiseBiome at random quart positions within 32k blocks, wall us per call and mean thread CPU us per call");
definitions.put("baseHeight", "NoiseBasedChunkGenerator.getBaseHeight as structure placement calls it, us per call");
definitions.put("baseColumn", "NoiseBasedChunkGenerator.getBaseColumn, us per call");
definitions.put("retainedHeapBytes", "used heap after four System.gc passes, delta across the registry load");
definitions.put("samplerHeapBytes", "used heap delta across RandomState creation and warmup (compiled samplers and buffer pools)");
definitions.put("roots.dagNodes", "distinct non-constant density function and spline nodes reachable, references shared");
definitions.put("roots.cachedNodes", "non-constant evaluations per point with caches enabled: every distinct cache body once, all branches");
definitions.put("roots.expandedNodes", "non-constant evaluations per point with every reference and cache re-expanded, all branches");
definitions.put("roots.uncachedPointWorst", "worst single uncached point evaluation with lazy splines, interval_select and range_choice; interpolated off-lattice costs 8 corners at expanded cost; find_top_surface counts its probe steps");
definitions.put("roots.dagShare", "share of the distinct nodes by the category of the named file that holds them; offset copies are Grad2 and Taps duplicates");
definitions.put("roots.exclusive", "named density functions ranked by multiplicity x own nodes in the expanded tree");
definitions.put("roots.inclusive", "named density functions ranked by multiplicity x subtree nodes in the expanded tree");
definitions.put("densityJson.structurallyDuplicateBytes", "bytes beyond one file per JSON shape, with numbers, density function references and noise ids abstracted");
return definitions;
}
private static String table(Report report) {
StringBuilder out = new StringBuilder(4096);
GeneratorStats vanilla = report.generators().get("vanilla");
GeneratorStats export = report.generators().get("export");
out.append(String.format(Locale.ROOT, "%s %s seed %d: %d chunks in %d interleaved rounds after %d warmup chunks, one thread, load %.0f-%.0f on %d cores%n",
LOG_PREFIX, report.dimension(), report.seed(), report.chunks(), report.rounds(), report.warmupChunks(),
report.load().loadAverageStart(), report.load().loadAverageEnd(), report.load().processors()));
out.append(String.format(Locale.ROOT, "%-34s %10s %10s %8s %10s %10s %8s%n", "stage (mean)", "vanilla", "export", "ratio",
"cpu van", "cpu exp", "ratio"));
out.append(String.format(Locale.ROOT, "%-34s %10s %10.1f%n", "export (s)", "-", report.export().seconds()));
row(out, "registry load (s)", vanilla.registryLoadSeconds(), export.registryLoadSeconds());
row(out, "retained heap after load (MB)", vanilla.retainedHeapBytes() / MEGABYTE, export.retainedHeapBytes() / MEGABYTE);
row(out, "sampler heap after warmup (MB)", vanilla.samplerHeapBytes() / MEGABYTE, export.samplerHeapBytes() / MEGABYTE);
stage(out, "biome fill (ms/chunk)", vanilla.chunks().biomes(), export.chunks().biomes());
stage(out, "noise fill (ms/chunk)", vanilla.chunks().noise(), export.chunks().noise());
stage(out, "surface (ms/chunk)", vanilla.chunks().surface(), export.chunks().surface());
stage(out, "carver biome lookup (ms/chunk)", vanilla.chunks().carverBiome(), export.chunks().carverBiome());
row(out, "chunk total (ms/chunk)", vanilla.chunks().totalMean(), export.chunks().totalMean(),
vanilla.chunks().totalCpuMean(), export.chunks().totalCpuMean());
call(out, "uncached getNoiseBiome (us/call)", vanilla.uncachedBiome(), export.uncachedBiome());
call(out, "getBaseHeight WORLD_SURFACE (us)", vanilla.baseHeightSurface(), export.baseHeightSurface());
call(out, "getBaseHeight OCEAN_FLOOR (us)", vanilla.baseHeightFloor(), export.baseHeightFloor());
call(out, "getBaseColumn (us/call)", vanilla.baseColumn(), export.baseColumn());
out.append(String.format(Locale.ROOT, "%-24s %9s %9s %9s %10s %10s %10s %10s%n", "router root", "dag(v)", "dag",
"cached", "expand(v)", "expanded", "uncPt(v)", "uncachedPt"));
List<DensityCostAnalysis.RootCost> vanillaRoots = report.roots().get("vanilla");
List<DensityCostAnalysis.RootCost> exportRoots = report.roots().get("export");
for (DensityCostAnalysis.RootCost root : exportRoots) {
DensityCostAnalysis.RootCost reference = find(vanillaRoots, root.root());
out.append(String.format(Locale.ROOT, "%-24s %9s %9s %9s %10s %10s %10s %10s%n", root.root(),
reference == null ? "-" : compact(reference.dagNodes()), compact(root.dagNodes()), compact(root.cachedNodes()),
reference == null ? "-" : compact(reference.expandedNodes()), compact(root.expandedNodes()),
reference == null ? "-" : compact(reference.uncachedPointWorst()), compact(root.uncachedPointWorst())));
}
out.append("top expanded offenders (exclusive share of root, multiplicity)\n");
for (DensityCostAnalysis.RootCost root : exportRoots) {
if (root.exclusive().isEmpty() || root.expandedNodes() < 1.0e4) {
continue;
}
StringBuilder line = new StringBuilder(String.format(Locale.ROOT, " %-22s", root.root()));
for (int index = 0; index < Math.min(2, root.exclusive().size()); index++) {
DensityCostAnalysis.Offender offender = root.exclusive().get(index);
line.append(String.format(Locale.ROOT, " %4.1f%% %s x%s;", 100.0 * offender.contribution() / root.expandedNodes(),
shortName(offender.name()), compact(offender.multiplicity())));
}
out.append(line).append('\n');
}
for (DensityCostAnalysis.RootCost root : exportRoots) {
if (root.dagNodes() < 1.0e4) {
continue;
}
List<Map.Entry<String, Double>> shares = new ArrayList<>(root.dagShare().entrySet());
shares.sort(Map.Entry.<String, Double>comparingByValue().reversed());
StringBuilder line = new StringBuilder(String.format(Locale.ROOT, " dag %-18s", root.root()));
for (int index = 0; index < Math.min(3, shares.size()); index++) {
line.append(String.format(Locale.ROOT, " %4.1f%% %s;", 100.0 * shares.get(index).getValue(), shares.get(index).getKey()));
}
out.append(line).append('\n');
}
DensityJsonBreakdown.Report json = report.densityJson();
out.append(String.format(Locale.ROOT, "density function JSON %.0f MB in %d files, %d cellular instances in %d shapes%n",
json.bytes() / MEGABYTE, json.files(), json.cellularInstances(), json.cellularShapes().size()));
for (int index = 0; index < Math.min(9, json.categories().size()); index++) {
DensityJsonBreakdown.CategoryBytes category = json.categories().get(index);
out.append(String.format(Locale.ROOT, " %-22s %8.1f MB %7d files %7d shapes %8.1f MB dup%n", category.category(),
category.bytes() / MEGABYTE, category.files(), category.distinctShapes(), category.structurallyDuplicateBytes() / MEGABYTE));
}
for (int index = 0; index < Math.min(4, json.libraryOwners().size()); index++) {
DensityJsonBreakdown.Bytes owner = json.libraryOwners().get(index);
out.append(String.format(Locale.ROOT, " %-48s %8.1f MB%n", owner.name(), owner.bytes() / MEGABYTE));
}
return out.toString();
}
private static void row(StringBuilder out, String label, double vanilla, double export) {
out.append(String.format(Locale.ROOT, "%-34s %10.3f %10.3f %8s%n", label, vanilla, export, ratio(vanilla, export)));
}
private static void row(StringBuilder out, String label, double vanilla, double export, double vanillaCpu, double exportCpu) {
out.append(String.format(Locale.ROOT, "%-34s %10.3f %10.3f %8s %10.3f %10.3f %8s%n", label, vanilla, export, ratio(vanilla, export),
vanillaCpu, exportCpu, ratio(vanillaCpu, exportCpu)));
}
private static void stage(StringBuilder out, String label, WorldgenStageBench.StageTiming vanilla, WorldgenStageBench.StageTiming export) {
row(out, label, vanilla.wall().mean(), export.wall().mean(), vanilla.cpu().mean(), export.cpu().mean());
}
private static void call(StringBuilder out, String label, WorldgenStageBench.CallTiming vanilla, WorldgenStageBench.CallTiming export) {
row(out, label, vanilla.wall().mean(), export.wall().mean(), vanilla.cpuMean(), export.cpuMean());
}
private static String ratio(double vanilla, double export) {
return vanilla > 0.0 ? String.format(Locale.ROOT, "%.1fx", export / vanilla) : "-";
}
private static DensityCostAnalysis.RootCost find(List<DensityCostAnalysis.RootCost> roots, String name) {
for (DensityCostAnalysis.RootCost root : roots) {
if (root.root().equals(name)) {
return root;
}
}
return null;
}
private static String shortName(String name) {
int separator = name.indexOf(':');
String path = separator < 0 ? name : name.substring(separator + 1);
return path.length() <= 34 ? path : "..." + path.substring(path.length() - 31);
}
private static String compact(double value) {
if (value < 1.0e4) {
return String.format(Locale.ROOT, "%.0f", value);
}
return String.format(Locale.ROOT, "%.2e", value);
}
private static void log(String message) {
System.out.println(LOG_PREFIX + " " + message);
}
private static void deleteTree(Path root) throws IOException {
if (!Files.exists(root)) {
return;
}
HeadlessNativeRegistries.delete(root);
}
record Configuration(Path pack, String dimension, long seed, int side, int rounds, int warmup, int calls, long callSeconds,
Path output, Path work) {
Configuration {
if (side < 1 || rounds < 1 || warmup < 1 || calls < MINIMUM_CALLS || callSeconds < 1) {
throw new IllegalArgumentException("side, rounds, warmup and callSeconds must be positive and calls at least " + MINIMUM_CALLS);
}
}
static Configuration parse(String[] arguments) {
if (arguments.length != 10) {
throw new IllegalArgumentException("Usage: pack dimension seed side rounds warmupSide calls callSeconds output work");
}
return new Configuration(new File(arguments[0]).toPath().toAbsolutePath(), arguments[1], Long.parseLong(arguments[2]),
Integer.parseInt(arguments[3]), Integer.parseInt(arguments[4]), Integer.parseInt(arguments[5]),
Integer.parseInt(arguments[6]), Long.parseLong(arguments[7]), new File(arguments[8]).toPath().toAbsolutePath(),
new File(arguments[9]).toPath().toAbsolutePath());
}
}
record ExportStats(double seconds, Map<String, Double> stageSeconds, long zipBytes, int files, int densityFunctions,
long densityFunctionBytes, int noises, int biomes, int diagnostics) {
}
record GeneratorStats(double registryLoadSeconds, long retainedHeapBytes, long samplerHeapBytes, WorldgenStageBench.ChunkTimings chunks,
WorldgenStageBench.CallTiming uncachedBiome, WorldgenStageBench.CallTiming baseHeightSurface,
WorldgenStageBench.CallTiming baseHeightFloor, WorldgenStageBench.CallTiming baseColumn) {
}
record MachineLoad(int processors, double loadAverageStart, double loadAverageEnd) {
}
record Report(String pack, String dimension, long seed, int chunks, int warmupChunks, int rounds, MachineLoad load,
String threading, String decoration,
ExportStats export, Map<String, GeneratorStats> generators, DensityJsonBreakdown.Report densityJson,
Map<String, List<DensityCostAnalysis.RootCost>> roots, Map<String, String> definitions) {
}
private record ExportRun(ExportStats stats, SortedMap<String, byte[]> files) {
}
private static final class Measurement {
private final WorldgenStageBench bench;
private final WorldgenStageBench.ChunkSamples chunks = new WorldgenStageBench.ChunkSamples();
private final WorldgenStageBench.CallSamples uncachedBiome = new WorldgenStageBench.CallSamples();
private final WorldgenStageBench.CallSamples surfaceHeight = new WorldgenStageBench.CallSamples();
private final WorldgenStageBench.CallSamples floorHeight = new WorldgenStageBench.CallSamples();
private final WorldgenStageBench.CallSamples column = new WorldgenStageBench.CallSamples();
private Measurement(WorldgenStageBench bench) {
this.bench = bench;
}
private GeneratorStats stats(double loadSeconds, long retainedHeap, long samplerHeap) {
return new GeneratorStats(loadSeconds, retainedHeap, samplerHeap, chunks.timings(), uncachedBiome.timing(),
surfaceHeight.timing(), floorHeight.timing(), column.timing());
}
}
private static final class StageClock implements WorldgenExportProgress {
private final Map<String, Long> starts = new LinkedHashMap<>();
private long origin;
private void start(long nanos) {
origin = nanos;
}
@Override
public void stage(String stage) {
starts.put(stage, System.nanoTime());
}
@Override
public void resources(int done, int total) {
}
private Map<String, Double> seconds(long finished) {
Map<String, Double> seconds = new LinkedHashMap<>();
String previous = "setup";
long previousStart = origin;
for (Map.Entry<String, Long> entry : starts.entrySet()) {
seconds.put(previous, (entry.getValue() - previousStart) / NANOS_PER_SECOND);
previous = entry.getKey();
previousStart = entry.getValue();
}
seconds.put(previous, (finished - previousStart) / NANOS_PER_SECOND);
return seconds;
}
}
}
@@ -0,0 +1,331 @@
package art.arcane.iris.probe;
import art.arcane.iris.generation.concurrent.MultiBurst;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.datapack.export.VanillaResourceIdentifier;
import art.arcane.iris.pack.datapack.export.WorldgenDatapackExporter;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.WorldgenExportRequest;
import art.arcane.iris.pack.datapack.export.WorldgenExportResult;
import art.arcane.iris.pack.datapack.export.WorldgenExportService;
import art.arcane.iris.pack.datapack.export.compile.surface.MaterialProgramCompiler;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.probe.fidelity.BiomeShareReport;
import art.arcane.iris.probe.fidelity.BiomeTypes;
import art.arcane.iris.probe.fidelity.ColumnSource;
import art.arcane.iris.probe.fidelity.ColumnSurvey;
import art.arcane.iris.probe.fidelity.FidelityComparison;
import art.arcane.iris.probe.fidelity.FidelityReport;
import art.arcane.iris.probe.fidelity.FidelitySampling;
import art.arcane.iris.probe.fidelity.FidelitySamples;
import art.arcane.iris.probe.fidelity.FidelityScanner;
import art.arcane.iris.probe.fidelity.FidelitySource;
import art.arcane.iris.probe.fidelity.FidelityStats;
import art.arcane.iris.probe.fidelity.FidelityThresholds;
import art.arcane.iris.probe.fidelity.IrisEngineColumnSource;
import art.arcane.iris.probe.fidelity.IrisEngineFidelitySource;
import art.arcane.iris.probe.fidelity.SurveyWindow;
import art.arcane.iris.probe.fidelity.VanillaNoiseColumnSource;
import art.arcane.iris.probe.fidelity.VanillaNoiseFidelitySource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.SortedMap;
import java.util.TreeMap;
public final class DatapackFidelityProbe {
private static final String LOG_PREFIX = "[datapack-fidelity]";
private static final String USAGE = "Usage: datapackFidelityProbe pack dimension seed radiusChunks stride output surveyBlocks surveyStride surveySeeds mode";
private static final String TARGET_VERSION = "26.3";
private static final String EXPORT_FORMAT = "directory";
private static final String EXPORT_OUTPUT = "export";
private static final int MAX_STRIDE = 16;
private static final int CHUNK_WIDTH = 16;
private static final int ARGUMENTS = 10;
private static final String COLUMN_SCOPE = "columns";
private static final String CHUNK_SCOPE = "chunks";
private static final int EXIT_ERROR = 1;
private static final int EXIT_FIDELITY_FAILED = 3;
private DatapackFidelityProbe() {
}
public static void main(String[] arguments) {
int status;
try {
status = execute(arguments, WorldgenDatapackExporter.create()).passed() ? 0 : EXIT_FIDELITY_FAILED;
} catch (Throwable failure) {
failure.printStackTrace(System.err);
status = EXIT_ERROR;
}
System.out.flush();
System.err.flush();
System.exit(status);
}
static FidelityReport execute(String[] arguments, WorldgenExportService exporter) throws Exception {
Objects.requireNonNull(exporter, "exporter");
Configuration configuration = Configuration.parse(arguments);
System.out.println(LOG_PREFIX + " pack=" + configuration.pack() + " dimension=" + configuration.dimension()
+ " seed=" + configuration.seed() + " radiusChunks=" + configuration.radiusChunks() + " stride=" + configuration.stride()
+ " surveyBlocks=" + configuration.survey().size() + " surveyStride=" + configuration.survey().stride()
+ " surveySeeds=" + configuration.surveySeeds() + " mode=" + configuration.mode().label());
Outcome outcome = compare(configuration, exporter);
writeReport(configuration.output(), outcome.json());
System.out.print(outcome.table());
System.out.println(LOG_PREFIX + " report=" + configuration.output());
return outcome.report();
}
private static Outcome compare(Configuration configuration, WorldgenExportService exporter) throws Exception {
Path scratch = Files.createTempDirectory("iris-datapack-fidelity-");
try {
return compareIn(scratch, configuration, exporter);
} finally {
ProbeWorkspaceCleanup.deleteRecursively(scratch);
}
}
private static Outcome compareIn(Path scratch, Configuration configuration, WorldgenExportService exporter) throws Exception {
HeadlessNativeRuntime runtime = new HeadlessNativeRuntime();
try (RealPackProbeSupport.Workspace workspace = RealPackProbeSupport.openWorkspace(new RealPackProbeSupport.WorkspaceOptions(
configuration.pack().toFile(), configuration.dimension(), LOG_PREFIX, runtime, scratch))) {
WorldgenExportResult export = export(exporter, workspace.pack().toPath(), configuration.dimension(), scratch.resolve("exports"));
Target target = new Target(export.output(), WorldgenExportRequest.DEFAULT_NAMESPACE,
VanillaResourceIdentifier.sanitizePath(configuration.dimension()), export.loadKeyByBiomeId());
return switch (configuration.mode()) {
case FULL -> Outcome.of(compareAll(workspace, target, configuration));
case BIOMES -> Outcome.of(compareBiomes(workspace, target, configuration));
};
}
}
private static FidelityReport compareAll(RealPackProbeSupport.Workspace workspace, Target target, Configuration configuration) throws Exception {
List<Long> seeds = configuration.surveySeeds();
FidelityStats irisColumns = null;
FidelityStats exportColumns = null;
FidelitySamples chunks = null;
for (long seed : seeds) {
try (RealPackProbeSupport.EngineSession session = workspace.openEngine(seed, false, "fidelity-" + seed)) {
Surveyed surveyed = survey(session.engine(), target, seed, configuration.survey());
irisColumns = irisColumns == null ? surveyed.iris() : irisColumns.merge(surveyed.iris());
exportColumns = exportColumns == null ? surveyed.export() : exportColumns.merge(surveyed.export());
if (seed == configuration.seed()) {
chunks = scanChunks(session.engine(), target, configuration);
}
}
}
FidelitySampling columnSampling = new FidelitySampling(COLUMN_SCOPE, configuration.survey().size(), configuration.survey().stride(),
seeds, irisColumns.columns());
return FidelityComparison.compare(new FidelitySamples(irisColumns, exportColumns, columnSampling), chunks, FidelityThresholds.defaults());
}
private static BiomeShareReport compareBiomes(RealPackProbeSupport.Workspace workspace, Target target, Configuration configuration) throws Exception {
List<FidelitySamples> seeds = new ArrayList<>(configuration.seedCount());
Map<String, String> biomeTypes = Map.of();
for (long seed : configuration.surveySeeds()) {
try (RealPackProbeSupport.EngineSession session = workspace.openEngine(seed, false, "biomes-" + seed)) {
Engine engine = session.engine();
Surveyed surveyed = survey(engine, target, seed, configuration.survey());
if (biomeTypes.isEmpty()) {
biomeTypes = BiomeTypes.of(engine.getDimension().getAllRegions(engine), key -> engine.getData().getBiomeLoader().load(key));
}
seeds.add(new FidelitySamples(surveyed.iris(), surveyed.export(), new FidelitySampling(COLUMN_SCOPE, configuration.survey().size(),
configuration.survey().stride(), List.of(seed), surveyed.iris().columns())));
}
}
return FidelityComparison.compareBiomeShares(seeds, biomeTypes, FidelityThresholds.defaults());
}
private static Surveyed survey(Engine engine, Target target, long seed, SurveyWindow window) throws Exception {
try (ColumnSource iris = new IrisEngineColumnSource(engine);
ColumnSource vanilla = new VanillaNoiseColumnSource(target.sampler(seed), target.loadKeyByBiomeId())) {
requireSameHeightRange(iris.minY(), iris.maxY(), vanilla.minY(), vanilla.maxY());
return new Surveyed(surveyed(iris, window, seed), surveyed(vanilla, window, seed));
}
}
private static FidelityStats surveyed(ColumnSource source, SurveyWindow window, long seed) {
long started = System.nanoTime();
FidelityStats stats = ColumnSurvey.scan(source, window, MultiBurst.burst.parallelism());
System.out.println(LOG_PREFIX + " surveyed " + source.label() + " seed=" + seed + " columns=" + stats.columns()
+ " in " + (System.nanoTime() - started) / 1_000_000L + "ms");
return stats;
}
private static FidelitySamples scanChunks(Engine engine, Target target, Configuration configuration) throws Exception {
try (IrisEngineFidelitySource iris = new IrisEngineFidelitySource(engine);
VanillaNoiseFidelitySource vanilla = new VanillaNoiseFidelitySource(target.sampler(configuration.seed()), target.loadKeyByBiomeId(),
target.namespace() + ":" + MaterialProgramCompiler.WALL_SHELL)) {
requireSameHeightRange(iris.minY(), iris.maxY(), vanilla.minY(), vanilla.maxY());
FidelityStats irisStats = scan(iris, configuration);
FidelityStats exportStats = scan(vanilla, configuration);
FidelitySampling sampling = new FidelitySampling(CHUNK_SCOPE, (2 * configuration.radiusChunks() + 1) * CHUNK_WIDTH,
configuration.stride(), List.of(configuration.seed()), irisStats.columns());
return new FidelitySamples(irisStats, exportStats, sampling);
}
}
private static WorldgenExportResult export(WorldgenExportService exporter, Path pack, String dimension, Path exportRoot) throws IOException {
Files.createDirectories(exportRoot);
WorldgenExportRequest request = WorldgenExportRequest.builder()
.pack(pack)
.dimension(dimension)
.version(TARGET_VERSION)
.format(EXPORT_FORMAT)
.output(EXPORT_OUTPUT)
.exportRoot(exportRoot)
.build();
WorldgenExportResult result = exporter.export(request, WorldgenExportProgress.NONE);
if (!result.isSuccess()) {
throw new IllegalStateException("Datapack export of dimension '" + dimension + "' was " + result.status() + ": " + result.message());
}
System.out.println(LOG_PREFIX + " exported target=" + TARGET_VERSION + " biomes=" + result.loadKeyByBiomeId().size()
+ " diagnostics=" + result.diagnostics().size() + " " + diagnosticCounts(result.diagnostics()));
return result;
}
private static FidelityStats scan(FidelitySource source, Configuration configuration) {
long started = System.nanoTime();
FidelityStats stats = FidelityScanner.scan(source, 0, 0, configuration.radiusChunks(), configuration.stride(),
MultiBurst.burst.parallelism());
System.out.println(LOG_PREFIX + " sampled " + source.label() + " columns=" + stats.columns() + " terrainColumns=" + stats.heightColumns()
+ " in " + (System.nanoTime() - started) / 1_000_000L + "ms");
return stats;
}
private static void requireSameHeightRange(int irisMinY, int irisMaxY, int exportMinY, int exportMaxY) {
if (irisMinY != exportMinY || irisMaxY != exportMaxY) {
throw new IllegalStateException("Iris height range [" + irisMinY + ", " + irisMaxY
+ ") differs from the exported dimension range [" + exportMinY + ", " + exportMaxY + ")");
}
}
private static SortedMap<String, Integer> diagnosticCounts(List<ExportDiagnostic> diagnostics) {
SortedMap<String, Integer> counts = new TreeMap<>();
for (ExportDiagnostic diagnostic : diagnostics) {
counts.merge(diagnostic.limit().name(), 1, Integer::sum);
}
return counts;
}
private static void writeReport(Path output, String json) throws IOException {
Path parent = output.getParent();
Files.createDirectories(parent);
Path staged = Files.createTempFile(parent, ".datapack-fidelity-", ".json");
try {
Files.writeString(staged, json + "\n", StandardCharsets.UTF_8);
Files.move(staged, output, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} finally {
Files.deleteIfExists(staged);
}
}
private enum Mode {
FULL,
BIOMES;
private static Mode parse(String value) {
String normalized = value.trim().toLowerCase(Locale.ROOT);
for (Mode mode : values()) {
if (mode.label().equals(normalized)) {
return mode;
}
}
throw new IllegalArgumentException("mode must be full or biomes, got '" + value + "'");
}
private String label() {
return name().toLowerCase(Locale.ROOT);
}
}
private record Outcome(FidelityReport report, String json, String table) {
private static Outcome of(FidelityReport report) {
return new Outcome(report, report.toJson(), report.toTable());
}
private static Outcome of(BiomeShareReport report) {
return new Outcome(report.mean(), report.toJson(), report.toTable());
}
}
private record Surveyed(FidelityStats iris, FidelityStats export) {
}
private record Target(Path output, String namespace, String dimension, Map<String, String> loadKeyByBiomeId) {
private WorldgenExportSampler sampler(long seed) throws IOException {
return WorldgenExportSampler.open(output, WorldgenExportMode.OVERWORLD, namespace + ":" + dimension, seed);
}
}
private record Configuration(Path pack, String dimension, long seed, int radiusChunks, int stride, Path output, SurveyWindow survey,
int seedCount, Mode mode) {
private static Configuration parse(String[] arguments) {
if (arguments.length != ARGUMENTS) {
throw new IllegalArgumentException(USAGE);
}
Path pack = Path.of(arguments[0]).toAbsolutePath().normalize();
if (!Files.isDirectory(pack)) {
throw new IllegalArgumentException("Pack folder " + pack + " does not exist");
}
String dimension = arguments[1].trim();
if (dimension.isEmpty()) {
throw new IllegalArgumentException("Dimension key must not be blank");
}
long seed = parseLong(arguments[2], "seed");
int radiusChunks = parseInt(arguments[3], "radiusChunks");
if (radiusChunks < 0) {
throw new IllegalArgumentException("radiusChunks must be zero or positive, got " + radiusChunks);
}
int stride = parseInt(arguments[4], "stride");
if (stride < 1 || stride > MAX_STRIDE) {
throw new IllegalArgumentException("stride must be within [1, " + MAX_STRIDE + "], got " + stride);
}
Path output = Path.of(arguments[5]).toAbsolutePath().normalize();
if (Files.isDirectory(output)) {
throw new IllegalArgumentException("Report output " + output + " is a directory");
}
SurveyWindow survey = new SurveyWindow(0, 0, parseInt(arguments[6], "surveyBlocks"), parseInt(arguments[7], "surveyStride"));
int seedCount = parseInt(arguments[8], "surveySeeds");
if (seedCount < 1) {
throw new IllegalArgumentException("surveySeeds must be at least 1, got " + seedCount);
}
Mode mode = Mode.parse(arguments[9]);
return new Configuration(pack, dimension, seed, radiusChunks, stride, output, survey, seedCount, mode);
}
private List<Long> surveySeeds() {
List<Long> seeds = new ArrayList<>(seedCount);
for (int index = 0; index < seedCount; index++) {
seeds.add(seed + index);
}
return seeds;
}
private static long parseLong(String value, String name) {
try {
return Long.parseLong(value.trim());
} catch (NumberFormatException failure) {
throw new IllegalArgumentException(name + " must be an integer, got '" + value + "'", failure);
}
}
private static int parseInt(String value, String name) {
try {
return Integer.parseInt(value.trim());
} catch (NumberFormatException failure) {
throw new IllegalArgumentException(name + " must be an integer, got '" + value + "'", failure);
}
}
}
}
@@ -0,0 +1,349 @@
package art.arcane.iris.probe;
import net.minecraft.core.Holder;
import net.minecraft.util.CubicSpline;
import net.minecraft.world.level.levelgen.densityfunction.DensityFunction;
import net.minecraft.world.level.levelgen.densityfunction.DensityFunctions;
import net.minecraft.world.level.levelgen.densityfunction.generator.ConstantFunction;
import net.minecraft.world.level.levelgen.densityfunction.op.CacheFunction;
import net.minecraft.world.level.levelgen.densityfunction.op.FindTopSurfaceFunction;
import net.minecraft.world.level.levelgen.densityfunction.op.InterpolatedFunction;
import net.minecraft.world.level.levelgen.densityfunction.op.IntervalSelectFunction;
import net.minecraft.world.level.levelgen.densityfunction.op.RangeChoiceFunction;
import net.minecraft.world.level.levelgen.densityfunction.op.SplineFunction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;
final class DensityCostAnalysis {
private static final double LATTICE_CORNERS = 8.0;
private static final int MAX_SURFACE_STEPS = 4096;
private static final String INLINE = "<inline>";
private final Function<String, String> categories;
private final int topCount;
private final Map<Object, Costs> costs = new IdentityHashMap<>();
private final Map<DensityFunction, Body> bodies = new IdentityHashMap<>();
private final Map<DensityFunction, String> names = new IdentityHashMap<>();
DensityCostAnalysis(Function<String, String> categories, int topCount) {
this.categories = categories;
this.topCount = topCount;
}
RootCost analyze(String root, DensityFunction function) {
Costs total = cost(function);
Reach reach = new Reach();
reach(function, reach, categories.apply(rootName(function, root)));
double cached = total.cachedLocal();
for (CacheFunction cache : reach.caches.keySet()) {
cached += cost(cache.input()).cachedLocal();
}
Body rootBody = new Body();
local(function, rootBody, true);
Map<DensityFunction, Double> multiplicity = multiplicity(rootBody);
List<Offender> offenders = new ArrayList<>(multiplicity.size());
Map<String, Double> shares = new TreeMap<>();
double expanded = total.expanded();
shares.merge(categories.apply(rootName(function, root)), rootBody.self / expanded, Double::sum);
for (Map.Entry<DensityFunction, Double> entry : multiplicity.entrySet()) {
DensityFunction value = entry.getKey();
Body body = body(value);
String name = names.get(value);
String category = categories.apply(name);
double contribution = entry.getValue() * body.self;
shares.merge(category, contribution / expanded, Double::sum);
offenders.add(new Offender(name, category, entry.getValue(), body.self, cost(value).expanded(),
contribution, entry.getValue() * cost(value).expanded()));
}
List<Offender> exclusive = top(offenders, Comparator.comparingDouble(Offender::contribution).reversed());
List<Offender> inclusive = top(offenders, Comparator.comparingDouble(Offender::inclusive).reversed());
Map<String, Double> dagShares = new TreeMap<>();
for (Map.Entry<String, Double> entry : reach.categories.entrySet()) {
dagShares.put(entry.getKey(), entry.getValue() / Math.max(1L, reach.nodes));
}
return new RootCost(root, reach.nodes, cached, expanded, total.lazy(), multiplicity.size(), exclusive, inclusive, shares, dagShares);
}
private List<Offender> top(List<Offender> offenders, Comparator<Offender> order) {
List<Offender> sorted = new ArrayList<>(offenders);
sorted.sort(order);
return List.copyOf(sorted.subList(0, Math.min(topCount, sorted.size())));
}
private String rootName(DensityFunction function, String root) {
if (function instanceof DensityFunctions.HolderHolder(Holder<DensityFunction> holder)) {
return name(holder);
}
return root;
}
private Costs cost(DensityFunction function) {
if (function instanceof DensityFunctions.HolderHolder(Holder<DensityFunction> holder)) {
DensityFunction value = holder.value();
names.putIfAbsent(value, name(holder));
return cost(value);
}
Costs known = costs.get(function);
if (known != null) {
return known;
}
Costs computed = compute(function);
costs.put(function, computed);
return computed;
}
private Costs compute(DensityFunction function) {
return switch (function) {
case ConstantFunction ignored -> new Costs(0.0, 0.0, 0.0);
case CacheFunction cache -> {
Costs input = cost(cache.input());
yield new Costs(1.0 + input.expanded(), 1.0 + input.lazy(), 1.0);
}
case SplineFunction spline -> {
Costs inner = spline(spline.spline());
yield new Costs(1.0 + inner.expanded(), 1.0 + inner.lazy(), 1.0 + inner.cachedLocal());
}
case IntervalSelectFunction select -> {
Costs input = cost(select.input());
double expanded = 1.0 + input.expanded();
double cached = 1.0 + input.cachedLocal();
double lazy = 0.0;
for (DensityFunction branch : select.functions()) {
Costs branchCost = cost(branch);
expanded += branchCost.expanded();
cached += branchCost.cachedLocal();
lazy = Math.max(lazy, branchCost.lazy());
}
yield new Costs(expanded, 1.0 + input.lazy() + lazy, cached);
}
case RangeChoiceFunction choice -> {
Costs input = cost(choice.input());
Costs inside = cost(choice.whenInRange());
Costs outside = cost(choice.whenOutOfRange());
yield new Costs(1.0 + input.expanded() + inside.expanded() + outside.expanded(),
1.0 + input.lazy() + Math.max(inside.lazy(), outside.lazy()),
1.0 + input.cachedLocal() + inside.cachedLocal() + outside.cachedLocal());
}
case InterpolatedFunction grid -> {
Costs input = cost(grid.input());
yield new Costs(1.0 + input.expanded(), 1.0 + LATTICE_CORNERS * input.expanded(), 1.0 + input.cachedLocal());
}
case FindTopSurfaceFunction surface -> {
Costs density = cost(surface.density());
Costs upper = cost(surface.upperBound());
double steps = surfaceSteps(surface);
yield new Costs(1.0 + density.expanded() + upper.expanded(), 1.0 + upper.lazy() + steps * density.lazy(),
1.0 + density.cachedLocal() + upper.cachedLocal());
}
default -> {
double expanded = 1.0;
double lazy = 1.0;
double cached = 1.0;
for (DensityFunction child : children(function)) {
Costs childCost = cost(child);
expanded += childCost.expanded();
lazy += childCost.lazy();
cached += childCost.cachedLocal();
}
yield new Costs(expanded, lazy, cached);
}
};
}
private Costs spline(CubicSpline<SplineFunction.Coordinate> spline) {
if (!(spline instanceof CubicSpline.Multipoint<SplineFunction.Coordinate> multipoint)) {
return new Costs(0.0, 0.0, 0.0);
}
Costs known = costs.get(multipoint);
if (known != null) {
return known;
}
Costs coordinate = cost(multipoint.coordinate().function());
List<CubicSpline<SplineFunction.Coordinate>> values = multipoint.values();
double expanded = 1.0 + coordinate.expanded();
double cached = 1.0 + coordinate.cachedLocal();
double[] lazy = new double[values.size()];
for (int index = 0; index < values.size(); index++) {
Costs value = spline(values.get(index));
expanded += value.expanded();
cached += value.cachedLocal();
lazy[index] = value.lazy();
}
double worstPair = lazy.length == 1 ? lazy[0] : 0.0;
for (int index = 0; index + 1 < lazy.length; index++) {
worstPair = Math.max(worstPair, lazy[index] + lazy[index + 1]);
}
Costs computed = new Costs(expanded, 1.0 + coordinate.lazy() + worstPair, cached);
costs.put(multipoint, computed);
return computed;
}
private void reach(DensityFunction function, Reach reach, String category) {
if (function instanceof DensityFunctions.HolderHolder(Holder<DensityFunction> holder)) {
reach(holder.value(), reach, categories.apply(name(holder)));
return;
}
if (function instanceof ConstantFunction || reach.visited.put(function, Boolean.TRUE) != null) {
return;
}
reach.count(category);
if (function instanceof CacheFunction cache) {
reach.caches.put(cache, Boolean.TRUE);
}
if (function instanceof SplineFunction spline) {
reachSpline(spline.spline(), reach, category);
return;
}
for (DensityFunction child : children(function)) {
reach(child, reach, category);
}
}
private void reachSpline(CubicSpline<SplineFunction.Coordinate> spline, Reach reach, String category) {
if (!(spline instanceof CubicSpline.Multipoint<SplineFunction.Coordinate> multipoint)) {
return;
}
if (reach.visited.put(multipoint, Boolean.TRUE) != null) {
return;
}
reach.count(category);
reach(multipoint.coordinate().function(), reach, category);
for (CubicSpline<SplineFunction.Coordinate> value : multipoint.values()) {
reachSpline(value, reach, category);
}
}
private Body body(DensityFunction value) {
Body known = bodies.get(value);
if (known != null) {
return known;
}
Body body = new Body();
local(value, body, true);
bodies.put(value, body);
return body;
}
private void local(DensityFunction function, Body body, boolean top) {
if (function instanceof DensityFunctions.HolderHolder(Holder<DensityFunction> holder)) {
if (!top) {
DensityFunction value = holder.value();
names.putIfAbsent(value, name(holder));
body.references.merge(value, 1.0, Double::sum);
return;
}
local(holder.value(), body, true);
return;
}
if (function instanceof ConstantFunction) {
return;
}
body.self++;
if (function instanceof SplineFunction spline) {
localSpline(spline.spline(), body);
return;
}
for (DensityFunction child : children(function)) {
local(child, body, false);
}
}
private void localSpline(CubicSpline<SplineFunction.Coordinate> spline, Body body) {
if (!(spline instanceof CubicSpline.Multipoint<SplineFunction.Coordinate> multipoint)) {
return;
}
body.self++;
local(multipoint.coordinate().function(), body, false);
for (CubicSpline<SplineFunction.Coordinate> value : multipoint.values()) {
localSpline(value, body);
}
}
private Map<DensityFunction, Double> multiplicity(Body root) {
List<DensityFunction> order = new ArrayList<>();
Map<DensityFunction, Boolean> visited = new IdentityHashMap<>();
for (DensityFunction child : root.references.keySet()) {
postOrder(child, visited, order);
}
Collections.reverse(order);
Map<DensityFunction, Double> multiplicity = new IdentityHashMap<>(order.size() * 2);
for (Map.Entry<DensityFunction, Double> entry : root.references.entrySet()) {
multiplicity.merge(entry.getKey(), entry.getValue(), Double::sum);
}
for (DensityFunction value : order) {
double times = multiplicity.getOrDefault(value, 0.0);
for (Map.Entry<DensityFunction, Double> entry : body(value).references.entrySet()) {
multiplicity.merge(entry.getKey(), times * entry.getValue(), Double::sum);
}
}
return multiplicity;
}
private void postOrder(DensityFunction value, Map<DensityFunction, Boolean> visited, List<DensityFunction> order) {
if (visited.put(value, Boolean.TRUE) != null) {
return;
}
for (DensityFunction child : body(value).references.keySet()) {
postOrder(child, visited, order);
}
order.add(value);
}
private static double surfaceSteps(FindTopSurfaceFunction surface) {
double upper = surface.upperBound().range().max();
if (!Double.isFinite(upper)) {
return MAX_SURFACE_STEPS;
}
double steps = Math.floor((upper - surface.lowerBound()) / surface.cellHeight()) + 1.0;
return Math.clamp(steps, 1.0, MAX_SURFACE_STEPS);
}
private static List<DensityFunction> children(DensityFunction function) {
List<DensityFunction> children = new ArrayList<>(4);
function.rewriteChildren(child -> {
children.add(child);
return child;
});
return children;
}
private static String name(Holder<DensityFunction> holder) {
return holder.unwrapKey().map(key -> key.identifier().toString()).orElse(INLINE);
}
record Costs(double expanded, double lazy, double cachedLocal) {
}
record Offender(String name, String category, double multiplicity, double selfNodes, double subtreeNodes,
double contribution, double inclusive) {
}
record RootCost(String root, long dagNodes, double cachedNodes, double expandedNodes, double uncachedPointWorst,
int namedSubtrees, List<Offender> exclusive, List<Offender> inclusive, Map<String, Double> categoryShare,
Map<String, Double> dagShare) {
}
private static final class Reach {
private final Map<Object, Boolean> visited = new IdentityHashMap<>();
private final Map<CacheFunction, Boolean> caches = new IdentityHashMap<>();
private final Map<String, Double> categories = new TreeMap<>();
private long nodes;
private void count(String category) {
nodes++;
categories.merge(category, 1.0, Double::sum);
}
}
private static final class Body {
private final Map<DensityFunction, Double> references = new IdentityHashMap<>();
private double self;
}
}
@@ -0,0 +1,409 @@
package art.arcane.iris.probe;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
final class DensityJsonBreakdown {
private static final String DENSITY_FUNCTIONS = "/worldgen/density_function/";
private static final String NOISES = "/worldgen/noise/";
private static final String JSON = ".json";
private static final String CELLULAR = "cellular";
private static final String NOISE_STYLE = "noise style";
private static final String UNREFERENCED = "unreferenced";
private static final String OFFSET_MARKER = "/offset_";
private static final String OFFSET_SUFFIX = " offset copies";
private static final int INSTANCE_SEGMENTS = 3;
private static final Set<String> ROUTER_ROOTS = Set.of("final_density", "temperature", "vegetation", "continents", "erosion",
"depth", "ridges", "chunk_surface_level", "barrier", "fluid_level_floodedness", "fluid_level_spread", "lava", "exclusion",
"surface_level", "spawn_elevation");
private static final long FNV_OFFSET = 0xcbf29ce484222325L;
private static final long FNV_PRIME = 0x100000001b3L;
private static final int TOP = 10;
private final String dimension;
private final String dimensionPrefix;
private final Map<String, Integer> categoryIndex = new HashMap<>();
private final List<String> categoryNames = new ArrayList<>();
private final Map<String, Entry> entries = new TreeMap<>();
private final Map<String, List<String>> parents = new HashMap<>();
private final Map<String, Long> owners = new HashMap<>();
private DensityJsonBreakdown(String dimension) {
this.dimension = dimension;
dimensionPrefix = dimension + "/";
}
static DensityJsonBreakdown analyze(SortedMap<String, byte[]> files, String dimension) {
DensityJsonBreakdown breakdown = new DensityJsonBreakdown(dimension);
breakdown.load(files);
return breakdown;
}
static String category(String dimension, String id) {
String base = baseCategory(dimension, id);
return id.contains(OFFSET_MARKER) ? base + OFFSET_SUFFIX : base;
}
private static String baseCategory(String dimension, String id) {
int separator = id.indexOf(':');
String path = separator < 0 ? id : id.substring(separator + 1);
String dimensionPrefix = dimension + "/";
if (path.startsWith(dimensionPrefix)) {
path = path.substring(dimensionPrefix.length());
}
if (ROUTER_ROOTS.contains(path)) {
return "router";
}
if (path.startsWith("cell/")) {
return CELLULAR;
}
if (path.startsWith("style/")) {
return NOISE_STYLE;
}
if (path.startsWith("biome/selector/")) {
return "biome selector";
}
if (path.startsWith("biome/carving/")) {
return "biome carving";
}
if (path.startsWith("biome/")) {
return "biome decision";
}
if (path.equals("height") || path.startsWith("height/") || path.startsWith("terrain/height/")) {
return "terrain height";
}
if (path.startsWith("terrain/generator/")) {
return "terrain generator";
}
if (path.startsWith("terrain/volume/")) {
return "terrain volumetric";
}
if (path.startsWith("terrain/")) {
return "terrain bands";
}
if (path.startsWith("cave")) {
return "caves";
}
if (path.startsWith("surface/")) {
return "surface";
}
int slash = path.indexOf('/');
return slash < 0 ? path : path.substring(0, slash);
}
Report report() {
Map<String, CategoryAccumulator> categories = new TreeMap<>();
Map<String, CategoryAccumulator> groups = new TreeMap<>();
Map<String, Long> libraryOwners = new TreeMap<>();
long totalBytes = 0;
long totalNodes = 0;
for (Map.Entry<String, Entry> item : entries.entrySet()) {
String id = item.getKey();
Entry entry = item.getValue();
totalBytes += entry.bytes;
totalNodes += entry.nodes;
String category = category(dimension, id);
categories.computeIfAbsent(category, ignored -> new CategoryAccumulator()).add(entry);
groups.computeIfAbsent(group(id), ignored -> new CategoryAccumulator()).add(entry);
if (isLibrary(category)) {
libraryOwners.merge(category + " via " + ownerLabel(owners(id)), entry.bytes, Long::sum);
}
}
List<CategoryBytes> categoryRows = rows(categories, Integer.MAX_VALUE);
List<CategoryBytes> groupRows = rows(groups, 40);
List<Bytes> ownerRows = new ArrayList<>();
for (Map.Entry<String, Long> owner : libraryOwners.entrySet()) {
ownerRows.add(new Bytes(owner.getKey(), owner.getValue()));
}
ownerRows.sort(Comparator.comparingLong(Bytes::bytes).reversed());
List<Bytes> largest = new ArrayList<>();
for (Map.Entry<String, Entry> item : entries.entrySet()) {
largest.add(new Bytes(item.getKey(), item.getValue().bytes));
}
largest.sort(Comparator.comparingLong(Bytes::bytes).reversed());
return new Report(entries.size(), totalBytes, totalNodes, categoryRows, groupRows, ownerRows,
List.copyOf(largest.subList(0, Math.min(TOP, largest.size()))), cellularInstances());
}
private void load(SortedMap<String, byte[]> files) {
Map<String, byte[]> bodies = new HashMap<>();
Set<String> noises = new HashSet<>();
for (Map.Entry<String, byte[]> file : files.entrySet()) {
String id = resourceId(file.getKey(), DENSITY_FUNCTIONS);
if (id != null) {
bodies.put(id, file.getValue());
continue;
}
String noise = resourceId(file.getKey(), NOISES);
if (noise != null) {
noises.add(noise);
}
}
for (Map.Entry<String, byte[]> body : bodies.entrySet()) {
JsonElement json = JsonParser.parseString(new String(body.getValue(), StandardCharsets.UTF_8));
Entry entry = new Entry(body.getValue().length);
entry.shape = shape(json, bodies.keySet(), noises, entry);
entries.put(body.getKey(), entry);
for (String reference : entry.references) {
parents.computeIfAbsent(reference, ignored -> new ArrayList<>()).add(body.getKey());
}
}
}
private long shape(JsonElement element, Set<String> functions, Set<String> noises, Entry entry) {
if (element.isJsonObject()) {
entry.nodes++;
JsonObject object = element.getAsJsonObject();
long hash = mix(FNV_OFFSET, '{');
for (String key : new TreeMap<>(object.asMap()).keySet()) {
hash = mix(mix(hash, key.hashCode()), shape(object.get(key), functions, noises, entry));
}
return mix(hash, '}');
}
if (element.isJsonArray()) {
JsonArray array = element.getAsJsonArray();
long hash = mix(FNV_OFFSET, '[');
for (JsonElement item : array) {
hash = mix(hash, shape(item, functions, noises, entry));
}
return mix(hash, ']');
}
if (element.isJsonPrimitive()) {
JsonPrimitive primitive = element.getAsJsonPrimitive();
if (primitive.isNumber()) {
return mix(FNV_OFFSET, 'N');
}
if (primitive.isString()) {
String value = primitive.getAsString();
if (functions.contains(value)) {
entry.references.add(value);
return mix(FNV_OFFSET, 'R');
}
if (noises.contains(value)) {
return mix(FNV_OFFSET, 'Z');
}
return mix(FNV_OFFSET, value.hashCode());
}
return mix(FNV_OFFSET, primitive.getAsBoolean() ? 'T' : 'F');
}
return mix(FNV_OFFSET, '0');
}
private List<CellularShape> cellularInstances() {
Map<String, List<String>> instances = new TreeMap<>();
for (String id : entries.keySet()) {
if (!isLibrary(category(dimension, id)) || !id.contains(":cell/")) {
continue;
}
instances.computeIfAbsent(instanceKey(id), ignored -> new ArrayList<>()).add(id);
}
Map<Long, CellularAccumulator> shapes = new HashMap<>();
for (Map.Entry<String, List<String>> instance : instances.entrySet()) {
List<String> members = instance.getValue();
members.sort(String::compareTo);
long hash = FNV_OFFSET;
long bytes = 0;
long owner = 0L;
StringBuilder layout = new StringBuilder();
for (String member : members) {
Entry entry = entries.get(member);
String suffix = member.substring(instance.getKey().length());
hash = mix(mix(hash, suffix.hashCode()), entry.shape);
bytes += entry.bytes;
owner |= owners(member);
if (!layout.isEmpty()) {
layout.append(',');
}
layout.append(suffix);
}
CellularAccumulator accumulator = shapes.computeIfAbsent(hash, ignored -> new CellularAccumulator(instance.getKey(), layout.toString()));
accumulator.instances++;
accumulator.bytes += bytes;
accumulator.owners |= owner;
}
List<CellularShape> rows = new ArrayList<>(shapes.size());
for (CellularAccumulator accumulator : shapes.values()) {
rows.add(new CellularShape(accumulator.example, accumulator.layout, accumulator.instances, accumulator.bytes, ownerLabel(accumulator.owners)));
}
rows.sort(Comparator.comparingLong(CellularShape::bytes).reversed());
return List.copyOf(rows);
}
private long owners(String id) {
Long known = owners.get(id);
if (known != null) {
return known;
}
owners.put(id, 0L);
long mask = 0L;
List<String> referrers = parents.get(id);
if (referrers == null) {
mask = bit(UNREFERENCED);
} else {
for (String parent : referrers) {
String category = category(dimension, parent);
mask |= isLibrary(category) ? owners(parent) : bit(category);
}
}
owners.put(id, mask);
return mask;
}
private long bit(String category) {
int index = categoryIndex.computeIfAbsent(category, name -> {
categoryNames.add(name);
return categoryNames.size() - 1;
});
if (index >= Long.SIZE) {
throw new IllegalStateException("More than " + Long.SIZE + " density function owner categories");
}
return 1L << index;
}
private String ownerLabel(long mask) {
if (mask == 0L) {
return UNREFERENCED;
}
List<String> labels = new ArrayList<>(Long.bitCount(mask));
for (int index = 0; index < categoryNames.size(); index++) {
if ((mask & (1L << index)) != 0L) {
labels.add(categoryNames.get(index));
}
}
labels.sort(String::compareTo);
return String.join("+", labels);
}
private String group(String id) {
int separator = id.indexOf(':');
String path = separator < 0 ? id : id.substring(separator + 1);
if (path.startsWith(dimensionPrefix)) {
path = path.substring(dimensionPrefix.length());
}
String[] segments = path.split("/");
if (segments.length == 1) {
return segments[0];
}
if (segments[0].equals("cell") || segments[0].equals("style")) {
return segments[0] + "/*/" + segments[segments.length - 1];
}
return segments[0] + "/" + segments[1];
}
private static boolean isLibrary(String category) {
return category.startsWith(CELLULAR) || category.startsWith(NOISE_STYLE);
}
private static String instanceKey(String id) {
int end = id.indexOf(':') + 1;
for (int segment = 0; segment < INSTANCE_SEGMENTS && end > 0; segment++) {
int slash = id.indexOf('/', end);
if (slash < 0) {
return id;
}
end = slash + 1;
}
return id.substring(0, end - 1);
}
private static List<CategoryBytes> rows(Map<String, CategoryAccumulator> accumulators, int limit) {
List<CategoryBytes> rows = new ArrayList<>(accumulators.size());
for (Map.Entry<String, CategoryAccumulator> item : accumulators.entrySet()) {
CategoryAccumulator accumulator = item.getValue();
long representative = 0;
for (long bytes : accumulator.representativeBytes.values()) {
representative += bytes;
}
rows.add(new CategoryBytes(item.getKey(), accumulator.files, accumulator.bytes, accumulator.nodes,
accumulator.representativeBytes.size(), accumulator.bytes - representative));
}
rows.sort(Comparator.comparingLong(CategoryBytes::bytes).reversed());
return List.copyOf(rows.subList(0, Math.min(limit, rows.size())));
}
private static String resourceId(String path, String folder) {
int marker = path.indexOf(folder);
if (!path.startsWith("data/") || marker < 0 || !path.endsWith(JSON)) {
return null;
}
return path.substring("data/".length(), marker) + ":" + path.substring(marker + folder.length(), path.length() - JSON.length());
}
private static long mix(long hash, long value) {
long mixed = hash ^ value;
mixed *= FNV_PRIME;
return mixed ^ (mixed >>> 29);
}
record Report(int files, long bytes, long nodes, List<CategoryBytes> categories, List<CategoryBytes> groups,
List<Bytes> libraryOwners, List<Bytes> largest, List<CellularShape> cellularShapes) {
int cellularInstances() {
int count = 0;
for (CellularShape shape : cellularShapes) {
count += shape.instances();
}
return count;
}
}
record CategoryBytes(String category, int files, long bytes, long nodes, int distinctShapes, long structurallyDuplicateBytes) {
}
record Bytes(String name, long bytes) {
}
record CellularShape(String example, String members, int instances, long bytes, String owners) {
}
private static final class Entry {
private final long bytes;
private final List<String> references = new ArrayList<>();
private long nodes;
private long shape;
private Entry(long bytes) {
this.bytes = bytes;
}
}
private static final class CategoryAccumulator {
private final Map<Long, Long> representativeBytes = new HashMap<>();
private int files;
private long bytes;
private long nodes;
private void add(Entry entry) {
files++;
bytes += entry.bytes;
nodes += entry.nodes;
representativeBytes.putIfAbsent(entry.shape, entry.bytes);
}
}
private static final class CellularAccumulator {
private final String example;
private final String layout;
private int instances;
private long bytes;
private long owners;
private CellularAccumulator(String example, String layout) {
this.example = example;
this.layout = layout;
}
}
}
@@ -1,6 +1,7 @@
package art.arcane.iris.probe;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.platform.ClasspathVanillaDataSource;
import art.arcane.iris.platform.bukkit.nms.BukkitGenerationRegistry;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.PlatformGenerationRegistry;
@@ -9,6 +10,7 @@ import art.arcane.iris.spi.PlatformBiomeWriter;
import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.iris.spi.PlatformScheduler;
import art.arcane.iris.spi.PlatformStructureHooks;
import art.arcane.iris.spi.VanillaDataSource;
import art.arcane.volmlib.nativelib.entity.NativeEntityType;
import art.arcane.volmlib.nativelib.item.NativeItem;
import art.arcane.volmlib.nativelib.minecraft26_2.modded.ModdedBlockState;
@@ -35,6 +37,7 @@ final class HeadlessNativePlatform implements IrisPlatform, PlatformRegistries,
private final NativeRegistryAccess nativeAccess;
private final PlatformBiomeWriter biomeWriter;
private final PlatformGenerationRegistry generationRegistry;
private final ClasspathVanillaDataSource vanillaData = new ClasspathVanillaDataSource(() -> SharedConstants.class);
private final NativeBlockResolver blocks = new NativeBlockResolver(this);
private final NativeBlockState air = blocks.getAir();
private final ConcurrentHashMap<String, NativeBlockState> states = new ConcurrentHashMap<>();
@@ -215,6 +218,11 @@ final class HeadlessNativePlatform implements IrisPlatform, PlatformRegistries,
return biomeWriter;
}
@Override
public VanillaDataSource vanillaData() {
return vanillaData;
}
@Override
public File dataFolder() {
return services.dataFolder();
@@ -4,6 +4,7 @@ import art.arcane.iris.pack.datapack.IrisDatapackCompiler;
import art.arcane.iris.pack.datapack.v263.DataFixerV263;
import art.arcane.volmlib.util.collection.KList;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
@@ -25,6 +26,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.stream.Stream;
final class HeadlessNativeRegistries implements AutoCloseable {
@@ -70,7 +72,7 @@ final class HeadlessNativeRegistries implements AutoCloseable {
}
}
private static HeadlessNativeRegistries load(Path directory) {
static HeadlessNativeRegistries load(Path directory) {
PackLocationInfo location = new PackLocationInfo("iris-headless", Component.literal("Iris"),
PackSource.WORLD, Optional.empty());
MultiPackResourceManager resources = new MultiPackResourceManager(PackType.SERVER_DATA, List.of(
@@ -78,12 +80,17 @@ final class HeadlessNativeRegistries implements AutoCloseable {
try {
RegistryAccess.Frozen builtins = RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY);
RegistryAccess.Frozen loaded;
RegistryAccess.Frozen dimensions;
try (ExecutorService executor = Executors.newFixedThreadPool(4)) {
loaded = RegistryDataLoader.load(resources, builtins.listRegistries().toList(),
RegistryDataLoader.WORLD_REGISTRIES, executor).join();
List<HolderLookup.RegistryLookup<?>> dimensionContext =
Stream.concat(builtins.listRegistries(), loaded.listRegistries()).toList();
dimensions = RegistryDataLoader.load(resources, dimensionContext,
RegistryDataLoader.DIMENSION_REGISTRIES, executor).join();
}
RegistryAccess.Frozen registries = new RegistryAccess.ImmutableRegistryAccess(
Stream.concat(builtins.registries(), loaded.registries())).freeze();
RegistryAccess.Frozen registries = new RegistryAccess.ImmutableRegistryAccess(Stream.of(
builtins.registries(), loaded.registries(), dimensions.registries()).flatMap(Function.identity())).freeze();
HeadlessNativeBootstrap.bindComponents(registries);
return new HeadlessNativeRegistries(directory, resources, registries);
} catch (RuntimeException failure) {
@@ -106,7 +113,7 @@ final class HeadlessNativeRegistries implements AutoCloseable {
delete(directory);
}
private static void delete(Path directory) throws IOException {
static void delete(Path directory) throws IOException {
try (Stream<Path> paths = Files.walk(directory)) {
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) {
Files.delete(path);
@@ -32,6 +32,7 @@ final class HeadlessNativeRuntime implements RealPackProbeSupport.RuntimeBinding
private final Path stagingRoot;
private NativeRegionTerrainWriter writer;
private HeadlessNativeRegistries nativeRegistries;
private File preparedPack;
private HolderLookup.Provider registries;
HeadlessNativeRuntime() {
@@ -60,12 +61,16 @@ final class HeadlessNativeRuntime implements RealPackProbeSupport.RuntimeBinding
@Override
public void prepare(IrisData data, IrisDimension dimension) {
try {
if (nativeRegistries != null) {
File pack = data.getDataFolder().getCanonicalFile();
if (nativeRegistries != null && !pack.equals(preparedPack)) {
throw new IllegalStateException("Headless native runtime supports one immutable pack per process");
}
nativeRegistries = HeadlessNativeRegistries.compile(data.getDataFolder());
if (nativeRegistries == null) {
nativeRegistries = HeadlessNativeRegistries.compile(data.getDataFolder());
preparedPack = pack;
writer = new NativeRegionTerrainWriter(nativeRegistries.registries());
}
registries = nativeRegistries.registries();
writer = new NativeRegionTerrainWriter(nativeRegistries.registries());
} catch (IOException failure) {
throw new UncheckedIOException("Cannot load native generation registries", failure);
}
@@ -92,6 +97,7 @@ final class HeadlessNativeRuntime implements RealPackProbeSupport.RuntimeBinding
if (nativeRegistries != null) {
nativeRegistries.close();
nativeRegistries = null;
preparedPack = null;
}
}
@@ -1,6 +1,8 @@
package art.arcane.iris.probe;
import art.arcane.volmlib.nativelib.terrain.NativeGenerationScope;
import art.arcane.volmlib.nativelib.terrain.structure.StructureWater;
import art.arcane.volmlib.nativelib.terrain.structure.StructureWaterRules;
import art.arcane.volmlib.nativelib.terrain.structure.StructureInjectionPolicy;
import art.arcane.volmlib.nativelib.terrain.structure.StructureOwnershipRecordView;
import art.arcane.volmlib.nativelib.terrain.structure.StructurePlacementDecision;
@@ -159,6 +161,11 @@ final class HeadlessStructurePlanner {
policies.injection().discard(plan.structureKey(), chunk.getPos().x(), chunk.getPos().z());
continue;
}
if (!StructureWaterRules.admitsStart(plan, false, policies.water(), NativeStructureTerrainIntegrator.pieceFootprints(generated))) {
chunk.setStartForStructure(structure, StructureStart.INVALID_START);
policies.injection().discard(plan.structureKey(), chunk.getPos().x(), chunk.getPos().z());
continue;
}
BoundingBox envelope = NativeStructureReferenceEnvelope.referenceBounds(generated, structure,
plan.terrain(), plan.structureKey());
policies.injection().record(plan, NativeStructureOwnershipFingerprint.capture(plan.structureKey(), generated, envelope));
@@ -319,11 +326,12 @@ final class HeadlessStructurePlanner {
record Policies<P extends StructureStartPlan, O extends StructureOwnershipRecordView<O>>(
StructureInjectionPolicy<P> injection, StructureReferencePolicy<P, O> references,
Predicate<BoundingBox> allowsFootprint) {
Predicate<BoundingBox> allowsFootprint, StructureWater water) {
Policies {
Objects.requireNonNull(injection, "injection");
Objects.requireNonNull(references, "references");
Objects.requireNonNull(allowsFootprint, "allowsFootprint");
Objects.requireNonNull(water, "water");
}
}
@@ -1,5 +1,6 @@
package art.arcane.iris.probe;
import art.arcane.iris.structure.placement.IrisStructureWater;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.platform.bukkit.nms.BukkitBiomePolicy;
import art.arcane.iris.structure.nativegen.IrisStructurePolicy;
@@ -63,7 +64,8 @@ final class HeadlessTerrainContext implements AutoCloseable {
IrisStructurePolicy policy = new IrisStructurePolicy(engine);
policies = new HeadlessStructurePlanner.Policies<>(policy, policy,
bounds -> engine.getComplex().allowsNewGenerationFootprint(
bounds.minX(), bounds.minZ(), bounds.maxX(), bounds.maxZ()));
bounds.minX(), bounds.minZ(), bounds.maxX(), bounds.maxZ()),
IrisStructureWater.world(engine));
NativeBiomeRegistryImpl registry = new NativeBiomeRegistryImpl(runtime.registries().lookupOrThrow(Registries.BIOME));
biomes = new BukkitBiomePolicy<>(new BukkitBiomePolicy.RuntimeOptions<>(seed, engine, null, () -> registry), registry);
serialization = new HeadlessChunkSerialization.Context(new StructurePieceSerializationContext(
@@ -2,8 +2,9 @@ package art.arcane.iris.probe;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.concurrent.MultiBurst;
import art.arcane.iris.generation.hydrology.HydrologyTileCache;
import art.arcane.iris.generation.hydrology.runtime.IrisHydrologyRuntime;
import art.arcane.iris.generation.hydrology.engine.HydrologyPregeneration;
import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.world.pregen.PregenHydrology;
import art.arcane.iris.world.pregen.PregenPerformanceProfile;
import net.minecraft.core.registries.Registries;
@@ -31,11 +32,16 @@ import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Set;
public final class OfflineRegionGenerator {
private static final int CHUNKS_PER_HYDROLOGY_REGION = WindowKey.SIZE >> 4;
private OfflineRegionGenerator() {
}
@@ -97,14 +103,13 @@ public final class OfflineRegionGenerator {
PregenPerformanceProfile.apply(session.engine());
System.out.println("generationProfile=pregen noiseCacheSize=" + IrisSettings.get().getPerformance().getNoiseCacheSize()
+ " burstParallelism=" + MultiBurst.burst.parallelism() + " multicore=true");
IrisHydrologyRuntime hydrology = session.engine().getComplex().getHydrologyRuntime();
try (HydrologyTileCache.PregenerationScope hydrologyScope = hydrology == null ? null
: hydrology.preparePregeneration(configuration.hydrologyArea());
try (HydrologyPregeneration pregeneration = PregenHydrology.open(session.engine());
HeadlessTerrainContext context = HeadlessTerrainContext.create(new HeadlessTerrainContext.Options(
session.engine(), runtime, staged.resolve("templates"), configuration.levelKey(),
configuration.noiseSettings(), spigot));
RegionGenerationWindow workers = new RegionGenerationWindow(configuration.parallelism(),
RegionGenerationWindow.Policy.STANDALONE)) {
PregenHydrology.prepareAll(pregeneration, configuration.hydrologyRegions());
HeadlessRegionTerrain.Session rolling = new HeadlessRegionTerrain.Session(workers);
Path regionDirectory = session.engine().getTarget().getWorld().worldFolder().toPath().resolve("region");
Files.createDirectory(regionDirectory);
@@ -214,7 +219,11 @@ public final class OfflineRegionGenerator {
}
private static void force(Path path) throws IOException {
try (FileChannel channel = FileChannel.open(path, Files.isDirectory(path)
boolean directory = Files.isDirectory(path);
if (directory && File.separatorChar == '\\') {
return;
}
try (FileChannel channel = FileChannel.open(path, directory
? StandardOpenOption.READ : StandardOpenOption.WRITE)) {
channel.force(true);
}
@@ -239,14 +248,27 @@ public final class OfflineRegionGenerator {
}
}
HydrologyTileCache.PregenerationArea hydrologyArea() {
List<long[]> hydrologyRegions() {
int halo = NativeRegionPlan.terrainHalo();
long minimumX = ((long) chunkX - halo) * 16L;
long minimumZ = ((long) chunkZ - halo) * 16L;
long maximumX = ((long) chunkX + (long) width * regionsX + halo) * 16L - 1L;
long maximumZ = ((long) chunkZ + (long) width * regionsZ + halo) * 16L - 1L;
return new HydrologyTileCache.PregenerationArea(Math.toIntExact((minimumX + maximumX) / 2L),
Math.toIntExact((minimumZ + maximumZ) / 2L), minimumX, minimumZ, maximumX, maximumZ);
Set<Long> seen = new HashSet<>();
List<long[]> regions = new ArrayList<>();
for (int row = 0; row < regionsZ; row++) {
for (int column = 0; column < regionsX; column++) {
int regionX = row % 2 == 0 ? column : regionsX - column - 1;
int minimumX = Math.floorDiv(chunkX + regionX * width - halo, CHUNKS_PER_HYDROLOGY_REGION);
int maximumX = Math.floorDiv(chunkX + (regionX + 1) * width - 1 + halo, CHUNKS_PER_HYDROLOGY_REGION);
int minimumZ = Math.floorDiv(chunkZ + row * width - halo, CHUNKS_PER_HYDROLOGY_REGION);
int maximumZ = Math.floorDiv(chunkZ + (row + 1) * width - 1 + halo, CHUNKS_PER_HYDROLOGY_REGION);
for (int hydrologyZ = minimumZ; hydrologyZ <= maximumZ; hydrologyZ++) {
for (int hydrologyX = minimumX; hydrologyX <= maximumX; hydrologyX++) {
if (seen.add(((long) hydrologyX << 32) | (hydrologyZ & 0xFFFFFFFFL))) {
regions.add(new long[]{hydrologyX, hydrologyZ});
}
}
}
}
}
return regions;
}
static Configuration parse(String[] arguments) throws IOException {
@@ -0,0 +1,39 @@
package art.arcane.iris.probe;
import io.papermc.paper.registry.PaperRegistryAccess;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
final class PaperRegistryScope implements AutoCloseable {
private final Map<Object, Object> registries;
private final Map<Object, Object> previous;
private PaperRegistryScope(Map<Object, Object> registries) {
this.registries = registries;
this.previous = new HashMap<>(registries);
registries.clear();
}
static PaperRegistryScope open() {
return new PaperRegistryScope(registries());
}
@Override
public void close() {
registries.clear();
registries.putAll(previous);
}
@SuppressWarnings("unchecked")
private static Map<Object, Object> registries() {
try {
Field field = PaperRegistryAccess.class.getDeclaredField("registries");
field.setAccessible(true);
return (Map<Object, Object>) field.get(PaperRegistryAccess.instance());
} catch (ReflectiveOperationException failure) {
throw new IllegalStateException("Paper registry access has no registries map to isolate", failure);
}
}
}
@@ -0,0 +1,301 @@
package art.arcane.iris.probe;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import net.minecraft.core.Holder;
import net.minecraft.core.QuartPos;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.util.datafix.DataFixers;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelHeightAccessor;
import net.minecraft.world.level.StructureManager;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeManager;
import net.minecraft.world.level.biome.BiomeResolver;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.PalettedContainerFactory;
import net.minecraft.world.level.chunk.ProtoChunk;
import net.minecraft.world.level.chunk.UpgradeData;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
import net.minecraft.world.level.levelgen.NoiseChunk;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.NoiseSettings;
import net.minecraft.world.level.levelgen.RandomState;
import net.minecraft.world.level.levelgen.WorldGenerationContext;
import net.minecraft.world.level.levelgen.blending.Blender;
import net.minecraft.world.level.levelgen.densityfunction.DensityFunction;
import net.minecraft.world.level.levelgen.densityfunction.DensityVolume;
import net.minecraft.world.level.levelgen.densityfunction.SamplerContext;
import net.minecraft.world.level.levelgen.densityfunction.ScopedDensityBuffer;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
import net.minecraft.world.level.storage.LevelStorageSource;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.Predicate;
import java.util.stream.Stream;
public final class WorldgenExportSampler implements AutoCloseable {
private static final String DENSITY_FUNCTIONS = "/worldgen/density_function/";
private static final int CHUNK_WIDTH = 16;
private static final Method CREATE_NOISE_CHUNK = generatorMethod("createNoiseChunk", ChunkAccess.class, StructureManager.class, Blender.class,
RandomState.class, NoiseSettings.class);
private static final Method DO_FILL = generatorMethod("doFill", NoiseChunk.class, ChunkAccess.class);
private final HeadlessNativeRegistries loaded;
private final NoiseBasedChunkGenerator generator;
private final RandomState randomState;
private final ThreadLocal<BiomeResolver> resolvers;
private final LevelHeightAccessor heights;
private final SortedSet<String> densityFunctionIds;
private final ThreadLocal<SamplerContext> densityContexts = ThreadLocal.withInitial(() -> SamplerContext.builder().enableCaches().build());
private final PalettedContainerFactory containers;
private final long seed;
private final long biomeZoomSeed;
private WorldgenExportSampler(HeadlessNativeRegistries loaded, LevelStem stem, long seed, SortedSet<String> densityFunctionIds) {
this.loaded = loaded;
if (!(stem.generator() instanceof NoiseBasedChunkGenerator noiseGenerator)) {
throw new IllegalStateException("Exported dimension uses " + stem.generator().getClass().getSimpleName() + ", not a noise generator");
}
this.generator = noiseGenerator;
this.randomState = RandomState.create(loaded.registries().lookupOrThrow(Registries.NOISE), seed, noiseGenerator.generatorSettings().value());
this.resolvers = ThreadLocal.withInitial(() -> noiseGenerator.getBiomeSource().createCachingResolver(randomState));
DimensionType type = stem.type().value();
this.heights = LevelHeightAccessor.create(type.minY(), type.height());
this.densityFunctionIds = densityFunctionIds;
this.containers = PalettedContainerFactory.create(loaded.registries());
this.seed = seed;
this.biomeZoomSeed = BiomeManager.obfuscateSeed(seed);
}
public static WorldgenExportSampler open(Map<String, byte[]> files, WorldgenExportMode mode, String dimensionId, long seed) throws IOException {
Objects.requireNonNull(mode);
Identifier dimension = Identifier.parse(dimensionId);
HeadlessNativeBootstrap.initialize();
Path directory = Files.createTempDirectory("iris-worldgen-export-");
HeadlessNativeRegistries loaded;
try {
for (Map.Entry<String, byte[]> file : files.entrySet()) {
Path target = directory.resolve(file.getKey()).normalize();
if (!target.startsWith(directory)) {
throw new IllegalArgumentException("Export file escapes the datapack root: " + file.getKey());
}
Files.createDirectories(target.getParent());
Files.write(target, file.getValue());
}
try (PaperRegistryScope scope = PaperRegistryScope.open()) {
loaded = HeadlessNativeRegistries.load(directory);
}
} catch (IOException | RuntimeException failure) {
HeadlessNativeRegistries.delete(directory);
throw failure;
}
try {
return new WorldgenExportSampler(loaded, stem(loaded.registries(), mode, dimension), seed, densityFunctionIds(files));
} catch (RuntimeException failure) {
loaded.close();
throw failure;
}
}
public static WorldgenExportSampler open(Path datapack, WorldgenExportMode mode, String dimensionId, long seed) throws IOException {
return open(files(datapack), mode, dimensionId, seed);
}
public float density(String functionId, int x, int y, int z) {
DensityFunction function = loaded.registries().lookupOrThrow(Registries.DENSITY_FUNCTION)
.getOrThrow(ResourceKey.create(Registries.DENSITY_FUNCTION, Identifier.parse(functionId))).value();
return randomState.getSampler(function).sampleValue(densityContexts.get(), x, y, z);
}
public float[] densityChunk(DensityFunction function, int chunkX, int chunkZ) {
DensityVolume volume = new DensityVolume(CHUNK_WIDTH, heights.getHeight(), CHUNK_WIDTH, chunkX * CHUNK_WIDTH, heights.getMinY(), chunkZ * CHUNK_WIDTH);
return sampleVolume(function, volume);
}
public DensityFunction finalDensity() {
return generator.generatorSettings().value().noiseRouter().finalDensity();
}
public int baseHeight(int x, int z) {
return generator.getBaseHeight(x, z, Heightmap.Types.WORLD_SURFACE_WG, heights, randomState);
}
public int floorHeight(int x, int z) {
return generator.getBaseHeight(x, z, Heightmap.Types.OCEAN_FLOOR_WG, heights, randomState);
}
public ProtoChunk terrainChunk(int chunkX, int chunkZ) {
ProtoChunk chunk = new ProtoChunk(new ChunkPos(chunkX, chunkZ), UpgradeData.EMPTY, heights, containers, null);
NoiseGeneratorSettings settings = generator.generatorSettings().value();
NoiseSettings noise = settings.noiseSettings().clampToHeightAccessor(chunk.getHeightAccessorForGeneration());
try (NoiseChunk noiseChunk = (NoiseChunk) invoke(CREATE_NOISE_CHUNK, chunk, NoStructures.INSTANCE, Blender.empty(), randomState, noise)) {
invoke(DO_FILL, noiseChunk, chunk);
randomState.surfaceSystem().buildSurface(randomState, new BiomeManager(resolvers.get(), biomeZoomSeed),
new WorldGenerationContext(generator, chunk.getHeightAccessorForGeneration()), chunk, noiseChunk, settings.materialRule().value(), null);
}
return chunk;
}
public StructureStart structureStart(String structureId, int chunkX, int chunkZ) throws IOException {
Holder.Reference<Structure> structure = loaded.registries().lookupOrThrow(Registries.STRUCTURE)
.getOrThrow(ResourceKey.create(Registries.STRUCTURE, Identifier.parse(structureId)));
Path storageRoot = Files.createTempDirectory("iris-worldgen-export-structures-");
try (LevelStorageSource.LevelStorageAccess storage = LevelStorageSource.createDefault(storageRoot).createAccess("export")) {
StructureTemplateManager templates = new StructureTemplateManager(loaded.resources(), storage, DataFixers.getDataFixer(),
loaded.registries().lookupOrThrow(Registries.BLOCK));
return structure.value().generate(structure, Level.OVERWORLD, loaded.registries(), generator, generator.getBiomeSource(),
randomState.createClimateSampler(SamplerContext.builder().enableCaches().build()), randomState, templates, seed,
new ChunkPos(chunkX, chunkZ), 0, heights, structure.value().biomes()::contains);
} finally {
HeadlessNativeRegistries.delete(storageRoot);
}
}
public String biome(int x, int y, int z) {
Holder<Biome> biome = resolvers.get().getNoiseBiome(QuartPos.fromBlock(x), QuartPos.fromBlock(y), QuartPos.fromBlock(z));
return biome.unwrapKey().orElseThrow().identifier().toString();
}
public Set<String> possibleBiomes() {
Set<String> biomes = new TreeSet<>();
for (Holder<Biome> biome : generator.getBiomeSource().possibleBiomes()) {
biomes.add(biome.unwrapKey().orElseThrow().identifier().toString());
}
return biomes;
}
public SortedSet<String> densityFunctionIds() {
return densityFunctionIds;
}
public int minY() {
return heights.getMinY();
}
public int height() {
return heights.getHeight();
}
public int seaLevel() {
return generator.getSeaLevel();
}
public RegistryAccess registries() {
return loaded.registries();
}
@Override
public void close() throws IOException {
loaded.close();
}
private float[] sampleVolume(DensityFunction function, DensityVolume volume) {
try (ScopedDensityBuffer buffer = randomState.getSampler(function).bind(densityContexts.get()).sampleVolume(volume)) {
float[] values = new float[volume.size()];
for (int index = 0; index < values.length; index++) {
values[index] = buffer.get(index);
}
return values;
}
}
private Object invoke(Method method, Object... arguments) {
try {
return method.invoke(generator, arguments);
} catch (InvocationTargetException failure) {
if (failure.getCause() instanceof RuntimeException runtime) {
throw runtime;
}
if (failure.getCause() instanceof Error error) {
throw error;
}
throw new IllegalStateException("Terrain stage " + method.getName() + " failed", failure.getCause());
} catch (IllegalAccessException failure) {
throw new IllegalStateException("Terrain stage " + method.getName() + " is not accessible", failure);
}
}
private static Method generatorMethod(String name, Class<?>... parameters) {
try {
Method method = NoiseBasedChunkGenerator.class.getDeclaredMethod(name, parameters);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException failure) {
throw new IllegalStateException("NoiseBasedChunkGenerator has no terrain stage " + name, failure);
}
}
private static LevelStem stem(RegistryAccess registries, WorldgenExportMode mode, Identifier dimension) {
return switch (mode) {
case PRESET -> registries.lookupOrThrow(Registries.WORLD_PRESET)
.getOrThrow(ResourceKey.create(Registries.WORLD_PRESET, dimension)).value().overworld()
.orElseThrow(() -> new IllegalStateException("World preset " + dimension + " has no overworld"));
case DIMENSION -> levelStem(registries, dimension);
case OVERWORLD -> levelStem(registries, LevelStem.OVERWORLD.identifier());
};
}
private static LevelStem levelStem(RegistryAccess registries, Identifier id) {
return registries.lookupOrThrow(Registries.LEVEL_STEM).getOrThrow(ResourceKey.create(Registries.LEVEL_STEM, id)).value();
}
private static SortedMap<String, byte[]> files(Path datapack) throws IOException {
if (!Files.isDirectory(datapack)) {
throw new IOException("Exported datapack " + datapack + " is not a directory");
}
SortedMap<String, byte[]> files = new TreeMap<>();
try (Stream<Path> paths = Files.walk(datapack)) {
List<Path> regular = paths.filter(Files::isRegularFile).toList();
for (Path file : regular) {
files.put(datapack.relativize(file).toString().replace('\\', '/'), Files.readAllBytes(file));
}
}
return files;
}
private static SortedSet<String> densityFunctionIds(Map<String, byte[]> files) {
SortedSet<String> ids = new TreeSet<>();
for (String path : files.keySet()) {
int marker = path.indexOf(DENSITY_FUNCTIONS);
if (path.startsWith("data/") && marker > 0 && path.endsWith(".json")) {
String namespace = path.substring("data/".length(), marker);
ids.add(namespace + ":" + path.substring(marker + DENSITY_FUNCTIONS.length(), path.length() - ".json".length()));
}
}
return ids;
}
private static final class NoStructures extends StructureManager {
private static final NoStructures INSTANCE = new NoStructures();
private NoStructures() {
super(null, null, null);
}
@Override
public List<StructureStart> startsForStructure(int chunkX, int chunkZ, Predicate<Structure> predicate) {
return List.of();
}
}
}
@@ -0,0 +1,394 @@
package art.arcane.iris.probe;
import io.papermc.paper.configuration.WorldConfiguration;
import net.minecraft.core.Holder;
import net.minecraft.core.QuartPos;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelHeightAccessor;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeManager;
import net.minecraft.world.level.biome.BiomeResolver;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.PalettedContainerFactory;
import net.minecraft.world.level.chunk.ProtoChunk;
import net.minecraft.world.level.chunk.UpgradeData;
import net.minecraft.world.level.chunk.status.ChunkStatus;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.levelgen.Aquifer;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
import net.minecraft.world.level.levelgen.NoiseChunk;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.NoiseSettings;
import net.minecraft.world.level.levelgen.RandomState;
import net.minecraft.world.level.levelgen.WorldGenerationContext;
import net.minecraft.world.level.levelgen.blending.Blender;
import net.minecraft.world.level.levelgen.densityfunction.DensityVolume;
import net.minecraft.world.level.levelgen.material.rule.MaterialRule;
import org.spigotmc.SpigotWorldConfig;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SplittableRandom;
import java.util.function.Supplier;
final class WorldgenStageBench {
private static final int SAMPLE_RADIUS_BLOCKS = 32_768;
private static final double NANOS_PER_MILLI = 1_000_000.0;
private static final double NANOS_PER_MICRO = 1_000.0;
private static final ThreadMXBean THREADS = ManagementFactory.getThreadMXBean();
private final String label;
private final NoiseBasedChunkGenerator generator;
private final NoiseGeneratorSettings settings;
private final RandomState randomState;
private final LevelHeightAccessor heights;
private final PalettedContainerFactory containers;
private final long seed;
private final Method fill;
private final Aquifer.FluidPicker fluidPicker;
private final BiomeResolver uncached;
private final Level surfaceLevel;
WorldgenStageBench(Options options) {
label = options.label();
if (!(options.stem().generator() instanceof NoiseBasedChunkGenerator noiseGenerator)) {
throw new IllegalStateException(label + " uses " + options.stem().generator().getClass().getSimpleName() + ", not a noise generator");
}
generator = noiseGenerator;
settings = noiseGenerator.generatorSettings().value();
seed = options.seed();
randomState = RandomState.create(options.registries().lookupOrThrow(Registries.NOISE), seed, settings);
DimensionType type = options.stem().type().value();
heights = LevelHeightAccessor.create(type.minY(), type.height());
containers = PalettedContainerFactory.create(options.registries());
fill = fillMethod();
fluidPicker = fluidPicker(noiseGenerator);
uncached = noiseGenerator.getBiomeSource().createUncachedResolver(randomState);
surfaceLevel = paperConfiguredLevel();
}
String label() {
return label;
}
NoiseGeneratorSettings settings() {
return settings;
}
void chunks(int originChunkX, int originChunkZ, int side, ChunkSamples samples) {
int ring = side + 2;
Map<Long, ProtoChunk> chunks = new HashMap<>(ring * ring * 2);
for (int dz = -1; dz <= side; dz++) {
for (int dx = -1; dx <= side; dx++) {
ChunkPos position = new ChunkPos(originChunkX + dx, originChunkZ + dz);
ProtoChunk chunk = new ProtoChunk(position, UpgradeData.EMPTY, heights, containers, null);
long started = System.nanoTime();
long startedCpu = THREADS.getCurrentThreadCpuTime();
generator.createBiomes(randomState, Blender.empty(), null, chunk).join();
samples.biomes.add(System.nanoTime() - started, THREADS.getCurrentThreadCpuTime() - startedCpu);
chunk.setPersistedStatus(ChunkStatus.BIOMES);
chunks.put(ChunkPos.pack(position.x(), position.z()), chunk);
}
}
RegionBiomes region = new RegionBiomes(chunks, uncached);
BiomeManager biomeManager = new BiomeManager(region, BiomeManager.obfuscateSeed(seed));
MaterialRule materialRule = settings.materialRule().value();
for (int dz = 0; dz < side; dz++) {
for (int dx = 0; dx < side; dx++) {
int chunkX = originChunkX + dx;
int chunkZ = originChunkZ + dz;
ProtoChunk chunk = chunks.get(ChunkPos.pack(chunkX, chunkZ));
Set<Holder<Biome>> possible = possibleBiomes(chunks, chunkX, chunkZ);
long started = System.nanoTime();
long startedCpu = THREADS.getCurrentThreadCpuTime();
try (NoiseChunk noiseChunk = new NoiseChunk(randomState, null, settings, fluidPicker, Blender.empty(), volume(chunk))) {
fill(noiseChunk, chunk);
long filled = System.nanoTime();
long filledCpu = THREADS.getCurrentThreadCpuTime();
randomState.surfaceSystem().buildSurface(randomState, biomeManager,
new WorldGenerationContext(generator, chunk.getHeightAccessorForGeneration(), surfaceLevel), chunk, noiseChunk, materialRule, possible);
samples.surface.add(System.nanoTime() - filled, THREADS.getCurrentThreadCpuTime() - filledCpu);
samples.noise.add(filled - started, filledCpu - startedCpu);
}
ChunkPos position = chunk.getPos();
long carverStarted = System.nanoTime();
long carverStartedCpu = THREADS.getCurrentThreadCpuTime();
uncached.getNoiseBiome(QuartPos.fromBlock(position.getMinBlockX()), 0, QuartPos.fromBlock(position.getMinBlockZ()));
samples.carverBiome.add(System.nanoTime() - carverStarted, THREADS.getCurrentThreadCpuTime() - carverStartedCpu);
samples.chunks++;
}
}
samples.biomeFallbacks += region.fallbacks();
}
void uncachedBiome(CallBudget budget, CallSamples samples) {
SplittableRandom random = new SplittableRandom(seed ^ 0x5DEECE66DL ^ samples.count);
int minQuart = QuartPos.fromBlock(heights.getMinY());
int quartHeight = QuartPos.fromBlock(heights.getHeight());
long deadline = System.nanoTime() + budget.limitNanos();
long startedCpu = THREADS.getCurrentThreadCpuTime();
int taken = 0;
while (taken < budget.calls() && (taken < budget.minimumCalls() || System.nanoTime() < deadline)) {
int quartX = QuartPos.fromBlock(random.nextInt(-SAMPLE_RADIUS_BLOCKS, SAMPLE_RADIUS_BLOCKS));
int quartY = minQuart + random.nextInt(quartHeight);
int quartZ = QuartPos.fromBlock(random.nextInt(-SAMPLE_RADIUS_BLOCKS, SAMPLE_RADIUS_BLOCKS));
long started = System.nanoTime();
uncached.getNoiseBiome(quartX, quartY, quartZ);
samples.wall.add(System.nanoTime() - started);
taken++;
}
samples.finish(taken, THREADS.getCurrentThreadCpuTime() - startedCpu);
}
void baseHeight(CallBudget budget, Heightmap.Types type, CallSamples samples) {
SplittableRandom random = new SplittableRandom(seed ^ type.ordinal() ^ 0x2545F4914F6CDD1DL ^ samples.count);
long deadline = System.nanoTime() + budget.limitNanos();
long startedCpu = THREADS.getCurrentThreadCpuTime();
int taken = 0;
while (taken < budget.calls() && (taken < budget.minimumCalls() || System.nanoTime() < deadline)) {
int x = random.nextInt(-SAMPLE_RADIUS_BLOCKS, SAMPLE_RADIUS_BLOCKS);
int z = random.nextInt(-SAMPLE_RADIUS_BLOCKS, SAMPLE_RADIUS_BLOCKS);
long started = System.nanoTime();
generator.getBaseHeight(x, z, type, heights, randomState);
samples.wall.add(System.nanoTime() - started);
taken++;
}
samples.finish(taken, THREADS.getCurrentThreadCpuTime() - startedCpu);
}
void baseColumn(CallBudget budget, CallSamples samples) {
SplittableRandom random = new SplittableRandom(seed ^ 0x9E3779B97F4A7C15L ^ samples.count);
long deadline = System.nanoTime() + budget.limitNanos();
long startedCpu = THREADS.getCurrentThreadCpuTime();
int taken = 0;
while (taken < budget.calls() && (taken < budget.minimumCalls() || System.nanoTime() < deadline)) {
int x = random.nextInt(-SAMPLE_RADIUS_BLOCKS, SAMPLE_RADIUS_BLOCKS);
int z = random.nextInt(-SAMPLE_RADIUS_BLOCKS, SAMPLE_RADIUS_BLOCKS);
long started = System.nanoTime();
generator.getBaseColumn(x, z, heights, randomState);
samples.wall.add(System.nanoTime() - started);
taken++;
}
samples.finish(taken, THREADS.getCurrentThreadCpuTime() - startedCpu);
}
private void fill(NoiseChunk noiseChunk, ChunkAccess chunk) {
try {
fill.invoke(generator, noiseChunk, chunk);
} catch (IllegalAccessException failure) {
throw new IllegalStateException("Cannot invoke NoiseBasedChunkGenerator.doFill for " + label, failure);
} catch (InvocationTargetException failure) {
if (failure.getCause() instanceof RuntimeException runtime) {
throw runtime;
}
throw new IllegalStateException("Noise fill failed for " + label, failure.getCause());
}
}
private DensityVolume volume(ChunkAccess chunk) {
NoiseSettings noise = settings.noiseSettings().clampToHeightAccessor(chunk.getHeightAccessorForGeneration());
ChunkPos position = chunk.getPos();
return new DensityVolume(16, noise.height(), 16, position.getMinBlockX(), noise.minY(), position.getMinBlockZ());
}
private static Set<Holder<Biome>> possibleBiomes(Map<Long, ProtoChunk> chunks, int chunkX, int chunkZ) {
Set<Holder<Biome>> possible = new HashSet<>();
for (int dz = -1; dz <= 1; dz++) {
for (int dx = -1; dx <= 1; dx++) {
chunks.get(ChunkPos.pack(chunkX + dx, chunkZ + dz)).collectBiomesInPalette(possible);
}
}
return possible;
}
private static Method fillMethod() {
try {
Method method = NoiseBasedChunkGenerator.class.getDeclaredMethod("doFill", NoiseChunk.class, ChunkAccess.class);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException failure) {
throw new IllegalStateException("NoiseBasedChunkGenerator has no doFill(NoiseChunk, ChunkAccess)", failure);
}
}
@SuppressWarnings("unchecked")
private static Aquifer.FluidPicker fluidPicker(NoiseBasedChunkGenerator generator) {
try {
Field field = NoiseBasedChunkGenerator.class.getDeclaredField("globalFluidPicker");
field.setAccessible(true);
return ((Supplier<Aquifer.FluidPicker>) field.get(generator)).get();
} catch (ReflectiveOperationException failure) {
throw new IllegalStateException("NoiseBasedChunkGenerator has no globalFluidPicker supplier", failure);
}
}
private static Level paperConfiguredLevel() {
try {
Constructor<WorldConfiguration> constructor = WorldConfiguration.class.getDeclaredConstructor(SpigotWorldConfig.class, Identifier.class);
constructor.setAccessible(true);
WorldConfiguration configuration = constructor.newInstance(null, Identifier.withDefaultNamespace("overworld"));
configuration.environment = configuration.new Environment();
Class<?> unsafeType = Class.forName("sun.misc.Unsafe");
Field unsafeField = unsafeType.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Method allocate = unsafeType.getMethod("allocateInstance", Class.class);
Level level = (Level) allocate.invoke(unsafeField.get(null), ServerLevel.class);
Field paperConfig = Level.class.getDeclaredField("paperConfig");
paperConfig.setAccessible(true);
paperConfig.set(level, configuration);
return level;
} catch (ReflectiveOperationException failure) {
throw new IllegalStateException("Cannot build the Paper world configuration that surface rules read", failure);
}
}
record Options(String label, LevelStem stem, RegistryAccess registries, long seed) {
Options {
Objects.requireNonNull(label, "label");
Objects.requireNonNull(stem, "stem");
Objects.requireNonNull(registries, "registries");
}
}
record CallBudget(int calls, int minimumCalls, long limitNanos) {
}
record ChunkTimings(int chunks, StageTiming biomes, StageTiming noise, StageTiming surface, StageTiming carverBiome,
long biomeFallbacks) {
double totalMean() {
return biomes.wall().mean() + noise.wall().mean() + surface.wall().mean() + carverBiome.wall().mean();
}
double totalCpuMean() {
return biomes.cpu().mean() + noise.cpu().mean() + surface.cpu().mean() + carverBiome.cpu().mean();
}
}
record StageTiming(Summary wall, Summary cpu) {
}
record CallTiming(Summary wall, int calls, double cpuMean) {
}
record Summary(int count, double mean, double median, double p90, double min, double max) {
private static Summary of(long[] nanos, double unit) {
if (nanos.length == 0) {
return new Summary(0, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN);
}
long[] sorted = nanos.clone();
Arrays.sort(sorted);
double total = 0.0;
for (long value : sorted) {
total += value;
}
return new Summary(sorted.length, total / sorted.length / unit, percentile(sorted, 0.5) / unit,
percentile(sorted, 0.9) / unit, sorted[0] / unit, sorted[sorted.length - 1] / unit);
}
private static double percentile(long[] sorted, double fraction) {
int index = (int) Math.min(sorted.length - 1, Math.round(fraction * (sorted.length - 1)));
return sorted[index];
}
}
static final class ChunkSamples {
private final StageSamples biomes = new StageSamples();
private final StageSamples noise = new StageSamples();
private final StageSamples surface = new StageSamples();
private final StageSamples carverBiome = new StageSamples();
private int chunks;
private long biomeFallbacks;
ChunkTimings timings() {
return new ChunkTimings(chunks, biomes.timing(), noise.timing(), surface.timing(), carverBiome.timing(), biomeFallbacks);
}
}
static final class CallSamples {
private final Samples wall = new Samples();
private int count;
private long cpuNanos;
CallTiming timing() {
return new CallTiming(Summary.of(wall.values(), NANOS_PER_MICRO), count,
count == 0 ? Double.NaN : cpuNanos / (double) count / NANOS_PER_MICRO);
}
private void finish(int calls, long cpu) {
count += calls;
cpuNanos += cpu;
}
}
private static final class StageSamples {
private final Samples wall = new Samples();
private final Samples cpu = new Samples();
private void add(long wallNanos, long cpuNanos) {
wall.add(wallNanos);
cpu.add(cpuNanos);
}
private StageTiming timing() {
return new StageTiming(Summary.of(wall.values(), NANOS_PER_MILLI), Summary.of(cpu.values(), NANOS_PER_MILLI));
}
}
private static final class Samples {
private long[] values = new long[64];
private int size;
private void add(long value) {
if (size == values.length) {
values = Arrays.copyOf(values, size * 2);
}
values[size++] = value;
}
private long[] values() {
return Arrays.copyOf(values, size);
}
}
private static final class RegionBiomes implements BiomeResolver {
private final Map<Long, ProtoChunk> chunks;
private final BiomeResolver fallback;
private long fallbacks;
private RegionBiomes(Map<Long, ProtoChunk> chunks, BiomeResolver fallback) {
this.chunks = chunks;
this.fallback = fallback;
}
@Override
public Holder<Biome> getNoiseBiome(int quartX, int quartY, int quartZ) {
ProtoChunk chunk = chunks.get(ChunkPos.pack(QuartPos.toSection(quartX), QuartPos.toSection(quartZ)));
if (chunk == null) {
fallbacks++;
return fallback.getNoiseBiome(quartX, quartY, quartZ);
}
return chunk.getNoiseBiome(quartX, quartY, quartZ);
}
private long fallbacks() {
return fallbacks;
}
}
}
@@ -0,0 +1,61 @@
package art.arcane.iris.probe.fidelity;
import art.arcane.iris.probe.WorldgenExportSampler;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
public final class VanillaNoiseColumnSource implements ColumnSource {
private final WorldgenExportSampler sampler;
private final Map<String, String> loadKeyByBiomeId;
private final int minY;
private final int maxY;
private final int seaLevel;
public VanillaNoiseColumnSource(WorldgenExportSampler sampler, Map<String, String> loadKeyByBiomeId) {
this.sampler = Objects.requireNonNull(sampler, "sampler");
this.loadKeyByBiomeId = Map.copyOf(loadKeyByBiomeId);
this.minY = sampler.minY();
this.maxY = sampler.minY() + sampler.height();
this.seaLevel = sampler.seaLevel();
}
@Override
public String label() {
return "vanilla:26.3";
}
@Override
public int minY() {
return minY;
}
@Override
public int maxY() {
return maxY;
}
@Override
public FidelityColumn column(int x, int z) {
int floor = sampler.floorHeight(x, z);
int terrainY = floor - 1;
boolean wet = floor < seaLevel && sampler.baseHeight(x, z) > floor;
return new FidelityColumn(loadKey(x, Math.max(minY, terrainY), z), terrainY, wet);
}
@Override
public void close() throws IOException {
sampler.close();
}
private String loadKey(int x, int y, int z) {
String biomeId = sampler.biome(x, y, z);
String loadKey = loadKeyByBiomeId.get(biomeId);
if (loadKey == null) {
throw new IllegalStateException("Exported biome " + biomeId + " at " + x + "," + y + "," + z
+ " has no Iris load key in the export result");
}
return loadKey;
}
}
@@ -0,0 +1,204 @@
package art.arcane.iris.probe.fidelity;
import art.arcane.iris.probe.WorldgenExportSampler;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.chunk.ProtoChunk;
import net.minecraft.world.level.levelgen.densityfunction.DensityFunction;
import net.minecraft.world.level.levelgen.densityfunction.DensityFunctions;
import net.minecraft.world.level.levelgen.densityfunction.op.BinaryFunction;
import java.io.IOException;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Objects;
public final class VanillaNoiseFidelitySource implements FidelitySource {
private static final int CHUNK_WIDTH = 16;
private static final byte SOLID = 0;
private static final byte OPEN = 1;
private static final byte FLUID = 2;
private static final byte LAVA = 3;
private final WorldgenExportSampler sampler;
private final Map<String, String> loadKeyByBiomeId;
private final String wallShell;
private final DensityFunction massDensity;
private final boolean walls;
private final int minY;
private final int maxY;
public VanillaNoiseFidelitySource(WorldgenExportSampler sampler, Map<String, String> loadKeyByBiomeId, String wallShell) {
this.sampler = Objects.requireNonNull(sampler, "sampler");
this.loadKeyByBiomeId = Map.copyOf(loadKeyByBiomeId);
this.wallShell = Objects.requireNonNull(wallShell, "wallShell");
this.massDensity = terrainMass(sampler.finalDensity());
this.walls = sampler.densityFunctionIds().contains(wallShell);
this.minY = sampler.minY();
this.maxY = sampler.minY() + sampler.height();
}
@Override
public String label() {
return "vanilla:26.3";
}
@Override
public int minY() {
return minY;
}
@Override
public int maxY() {
return maxY;
}
@Override
public FidelityChunk sample(int chunkX, int chunkZ) {
return new TerrainChunk(sampler.terrainChunk(chunkX, chunkZ), chunkX * CHUNK_WIDTH, chunkZ * CHUNK_WIDTH);
}
@Override
public void close() throws IOException {
sampler.close();
}
private String loadKey(int x, int y, int z) {
String biomeId = sampler.biome(x, y, z);
String loadKey = loadKeyByBiomeId.get(biomeId);
if (loadKey == null) {
throw new IllegalStateException("Exported biome " + biomeId + " at " + x + "," + y + "," + z
+ " has no Iris load key in the export result");
}
return loadKey;
}
static DensityFunction terrainMass(DensityFunction finalDensity) {
DensityFunction root = finalDensity;
while (root instanceof DensityFunctions.HolderHolder(Holder<DensityFunction> holder)) {
root = holder.value();
}
return root instanceof BinaryFunction(BinaryFunction.Type type, DensityFunction terrain, DensityFunction ignored) && type == BinaryFunction.Type.MIN
? terrain : root;
}
private static byte classify(Block block) {
String id = BuiltInRegistries.BLOCK.getKey(block).toString();
if (FidelityBlocks.open(id)) {
return OPEN;
}
if (FidelityBlocks.lava(id)) {
return LAVA;
}
return FidelityBlocks.fluid(id) ? FLUID : SOLID;
}
private record Column(int surfaceY, String biome, byte[] kinds) {
}
private final class TerrainChunk implements FidelityChunk {
private final ProtoChunk terrain;
private final int blockX;
private final int blockZ;
private final Column[] columns = new Column[CHUNK_WIDTH * CHUNK_WIDTH];
private final Map<Block, Byte> kinds = new IdentityHashMap<>();
private float[] masses;
private TerrainChunk(ProtoChunk terrain, int blockX, int blockZ) {
this.terrain = terrain;
this.blockX = blockX;
this.blockZ = blockZ;
}
@Override
public int surfaceY(int localX, int localZ) {
return column(localX, localZ).surfaceY();
}
@Override
public String surfaceBiome(int localX, int localZ) {
return column(localX, localZ).biome();
}
@Override
public boolean open(int localX, int y, int localZ) {
return kind(localX, y, localZ) == OPEN;
}
@Override
public boolean fluid(int localX, int y, int localZ) {
byte kind = kind(localX, y, localZ);
return kind == FLUID || kind == LAVA;
}
@Override
public boolean lava(int localX, int y, int localZ) {
return kind(localX, y, localZ) == LAVA;
}
@Override
public String block(int localX, int y, int localZ) {
return null;
}
@Override
public boolean terrainMass(int localX, int y, int localZ) {
if (y < minY || y >= maxY) {
throw new IllegalArgumentException("Y " + y + " is outside [" + minY + ", " + maxY + ")");
}
if (localX < 0 || localX >= CHUNK_WIDTH || localZ < 0 || localZ >= CHUNK_WIDTH) {
throw new IllegalArgumentException("Column " + localX + "," + localZ + " is outside the chunk");
}
if (masses == null) {
masses = sampler.densityChunk(massDensity, Math.floorDiv(blockX, CHUNK_WIDTH), Math.floorDiv(blockZ, CHUNK_WIDTH));
}
return masses[(localZ * CHUNK_WIDTH + localX) * (maxY - minY) + y - minY] > 0.0F;
}
@Override
public boolean wallsKnown() {
return walls;
}
@Override
public boolean wall(int localX, int y, int localZ) {
return walls && sampler.density(wallShell, blockX + localX, y, blockZ + localZ) > 0.0F;
}
private byte kind(int localX, int y, int localZ) {
if (y < minY || y >= maxY) {
throw new IllegalArgumentException("Y " + y + " is outside [" + minY + ", " + maxY + ")");
}
return column(localX, localZ).kinds()[y - minY];
}
private Column column(int localX, int localZ) {
if (localX < 0 || localX >= CHUNK_WIDTH || localZ < 0 || localZ >= CHUNK_WIDTH) {
throw new IllegalArgumentException("Column " + localX + "," + localZ + " is outside the chunk");
}
int index = localZ * CHUNK_WIDTH + localX;
Column column = columns[index];
if (column == null) {
column = sampleColumn(localX, localZ);
columns[index] = column;
}
return column;
}
private Column sampleColumn(int localX, int localZ) {
byte[] column = new byte[maxY - minY];
int surfaceY = minY - 1;
for (int y = maxY - 1; y >= minY; y--) {
LevelChunkSection section = terrain.getSection(terrain.getSectionIndex(y));
byte kind = kinds.computeIfAbsent(section.getBlockState(localX, y & (CHUNK_WIDTH - 1), localZ).getBlock(), VanillaNoiseFidelitySource::classify);
column[y - minY] = kind;
if (kind == SOLID && surfaceY < minY) {
surfaceY = y;
}
}
return new Column(surfaceY, loadKey(blockX + localX, Math.max(minY, surfaceY), blockZ + localZ), column);
}
}
}
@@ -1,5 +1,7 @@
package art.arcane.iris.nativegen.v26_3_R1;
import art.arcane.volmlib.nativelib.terrain.structure.StructureWater;
import art.arcane.volmlib.nativelib.terrain.structure.StructurePalette;
import art.arcane.volmlib.nativelib.terrain.structure.StructureTerrainSettings;
@@ -90,7 +92,7 @@ public class NativeStructurePostProcessorEncaseTest {
.setHorizontalPadding(1)
.setCeilingPadding(1)
.setFloorPadding(1),
null);
null, StructureWater.DRY);
assertEquals(Blocks.DIRT.defaultBlockState(),
state(blocks, bounds.minX(), bounds.minY(), bounds.minZ()));
@@ -111,7 +113,7 @@ public class NativeStructurePostProcessorEncaseTest {
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), bounds, "minecraft:stronghold", start,
new IrisStructureTerrain().setMode(StructureTerrainMode.ENCASE),
null);
null, StructureWater.DRY);
assertEquals(-1, bounds.minY());
assertEquals(Blocks.DEEPSLATE.defaultBlockState(),
@@ -222,7 +224,7 @@ public class NativeStructurePostProcessorEncaseTest {
new IrisStructureTerrain()
.setMode(StructureTerrainMode.ENCASE)
.setEncasePalette(palette),
NativeStructurePostProcessorEncaseTest::tuffBlock);
NativeStructurePostProcessorEncaseTest::tuffBlock, StructureWater.DRY);
assertEquals(Blocks.TUFF.defaultBlockState(),
state(blocks, bounds.minX(), bounds.minY(), bounds.minZ()));
@@ -250,7 +252,7 @@ public class NativeStructurePostProcessorEncaseTest {
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), area, "test:bury", start,
new IrisStructureTerrain().setMode(StructureTerrainMode.SOURCE), null);
new IrisStructureTerrain().setMode(StructureTerrainMode.SOURCE), null, StructureWater.DRY);
assertEquals(Blocks.STONE.defaultBlockState(),
state(blocks, bounds.minX() - 5, groundY, bounds.minZ()));
@@ -277,7 +279,7 @@ public class NativeStructurePostProcessorEncaseTest {
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), area, "test:encapsulate", start,
new IrisStructureTerrain().setMode(StructureTerrainMode.SOURCE), null);
new IrisStructureTerrain().setMode(StructureTerrainMode.SOURCE), null, StructureWater.DRY);
assertEquals(Blocks.STONE.defaultBlockState(),
state(blocks, bounds.minX() - 11, bounds.minY(), bounds.minZ()));
@@ -1,5 +1,8 @@
package art.arcane.iris.nativegen.v26_3_R1;
import art.arcane.volmlib.nativelib.terrain.structure.StructureWater;
import art.arcane.volmlib.nativelib.terrain.structure.StructureWaterColumn;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureVerticalPlacer;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureReferenceEnvelope;
@@ -11,6 +14,7 @@ import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureFoundationBu
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceSupportBuilder;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceFitter;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceFitter.SeaSurface;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureVegetationClearer;
@@ -238,7 +242,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)),
(x, z) -> x < 2 ? groundY - 32 : groundY + 32);
(x, z) -> x < 2 ? groundY - 32 : groundY + 32, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int x = 0; x <= 3; x++) {
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, x, groundY, 0));
@@ -266,10 +270,11 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
put(blocks, 0, groundY - 19, 0, Blocks.DIRT.defaultBlockState());
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int y = groundY - 19; y <= groundY; y++) {
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, y, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, groundY - 19, 0));
for (int y = groundY - 18; y <= groundY; y++) {
assertEquals(PlainSurfaceStrata.at(groundY, y), state(blocks, 0, y, 0));
}
assertTrue(state(blocks, 0, groundY + 1, 0).isAir());
}
@@ -292,7 +297,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureTerrainIntegrator.TerrainTarget target = surfaceTarget(start, StructureTerrainMode.FLATTEN);
((IrisStructureTerrain) target.terrain()).setHorizontalPadding(24).setFlattenRange(64);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(target), (px, pz) -> groundY);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(target), (px, pz) -> groundY, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int y = groundY - 34; y <= groundY - 13; y++) {
assertEquals("Cave at " + y, Blocks.CAVE_AIR.defaultBlockState(), state(blocks, x, y, z));
@@ -315,10 +320,10 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
}
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int y = groundY - 8; y < groundY; y++) {
assertEquals("Foundation at " + y, Blocks.STONE.defaultBlockState(), state(blocks, 0, y, 0));
assertEquals("Foundation at " + y, PlainSurfaceStrata.at(groundY, y), state(blocks, 0, y, 0));
}
for (int y = groundY - 20; y <= groundY - 12; y++) {
assertEquals("Cave at " + y, Blocks.CAVE_AIR.defaultBlockState(), state(blocks, 0, y, 0));
@@ -337,9 +342,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
Map<BlockPos, BlockState> originalSubmerged = new HashMap<>(submerged);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(buried), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> 100);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> 100, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(submerged), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY - 8);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY - 8, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(originalBuried, buried);
assertEquals(originalSubmerged, submerged);
@@ -386,14 +391,62 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
return method.invoke(delegate, arguments);
});
NativeStructureSurfaceFitter.prepareSurfaceStructures(bounded, area, List.of(target), (x, z) -> 127);
NativeStructureSurfaceFitter.prepareSurfaceStructures(bounded, area, List.of(target), (x, z) -> 127, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GOLD_BLOCK.defaultBlockState(), state(blocks, 0, 94, 0));
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 95, 0));
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 127, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 127, 0));
assertTrue(state(blocks, 0, 128, 0).isAir());
}
@Test
public void flattenKeepsDryBanksAtTheWaterSurface() {
StructureStart start = desertStart();
int groundY = start.getBoundingBox().minY() - 1;
int streamX = start.getBoundingBox().maxX() + 6;
NativeStructureTerrainIntegrator.TerrainTarget target = new NativeStructureTerrainIntegrator.TerrainTarget(
"minecraft:village_plains", start,
new IrisStructureTerrain().setMode(StructureTerrainMode.FLATTEN).setHorizontalPadding(24).setFlattenRange(64));
assertStreamStaysBetweenItsBanks(target, streamX, start.getBoundingBox().minZ(), groundY + 8);
}
@Test
public void sourceFittingKeepsDryBanksAtTheWaterSurface() {
StructureStart start = desertStart(TerrainAdjustment.BEARD_THIN);
BoundingBox piece = start.getPieces().getFirst().getBoundingBox();
assertStreamStaysBetweenItsBanks(surfaceTarget(start, StructureTerrainMode.SOURCE), piece.maxX() + 3,
piece.minZ(), piece.minY() + 7);
}
private static void assertStreamStaysBetweenItsBanks(
NativeStructureTerrainIntegrator.TerrainTarget target, int streamX, int z, int bedY) {
int waterY = bedY + 1;
BoundingBox area = new BoundingBox(streamX - 1, 0, z, streamX + 1, 127, z);
Map<BlockPos, BlockState> blocks = new HashMap<>();
for (int x = streamX - 1; x <= streamX + 1; x++) {
for (int y = 0; y <= (x == streamX ? bedY : waterY); y++) {
put(blocks, x, y, z, Blocks.STONE.defaultBlockState());
}
}
put(blocks, streamX, bedY, z, Blocks.SAND.defaultBlockState());
put(blocks, streamX, waterY, z, Blocks.WATER.defaultBlockState());
StructureWater water = (x, columnZ) -> x == streamX && columnZ == z
? new StructureWaterColumn(true, true, bedY, waterY) : StructureWaterColumn.DRY;
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(target),
(x, columnZ) -> x == streamX && columnZ == z ? bedY : waterY, SeaSurface.NONE, water, PlainSurfaceStrata.STRATA);
int top = waterY;
while (top >= 0 && state(blocks, streamX, top, z).getFluidState().isEmpty()) {
top--;
}
assertTrue("the stream goes down with its banks", top >= 0 && top < waterY);
assertEquals(Blocks.SAND.defaultBlockState(), state(blocks, streamX, top - 1, z));
assertTrue("nothing stands above the lowered water", state(blocks, streamX, waterY, z).isAir());
assertFalse("west bank holds the water", state(blocks, streamX - 1, top, z).isAir());
assertFalse("east bank holds the water", state(blocks, streamX + 1, top, z).isAir());
}
@Test
public void flattenReferencesIncludeTheMaximumConfiguredFeather() throws Exception {
PoolElementStructurePiece piece = rigidTemplatePiece(new InlineSinglePoolElement(template(List.of(
@@ -406,9 +459,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
BoundingBox references = NativeStructureReferenceEnvelope.referenceBounds(start, start.getStructure(), terrain);
assertEquals(-128, references.minX());
assertEquals(128, references.maxX());
assertEquals(143, references.maxX());
assertEquals(-128, references.minZ());
assertEquals(128, references.maxZ());
assertEquals(143, references.maxZ());
NativeStructureSurfaceFitter.FlattenAnchor anchor = new NativeStructureSurfaceFitter.FlattenAnchor(
new NativeStructureSurfaceFitter.SurfaceAnchor(0, 0, 0, 0, 64, 2), 128, 128);
assertTrue(NativeStructureSurfaceFitter.resolveFlattenSurface(List.of(anchor), 127, 0, 100).range() > 0);
@@ -477,7 +530,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)),
(x, z) -> x == footprint.minX() ? 80 : 112);
(x, z) -> x == footprint.minX() ? 80 : 112, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(81, piece.getBoundingBox().minY());
assertTrue(piece.attemptVanillaAlignment());
@@ -511,13 +564,13 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
WorldGenLevel world = world(blocks);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world, area, List.of(target),
(x, z) -> x == 0 || x == 8 ? 64 : 96);
(x, z) -> x == 0 || x == 8 ? 64 : 96, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureTemplateOccupancy.OccupancyResult occupancy = NativeStructureTemplateOccupancy.resolve(
world, path, BlockPos.ZERO, area,
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertTrue(state(blocks, 4, 96, 0).isAir());
assertEquals(1, pathGround.size());
@@ -555,7 +608,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, area, List.of(target), (x, z) -> x < 4 ? 96 : 32);
world, area, List.of(target), (x, z) -> x < 4 ? 96 : 32, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(96, chunk.getHeight(Heightmap.Types.WORLD_SURFACE_WG, 0, 0));
assertEquals(32, chunk.getHeight(Heightmap.Types.WORLD_SURFACE_WG, 8, 0));
@@ -566,7 +619,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertEquals(2, pathGround.size());
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
@@ -615,14 +668,14 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, area, List.of(target), (x, z) -> x == 0 || x == 8 ? 64 : 96);
world, area, List.of(target), (x, z) -> x == 0 || x == 8 ? 64 : 96, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
plan.primeHeightmaps(chunk);
NativeStructureTemplateOccupancy.OccupancyResult occupancy = NativeStructureTemplateOccupancy.resolve(
world, path, BlockPos.ZERO, area,
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertEquals(2, pathGround.size());
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
@@ -670,7 +723,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
}
NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(target),
(x, z) -> (x == 0 || x == 8) && (z == 0 || z == 8) ? 64 : 96);
(x, z) -> (x == 0 || x == 8) && (z == 0 || z == 8) ? 64 : 96, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int x = 0; x <= 8; x++) {
for (int z = 0; z <= 8; z++) {
@@ -740,7 +793,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> 64);
(x, z) -> 64, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(before, blocks);
}
@@ -866,13 +919,13 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
new IrisStructureTerrain().setMode(StructureTerrainMode.SOURCE)));
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, targets,
(x, z) -> 65);
(x, z) -> 65, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 71, 1));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 11, 71, 1));
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 11, 70, 1));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 2, 65, 2));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 12, 65, 2));
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 2, 65, 2));
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 12, 65, 2));
}
@Test
@@ -891,7 +944,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> 64);
(x, z) -> 64, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 68, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 64, 0));
@@ -912,7 +965,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> 40);
(x, z) -> 40, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 46, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 47, 0));
@@ -944,7 +997,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> x == 0 ? 60 : x == 30 ? 72 : 64);
(x, z) -> x == 0 ? 60 : x == 30 ? 72 : 64, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 61, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 30, 71, 0));
@@ -972,7 +1025,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 64, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 63, 0));
@@ -997,7 +1050,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 64, 0));
@@ -1018,7 +1071,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 80);
(x, z) -> 80, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int y = 61; y <= 74; y++) {
assertFalse(state(blocks, 0, y, 0).isAir());
@@ -1043,7 +1096,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 79);
(x, z) -> 79, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int y = 61; y <= 74; y++) {
assertFalse(state(blocks, 0, y, 0).isAir());
@@ -1075,7 +1128,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int y = 61; y <= 64; y++) {
put(blocks, 0, y, 0, Blocks.CAVE_AIR.defaultBlockState());
}
@@ -1086,7 +1139,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
BlockState authoredAirSupport = state(blocks, 2, 66, 0);
NativeStructureSurfaceFitter.repairVacuumFoundations(
world(blocks), area, plan);
world(blocks), area, plan, PlainSurfaceStrata.STRATA);
for (int y = 61; y <= 64; y++) {
assertFalse(state(blocks, 0, y, 0).isAir());
@@ -1115,11 +1168,11 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
put(blocks, 0, 65, 0, Blocks.COBBLESTONE.defaultBlockState());
NativeStructureSurfaceFitter.repairVacuumFoundations(
world(blocks), area, plan);
world(blocks), area, plan, PlainSurfaceStrata.STRATA);
for (int y = 61; y <= 64; y++) {
assertTrue(state(blocks, 0, y, 0).isAir());
@@ -1145,13 +1198,13 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.SurfaceTerrainPlan widePlan =
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60);
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.SurfaceTerrainPlan westPlan =
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), westArea, List.of(target), (x, z) -> 60);
world(splitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.SurfaceTerrainPlan eastPlan =
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60);
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int x = 15; x <= 16; x++) {
for (int y = 61; y <= 64; y++) {
put(wideBlocks, x, y, 0, Blocks.CAVE_AIR.defaultBlockState());
@@ -1162,11 +1215,11 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
}
NativeStructureSurfaceFitter.repairVacuumFoundations(
world(wideBlocks), wideArea, widePlan);
world(wideBlocks), wideArea, widePlan, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.repairVacuumFoundations(
world(splitBlocks), eastArea, eastPlan);
world(splitBlocks), eastArea, eastPlan, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.repairVacuumFoundations(
world(splitBlocks), westArea, westPlan);
world(splitBlocks), westArea, westPlan, PlainSurfaceStrata.STRATA);
assertEquals(wideBlocks, splitBlocks);
}
@@ -1186,7 +1239,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(originalBlocks, blocks);
}
@@ -1207,7 +1260,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(originalBlocks, blocks);
}
@@ -1231,7 +1284,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 66, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 1, 67, 0));
@@ -1256,7 +1309,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(originalBlocks, blocks);
}
@@ -1276,7 +1329,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 66, 0));
@@ -1301,7 +1354,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(originalBlocks, blocks);
}
@@ -1322,7 +1375,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 4, 61, 4));
}
@@ -1340,7 +1393,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 50);
(x, z) -> 50, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(originalBlocks, blocks);
}
@@ -1359,7 +1412,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60, 1);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA, 1);
assertEquals(originalBlocks, blocks);
}
@@ -1383,7 +1436,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
for (int y = 61; y <= 65; y++) {
assertFalse(state(blocks, 10, y, 0).isAir());
@@ -1411,15 +1464,15 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
Map<BlockPos, BlockState> reverseSplitBlocks = flatTerrain(wideArea, 60);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60);
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), westArea, List.of(target), (x, z) -> 60);
world(splitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60);
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(reverseSplitBlocks), eastArea, List.of(target), (x, z) -> 60);
world(reverseSplitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(reverseSplitBlocks), westArea, List.of(target), (x, z) -> 60);
world(reverseSplitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(wideBlocks, splitBlocks);
assertEquals(wideBlocks, reverseSplitBlocks);
@@ -1883,7 +1936,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
List<NativeStructureTerrainIntegrator.TerrainTarget> targets =
List.of(surfaceTarget(start));
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, area, targets, (x, z) -> 60);
world, area, targets, (x, z) -> 60, SeaSurface.NONE, StructureWater.DRY, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 2, 62, 2));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 2, 65, 2));
@@ -1937,9 +1990,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(lowered), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.STONE.defaultBlockState(), state(lowered, 0, 61, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(lowered, 0, 61, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(lowered, 0, 62, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(lowered, 0, 63, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(lowered, 0, 64, 0));
@@ -1952,9 +2005,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(raised), new BlockPos.MutableBlockPos(),
0, 0, 64, 68, -64, 319);
0, 0, 64, 68, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 65, 0));
assertEquals(Blocks.STONE.defaultBlockState(), state(raised, 0, 65, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 66, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 67, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(raised, 0, 68, 0));
@@ -1971,10 +2024,10 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 99, 83, -64, 319);
0, 0, 99, 83, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 82, 0));
assertEquals(Blocks.SNOW_BLOCK.defaultBlockState(), state(blocks, 0, 83, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 82, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 83, 0));
for (int y = 84; y <= 100; y++) {
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, y, 0));
}
@@ -1993,7 +2046,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 62, 0));
for (int y = 63; y <= 68; y++) {
@@ -2015,7 +2068,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 62, 0));
for (int y = 63; y <= 65; y++) {
@@ -2034,9 +2087,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 64, -64, 319, true);
0, 0, 64, 64, -64, 319, true, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 64, 0));
}
@@ -2047,10 +2100,10 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 64, -64, 319, true);
0, 0, 64, 64, -64, 319, true, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 64, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 64, 0));
}
@Test
@@ -2059,9 +2112,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, -64, -64, -64, 319, true);
0, 0, -64, -64, -64, 319, true, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, -64, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, -64, 0));
}
@Test
@@ -2076,7 +2129,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 68, -64, 319);
0, 0, 64, 68, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(log, state(blocks, 0, 66, 0));
assertEquals(leaves, state(blocks, 0, 68, 0));
@@ -2098,9 +2151,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
world, chunk, area, List.of(desertStart()));
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(),
0, 0, 64, 68, -64, 319);
0, 0, 64, 68, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 65, 0)));
assertEquals(Blocks.STONE.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 65, 0)));
assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 66, 0)));
assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 67, 0)));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 68, 0)));
@@ -2116,12 +2169,12 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 64, 0));
assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 65, 0));
assertEquals(Blocks.GRAVEL.defaultBlockState(), state(blocks, 0, 62, 0));
assertEquals("a surface under the fluid takes submerged soil", Blocks.DIRT.defaultBlockState(), state(blocks, 0, 62, 0));
}
@Test
@@ -2184,7 +2237,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), bounds, "minecraft:desert_pyramid", start,
new IrisStructureTerrain().setMode(StructureTerrainMode.VACUUM), null);
new IrisStructureTerrain().setMode(StructureTerrainMode.VACUUM), null, StructureWater.DRY);
assertEquals(Blocks.STONE.defaultBlockState(),
state(blocks, bounds.minX(), bounds.minY(), bounds.minZ()));
@@ -2208,7 +2261,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
new IrisStructureTerrain()
.setMode(StructureTerrainMode.FORCE_CARVE)
.setHorizontalPadding(1)
.setCeilingPadding(1), null);
.setCeilingPadding(1), null, StructureWater.DRY);
assertEquals(Blocks.AIR.defaultBlockState(),
state(blocks, bounds.maxX() + 1, bounds.minY(), bounds.maxZ()));
@@ -2240,7 +2293,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureTerrainIntegrator.integrateTerrain(
world(blocks), area, "minecraft:ancient_city", start,
new IrisStructureTerrain().setMode(StructureTerrainMode.FORCE_CARVE), null);
new IrisStructureTerrain().setMode(StructureTerrainMode.FORCE_CARVE), null, StructureWater.DRY);
assertEquals(Blocks.AIR.defaultBlockState(),
state(blocks, firstBounds.minX(), y, z));
@@ -2381,7 +2434,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
bounds.maxX() + 6, bounds.maxY() + 12, bounds.maxZ() + 6);
Map<BlockPos, BlockState> blocks = fill(area);
NativeStructureTerrainIntegrator.carveOrganicColumns(world(blocks), area, carve);
NativeStructureTerrainIntegrator.carveOrganicColumns(world(blocks), area, StructureWater.DRY, carve);
int centerX = bounds.minX() + bounds.getXSpan() / 2;
int centerZ = bounds.minZ() + bounds.getZSpan() / 2;
@@ -2406,9 +2459,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
Map<BlockPos, BlockState> lobedBlocks = fill(area);
NativeStructureTerrainIntegrator.carveOrganicColumns(
world(uniformBlocks), area, organicCarve(start, 10, 0D));
world(uniformBlocks), area, StructureWater.DRY, organicCarve(start, 10, 0D));
NativeStructureTerrainIntegrator.carveOrganicColumns(
world(lobedBlocks), area, organicCarve(start, 10, 0.85D));
world(lobedBlocks), area, StructureWater.DRY, organicCarve(start, 10, 0.85D));
int uniform = 0;
int lobed = 0;
@@ -2456,9 +2509,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
// Each chunk context rebuilds its own noise channels from the shared start identity.
NativeStructureTerrainIntegrator.carveOrganicColumns(
world(wideBlocks), wide, organicCarve(start, 6));
world(wideBlocks), wide, StructureWater.DRY, organicCarve(start, 6));
NativeStructureTerrainIntegrator.carveOrganicColumns(
world(narrowBlocks), narrow, organicCarve(start, 6));
world(narrowBlocks), narrow, StructureWater.DRY, organicCarve(start, 6));
int carved = 0;
for (int x = narrow.minX(); x <= narrow.maxX(); x++) {
@@ -2495,7 +2548,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
.setCeilingPadding(8)
.setFloorPadding(0)
.setErosionStrength(1D)
.setErosionFrequency(0.05D), null);
.setErosionFrequency(0.05D), null, StructureWater.DRY);
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, centerX, bounds.minY(), centerZ));
assertEquals(Blocks.STONE.defaultBlockState(),
@@ -2813,7 +2866,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
SLAB_WIDTH - 1 + SLAB_PADDING, transectY, SLAB_DEPTH - 1);
Map<BlockPos, BlockState> blocks = fill(area);
NativeStructureTerrainIntegrator.carveOrganicColumns(world(blocks), area,
NativeStructureTerrainIntegrator.carveOrganicColumns(world(blocks), area, StructureWater.DRY,
NativeStructureTerrainIntegrator.organicCarve(
footprint, terrain, StructureCarveShape.ERODED, TEST_SEED));
@@ -3,6 +3,7 @@ package art.arcane.iris.nativegen.v26_3_R1;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureVerticalPlacer;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceFitter;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceFitter.SeaSurface;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureVegetationClearer;
@@ -206,9 +207,9 @@ public class NativeStructurePostProcessorVegetationTest {
write(chunk, 4, 106, 4, Blocks.CACTUS_FLOWER.defaultBlockState());
NativeStructureSurfaceFitter.applySurfaceColumn(
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 102, 93, MIN_Y, MAX_Y);
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 102, 93, MIN_Y, MAX_Y, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.SAND.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 93, 4)));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 93, 4)));
for (int y = 94; y <= 106; y++) {
assertTrue("Unsupported decoration at " + y, chunk.getBlockState(new BlockPos(4, y, 4)).isAir());
}
@@ -227,9 +228,9 @@ public class NativeStructurePostProcessorVegetationTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertTrue(chunk.getBlockState(new BlockPos(4, 65, 4)).isAir());
assertTrue(chunk.getBlockState(new BlockPos(4, 66, 4)).isAir());
@@ -249,7 +250,7 @@ public class NativeStructurePostProcessorVegetationTest {
write(chunk, 4, 67, 4, Blocks.CACTUS_FLOWER.defaultBlockState());
NativeStructureSurfaceFitter.applySurfaceColumn(
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y);
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(boundary, chunk.getBlockState(new BlockPos(4, 65, 4)));
assertEquals(Blocks.CACTUS.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 66, 4)));
@@ -271,11 +272,11 @@ public class NativeStructurePostProcessorVegetationTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y, false, SeaSurface.NONE, PlainSurfaceStrata.STRATA);
assertEquals(Blocks.SAND.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 60, 4)));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 60, 4)));
for (int y = 61; y <= 67; y++) {
assertTrue(chunk.getBlockState(new BlockPos(4, y, 4)).isAir());
}
@@ -0,0 +1,31 @@
package art.arcane.iris.nativegen.v26_3_R1;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceFitter;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
final class PlainSurfaceStrata {
static final NativeStructureSurfaceFitter.SurfaceStrata STRATA = (x, z, surfaceY, submerged) ->
new NativeStructureSurfaceFitter.SurfaceStrata.Column() {
@Override
public BlockState block(int y) {
int depth = surfaceY - y;
if (depth == 0) {
return submerged ? Blocks.DIRT.defaultBlockState() : Blocks.GRASS_BLOCK.defaultBlockState();
}
return depth <= 2 ? Blocks.DIRT.defaultBlockState() : Blocks.STONE.defaultBlockState();
}
@Override
public int soilDepth() {
return 3;
}
};
static BlockState at(int surfaceY, int y) {
return STRATA.column(0, 0, surfaceY, false).block(y);
}
private PlainSurfaceStrata() {
}
}
@@ -1,5 +1,7 @@
package art.arcane.iris.platform.bukkit.nms.v26_3_R1;
import art.arcane.volmlib.nativelib.terrain.structure.StructureWater;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureWorldgenAccess;
import art.arcane.iris.structure.placement.IrisStructureTerrain;
@@ -94,13 +96,13 @@ public class NativeStructureWorldgenAccessTest {
unbounded.rejectDistantTerrainReads = true;
assertThrows(IllegalStateException.class, () -> NativeStructurePostProcessor.prepareTerrain(
unbounded.world(), area, targets, (palette, rng, x, y, z) -> Blocks.STONE.defaultBlockState()));
unbounded.world(), area, targets, (palette, rng, x, y, z) -> Blocks.STONE.defaultBlockState(), StructureWater.DRY));
RecordingDelegate recording = new RecordingDelegate();
recording.rejectDistantTerrainReads = true;
NativeStructureWorldgenAccess access = access(recording);
NativeStructurePostProcessor.prepareTerrain(
access, area, targets, (palette, rng, x, y, z) -> Blocks.STONE.defaultBlockState());
access, area, targets, (palette, rng, x, y, z) -> Blocks.STONE.defaultBlockState(), StructureWater.DRY);
assertEquals(0, recording.heightReads);
assertEquals(0, recording.chunkReads);
@@ -0,0 +1,73 @@
package art.arcane.iris.probe;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.spi.VanillaDataSource;
import net.minecraft.resources.Identifier;
import net.minecraft.server.packs.PackResources;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.IoSupplier;
import org.bukkit.Bukkit;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public final class BukkitVanillaDataTest {
private static final String PLAINS = "data/minecraft/worldgen/biome/plains.json";
private static final String BIOME_TAGS = "data/minecraft/tags/worldgen/biome";
@BeforeClass
public static void bootstrap() {
HeadlessNativeBootstrap.initialize();
}
@Test
public void bukkitPlatformReadsTheServerPlainsBiome() throws IOException {
byte[] plains = new BukkitPlatform().vanillaData().read(PLAINS).orElseThrow();
assertTrue(new String(plains, StandardCharsets.UTF_8).contains("\"temperature\""));
try (PackResources vanilla = ServerPacksSource.createVanillaPackSource().fullResources()) {
IoSupplier<InputStream> resource = vanilla.getResource(PackType.SERVER_DATA,
Identifier.withDefaultNamespace("worldgen/biome/plains.json"));
try (InputStream input = resource.get()) {
assertArrayEquals(input.readAllBytes(), plains);
}
}
assertNull(Bukkit.getServer());
}
@Test
public void bukkitPlatformListsTheBiomeTagsTheGameLoads() {
List<String> expected = new ArrayList<>();
try (PackResources vanilla = ServerPacksSource.createVanillaPackSource().fullResources()) {
vanilla.listResources(PackType.SERVER_DATA, "minecraft", "tags/worldgen/biome",
(id, resource) -> expected.add("data/" + id.getNamespace() + "/" + id.getPath()));
}
Collections.sort(expected);
List<String> listed = new BukkitPlatform().vanillaData().list(BIOME_TAGS);
assertFalse(listed.isEmpty());
assertTrue(listed.contains(BIOME_TAGS + "/is_overworld.json"));
assertEquals(expected, listed);
}
@Test
public void headlessPlatformReadsTheSameVanillaData() {
HeadlessNativePlatform platform = new HeadlessNativePlatform(new File("unused-native-platform"),
HeadlessNativeTestRegistries::get);
VanillaDataSource bukkit = new BukkitPlatform().vanillaData();
assertArrayEquals(bukkit.read(PLAINS).orElseThrow(), platform.vanillaData().read(PLAINS).orElseThrow());
assertEquals(bukkit.list(BIOME_TAGS), platform.vanillaData().list(BIOME_TAGS));
}
}
@@ -0,0 +1,146 @@
package art.arcane.iris.probe;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.RandomState;
import net.minecraft.world.level.levelgen.densityfunction.CachingDensitySampler;
import net.minecraft.world.level.levelgen.densityfunction.DensityFunction;
import net.minecraft.world.level.levelgen.densityfunction.DensitySampler;
import net.minecraft.world.level.levelgen.material.rule.ConditionRule;
import net.minecraft.world.level.levelgen.material.rule.MaterialRule;
import net.minecraft.world.level.levelgen.material.rule.OreVeinRule;
import net.minecraft.world.level.levelgen.material.rule.SequenceRule;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
final class CompiledCaches {
private static final String MINECRAFT_PACKAGE = "net.minecraft.";
private static final String DENSITY_PACKAGE = "net.minecraft.world.level.levelgen.densityfunction.";
private static final String SPLINE_PACKAGE = "net.minecraft.util.";
private static final String SPLINE_NAME = "Spline";
private final RegistryAccess registries;
private final NoiseGeneratorSettings settings;
private final RandomState state;
private CompiledCaches(RegistryAccess registries, NoiseGeneratorSettings settings, long seed) {
this.registries = registries;
this.settings = settings;
this.state = RandomState.create(registries.lookupOrThrow(Registries.NOISE), seed, settings);
}
static CompiledCaches open(RegistryAccess registries, long seed) {
if (!(DatapackCostProbe.exportedOverworld(registries).generator() instanceof NoiseBasedChunkGenerator generator)) {
throw new IllegalStateException("Exported overworld has no noise generator");
}
return new CompiledCaches(registries, generator.generatorSettings().value(), seed);
}
DensityFunction finalDensity() {
return settings.noiseRouter().finalDensity();
}
DensityFunction function(String id) {
return registries.lookupOrThrow(Registries.DENSITY_FUNCTION)
.getOrThrow(ResourceKey.create(Registries.DENSITY_FUNCTION, Identifier.parse(id))).value();
}
List<OreVeinRule> oreVeins() {
List<OreVeinRule> veins = new ArrayList<>();
Deque<MaterialRule> pending = new ArrayDeque<>();
pending.push(settings.materialRule().value());
while (!pending.isEmpty()) {
MaterialRule rule = pending.pop();
switch (rule) {
case OreVeinRule vein -> veins.add(vein);
case SequenceRule sequence -> sequence.sequence().reversed().forEach(pending::push);
case ConditionRule condition -> pending.push(condition.thenRun());
default -> {
}
}
}
return veins;
}
int rootId(DensityFunction function) {
if (!(state.getSampler(function) instanceof CachingDensitySampler cache)) {
throw new IllegalStateException("Density function " + function + " does not compile to a cache");
}
return cache.id();
}
Set<Integer> ids(DensityFunction function) {
Set<Integer> ids = new TreeSet<>();
Set<Object> visited = Collections.newSetFromMap(new IdentityHashMap<>());
Deque<Object> pending = new ArrayDeque<>();
pending.push(state.getSampler(function));
while (!pending.isEmpty()) {
Object node = pending.pop();
if (node == null || !visited.add(node)) {
continue;
}
if (node instanceof CachingDensitySampler cache) {
ids.add(cache.id());
}
for (Object child : children(node)) {
pending.push(child);
}
}
return ids;
}
private static List<Object> children(Object node) {
List<Object> children = new ArrayList<>();
if (node instanceof Object[] array) {
Collections.addAll(children, array);
return children;
}
if (node instanceof Collection<?> collection) {
children.addAll(collection);
return children;
}
if (!traversed(node)) {
return children;
}
for (Class<?> type = node.getClass(); type != null && type.getName().startsWith(MINECRAFT_PACKAGE); type = type.getSuperclass()) {
for (Field field : type.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers()) || field.getType().isPrimitive()) {
continue;
}
children.add(read(field, node));
}
}
return children;
}
private static boolean traversed(Object node) {
if (node instanceof Enum<?>) {
return false;
}
String name = node.getClass().getName();
return node instanceof DensitySampler || name.startsWith(DENSITY_PACKAGE) || name.startsWith(SPLINE_PACKAGE) && name.contains(SPLINE_NAME);
}
private static Object read(Field field, Object owner) {
try {
field.setAccessible(true);
return field.get(owner);
} catch (IllegalAccessException | RuntimeException failure) {
throw new IllegalStateException("Cannot read " + field + " of " + owner.getClass().getName(), failure);
}
}
}
@@ -0,0 +1,46 @@
package art.arcane.iris.probe;
import art.arcane.iris.probe.fidelity.FidelityReport;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public final class DatapackFidelityProbeBiomeModeTest {
@ClassRule
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
@Rule
public TemporaryFolder temporary = new TemporaryFolder();
@Test(timeout = 300_000L)
public void biomeModeJudgesTheSeedMeanWithoutTheChunkScan() throws Exception {
Path pack = DatapackFidelityProbeTest.pack(temporary);
Path output = temporary.getRoot().toPath().resolve("reports").resolve("biomes.json");
FidelityReport report = DatapackFidelityProbe.execute(
new String[]{pack.toString(), "main", "1337", "0", "1", output.toString(), "256", "32", "3", "biomes"}, DatapackFidelityProbeTest.exporter());
JsonObject json = JsonParser.parseString(Files.readString(output, StandardCharsets.UTF_8)).getAsJsonObject();
assertTrue(report.toTable(), report.passed());
assertTrue(json.get("passed").getAsBoolean());
assertEquals(1.0D, DatapackFidelityProbeTest.metric(report, "biome.share.plains").export(), 0.0D);
assertEquals(1, report.sampling().size());
assertEquals(List.of(1337L, 1338L, 1339L), report.sampling().getFirst().seeds());
assertEquals(3, json.getAsJsonArray("seeds").size());
assertEquals(3, json.getAsJsonObject("seedsPassing").getAsJsonObject("biome.share.plains").get("passing").getAsInt());
assertTrue(report.observations().stream().anyMatch(observation -> observation.name().equals("biome.type.land")
&& observation.iris() == 1.0D && observation.export() == 1.0D));
assertTrue(RealPackProbeSupport.drainReported().isEmpty());
}
}
@@ -0,0 +1,116 @@
package art.arcane.iris.probe;
import art.arcane.iris.pack.datapack.export.WorldgenDatapackExporter;
import art.arcane.iris.pack.datapack.export.compile.DimensionStage;
import art.arcane.iris.pack.datapack.export.compile.ImageMapStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompiler;
import art.arcane.iris.pack.datapack.export.emit.WorldgenJsonWriter;
import art.arcane.iris.probe.fidelity.FidelityMetric;
import art.arcane.iris.probe.fidelity.FidelityReport;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public final class DatapackFidelityProbeTest {
@ClassRule
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
@Rule
public TemporaryFolder temporary = new TemporaryFolder();
@Test(timeout = 300_000L)
public void probeExportsTheSyntheticPackAndComparesBothGenerators() throws Exception {
Path pack = pack(temporary);
Path output = temporary.getRoot().toPath().resolve("reports").resolve("fidelity.json");
FidelityReport report = DatapackFidelityProbe.execute(
new String[]{pack.toString(), "main", "1337", "1", "8", output.toString(), "256", "32", "2", "full"}, exporter());
JsonObject json = JsonParser.parseString(Files.readString(output, StandardCharsets.UTF_8)).getAsJsonObject();
assertTrue(report.toTable(), report.passed());
assertTrue(json.get("passed").getAsBoolean());
assertEquals(report.metrics().size(), json.getAsJsonArray("metrics").size());
FidelityMetric biome = metric(report, "biome.share.plains");
assertEquals(1.0D, biome.iris(), 0.0D);
assertEquals(1.0D, biome.export(), 0.0D);
assertTrue(biome.pass());
assertEquals(0.0D, metric(report, "biome.totalVariation").delta(), 0.0D);
assertEquals(1.0D, metric(report, "height.landFraction").export(), 0.0D);
JsonObject columns = json.getAsJsonArray("sampling").get(0).getAsJsonObject();
assertEquals("columns", columns.get("scope").getAsString());
assertEquals(256, columns.get("windowBlocks").getAsInt());
assertEquals(32, columns.get("strideBlocks").getAsInt());
assertEquals(2, columns.getAsJsonArray("seeds").size());
assertEquals(128L, columns.get("columns").getAsLong());
JsonObject chunks = json.getAsJsonArray("sampling").get(1).getAsJsonObject();
assertEquals("chunks", chunks.get("scope").getAsString());
assertEquals(48, chunks.get("windowBlocks").getAsInt());
assertTrue(RealPackProbeSupport.drainReported().isEmpty());
}
@Test
public void malformedArgumentsAreRejectedBeforeThePackOpens() throws Exception {
Path pack = pack(temporary);
String output = temporary.getRoot().toPath().resolve("unused.json").toString();
IllegalArgumentException missing = assertThrows(IllegalArgumentException.class,
() -> DatapackFidelityProbe.execute(new String[]{pack.toString(), "main"}, exporter()));
IllegalArgumentException stride = assertThrows(IllegalArgumentException.class,
() -> DatapackFidelityProbe.execute(new String[]{pack.toString(), "main", "1337", "1", "17", output, "256", "32", "1", "full"}, exporter()));
IllegalArgumentException survey = assertThrows(IllegalArgumentException.class,
() -> DatapackFidelityProbe.execute(new String[]{pack.toString(), "main", "1337", "1", "8", output, "250", "32", "1", "full"}, exporter()));
IllegalArgumentException seeds = assertThrows(IllegalArgumentException.class,
() -> DatapackFidelityProbe.execute(new String[]{pack.toString(), "main", "1337", "1", "8", output, "256", "32", "0", "full"}, exporter()));
IllegalArgumentException mode = assertThrows(IllegalArgumentException.class,
() -> DatapackFidelityProbe.execute(new String[]{pack.toString(), "main", "1337", "1", "8", output, "256", "32", "1", "caves"}, exporter()));
assertTrue(missing.getMessage(), missing.getMessage().startsWith("Usage:"));
assertTrue(stride.getMessage(), stride.getMessage().contains("stride"));
assertTrue(survey.getMessage(), survey.getMessage().contains("multiple"));
assertTrue(seeds.getMessage(), seeds.getMessage().contains("surveySeeds"));
assertTrue(mode.getMessage(), mode.getMessage().contains("caves"));
assertFalse(Files.exists(Path.of(output)));
}
static WorldgenDatapackExporter exporter() {
return new WorldgenDatapackExporter(WorldgenJsonWriter::forTarget, new PackCompiler(List.of(new DimensionStage(), new ImageMapStage())));
}
static FidelityMetric metric(FidelityReport report, String name) {
for (FidelityMetric metric : report.metrics()) {
if (metric.name().equals(name)) {
return metric;
}
}
throw new AssertionError("Report has no metric " + name + ": " + report.toJson());
}
static Path pack(TemporaryFolder temporary) throws Exception {
Path pack = temporary.newFolder().toPath();
for (String directory : List.of("dimensions", "regions", "biomes", "generators")) {
Files.createDirectories(pack.resolve(directory));
}
Files.writeString(pack.resolve("dimensions/main.json"), """
{"name":"Fidelity","focus":"plains","regions":["owned"],"landChance":1,"carvingEnabled":false}
""");
Files.writeString(pack.resolve("regions/owned.json"), "{\"landBiomes\":[\"plains\"]}");
Files.writeString(pack.resolve("generators/flat.json"), "{\"composite\":[]}");
Files.writeString(pack.resolve("biomes/plains.json"), """
{"derivative":"minecraft:plains","generators":[{"generator":"flat","min":0,"max":0}]}
""");
return pack;
}
}
@@ -0,0 +1,110 @@
package art.arcane.iris.probe;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.levelgen.densityfunction.DensityFunction;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public final class DensityCostAnalysisTest {
@ClassRule
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
private static final double EPSILON = 1.0E-9;
private static final String LEAF = "{\"type\":\"noise\",\"noise\":\"minecraft:temperature\",\"xz_scale\":1.0,\"y_scale\":0.0}";
private static HeadlessNativeRegistries registries;
@BeforeClass
public static void loadGraphs() throws IOException {
Map<String, String> definitions = new LinkedHashMap<>();
definitions.put(path("leaf"), LEAF);
definitions.put(path("pair"), "{\"type\":\"add\",\"left\":\"t:leaf\",\"right\":\"t:leaf\"}");
definitions.put(path("quad"), "{\"type\":\"mul\",\"left\":\"t:pair\",\"right\":\"t:pair\"}");
definitions.put(path("cached"), "{\"type\":\"cache\",\"input\":\"t:pair\"}");
definitions.put(path("twice"), "{\"type\":\"add\",\"left\":\"t:cached\",\"right\":\"t:cached\"}");
definitions.put(path("select"), "{\"type\":\"interval_select\",\"input\":\"t:leaf\",\"thresholds\":[0.0],\"functions\":[\"t:quad\",\"t:pair\"]}");
definitions.put(path("spline"), "{\"type\":\"spline\",\"spline\":{\"coordinate\":\"t:leaf\",\"points\":["
+ "{\"location\":-1.0,\"value\":" + nested("t:quad") + ",\"derivative\":0.0},"
+ "{\"location\":0.0,\"value\":0.0,\"derivative\":0.0},"
+ "{\"location\":1.0,\"value\":" + nested("t:quad") + ",\"derivative\":0.0}]}}");
definitions.put(path("grid"), "{\"type\":\"interpolated\",\"input\":\"t:pair\",\"cell_size_xz\":4,\"cell_size_y\":8}");
registries = HeadlessNativeRegistries.load(definitions);
}
@AfterClass
public static void closeRegistries() throws IOException {
if (registries != null) {
registries.close();
}
}
@Test
public void referencesExpandWhileTheDagSharesThem() {
DensityCostAnalysis.RootCost quad = analysis().analyze("quad", function("quad"));
assertEquals(3L, quad.dagNodes());
assertEquals(7.0, quad.expandedNodes(), EPSILON);
assertEquals(7.0, quad.cachedNodes(), EPSILON);
assertEquals(2, quad.namedSubtrees());
assertEquals("t:leaf", quad.exclusive().getFirst().name());
assertEquals(4.0, quad.exclusive().getFirst().multiplicity(), EPSILON);
assertEquals(4.0, quad.exclusive().getFirst().contribution(), EPSILON);
assertEquals("t:pair", quad.inclusive().getFirst().name());
assertEquals(6.0, quad.inclusive().getFirst().inclusive(), EPSILON);
assertEquals(1.0 / 3.0, quad.dagShare().get("leaf"), EPSILON);
assertEquals(1.0 / 3.0, quad.dagShare().get("quad"), EPSILON);
}
@Test
public void cachesEvaluateTheirBodyOnceWhenEnabled() {
DensityCostAnalysis.RootCost twice = analysis().analyze("twice", function("twice"));
assertEquals(4L, twice.dagNodes());
assertEquals(9.0, twice.expandedNodes(), EPSILON);
assertEquals(6.0, twice.cachedNodes(), EPSILON);
}
@Test
public void uncachedPointEvaluationTakesOneSelectedBranch() {
DensityCostAnalysis analysis = analysis();
DensityCostAnalysis.RootCost select = analysis.analyze("select", function("select"));
assertEquals(12.0, select.expandedNodes(), EPSILON);
assertEquals(9.0, select.uncachedPointWorst(), EPSILON);
DensityCostAnalysis.RootCost spline = analysis.analyze("spline", function("spline"));
assertEquals(19.0, spline.expandedNodes(), EPSILON);
assertEquals(11.0, spline.uncachedPointWorst(), EPSILON);
}
@Test
public void offLatticeGridPointsSampleEightCorners() {
DensityCostAnalysis.RootCost grid = analysis().analyze("grid", function("grid"));
assertEquals(4.0, grid.expandedNodes(), EPSILON);
assertEquals(25.0, grid.uncachedPointWorst(), EPSILON);
}
private static DensityCostAnalysis analysis() {
return new DensityCostAnalysis(id -> DensityJsonBreakdown.category("overworld", id), 10);
}
private static DensityFunction function(String name) {
return registries.registries().lookupOrThrow(Registries.DENSITY_FUNCTION)
.getOrThrow(ResourceKey.create(Registries.DENSITY_FUNCTION, Identifier.parse("t:" + name))).value();
}
private static String nested(String coordinate) {
return "{\"coordinate\":\"" + coordinate + "\",\"points\":[{\"location\":0.0,\"value\":1.0,\"derivative\":0.0},"
+ "{\"location\":1.0,\"value\":2.0,\"derivative\":0.0}]}";
}
private static String path(String name) {
return "data/t/worldgen/density_function/" + name + ".json";
}
}
@@ -0,0 +1,88 @@
package art.arcane.iris.probe;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import java.util.SortedMap;
import java.util.TreeMap;
import static org.junit.Assert.assertEquals;
public final class DensityJsonBreakdownTest {
private static final String TEMPERATURE = "{\"type\":\"add\",\"left\":\"x:biome/selector/0\",\"right\":1.0}";
private static final String SELECTOR = "{\"type\":\"mul\",\"left\":\"x:cell/cellular/a/value\",\"right\":2.0}";
private static final String CELL_A = "{\"type\":\"noise\",\"noise\":\"x:hash_a\",\"xz_scale\":0.5,\"y_scale\":0.0}";
private static final String CELL_B = "{\"type\":\"noise\",\"noise\":\"x:hash_b\",\"xz_scale\":0.25,\"y_scale\":0.0}";
private static final String FINAL_DENSITY = "{\"type\":\"min\",\"left\":\"x:cell/cellular/b/value\",\"right\":0.0}";
private static final String NOISE = "{\"firstOctave\":-1,\"amplitudes\":[1.0]}";
@Test
public void categoriesFollowProducingCompilers() {
assertEquals("router", DensityJsonBreakdown.category("overworld", "x:overworld/final_density"));
assertEquals("cellular", DensityJsonBreakdown.category("overworld", "x:cell/cracks/abc/distance"));
assertEquals("biome selector", DensityJsonBreakdown.category("overworld", "x:biome/selector/12"));
assertEquals("biome decision", DensityJsonBreakdown.category("overworld", "x:biome/base_code"));
assertEquals("terrain height", DensityJsonBreakdown.category("overworld", "x:height"));
assertEquals("terrain bands", DensityJsonBreakdown.category("overworld", "x:terrain/plains/blend/3"));
assertEquals("noise style", DensityJsonBreakdown.category("overworld", "x:style/shared/ab12"));
assertEquals("cellular offset copies", DensityJsonBreakdown.category("overworld", "x:cell/cellular/abc/vx_0_0/offset_x4_z0"));
assertEquals("biome selector offset copies", DensityJsonBreakdown.category("overworld", "x:biome/selector/4/offset_x0_z4"));
}
@Test
public void reportsBytesShapesAndCellularOwners() {
SortedMap<String, byte[]> files = new TreeMap<>();
put(files, "density_function/overworld/temperature", TEMPERATURE);
put(files, "density_function/biome/selector/0", SELECTOR);
put(files, "density_function/cell/cellular/a/value", CELL_A);
put(files, "density_function/cell/cellular/b/value", CELL_B);
put(files, "density_function/overworld/final_density", FINAL_DENSITY);
put(files, "noise/hash_a", NOISE);
put(files, "noise/hash_b", NOISE);
DensityJsonBreakdown.Report report = DensityJsonBreakdown.analyze(files, "overworld").report();
assertEquals(5, report.files());
assertEquals(bytes(TEMPERATURE, SELECTOR, CELL_A, CELL_B, FINAL_DENSITY), report.bytes());
DensityJsonBreakdown.CategoryBytes cellular = category(report, "cellular");
assertEquals(2, cellular.files());
assertEquals(1, cellular.distinctShapes());
assertEquals(bytes(CELL_B), cellular.structurallyDuplicateBytes());
assertEquals(2, category(report, "router").files());
assertEquals(2, report.cellularInstances());
assertEquals(1, report.cellularShapes().size());
assertEquals("biome selector+router", report.cellularShapes().getFirst().owners());
assertEquals(bytes(CELL_A), owner(report, "cellular via biome selector"));
assertEquals(bytes(CELL_B), owner(report, "cellular via router"));
}
private static DensityJsonBreakdown.CategoryBytes category(DensityJsonBreakdown.Report report, String name) {
for (DensityJsonBreakdown.CategoryBytes category : report.categories()) {
if (category.category().equals(name)) {
return category;
}
}
throw new AssertionError("No category " + name + " in " + report.categories());
}
private static long owner(DensityJsonBreakdown.Report report, String name) {
for (DensityJsonBreakdown.Bytes owner : report.libraryOwners()) {
if (owner.name().equals(name)) {
return owner.bytes();
}
}
throw new AssertionError("No owner " + name + " in " + report.libraryOwners());
}
private static long bytes(String... bodies) {
long total = 0;
for (String body : bodies) {
total += body.getBytes(StandardCharsets.UTF_8).length;
}
return total;
}
private static void put(SortedMap<String, byte[]> files, String path, String body) {
files.put("data/x/worldgen/" + path + ".json", body.getBytes(StandardCharsets.UTF_8));
}
}
@@ -137,7 +137,7 @@ public class HeadlessChunkGeneratorTest {
}
Files.writeString(pack.resolve("dimensions/main.json"), """
{"name":"Native columns","focus":"swamp","regions":["owned"],"fluidHeight":40,"logicalHeight":256,
"landChance":1,"carvingEnabled":false,"hydrology":{"rivers":{"enabled":false}}}
"landChance":1,"carvingEnabled":false}
""");
Files.writeString(pack.resolve("regions/owned.json"), "{\"landBiomes\":[\"swamp\"]}");
Files.writeString(pack.resolve("generators/flat.json"), "{\"composite\":[]}");
@@ -1,7 +1,6 @@
package art.arcane.iris.probe;
import art.arcane.iris.structure.nativegen.NativeStructureVolumeIndex;
import art.arcane.iris.generation.hydrology.HydrologyTileCache;
import art.arcane.volmlib.nativelib.terrain.structure.NativeStructureVolume;
import art.arcane.volmlib.util.collection.KList;
import net.minecraft.nbt.CompoundTag;
@@ -68,11 +67,10 @@ public final class HeadlessRegionTerrainTest {
OfflineRegionGenerator.Configuration export = new OfflineRegionGenerator.Configuration(
workspace.pack(), "main", 69420L, -3, 2, 1, 2, 3, 4, configuration,
"probe", Level.OVERWORLD, NoiseGeneratorSettings.OVERWORLD, root.resolve("export"));
HydrologyTileCache.PregenerationArea bounds = export.hydrologyArea();
assertEquals(-80L, bounds.minimumBlockX());
assertEquals(0L, bounds.minimumBlockZ());
assertEquals(15L, bounds.maximumBlockX());
assertEquals(111L, bounds.maximumBlockZ());
List<long[]> regions = export.hydrologyRegions();
assertEquals(2, regions.size());
assertArrayEquals(new long[]{-1L, 0L}, regions.get(0));
assertArrayEquals(new long[]{0L, 0L}, regions.get(1));
assertEquals(1, result.targetChunks());
assertEquals(529, result.chunks().size());
long terrain = result.chunks().stream().filter(chunk -> chunk.getPersistedStatus() == ChunkStatus.TERRAIN).count();
@@ -189,7 +187,7 @@ public final class HeadlessRegionTerrainTest {
}
Files.writeString(pack.resolve("dimensions/main.json"), """
{"name":"Native region","focus":"swamp","regions":["owned"],"fluidHeight":40,"logicalHeight":256,
"landChance":1,"carvingEnabled":false,"hydrology":{"rivers":{"enabled":false}}}
"landChance":1,"carvingEnabled":false}
""");
Files.writeString(pack.resolve("regions/owned.json"), "{\"landBiomes\":[\"swamp\"]}");
Files.writeString(pack.resolve("generators/flat.json"), "{\"composite\":[]}");
@@ -1,5 +1,7 @@
package art.arcane.iris.probe;
import art.arcane.volmlib.nativelib.terrain.structure.StructureWater;
import art.arcane.iris.structure.nativegen.IrisNativeStructure;
import art.arcane.iris.structure.nativegen.IrisNativeStructureDecision;
import art.arcane.iris.structure.nativegen.NativeStructureGenerationStatus;
@@ -215,7 +217,7 @@ public class HeadlessStructurePlannerTest {
new IrisNativeStructure().setStructure("probe:hut"), -1, 0, 30);
TestPolicy policy = new TestPolicy(plan);
HeadlessStructurePlanner.Policies<NativeStructureStartPlan, NativeStructureOwnershipRecord> policies =
new HeadlessStructurePlanner.Policies<>(policy, policy, footprint -> true);
new HeadlessStructurePlanner.Policies<>(policy, policy, footprint -> true, StructureWater.DRY);
try (MultiPackResourceManager resources = resources();
LevelStorageSource.LevelStorageAccess storage = LevelStorageSource.createDefault(temporary.newFolder().toPath()).createAccess("world")) {
StructureTemplateManager templates = new StructureTemplateManager(resources, storage,
@@ -249,7 +251,7 @@ public class HeadlessStructurePlannerTest {
assertTrue(target.chunk().getAllReferences().get(hut.value()).contains(new ChunkPos(-1, 0).pack()));
assertEquals(ChunkStatus.STRUCTURE_REFERENCES, target.chunk().getPersistedStatus());
HeadlessStructurePlanner.Policies<NativeStructureStartPlan, NativeStructureOwnershipRecord> excluded =
new HeadlessStructurePlanner.Policies<>(policy, policy, footprint -> false);
new HeadlessStructurePlanner.Policies<>(policy, policy, footprint -> false, StructureWater.DRY);
HeadlessStructurePlanner.PlannedChunk<NativeStructureOwnershipRecord> rejected = HeadlessStructurePlanner.plan(
context, excluded, new ChunkPos(-1, 0));
assertFalse(rejected.chunk().getStartForStructure(hut.value()).isValid());
@@ -6,6 +6,7 @@ import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.MockedStatic;
import java.io.File;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
@@ -78,7 +79,7 @@ public final class OfflineRegionPublicationTest {
assertFalse(Files.exists(target));
} else {
OfflineRegionGenerator.publish(staged, target);
assertEquals(List.of(data, nested, staged, output), forced);
assertEquals(File.separatorChar == '\\' ? List.of(data) : List.of(data, nested, staged, output), forced);
assertEquals("checkpoint", Files.readString(target.resolve("world/data")));
}
}
@@ -1,37 +1,19 @@
package art.arcane.iris.probe;
import io.papermc.paper.registry.PaperRegistryAccess;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public final class PaperRegistryIsolation implements TestRule {
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
Map<Object, Object> registries = registries();
Map<Object, Object> previous = new HashMap<>(registries);
registries.clear();
try {
try (PaperRegistryScope scope = PaperRegistryScope.open()) {
base.evaluate();
} finally {
registries.clear();
registries.putAll(previous);
}
}
};
}
@SuppressWarnings("unchecked")
private static Map<Object, Object> registries() throws ReflectiveOperationException {
Field field = PaperRegistryAccess.class.getDeclaredField("registries");
field.setAccessible(true);
return (Map<Object, Object>) field.get(PaperRegistryAccess.instance());
}
}
@@ -0,0 +1,126 @@
package art.arcane.iris.probe;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.emit.DensityFunctionEmitter;
import art.arcane.iris.pack.datapack.export.emit.FunctionTable;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.datapack.export.ir.ValueRange;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.datapack.export.lower.VanillaBounds;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.util.Interval;
import org.junit.ClassRule;
import org.junit.Test;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public final class VanillaBoundsParity263Test {
@ClassRule
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
private static final String NAMESPACE = "iris_export";
private static final List<NoiseDef> NOISES = List.of(new NoiseDef("parity/base", -3, List.of(1.0, 0.5, 0.25)),
new NoiseDef("parity/sparse", 0, List.of(0.0, 1.5, 0.0, 0.7)));
private static final Field BASE = new Field.Noise(NAMESPACE + ":parity/base", 0.25, 0.0, null, null, null);
private static final Field SPARSE = new Field.Noise(NAMESPACE + ":parity/sparse", 0.5, 0.25, null, null, null);
private static final Field UNIT = new Field.Clamp(BASE, 0.0, 1.0);
private static final Field BAND = new Field.Clamp(SPARSE, 0.3, 0.9);
@Test
public void boundsMatchMinecraftForEveryEmittedNode() throws Exception {
List<Field> fields = fields();
VanillaBounds bounds = VanillaBounds.of(NAMESPACE, NOISES);
DensityFunctionEmitter emitter = DensityFunctionEmitter.forTarget(ExportCapabilities.forTarget(DataVersion.V26_3), NAMESPACE, bounds);
FunctionTable table = new FunctionTable(NAMESPACE);
List<String> references = new ArrayList<>(fields.size());
for (int index = 0; index < fields.size(); index++) {
JsonElement emitted = emitter.emit(fields.get(index), table);
boolean reference = emitted.isJsonPrimitive() && emitted.getAsJsonPrimitive().isString();
references.add(reference ? emitted.getAsString() : table.register("parity/field_" + index, emitted));
}
Map<String, String> definitions = new LinkedHashMap<>();
for (Map.Entry<String, JsonElement> function : table.files().entrySet()) {
definitions.put("data/" + NAMESPACE + "/worldgen/density_function/" + function.getKey() + ".json", function.getValue().toString());
}
for (NoiseDef noise : NOISES) {
definitions.put("data/" + NAMESPACE + "/worldgen/noise/" + noise.id() + ".json", noiseJson(noise).toString());
}
try (HeadlessNativeRegistries registries = HeadlessNativeRegistries.load(definitions)) {
for (int index = 0; index < fields.size(); index++) {
Interval vanilla = registries.registries().lookupOrThrow(Registries.DENSITY_FUNCTION)
.getOrThrow(ResourceKey.create(Registries.DENSITY_FUNCTION, Identifier.parse(references.get(index)))).value().range();
Optional<ValueRange> modelled = bounds.range(fields.get(index));
assertTrue("field " + index + " " + fields.get(index) + " has no modelled range, Minecraft " + vanilla, modelled.isPresent());
assertEquals("field " + index + " " + fields.get(index), new ValueRange(vanilla.min(), vanilla.max()), modelled.get());
}
}
}
private static List<Field> fields() {
Field scaled = new Field.Binary(Field.BinaryOp.MUL, new Field.Const(0.3), BAND);
Field curve = new Field.Curve(new Field.Binary(Field.BinaryOp.MUL, BASE, new Field.Const(1.7)), List.of(
new Field.Knot(-1.0, new Field.Const(0.2), 0.75),
new Field.Knot(0.1, new Field.Curve(SPARSE, List.of(new Field.Knot(-0.5, new Field.Const(-1.0), 0.0),
new Field.Knot(0.5, new Field.Const(1.3), 2.0))), 0.0),
new Field.Knot(0.8, new Field.Const(0.6), -1.5)));
List<Field> fields = new ArrayList<>();
fields.add(BASE);
fields.add(SPARSE);
fields.add(new Field.Const(0.1));
fields.add(new Field.Coord(Axis.Y, Field.Tiling.CLAMP, -64.0, 320.0, 1.5, -0.7));
fields.add(new Field.Clamp(BASE, -0.3, 0.8));
for (Field.BinaryOp op : Field.BinaryOp.values()) {
fields.add(new Field.Binary(op, BASE, new Field.Binary(Field.BinaryOp.ADD, BAND, new Field.Const(0.6))));
}
fields.add(new Field.Binary(Field.BinaryOp.POW, UNIT, new Field.Const(2.5)));
fields.add(new Field.Binary(Field.BinaryOp.MAX, scaled, new Field.Const(0.0)));
fields.add(new Field.Binary(Field.BinaryOp.MIN, new Field.Const(2.0), scaled));
fields.add(new Field.Binary(Field.BinaryOp.MIN, new Field.Const(0.2), scaled));
for (Field.UnaryOp op : Field.UnaryOp.values()) {
fields.add(new Field.Unary(op, new Field.Binary(Field.BinaryOp.SUB, SPARSE, new Field.Const(0.4))));
}
fields.add(new Field.Lerp(UNIT, BASE, new Field.Binary(Field.BinaryOp.MUL, SPARSE, new Field.Const(3.0))));
for (Field.RoundMode mode : Field.RoundMode.values()) {
fields.add(new Field.Round(mode, new Field.Binary(Field.BinaryOp.MUL, BASE, new Field.Const(10.3)), new Field.Const(2.5)));
}
fields.add(curve);
fields.add(new Field.Curve(UNIT, List.of(new Field.Knot(0.0, new Field.Const(0.0), -3.0), new Field.Knot(1.0, new Field.Const(1.0), -3.0))));
fields.add(new Field.Partition(BASE, List.of(-0.2, 0.4), List.of(new Field.Const(-3.0), new Field.Const(0.5), new Field.Const(7.25))));
fields.add(new Field.Mux(new Field.Binary(Field.BinaryOp.MUL, UNIT, new Field.Const(2.0)), List.of(new Field.Const(4.0), BAND, scaled)));
fields.add(new Field.Gate(BASE, new Field.Binary(Field.BinaryOp.ADD, BAND, new Field.Const(40.0))));
fields.add(new Field.RangeIf(BASE, -0.1, 0.2, new Field.Const(-2.0), BAND));
fields.add(new Field.Grid(new Field.Binary(Field.BinaryOp.ADD, BASE, SPARSE), 4, 8));
fields.add(new Field.Shared("parity/shared", new Field.Binary(Field.BinaryOp.SUB, BAND, BASE)));
fields.add(new Field.Slice(new Field.Binary(Field.BinaryOp.MUL, SPARSE, new Field.Const(-2.0)), Axis.Y, 64));
fields.add(new Field.TopSurface(new Field.Binary(Field.BinaryOp.SUB, BASE, new Field.Const(0.1)), 200, -48, 4));
return fields;
}
private static JsonObject noiseJson(NoiseDef noise) {
JsonArray modifiers = new JsonArray(noise.amplitudes().size());
for (double amplitude : noise.amplitudes()) {
modifiers.add(amplitude);
}
JsonObject json = new JsonObject();
json.addProperty("base_octave", noise.firstOctave());
json.addProperty("octave_count", noise.amplitudes().size());
json.add("amplitude_modifiers", modifiers);
json.addProperty("base_amplitude", 1.0);
json.addProperty("normalize", false);
return json;
}
}
@@ -0,0 +1,242 @@
package art.arcane.iris.probe;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.compile.noise.VanillaNoiseModel;
import net.minecraft.core.HolderGetter;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.PositionalRandomFactory;
import net.minecraft.world.level.levelgen.RandomState;
import net.minecraft.world.level.levelgen.XoroshiroRandomSource;
import net.minecraft.world.level.levelgen.synth.Noise;
import net.minecraft.world.level.levelgen.synth.NormalNoise;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SplittableRandom;
import java.util.stream.Collectors;
import static org.junit.Assert.assertTrue;
public final class VanillaNoiseModelParity263Test {
@ClassRule
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
private static final int POINTS = 4096;
private static final double TOLERANCE = 1.0E-5D;
private static final double RUNTIME_TOLERANCE = 1.0E-4D;
private static final List<Long> WORLD_SEEDS = List.of(0L, 8_675_309L, -4_611_686_018_427_387_904L);
private static final List<ParityNoise> NOISES = List.of(
ParityNoise.mapped("iris_export:parity/single", -7, List.of(1.0D)),
ParityNoise.mapped("iris_export:parity/fbm", -9, List.of(1.0D, 1.0D, 0.5D, 0.25D)),
ParityNoise.mapped("iris_export:parity/sparse", -10, List.of(1.5D, 0.0D, 1.0D, 0.0D, 0.0D, 0.0D)),
ParityNoise.mapped("iris_export:parity/leading_zero", -6, List.of(0.0D, 0.0D, 1.0D, 2.0D)),
ParityNoise.mapped("iris_export:parity/positive", 2, List.of(1.0D, 0.5D)),
ParityNoise.profiled("iris_export:parity/enabled",
"{\"base_octave\":-10,\"octave_count\":6,\"amplitude_modifiers\":[1.5,0.0,1.0,0.0,0.0,0.0],"
+ "\"base_amplitude\":1.2453007926713473}",
new VanillaNoiseModel.OctaveProfile(-10, 6, List.of(1.5D, 0.0D, 1.0D, 0.0D, 0.0D, 0.0D),
1.2453007926713473D, VanillaNoiseModel.Normalization.ENABLED)),
ParityNoise.profiled("iris_export:parity/legacy",
"{\"base_octave\":-9,\"octave_count\":3,\"amplitude_modifiers\":[1.0,0.0,1.0],\"normalize\":\"legacy\"}",
new VanillaNoiseModel.OctaveProfile(-9, 3, List.of(1.0D, 0.0D, 1.0D), 1.0D,
VanillaNoiseModel.Normalization.LEGACY)),
ParityNoise.profiled("iris_export:parity/defaults", "{\"base_octave\":-5}",
new VanillaNoiseModel.OctaveProfile(-5, 1, List.of(), 1.0D, VanillaNoiseModel.Normalization.ENABLED)),
ParityNoise.profiled("iris_export:parity/scaled",
"{\"base_octave\":-6,\"octave_count\":2,\"normalize\":false,\"base_amplitude\":0.5}",
new VanillaNoiseModel.OctaveProfile(-6, 2, List.of(), 0.5D, VanillaNoiseModel.Normalization.DISABLED)));
private static HeadlessNativeRegistries registries;
@BeforeClass
public static void loadNoiseDefinitions() throws IOException {
Map<String, String> definitions = new LinkedHashMap<>();
for (ParityNoise noise : NOISES) {
definitions.put(resourcePath(noise.id()), noise.json());
}
registries = HeadlessNativeRegistries.load(definitions);
}
@AfterClass
public static void closeRegistries() throws IOException {
if (registries != null) {
registries.close();
}
}
@Test
public void modelMatchesNoiseBuiltFromLoadedDefinitions() {
List<String> report = new ArrayList<>();
for (long seed : WORLD_SEEDS) {
PositionalRandomFactory world = new VanillaPrecisionRandom(new XoroshiroRandomSource(seed)).forkPositional();
for (ParityNoise noise : NOISES) {
NormalNoise definition = registries.registries().lookupOrThrow(Registries.NOISE).getOrThrow(key(noise.id())).value();
Noise real = definition.create(world.fromHashOf(Identifier.parse(noise.id())));
report.add(noise.id() + "@" + seed + "=" + assertParity(noise, seed, real, TOLERANCE));
}
}
System.out.println("26.3 vanilla-precision parity " + report);
}
@Test
public void modelMatchesRuntimeRandomStateNoise() {
List<String> report = new ArrayList<>();
for (long seed : WORLD_SEEDS) {
RandomState state = randomState(seed);
for (ParityNoise noise : NOISES) {
Noise real = state.getOrCreateNoise(key(noise.id()));
report.add(noise.id() + "@" + seed + "=" + assertParity(noise, seed, real, RUNTIME_TOLERANCE));
}
}
System.out.println("26.3 runtime parity " + report);
}
private static double assertParity(ParityNoise noise, long seed, Noise real, double tolerance) {
VanillaNoiseModel model = noise.model(seed);
SplittableRandom random = new SplittableRandom(seed ^ noise.id().hashCode());
double worst = 0.0D;
double peak = 0.0D;
for (int index = 0; index < POINTS; index++) {
double range = random.nextInt(4) == 0 ? 30_000_000.0D : 100_000.0D;
double x = random.nextDouble(-range, range);
double y = random.nextDouble(-2_048.0D, 2_048.0D);
double z = random.nextDouble(-range, range);
double expected = real.get(x, y, z);
worst = Math.max(worst, Math.abs(expected - model.sample(x, y, z)));
peak = Math.max(peak, Math.abs(expected));
}
assertTrue(noise.id() + " seed " + seed + " differs by " + worst, worst <= tolerance);
assertTrue(noise.id() + " seed " + seed + " is flat", peak > 0.05D);
return worst;
}
private static RandomState randomState(long seed) {
HolderGetter<NormalNoise> noises = registries.registries().lookupOrThrow(Registries.NOISE);
NoiseGeneratorSettings settings = registries.registries().lookupOrThrow(Registries.NOISE_SETTINGS)
.getOrThrow(NoiseGeneratorSettings.OVERWORLD).value();
return RandomState.create(noises, seed, settings);
}
private static ResourceKey<NormalNoise> key(String id) {
return ResourceKey.create(Registries.NOISE, Identifier.parse(id));
}
private static String resourcePath(String id) {
Identifier identifier = Identifier.parse(id);
return "data/" + identifier.getNamespace() + "/worldgen/noise/" + identifier.getPath() + ".json";
}
private record ParityNoise(String id, String json, int firstOctave, List<Double> amplitudes,
VanillaNoiseModel.OctaveProfile profile) {
private static ParityNoise mapped(String id, int firstOctave, List<Double> amplitudes) {
String modifiers = amplitudes.stream().map(String::valueOf).collect(Collectors.joining(","));
String json = "{\"base_octave\":" + firstOctave + ",\"octave_count\":" + amplitudes.size()
+ ",\"amplitude_modifiers\":[" + modifiers + "],\"base_amplitude\":1.0,\"normalize\":false}";
return new ParityNoise(id, json, firstOctave, amplitudes, null);
}
private static ParityNoise profiled(String id, String json, VanillaNoiseModel.OctaveProfile profile) {
return new ParityNoise(id, json, 0, List.of(), profile);
}
private VanillaNoiseModel model(long seed) {
if (profile == null) {
return VanillaNoiseModel.create(id, firstOctave, amplitudes, seed, DataVersion.V26_3);
}
return VanillaNoiseModel.create(id, profile, seed);
}
}
private static final class VanillaPrecisionRandom implements RandomSource {
private static final double DOUBLE_UNIT = 1.1102230246251565E-16D;
private final RandomSource source;
private VanillaPrecisionRandom(RandomSource source) {
this.source = source;
}
@Override
public RandomSource fork() {
return new VanillaPrecisionRandom(source.fork());
}
@Override
public PositionalRandomFactory forkPositional() {
return new VanillaPrecisionPositional(source.forkPositional());
}
@Override
public void setSeed(long seed) {
source.setSeed(seed);
}
@Override
public int nextInt() {
return source.nextInt();
}
@Override
public int nextInt(int bound) {
return source.nextInt(bound);
}
@Override
public long nextLong() {
return source.nextLong();
}
@Override
public boolean nextBoolean() {
return source.nextBoolean();
}
@Override
public float nextFloat() {
return source.nextFloat();
}
@Override
public double nextDouble() {
return (source.nextLong() >>> 11) * DOUBLE_UNIT;
}
@Override
public double nextGaussian() {
return source.nextGaussian();
}
}
private record VanillaPrecisionPositional(PositionalRandomFactory factory) implements PositionalRandomFactory {
@Override
public RandomSource at(int x, int y, int z) {
return new VanillaPrecisionRandom(factory.at(x, y, z));
}
@Override
public RandomSource fromHashOf(String name) {
return new VanillaPrecisionRandom(factory.fromHashOf(name));
}
@Override
public RandomSource fromSeed(long seed) {
return new VanillaPrecisionRandom(factory.fromSeed(seed));
}
@Override
public void parityConfigString(StringBuilder builder) {
factory.parityConfigString(builder);
}
}
}
@@ -0,0 +1,700 @@
package art.arcane.iris.probe;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.AtomicDatapackPublisher;
import art.arcane.iris.pack.datapack.export.DatapackExportFormat;
import art.arcane.iris.pack.datapack.export.ExportIrFixtures;
import art.arcane.iris.pack.datapack.export.GenerationCost;
import art.arcane.iris.pack.datapack.export.WorldgenDatapackExporter;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.WorldgenExportRequest;
import art.arcane.iris.pack.datapack.export.WorldgenExportResult;
import art.arcane.iris.pack.datapack.export.compile.PackCompiler;
import art.arcane.iris.pack.datapack.export.compile.surface.MaterialProgramCompiler;
import art.arcane.iris.pack.datapack.export.compile.terrain.FieldMacros;
import art.arcane.iris.pack.datapack.export.compile.terrain.HeightCompiler;
import art.arcane.iris.pack.datapack.export.emit.NestingSplitter;
import art.arcane.iris.pack.datapack.export.emit.WorldgenJsonWriter;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportIr;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.datapack.export.lower.GenerationBudget;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.tags.WorldPresetTags;
import net.minecraft.util.Interval;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ProtoChunk;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.levelgen.densityfunction.DensityFunction;
import net.minecraft.world.level.levelgen.densityfunction.DfRewriteRule;
import net.minecraft.world.level.levelgen.densityfunction.op.BinaryFunction;
import net.minecraft.world.level.levelgen.material.rule.OreVeinRule;
import net.minecraft.world.level.levelgen.presets.WorldPreset;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.Enumeration;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public final class WorldgenExport263CodecTest {
@ClassRule
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
@ClassRule
public static final TemporaryFolder overworldFolder = new TemporaryFolder();
private static final long SEED = 1337L;
private static final String DIMENSION_ID = ExportIrFixtures.NAMESPACE + ":" + ExportIrFixtures.DIMENSION;
private static final String HEIGHT_ID = ExportIrFixtures.NAMESPACE + ":" + ExportIrFixtures.DIMENSION + "/height";
private static final double SURFACE_TOLERANCE = 2.0;
private static final String BIOME_PREFIX = "data/" + ExportIrFixtures.NAMESPACE + "/worldgen/biome/";
private static final int[] SAMPLE_Y = {-64, 0, 64, 200};
private static final int LATTICE = 16;
private static final int LATTICE_STEP = 61;
private static final int HEIGHT_POINTS = 8;
private static final int HEIGHT_STEP = 97;
private static final String PROBE_PACK = "iris.exportProbePack";
private static final String OVERWORLD = "overworld";
private static final String OVERWORLD_ID = WorldgenExportRequest.DEFAULT_NAMESPACE + ":" + OVERWORLD;
private static final String OVERWORLD_BIOME_PREFIX = "data/" + WorldgenExportRequest.DEFAULT_NAMESPACE + "/worldgen/biome/";
private static final String LOG_PREFIX = "[worldgen-export]";
private static final int OVERWORLD_LATTICE = 4;
private static final int OVERWORLD_STEP = 509;
private static final int MAX_NESTING = 255;
private static final String CAVE_FIELD = "cave/field";
private static final String WALL_FALLBACK = "uses the nearest kept palette (minecraft:";
private static final double WALL_SHELL_BAND_LIMIT = 0.25;
private static final String DENSITY_FUNCTION_RESOURCE = "worldgen/density_function";
private static final double MEGABYTE = 1024.0 * 1024.0;
private static final int OVERWORLD_LAVA_Y = -248;
private static final int LAVA_LINE = -54;
private static final int DEEP_CHUNKS = 2;
private static final int DEEP_STRIDE = 4;
private static final int CHUNK_WIDTH = 16;
private static final float OPEN_MARGIN = 1.0e-3f;
private static final int LAVA_SEARCH_RADIUS = 1024;
private static final int LAVA_SEARCH_STEP = 16;
private static final int LAVA_CELLS = 4;
private static final int AGREEMENT_POINTS = 16;
private static final double AGREEMENT_TOLERANCE = 1.0;
private static final int AGREEMENT_OUTLIERS = 2;
private static final String SUBTERRAIN_STRUCTURES = "data/" + WorldgenExportRequest.DEFAULT_NAMESPACE + "/worldgen/structure/subterrain/";
private static final String SUBTERRAIN_TEMPLATES = "data/" + WorldgenExportRequest.DEFAULT_NAMESPACE + "/structure/subterrain/";
private static final int ROOM_GRID = 24;
private static final int ROOM_STEP_CHUNKS = 8;
private static final int ROOM_ATTEMPTS = 4;
private static final int ROOM_REACH = 128;
private static final Map<WorldgenExportMode, SortedMap<String, byte[]>> FILES = new EnumMap<>(WorldgenExportMode.class);
private static final Map<WorldgenExportMode, WorldgenExportSampler> SAMPLERS = new EnumMap<>(WorldgenExportMode.class);
private static SortedMap<String, byte[]> exportedOverworld;
private static WorldgenExportResult exportedOverworldResult;
private static ExportIr exportedOverworldIr;
@BeforeClass
public static void loadExports() throws IOException {
for (WorldgenExportMode mode : WorldgenExportMode.values()) {
SortedMap<String, byte[]> files = WorldgenJsonWriter.forTarget(DataVersion.V26_3).write(ExportIrFixtures.flatNoise(DataVersion.V26_3, mode));
FILES.put(mode, files);
SAMPLERS.put(mode, WorldgenExportSampler.open(files, mode, DIMENSION_ID, SEED));
}
}
@AfterClass
public static void closeExports() throws IOException {
for (WorldgenExportSampler sampler : SAMPLERS.values()) {
sampler.close();
}
SAMPLERS.clear();
FILES.clear();
exportedOverworld = null;
exportedOverworldResult = null;
exportedOverworldIr = null;
}
@Test
public void fixtureLoadsInEveryMode() {
for (WorldgenExportMode mode : WorldgenExportMode.values()) {
WorldgenExportSampler sampler = SAMPLERS.get(mode);
assertEquals(ExportIrFixtures.MIN_Y, sampler.minY());
assertEquals(ExportIrFixtures.HEIGHT, sampler.height());
assertEquals(ExportIrFixtures.SEA_LEVEL, sampler.seaLevel());
assertFalse(sampler.densityFunctionIds().isEmpty());
for (String id : sampler.densityFunctionIds()) {
assertTrue(mode + " " + id, sampler.registries().lookupOrThrow(Registries.DENSITY_FUNCTION).containsKey(Identifier.parse(id)));
}
assertTrue(sampler.registries().lookupOrThrow(Registries.NOISE_SETTINGS).containsKey(Identifier.parse(DIMENSION_ID)));
assertTrue(sampler.registries().lookupOrThrow(Registries.DIMENSION_TYPE).containsKey(Identifier.parse(DIMENSION_ID)));
assertTrue(sampler.registries().lookupOrThrow(Registries.MATERIAL_RULE).containsKey(Identifier.parse(DIMENSION_ID)));
boolean preset = sampler.registries().lookupOrThrow(Registries.WORLD_PRESET).containsKey(Identifier.parse(DIMENSION_ID));
boolean dimension = sampler.registries().lookupOrThrow(Registries.LEVEL_STEM).containsKey(Identifier.parse(DIMENSION_ID));
boolean overworld = sampler.registries().lookupOrThrow(Registries.LEVEL_STEM).containsKey(LevelStem.OVERWORLD.identifier());
assertEquals(mode.toString(), mode == WorldgenExportMode.PRESET, preset);
assertEquals(mode.toString(), mode == WorldgenExportMode.DIMENSION, dimension);
assertEquals(mode.toString(), mode == WorldgenExportMode.OVERWORLD, overworld);
}
WorldgenExportSampler presetSampler = SAMPLERS.get(WorldgenExportMode.PRESET);
Holder<WorldPreset> preset = presetSampler.registries().lookupOrThrow(Registries.WORLD_PRESET)
.getOrThrow(ResourceKey.create(Registries.WORLD_PRESET, Identifier.parse(DIMENSION_ID)));
assertTrue(preset.value().createWorldDimensions().get(LevelStem.NETHER).isPresent());
assertTrue(preset.value().createWorldDimensions().get(LevelStem.END).isPresent());
HolderSet.Named<WorldPreset> normal = presetSampler.registries().lookupOrThrow(Registries.WORLD_PRESET).getOrThrow(WorldPresetTags.NORMAL);
assertTrue(normal.contains(preset));
}
@Test
public void everyDensityFunctionEvaluatesFinite() {
for (WorldgenExportMode mode : WorldgenExportMode.values()) {
WorldgenExportSampler sampler = SAMPLERS.get(mode);
for (String id : sampler.densityFunctionIds()) {
for (int y : SAMPLE_Y) {
for (int xIndex = 0; xIndex < LATTICE; xIndex++) {
for (int zIndex = 0; zIndex < LATTICE; zIndex++) {
int x = (xIndex - LATTICE / 2) * LATTICE_STEP;
int z = (zIndex - LATTICE / 2) * LATTICE_STEP;
float value = sampler.density(id, x, y, z);
assertTrue(mode + " " + id + " at " + x + "," + y + "," + z + " = " + value, Float.isFinite(value));
}
}
}
}
}
}
@Test
public void baseHeightWithinDimension() {
for (WorldgenExportMode mode : WorldgenExportMode.values()) {
WorldgenExportSampler sampler = SAMPLERS.get(mode);
Set<Integer> heights = new HashSet<>();
int land = 0;
for (int xIndex = 0; xIndex < HEIGHT_POINTS; xIndex++) {
for (int zIndex = 0; zIndex < HEIGHT_POINTS; zIndex++) {
int x = (xIndex - HEIGHT_POINTS / 2) * HEIGHT_STEP;
int z = (zIndex - HEIGHT_POINTS / 2) * HEIGHT_STEP;
int height = sampler.baseHeight(x, z);
assertTrue(mode + " height " + height + " at " + x + "," + z,
height >= sampler.minY() && height <= sampler.minY() + sampler.height());
float surface = sampler.density(HEIGHT_ID, x, 0, z);
int floor = sampler.floorHeight(x, z);
assertTrue(mode + " height " + height + " below floor " + floor, height >= floor);
if (surface > sampler.seaLevel() + 1) {
assertTrue(mode + " floor " + floor + " against surface " + surface, Math.abs(floor - surface) <= SURFACE_TOLERANCE);
land++;
}
heights.add(height);
}
}
assertTrue(mode + " surface never varies", heights.size() > 1);
assertTrue(mode + " has no land column above sea level", land > 0);
}
}
@Test
public void resolverReturnsOnlyExportedBiomes() {
for (WorldgenExportMode mode : WorldgenExportMode.values()) {
WorldgenExportSampler sampler = SAMPLERS.get(mode);
Set<String> exported = exportedBiomes(FILES.get(mode), BIOME_PREFIX, ExportIrFixtures.NAMESPACE);
assertFalse(exported.isEmpty());
assertTrue(mode + " " + sampler.possibleBiomes(), exported.containsAll(sampler.possibleBiomes()));
for (int y : SAMPLE_Y) {
for (int xIndex = 0; xIndex < LATTICE; xIndex++) {
for (int zIndex = 0; zIndex < LATTICE; zIndex++) {
String biome = sampler.biome((xIndex - LATTICE / 2) * LATTICE_STEP, y, (zIndex - LATTICE / 2) * LATTICE_STEP);
assertTrue(mode + " " + biome, exported.contains(biome));
}
}
}
}
}
@Test
public void overworldPackLoads() throws Exception {
SortedMap<String, byte[]> files = overworldFiles();
assertGenerationBudget(exportedOverworldResult);
assertWallPalettesFallBack(exportedOverworldResult);
for (Map.Entry<String, byte[]> file : files.entrySet()) {
if (file.getKey().endsWith(".json")) {
int depth = NestingSplitter.depth(JsonParser.parseString(new String(file.getValue(), StandardCharsets.UTF_8)));
assertTrue(file.getKey() + " nests " + depth, depth <= MAX_NESTING);
}
if (file.getKey().endsWith(".nbt")) {
assertCompleteGzip(file.getKey(), file.getValue());
}
}
try (WorldgenExportSampler sampler = WorldgenExportSampler.open(files, WorldgenExportMode.OVERWORLD, OVERWORLD_ID, SEED)) {
Set<String> roots = new TreeSet<>();
for (String id : sampler.densityFunctionIds()) {
if (id.startsWith(OVERWORLD_ID + "/")) {
roots.add(id);
}
}
assertTrue(roots.toString(), roots.contains(OVERWORLD_ID + "/final_density"));
for (String id : roots) {
for (int y : SAMPLE_Y) {
for (int xIndex = 0; xIndex < OVERWORLD_LATTICE; xIndex++) {
for (int zIndex = 0; zIndex < OVERWORLD_LATTICE; zIndex++) {
int x = (xIndex - OVERWORLD_LATTICE / 2) * OVERWORLD_STEP;
int z = (zIndex - OVERWORLD_LATTICE / 2) * OVERWORLD_STEP;
float value = sampler.density(id, x, y, z);
assertTrue(id + " at " + x + "," + y + "," + z + " = " + value, Float.isFinite(value));
}
}
}
}
assertNaturalHeightMatchesTheEvaluator(exportedOverworldIr, sampler);
Set<String> exported = exportedBiomes(files, OVERWORLD_BIOME_PREFIX, WorldgenExportRequest.DEFAULT_NAMESPACE);
assertFalse(exported.isEmpty());
assertTrue(sampler.possibleBiomes().toString(), exported.containsAll(sampler.possibleBiomes()));
for (int xIndex = 0; xIndex < HEIGHT_POINTS; xIndex++) {
for (int zIndex = 0; zIndex < HEIGHT_POINTS; zIndex++) {
int x = (xIndex - HEIGHT_POINTS / 2) * HEIGHT_STEP;
int z = (zIndex - HEIGHT_POINTS / 2) * HEIGHT_STEP;
int height = sampler.baseHeight(x, z);
assertTrue("height " + height + " at " + x + "," + z, height >= sampler.minY() && height <= sampler.minY() + sampler.height());
for (int y : SAMPLE_Y) {
String biome = sampler.biome(x, y, z);
assertTrue(biome + " at " + x + "," + y + "," + z, exported.contains(biome));
}
}
}
}
}
@Test
public void overworldHasNoDisjointMinMax() throws Exception {
SortedMap<String, byte[]> files = overworldFiles();
try (WorldgenExportSampler sampler = WorldgenExportSampler.open(files, WorldgenExportMode.OVERWORLD, OVERWORLD_ID, SEED)) {
MinMaxAudit audit = new MinMaxAudit();
for (String id : sampler.densityFunctionIds()) {
audit.rewrite(sampler.registries().lookupOrThrow(Registries.DENSITY_FUNCTION)
.getOrThrow(ResourceKey.create(Registries.DENSITY_FUNCTION, Identifier.parse(id))).value());
}
System.out.println(LOG_PREFIX + " min/max nodes " + audit.checked() + ", disjoint " + audit.disjoint().size());
assertTrue(audit.checked() > 0);
assertTrue(audit.disjoint().size() + " disjoint min/max nodes: " + audit.disjoint(), audit.disjoint().isEmpty());
}
}
@Test
public void overworldDeepCavesOpenWithoutLava() throws Exception {
SortedMap<String, byte[]> files = overworldFiles();
String field = WorldgenExportRequest.DEFAULT_NAMESPACE + ":" + CAVE_FIELD;
long open = 0L;
long lava = 0L;
try (WorldgenExportSampler sampler = WorldgenExportSampler.open(files, WorldgenExportMode.OVERWORLD, OVERWORLD_ID, SEED)) {
assertTrue(field, sampler.densityFunctionIds().contains(field));
BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos();
for (int chunkX = -DEEP_CHUNKS; chunkX < DEEP_CHUNKS; chunkX++) {
for (int chunkZ = -DEEP_CHUNKS; chunkZ < DEEP_CHUNKS; chunkZ++) {
ProtoChunk chunk = sampler.terrainChunk(chunkX, chunkZ);
for (int x = 0; x < CHUNK_WIDTH; x++) {
for (int z = 0; z < CHUNK_WIDTH; z++) {
for (int y = OVERWORLD_LAVA_Y + 1; y < LAVA_LINE; y++) {
BlockState state = chunk.getBlockState(position.set(x, y, z));
assertFalse(state + " at chunk " + chunkX + "," + chunkZ + " " + x + "," + y + "," + z, state.is(Blocks.LAVA));
}
}
}
for (int x = 0; x < CHUNK_WIDTH; x += DEEP_STRIDE) {
for (int z = 0; z < CHUNK_WIDTH; z += DEEP_STRIDE) {
int blockX = (chunkX << 4) + x;
int blockZ = (chunkZ << 4) + z;
for (int y = OVERWORLD_LAVA_Y + 1; y < LAVA_LINE; y++) {
if (sampler.density(field, blockX, y, blockZ) > -OPEN_MARGIN) {
continue;
}
BlockState state = chunk.getBlockState(position.set(x, y, z));
assertTrue(state + " at " + blockX + "," + y + "," + blockZ, state.isAir());
open++;
}
}
}
}
}
for (BlockPos cell : openLavaBandCells(sampler, field)) {
ProtoChunk chunk = sampler.terrainChunk(cell.getX() >> 4, cell.getZ() >> 4);
BlockState state = chunk.getBlockState(position.set(cell.getX() & (CHUNK_WIDTH - 1), cell.getY(), cell.getZ() & (CHUNK_WIDTH - 1)));
assertTrue(state + " at " + cell, state.is(Blocks.LAVA));
lava++;
}
}
System.out.println(LOG_PREFIX + " deep cave cells open " + open + ", lava band cells " + lava);
assertTrue("no deep cave cell opened", open > 0L);
assertTrue("no lava band cell opened", lava > 0L);
}
@Test
public void overworldMaterialPassComputesTheCaveFieldOnce() throws Exception {
SortedMap<String, byte[]> files = overworldFiles();
try (WorldgenExportSampler sampler = WorldgenExportSampler.open(files, WorldgenExportMode.OVERWORLD, OVERWORLD_ID, SEED)) {
CompiledCaches caches = CompiledCaches.open(sampler.registries(), SEED);
int field = caches.rootId(caches.function(WorldgenExportRequest.DEFAULT_NAMESPACE + ":" + CAVE_FIELD));
List<OreVeinRule> veins = caches.oreVeins();
DensityFunction opening = veins.getFirst().density();
assertTrue(caches.ids(opening).contains(field));
assertTrue(caches.ids(caches.finalDensity()).contains(field));
Set<Integer> caveCaches = caches.ids(caches.function(WorldgenExportRequest.DEFAULT_NAMESPACE + ":" + CAVE_FIELD));
int shells = 0;
for (OreVeinRule vein : veins) {
if (!vein.oreBlock().isAir()) {
assertTrue("wall shell " + shells + " " + vein.oreBlock(), caches.ids(vein.density()).contains(field));
assertTrue("wall shell " + shells + " " + vein.oreBlock(), caveCaches.containsAll(caches.ids(vein.density())));
shells++;
}
}
JsonObject shell = JsonParser.parseString(new String(files.get("data/" + WorldgenExportRequest.DEFAULT_NAMESPACE + "/" + DENSITY_FUNCTION_RESOURCE
+ "/" + MaterialProgramCompiler.WALL_SHELL + ".json"), StandardCharsets.UTF_8)).getAsJsonObject();
double band = shell.get("max_exclusive").getAsDouble();
System.out.println(LOG_PREFIX + " material pass: " + veins.size() + " ore vein rules, " + shells + " wall shells read cave field cache " + field
+ " within band " + band);
assertTrue(String.valueOf(shells), shells > 0);
assertTrue(String.valueOf(band), band > 0.0 && band < WALL_SHELL_BAND_LIMIT);
}
}
@Test
public void overworldSubterrainRoomsPlace() throws Exception {
SortedMap<String, byte[]> files = overworldFiles();
SortedMap<String, JsonObject> structures = new TreeMap<>();
for (Map.Entry<String, byte[]> file : files.entrySet()) {
if (file.getKey().startsWith(SUBTERRAIN_STRUCTURES) && file.getKey().endsWith(".json")) {
String path = file.getKey().substring(SUBTERRAIN_STRUCTURES.length(), file.getKey().length() - ".json".length());
structures.put(WorldgenExportRequest.DEFAULT_NAMESPACE + ":subterrain/" + path,
JsonParser.parseString(new String(file.getValue(), StandardCharsets.UTF_8)).getAsJsonObject());
}
}
long templateBytes = 0L;
for (Map.Entry<String, byte[]> file : files.entrySet()) {
if (file.getKey().startsWith(SUBTERRAIN_TEMPLATES)) {
templateBytes += file.getValue().length;
}
}
System.out.println(LOG_PREFIX + " subterrain structures " + structures.size() + ", structure sets "
+ count(files, "/worldgen/structure_set/subterrain/", ".json") + ", templates " + count(files, "/structure/subterrain/", ".nbt")
+ ", template bytes " + templateBytes);
assertFalse(structures.isEmpty());
try (WorldgenExportSampler sampler = WorldgenExportSampler.open(files, WorldgenExportMode.OVERWORLD, OVERWORLD_ID, SEED)) {
for (Map.Entry<String, JsonObject> entry : structures.entrySet()) {
Structure structure = sampler.registries().lookupOrThrow(Registries.STRUCTURE)
.getOrThrow(ResourceKey.create(Registries.STRUCTURE, Identifier.parse(entry.getKey()))).value();
JsonObject height = entry.getValue().getAsJsonObject("start_height");
int y = (height.getAsJsonObject("min_inclusive").get("absolute").getAsInt()
+ height.getAsJsonObject("max_inclusive").get("absolute").getAsInt()) / 2;
List<ChunkPos> matches = new ArrayList<>();
for (int xIndex = 0; xIndex < ROOM_GRID; xIndex++) {
for (int zIndex = 0; zIndex < ROOM_GRID; zIndex++) {
ChunkPos chunk = new ChunkPos((xIndex - ROOM_GRID / 2) * ROOM_STEP_CHUNKS, (zIndex - ROOM_GRID / 2) * ROOM_STEP_CHUNKS);
String biome = sampler.biome(chunk.getMinBlockX(), y, chunk.getMinBlockZ());
Holder<Biome> holder = sampler.registries().lookupOrThrow(Registries.BIOME)
.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(biome)));
if (structure.biomes().contains(holder)) {
matches.add(chunk);
}
}
}
System.out.println(String.format(Locale.ROOT, "%s subterrain %s biome match %d/%d at y %d", LOG_PREFIX, entry.getKey(),
matches.size(), ROOM_GRID * ROOM_GRID, y));
assertFalse(entry.getKey() + " finds no biome at y " + y, matches.isEmpty());
StructureStart start = null;
for (ChunkPos chunk : matches.subList(0, Math.min(ROOM_ATTEMPTS, matches.size()))) {
StructureStart candidate = sampler.structureStart(entry.getKey(), chunk.x(), chunk.z());
if (candidate.isValid()) {
start = candidate;
BoundingBox box = start.getBoundingBox();
assertTrue(entry.getKey() + " " + box, chunk.getMinBlockX() - box.minX() <= ROOM_REACH && box.maxX() - chunk.getMinBlockX() <= ROOM_REACH);
assertTrue(entry.getKey() + " " + box, chunk.getMinBlockZ() - box.minZ() <= ROOM_REACH && box.maxZ() - chunk.getMinBlockZ() <= ROOM_REACH);
assertTrue(entry.getKey() + " " + box, box.minY() >= sampler.minY() && box.maxY() < sampler.minY() + sampler.height());
break;
}
}
assertTrue(entry.getKey() + " never starts", start != null);
}
}
}
private static List<BlockPos> openLavaBandCells(WorldgenExportSampler sampler, String field) {
List<BlockPos> cells = new ArrayList<>(LAVA_CELLS);
for (int x = -LAVA_SEARCH_RADIUS; x < LAVA_SEARCH_RADIUS; x += LAVA_SEARCH_STEP) {
for (int z = -LAVA_SEARCH_RADIUS; z < LAVA_SEARCH_RADIUS; z += LAVA_SEARCH_STEP) {
for (int y = sampler.minY(); y <= OVERWORLD_LAVA_Y; y++) {
if (sampler.density(field, x, y, z) > -OPEN_MARGIN) {
continue;
}
cells.add(new BlockPos(x, y, z));
if (cells.size() == LAVA_CELLS) {
return cells;
}
}
}
}
return cells;
}
private static synchronized SortedMap<String, byte[]> overworldFiles() throws Exception {
String probePack = System.getProperty(PROBE_PACK);
Assume.assumeTrue("Set -P" + PROBE_PACK + " to export a real pack", probePack != null && !probePack.isBlank());
if (exportedOverworld != null) {
return exportedOverworld;
}
Path root = overworldFolder.newFolder("exports").toPath();
SortedMap<String, byte[]> untrimmed = new TreeMap<>();
AtomicReference<ExportIr> compiled = new AtomicReference<>();
WorldgenExportResult result;
try (RealPackProbeSupport.Workspace workspace = RealPackProbeSupport.openWorkspace(new RealPackProbeSupport.WorkspaceOptions(
new File(probePack), OVERWORLD, LOG_PREFIX, new HeadlessNativeRuntime(), overworldFolder.newFolder("workspace").toPath()))) {
WorldgenExportRequest request = WorldgenExportRequest.builder()
.pack(workspace.pack().toPath())
.dimension(OVERWORLD)
.exportRoot(root)
.objects(true)
.build();
result = new WorldgenDatapackExporter(target -> ir -> {
compiled.set(ir);
SortedMap<String, byte[]> written = WorldgenJsonWriter.forTarget(target).write(ir);
untrimmed.putAll(written);
return written;
}, PackCompiler.create()).export(request, WorldgenExportProgress.NONE);
}
assertTrue(result.message() + " " + result.diagnostics(), result.isSuccess());
SortedMap<String, byte[]> files = zipEntries(result.output());
Path untrimmedZip = root.resolve("untrimmed.zip");
new AtomicDatapackPublisher().publish(untrimmed, untrimmedZip, DatapackExportFormat.ZIP, false, ".untrimmed-");
report(result, untrimmed, Files.size(untrimmedZip), files);
exportedOverworld = files;
exportedOverworldResult = result;
exportedOverworldIr = compiled.get();
return files;
}
private static void assertGenerationBudget(WorldgenExportResult result) {
GenerationCost cost = result.cost();
Set<String> flagged = new TreeSet<>();
for (ExportDiagnostic diagnostic : result.diagnostics()) {
if (diagnostic.limit() == ExportLimit.GENERATION_COST) {
flagged.add(diagnostic.resource());
}
}
for (GenerationCost.Root root : GenerationCost.Root.values()) {
GenerationCost.RootCost rootCost = cost.root(root).orElseThrow();
System.out.println(String.format(Locale.ROOT, "%s cost %s worst case %.3e expanded %.3e distinct %d", LOG_PREFIX, root.id(),
rootCost.worstCaseNodes(), rootCost.expandedNodes(), rootCost.distinctNodes()));
}
for (GenerationCost.Root root : GenerationCost.Root.values()) {
if (!root.climate()) {
continue;
}
double limit = GenerationBudget.worstCaseLimit(root).orElseThrow();
double nodes = cost.root(root).orElseThrow().worstCaseNodes();
String resource = "noise_settings/" + OVERWORLD + "/" + root.id();
assertTrue(root.id() + " evaluates " + nodes + " nodes, budget " + limit, nodes <= limit);
assertFalse(resource + " " + flagged, flagged.contains(resource));
}
long finalDensity = cost.root(GenerationCost.Root.FINAL_DENSITY).orElseThrow().distinctNodes();
String finalResource = "noise_settings/" + OVERWORLD + "/" + GenerationCost.Root.FINAL_DENSITY.id();
System.out.println(String.format(Locale.ROOT, "%s final_density distinct %d of %d, density function JSON %.1f of %.1f MB", LOG_PREFIX, finalDensity,
GenerationBudget.FINAL_DENSITY_DISTINCT_NODES, cost.densityFunctionBytes() / MEGABYTE, GenerationBudget.DENSITY_FUNCTION_JSON_BYTES / MEGABYTE));
assertEquals(finalResource + " " + flagged, finalDensity > GenerationBudget.FINAL_DENSITY_DISTINCT_NODES, flagged.contains(finalResource));
assertTrue(cost.densityFunctionBytes() + " bytes", cost.densityFunctionBytes() > 0L);
assertTrue(cost.densityFunctionBytes() + " bytes", cost.densityFunctionBytes() <= GenerationBudget.DENSITY_FUNCTION_JSON_BYTES);
assertFalse(flagged.toString(), flagged.contains(DENSITY_FUNCTION_RESOURCE));
}
private static void assertWallPalettesFallBack(WorldgenExportResult result) {
int fallbacks = 0;
for (ExportDiagnostic diagnostic : result.diagnostics()) {
if (diagnostic.limit() == ExportLimit.WALL_PALETTE && diagnostic.severity() == ExportDiagnostic.Severity.WARNING) {
assertTrue(diagnostic.resource() + " " + diagnostic.message(), diagnostic.message().contains(WALL_FALLBACK));
fallbacks++;
}
}
System.out.println(LOG_PREFIX + " wall palettes over the ore vein budget " + fallbacks);
}
private static void assertNaturalHeightMatchesTheEvaluator(ExportIr ir, WorldgenExportSampler sampler) {
Field.Shared height = shared(ir.router().chunkSurfaceLevel(), HeightCompiler.HEIGHT);
Map<String, NoiseDef> noises = new HashMap<>();
for (NoiseDef noise : ir.noises()) {
noises.put(ir.namespace() + ":" + noise.id(), noise);
}
String heightId = ir.namespace() + ":" + HeightCompiler.HEIGHT;
int outliers = 0;
StringBuilder detail = new StringBuilder();
for (int xIndex = 0; xIndex < AGREEMENT_POINTS; xIndex++) {
for (int zIndex = 0; zIndex < AGREEMENT_POINTS; zIndex++) {
int x = (xIndex - AGREEMENT_POINTS / 2) * OVERWORLD_STEP;
int z = (zIndex - AGREEMENT_POINTS / 2) * OVERWORLD_STEP;
double evaluated = FieldEvaluator.sample(height.expr(), noises, SEED, DataVersion.V26_3, x, 0, z);
double exported = sampler.density(heightId, x, 0, z);
if (Math.abs(evaluated - exported) > AGREEMENT_TOLERANCE) {
outliers++;
detail.append(' ').append(x).append(',').append(z).append('=').append(evaluated).append('/').append(exported);
}
}
}
assertTrue(outliers + " columns differ:" + detail, outliers <= AGREEMENT_OUTLIERS);
}
private static Field.Shared shared(Field root, String name) {
Set<Field> visited = Collections.newSetFromMap(new IdentityHashMap<>());
Deque<Field> pending = new ArrayDeque<>();
pending.push(root);
while (!pending.isEmpty()) {
Field field = pending.pop();
if (!visited.add(field)) {
continue;
}
if (field instanceof Field.Shared candidate && candidate.name().equals(name)) {
return candidate;
}
for (Field child : FieldMacros.children(field)) {
pending.push(child);
}
}
throw new AssertionError("Router has no shared field " + name);
}
private static void assertCompleteGzip(String path, byte[] bytes) throws IOException {
try (InputStream input = new GZIPInputStream(new ByteArrayInputStream(bytes))) {
input.readAllBytes();
assertEquals(path, -1, input.read());
}
}
private static void report(WorldgenExportResult result, SortedMap<String, byte[]> untrimmed, long untrimmedZipBytes,
SortedMap<String, byte[]> files) throws IOException {
SortedMap<ExportLimit, Integer> limits = new TreeMap<>();
for (ExportDiagnostic diagnostic : result.diagnostics()) {
limits.merge(diagnostic.limit(), 1, Integer::sum);
}
System.out.println(LOG_PREFIX + " untrimmed zip bytes " + untrimmedZipBytes + ", files " + untrimmed.size()
+ ", trimmed zip bytes " + Files.size(result.output()) + ", files " + files.size() + ", trim " + result.trim());
System.out.println(LOG_PREFIX + " diagnostics " + result.diagnostics().size() + " " + limits);
reportCounts("untrimmed", untrimmed);
reportCounts("trimmed", files);
}
private static void reportCounts(String label, SortedMap<String, byte[]> files) {
System.out.println(LOG_PREFIX + " " + label + " templates " + count(files, "/structure/", ".nbt")
+ ", structures " + count(files, "/worldgen/structure/", ".json")
+ ", structure sets " + count(files, "/worldgen/structure_set/", ".json")
+ ", placed features " + count(files, "/worldgen/placed_feature/", ".json")
+ ", features " + count(files, "/worldgen/feature/", ".json")
+ ", density functions " + count(files, "/worldgen/density_function/", ".json")
+ ", noises " + count(files, "/worldgen/noise/", ".json")
+ ", biomes " + count(files, "/worldgen/biome/", ".json"));
}
private static int count(SortedMap<String, byte[]> files, String folder, String suffix) {
int count = 0;
for (String path : files.keySet()) {
if (path.contains(folder) && path.endsWith(suffix)) {
count++;
}
}
return count;
}
private static SortedMap<String, byte[]> zipEntries(Path zip) throws IOException {
SortedMap<String, byte[]> files = new TreeMap<>();
try (ZipFile archive = new ZipFile(zip.toFile())) {
Enumeration<? extends ZipEntry> entries = archive.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (!entry.isDirectory()) {
files.put(entry.getName(), archive.getInputStream(entry).readAllBytes());
}
}
}
return files;
}
private static Set<String> exportedBiomes(SortedMap<String, byte[]> files, String prefix, String namespace) {
Set<String> biomes = new TreeSet<>();
for (String path : files.keySet()) {
if (path.startsWith(prefix)) {
biomes.add(namespace + ":" + path.substring(prefix.length(), path.length() - ".json".length()));
}
}
return biomes;
}
private static final class MinMaxAudit implements DfRewriteRule {
private final Set<DensityFunction> visited = Collections.newSetFromMap(new IdentityHashMap<>());
private final List<String> disjoint = new ArrayList<>();
private int checked;
@Override
public DensityFunction rewrite(DensityFunction function) {
if (!visited.add(function)) {
return function;
}
if (function instanceof BinaryFunction binary && (binary.type() == BinaryFunction.Type.MIN || binary.type() == BinaryFunction.Type.MAX)) {
checked++;
Interval left = binary.left().range();
Interval right = binary.right().range();
if (left.max() < right.min() || right.max() < left.min()) {
disjoint.add(binary.type() + " " + left + " " + right);
}
}
function.rewriteChildren(this);
return function;
}
private int checked() {
return checked;
}
private List<String> disjoint() {
return disjoint;
}
}
}
@@ -0,0 +1,136 @@
package art.arcane.iris.probe;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.WorldgenDatapackExporter;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.WorldgenExportRequest;
import art.arcane.iris.pack.datapack.export.WorldgenExportResult;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ProtoChunk;
import net.minecraft.world.level.levelgen.densityfunction.DensityFunction;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public final class WorldgenExportDeepCaves263Test {
@ClassRule
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
private static final long SEED = 1337L;
private static final String NAMESPACE = WorldgenExportRequest.DEFAULT_NAMESPACE;
private static final String DIMENSION_ID = NAMESPACE + ":" + ExportTestPacks.DIMENSION;
private static final int MIN_Y = -64;
private static final int LAVA_Y = -62;
private static final int LAVA_LINE = -54;
private static final int CAVE_TOP = -14;
private static final int CHUNK_WIDTH = 16;
private static final String CAVE_FIELD = "cave/field";
private static final String DIMENSION = """
{
"regions": ["region"],
"dimensionHeight": {"min": -64, "max": 192},
"fluidHeight": 63,
"caveLavaHeight": 2,
"caveProfile": {
"enabled": true,
"verticalRange": {"min": 0, "max": 50},
"verticalEdgeFade": 0,
"baseDensityStyle": {"style": "SIMPLEX", "zoom": 0.6},
"detailDensityStyle": {"style": "SIMPLEX", "zoom": 0.3},
"baseWeight": 1.0,
"detailWeight": 0.0,
"densityThreshold": {"min": 5.0, "max": 5.0, "style": {"style": "SIMPLEX"}},
"thresholdBias": 0.0,
"surfaceClearance": 0,
"allowSurfaceBreak": false,
"allowFluid": false,
"allowLava": true,
"modules": []
}
}
""";
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void deepCavesOpenAsAirAboveTheIrisLavaBand() throws IOException {
WorldgenExportResult result = export();
assertTrue(result.message() + " " + result.diagnostics(), result.isSuccess());
JsonObject head = JsonParser.parseString(Files.readString(result.output().resolve("data/" + NAMESPACE + "/worldgen/material_rule/"
+ ExportTestPacks.DIMENSION + ".json"), StandardCharsets.UTF_8)).getAsJsonObject().getAsJsonArray("sequence").get(0).getAsJsonObject();
assertEquals("minecraft:ore_vein", head.get("type").getAsString());
String opening = head.get("density").getAsString();
assertTrue(opening, Files.isRegularFile(densityFunction(result.output(), opening)));
try (WorldgenExportSampler sampler = WorldgenExportSampler.open(result.output(), WorldgenExportMode.OVERWORLD, DIMENSION_ID, SEED)) {
ProtoChunk chunk = sampler.terrainChunk(0, 0);
for (int x = 0; x < CHUNK_WIDTH; x++) {
for (int z = 0; z < CHUNK_WIDTH; z++) {
for (int y = MIN_Y; y <= CAVE_TOP; y++) {
BlockState state = chunk.getBlockState(new BlockPos(x, y, z));
String where = state + " at " + x + "," + y + "," + z;
if (y <= LAVA_Y) {
assertTrue(where, state.is(Blocks.LAVA));
} else {
assertTrue(where, state.isAir());
}
}
}
}
assertTrue(chunk.getBlockState(new BlockPos(0, LAVA_LINE - 1, 0)).isAir());
}
}
@Test
public void deepCaveRuleSharesTheCaveFieldCacheWithTheFinalDensity() throws IOException {
WorldgenExportResult result = export();
assertTrue(result.message() + " " + result.diagnostics(), result.isSuccess());
try (WorldgenExportSampler sampler = WorldgenExportSampler.open(result.output(), WorldgenExportMode.OVERWORLD, DIMENSION_ID, SEED)) {
CompiledCaches caches = CompiledCaches.open(sampler.registries(), SEED);
DensityFunction opening = caches.oreVeins().getFirst().density();
int field = caches.rootId(caches.function(NAMESPACE + ":" + CAVE_FIELD));
Set<Integer> finalDensity = caches.ids(caches.finalDensity());
assertTrue(caches.ids(opening).toString(), caches.ids(opening).contains(field));
assertTrue(finalDensity.toString(), finalDensity.contains(field));
assertTrue(finalDensity.toString(), finalDensity.contains(caches.rootId(opening)));
}
}
private WorldgenExportResult export() throws IOException {
File pack = ExportTestPacks.withDimension(temporaryFolder.newFolder("pack"), DIMENSION);
WorldgenExportRequest request = WorldgenExportRequest.builder()
.pack(pack.toPath())
.dimension(ExportTestPacks.DIMENSION)
.exportRoot(temporaryFolder.newFolder("exports").toPath())
.format("directory")
.build();
return WorldgenDatapackExporter.create().export(request, WorldgenExportProgress.NONE);
}
private static Path densityFunction(Path datapack, String id) {
int separator = id.indexOf(':');
return datapack.resolve("data/" + id.substring(0, separator) + "/worldgen/density_function/" + id.substring(separator + 1) + ".json");
}
}
@@ -0,0 +1,75 @@
package art.arcane.iris.probe;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.WorldgenDatapackExporter;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.WorldgenExportRequest;
import art.arcane.iris.pack.datapack.export.WorldgenExportResult;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public final class WorldgenExportPipeline263Test {
@ClassRule
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
private static final long SEED = 1337L;
private static final String DIMENSION_ID = WorldgenExportRequest.DEFAULT_NAMESPACE + ":" + ExportTestPacks.DIMENSION;
private static final int[] SAMPLE_Y = {-64, 0, 64, 200};
private static final int LATTICE = 8;
private static final int LATTICE_STEP = 61;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void exportedPackLoadsAndSamples() throws IOException {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
Path root = temporaryFolder.newFolder("exports").toPath();
WorldgenExportRequest request = WorldgenExportRequest.builder()
.pack(pack.toPath())
.dimension(ExportTestPacks.DIMENSION)
.exportRoot(root)
.format("directory")
.build();
WorldgenExportResult result = WorldgenDatapackExporter.create().export(request, WorldgenExportProgress.NONE);
assertTrue(result.message() + " " + result.diagnostics(), result.isSuccess());
try (WorldgenExportSampler sampler = WorldgenExportSampler.open(result.output(), WorldgenExportMode.OVERWORLD, DIMENSION_ID, SEED)) {
assertFalse(sampler.densityFunctionIds().isEmpty());
for (String id : sampler.densityFunctionIds()) {
for (int y : SAMPLE_Y) {
for (int xIndex = 0; xIndex < LATTICE; xIndex++) {
for (int zIndex = 0; zIndex < LATTICE; zIndex++) {
int x = (xIndex - LATTICE / 2) * LATTICE_STEP;
int z = (zIndex - LATTICE / 2) * LATTICE_STEP;
float value = sampler.density(id, x, y, z);
assertTrue(id + " at " + x + "," + y + "," + z + " = " + value, Float.isFinite(value));
}
}
}
}
for (int xIndex = 0; xIndex < LATTICE; xIndex++) {
for (int zIndex = 0; zIndex < LATTICE; zIndex++) {
int x = (xIndex - LATTICE / 2) * LATTICE_STEP;
int z = (zIndex - LATTICE / 2) * LATTICE_STEP;
int height = sampler.baseHeight(x, z);
assertTrue("height " + height + " at " + x + "," + z, height >= sampler.minY() && height <= sampler.minY() + sampler.height());
}
}
}
}
}
@@ -0,0 +1,97 @@
package art.arcane.iris.probe;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.WorldgenDatapackExporter;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.WorldgenExportRequest;
import art.arcane.iris.pack.datapack.export.WorldgenExportResult;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public final class WorldgenExportSamplerThreadsTest {
@ClassRule
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
private static final long SEED = 1337L;
private static final String DIMENSION_ID = WorldgenExportRequest.DEFAULT_NAMESPACE + ":" + ExportTestPacks.DIMENSION;
private static final String FINAL_DENSITY_ID = DIMENSION_ID + "/final_density";
private static final int THREADS = 8;
private static final int POINTS = 2048;
private static final int ROW = 64;
private static final int STEP = 37;
private static final int ROUNDS = 3;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void concurrentSamplingMatchesSequentialSampling() throws Exception {
File pack = ExportTestPacks.basic(temporaryFolder.newFolder("pack"));
WorldgenExportRequest request = WorldgenExportRequest.builder()
.pack(pack.toPath())
.dimension(ExportTestPacks.DIMENSION)
.exportRoot(temporaryFolder.newFolder("exports").toPath())
.format("directory")
.build();
WorldgenExportResult result = WorldgenDatapackExporter.create().export(request, WorldgenExportProgress.NONE);
assertTrue(result.message() + " " + result.diagnostics(), result.isSuccess());
try (WorldgenExportSampler sampler = WorldgenExportSampler.open(result.output(), WorldgenExportMode.OVERWORLD, DIMENSION_ID, SEED)) {
assertTrue(sampler.densityFunctionIds().toString(), sampler.densityFunctionIds().contains(FINAL_DENSITY_ID));
Sample expected = sweep(sampler, 0, 1).call();
ExecutorService executor = Executors.newFixedThreadPool(THREADS);
try {
List<Future<Sample>> futures = new ArrayList<>(THREADS);
for (int thread = 0; thread < THREADS; thread++) {
futures.add(executor.submit(sweep(sampler, thread * (POINTS / THREADS), ROUNDS)));
}
for (Future<Sample> future : futures) {
Sample sample = future.get();
assertArrayEquals(expected.density(), sample.density(), 0.0F);
assertEquals(List.of(expected.biome()), List.of(sample.biome()));
}
} finally {
executor.shutdownNow();
}
}
}
private static Callable<Sample> sweep(WorldgenExportSampler sampler, int offset, int rounds) {
return () -> {
float[] density = new float[POINTS];
String[] biome = new String[POINTS];
for (int round = 0; round < rounds; round++) {
for (int step = 0; step < POINTS; step++) {
int index = (offset + step) % POINTS;
int x = (index % ROW - ROW / 2) * STEP;
int y = (index * 7) % 256 - 64;
int z = (index / ROW - POINTS / ROW / 2) * STEP;
density[index] = sampler.density(FINAL_DENSITY_ID, x, y, z);
biome[index] = sampler.biome(x, y, z);
}
}
return new Sample(density, biome);
};
}
private record Sample(float[] density, String[] biome) {
}
}
@@ -0,0 +1,90 @@
package art.arcane.iris.probe;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.WorldgenDatapackExporter;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.WorldgenExportRequest;
import art.arcane.iris.pack.datapack.export.WorldgenExportResult;
import art.arcane.iris.testsupport.CompatTestPlatform;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ProtoChunk;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public final class WorldgenExportSeaLevel263Test {
@ClassRule
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
private static final long SEED = 1337L;
private static final String DIMENSION_ID = WorldgenExportRequest.DEFAULT_NAMESPACE + ":" + ExportTestPacks.DIMENSION;
private static final int FLUID_HEIGHT = 40;
private static final int SEA_FLOOR = 28;
private static final int CHUNK_WIDTH = 16;
private static final String DIMENSION = """
{
"regions": ["region"],
"dimensionHeight": {"min": -64, "max": 192},
"fluidHeight": 40,
"landChance": 0,
"carvingEnabled": false
}
""";
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void waterFillsThroughTheIrisFluidHeight() throws IOException {
WorldgenExportResult result = export();
assertTrue(result.message() + " " + result.diagnostics(), result.isSuccess());
try (WorldgenExportSampler sampler = WorldgenExportSampler.open(result.output(), WorldgenExportMode.OVERWORLD, DIMENSION_ID, SEED)) {
ProtoChunk chunk = sampler.terrainChunk(0, 0);
for (int x = 0; x < CHUNK_WIDTH; x++) {
for (int z = 0; z < CHUNK_WIDTH; z++) {
assertSolid(chunk.getBlockState(new BlockPos(x, SEA_FLOOR, z)), x, z);
for (int y = SEA_FLOOR + 1; y <= FLUID_HEIGHT; y++) {
BlockState state = chunk.getBlockState(new BlockPos(x, y, z));
assertTrue(state + " at " + x + "," + y + "," + z, state.is(Blocks.WATER));
}
BlockState above = chunk.getBlockState(new BlockPos(x, FLUID_HEIGHT + 1, z));
assertTrue(above + " above the fluid height at " + x + "," + z, above.isAir());
}
}
assertEquals(FLUID_HEIGHT + 1, sampler.seaLevel());
}
}
private static void assertSolid(BlockState state, int x, int z) {
assertTrue(state + " sea floor at " + x + "," + z, !state.isAir() && state.getFluidState().isEmpty());
}
private WorldgenExportResult export() throws IOException {
File pack = ExportTestPacks.withDimension(temporaryFolder.newFolder("pack"), DIMENSION);
CompatTestPlatform.write(pack, "generators/flat.json", "{\"composite\":[]}");
CompatTestPlatform.write(pack, "biomes/ocean.json", """
{"name":"Ocean","generators":[{"generator":"flat","min":-12,"max":-12}]}
""");
WorldgenExportRequest request = WorldgenExportRequest.builder()
.pack(pack.toPath())
.dimension(ExportTestPacks.DIMENSION)
.exportRoot(temporaryFolder.newFolder("exports").toPath())
.format("directory")
.build();
return WorldgenDatapackExporter.create().export(request, WorldgenExportProgress.NONE);
}
}
@@ -0,0 +1,165 @@
package art.arcane.iris.probe;
import art.arcane.iris.pack.datapack.export.ExportTestPacks;
import art.arcane.iris.pack.datapack.export.WorldgenDatapackExporter;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.WorldgenExportRequest;
import art.arcane.iris.pack.datapack.export.WorldgenExportResult;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtAccounter;
import net.minecraft.nbt.NbtIo;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.Rotation;
import net.minecraft.world.level.levelgen.GenerationStep;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructureSet;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadStructurePlacement;
import net.minecraft.world.level.levelgen.structure.pools.ListPoolElement;
import net.minecraft.world.level.levelgen.structure.structures.JigsawStructure;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public final class WorldgenExportSubterrain263Test {
@ClassRule
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
private static final long SEED = 1337L;
private static final String DIMENSION_ID = WorldgenExportRequest.DEFAULT_NAMESPACE + ":" + ExportTestPacks.DIMENSION;
private static final String POOLS = WorldgenExportRequest.DEFAULT_NAMESPACE + ":subterrain/pools";
private static final String TUBES = WorldgenExportRequest.DEFAULT_NAMESPACE + ":subterrain/tubes";
private static final String ANCHOR = WorldgenExportRequest.DEFAULT_NAMESPACE + ":subterrain/anchor";
private static final String TEMPLATES = "data/" + WorldgenExportRequest.DEFAULT_NAMESPACE + "/structure/subterrain/";
private static final int CHUNK_X = 3;
private static final int CHUNK_Z = -2;
private static final int POOLS_CENTER_Y = -49;
private static final int POOLS_BELOW_CENTER = 10;
private static final int POOLS_EXTENT = 10;
private static final int MAX_REACH = 128;
private static final String DIMENSION = """
{"regions": ["region"], "subterrainFeatures": [
{"id": "pools", "family": "CENOTE", "worldYRange": {"min": -60, "max": -40}, "spacing": 64, "probability": 1.0,
"radius": 8, "height": 12, "fluid": "WATER", "fluidDepth": 2, "shapeWarp": 0.5, "pillarSpacing": 0,
"formationFraction": 0.0, "solid": "minecraft:stone"},
{"id": "tubes", "family": "LAVA_TUBE", "allowedRegions": ["region"], "worldYRange": {"min": -60, "max": 40},
"spacing": 320, "probability": 0.5, "length": 300, "radius": 6, "height": 8, "fluidDepth": 2, "chimneyHeight": 0,
"shapeWarp": 0.0, "pillarSpacing": 0, "formationFraction": 0.0, "solid": "minecraft:stone"}]}
""";
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
@Test
public void subterrainRoomsLoadAndPlaceThroughRealCodecs() throws IOException {
File pack = ExportTestPacks.withDimension(temporaryFolder.newFolder("pack"), DIMENSION);
WorldgenExportRequest request = WorldgenExportRequest.builder()
.pack(pack.toPath())
.dimension(ExportTestPacks.DIMENSION)
.exportRoot(temporaryFolder.newFolder("exports").toPath())
.format("directory")
.build();
WorldgenExportResult result = WorldgenDatapackExporter.create().export(request, WorldgenExportProgress.NONE);
assertTrue(result.message() + " " + result.diagnostics(), result.isSuccess());
try (WorldgenExportSampler sampler = WorldgenExportSampler.open(result.output(), WorldgenExportMode.OVERWORLD, DIMENSION_ID, SEED)) {
assertRegistered(sampler, POOLS, 4, 2);
assertRegistered(sampler, TUBES, 20, 10);
int cornerX = CHUNK_X << 4;
int cornerZ = CHUNK_Z << 4;
BoundingBox pools = placedBox(sampler, POOLS);
assertEquals(cornerX - POOLS_EXTENT, pools.minX());
assertEquals(cornerX + POOLS_EXTENT, pools.maxX());
assertEquals(cornerZ - POOLS_EXTENT, pools.minZ());
assertEquals(cornerZ + POOLS_EXTENT, pools.maxZ());
assertEquals(POOLS_CENTER_Y - POOLS_BELOW_CENTER, pools.minY());
BoundingBox tubes = placedBox(sampler, TUBES);
assertEquals(2 * MAX_REACH + 1, Math.max(tubes.getXSpan(), tubes.getZSpan()));
assertTrue(tubes.toString(), tubes.minX() >= cornerX - MAX_REACH && tubes.maxX() <= cornerX + MAX_REACH);
assertTrue(tubes.toString(), tubes.minZ() >= cornerZ - MAX_REACH && tubes.maxZ() <= cornerZ + MAX_REACH);
assertTrue(tubes.toString(), tubes.minY() >= -60 && tubes.maxY() <= 40);
}
assertTemplatesResolve(result.output());
}
private static void assertRegistered(WorldgenExportSampler sampler, String id, int spacing, int separation) {
Identifier identifier = Identifier.parse(id);
Structure structure = sampler.registries().lookupOrThrow(Registries.STRUCTURE)
.getOrThrow(ResourceKey.create(Registries.STRUCTURE, identifier)).value();
assertTrue(id, structure instanceof JigsawStructure);
assertEquals(id, GenerationStep.Decoration.UNDERGROUND_STRUCTURES, structure.step());
StructureSet set = sampler.registries().lookupOrThrow(Registries.STRUCTURE_SET)
.getOrThrow(ResourceKey.create(Registries.STRUCTURE_SET, identifier)).value();
RandomSpreadStructurePlacement placement = (RandomSpreadStructurePlacement) set.placement();
assertEquals(id, spacing, placement.spacing());
assertEquals(id, separation, placement.separation());
assertTrue(id, sampler.registries().lookupOrThrow(Registries.TEMPLATE_POOL).containsKey(identifier));
}
private static BoundingBox placedBox(WorldgenExportSampler sampler, String id) throws IOException {
StructureStart start = sampler.structureStart(id, CHUNK_X, CHUNK_Z);
assertTrue(id, start.isValid());
assertEquals(id, 1, start.getPieces().size());
PoolElementStructurePiece piece = (PoolElementStructurePiece) start.getPieces().getFirst();
assertTrue(id + " " + piece.getElement(), piece.getElement() instanceof ListPoolElement);
return start.getBoundingBox();
}
private static void assertTemplatesResolve(Path datapack) throws IOException {
List<Path> templates;
try (Stream<Path> paths = Files.walk(datapack.resolve(TEMPLATES))) {
templates = paths.filter(path -> path.toString().endsWith(".nbt")).sorted().toList();
}
assertEquals(12, templates.size());
boolean lava = false;
for (Path path : templates) {
CompoundTag tag;
try (InputStream input = Files.newInputStream(path)) {
tag = NbtIo.readCompressed(input, NbtAccounter.unlimitedHeap());
}
StructureTemplate template = new StructureTemplate();
template.load(BuiltInRegistries.BLOCK, tag);
StructurePlaceSettings settings = new StructurePlaceSettings();
assertTrue(path.toString(), template.filterBlocks(BlockPos.ZERO, settings, Blocks.AIR).isEmpty());
if (path.getFileName().toString().endsWith("_core.nbt")) {
assertFalse(path.toString(), template.filterBlocks(BlockPos.ZERO, settings, Blocks.CAVE_AIR).isEmpty());
List<StructureTemplate.JigsawBlockInfo> jigsaws = template.getJigsaws(BlockPos.ZERO, Rotation.NONE);
assertEquals(path.toString(), 1, jigsaws.size());
assertEquals(ANCHOR, jigsaws.getFirst().name().toString());
lava |= !template.filterBlocks(BlockPos.ZERO, settings, Blocks.LAVA).isEmpty();
} else {
assertFalse(path.toString(), template.filterBlocks(BlockPos.ZERO, settings, Blocks.STONE).isEmpty());
}
}
assertTrue("no lava tube template holds lava", lava);
}
}
@@ -0,0 +1,111 @@
package art.arcane.iris.probe;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportIrFixtures;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.emit.WorldgenJsonWriter;
import net.minecraft.world.level.levelgen.Heightmap;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.SortedMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public final class WorldgenStageBenchTest {
@ClassRule
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
private static final long SEED = 1337L;
private static final int SIDE = 2;
private static final WorldgenStageBench.CallBudget BUDGET = new WorldgenStageBench.CallBudget(32, 8, 0L);
private static HeadlessNativeRegistries loaded;
@BeforeClass
public static void loadFixture() throws IOException {
HeadlessNativeBootstrap.initialize();
SortedMap<String, byte[]> files = WorldgenJsonWriter.forTarget(DataVersion.V26_3)
.write(ExportIrFixtures.flatNoise(DataVersion.V26_3, WorldgenExportMode.PRESET));
Path directory = Files.createTempDirectory("iris-stage-bench-");
for (Map.Entry<String, byte[]> file : files.entrySet()) {
Path target = directory.resolve(file.getKey());
Files.createDirectories(target.getParent());
Files.write(target, file.getValue());
}
try (PaperRegistryScope scope = PaperRegistryScope.open()) {
loaded = HeadlessNativeRegistries.load(directory);
}
}
@AfterClass
public static void closeFixture() throws IOException {
if (loaded != null) {
loaded.close();
}
}
@Test
public void exportedFixtureRunsEveryStage() {
assertStages(bench("export", ExportIrFixtures.NAMESPACE + ":" + ExportIrFixtures.DIMENSION));
}
@Test
public void vanillaOverworldRunsEveryStage() {
assertStages(bench("vanilla", DatapackCostProbe.VANILLA_PRESET));
}
private static void assertStages(WorldgenStageBench bench) {
WorldgenStageBench.ChunkSamples samples = new WorldgenStageBench.ChunkSamples();
bench.chunks(0, 0, SIDE, samples);
bench.chunks(SIDE + 4, 0, SIDE, samples);
WorldgenStageBench.ChunkTimings timings = samples.timings();
assertEquals(2 * SIDE * SIDE, timings.chunks());
assertEquals(2 * (SIDE + 2) * (SIDE + 2), timings.biomes().wall().count());
assertEquals(2 * SIDE * SIDE, timings.noise().cpu().count());
assertEquals(2 * SIDE * SIDE, timings.surface().wall().count());
assertEquals(2 * SIDE * SIDE, timings.carverBiome().wall().count());
assertEquals(0L, timings.biomeFallbacks());
assertTrue(Double.isFinite(timings.totalMean()));
assertTrue(Double.isFinite(timings.totalCpuMean()));
assertCalls(samples(bench, Call.UNCACHED_BIOME));
assertCalls(samples(bench, Call.BASE_HEIGHT));
assertCalls(samples(bench, Call.BASE_COLUMN));
}
private static void assertCalls(WorldgenStageBench.CallTiming timing) {
assertEquals(2 * BUDGET.minimumCalls(), timing.calls());
assertEquals(2 * BUDGET.minimumCalls(), timing.wall().count());
assertTrue(Double.isFinite(timing.cpuMean()));
}
private static WorldgenStageBench.CallTiming samples(WorldgenStageBench bench, Call call) {
WorldgenStageBench.CallSamples samples = new WorldgenStageBench.CallSamples();
for (int round = 0; round < 2; round++) {
switch (call) {
case UNCACHED_BIOME -> bench.uncachedBiome(BUDGET, samples);
case BASE_HEIGHT -> bench.baseHeight(BUDGET, Heightmap.Types.WORLD_SURFACE_WG, samples);
case BASE_COLUMN -> bench.baseColumn(BUDGET, samples);
}
}
return samples.timing();
}
private static WorldgenStageBench bench(String label, String preset) {
return new WorldgenStageBench(new WorldgenStageBench.Options(label,
DatapackCostProbe.presetOverworld(loaded.registries(), preset), loaded.registries(), SEED));
}
private enum Call {
UNCACHED_BIOME,
BASE_HEIGHT,
BASE_COLUMN
}
}
@@ -0,0 +1,99 @@
package art.arcane.iris.probe.fidelity;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportIrFixtures;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.emit.WorldgenJsonWriter;
import art.arcane.iris.pack.datapack.export.ir.AquiferDef;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.DimensionDef;
import art.arcane.iris.pack.datapack.export.ir.ExportIr;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.MaterialProgram;
import art.arcane.iris.pack.datapack.export.ir.RouterDef;
import art.arcane.iris.probe.PaperRegistryIsolation;
import art.arcane.iris.probe.WorldgenExportSampler;
import org.junit.ClassRule;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public final class VanillaNoiseColumnSourceTest {
@ClassRule
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
private static final long SEED = 1337L;
private static final String DIMENSION_ID = ExportIrFixtures.NAMESPACE + ":" + ExportIrFixtures.DIMENSION;
private static final String BIOME_ID = ExportIrFixtures.NAMESPACE + ":" + ExportIrFixtures.BIOME;
private static final String LOAD_KEY = "Flat Plains";
private static final int LAND_HEIGHT = 80;
private static final int SEA_FLOOR_HEIGHT = 40;
private static final int MAX_Y = ExportIrFixtures.MIN_Y + ExportIrFixtures.HEIGHT;
@Test
public void landColumnsReportTheTopSolidBlockAndStayDry() throws IOException {
try (VanillaNoiseColumnSource source = new VanillaNoiseColumnSource(open(LAND_HEIGHT), Map.of(BIOME_ID, LOAD_KEY))) {
assertEquals(ExportIrFixtures.MIN_Y, source.minY());
assertEquals(MAX_Y, source.maxY());
for (int x : new int[]{-37, 0, 113}) {
FidelityColumn column = source.column(x, -x);
assertEquals(new FidelityColumn(LOAD_KEY, LAND_HEIGHT - 1, false), column);
}
}
}
@Test
public void seaColumnsReportTheFloorUnderWater() throws IOException {
WorldgenExportSampler sampler = open(SEA_FLOOR_HEIGHT);
try (VanillaNoiseColumnSource source = new VanillaNoiseColumnSource(sampler, Map.of(BIOME_ID, LOAD_KEY))) {
FidelityStats stats = new FidelityStats(source.minY(), source.maxY());
for (int x : new int[]{-37, 0, 113}) {
FidelityColumn column = source.column(x, x);
assertEquals(new FidelityColumn(LOAD_KEY, sampler.floorHeight(x, x) - 1, true), column);
assertTrue(column.terrainY() + " under sea level", column.terrainY() < ExportIrFixtures.SEA_LEVEL - 1);
assertEquals(ExportIrFixtures.SEA_LEVEL, sampler.baseHeight(x, x));
stats.accept(column);
}
assertEquals(0.0D, stats.landFraction(), 0.0D);
}
}
@Test
public void exportedBiomeWithoutALoadKeyIsRejected() throws IOException {
try (VanillaNoiseColumnSource source = new VanillaNoiseColumnSource(open(LAND_HEIGHT), Map.of())) {
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> source.column(0, 0));
assertTrue(failure.getMessage(), failure.getMessage().contains(BIOME_ID));
}
}
private static WorldgenExportSampler open(int height) throws IOException {
return WorldgenExportSampler.open(flatExport(height), WorldgenExportMode.PRESET, DIMENSION_ID, SEED);
}
private static SortedMap<String, byte[]> flatExport(int height) {
Field zero = new Field.Const(0.0);
Field level = new Field.Const(height);
Field y = new Field.Coord(Axis.Y, Field.Tiling.CLAMP, -4064.0, 4062.0, -4064.0, 4062.0);
Field finalDensity = new Field.Grid(new Field.Binary(Field.BinaryOp.MUL, new Field.Const(0.125),
new Field.Binary(Field.BinaryOp.SUB, level, y)), 4, 8);
RouterDef router = new RouterDef(zero, zero, zero, zero, zero, zero, new Field.Grid(level, 16, 1), finalDensity, AquiferDef.dry(level));
DimensionDef dimension = new DimensionDef(ExportIrFixtures.DIMENSION, ExportIrFixtures.MIN_Y, ExportIrFixtures.HEIGHT,
ExportIrFixtures.HEIGHT, ExportIrFixtures.FLUID_HEIGHT, "minecraft:stone", "minecraft:water", ExportIrFixtures.dimensionType());
ClimateLayout climate = new ClimateLayout(List.of(new ClimateLayout.ClimateEntry(BIOME_ID, ClimateLayout.ClimateAxis.TEMPERATURE, -2.0, 2.0)));
ExportIr ir = new ExportIr(ExportIrFixtures.NAMESPACE, DataVersion.V26_3, WorldgenExportMode.PRESET, dimension, List.of(), router, climate,
List.of(new BiomeDef(ExportIrFixtures.BIOME, ExportIrFixtures.biome())), MaterialProgram.rock("minecraft:stone"),
List.of(), List.of(), List.of());
return WorldgenJsonWriter.forTarget(DataVersion.V26_3).write(ir);
}
}
@@ -0,0 +1,189 @@
package art.arcane.iris.probe.fidelity;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportIrFixtures;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.emit.WorldgenJsonWriter;
import art.arcane.iris.pack.datapack.export.ir.AquiferDef;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.DimensionDef;
import art.arcane.iris.pack.datapack.export.ir.ExportIr;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.datapack.export.ir.MaterialProgram;
import art.arcane.iris.pack.datapack.export.ir.RouterDef;
import art.arcane.iris.probe.PaperRegistryIsolation;
import art.arcane.iris.probe.WorldgenExportSampler;
import com.google.gson.JsonParser;
import org.junit.ClassRule;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public final class VanillaNoiseFidelitySourceTest {
@ClassRule
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
private static final long SEED = 1337L;
private static final String DIMENSION_ID = ExportIrFixtures.NAMESPACE + ":" + ExportIrFixtures.DIMENSION;
private static final String BIOME_ID = ExportIrFixtures.NAMESPACE + ":" + ExportIrFixtures.BIOME;
private static final String LOAD_KEY = "Flat Plains";
private static final int LAND_HEIGHT = 80;
private static final int MAX_Y = ExportIrFixtures.MIN_Y + ExportIrFixtures.HEIGHT;
private static final String WALL_SHELL = ExportIrFixtures.NAMESPACE + ":cave/wall_shell";
private static final int WALL_MIN_Y = 10;
private static final int WALL_MAX_Y = 20;
private static final int CARVED_HEIGHT = 120;
private static final int VOID_MIN_Y = 96;
private static final int CAVE_MIN_Y = 64;
private static final Field BLOCK_Y = new Field.Coord(Axis.Y, Field.Tiling.CLAMP, -4064.0, 4062.0, -4064.0, 4062.0);
@Test
public void flatExportReportsTheConstantSurface() throws IOException {
WorldgenExportSampler sampler = open(LAND_HEIGHT);
try (VanillaNoiseFidelitySource source = new VanillaNoiseFidelitySource(sampler, Map.of(BIOME_ID, LOAD_KEY), WALL_SHELL)) {
assertEquals(ExportIrFixtures.MIN_Y, source.minY());
assertEquals(MAX_Y, source.maxY());
for (int x : new int[]{-37, 0, 113}) {
assertEquals(LAND_HEIGHT, sampler.baseHeight(x, -x));
}
for (int[] chunkPosition : new int[][]{{0, 0}, {-3, 5}}) {
FidelityChunk chunk = source.sample(chunkPosition[0], chunkPosition[1]);
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
assertEquals(LAND_HEIGHT - 1, chunk.surfaceY(x, z));
assertEquals(LOAD_KEY, chunk.surfaceBiome(x, z));
assertTrue(chunk.open(x, LAND_HEIGHT, z));
assertNull(chunk.block(x, LAND_HEIGHT - 1, z));
}
}
for (int y = ExportIrFixtures.MIN_Y; y < LAND_HEIGHT; y++) {
assertFalse("y " + y, chunk.open(7, y, 9));
assertFalse("y " + y, chunk.fluid(7, y, 9));
}
}
FidelityStats stats = FidelityScanner.scan(source, 0, 0, 1, 4, 2);
assertEquals(144L, stats.heightColumns());
assertEquals(LAND_HEIGHT - 1, stats.heightQuantile(0.1D), 0.0D);
assertEquals(LAND_HEIGHT - 1, stats.heightQuantile(0.9D), 0.0D);
assertEquals(1.0D, stats.landFraction(), 0.0D);
assertEquals(Map.of(LOAD_KEY, 144L), stats.biomeColumns());
assertEquals(0L, stats.blockColumns());
assertEquals(0L, stats.wallSolidVoxels());
}
}
@Test
public void wallShellDensityMarksWallVoxels() throws IOException {
WorldgenExportSampler sampler = WorldgenExportSampler.open(flatExport(LAND_HEIGHT, wallShell()), WorldgenExportMode.PRESET, DIMENSION_ID, SEED);
try (VanillaNoiseFidelitySource source = new VanillaNoiseFidelitySource(sampler, Map.of(BIOME_ID, LOAD_KEY), WALL_SHELL)) {
FidelityChunk chunk = source.sample(2, -1);
assertTrue(chunk.wallsKnown());
assertTrue(chunk.wall(7, WALL_MIN_Y, 9));
assertTrue(chunk.wall(7, WALL_MAX_Y - 1, 9));
assertFalse(chunk.wall(7, WALL_MIN_Y - 1, 9));
assertFalse(chunk.wall(7, WALL_MAX_Y, 9));
FidelityStats stats = FidelityScanner.scan(source, 0, 0, 1, 4, 2);
long interiorColumns = 9L * 9L;
assertEquals(interiorColumns * (LAND_HEIGHT - 1 - ExportIrFixtures.MIN_Y), stats.wallSolidVoxels());
assertEquals(interiorColumns * (WALL_MAX_Y - WALL_MIN_Y), stats.wallVoxels());
}
}
@Test
public void openSpaceOutsideTheTerrainOperandIsATerrainVoid() throws IOException {
WorldgenExportSampler sampler = WorldgenExportSampler.open(carvedExport(), WorldgenExportMode.PRESET, DIMENSION_ID, SEED);
try (VanillaNoiseFidelitySource source = new VanillaNoiseFidelitySource(sampler, Map.of(BIOME_ID, LOAD_KEY), WALL_SHELL)) {
FidelityChunk chunk = source.sample(1, -2);
assertEquals(CARVED_HEIGHT - 1, chunk.surfaceY(7, 9));
assertTrue(chunk.open(7, VOID_MIN_Y, 9));
assertFalse(chunk.terrainMass(7, VOID_MIN_Y, 9));
assertTrue(chunk.open(7, CAVE_MIN_Y + 3, 9));
assertTrue(chunk.terrainMass(7, CAVE_MIN_Y + 3, 9));
assertFalse(chunk.open(7, VOID_MIN_Y - 4, 9));
assertTrue(chunk.terrainMass(7, VOID_MIN_Y - 4, 9));
FidelityStats stats = FidelityScanner.scan(source, 0, 0, 1, 4, 2);
int voidBand = (VOID_MIN_Y - ExportIrFixtures.MIN_Y) / 16;
int caveBand = (CAVE_MIN_Y - ExportIrFixtures.MIN_Y) / 16;
assertEquals(1.0D, stats.voidShare(voidBand), 0.0D);
assertEquals(0.0D, stats.caveShare(voidBand), 0.0D);
assertEquals(1.0D, stats.caveShare(caveBand), 0.0D);
assertEquals(0.0D, stats.voidShare(caveBand), 0.0D);
}
}
@Test
public void exportWithoutAWallShellReportsNoWalls() throws IOException {
try (VanillaNoiseFidelitySource source = new VanillaNoiseFidelitySource(open(LAND_HEIGHT), Map.of(BIOME_ID, LOAD_KEY), WALL_SHELL)) {
assertFalse(source.sample(0, 0).wallsKnown());
}
}
@Test
public void exportedBiomeWithoutALoadKeyIsRejected() throws IOException {
try (VanillaNoiseFidelitySource source = new VanillaNoiseFidelitySource(open(LAND_HEIGHT), Map.of(), WALL_SHELL)) {
FidelityChunk chunk = source.sample(0, 0);
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> chunk.surfaceBiome(0, 0));
assertTrue(failure.getMessage(), failure.getMessage().contains(BIOME_ID));
}
}
private static WorldgenExportSampler open(int height) throws IOException {
return WorldgenExportSampler.open(flatExport(height), WorldgenExportMode.PRESET, DIMENSION_ID, SEED);
}
private static JsonResource wallShell() {
return new JsonResource("data/" + ExportIrFixtures.NAMESPACE + "/worldgen/density_function/cave/wall_shell.json", JsonParser.parseString(
"{\"type\":\"minecraft:range_choice\",\"input\":{\"type\":\"minecraft:gradient\",\"axis\":\"y\",\"tiling\":\"clamp_to_edge\","
+ "\"from_coordinate\":-4064,\"to_coordinate\":4062,\"from_value\":-4064.0,\"to_value\":4062.0},"
+ "\"min_inclusive\":" + WALL_MIN_Y + ".0,\"max_exclusive\":" + WALL_MAX_Y + ".0,\"when_in_range\":1.0,\"when_out_of_range\":0.0}"));
}
private static SortedMap<String, byte[]> flatExport(int height, JsonResource... resources) {
Field level = new Field.Const(height);
Field finalDensity = new Field.Grid(new Field.Binary(Field.BinaryOp.MUL, new Field.Const(0.125),
new Field.Binary(Field.BinaryOp.SUB, level, BLOCK_Y)), 4, 8);
return export(height, finalDensity, resources);
}
private static SortedMap<String, byte[]> carvedExport() {
Field ramp = new Field.Binary(Field.BinaryOp.MUL, new Field.Const(0.125), new Field.Binary(Field.BinaryOp.SUB, new Field.Const(CARVED_HEIGHT), BLOCK_Y));
Field terrain = new Field.RangeIf(BLOCK_Y, VOID_MIN_Y, VOID_MIN_Y + 16, new Field.Const(-1.0), ramp);
Field caves = new Field.RangeIf(BLOCK_Y, CAVE_MIN_Y, CAVE_MIN_Y + 16, new Field.Const(-1.0), new Field.Const(1.0));
return export(CARVED_HEIGHT, new Field.Binary(Field.BinaryOp.MIN, terrain, caves));
}
private static SortedMap<String, byte[]> export(int height, Field finalDensity, JsonResource... resources) {
Field zero = new Field.Const(0.0);
Field level = new Field.Const(height);
RouterDef router = new RouterDef(zero, zero, zero, zero, zero, zero, new Field.Grid(level, 16, 1), finalDensity, AquiferDef.dry(level));
DimensionDef dimension = new DimensionDef(ExportIrFixtures.DIMENSION, ExportIrFixtures.MIN_Y, ExportIrFixtures.HEIGHT,
ExportIrFixtures.HEIGHT, ExportIrFixtures.FLUID_HEIGHT, "minecraft:stone", "minecraft:water", ExportIrFixtures.dimensionType());
ClimateLayout climate = new ClimateLayout(List.of(new ClimateLayout.ClimateEntry(BIOME_ID, ClimateLayout.ClimateAxis.TEMPERATURE, -2.0, 2.0)));
ExportIr ir = new ExportIr(ExportIrFixtures.NAMESPACE, DataVersion.V26_3, WorldgenExportMode.PRESET, dimension, List.of(), router, climate,
List.of(new BiomeDef(ExportIrFixtures.BIOME, ExportIrFixtures.biome())), MaterialProgram.rock("minecraft:stone"),
List.of(), List.of(resources), List.of());
return WorldgenJsonWriter.forTarget(DataVersion.V26_3).write(ir);
}
}
@@ -497,7 +497,13 @@ public class NativeStructureVolumeIndexTest {
private static Map<?, ?> cache(NativeStructureVolumeIndex index, String name) throws Exception {
Field field = NativeStructureVolumeIndex.class.getDeclaredField(name);
field.setAccessible(true);
return (Map<?, ?>) field.get(index);
Object value = field.get(index);
if (value instanceof Map<?, ?> map) {
return map;
}
Field entries = value.getClass().getDeclaredField("entries");
entries.setAccessible(true);
return (Map<?, ?>) entries.get(value);
}
private static StructureStart swampHut(int chunkX, int chunkZ, int x, int z) {
+12 -1
View File
@@ -14,7 +14,7 @@ dependencies {
// log4j-core Filter interface, so its constructor reference needs the type resolvable.
compileOnly(libs.log4j.core)
testImplementation('junit:junit:4.13.2')
testImplementation('org.mockito:mockito-core:5.23.0')
testImplementation(libs.mockito.core)
testImplementation(libs.paper.api)
testImplementation(libs.bstats)
testImplementation(project(':core'))
@@ -28,6 +28,16 @@ dependencies {
}
}
String lwjglVersion = libs.versions.lwjgl.get()
List<String> mavenLibraries = [
"org.lwjgl:lwjgl:${lwjglVersion}",
"org.lwjgl:lwjgl:jar:natives-linux:${lwjglVersion}",
"org.lwjgl:lwjgl-opengl:${lwjglVersion}",
"org.lwjgl:lwjgl-opengl:jar:natives-linux:${lwjglVersion}",
"org.lwjgl:lwjgl-egl:${lwjglVersion}",
"org.lwjgl:lwjgl-jawt:${lwjglVersion}",
].collect { GString coordinate -> coordinate.toString() }
tasks.named('processResources').configure {
def pluginProperties = [
name : rootProject.name,
@@ -35,6 +45,7 @@ tasks.named('processResources').configure {
apiVersion: apiVersion,
main : mainClass,
bootstrapper: bootstrapperClass,
libraries : mavenLibraries.collect { String coordinate -> "'${coordinate}'" }.join(', '),
]
inputs.properties(pluginProperties)
filesMatching(['**/paper-plugin.yml', '**/plugin.yml']) {
File diff suppressed because it is too large. Load diff
@@ -1,233 +1,12 @@
package art.arcane.iris;
import art.arcane.iris.world.lifecycle.BukkitStartupPaths;
import art.arcane.iris.world.lifecycle.BukkitWorldConfiguration;
import art.arcane.iris.world.lifecycle.BukkitWorldConfiguration.IrisWorldStorageEntry;
import art.arcane.iris.world.lifecycle.HuskWorldQuarantine;
import art.arcane.iris.world.lifecycle.MissingWorldStorageLog;
import art.arcane.iris.world.lifecycle.WorldReplacementBootstrap;
import art.arcane.iris.world.lifecycle.WorldReplacementBootstrapMarker;
import art.arcane.iris.pack.DefaultPackBootstrapProvisioner;
import art.arcane.iris.pack.DefaultPackBootstrapProvisioner.BootstrapRequest;
import art.arcane.iris.pack.datapack.DataVersion;
import io.papermc.paper.ServerBuildInfo;
import art.arcane.iris.pack.DefaultPackBootstrapProvisioner.ProvisionResult;
import art.arcane.iris.platform.bootstrap.SlimJar;
import art.arcane.iris.world.safeguard.GenerationRefusalNotice;
import io.papermc.paper.plugin.bootstrap.BootstrapContext;
import io.papermc.paper.plugin.bootstrap.PluginBootstrap;
import io.papermc.paper.plugin.lifecycle.event.LifecycleEvent;
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEventType;
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
@SuppressWarnings("UnstableApiUsage")
public final class IrisBootstrap implements PluginBootstrap {
@Override
public void bootstrap(BootstrapContext context) {
WorldReplacementBootstrapMarker.markBootstrapped();
try {
loadRuntimeLibraries(context);
BukkitStartupPaths startupPaths = BukkitStartupPaths.resolveCurrent();
reconcilePendingWorldReplacements(context, startupPaths);
quarantineWorthlessHusks(startupPaths, message -> context.getLogger().warn(message));
requireUsableWorldStorage(startupPaths);
ProvisionResult provisioned = provision(context, startupPaths);
Path datapackRoot = provisioned.datapackRoot();
context.getLogger().info("Iris startup datapack is {} at {}", provisioned.status(), datapackRoot);
} catch (Throwable failure) {
armStartupFailure(context, failure);
}
}
private static void loadRuntimeLibraries(BootstrapContext context) {
SlimJar.loadBootstrap(
context.getDataDirectory().resolve("cache").resolve("libraries"),
ServerBuildInfo.buildInfo().minecraftVersionId(),
new SlimJar.BootstrapLogger() {
@Override
public void info(String message) {
context.getLogger().info(message);
}
@Override
public void error(String message) {
context.getLogger().error(message);
}
@Override
public void debug(String message) {
context.getLogger().debug(message);
}
});
}
private static void reconcilePendingWorldReplacements(
BootstrapContext context,
BukkitStartupPaths startupPaths
) {
try {
WorldReplacementBootstrap.ReconcileResult result = WorldReplacementBootstrap.reconcile(
context.getDataDirectory(),
startupPaths.levelRoot(),
startupPaths.bukkitConfiguration(),
message -> context.getLogger().info(message)
);
if (result.transactions() > 0) {
context.getLogger().info(
"Reconciled {} pending Iris world replacement(s): {} published, {} rolled back, {} retained",
result.transactions(),
result.published(),
result.rolledBack(),
result.retained()
);
}
} catch (IOException failure) {
throw new IllegalStateException(
"Unable to reconcile pending Iris world replacements before registry bootstrap",
failure
);
}
}
/**
* Moves a hot-deleted world's husk out of {@code <levelRoot>/dimensions/iris} before anything enumerates
* it.
* <p>
* Deleting a loaded world's folder and letting the server save the level back leaves a directory holding
* only the server's own {@code data/} skeleton. Left there it stops the boot whichever way it is
* classified: as unusable storage it trips the guard below, and as an empty folder it is excluded from
* the dimension registry, which trips Paper's interactive world-migration gate - a prompt that consumes
* no console input and hangs startup forever. The folder is moved rather than deleted, so it stays
* recoverable; {@link HuskWorldQuarantine} refuses anything that is not provably worthless.
*/
static void quarantineWorthlessHusks(BukkitStartupPaths startupPaths, Consumer<String> warn) {
HuskWorldQuarantine.quarantineWorthlessHusks(startupPaths.levelRoot(), warn);
}
/**
* Stops startup when a world the server is about to load carries Iris storage Iris cannot generate from.
* <p>
* The server enumerates levels from {@code <levelRoot>/dimensions/<namespace>/<key>} on disk, so a world
* whose folder is present is going to be loaded whatever Iris does. The generator resolver answers a world
* it cannot generate with a fail-closed generator, which stops startup at that world's own level creation,
* after the levels before it have loaded. A pack snapshot that has gone missing is found here instead,
* before any level is created, exactly as a corrupt {@code dimensions/<id>.json} is. An Iris world in a
* vanilla slot whose bukkit.yml entry no longer names Iris stops startup too: CraftServer would build it
* with the vanilla generator without ever asking Iris.
* <p>
* A world with no folder at all is not a startup failure: nothing enumerates it, nothing loads it, and
* its bukkit.yml and Multiverse entries are what make restoring the folder a complete recovery. Neither
* is a folder that holds no pack snapshot and no world data - {@link #quarantineWorthlessHusks} has
* already moved those out of the dimensions tree, and one that survives it (a Spigot-layout world folder,
* or a move that failed) owns nothing to lose. Both are only reported here.
*/
static void requireUsableWorldStorage(BukkitStartupPaths startupPaths) throws IOException {
Path levelRoot = startupPaths.levelRoot();
Path levelName = levelRoot.getFileName();
if (levelName == null || levelName.toString().isBlank()) {
throw new IOException("Configured level root has no startup level id: " + levelRoot);
}
List<IrisWorldStorageEntry> entries = BukkitWorldConfiguration.auditIrisWorldStorage(
startupPaths.bukkitConfiguration().toFile(),
levelName.toString(),
levelRoot
);
StringBuilder unusable = new StringBuilder();
StringBuilder unbound = new StringBuilder();
for (IrisWorldStorageEntry entry : entries) {
switch (entry.state()) {
case PRESENT -> {
}
case MISSING -> MissingWorldStorageLog.warnOnce(
entry.configuredWorldName(),
entry.storagePath());
case EMPTY -> MissingWorldStorageLog.warnEmptyOnce(
entry.configuredWorldName(),
entry.storagePath());
case UNUSABLE -> unusable.append(unusable.isEmpty() ? "" : "; ")
.append(entry.configuredWorldName())
.append(" (")
.append(entry.storagePath())
.append(": ")
.append(entry.detail() == null ? "storage is unusable" : entry.detail())
.append(')');
case UNBOUND -> unbound.append(unbound.isEmpty() ? "" : "; ")
.append(entry.configuredWorldName())
.append(" (")
.append(entry.storagePath())
.append("): set worlds.")
.append(entry.configuredWorldName())
.append(".generator to Iris:<pack> in bukkit.yml, or move the folder aside to start a new"
+ " vanilla world there");
}
}
List<String> refusals = new ArrayList<>(2);
if (!unusable.isEmpty()) {
refusals.add("Iris world storage is unusable and the server would generate vanilla terrain over it: "
+ unusable + ". Restore each world folder from a backup, or move it aside; a world with no"
+ " folder is reported and skipped, and the server starts.");
}
if (!unbound.isEmpty()) {
refusals.add("Iris worlds in vanilla slots are not bound to Iris, so the server would generate vanilla"
+ " terrain into them: " + unbound + ".");
}
if (!refusals.isEmpty()) {
throw new IllegalStateException(String.join(" ", refusals));
}
}
static void armStartupFailure(BootstrapContext context, Throwable failure) {
armStartupFailure(context, failure, LifecycleEvents.DATAPACK_DISCOVERY);
}
static <E extends LifecycleEvent> void armStartupFailure(
BootstrapContext context,
Throwable failure,
LifecycleEventType<? super BootstrapContext, ? extends E, ?> eventType
) {
context.getLifecycleManager().registerEventHandler(eventType, event -> {
throw new IllegalStateException("Iris bootstrap did not establish safe world-generation state.", failure);
});
List<String> notice = startupRefusalNotice(failure);
try {
for (String line : notice) {
context.getLogger().error(line);
}
context.getLogger().warn("Iris bootstrap failure", failure);
} catch (Throwable loggingFailure) {
notice.forEach(System.err::println);
failure.addSuppressed(loggingFailure);
failure.printStackTrace(System.err);
}
}
static List<String> startupRefusalNotice(Throwable failure) {
return GenerationRefusalNotice.compose(
"Iris stopped server startup before any world loads",
GenerationRefusalNotice.causes(failure),
List.of(
"Startup stops at datapack discovery: no world loads and no chunks are written.",
"Fix the cause, then start the server again. Paper's --safeMode hint does not apply:"
+ " Iris worlds must not load without Iris."
));
}
private static ProvisionResult provision(BootstrapContext context, BukkitStartupPaths startupPaths) {
try {
return DefaultPackBootstrapProvisioner.provision(new BootstrapRequest(
context.getDataDirectory(),
message -> context.getLogger().info(message),
startupPaths,
DataVersion.forMinecraftVersion(ServerBuildInfo.buildInfo().minecraftVersionId())
));
} catch (IOException e) {
throw new IllegalStateException("Unable to provision the Iris startup datapack", e);
}
IrisPluginRuntime.bootstrap(context);
}
}
@@ -0,0 +1,234 @@
package art.arcane.iris;
import art.arcane.iris.world.lifecycle.BukkitStartupPaths;
import art.arcane.iris.world.lifecycle.BukkitWorldConfiguration;
import art.arcane.iris.world.lifecycle.BukkitWorldConfiguration.IrisWorldStorageEntry;
import art.arcane.iris.world.lifecycle.HuskWorldQuarantine;
import art.arcane.iris.world.lifecycle.MissingWorldStorageLog;
import art.arcane.iris.world.lifecycle.WorldReplacementBootstrap;
import art.arcane.iris.world.lifecycle.WorldReplacementBootstrapMarker;
import art.arcane.iris.pack.DefaultPackBootstrapProvisioner;
import art.arcane.iris.pack.DefaultPackBootstrapProvisioner.BootstrapRequest;
import art.arcane.iris.pack.datapack.DataVersion;
import io.papermc.paper.ServerBuildInfo;
import art.arcane.iris.pack.DefaultPackBootstrapProvisioner.ProvisionResult;
import art.arcane.iris.platform.bootstrap.SlimJar;
import art.arcane.iris.world.safeguard.GenerationRefusalNotice;
import io.papermc.paper.plugin.bootstrap.BootstrapContext;
import io.papermc.paper.plugin.lifecycle.event.LifecycleEvent;
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEventType;
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
@SuppressWarnings("UnstableApiUsage")
final class IrisBootstrapSequence {
private IrisBootstrapSequence() {
}
static void bootstrap(BootstrapContext context) {
WorldReplacementBootstrapMarker.markBootstrapped();
try {
loadRuntimeLibraries(context);
BukkitStartupPaths startupPaths = BukkitStartupPaths.resolveCurrent();
reconcilePendingWorldReplacements(context, startupPaths);
quarantineWorthlessHusks(startupPaths, message -> context.getLogger().warn(message));
requireUsableWorldStorage(startupPaths);
ProvisionResult provisioned = provision(context, startupPaths);
Path datapackRoot = provisioned.datapackRoot();
context.getLogger().info("Iris startup datapack is {} at {}", provisioned.status(), datapackRoot);
} catch (Throwable failure) {
armStartupFailure(context, failure);
}
}
private static void loadRuntimeLibraries(BootstrapContext context) {
SlimJar.loadBootstrap(
context.getDataDirectory().resolve("cache").resolve("libraries"),
ServerBuildInfo.buildInfo().minecraftVersionId(),
new SlimJar.BootstrapLogger() {
@Override
public void info(String message) {
context.getLogger().info(message);
}
@Override
public void error(String message) {
context.getLogger().error(message);
}
@Override
public void debug(String message) {
context.getLogger().debug(message);
}
});
}
private static void reconcilePendingWorldReplacements(
BootstrapContext context,
BukkitStartupPaths startupPaths
) {
try {
WorldReplacementBootstrap.ReconcileResult result = WorldReplacementBootstrap.reconcile(
context.getDataDirectory(),
startupPaths.levelRoot(),
startupPaths.bukkitConfiguration(),
message -> context.getLogger().info(message)
);
if (result.transactions() > 0) {
context.getLogger().info(
"Reconciled {} pending Iris world replacement(s): {} published, {} rolled back, {} retained",
result.transactions(),
result.published(),
result.rolledBack(),
result.retained()
);
}
} catch (IOException failure) {
throw new IllegalStateException(
"Unable to reconcile pending Iris world replacements before registry bootstrap",
failure
);
}
}
/**
* Moves a hot-deleted world's husk out of {@code <levelRoot>/dimensions/iris} before anything enumerates
* it.
* <p>
* Deleting a loaded world's folder and letting the server save the level back leaves a directory holding
* only the server's own {@code data/} skeleton. Left there it stops the boot whichever way it is
* classified: as unusable storage it trips the guard below, and as an empty folder it is excluded from
* the dimension registry, which trips Paper's interactive world-migration gate - a prompt that consumes
* no console input and hangs startup forever. The folder is moved rather than deleted, so it stays
* recoverable; {@link HuskWorldQuarantine} refuses anything that is not provably worthless.
*/
static void quarantineWorthlessHusks(BukkitStartupPaths startupPaths, Consumer<String> warn) {
HuskWorldQuarantine.quarantineWorthlessHusks(startupPaths.levelRoot(), warn);
}
/**
* Stops startup when a world the server is about to load carries Iris storage Iris cannot generate from.
* <p>
* The server enumerates levels from {@code <levelRoot>/dimensions/<namespace>/<key>} on disk, so a world
* whose folder is present is going to be loaded whatever Iris does. The generator resolver answers a world
* it cannot generate with a fail-closed generator, which stops startup at that world's own level creation,
* after the levels before it have loaded. A pack snapshot that has gone missing is found here instead,
* before any level is created, exactly as a corrupt {@code dimensions/<id>.json} is. An Iris world in a
* vanilla slot whose bukkit.yml entry no longer names Iris stops startup too: CraftServer would build it
* with the vanilla generator without ever asking Iris.
* <p>
* A world with no folder at all is not a startup failure: nothing enumerates it, nothing loads it, and
* its bukkit.yml and Multiverse entries are what make restoring the folder a complete recovery. Neither
* is a folder that holds no pack snapshot and no world data - {@link #quarantineWorthlessHusks} has
* already moved those out of the dimensions tree, and one that survives it (a Spigot-layout world folder,
* or a move that failed) owns nothing to lose. Both are only reported here.
*/
static void requireUsableWorldStorage(BukkitStartupPaths startupPaths) throws IOException {
Path levelRoot = startupPaths.levelRoot();
Path levelName = levelRoot.getFileName();
if (levelName == null || levelName.toString().isBlank()) {
throw new IOException("Configured level root has no startup level id: " + levelRoot);
}
List<IrisWorldStorageEntry> entries = BukkitWorldConfiguration.auditIrisWorldStorage(
startupPaths.bukkitConfiguration().toFile(),
levelName.toString(),
levelRoot
);
StringBuilder unusable = new StringBuilder();
StringBuilder unbound = new StringBuilder();
for (IrisWorldStorageEntry entry : entries) {
switch (entry.state()) {
case PRESENT -> {
}
case MISSING -> MissingWorldStorageLog.warnOnce(
entry.configuredWorldName(),
entry.storagePath());
case EMPTY -> MissingWorldStorageLog.warnEmptyOnce(
entry.configuredWorldName(),
entry.storagePath());
case UNUSABLE -> unusable.append(unusable.isEmpty() ? "" : "; ")
.append(entry.configuredWorldName())
.append(" (")
.append(entry.storagePath())
.append(": ")
.append(entry.detail() == null ? "storage is unusable" : entry.detail())
.append(')');
case UNBOUND -> unbound.append(unbound.isEmpty() ? "" : "; ")
.append(entry.configuredWorldName())
.append(" (")
.append(entry.storagePath())
.append("): set worlds.")
.append(entry.configuredWorldName())
.append(".generator to Iris:<pack> in bukkit.yml, or move the folder aside to start a new"
+ " vanilla world there");
}
}
List<String> refusals = new ArrayList<>(2);
if (!unusable.isEmpty()) {
refusals.add("Iris world storage is unusable and the server would generate vanilla terrain over it: "
+ unusable + ". Restore each world folder from a backup, or move it aside; a world with no"
+ " folder is reported and skipped, and the server starts.");
}
if (!unbound.isEmpty()) {
refusals.add("Iris worlds in vanilla slots are not bound to Iris, so the server would generate vanilla"
+ " terrain into them: " + unbound + ".");
}
if (!refusals.isEmpty()) {
throw new IllegalStateException(String.join(" ", refusals));
}
}
static void armStartupFailure(BootstrapContext context, Throwable failure) {
armStartupFailure(context, failure, LifecycleEvents.DATAPACK_DISCOVERY);
}
static <E extends LifecycleEvent> void armStartupFailure(
BootstrapContext context,
Throwable failure,
LifecycleEventType<? super BootstrapContext, ? extends E, ?> eventType
) {
context.getLifecycleManager().registerEventHandler(eventType, event -> {
throw new IllegalStateException("Iris bootstrap did not establish safe world-generation state.", failure);
});
List<String> notice = startupRefusalNotice(failure);
try {
for (String line : notice) {
context.getLogger().error(line);
}
context.getLogger().warn("Iris bootstrap failure", failure);
} catch (Throwable loggingFailure) {
notice.forEach(System.err::println);
failure.addSuppressed(loggingFailure);
failure.printStackTrace(System.err);
}
}
static List<String> startupRefusalNotice(Throwable failure) {
return GenerationRefusalNotice.compose(
"Iris stopped server startup before any world loads",
GenerationRefusalNotice.causes(failure),
List.of(
"Startup stops at datapack discovery: no world loads and no chunks are written.",
"Fix the cause, then start the server again. Paper's --safeMode hint does not apply:"
+ " Iris worlds must not load without Iris."
));
}
private static ProvisionResult provision(BootstrapContext context, BukkitStartupPaths startupPaths) {
try {
return DefaultPackBootstrapProvisioner.provision(new BootstrapRequest(
context.getDataDirectory(),
message -> context.getLogger().info(message),
startupPaths,
DataVersion.forMinecraftVersion(ServerBuildInfo.buildInfo().minecraftVersionId())
));
} catch (IOException e) {
throw new IllegalStateException("Unable to provision the Iris startup datapack", e);
}
}
}
@@ -6,12 +6,22 @@ import io.papermc.paper.plugin.bootstrap.PluginProviderContext;
import io.papermc.paper.plugin.loader.PluginClasspathBuilder;
import io.papermc.paper.plugin.loader.PluginLoader;
import io.papermc.paper.plugin.loader.library.impl.JarLibrary;
import io.papermc.paper.plugin.loader.library.impl.MavenLibraryResolver;
import org.bukkit.configuration.file.YamlConfiguration;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.repository.RemoteRepository;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
@SuppressWarnings("UnstableApiUsage")
public final class IrisPluginLoader implements PluginLoader {
@@ -40,6 +50,21 @@ public final class IrisPluginLoader implements PluginLoader {
classpathBuilder.addLibrary(new JarLibrary(library));
}
}
classpathBuilder.addLibrary(mavenResolver(mavenLibraries(context.getPluginSource())));
}
static List<String> mavenLibraries(Path pluginJar) {
try (ZipFile jar = new ZipFile(pluginJar.toFile())) {
ZipEntry descriptor = jar.getEntry("plugin.yml");
if (descriptor == null) {
throw new IllegalStateException("The Iris jar " + pluginJar + " has no plugin.yml library list.");
}
try (Reader reader = new InputStreamReader(jar.getInputStream(descriptor), StandardCharsets.UTF_8)) {
return YamlConfiguration.loadConfiguration(reader).getStringList("libraries");
}
} catch (IOException failure) {
throw new IllegalStateException("Unable to read the Iris library list from " + pluginJar + ".", failure);
}
}
static List<Path> relocatedLibraries(Path libraryRoot) {
@@ -59,6 +84,16 @@ public final class IrisPluginLoader implements PluginLoader {
}
}
private static MavenLibraryResolver mavenResolver(List<String> coordinates) {
MavenLibraryResolver resolver = new MavenLibraryResolver();
resolver.addRepository(new RemoteRepository.Builder("central", "default",
MavenLibraryResolver.MAVEN_CENTRAL_DEFAULT_MIRROR).build());
for (String coordinate : coordinates) {
resolver.addDependency(new Dependency(new DefaultArtifact(coordinate), null));
}
return resolver;
}
private static boolean isRelocatedLibrary(Path path) {
int count = path.getNameCount();
for (int i = 0; i < count - 2; i++) {
@@ -0,0 +1,119 @@
package art.arcane.iris;
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
import art.arcane.volmlib.integration.ReloadAware;
import art.arcane.volmlib.util.function.NastyRunnable;
import io.papermc.paper.plugin.bootstrap.BootstrapContext;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Event;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.generator.BiomeProvider;
import org.bukkit.generator.ChunkGenerator;
import java.util.List;
import java.util.concurrent.CompletionStage;
interface IrisPluginRuntime {
static IrisPluginRuntime create(Iris plugin) {
return new IrisRuntime(plugin);
}
static void bootstrap(BootstrapContext context) {
IrisBootstrapSequence.bootstrap(context);
}
static VolmitSender getSender() {
return IrisRuntime.getSender();
}
static <T> T service(Class<T> type) {
return IrisRuntime.service(type);
}
static void callEvent(Event event) {
IrisRuntime.callEvent(event);
}
static void msg(String message) {
IrisRuntime.msg(message);
}
static void warn(String format, Object... args) {
IrisRuntime.warn(format, args);
}
static void error(String format, Object... args) {
IrisRuntime.error(format, args);
}
static void debug(String message) {
IrisRuntime.debug(message);
}
static void debug(String category, int line, String message) {
IrisRuntime.debug(category, line, message);
}
static void verbose(String message) {
IrisRuntime.verbose(message);
}
static void success(String message) {
IrisRuntime.success(message);
}
static void info(String format, Object... args) {
IrisRuntime.info(format, args);
}
static void later(NastyRunnable task) {
IrisRuntime.later(task);
}
static void reportErrorChunk(int x, int z, Throwable failure, String extra) {
IrisRuntime.reportErrorChunk(x, z, failure, extra);
}
static void reportError(Throwable failure) {
IrisRuntime.reportError(failure);
}
static void reportError(String context, Throwable failure) {
IrisRuntime.reportError(context, failure);
}
static void dump() {
IrisRuntime.dump();
}
static void panic() {
IrisRuntime.panic();
}
static String tag(String subTag) {
return IrisRuntime.tag(subTag);
}
void initialize();
void onEnable();
void onDisable();
CompletionStage<Void> commitReload(ReloadAware.PreUnloadReason reason);
void selectLanguage(CommandSender sender, String[] arguments);
List<String> completeLanguage(CommandSender sender, String[] arguments);
void onPlaceholderApiEnable(PluginEnableEvent event);
void onPlaceholderApiDisable(PluginDisableEvent event);
BiomeProvider getDefaultBiomeProvider(String worldName, String id);
ChunkGenerator getDefaultWorldGenerator(String worldName, String id);
ChunkGenerator requireWorldGenerator(String worldName, String id);
}
File diff suppressed because it is too large. Load diff
@@ -12,7 +12,8 @@ public record IrisColumnSample(
IrisRiverState riverState,
double riverDistance,
int riverFlow,
int riverWaterSurfaceY
int riverWaterSurfaceY,
boolean provisional
) {
public static final int UNAVAILABLE_HEIGHT = Integer.MIN_VALUE;
public static final double UNAVAILABLE_RIVER_DISTANCE = Double.NaN;
@@ -18,21 +18,41 @@
package art.arcane.iris.command;
import art.arcane.iris.pack.datapack.DatapackIngestService;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.iris.Iris;
import art.arcane.iris.command.handlers.DimensionHandler;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.localization.BukkitCommandMessages;
import art.arcane.iris.localization.C;
import art.arcane.iris.localization.DirectorCommandMessages;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.DatapackIngestService;
import art.arcane.iris.pack.datapack.export.DatapackExportDestinations;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.WorldgenExportRequest;
import art.arcane.iris.pack.datapack.export.WorldgenExportResult;
import art.arcane.iris.pack.datapack.export.WorldgenExportService;
import art.arcane.iris.pack.datapack.export.WorldgenExportServices;
import art.arcane.iris.pack.datapack.export.WorldgenExportTargets;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.world.task.J;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.director.annotations.Director;
import art.arcane.volmlib.util.director.annotations.Param;
import art.arcane.volmlib.util.localization.LanguageAudience;
import art.arcane.volmlib.util.localization.MessageArgument;
import art.arcane.volmlib.util.localization.TextKey;
import java.util.List;
import java.util.UUID;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.localization.BukkitCommandMessages;
import art.arcane.volmlib.util.localization.MessageArgument;
@Director(name = "datapack", aliases = {"datapacks", "dp"}, description = "Download & manage external datapack imports", descriptionKey = "iris.director.commanddatapack.director.download_manage_external_datapack_imports_modrinth")
public class CommandDatapack implements DirectorExecutor {
private static final int RESOURCE_REPORTS = 4;
@Director(description = "Download/update every datapack listed in a pack dimension's 'datapackImports' and install it into the world so its structures register like vanilla", descriptionKey = "iris.director.commanddatapack.director.download_update_every_datapack_listed_pack_dimension_s_datapackimports_install_it_into", aliases = {"pull"})
public void ingest(
@Param(description = "Restart the server when new datapacks are installed (required for new structures to register and generate)", descriptionKey = "iris.director.commanddatapack.param.restart_server_when_new_datapacks_are_installed_required_new_structures_register_generate", defaultValue = "false")
@@ -71,4 +91,128 @@ public class CommandDatapack implements DirectorExecutor {
) {
DatapackIngestService.remove(sender(), id);
}
@Director(description = "Export a dimension as a vanilla worldgen datapack", descriptionKey = "iris.director.commanddatapack.director.export_dimension_vanilla_worldgen_datapack")
public void export(
@Param(name = "dimension", description = "The dimension to export", descriptionKey = "iris.director.commanddatapack.param.export_dimension", customHandler = DimensionHandler.class)
IrisDimension dimension,
@Param(name = "version", description = "Target Minecraft version, 26.3 or later (blank uses the latest)", descriptionKey = "iris.director.commanddatapack.param.export_version", defaultValue = "")
String version,
@Param(name = "mode", description = "Output mode: preset, dimension, or overworld", descriptionKey = "iris.director.commanddatapack.param.export_mode", defaultValue = WorldgenExportRequest.DEFAULT_MODE)
String mode,
@Param(name = "namespace", description = "Namespace for the exported resources", descriptionKey = "iris.director.commanddatapack.param.export_namespace", defaultValue = WorldgenExportRequest.DEFAULT_NAMESPACE)
String namespace,
@Param(name = "output", description = "Output name in the datapack exports folder (blank uses the dimension and version)", descriptionKey = "iris.director.commanddatapack.param.export_output", defaultValue = "")
String output,
@Param(name = "format", description = "zip or directory", descriptionKey = "iris.director.commanddatapack.param.export_format", defaultValue = WorldgenExportRequest.DEFAULT_FORMAT)
String format,
@Param(name = "objects", description = "Include objects as structure templates", descriptionKey = "iris.director.commanddatapack.param.export_objects", defaultValue = "true")
boolean objects,
@Param(name = "replace", description = "Replace an existing export with the same name", descriptionKey = "iris.director.commanddatapack.param.export_replace", defaultValue = "false")
boolean replace
) {
VolmitSender sender = sender();
WorldgenExportRequest request = WorldgenExportRequest.builder()
.pack(dimension.getLoader().getDataFolder().toPath())
.dimension(dimension.getLoadKey())
.version(version)
.mode(mode)
.namespace(namespace)
.output(output)
.format(format)
.objects(objects)
.replace(replace)
.exportRoot(IrisPlatforms.get().dataFolder("exports", "datapacks").toPath())
.build();
DataVersion target;
try {
target = validateExport(request);
} catch (IllegalArgumentException invalid) {
sender.sendMessage(C.RED + IrisLanguage.text(DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_INVALID, MessageArgument.untrusted("reason", invalid.getMessage())));
return;
}
WorldgenExportService service = WorldgenExportServices.get();
sender.sendMessage(C.GRAY + IrisLanguage.text(DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_STARTED, MessageArgument.untrusted("dimension", request.dimension()), MessageArgument.untrusted("version", target.getVersion())));
UUID audience = LanguageAudience.current();
ExportFeedback feedback = new ExportFeedback(sender);
J.a(() -> LanguageAudience.run(audience, () -> runExport(service, request, feedback)));
}
static DataVersion validateExport(WorldgenExportRequest request) {
DataVersion target = WorldgenExportTargets.resolve(request.version());
WorldgenExportMode.parse(request.mode());
DatapackExportDestinations.parseFormat(request.format());
return target;
}
private static void runExport(WorldgenExportService service, WorldgenExportRequest request, ExportFeedback feedback) {
WorldgenExportResult result;
try {
result = service.export(request, feedback);
} catch (Throwable failure) {
Iris.reportError("Datapack export failed for '" + request.dimension() + "'.", failure);
feedback.send(C.RED, IrisLanguage.text(DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_FAILED, MessageArgument.untrusted("reason", IrisLanguage.errorDetail(failure))));
return;
}
reportExport(feedback, result);
}
private static void reportExport(ExportFeedback feedback, WorldgenExportResult result) {
for (ExportDiagnostic diagnostic : result.diagnostics()) {
feedback.send(diagnosticColor(diagnostic.severity()), IrisLanguage.text(DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_DIAGNOSTIC, MessageArgument.untrusted("key", diagnosticLabel(diagnostic)), MessageArgument.untrusted("message", diagnostic.message())));
}
if (result.isSuccess()) {
feedback.send(C.GREEN, IrisLanguage.text(DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_EXPORTED, MessageArgument.untrusted("path", result.output())));
return;
}
TextKey outcome = result.status() == WorldgenExportResult.Status.REJECTED
? DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_REJECTED
: DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_FAILED;
feedback.send(C.RED, IrisLanguage.text(outcome, MessageArgument.untrusted("reason", result.message())));
}
private static C diagnosticColor(ExportDiagnostic.Severity severity) {
return switch (severity) {
case ERROR -> C.RED;
case WARNING -> C.YELLOW;
case INFO -> C.GRAY;
};
}
private static String diagnosticLabel(ExportDiagnostic diagnostic) {
return diagnostic.resource().isEmpty()
? diagnostic.limit().name()
: diagnostic.limit().name() + " " + diagnostic.resource();
}
private static final class ExportFeedback implements WorldgenExportProgress {
private final VolmitSender sender;
private ExportFeedback(VolmitSender sender) {
this.sender = sender;
}
@Override
public void stage(String stage) {
send(C.GRAY, IrisLanguage.text(DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_STAGE, MessageArgument.untrusted("stage", stage)));
}
@Override
public void resources(int done, int total) {
int stride = Math.max(1, total / RESOURCE_REPORTS);
if (done != total && done % stride != 0) {
return;
}
send(C.GRAY, IrisLanguage.text(DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_RESOURCES, MessageArgument.untrusted("done", done), MessageArgument.untrusted("total", total)));
}
private void send(C color, String message) {
String line = color + message;
if (sender.isPlayer()) {
J.runEntity(sender.player(), () -> sender.sendMessage(line));
return;
}
sender.sendMessage(line);
}
}
}
@@ -1,6 +1,7 @@
package art.arcane.iris.command;
import art.arcane.iris.Iris;
import art.arcane.iris.IrisRuntime;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.localization.BukkitCommandMessagesExtended;
import art.arcane.iris.localization.IrisLanguage;
@@ -19,7 +20,7 @@ public final class CommandDebug implements DirectorExecutor {
@Param(name = "upload", defaultValue = "true", description = "Upload the report to mclo.gs", descriptionKey = "iris.director.commandiris.param.debugdump_upload") boolean upload,
@Param(name = "sender", contextual = true) CommandSender sender
) {
Iris.instance.debugDump().request(sender, upload);
IrisRuntime.require().debugDump().request(sender, upload);
}
@Director(sync = true, description = "Print version information", descriptionKey = "iris.director.commandiris.director.print_version_information")
@@ -31,8 +31,7 @@ import art.arcane.iris.structure.placement.IrisStructureLocator;
import art.arcane.iris.structure.nativegen.NativeStructureGenerationPolicy;
import art.arcane.iris.structure.placement.StructureReachability;
import art.arcane.iris.world.history.GenerationSemanticQueries;
import art.arcane.iris.generation.hydrology.HydrologyFeatureQuery;
import art.arcane.iris.generation.hydrology.runtime.IrisHydrologyRuntime;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.structure.nativegen.IrisNativeStructureDecision;
import art.arcane.iris.generation.terrain.IrisRegion;
@@ -71,6 +70,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CancellationException;
@Director(name = "find", origin = DirectorOrigin.PLAYER, description = "Iris Find commands", descriptionKey = "iris.director.commandfind.director.iris_find_commands", aliases = "goto")
public class CommandFind implements DirectorExecutor {
@@ -196,9 +196,9 @@ public class CommandFind implements DirectorExecutor {
EngineBukkitOps.gotoPOI(e, type, player(), teleport);
}
@Director(description = "Find an accepted hydrology feature", sync = true)
@Director(description = "Find a hydrology water feature", sync = true)
public void river(
@Param(description = "Feature type: surface, waterfall, underground, grotto, mouth, or a deep-fluid id", customHandler = HydrologyTypeHandler.class)
@Param(description = "Feature type: stream, river, major_river, cascade, waterfall, mouth, pond, lake, dam, sea_inlet, grotto or cave_pool", customHandler = HydrologyTypeHandler.class)
String type,
@Param(description = "Should you be teleported", defaultValue = "true")
boolean teleport
@@ -212,57 +212,58 @@ public class CommandFind implements DirectorExecutor {
}
return;
}
IrisHydrologyRuntime runtime = activeEngine.getComplex().getHydrologyRuntime();
HydrologyFeatureQuery query;
HydrologyFeatureType featureType;
try {
query = HydrologyFeatureQuery.parse(type);
featureType = HydrologyFeatureType.parse(type);
} catch (IllegalArgumentException error) {
commandSender.sendMessage(C.RED + error.getMessage());
return;
}
Location origin = target.getLocation();
World originWorld = origin.getWorld();
int requestedDistance = runtime == null
? 8192
: Math.min(8192, runtime.settings().routing().tileSize() * 15);
int maximumDistance = runtime == null
? requestedDistance
: runtime.maximumFeatureSearchDistance(
origin.getBlockX(), origin.getBlockZ(), requestedDistance);
commandSender.sendMessage(C.GRAY + "Searching accepted hydrology plans for " + type + "...");
J.a(() -> {
try {
GenerationSemanticQueries.RiverResult feature = GenerationSemanticQueries.nearestRiver(
activeEngine,
query,
origin.getBlockX(),
origin.getBlockZ(),
maximumDistance,
(int visited) -> sendStructureMessage(target, commandSender,
C.GRAY + "Searched " + visited + " hydrology tiles for " + type + "...")
).orElse(null);
if (feature == null) {
sendStructureMessage(target, commandSender,
C.YELLOW + "No accepted " + type + " hydrology feature found within "
+ maximumDistance + " blocks.");
return;
}
String label = type + " hydrology feature";
if (!teleport) {
sendStructureMessage(target, commandSender,
C.GREEN + "Found " + label + " at " + feature.x() + ", " + feature.y() + ", " + feature.z() + ".");
return;
}
Location destination = new Location(
originWorld, feature.x(), feature.y(), feature.z());
prepareStructureTeleport(
target, originWorld, commandSender, label, destination, true);
} catch (Throwable error) {
sendStructureMessage(target, commandSender,
C.RED + "Could not locate " + type + " hydrology: " + error.getClass().getSimpleName());
Iris.reportError("Could not locate accepted hydrology feature '" + type + "'.", error);
RiverRequest request = new RiverRequest(target, origin.getWorld(), commandSender, featureType, teleport);
commandSender.sendMessage(C.GRAY + GenerationSemanticQueries.riverSearchMessage(featureType,
GenerationSemanticQueries.RIVER_SEARCH_DISTANCE));
GenerationSemanticQueries.startRiverSearch(target.getUniqueId(), J::a, activeEngine, featureType, origin.getBlockX(),
origin.getBlockZ())
.whenComplete((search, failure) -> finishRiverSearch(request, search, failure));
}
private void finishRiverSearch(RiverRequest request, GenerationSemanticQueries.RiverSearch search, Throwable failure) {
if (failure instanceof CancellationException) {
return;
}
if (failure != null) {
reportRiverFailure(request, failure);
return;
}
try {
switch (search) {
case GenerationSemanticQueries.RiverSearch.Missing missing ->
sendStructureMessage(request.target(), request.sender(), C.YELLOW + missing.message());
case GenerationSemanticQueries.RiverSearch.Stopped stopped ->
sendStructureMessage(request.target(), request.sender(), C.YELLOW + stopped.message());
case GenerationSemanticQueries.RiverSearch.Found found -> arriveAtRiver(request, found.feature());
}
});
} catch (Throwable error) {
reportRiverFailure(request, error);
}
}
private void arriveAtRiver(RiverRequest request, GenerationSemanticQueries.RiverResult feature) {
if (!request.teleport()) {
sendStructureMessage(request.target(), request.sender(),
C.GREEN + "Found " + request.label() + " at " + feature.x() + ", " + feature.y() + ", " + feature.z() + ".");
return;
}
Location destination = new Location(request.world(), feature.x(), feature.y(), feature.z());
prepareStructureTeleport(request.target(), request.world(), request.sender(), request.label(), destination, true);
}
private void reportRiverFailure(RiverRequest request, Throwable failure) {
Iris.reportError("Could not locate hydrology feature '" + request.type().key() + "'.", failure);
sendStructureMessage(request.target(), request.sender(),
C.RED + "Could not search for " + request.label() + ": " + failure.getClass().getSimpleName()
+ (failure.getMessage() == null ? "" : " - " + failure.getMessage()));
}
@Director(description = "Find a structure (a vanilla key like minecraft:village_plains or minecraft:stronghold, or an imported iris structure key)", descriptionKey = "iris.director.commandfind.director.find_structure_vanilla_key_like_minecraft_village_plains_minecraft_stronghold_imported_iris", sync = true)
@@ -929,6 +930,12 @@ public class CommandFind implements DirectorExecutor {
int configuredUnregistered, int editableUnplaced, int managedUnregistered) {
}
private record RiverRequest(Player target, World world, VolmitSender sender, HydrologyFeatureType type, boolean teleport) {
private String label() {
return type.key().replace('_', ' ');
}
}
private record ManagedDatapackStructure(String key, Set<String> sourceIds) {
private ManagedDatapackStructure(String key) {
this(key, new LinkedHashSet<>());
@@ -19,6 +19,7 @@
package art.arcane.iris.command;
import art.arcane.iris.Iris;
import art.arcane.iris.IrisRuntime;
import art.arcane.iris.world.BukkitWorldReconciler;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.configuration.IrisSettings;
@@ -216,7 +217,7 @@ public class CommandIris implements DirectorExecutor {
) {
NamespacedKey worldKey;
try {
worldKey = Iris.instance.pendingWorldReplacements().resolveRequestedWorldKey(target);
worldKey = IrisRuntime.require().pendingWorldReplacements().resolveRequestedWorldKey(target);
} catch (IllegalArgumentException e) {
sender().sendMessage(C.RED + e.getMessage());
return;
@@ -240,7 +241,7 @@ public class CommandIris implements DirectorExecutor {
}
try {
PendingWorldReplacementManager.StagedReplacement staged = Iris.instance
PendingWorldReplacementManager.StagedReplacement staged = IrisRuntime.require()
.pendingWorldReplacements()
.stageReplacement(sender(), worldKey, dimension, seed);
String seedDetail = seed == null
@@ -634,7 +635,7 @@ public class CommandIris implements DirectorExecutor {
VolmitSender responseSender = sender();
responseSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_LOADING_WORLD, MessageArgument.untrusted("logicalWorldName", logicalWorldName)));
Iris.instance.worldReconciler()
IrisRuntime.require().worldReconciler()
.loadWorld(BUKKIT_YML, worldKey.toString())
.whenComplete((result, failure) -> {
Runnable response = () -> reportLoadWorldResult(
@@ -21,8 +21,10 @@ import art.arcane.iris.structure.StructureImporter;
import art.arcane.iris.structure.VillageImporter;
import art.arcane.iris.structure.authoring.StructureKey;
import art.arcane.iris.structure.authoring.StructureWriteResult;
import art.arcane.iris.structure.export.VanillaJigsawExportFormat;
import art.arcane.iris.pack.datapack.export.DatapackExportDestinations;
import art.arcane.iris.pack.datapack.export.DatapackExportFormat;
import art.arcane.iris.structure.export.VanillaJigsawExportRequest;
import art.arcane.iris.structure.export.VanillaJigsawExportSettings;
import art.arcane.iris.structure.export.VanillaJigsawExportSource;
import art.arcane.iris.structure.graph.PlanarJigsawWorkcellResolver;
import art.arcane.iris.generation.terrain.IrisDimension;
@@ -419,9 +421,9 @@ public class CommandJigsaw implements DirectorExecutor {
sendError("Wait for the pending autosave or discard the edits before exporting the on-disk graph.");
return;
}
VanillaJigsawExportFormat exportFormat;
DatapackExportFormat exportFormat;
try {
exportFormat = CommandJigsawExports.parseFormat(format);
exportFormat = DatapackExportDestinations.parseFormat(format);
} catch (IllegalArgumentException exception) {
sendError(exception.getMessage());
return;
@@ -430,20 +432,21 @@ public class CommandJigsaw implements DirectorExecutor {
.toPath().toAbsolutePath().normalize();
Path destination;
try {
destination = CommandJigsawExports.resolveExportDestination(exportRoot, output, exportFormat);
destination = DatapackExportDestinations.resolve(exportRoot, output, exportFormat);
} catch (IllegalArgumentException exception) {
sendError(exception.getMessage());
return;
}
VanillaJigsawExportRequest request;
try {
request = VanillaJigsawExportRequest.builder(
VanillaJigsawExportSource.forData(
context.request().source(), context.request().structureKey()), destination)
VanillaJigsawExportSource source = VanillaJigsawExportSource.forData(
context.request().source(), context.request().structureKey());
request = VanillaJigsawExportRequest.builder(source, destination)
.namespace(namespace)
.resourcePath(context.request().structureKey())
.format(exportFormat)
.replaceExisting(replace)
.settings(VanillaJigsawExportSettings.runtimeDefaults(source.loadStructure()))
.build();
} catch (IllegalArgumentException exception) {
sendError(exception.getMessage());
@@ -4,7 +4,7 @@ import art.arcane.iris.Iris;
import art.arcane.iris.studio.jigsaw.JigsawStudioService;
import art.arcane.iris.structure.export.VanillaJigsawDatapackExporter;
import art.arcane.iris.structure.export.VanillaJigsawExportDiagnostic;
import art.arcane.iris.structure.export.VanillaJigsawExportFormat;
import art.arcane.iris.pack.datapack.export.DatapackExportDestinations;
import art.arcane.iris.structure.export.VanillaJigsawExportRequest;
import art.arcane.iris.structure.export.VanillaJigsawExportResult;
import art.arcane.iris.localization.C;
@@ -13,18 +13,14 @@ import art.arcane.iris.world.task.J;
import org.bukkit.entity.Player;
import java.nio.file.Path;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
final class CommandJigsawExports {
private static final Pattern EXPORT_OUTPUT_NAME = Pattern.compile("[a-zA-Z0-9_-][a-zA-Z0-9._-]{0,127}");
private static final Set<UUID> EXPORTING_PLAYERS = ConcurrentHashMap.newKeySet();
private static final Set<Path> EXPORT_DESTINATIONS = ConcurrentHashMap.newKeySet();
private CommandJigsawExports() {
}
@@ -45,11 +41,11 @@ final class CommandJigsawExports {
static boolean beginExport(UUID playerId, Path destination) {
Objects.requireNonNull(playerId);
Path normalizedDestination = Objects.requireNonNull(destination).toAbsolutePath().normalize();
Objects.requireNonNull(destination);
if (!EXPORTING_PLAYERS.add(playerId)) {
return false;
}
if (EXPORT_DESTINATIONS.add(normalizedDestination)) {
if (DatapackExportDestinations.claim(destination)) {
return true;
}
EXPORTING_PLAYERS.remove(playerId);
@@ -58,7 +54,7 @@ final class CommandJigsawExports {
static void finishExport(UUID playerId, Path destination) {
EXPORTING_PLAYERS.remove(Objects.requireNonNull(playerId));
EXPORT_DESTINATIONS.remove(Objects.requireNonNull(destination).toAbsolutePath().normalize());
DatapackExportDestinations.release(destination);
}
static void runExport(ExportOperation operation) {
@@ -102,35 +98,6 @@ final class CommandJigsawExports {
+ result.status() + ": " + result.output());
}
static VanillaJigsawExportFormat parseFormat(String value) {
return switch (value.trim().toLowerCase(Locale.ROOT)) {
case "zip" -> VanillaJigsawExportFormat.ZIP;
case "directory", "dir", "folder" -> VanillaJigsawExportFormat.DIRECTORY;
default -> throw new IllegalArgumentException("Export format must be directory or zip.");
};
}
static Path resolveExportDestination(
Path exportRoot,
String output,
VanillaJigsawExportFormat format
) {
Path root = Objects.requireNonNull(exportRoot, "Jigsaw export root").toAbsolutePath().normalize();
String requested = Objects.requireNonNull(output, "Jigsaw export output name");
String name = requested.trim();
if (!name.equals(requested) || !EXPORT_OUTPUT_NAME.matcher(name).matches()) {
throw new IllegalArgumentException(
"Export output must be one file name using letters, numbers, '.', '_', or '-'.");
}
String fileName = format == VanillaJigsawExportFormat.ZIP && !name.endsWith(".zip")
? name + ".zip" : name;
Path destination = root.resolve(fileName).normalize();
if (destination.equals(root) || !root.equals(destination.getParent())) {
throw new IllegalArgumentException("Export output must be one artifact inside the Studio exports folder.");
}
return destination;
}
record ExportOperation(
Player player,
VolmitSender sender,
@@ -24,6 +24,7 @@ import art.arcane.iris.structure.BulkStructureImporter;
import art.arcane.iris.structure.StructureCaptureImporter;
import art.arcane.iris.structure.StructureImporter;
import art.arcane.iris.structure.StructureIndexService;
import art.arcane.iris.studio.object.ObjectSVC;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.structure.placement.IrisStructureLocator;
import art.arcane.iris.structure.nativegen.NativeStructureGenerationPolicy;
@@ -368,6 +369,7 @@ public class CommandStructure implements DirectorExecutor {
}
p.getObject().place(p.getX(), p.getY(), p.getZ(), placer, config, rng, null, null, data);
}
J.runGlobal(() -> Iris.service(ObjectSVC.class).addChanges(future));
int blockChanges = 0;
for (Map.Entry<Block, BlockData> entry : future.entrySet()) {
if (!entry.getKey().getBlockData().equals(entry.getValue())) {
@@ -21,10 +21,9 @@ package art.arcane.iris.command;
import art.arcane.iris.Iris;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.studio.map.MapWindow;
import art.arcane.iris.studio.map.PaletteExplorerStart;
import art.arcane.iris.studio.view.GuiHost;
import art.arcane.iris.studio.view.ImageMapStudioGUI;
import art.arcane.iris.studio.view.NoiseExplorerGUI;
import art.arcane.iris.studio.view.VisionGUI;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.studio.workspace.IrisProject;
import art.arcane.iris.studio.workspace.IrisCodeWorkspace;
@@ -98,11 +97,14 @@ import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.localization.BukkitCommandMessages;
import art.arcane.volmlib.util.localization.MessageArgument;
import art.arcane.volmlib.util.localization.LanguageAudience;
import art.arcane.iris.localization.BukkitCommandMessagesExtended;
@Director(name = "studio", aliases = {"std", "s"}, description = "Studio Commands", descriptionKey = "iris.director.commandstudio.director.studio_commands")
public class CommandStudio implements DirectorExecutor {
@@ -202,6 +204,22 @@ public class CommandStudio implements DirectorExecutor {
}));
}
@Director(description = "Hotload the active Studio pack", descriptionKey = "iris.director.commandstudio.director.hotload_active_studio_pack", aliases = {"refresh"}, origin = DirectorOrigin.BOTH)
public void hotload() {
VolmitSender commandSender = sender();
IrisProject project = Iris.service(StudioSVC.class).getActiveProject();
PlatformChunkGenerator generator = project == null ? null : project.getActiveProvider();
if (generator == null) {
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_NO_OPEN_STUDIO_PROJECTS));
return;
}
UUID audience = LanguageAudience.current();
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_HOTLOADING));
generator.hotloadAsync().whenComplete((ignored, failure) ->
LanguageAudience.run(audience, () -> sendHotloadResult(commandSender, failure)));
}
@Director(description = "Toggle your Studio debug scoreboard", descriptionKey = "iris.director.commandstudio.director.toggle_your_studio_debug_scoreboard", aliases = {"board", "sidebar", "sb"}, origin = DirectorOrigin.PLAYER)
public void scoreboard() {
Player target = player();
@@ -255,15 +273,10 @@ public class CommandStudio implements DirectorExecutor {
long seed
) {
if (noGUI()) return;
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_NOISE_EXPLORER));
if (generator == null) {
NoiseExplorerGUI.launch();
return;
}
String generatorKey = generator.getLoadKey();
NoiseExplorerGUI.launchGeneratorKey(generatorKey, generator, seed);
VolmitSender commandSender = sender();
UUID openerId = commandSender.isPlayer() ? commandSender.player().getUniqueId() : null;
MapWindow.NoiseSelection selection = new MapWindow.NoiseSelection(generator == null ? null : generator.getLoadKey(), generator, seed);
withPlayerContext(opener -> openNoiseAtPlayer(commandSender, openerId, opener, selection));
}
@Director(description = "Open the image-map studio (External GUI)", descriptionKey = "iris.director.commandstudio.director.open_image_map_studio_external_gui", aliases = {"imap"})
@@ -279,8 +292,7 @@ public class CommandStudio implements DirectorExecutor {
return;
}
Engine activeEngine = IrisToolbelt.access(world).getEngine();
ImageMapStudioGUI.launch(activeEngine);
requestMapStart(world, MapWindow::openImageMaps);
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_IMAGE_MAP_STUDIO));
}
@@ -420,11 +432,61 @@ public class CommandStudio implements DirectorExecutor {
return;
}
UUID openerId = sender().isPlayer() ? player().getUniqueId() : null;
VisionGUI.launch(IrisToolbelt.access(world).getEngine(), openerId);
requestMapStart(world, MapWindow::openMap);
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP));
}
// The map opens where the player stands when they are in that world, otherwise at the world origin.
private PaletteExplorerStart mapStartIn(World world, Player opener, UUID openerId) {
Location center = opener != null && opener.getWorld().equals(world) ? opener.getLocation() : null;
return new PaletteExplorerStart(
IrisToolbelt.access(world).getEngine(),
world.getUID(),
openerId,
null,
center == null ? 0D : center.getX(),
center == null ? 0D : center.getZ()
);
}
private void requestMapStart(World world, Consumer<PaletteExplorerStart> launch) {
UUID openerId = sender().isPlayer() ? player().getUniqueId() : null;
withPlayerContext(opener -> launch.accept(mapStartIn(world, opener, openerId)));
}
private void openNoiseAtPlayer(VolmitSender commandSender, UUID openerId, Player opener, MapWindow.NoiseSelection selection) {
World world = opener == null ? null : opener.getWorld();
PlatformChunkGenerator worldGenerator = world == null ? null : IrisToolbelt.access(world);
Engine engine = worldGenerator == null ? GuiHost.get().findActiveEngine() : worldGenerator.getEngine();
if (engine == null) {
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
return;
}
PaletteExplorerStart start = worldGenerator == null
? new PaletteExplorerStart(engine, null, openerId, null, 0D, 0D)
: mapStartIn(world, opener, openerId);
MapWindow.openNoise(start, selection);
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_NOISE_EXPLORER));
}
private void withPlayerContext(Consumer<Player> action) {
Player opener = sender().isPlayer() ? player() : null;
if (opener == null) {
action.accept(null);
return;
}
AtomicBoolean completed = new AtomicBoolean();
Consumer<Player> complete = player -> {
if (completed.compareAndSet(false, true)) {
action.accept(player);
}
};
Runnable retired = () -> complete.accept(null);
if (!J.runEntity(opener, () -> complete.accept(opener.isOnline() ? opener : null), 0, retired)) {
retired.run();
}
}
@Director(description = "Profiles the performance of a dimension", descriptionKey = "iris.director.commandstudio.director.profiles_performance_dimension", origin = DirectorOrigin.PLAYER)
public void profile(
@Param(description = "The dimension to profile", descriptionKey = "iris.director.commandstudio.param.dimension_profile", contextual = true, contextualOverride = true, defaultValue = "default", customHandler = DimensionHandler.class)
@@ -597,6 +659,16 @@ public class CommandStudio implements DirectorExecutor {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_DONE, MessageArgument.untrusted("value", report.getPath())));
}
private void sendHotloadResult(VolmitSender commandSender, Throwable failure) {
if (failure != null) {
Iris.reportError(failure);
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_HOTLOAD_FAILED,
MessageArgument.untrusted("value", String.valueOf(failure.getMessage()))));
return;
}
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_HOTLOADED));
}
private PlatformChunkGenerator resolveProfileGenerator(IrisDimension dimension) {
StudioSVC studioService = Iris.service(StudioSVC.class);
if (studioService != null && studioService.isProjectOpen()) {
@@ -0,0 +1,50 @@
package art.arcane.iris.platform.agent;
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.util.Locale;
public final class AttachSignal {
private static final int SIGQUIT = 3;
private static final int SIGTERM = 15;
private static final long ACTION_BYTES = 256;
private static final long SIG_IGN = 1L;
private AttachSignal() {
}
public static boolean restoreJvmHandler() {
if (System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win")) {
return false;
}
Linker linker = Linker.nativeLinker();
MethodHandle sigaction = linker.downcallHandle(
linker.defaultLookup().find("sigaction")
.orElseThrow(() -> new IllegalStateException("sigaction is unavailable")),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
try (Arena arena = Arena.ofConfined()) {
MemorySegment jvm = arena.allocate(ACTION_BYTES);
MemorySegment quit = arena.allocate(ACTION_BYTES);
if ((int) sigaction.invokeExact(SIGTERM, MemorySegment.NULL, jvm) != 0
|| (int) sigaction.invokeExact(SIGQUIT, MemorySegment.NULL, quit) != 0) {
throw new IllegalStateException("sigaction could not read the SIGTERM and SIGQUIT handlers");
}
long handler = jvm.get(ValueLayout.JAVA_LONG, 0);
if (handler == 0L || handler == SIG_IGN || quit.get(ValueLayout.JAVA_LONG, 0) == handler) {
return false;
}
if ((int) sigaction.invokeExact(SIGQUIT, jvm, MemorySegment.NULL) != 0) {
throw new IllegalStateException("sigaction could not restore the JVM SIGQUIT handler");
}
return true;
} catch (RuntimeException | Error failure) {
throw failure;
} catch (Throwable failure) {
throw new IllegalStateException("Unable to restore the JVM SIGQUIT handler", failure);
}
}
}
@@ -17,8 +17,8 @@ import art.arcane.iris.platform.bukkit.terrain.IrisSampleLimits;
import art.arcane.iris.platform.bukkit.terrain.IrisSurfaceClassifier;
import art.arcane.iris.platform.bukkit.terrain.IrisWorldInfoFactory;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.hydrology.HydrologyColumnLayer;
import art.arcane.iris.generation.hydrology.HydrologyColumnSample;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.stream.ProvisionalSampling;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.terrain.IrisRegion;
@@ -92,7 +92,9 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
return OptionalInt.of(engine.getHeight(blockX, blockZ) + engine.getMinHeight());
long revision = ProvisionalSampling.revision();
int height = engine.getHeight(blockX, blockZ) + engine.getMinHeight();
return provisionalSince(revision) ? OptionalInt.empty() : OptionalInt.of(height);
} catch (Throwable error) {
reportQueryFault("surfaceHeight", world, error);
return OptionalInt.empty();
@@ -107,16 +109,18 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
long revision = ProvisionalSampling.revision();
int surface = engine.getHeight(blockX, blockZ);
HydrologyColumnSample hydrology = hydrologySample(engine, blockX, blockZ);
WaterRole role = engine.getComplex().getWaterRoleStream().get(blockX, blockZ);
int fluid = (int) Math.round(
engine.getComplex().getRiverWaterSurfaceStream().get(blockX, blockZ));
engine.getComplex().getWaterHeadStream().get(blockX, blockZ));
InferredType inferredType = null;
if (IrisSurfaceClassifier.requiresSurfaceBiome(surface, fluid)) {
IrisBiome biome = engine.getSurfaceBiome(blockX, blockZ);
inferredType = biome == null ? null : biome.getInferredType();
}
return IrisSurfaceClassifier.classify(surface, fluid, inferredType, hydrology);
IrisSurfaceKind kind = IrisSurfaceClassifier.classify(surface, fluid, inferredType, role);
return provisionalSince(revision) ? IrisSurfaceKind.UNKNOWN : kind;
} catch (Throwable error) {
reportQueryFault("surfaceKind", world, error);
return IrisSurfaceKind.UNKNOWN;
@@ -131,7 +135,9 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
return key(engine.getSurfaceBiome(blockX, blockZ));
long revision = ProvisionalSampling.revision();
Optional<String> key = key(engine.getSurfaceBiome(blockX, blockZ));
return provisionalSince(revision) ? Optional.empty() : key;
} catch (Throwable error) {
reportQueryFault("surfaceBiomeKey", world, error);
return Optional.empty();
@@ -146,7 +152,9 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
return name(engine.getSurfaceBiome(blockX, blockZ));
long revision = ProvisionalSampling.revision();
Optional<String> name = name(engine.getSurfaceBiome(blockX, blockZ));
return provisionalSince(revision) ? Optional.empty() : name;
} catch (Throwable error) {
reportQueryFault("surfaceBiomeName", world, error);
return Optional.empty();
@@ -161,8 +169,10 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
return Optional.of(IrisBiomeInfoFactory.surface(engine, blockX, blockZ,
error -> reportQueryFault("surfaceBiomeInfo", world, error)));
long revision = ProvisionalSampling.revision();
IrisBiomeInfo info = IrisBiomeInfoFactory.surface(engine, blockX, blockZ,
error -> reportQueryFault("surfaceBiomeInfo", world, error));
return provisionalSince(revision) ? Optional.empty() : Optional.of(info);
} catch (Throwable error) {
reportQueryFault("surfaceBiomeInfo", world, error);
return Optional.empty();
@@ -177,7 +187,9 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
return key(engine.getBiome(blockX, blockY - engine.getMinHeight(), blockZ));
long revision = ProvisionalSampling.revision();
Optional<String> key = key(engine.getBiome(blockX, blockY - engine.getMinHeight(), blockZ));
return provisionalSince(revision) ? Optional.empty() : key;
} catch (Throwable error) {
reportQueryFault("biomeKey", world, error);
return Optional.empty();
@@ -192,9 +204,10 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
long revision = ProvisionalSampling.revision();
IrisRegion region = engine.getRegion(blockX, blockZ);
String loadKey = region == null ? null : region.getLoadKey();
return loadKey == null || loadKey.isEmpty() ? Optional.empty() : Optional.of(loadKey);
return provisionalSince(revision) || loadKey == null || loadKey.isEmpty() ? Optional.empty() : Optional.of(loadKey);
} catch (Throwable error) {
reportQueryFault("regionKey", world, error);
return Optional.empty();
@@ -209,9 +222,10 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
long revision = ProvisionalSampling.revision();
IrisRegion region = engine.getRegion(blockX, blockZ);
String name = region == null ? null : region.getName();
return name == null || name.isEmpty() ? Optional.empty() : Optional.of(name);
return provisionalSince(revision) || name == null || name.isEmpty() ? Optional.empty() : Optional.of(name);
} catch (Throwable error) {
reportQueryFault("regionName", world, error);
return Optional.empty();
@@ -266,12 +280,13 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
return false;
}
HydrologyColumnSample hydrology = wantRiver
? hydrologySample(engine, blockX, blockZ)
: null;
long revision = ProvisionalSampling.revision();
WaterRole role = wantRiver
? engine.getComplex().getWaterRoleStream().get(blockX, blockZ)
: WaterRole.NONE;
int surface = wantHeight || wantKind ? engine.getHeight(blockX, blockZ) : 0;
int fluid = wantRiver
? (int) Math.round(engine.getComplex().getRiverWaterSurfaceStream().get(blockX, blockZ))
? (int) Math.round(engine.getComplex().getWaterHeadStream().get(blockX, blockZ))
: engine.getDimension().getFluidHeight();
boolean needsBiome = wantBiome
|| (wantKind && IrisSurfaceClassifier.requiresSurfaceBiome(surface, fluid));
@@ -281,29 +296,23 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
surface,
fluid,
biome == null ? null : biome.getInferredType(),
hydrology
role
)
: IrisSurfaceKind.UNKNOWN;
String biomeKey = wantBiome && biome != null ? biome.getLoadKey() : null;
int natural = wantNaturalHeight
? (int) Math.round(engine.getComplex().getNaturalHeightStream().get(blockX, blockZ)) + minHeight
: IrisColumnSample.UNAVAILABLE_HEIGHT;
HydrologyColumnLayer surfaceLayer = hydrology == null
? null
: hydrology.primarySurfaceLayer().orElse(null);
boolean riverPresent = surfaceLayer != null;
IrisRiverState riverState = wantRiverState
? riverState(hydrology)
? riverState(role)
: IrisRiverState.NONE;
double riverDistance = wantRiverDistance && riverPresent
? engine.getComplex().getRiverDistanceStream().get(blockX, blockZ)
double riverDistance = wantRiverDistance
? riverDistance(role)
: IrisColumnSample.UNAVAILABLE_RIVER_DISTANCE;
int riverFlow = wantRiverFlow && riverPresent
? (int) Math.round(engine.getComplex().getRiverFlowStream().get(blockX, blockZ))
int riverFlow = wantRiverFlow
? riverFlow(role)
: IrisColumnSample.UNAVAILABLE_RIVER_FLOW;
int riverWaterSurfaceY = wantRiverWaterSurface
&& surfaceLayer != null
&& surfaceLayer.connectedFluid()
int riverWaterSurfaceY = wantRiverWaterSurface && role.wet()
? fluid + minHeight
: IrisColumnSample.UNAVAILABLE_HEIGHT;
sink.accept(new IrisColumnSample(
@@ -316,7 +325,8 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
riverState,
riverDistance,
riverFlow,
riverWaterSurfaceY
riverWaterSurfaceY,
provisionalSince(revision)
));
return true;
});
@@ -327,21 +337,25 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
}
static IrisRiverState riverState(HydrologyColumnSample hydrology) {
HydrologyColumnLayer layer = hydrology == null
? null
: hydrology.primarySurfaceLayer().orElse(null);
if (layer == null || !layer.channel()) {
return IrisRiverState.NONE;
}
return layer.connectedFluid() ? IrisRiverState.WET : IrisRiverState.DRY;
static IrisRiverState riverState(WaterRole role) {
return role.wet() ? IrisRiverState.WET : IrisRiverState.NONE;
}
private static HydrologyColumnSample hydrologySample(Engine engine, int blockX, int blockZ) {
if (engine.getComplex().getHydrologyRuntime() == null) {
return null;
}
return engine.getComplex().getHydrologyRuntime().sample(blockX, blockZ).orElse(null);
static double riverDistance(WaterRole role) {
return switch (role) {
case NONE -> IrisColumnSample.UNAVAILABLE_RIVER_DISTANCE;
case CHANNEL, POND, MOUTH, CASCADE, WATERFALL, INLET -> 0D;
case SHORE, POND_SHORE -> 1D;
case BANK, DAM -> 2D;
};
}
static int riverFlow(WaterRole role) {
return switch (role) {
case NONE, SHORE, POND_SHORE, BANK, DAM -> IrisColumnSample.UNAVAILABLE_RIVER_FLOW;
case CHANNEL, MOUTH, CASCADE, WATERFALL -> 1;
case POND, INLET -> 0;
};
}
private static Optional<String> key(IrisBiome biome) {
@@ -354,6 +368,10 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
return name == null || name.isEmpty() ? Optional.empty() : Optional.of(name);
}
private static boolean provisionalSince(long revision) {
return ProvisionalSampling.revision() != revision;
}
private static int noiseCacheChunks() {
return IrisSettings.get().getPerformance().getNoiseCacheSize();
}
@@ -1,8 +1,7 @@
package art.arcane.iris.platform.bukkit.terrain;
import art.arcane.iris.api.terrain.IrisSurfaceKind;
import art.arcane.iris.generation.hydrology.HydrologyColumnLayer;
import art.arcane.iris.generation.hydrology.HydrologyColumnSample;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.terrain.InferredType;
public final class IrisSurfaceClassifier {
@@ -29,25 +28,16 @@ public final class IrisSurfaceClassifier {
int engineSurfaceHeight,
int engineFluidHeight,
InferredType inferredType,
HydrologyColumnSample hydrology
WaterRole role
) {
if (engineSurfaceHeight <= 0) {
return IrisSurfaceKind.VOID;
}
HydrologyColumnLayer layer = hydrology == null
? null
: hydrology.primarySurfaceLayer().orElse(null);
if (layer != null) {
if (layer.shore()) {
return IrisSurfaceKind.RIVER_SHORE;
}
if (layer.channel()) {
return layer.connectedFluid() ? IrisSurfaceKind.RIVER : IrisSurfaceKind.DRY_CHANNEL;
}
if (layer.grading()) {
return IrisSurfaceKind.LAND;
}
}
return classify(engineSurfaceHeight, engineFluidHeight, inferredType);
return switch (role) {
case NONE -> classify(engineSurfaceHeight, engineFluidHeight, inferredType);
case SHORE, POND_SHORE -> IrisSurfaceKind.RIVER_SHORE;
case BANK, DAM -> IrisSurfaceKind.LAND;
case CHANNEL, POND, MOUTH, CASCADE, WATERFALL, INLET -> IrisSurfaceKind.RIVER;
};
}
}
@@ -23,6 +23,8 @@ import art.arcane.iris.world.event.IrisEngineHotloadEvent;
import art.arcane.iris.world.IrisToolbelt;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.platform.generation.PlatformChunkGenerator;
import art.arcane.iris.studio.StudioSVC;
import art.arcane.iris.studio.workspace.IrisProject;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
@@ -40,16 +42,21 @@ public final class BukkitGuiHost implements GuiHost.Provider {
GuiHost.set(new BukkitGuiHost());
}
/**
* The engine of the open studio project, which reads the pack folder being edited, or else the first
* Iris world. A normal Iris world runs on its own copy of the pack, made when the world was created.
*/
@Override
public Engine findActiveEngine() {
Engine studioEngine = findStudioEngine();
if (studioEngine != null) {
return studioEngine;
}
try {
for (World world : new ArrayList<>(Bukkit.getWorlds())) {
try {
PlatformChunkGenerator access = IrisToolbelt.access(world);
if (access != null && access.getEngine() != null && !access.getEngine().isClosed()) {
return access.getEngine();
}
} catch (Throwable ignored) {
Engine engine = engineOf(world);
if (engine != null) {
return engine;
}
}
} catch (Throwable ignored) {
@@ -57,6 +64,35 @@ public final class BukkitGuiHost implements GuiHost.Provider {
return null;
}
@Override
public Engine findEngine(UUID worldId) {
World world = worldId == null ? null : Bukkit.getWorld(worldId);
return world == null ? null : engineOf(world);
}
private static Engine findStudioEngine() {
try {
StudioSVC studio = Iris.service(StudioSVC.class);
IrisProject project = studio == null || !studio.isProjectOpen() ? null : studio.getActiveProject();
PlatformChunkGenerator provider = project == null ? null : project.getActiveProvider();
Engine engine = provider == null ? null : provider.getEngine();
return engine == null || engine.isClosed() ? null : engine;
} catch (Throwable ignored) {
return null;
}
}
private static Engine engineOf(World world) {
try {
PlatformChunkGenerator access = IrisToolbelt.access(world);
if (access != null && access.getEngine() != null && !access.getEngine().isClosed()) {
return access.getEngine();
}
} catch (Throwable ignored) {
}
return null;
}
@Override
public void registerHotloadHook(Runnable onHotload) {
Listener listener = new HotloadListener(onHotload);
@@ -18,23 +18,19 @@
package art.arcane.iris.studio.view;
import art.arcane.volmlib.nativelib.view.WorldMarker;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.studio.render.RenderType;
import art.arcane.iris.world.IrisWorld;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.world.task.J;
import art.arcane.volmlib.util.format.Form;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -56,7 +52,7 @@ public final class BukkitVisionOverlay implements GuiOverlay {
private final AtomicBoolean playerRefreshQueued = new AtomicBoolean();
private final AtomicLong teleportSequence = new AtomicLong();
private final AtomicReference<VisionTeleportRequest> latestTeleport = new AtomicReference<>();
private volatile List<WorldMarker> playerMarkers = List.of();
private volatile List<GuiMarker> playerMarkers = List.of();
public BukkitVisionOverlay(Engine engine, UUID openerId) {
this.engine = engine;
@@ -68,7 +64,7 @@ public final class BukkitVisionOverlay implements GuiOverlay {
* built by a server thread.
*/
@Override
public List<WorldMarker> players() {
public List<GuiMarker> players() {
queuePlayerRefresh();
return playerMarkers;
}
@@ -78,26 +74,48 @@ public final class BukkitVisionOverlay implements GuiOverlay {
return;
}
boolean scheduled = J.runGlobal(() -> {
try {
List<WorldMarker> markers = new ArrayList<>();
for (Player player : BukkitWorldBinding.players(engine.getWorld())) {
Location at = player.getLocation();
markers.add(WorldMarker.player(player.getName(), at.getX(), at.getZ()));
}
playerMarkers = List.copyOf(markers);
} finally {
playerRefreshQueued.set(false);
}
});
boolean scheduled = J.runGlobal(this::refreshPlayers);
if (!scheduled) {
playerRefreshQueued.set(false);
}
}
private void refreshPlayers() {
World world = BukkitWorldBinding.world(engine.getWorld());
List<Player> players = BukkitWorldBinding.players(engine.getWorld());
if (players.isEmpty() || world == null) {
playerMarkers = List.of();
playerRefreshQueued.set(false);
return;
}
List<GuiMarker> markers = Collections.synchronizedList(new ArrayList<>(players.size()));
AtomicInteger pending = new AtomicInteger(players.size());
for (Player player : players) {
AtomicBoolean completed = new AtomicBoolean();
Runnable complete = () -> {
if (completed.compareAndSet(false, true) && pending.decrementAndGet() == 0) {
playerMarkers = List.copyOf(markers);
playerRefreshQueued.set(false);
}
};
if (!J.runEntity(player, () -> {
try {
if (player.isOnline() && player.getWorld() == world) {
Location at = player.getLocation();
markers.add(GuiMarker.player(player.getName(), at.getX(), at.getZ(), at.getYaw()));
}
} finally {
complete.run();
}
}, 0, complete)) {
complete.run();
}
}
}
@Override
public void requestEntities(Consumer<List<WorldMarker>> sink) {
public void requestEntities(Consumer<List<GuiMarker>> sink) {
J.runGlobal(() -> {
IrisWorld target = engine.getWorld();
World world = BukkitWorldBinding.world(target);
@@ -118,7 +136,7 @@ public final class BukkitVisionOverlay implements GuiOverlay {
return;
}
List<WorldMarker> collected = Collections.synchronizedList(new ArrayList<>(living.size()));
List<GuiMarker> collected = Collections.synchronizedList(new ArrayList<>(living.size()));
AtomicInteger pending = new AtomicInteger(living.size());
Runnable complete = () -> {
if (pending.decrementAndGet() == 0) {
@@ -144,22 +162,22 @@ public final class BukkitVisionOverlay implements GuiOverlay {
});
}
private WorldMarker marker(LivingEntity entity, Location at) {
private GuiMarker marker(LivingEntity entity, Location at) {
String label = Form.capitalizeWords(entity.getType().name().toLowerCase(Locale.ROOT).replaceAll("\\Q_\\E", " "));
double maxHealth = 0;
try {
maxHealth = entity.getAttribute(MAX_HEALTH).getValue();
} catch (Throwable ignored) {
}
return WorldMarker.entity(label, at.getX(), at.getY(), at.getZ(), entity.getHealth(), maxHealth);
return GuiMarker.entity(label, at.getX(), at.getY(), at.getZ(), entity.getHealth(), maxHealth);
}
@Override
public void teleport(double worldX, double worldZ) {
VisionTeleportRequest request = new VisionTeleportRequest(
teleportSequence.incrementAndGet(),
VisionGUI.floorWorldCoordinate(worldX),
VisionGUI.floorWorldCoordinate(worldZ));
(int) StrictMath.floor(worldX),
(int) StrictMath.floor(worldZ));
latestTeleport.set(request);
startTeleport(request);
}
@@ -212,6 +230,46 @@ public final class BukkitVisionOverlay implements GuiOverlay {
}
}
@Override
public void requestOpenerPosition(Consumer<OpenerPosition> sink) {
AtomicBoolean completed = new AtomicBoolean();
Consumer<OpenerPosition> complete = position -> {
if (completed.compareAndSet(false, true)) {
sink.accept(position);
}
};
if (openerId == null) {
complete.accept(OpenerPosition.OFFLINE);
return;
}
boolean scheduled = J.runGlobal(() -> {
Player player = Bukkit.getPlayer(openerId);
if (player == null) {
complete.accept(OpenerPosition.OFFLINE);
return;
}
Runnable retired = () -> complete.accept(OpenerPosition.OFFLINE);
if (!J.runEntity(player, () -> complete.accept(positionOf(player,
BukkitWorldBinding.world(engine.getWorld()))), 0, retired)) {
retired.run();
}
});
if (!scheduled) {
complete.accept(OpenerPosition.OFFLINE);
}
}
private static OpenerPosition positionOf(Player player, World world) {
if (!player.isOnline()) {
return OpenerPosition.OFFLINE;
}
if (world == null || player.getWorld() != world) {
return OpenerPosition.IN_OTHER_WORLD;
}
Location at = player.getLocation();
return OpenerPosition.inWorld(at.getX(), at.getY(), at.getZ());
}
private Player selectPlayer(List<Player> players) {
if (openerId == null) {
return players.isEmpty() ? null : players.get(0);
@@ -316,21 +374,6 @@ public final class BukkitVisionOverlay implements GuiOverlay {
+ blockX + "," + blockZ + ".", failure);
}
@Override
public String openInEditor(double worldX, double worldZ, RenderType type) {
IrisComplex complex = engine.getComplex();
File file = switch (type) {
case BIOME, LAYER_LOAD, DECORATOR_LOAD, OBJECT_LOAD, HEIGHT, RIVER ->
complex.getTrueBiomeStream().get(worldX, worldZ).openInVSCode();
case BIOME_LAND -> complex.getLandBiomeStream().get(worldX, worldZ).openInVSCode();
case BIOME_SEA -> complex.getSeaBiomeStream().get(worldX, worldZ).openInVSCode();
case REGION -> complex.getRegionStream().get(worldX, worldZ).openInVSCode();
case CAVE_LAND -> complex.getCaveBiomeStream().get(worldX, worldZ).openInVSCode();
default -> null;
};
return file == null ? null : file.getName();
}
private static final class VisionTeleportRequest {
private final long sequence;
private final int blockX;
@@ -27,6 +27,8 @@ import org.bukkit.Particle;
import org.bukkit.Sound;
import org.bukkit.World;
import art.arcane.iris.Iris;
import art.arcane.iris.IrisRuntime;
import art.arcane.iris.platform.bukkit.chunk.TicketHolder;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.localization.RuntimeUiMessages;
import art.arcane.iris.studio.edit.DustRevealer;
@@ -109,7 +111,7 @@ public class WandSVC implements IrisService {
int total = c.getSizeX() * c.getSizeY() * c.getSizeZ();
var latch = new CountDownLatch(1);
var holder = Iris.tickets.getHolder(p.getWorld());
TicketHolder holder = IrisRuntime.require().tickets().getHolder(p.getWorld());
new Job() {
private volatile int i;
private Chunk chunk;
@@ -68,8 +68,8 @@ public final class BukkitWorldReconciler {
private final Backend backend;
private final LifecycleOperationCoordinator coordinator;
public BukkitWorldReconciler(Iris plugin) {
this(new BukkitBackend(plugin), LifecycleOperationCoordinator.get());
public BukkitWorldReconciler(IrisWorldGeneratorResolver generatorResolver) {
this(new BukkitBackend(generatorResolver), LifecycleOperationCoordinator.get());
}
BukkitWorldReconciler(Backend backend, LifecycleOperationCoordinator coordinator) {
@@ -688,10 +688,10 @@ public final class BukkitWorldReconciler {
}
private static final class BukkitBackend implements Backend {
private final Iris plugin;
private final IrisWorldGeneratorResolver generatorResolver;
private BukkitBackend(Iris plugin) {
this.plugin = Objects.requireNonNull(plugin, "plugin");
private BukkitBackend(IrisWorldGeneratorResolver generatorResolver) {
this.generatorResolver = Objects.requireNonNull(generatorResolver, "generatorResolver");
}
@Override
@@ -734,13 +734,13 @@ public final class BukkitWorldReconciler {
try {
configuredWorldName = configuredWorldName(worldKey);
Iris.info("Loading World: %s | Generator: %s", IrisWorldStorage.logicalName(worldKey), dimension);
generator = plugin.requireWorldGenerator(configuredWorldName, dimension);
generator = generatorResolver.requireWorldGenerator(configuredWorldName, dimension);
irisDimension = IrisWorldGeneratorResolver.loadDimension(configuredWorldName, dimension);
if (generator == null || irisDimension == null) {
throw new IllegalStateException("Could not resolve the Iris generator or dimension \"" + dimension + "\".");
}
} catch (Throwable refusal) {
plugin.worldRefusals().report(configuredWorldName, worldKey, refusal);
generatorResolver.refusals().report(configuredWorldName, worldKey, refusal);
return CompletableFuture.failedFuture(refusal);
}
try {
@@ -58,6 +58,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@@ -78,6 +79,9 @@ public final class PendingWorldReplacementManager implements Listener {
private volatile UUID overworldEntryAwaitingVerification;
private volatile World overworldEntryWorld;
private volatile boolean paperEntryListenerRegistered;
private final Object stagingMonitor = new Object();
private boolean stagingAdmissionOpen = true;
private StagingAdmission activeStaging;
public PendingWorldReplacementManager(Iris plugin) {
this.plugin = Objects.requireNonNull(plugin, "plugin");
@@ -135,7 +139,8 @@ public final class PendingWorldReplacementManager implements Listener {
LifecycleOperationCoordinator.Domain.WORLD_MUTATION,
LifecycleOperationCoordinator.OperationKind.WORLD_REPLACE,
requiredWorldKey.toString()
); WorldReplacementProgress progress = WorldReplacementProgress.start(
); StagingAdmission ignoredAdmission = admitStaging(requiredWorldKey);
WorldReplacementProgress progress = WorldReplacementProgress.start(
requiredSender, requiredWorldKey.toString())) {
synchronized (this) {
IrisStartupValidation.requireWorldReplacementStagingReady();
@@ -271,6 +276,29 @@ public final class PendingWorldReplacementManager implements Listener {
}
}
public void awaitStagingForShutdown() {
StagingAdmission staging;
synchronized (stagingMonitor) {
stagingAdmissionOpen = false;
staging = activeStaging;
}
if (staging == null) {
return;
}
Iris.warn("Waiting for the replacement of " + staging.worldKey + " to finish staging before Iris shuts down.");
boolean interrupted = false;
while (staging.finished.getCount() > 0L) {
try {
staging.finished.await();
} catch (InterruptedException e) {
interrupted = true;
}
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
public synchronized void processPendingStartupReplacements() {
ArrayList<String> failures = new ArrayList<>();
ArrayList<String> restartBoundaries = new ArrayList<>();
@@ -1048,6 +1076,17 @@ public final class PendingWorldReplacementManager implements Listener {
return plugin.getDataFolder().toPath().toAbsolutePath().normalize();
}
private StagingAdmission admitStaging(NamespacedKey worldKey) throws IOException {
synchronized (stagingMonitor) {
if (!stagingAdmissionOpen) {
throw new IOException("Iris is shutting down. Run the replacement again after the server starts.");
}
StagingAdmission staging = new StagingAdmission(worldKey);
activeStaging = staging;
return staging;
}
}
private synchronized void loadOverworldEntryGuard() throws IOException {
ExactWorldSlotPathPolicy.Target target = resolveTarget(OVERWORLD_KEY);
Optional<WorldReplacementEntryGuard.Entry> loaded = WorldReplacementEntryGuard.load(target.worldDirectory());
@@ -1218,6 +1257,25 @@ public final class PendingWorldReplacementManager implements Listener {
record SavedLocationInspection(boolean safe, Throwable failure) {
}
private final class StagingAdmission implements AutoCloseable {
private final NamespacedKey worldKey;
private final CountDownLatch finished = new CountDownLatch(1);
private StagingAdmission(NamespacedKey worldKey) {
this.worldKey = worldKey;
}
@Override
public void close() {
synchronized (stagingMonitor) {
if (activeStaging == this) {
activeStaging = null;
}
}
finished.countDown();
}
}
private static final class RestartBoundaryRequired extends IOException {
private RestartBoundaryRequired(String message) {
super(message);
@@ -27,3 +27,4 @@ permissions:
description: Allows survival players to fell Iris-managed trees with an axe.
default: op
api-version: '${apiVersion}'
libraries: [ ${libraries} ]
@@ -1,6 +1,6 @@
package art.arcane.iris.fixture;
import art.arcane.iris.Iris;
import art.arcane.iris.IrisRuntime;
import art.arcane.volmlib.nativelib.NativeAdapters;
import art.arcane.iris.world.runtime.RuntimeInjection;
import art.arcane.iris.generation.runtime.Engine;
@@ -138,7 +138,7 @@ public final class NativeLifecycleFixture extends JavaPlugin implements WorldRun
return CompletableFuture.completedFuture(null);
}
if (WorldCreatorCompat.persistentLevelRoot(TREASURE_KEY).exists()) {
return Iris.instance.worldReconciler().loadWorld(ServerProperties.BUKKIT_YML, TREASURE_KEY.toString());
return IrisRuntime.require().worldReconciler().loadWorld(ServerProperties.BUKKIT_YML, TREASURE_KEY.toString());
}
return runAsync(() -> {
try {
@@ -0,0 +1,72 @@
import { readFile, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { setup, openStudio, closeStudio, sampleTerrain, readJson, writeJson,
logPosition, logSince } from './studio-support.mjs'
async function hotload(context, fixture, active, command) {
const before = await readJson(fixture.manifestPath(active.key))
const response = await context.command(command, /^Studio hotloaded\.$|^Studio hotload failed:/, 90000)
context.expect(response === 'Studio hotloaded.', 'The manual Studio command did not complete successfully', { command, response })
const after = await readJson(fixture.manifestPath(active.key))
context.expect(after.pendingActivationId === null, 'The manual hotload completed with a pending activation')
context.report.iris.manualHotloads.push({ command, response,
before: before.activeActivationId, after: after.activeActivationId })
return after
}
export default {
name: 'iris-studio-manual-hotload',
description: 'Refresh an open Studio through hotload and its refresh alias, verify terrain, and reject commands without a Studio.',
async run(context) {
const fixture = await setup(context)
const biomeFile = path.join(fixture.pack, 'biomes', 'flat.json')
const original = await readFile(biomeFile, 'utf8')
const logOffset = await logPosition(fixture)
const processId = (await context.observe()).processId
context.report.iris.manualHotloads = []
let active
try {
await context.step('Reject hotload without an open Studio', async () => {
await context.command('/iris studio hotload', /^No open studio projects\.$/, 10000)
})
await context.step('Open Studio and hotload an unchanged pack', async () => {
active = await openStudio(context, fixture)
await sampleTerrain(context, fixture, 0, fixture.state.material)
await hotload(context, fixture, active, '/iris studio hotload')
await sampleTerrain(context, fixture, 4096, fixture.state.material)
})
await context.step('Refresh an edited pack and inspect newly generated terrain', async () => {
const before = await readJson(fixture.manifestPath(active.key))
const biome = await readJson(biomeFile)
biome.name = 'Manual hotload terrain'
biome.layers[0].palette[0].block = 'minecraft:gold_block'
await writeJson(biomeFile, biome)
await hotload(context, fixture, active, '/iris studio refresh')
const after = await fixture.wait(async () => {
const manifest = await readJson(fixture.manifestPath(active.key))
return manifest.activeActivationId !== before.activeActivationId && manifest.pendingActivationId === null ? manifest : false
}, 'The edited Studio pack did not become active', 90000)
context.report.iris.activations.push({ before: before.activeActivationId,
after: after.activeActivationId, material: 'gold_block' })
await sampleTerrain(context, fixture, 16384, 'gold_block')
await sampleTerrain(context, fixture, 0, fixture.state.material)
})
await context.step('Close Studio and reject another refresh', async () => {
await closeStudio(context, fixture, active)
active = undefined
await context.command('/iris studio refresh', /^No open studio projects\.$/, 10000)
await context.command('/minecraft:seed', /Seed:/i, 10000)
})
context.expect((await context.observe()).processId === processId, 'The server restarted during manual Studio hotload')
const log = await logSince(fixture, logOffset)
context.expect(!/Studio generation update failed|Studio hotload failed|Unable to (capture terrain|save the terrain boundary)|ClosedChannelException|Chunk system error|server has stopped responding|could not acquire its engine runtime|Failed to list files/i.test(log),
'Manual Studio hotload emitted a generation, snapshot, storage, or watchdog failure')
} finally {
try {
if (active) await closeStudio(context, fixture, active)
} finally {
await writeFile(biomeFile, original)
}
}
}
}
@@ -148,13 +148,16 @@ public class FailedEnableLockTest {
try (EnableFixture fixture = new EnableFixture(false)) {
IllegalStateException failure = assertThrows(IllegalStateException.class, plugin::onEnable);
assertTrue(failure.getMessage(), failure.getMessage().contains("already bound"));
Field failed = IrisRuntime.class.getDeclaredField("enableFailed");
failed.setAccessible(true);
assertTrue(failed.getBoolean(plugin.runtime()));
}
}
@Test
public void anUnsupportedServerWithIrisWorldsLocksInsteadOfDisablingIris() throws Exception {
Iris plugin = plugin();
set(plugin, "pendingWorldReplacements", mock(PendingWorldReplacementManager.class));
set(IrisRuntime.class, plugin.runtime(), "pendingWorldReplacements", mock(PendingWorldReplacementManager.class));
try (EnableFixture fixture = new EnableFixture(true);
MockedStatic<INMS> nms = mockStatic(INMS.class);
@@ -205,18 +208,18 @@ public class FailedEnableLockTest {
/**
* Paper builds plugins through its class loader, so the plugin under test is the real class with its fields
* set by hand: the resolver getDefaultWorldGenerator delegates to, and whatever enable touches before failing.
* set by hand: the runtime getDefaultWorldGenerator delegates to, and whatever enable touches before failing.
*/
private static Iris plugin() throws Exception {
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
set(plugin, "generatorResolver", new IrisWorldGeneratorResolver(plugin));
set(Iris.class, plugin, "runtime", new IrisRuntime(plugin));
return plugin;
}
private static void set(Iris plugin, String name, Object value) throws Exception {
Field field = Iris.class.getDeclaredField(name);
private static void set(Class<?> owner, Object target, String name, Object value) throws Exception {
Field field = owner.getDeclaredField(name);
field.setAccessible(true);
field.set(plugin, value);
field.set(target, value);
}
/**
@@ -11,8 +11,8 @@ import static org.junit.Assert.assertTrue;
public class IrisApiServiceDiscoveryTest {
@Test
public void bothApiServicesSatisfyTheServiceLoaderRule() {
assertTrue(Iris.isConcreteImplementation(IrisTerrainSVC.class, IrisService.class));
assertTrue(Iris.isConcreteImplementation(IrisApiEventSVC.class, IrisService.class));
assertTrue(IrisRuntime.isConcreteImplementation(IrisTerrainSVC.class, IrisService.class));
assertTrue(IrisRuntime.isConcreteImplementation(IrisApiEventSVC.class, IrisService.class));
}
@Test
@@ -31,7 +31,7 @@ public class IrisBootstrapFailureContractTest {
when(context.getLogger()).thenReturn(logger);
when(context.getLifecycleManager()).thenReturn(manager);
IrisBootstrap.armStartupFailure(context, cause, eventType);
IrisBootstrapSequence.armStartupFailure(context, cause, eventType);
assertSame(eventType, manager.eventType);
IllegalStateException failure = assertThrows(IllegalStateException.class, manager::runCapturedHandler);
@@ -47,7 +47,7 @@ public class IrisBootstrapFailureContractTest {
IllegalStateException failure = new IllegalStateException("Iris world storage is unusable",
new IOException("Invalid generation manifest: manifest.json"));
IrisBootstrap.armStartupFailure(context, failure, lifecycleEventType());
IrisBootstrapSequence.armStartupFailure(context, failure, lifecycleEventType());
ArgumentCaptor<String> lines = ArgumentCaptor.forClass(String.class);
verify(logger, atLeastOnce()).error(lines.capture());
@@ -44,7 +44,7 @@ public class IrisBootstrapWorldStorageContractTest {
IllegalStateException failure = assertThrows(
IllegalStateException.class,
() -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)));
() -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)));
assertTrue(failure.getMessage(), failure.getMessage().contains("world_iris_orphan2"));
assertTrue(failure.getMessage(),
@@ -64,7 +64,7 @@ public class IrisBootstrapWorldStorageContractTest {
writeServerProperties(serverRoot);
writeBukkitWorlds(serverRoot, "world_iris_husk");
IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot));
IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot));
assertTrue(MissingWorldStorageLog.hasWarned("world_iris_husk"));
}
@@ -83,8 +83,8 @@ public class IrisBootstrapWorldStorageContractTest {
writeBukkitWorlds(serverRoot, "world_iris_husk");
List<String> warnings = new ArrayList<>();
IrisBootstrap.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot));
IrisBootstrapSequence.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot));
assertFalse(Files.exists(serverRoot.resolve("world/dimensions/iris/husk")));
assertEquals(1, warnings.size());
@@ -106,7 +106,7 @@ public class IrisBootstrapWorldStorageContractTest {
writeBukkitWorlds(serverRoot);
List<String> warnings = new ArrayList<>();
IrisBootstrap.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
IrisBootstrapSequence.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
assertFalse(Files.exists(serverRoot.resolve("world/dimensions/iris/husk")));
assertEquals(1, warnings.size());
@@ -121,13 +121,13 @@ public class IrisBootstrapWorldStorageContractTest {
writeBukkitWorlds(serverRoot, "world_iris_kept");
List<String> warnings = new ArrayList<>();
IrisBootstrap.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
IrisBootstrapSequence.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
assertTrue(Files.isDirectory(serverRoot.resolve("world/dimensions/iris/kept")));
assertTrue(warnings.isEmpty());
assertThrows(
IllegalStateException.class,
() -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)));
() -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)));
}
/**
@@ -142,13 +142,13 @@ public class IrisBootstrapWorldStorageContractTest {
writeBukkitWorlds(serverRoot, "world_iris_marked");
List<String> warnings = new ArrayList<>();
IrisBootstrap.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
IrisBootstrapSequence.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
assertTrue(Files.isDirectory(serverRoot.resolve("world/dimensions/iris/marked/iris/engine-data")));
assertTrue(warnings.isEmpty());
assertThrows(
IllegalStateException.class,
() -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)));
() -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)));
}
@Test
@@ -158,7 +158,7 @@ public class IrisBootstrapWorldStorageContractTest {
writeServerProperties(serverRoot);
writeBukkitWorlds(serverRoot, "world_iris_orphan1");
IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot));
IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot));
assertTrue(MissingWorldStorageLog.hasWarned("world_iris_orphan1"));
}
@@ -170,7 +170,7 @@ public class IrisBootstrapWorldStorageContractTest {
writeServerProperties(serverRoot);
writeBukkitWorlds(serverRoot, "world_iris_moon");
IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot));
IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot));
assertFalse(MissingWorldStorageLog.hasWarned("world_iris_moon"));
}
@@ -190,7 +190,7 @@ public class IrisBootstrapWorldStorageContractTest {
IllegalStateException failure = assertThrows(
IllegalStateException.class,
() -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)));
() -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)));
assertTrue(failure.getMessage(),
failure.getMessage().contains(serverRoot.toRealPath().resolve("world/dimensions/minecraft/overworld")
@@ -210,7 +210,7 @@ public class IrisBootstrapWorldStorageContractTest {
IllegalStateException failure = assertThrows(
IllegalStateException.class,
() -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)));
() -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)));
assertTrue(failure.getMessage(), failure.getMessage().contains("Invalid generation manifest"));
assertFalse(failure.getMessage(), failure.getMessage().contains("\n"));
@@ -229,7 +229,7 @@ public class IrisBootstrapWorldStorageContractTest {
IllegalStateException failure = assertThrows(
IllegalStateException.class,
() -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)));
() -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)));
assertTrue(failure.getMessage(), failure.getMessage().contains("worlds.world.generator"));
assertTrue(failure.getMessage(),
@@ -247,7 +247,7 @@ public class IrisBootstrapWorldStorageContractTest {
writeServerProperties(serverRoot);
writeBukkitWorlds(serverRoot);
IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot));
IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot));
}
private static BukkitStartupPaths startupPaths(Path serverRoot) throws Exception {
@@ -15,18 +15,18 @@ import static org.junit.Assert.assertNull;
public class IrisDiagnosticLogLevelTest {
@Test
public void coreDiagnosticsKeepTheirSeverity() {
assertEquals(Level.WARNING, Iris.diagnosticLevel(LogLevel.WARN));
assertEquals(Level.SEVERE, Iris.diagnosticLevel(LogLevel.ERROR));
assertEquals(Level.WARNING, IrisRuntime.diagnosticLevel(LogLevel.WARN));
assertEquals(Level.SEVERE, IrisRuntime.diagnosticLevel(LogLevel.ERROR));
}
@Test
public void informationalAndDebugMessagesStayOnTheInformationalPath() {
assertNull(Iris.diagnosticLevel(LogLevel.INFO));
assertNull(Iris.diagnosticLevel(LogLevel.DEBUG));
assertNull(IrisRuntime.diagnosticLevel(LogLevel.INFO));
assertNull(IrisRuntime.diagnosticLevel(LogLevel.DEBUG));
}
@Test
public void lifecycleNoticesReachThePluginLoggerAtInfo() {
assertEquals(Level.INFO, Iris.diagnosticLevel(LogLevel.NOTICE));
assertEquals(Level.INFO, IrisRuntime.diagnosticLevel(LogLevel.NOTICE));
}
}
@@ -23,8 +23,8 @@ public class IrisDiagnosticsTest {
public void serviceInitializationSkipsPackageHelperClasses() throws Exception {
Class<?> registrar = Class.forName("art.arcane.iris.command.PaperCommandRegistrar");
assertFalse(Iris.isConcreteImplementation(registrar, IrisService.class));
assertTrue(Iris.isConcreteImplementation(CommandSVC.class, IrisService.class));
assertFalse(IrisRuntime.isConcreteImplementation(registrar, IrisService.class));
assertTrue(IrisRuntime.isConcreteImplementation(CommandSVC.class, IrisService.class));
// The service package is eagerly Class.forName-scanned by JarScanner at enable; a class
// referencing Paper-only types there prints an NCDFE stack trace on plain Spigot.
assertFalse(
@@ -0,0 +1,75 @@
package art.arcane.iris;
import art.arcane.iris.configuration.IrisSettings;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.MockedStatic;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
public class IrisErrorReportingTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void debugReportingPreservesStacklessFailures() throws Exception {
ArrayIndexOutOfBoundsException failure = new ArrayIndexOutOfBoundsException("raster index");
failure.setStackTrace(new StackTraceElement[0]);
String output = reportWithDebug(failure);
assertEquals(1L, output.lines().filter(line -> line.contains("raster index")).count());
}
@Test
public void debugReportingPreservesFailureWithStacklessCause() throws Exception {
ArrayIndexOutOfBoundsException cause = new ArrayIndexOutOfBoundsException("raster index");
cause.setStackTrace(new StackTraceElement[0]);
IllegalStateException failure = new IllegalStateException("Hydrology failed", cause);
String output = reportWithDebug(failure);
assertEquals(1L, output.lines().filter(line -> line.contains("Hydrology failed")).count());
assertTrue(output.contains("Caused by: java.lang.ArrayIndexOutOfBoundsException: raster index"));
assertTrue(output.contains("IrisErrorReportingTest.debugReportingPreservesFailureWithStacklessCause"));
}
private String reportWithDebug(Throwable failure) throws Exception {
Iris previousPlugin = Iris.instance;
IrisSettings previousSettings = IrisSettings.settings;
PrintStream previousError = System.err;
Iris plugin = mock(Iris.class);
File report = new File(temporaryFolder.getRoot(), "failure.txt");
when(plugin.getDataFile(any(String[].class))).thenReturn(report);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (PrintStream errors = new PrintStream(output, true, StandardCharsets.UTF_8);
MockedStatic<Iris> iris = mockStatic(Iris.class)) {
Iris.instance = plugin;
IrisSettings.settings = new IrisSettings();
IrisSettings.settings.getGeneral().setDebug(true);
System.setErr(errors);
iris.when(() -> Iris.reportError(failure)).thenCallRealMethod();
Iris.reportError(failure);
assertTrue(Files.readString(report.toPath()).contains(failure.toString()));
return output.toString(StandardCharsets.UTF_8);
} finally {
System.setErr(previousError);
IrisSettings.settings = previousSettings;
Iris.instance = previousPlugin;
}
}
}
@@ -4,9 +4,13 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.junit.Assert.assertEquals;
@@ -31,4 +35,19 @@ public class IrisPluginLoaderTest {
assertEquals(List.of(relocatedCaffeine, relocatedGson), libraries);
}
@Test
public void readsMavenLibrariesFromTheSpigotDescriptorInThePluginJar() throws Exception {
Path jar = temporaryFolder.getRoot().toPath().resolve("Iris.jar");
try (OutputStream file = Files.newOutputStream(jar); ZipOutputStream zip = new ZipOutputStream(file)) {
zip.putNextEntry(new ZipEntry("plugin.yml"));
zip.write("name: Iris\nlibraries: [ 'org.lwjgl:lwjgl:3.4.3', 'org.lwjgl:lwjgl:jar:natives-linux:3.4.3' ]\n"
.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
List<String> libraries = IrisPluginLoader.mavenLibraries(jar);
assertEquals(List.of("org.lwjgl:lwjgl:3.4.3", "org.lwjgl:lwjgl:jar:natives-linux:3.4.3"), libraries);
}
}
@@ -1,7 +1,16 @@
package art.arcane.iris;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.concurrent.MultiBurst;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.platform.agent.Agent;
import art.arcane.iris.platform.bootstrap.SlimJar;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.platform.bukkit.plugin.IrisService;
import art.arcane.iris.platform.bukkit.plugin.VolmitPlugin;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.world.lifecycle.IrisRuntimeStatics;
import art.arcane.volmlib.util.collection.KMap;
import art.arcane.iris.generation.runtime.GenerationSessionLease;
import art.arcane.iris.generation.runtime.GenerationSessionManager;
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
@@ -17,6 +26,7 @@ import art.arcane.iris.world.WorldMaintenance;
import art.arcane.iris.world.runtime.BukkitEnginePlatformHooks;
import art.arcane.iris.world.task.J;
import art.arcane.volmlib.nativelib.terrain.ServerShutdownBoundary;
import art.arcane.volmlib.integration.ReloadAware;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.World;
@@ -26,10 +36,14 @@ import org.mockito.MockedStatic;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
@@ -37,10 +51,16 @@ import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -64,7 +84,7 @@ public class IrisShutdownMaintenanceTest {
assertTrue(release.await(5, TimeUnit.SECONDS));
return false;
});
setField(fixture.plugin, "serverShutdownBoundary", boundary);
setField(fixture.runtime, "serverShutdownBoundary", boundary);
fixture.quiesce();
fixture.startFinisher();
try {
@@ -88,9 +108,9 @@ public class IrisShutdownMaintenanceTest {
@Test
public void missingShutdownBoundaryDoesNotAuthorizeResourceRelease() throws Exception {
try (Fixture fixture = new Fixture()) {
Method method = Iris.class.getDeclaredMethod("awaitServerShutdownBoundary");
Method method = IrisRuntime.class.getDeclaredMethod("awaitServerShutdownBoundary");
method.setAccessible(true);
assertEquals(false, method.invoke(fixture.plugin));
assertEquals(false, method.invoke(fixture.runtime));
}
}
@@ -109,8 +129,6 @@ public class IrisShutdownMaintenanceTest {
}
verify(fixture.generator).quiesceForServerShutdown();
verify(fixture.generator, never()).closeAsync();
fixture.nms.verify(INMS::get);
verify(fixture.binding).deferPluginClassLoaderClose();
verify(fixture.binding, never()).releasePluginClassLoaderClose();
}
assertEquals(0, sessions.activeLeases());
@@ -151,14 +169,236 @@ public class IrisShutdownMaintenanceTest {
}
}
private static void setField(Iris plugin, String name, Object value) throws ReflectiveOperationException {
Field field = Iris.class.getDeclaredField(name);
@Test
public void startupEnsuresAgentReadinessBeforeLifecycleProtectionWithoutWorldInjection() throws Exception {
try (Fixture fixture = new Fixture(); MockedStatic<Agent> agent = mockStatic(Agent.class)) {
when(fixture.binding.supportsIrisWorldGeneration()).thenReturn(true);
agent.when(Agent::install).thenReturn(true);
doAnswer(invocation -> {
agent.verify(Agent::install);
assertSame(fixture.plugin.getClass().getClassLoader(), invocation.getArgument(0));
return null;
}).when(fixture.binding).initializeLifecycle(fixture.plugin.getClass().getClassLoader());
invoke(fixture.runtime, "initializeShutdownProtection");
verify(fixture.binding).initializeLifecycle(fixture.plugin.getClass().getClassLoader());
verify(fixture.binding, never()).injectBukkit();
}
}
@Test
public void unavailableAgentStopsLifecycleInitialization() throws Exception {
try (Fixture fixture = new Fixture(); MockedStatic<Agent> agent = mockStatic(Agent.class)) {
when(fixture.binding.supportsIrisWorldGeneration()).thenReturn(true);
InvocationTargetException failure = assertThrows(InvocationTargetException.class,
() -> invoke(fixture.runtime, "initializeShutdownProtection"));
assertTrue(failure.getCause() instanceof IllegalStateException);
verify(fixture.binding, never()).initializeLifecycle(fixture.plugin.getClass().getClassLoader());
}
}
@Test
public void worldHookTeardownFailureReleasesProtectionAfterServicesAndWorkersStop() throws Exception {
try (Fixture fixture = new Fixture();
MockedStatic<Iris> iris = mockStatic(Iris.class);
MockedStatic<IrisRuntimeStatics> statics = mockStatic(IrisRuntimeStatics.class);
MockedStatic<IrisPlatforms> platforms = mockStatic(IrisPlatforms.class);
MockedStatic<BukkitPlatform> bukkitPlatform = mockStatic(BukkitPlatform.class);
MockedStatic<SlimJar> providers = mockStatic(SlimJar.class)) {
IrisService service = mock(IrisService.class);
IllegalStateException failure = new IllegalStateException("world hook teardown failed");
fixture.nms.when(INMS::isBound).thenReturn(true);
doThrow(failure).when(fixture.binding).uninjectBukkit();
setField(fixture.runtime, "services", new KMap<Class<? extends IrisService>, IrisService>());
setField(fixture.runtime, "enabledServices", List.of(service));
doAnswer(invocation -> {
platforms.verify(IrisPlatforms::unbind);
bukkitPlatform.verify(BukkitPlatform::releaseHost);
assertTrue(MultiBurst.burst.isTerminated());
assertTrue(MultiBurst.hydrology.isTerminated());
assertTrue(MultiBurst.ioBurst.isTerminated());
return null;
}).when(fixture.binding).releasePluginClassLoaderClose();
fixture.quiesce();
try {
fixture.finish(5L);
fixture.finish(5L);
verify(service).onDisable();
iris.verify(() -> Iris.reportError("Failed to remove Iris world-generation hooks.", failure));
assertTrue(MultiBurst.burst.isTerminated());
assertTrue(MultiBurst.hydrology.isTerminated());
assertTrue(MultiBurst.ioBurst.isTerminated());
verify(fixture.binding).releasePluginClassLoaderClose();
platforms.verify(IrisPlatforms::unbind);
bukkitPlatform.verify(BukkitPlatform::releaseHost);
} finally {
MultiBurst.burst.reopen();
MultiBurst.hydrology.reopen();
MultiBurst.ioBurst.reopen();
}
}
}
@Test
public void failedServiceWithAnOwnedExecutorRetainsTheClassLoader() throws Exception {
ExecutorService ownedExecutor = Executors.newSingleThreadExecutor();
CountDownLatch started = new CountDownLatch(1);
CountDownLatch finish = new CountDownLatch(1);
ownedExecutor.submit(() -> {
started.countDown();
finish.await();
return null;
});
try (Fixture fixture = new Fixture();
MockedStatic<Iris> iris = mockStatic(Iris.class);
MockedStatic<IrisRuntimeStatics> statics = mockStatic(IrisRuntimeStatics.class);
MockedStatic<IrisPlatforms> platforms = mockStatic(IrisPlatforms.class);
MockedStatic<BukkitPlatform> bukkitPlatform = mockStatic(BukkitPlatform.class)) {
assertTrue(started.await(5, TimeUnit.SECONDS));
IrisService service = mock(IrisService.class);
IllegalStateException failure = new IllegalStateException("service teardown failed");
doThrow(failure).when(service).onDisable();
setField(fixture.runtime, "services", new KMap<Class<? extends IrisService>, IrisService>());
setField(fixture.runtime, "enabledServices", List.of(service));
fixture.quiesce();
fixture.finish(5L);
verify(service).onDisable();
iris.verify(() -> Iris.reportError("Failed to disable " + service.getClass().getSimpleName() + ".", failure));
assertFalse(ownedExecutor.isTerminated());
verify(fixture.binding, never()).releasePluginClassLoaderClose();
} finally {
finish.countDown();
ownedExecutor.shutdownNow();
assertTrue(ownedExecutor.awaitTermination(5, TimeUnit.SECONDS));
MultiBurst.burst.reopen();
MultiBurst.hydrology.reopen();
MultiBurst.ioBurst.reopen();
}
}
@Test
public void failedPostShutdownCallbackRetainsTheClassLoaderForSkippedCleanup() throws Exception {
ExecutorService ownedExecutor = Executors.newSingleThreadExecutor();
CountDownLatch started = new CountDownLatch(1);
CountDownLatch finish = new CountDownLatch(1);
ownedExecutor.submit(() -> {
started.countDown();
finish.await();
return null;
});
try (Fixture fixture = new Fixture();
MockedStatic<Iris> iris = mockStatic(Iris.class);
MockedStatic<IrisRuntimeStatics> statics = mockStatic(IrisRuntimeStatics.class);
MockedStatic<IrisPlatforms> platforms = mockStatic(IrisPlatforms.class);
MockedStatic<BukkitPlatform> bukkitPlatform = mockStatic(BukkitPlatform.class)) {
assertTrue(started.await(5, TimeUnit.SECONDS));
IllegalStateException failure = new IllegalStateException("post-shutdown callback failed");
AtomicBoolean cleanupAttempted = new AtomicBoolean();
List<Runnable> callbacks = new ArrayList<>();
callbacks.add(() -> { throw failure; });
callbacks.add(() -> {
cleanupAttempted.set(true);
ownedExecutor.shutdown();
});
Field callbacksField = VolmitPlugin.class.getDeclaredField("postShutdown");
callbacksField.setAccessible(true);
callbacksField.set(fixture.plugin, callbacks);
doCallRealMethod().when(fixture.plugin).runPostShutdown();
fixture.quiesce();
fixture.finish(5L);
iris.verify(() -> Iris.reportError("Failed to run Iris post-shutdown cleanup.", failure));
assertFalse(cleanupAttempted.get());
assertFalse(ownedExecutor.isShutdown());
assertFalse(ownedExecutor.isTerminated());
verify(fixture.binding, never()).releasePluginClassLoaderClose();
} finally {
finish.countDown();
ownedExecutor.shutdownNow();
assertTrue(ownedExecutor.awaitTermination(5, TimeUnit.SECONDS));
MultiBurst.burst.reopen();
MultiBurst.hydrology.reopen();
MultiBurst.ioBurst.reopen();
}
}
@Test
public void incompleteDrainRetainsServicesWorkersAndClassLoader() throws Exception {
try (Fixture fixture = new Fixture(); MockedStatic<Iris> iris = mockStatic(Iris.class)) {
IrisService service = mock(IrisService.class);
setField(fixture.runtime, "services", new KMap<Class<? extends IrisService>, IrisService>());
setField(fixture.runtime, "enabledServices", List.of(service));
when(fixture.generator.closeAsync()).thenReturn(new CompletableFuture<>());
fixture.quiesce();
fixture.finish(0L);
verify(service, never()).onDisable();
verify(fixture.binding, never()).releasePluginClassLoaderClose();
verify(fixture.binding, never()).uninjectBukkit();
}
}
@Test
public void serverStopPreUnloadDefersTeardownWhileTheClassLoaderIsHeld() throws Exception {
try (Fixture fixture = new Fixture()) {
setField(fixture.runtime, "postStopFinisherStarted", new AtomicBoolean(true));
try {
fixture.commitReloadDuringServerStop();
verify(fixture.binding).deferPluginClassLoaderClose();
verify(fixture.generator).quiesceForServerShutdown();
verify(fixture.generator, never()).closeAsync();
assertTrue(fixture.serverStopTeardownDeferred());
} finally {
WorldMaintenance.endWorldMaintenance(fixture.identity, "pre-unload:HOT_UNLOAD");
}
}
}
@Test
public void serverStopPreUnloadDrainsInlineWhenTheClassLoaderCannotBeHeld() throws Exception {
try (Fixture fixture = new Fixture(); MockedStatic<Iris> iris = mockStatic(Iris.class)) {
IllegalStateException failure = new IllegalStateException("class loader hold failed");
doThrow(failure).when(fixture.binding).deferPluginClassLoaderClose();
try {
fixture.commitReloadDuringServerStop();
verify(fixture.generator).closeAsync();
verify(fixture.generator, never()).quiesceForServerShutdown();
assertFalse(fixture.serverStopTeardownDeferred());
iris.verify(() -> Iris.reportError("Failed to retain the Iris plugin class loader; draining shutdown inline.", failure));
} finally {
WorldMaintenance.endWorldMaintenance(fixture.identity, "pre-unload:HOT_UNLOAD", true);
}
}
}
@Test
public void serverStopPreUnloadDrainsInlineWithoutInitializedProtection() throws Exception {
try (Fixture fixture = new Fixture()) {
setField(fixture.runtime, "shutdownProtectionInitialized", false);
try {
fixture.commitReloadDuringServerStop();
verify(fixture.binding, never()).deferPluginClassLoaderClose();
verify(fixture.generator).closeAsync();
verify(fixture.generator, never()).quiesceForServerShutdown();
assertFalse(fixture.serverStopTeardownDeferred());
} finally {
WorldMaintenance.endWorldMaintenance(fixture.identity, "pre-unload:HOT_UNLOAD", true);
}
}
}
private static void invoke(IrisRuntime runtime, String name) throws ReflectiveOperationException {
Method method = IrisRuntime.class.getDeclaredMethod(name);
method.setAccessible(true);
method.invoke(runtime);
}
private static void setField(IrisRuntime runtime, String name, Object value) throws ReflectiveOperationException {
Field field = IrisRuntime.class.getDeclaredField(name);
field.setAccessible(true);
field.set(plugin, value);
field.set(runtime, value);
}
private static final class Fixture implements AutoCloseable {
private final Iris plugin = mock(Iris.class);
private final IrisRuntime runtime = mock(IrisRuntime.class);
private final World world = mock(World.class);
private final IrisWorld irisWorld = mock(IrisWorld.class);
private final Engine engine = mock(Engine.class);
@@ -178,9 +418,16 @@ public class IrisShutdownMaintenanceTest {
private Fixture() throws ReflectiveOperationException {
IrisSettings.settings = new IrisSettings();
setField(plugin, "serverStopTeardownDeferred", new AtomicBoolean());
setField(plugin, "postStopFinisherStarted", new AtomicBoolean());
setField(plugin, "deferredShutdownGenerators", new CopyOnWriteArrayList<PlatformChunkGenerator>());
setField(runtime, "plugin", plugin);
setField(runtime, "shutdownProtectionInitialized", true);
setField(runtime, "alreadyDrained", new AtomicBoolean());
setField(runtime, "servicesDisabled", new AtomicBoolean());
setField(runtime, "runtimeTeardownFailed", new AtomicBoolean());
setField(runtime, "sharedRuntimeClosed", new AtomicBoolean());
setField(runtime, "terminalCleanupCompleted", new AtomicBoolean());
setField(runtime, "serverStopTeardownDeferred", new AtomicBoolean());
setField(runtime, "postStopFinisherStarted", new AtomicBoolean());
setField(runtime, "deferredShutdownGenerators", new CopyOnWriteArrayList<PlatformChunkGenerator>());
when(world.getKey()).thenReturn(NamespacedKey.fromString(identity));
when(engine.getWorld()).thenReturn(irisWorld);
when(irisWorld.hasPlatformWorld()).thenReturn(true);
@@ -194,22 +441,42 @@ public class IrisShutdownMaintenanceTest {
}
private void quiesce() throws ReflectiveOperationException {
Method method = Iris.class.getDeclaredMethod("quiesceRuntimeForServerShutdown", String.class);
Method method = IrisRuntime.class.getDeclaredMethod("quiesceRuntimeForServerShutdown", String.class);
method.setAccessible(true);
method.invoke(plugin, "server_stop");
method.invoke(runtime, "server_stop");
quiesces++;
}
private void drain() throws ReflectiveOperationException {
Method method = Iris.class.getDeclaredMethod("drainWorldGenerators", String.class, long.class);
Method method = IrisRuntime.class.getDeclaredMethod("drainWorldGenerators", String.class, long.class);
method.setAccessible(true);
method.invoke(plugin, "manual_disable", 5L);
method.invoke(runtime, "manual_disable", 5L);
}
private void commitReloadDuringServerStop() throws ReflectiveOperationException {
setField(runtime, "alreadyDrained", new AtomicBoolean());
toolbelt.when(IrisToolbelt::isServerStopping).thenReturn(true);
doCallRealMethod().when(runtime).commitReload(any());
runtime.commitReload(ReloadAware.PreUnloadReason.HOT_UNLOAD);
}
private boolean serverStopTeardownDeferred() throws ReflectiveOperationException {
Field field = IrisRuntime.class.getDeclaredField("serverStopTeardownDeferred");
field.setAccessible(true);
return ((AtomicBoolean) field.get(runtime)).get();
}
private void finish(long timeoutSeconds) throws ReflectiveOperationException {
Method method = IrisRuntime.class.getDeclaredMethod("finishDeferredRuntimeTeardown", String.class, long.class);
method.setAccessible(true);
method.invoke(runtime, "test_shutdown", timeoutSeconds);
}
private void startFinisher() throws ReflectiveOperationException {
Method method = Iris.class.getDeclaredMethod("startPostStopFinisher");
Method method = IrisRuntime.class.getDeclaredMethod("startPostStopFinisher");
method.setAccessible(true);
method.invoke(plugin);
method.invoke(runtime);
}
@Override
@@ -11,16 +11,13 @@ import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Answers.CALLS_REAL_METHODS;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
public class IrisVersionNumberTest {
@Test
public void releaseAndQualifiedBuildsUseTheSameVersionNumber() {
for (String version : List.of("4.3.3", "4.3.3-SNAPSHOT", "4.3.3-test")) {
assertEquals(version, 433, plugin(version).getIrisVersion());
assertEquals(version, 433, IrisRuntime.irisVersion(version));
}
}
@@ -29,10 +26,8 @@ public class IrisVersionNumberTest {
try (InputStream stream = getClass().getResourceAsStream("/plugin.yml")) {
assertNotNull(stream);
PluginDescriptionFile description = new PluginDescriptionFile(stream);
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
doReturn(description).when(plugin).getDescription();
assertNotEquals(-1, plugin.getIrisVersion());
assertNotEquals(-1, IrisRuntime.irisVersion(description.getVersion()));
}
}
@@ -40,28 +35,21 @@ public class IrisVersionNumberTest {
public void malformedAndOverflowingReleaseNumbersStayInvalid() {
for (String version : List.of("development", "4..3", ".4.3.3", "4.3.3.", "4.3a.3-test",
"2147483648", "999999999999999999999-SNAPSHOT", "-SNAPSHOT")) {
assertEquals(version, -1, plugin(version).getIrisVersion());
assertEquals(version, -1, IrisRuntime.irisVersion(version));
}
}
@Test
public void supportedMinecraftVersionsRetainTheirEngineNumbers() {
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
try (MockedStatic<Bukkit> bukkit = mockStatic(Bukkit.class)) {
bukkit.when(Bukkit::getVersion).thenReturn("26.1.2-74-ver/26.1.2@e4e17fc (MC: 26.1.2)");
assertEquals(2612, plugin.getMCVersion());
assertEquals(2612, IrisRuntime.minecraftVersion());
bukkit.when(Bukkit::getVersion).thenReturn("26.1.2-8-ver/26.1.x@62dc0f2 (MC: 26.1.2)");
assertEquals(2612, plugin.getMCVersion());
assertEquals(2612, IrisRuntime.minecraftVersion());
bukkit.when(Bukkit::getVersion).thenReturn("26.2-133 (MC: 26.2)");
assertEquals(262, plugin.getMCVersion());
assertEquals(262, IrisRuntime.minecraftVersion());
bukkit.when(Bukkit::getVersion).thenReturn("26.3-169 (MC: 26.3)");
assertEquals(263, plugin.getMCVersion());
assertEquals(263, IrisRuntime.minecraftVersion());
}
}
private static Iris plugin(String version) {
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
doReturn(new PluginDescriptionFile("Iris", version, Iris.class.getName())).when(plugin).getDescription();
return plugin;
}
}
@@ -139,7 +139,8 @@ public class IrisColumnSampleTest {
riverState,
riverDistance,
riverFlow,
riverWaterSurfaceY
riverWaterSurfaceY,
false
);
}
}
@@ -0,0 +1,104 @@
package art.arcane.iris.command;
import art.arcane.iris.command.handlers.DimensionHandler;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.WorldgenExportRequest;
import art.arcane.volmlib.util.director.annotations.Director;
import art.arcane.volmlib.util.director.annotations.Param;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
public class CommandDatapackExportContractTest {
private static final List<String> NAMES = List.of(
"dimension", "version", "mode", "namespace", "output", "format", "objects", "replace");
private static final List<String> DEFAULTS = List.of(
Param.NO_DEFAULT, "", "overworld", "iris_export", "", "zip", "true", "false");
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void exportParametersAreNamedInOrder() throws Exception {
List<String> names = new ArrayList<>();
for (Parameter parameter : exportMethod().getParameters()) {
names.add(parameter.getAnnotation(Param.class).name());
}
assertEquals(NAMES, names);
}
@Test
public void dimensionIsPositionalAndEveryOtherParameterIsKeyedWithItsDefault() throws Exception {
Parameter[] parameters = exportMethod().getParameters();
List<String> defaults = new ArrayList<>();
for (Parameter parameter : parameters) {
defaults.add(parameter.getAnnotation(Param.class).defaultValue());
}
assertEquals(DEFAULTS, defaults);
assertEquals(DimensionHandler.class, parameters[0].getAnnotation(Param.class).customHandler());
}
@Test
public void exportCommandAndParametersUseRegisteredDescriptions() throws Exception {
Method export = exportMethod();
Director director = export.getAnnotation(Director.class);
assertNotNull(director);
assertEquals(0L, Arrays.stream(director.aliases()).filter((String alias) -> !alias.isBlank()).count());
assertNotNull(director.descriptionKey(), IrisLanguage.catalog().key(director.descriptionKey()));
for (Parameter parameter : export.getParameters()) {
String key = parameter.getAnnotation(Param.class).descriptionKey();
assertNotNull(key, IrisLanguage.catalog().key(key));
}
}
@Test
public void validRequestResolvesItsTarget() {
assertSame(DataVersion.V26_3, CommandDatapack.validateExport(request().build()));
assertSame(DataVersion.V26_3, CommandDatapack.validateExport(request().version("26.3").build()));
}
@Test
public void unsupportedArgumentsAreRejectedWithSharedMessages() {
assertEquals("Unsupported datapack export version '1.21.1'. Supported: 26.3",
reason(request().version("1.21.1").build()));
assertEquals("Unsupported datapack export version '26.2'. Supported: 26.3",
reason(request().version("26.2").build()));
assertEquals("Unknown export mode 'nether'. Expected: preset, dimension, overworld",
reason(request().mode("nether").build()));
assertEquals("Export format must be directory or zip.", reason(request().format("rar").build()));
}
private WorldgenExportRequest.Builder request() {
Path root = temporaryFolder.getRoot().toPath();
return WorldgenExportRequest.builder()
.pack(root.resolve("packs").resolve("overworld"))
.dimension("overworld")
.exportRoot(root.resolve("exports"));
}
private static String reason(WorldgenExportRequest request) {
return assertThrows(IllegalArgumentException.class, () -> CommandDatapack.validateExport(request)).getMessage();
}
private static Method exportMethod() throws NoSuchMethodException {
return CommandDatapack.class.getDeclaredMethod("export", IrisDimension.class, String.class, String.class,
String.class, String.class, String.class, boolean.class, boolean.class);
}
}
@@ -1,6 +1,7 @@
package art.arcane.iris.command;
import art.arcane.iris.Iris;
import art.arcane.iris.IrisRuntime;
import art.arcane.iris.command.CommandSVC;
import art.arcane.iris.world.task.J;
import art.arcane.volmlib.util.diagnostics.BukkitDebugDump;
@@ -30,18 +31,18 @@ import static org.mockito.Mockito.when;
public class CommandDebugTest {
@Test
public void nestedDumpPreservesUploadDefaultAndLocalOnlyOption() {
Iris previousPlugin = Iris.instance;
Iris plugin = mock(Iris.class);
Iris.instance = plugin;
IrisRuntime runtime = mock(IrisRuntime.class);
BukkitDebugDump dump = mock(BukkitDebugDump.class);
CommandSender sender = mock(CommandSender.class);
DirectorSender invocationSender = mock(DirectorSender.class);
when(plugin.debugDump()).thenReturn(dump);
when(runtime.debugDump()).thenReturn(dump);
when(invocationSender.getName()).thenReturn("Console");
DirectorContextRegistry contexts = new DirectorContextRegistry();
contexts.register(CommandSender.class, (invocation, arguments) -> sender);
try (MockedStatic<Iris> iris = mockStatic(Iris.class)) {
try (MockedStatic<Iris> iris = mockStatic(Iris.class);
MockedStatic<IrisRuntime> runtimes = mockStatic(IrisRuntime.class)) {
runtimes.when(IrisRuntime::require).thenReturn(runtime);
DirectorRuntimeEngine engine = DirectorEngineFactory.create(new CommandIris(),
DirectorEngineOptions.builder().contexts(contexts).build());
@@ -52,8 +53,6 @@ public class CommandDebugTest {
assertEquals(List.of("dump", "toggle", "version"),
DirectorMiniMenu.resolveHelp(engine, List.of("debug")).orElseThrow().entries().stream()
.map(entry -> entry.getDescriptor().getName()).sorted().toList());
} finally {
Iris.instance = previousPlugin;
}
}
@@ -1,7 +1,11 @@
package art.arcane.iris.command;
import art.arcane.iris.Iris;
import art.arcane.iris.generation.hydrology.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.localization.IrisLanguage;
@@ -17,17 +21,21 @@ import org.bukkit.entity.Player;
import org.junit.Test;
import org.mockito.MockedStatic;
import java.time.Duration;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
@@ -45,7 +53,7 @@ public class CommandFindHydrologyTest {
@Test
public void worldChangeDuringSearchDoesNotLoadOrTeleportIntoTheNewWorld() {
try (Fixture fixture = new Fixture()) {
fixture.command.river("surface", true);
fixture.command.river("river", true);
when(fixture.player.getWorld()).thenReturn(mock(World.class));
fixture.search.get().run();
@@ -58,7 +66,7 @@ public class CommandFindHydrologyTest {
@Test
public void disconnectDuringSearchDoesNotLoadTheDestination() {
try (Fixture fixture = new Fixture()) {
fixture.command.river("surface", true);
fixture.command.river("river", true);
when(fixture.player.isOnline()).thenReturn(false);
fixture.search.get().run();
@@ -69,7 +77,7 @@ public class CommandFindHydrologyTest {
@Test
public void worldChangeWhileLoadingTheDestinationCancelsTeleport() {
try (Fixture fixture = new Fixture()) {
fixture.command.river("surface", true);
fixture.command.river("river", true);
fixture.search.get().run();
when(fixture.player.getWorld()).thenReturn(mock(World.class));
fixture.chunk.complete(mock(Chunk.class));
@@ -82,7 +90,7 @@ public class CommandFindHydrologyTest {
@Test
public void successIsReportedOnlyAfterTeleportCompletes() {
try (Fixture fixture = new Fixture()) {
fixture.command.river("surface", true);
fixture.command.river("river", true);
fixture.search.get().run();
fixture.chunk.complete(mock(Chunk.class));
@@ -95,7 +103,7 @@ public class CommandFindHydrologyTest {
@Test
public void rejectedTeleportReportsFailureWithoutSuccess() {
try (Fixture fixture = new Fixture()) {
fixture.command.river("surface", true);
fixture.command.river("river", true);
fixture.search.get().run();
fixture.chunk.complete(mock(Chunk.class));
fixture.teleport.complete(false);
@@ -109,7 +117,7 @@ public class CommandFindHydrologyTest {
public void failedTeleportReportsTheFullCauseWithoutSuccess() {
try (Fixture fixture = new Fixture()) {
IllegalStateException failure = new IllegalStateException("destination unloaded");
fixture.command.river("surface", true);
fixture.command.river("river", true);
fixture.search.get().run();
fixture.chunk.complete(mock(Chunk.class));
fixture.teleport.completeExceptionally(failure);
@@ -120,10 +128,138 @@ public class CommandFindHydrologyTest {
}
}
@Test
public void everyFeatureTypeIsSearchedOffTheCommandThreadAtTheRuntimeRadius() {
for (HydrologyFeatureType type : HydrologyFeatureType.values()) {
try (Fixture fixture = new Fixture()) {
fixture.command.river(type.key(), false);
fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(any(), any(), anyInt(), anyInt(), anyInt(), any()),
never());
fixture.search.get().run();
fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), eq(type), eq(0), eq(0),
eq(GenerationSemanticQueries.RIVER_SEARCH_DISTANCE), any()));
verify(fixture.sender).sendMessage(contains("Found " + type.key().replace('_', ' ') + " at 32, 63, 32."));
}
}
}
@Test
public void unknownTypeIsRejectedWithTheAcceptedTypesBeforeAnySearch() {
try (Fixture fixture = new Fixture()) {
fixture.command.river("surface", true);
verify(fixture.sender).sendMessage(contains("Use one of: stream, river, major_river, cascade, waterfall, mouth, pond, lake, dam, sea_inlet, cave_pool, grotto."));
assertNull(fixture.search.get());
}
}
@Test
public void aNewSearchSilentlyReplacesThePlayersRunningSearch() {
try (Fixture fixture = new Fixture()) {
fixture.command.river("pond", false);
Runnable replaced = fixture.search.get();
fixture.command.river("river", false);
replaced.run();
fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(any(), eq(HydrologyFeatureType.POND), anyInt(), anyInt(),
anyInt(), any()), never());
fixture.search.get().run();
verify(fixture.sender).sendMessage(contains("Found river at 32, 63, 32."));
verify(fixture.sender, never()).sendMessage(contains("Found pond"));
verify(fixture.sender, never()).sendMessage(contains("Could not search"));
}
}
@Test
public void disabledTypeIsReportedWithItsReason() throws Exception {
try (Fixture fixture = new Fixture()) {
fixture.searchForReal();
when(fixture.runtime.unavailable(HydrologyFeatureType.LAKE)).thenReturn(Optional.of("hydrology.lakes is disabled"));
fixture.command.river("lake", true);
fixture.search.get().run();
verify(fixture.sender).sendMessage(contains("No lake forms in this dimension: hydrology.lakes is disabled."));
verify(fixture.runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any());
}
}
@Test
public void stoppedSearchReportsTheNearestWaterWithoutTeleporting() throws Exception {
try (Fixture fixture = new Fixture()) {
fixture.searchForReal();
IrisDimension dimension = mock(IrisDimension.class);
when(fixture.engine.getDimension()).thenReturn(dimension);
when(dimension.getMinHeight()).thenReturn(-64);
when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenThrow(
new HydrologySearchTimeoutException(Duration.ofSeconds(30L), new HydrologyFeatureRef(1L, HydrologyFeatureType.RIVER, 32, 127, 32)));
fixture.command.river("river", true);
fixture.search.get().run();
verify(fixture.sender).sendMessage(contains("Stopped searching for the nearest river after 30 seconds. The nearest river found so "
+ "far is at 32, 63, 32; a nearer one may exist."));
fixture.platform.verify(() -> BukkitPlatform.chunkAtAsync(any(World.class), anyInt(), anyInt(), eq(true)), never());
fixture.platform.verify(() -> BukkitPlatform.teleportAsync(any(Player.class), any(Location.class)), never());
}
}
@Test
public void deliveryFailureIsReportedInsteadOfLost() {
try (Fixture fixture = new Fixture()) {
LinkageError failure = new LinkageError("sender gone");
doThrow(failure).when(fixture.sender).sendMessage(contains("Found river"));
fixture.command.river("river", false);
fixture.search.get().run();
fixture.logging.verify(() -> Iris.reportError(any(String.class), eq(failure)));
verify(fixture.sender).sendMessage(contains("Could not search for river: LinkageError - sender gone"));
}
}
@Test
public void missingCavePoolIsReportedAsNotFoundInGeneratedChunks() {
try (Fixture fixture = new Fixture()) {
fixture.searchForReal();
fixture.command.river("cave_pool", true);
fixture.search.get().run();
verify(fixture.sender).sendMessage(contains("Searching generated chunks for the nearest cave pool within 7168 blocks"));
verify(fixture.sender).sendMessage(contains("No cave pool found in generated chunks within 7168 blocks."));
}
}
@Test
public void missingFeatureIsReportedAsNotFound() {
try (Fixture fixture = new Fixture()) {
fixture.searchForReal();
fixture.command.river("sea_inlet", true);
fixture.search.get().run();
verify(fixture.sender).sendMessage(contains("No sea inlet found within 7168 blocks."));
fixture.platform.verify(() -> BukkitPlatform.chunkAtAsync(any(World.class), anyInt(), anyInt(), eq(true)), never());
}
}
@Test
public void plannerFailureIsReportedAsAnErrorNotAsNotFound() {
try (Fixture fixture = new Fixture()) {
IllegalStateException failure = new IllegalStateException("window planner exploded");
fixture.queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), any(), eq(0), eq(0), anyInt(), any()))
.thenThrow(failure);
fixture.command.river("lake", true);
fixture.search.get().run();
verify(fixture.sender).sendMessage(contains("Could not search for lake: IllegalStateException - window planner exploded"));
verify(fixture.sender, never()).sendMessage(contains("No lake found"));
fixture.logging.verify(() -> Iris.reportError(any(String.class), eq(failure)));
}
}
private static final class Fixture implements AutoCloseable {
private final CommandFind command = mock(CommandFind.class, CALLS_REAL_METHODS);
private final Engine engine = mock(Engine.class);
private final IrisComplex complex = mock(IrisComplex.class);
private final HydrologyRuntime runtime = mock(HydrologyRuntime.class);
private final Player player = mock(Player.class);
private final World world = mock(World.class);
private final VolmitSender sender = mock(VolmitSender.class);
@@ -132,7 +268,7 @@ public class CommandFindHydrologyTest {
private final CompletableFuture<Boolean> teleport = new CompletableFuture<>();
private final MockedStatic<J> scheduler = mockStatic(J.class);
private final MockedStatic<BukkitPlatform> platform = mockStatic(BukkitPlatform.class);
private final MockedStatic<GenerationSemanticQueries> queries = mockStatic(GenerationSemanticQueries.class);
private final MockedStatic<GenerationSemanticQueries> queries = mockStatic(GenerationSemanticQueries.class, CALLS_REAL_METHODS);
private final MockedStatic<IrisLanguage> language = mockStatic(IrisLanguage.class, invocation -> "teleported");
private final MockedStatic<Iris> logging = mockStatic(Iris.class);
@@ -141,6 +277,8 @@ public class CommandFindHydrologyTest {
doReturn(player).when(command).player();
doReturn(sender).when(command).sender();
when(engine.getComplex()).thenReturn(complex);
when(complex.getHydrologyRuntime()).thenReturn(runtime);
when(player.getUniqueId()).thenReturn(UUID.randomUUID());
when(player.getWorld()).thenReturn(world);
when(player.getLocation()).thenReturn(new Location(world, 0, 70, 0));
when(player.isOnline()).thenReturn(true);
@@ -161,9 +299,14 @@ public class CommandFindHydrologyTest {
platform.when(() -> BukkitPlatform.chunkAtAsync(any(World.class), anyInt(), anyInt(), eq(true))).thenReturn(chunk);
platform.when(() -> BukkitPlatform.teleportAsync(eq(player), any(Location.class))).thenReturn(teleport);
queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(engine), any(), eq(0), eq(0), anyInt(), any()))
.thenReturn(Optional.of(new GenerationSemanticQueries.RiverResult(
.thenReturn(new GenerationSemanticQueries.RiverSearch.Found(new GenerationSemanticQueries.RiverResult(
GenerationSemanticQueries.RiverSource.ACTIVE_PREDICTION,
HydrologyFeatureType.RIFFLE, Optional.empty(), 1L, 32, 63, 32, OptionalLong.empty())));
HydrologyFeatureType.RIVER, 1L, 32, 63, 32, OptionalLong.empty())));
}
private void searchForReal() {
queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(engine), any(), eq(0), eq(0), anyInt(), any()))
.thenCallRealMethod();
}
@Override
@@ -17,7 +17,6 @@ import art.arcane.iris.structure.authoring.StructureOwnershipManifest;
import art.arcane.iris.structure.authoring.StructureSource;
import art.arcane.iris.structure.authoring.StructureTransactionWriter;
import art.arcane.iris.structure.conversion.IrisStructureAdoptionInputKind;
import art.arcane.iris.structure.export.VanillaJigsawExportFormat;
import art.arcane.iris.world.IrisCreator;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.pack.value.IrisDirection;
@@ -413,24 +412,6 @@ public class CommandJigsawContractTest {
}
}
@Test
public void exportOutputIsOneSafeChildArtifact() {
Path root = Path.of("build", "jigsaw-exports").toAbsolutePath().normalize();
assertEquals(root.resolve("village.zip"), CommandJigsawExports.resolveExportDestination(
root, "village", VanillaJigsawExportFormat.ZIP));
assertEquals(root.resolve("village"), CommandJigsawExports.resolveExportDestination(
root, "village", VanillaJigsawExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class, () -> CommandJigsawExports.resolveExportDestination(
root, "", VanillaJigsawExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class, () -> CommandJigsawExports.resolveExportDestination(
root, ".", VanillaJigsawExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class, () -> CommandJigsawExports.resolveExportDestination(
root, "../all-exports", VanillaJigsawExportFormat.DIRECTORY));
assertThrows(IllegalArgumentException.class, () -> CommandJigsawExports.resolveExportDestination(
root, "nested/export", VanillaJigsawExportFormat.DIRECTORY));
}
@Test
public void exportLeaseRejectsDuplicatePlayerAndDestination() {
UUID firstPlayer = UUID.randomUUID();
@@ -20,26 +20,26 @@ import static org.mockito.Mockito.when;
public class CommandObjectFluidHeightTest {
@Test
public void absoluteObjectPlacementShiftsTheColumnRiverHeadFromNegativeMinY() {
public void absoluteObjectPlacementShiftsTheColumnWaterHeadFromNegativeMinY() {
World world = mock(World.class);
Engine engine = mock(Engine.class);
IrisDimension dimension = mock(IrisDimension.class);
IrisComplex complex = mock(IrisComplex.class);
@SuppressWarnings("unchecked")
ProceduralStream<Double> riverHead = mock(ProceduralStream.class);
ProceduralStream<Double> waterHead = mock(ProceduralStream.class);
Map<Block, BlockData> future = new HashMap<>();
when(engine.getMinHeight()).thenReturn(-64);
when(engine.getDimension()).thenReturn(dimension);
when(engine.getComplex()).thenReturn(complex);
when(dimension.getFluidHeight()).thenReturn(127);
when(complex.getRiverWaterSurfaceStream()).thenReturn(riverHead);
when(riverHead.get(12, -7)).thenReturn(131D);
when(complex.getWaterHeadStream()).thenReturn(waterHead);
when(waterHead.get(12, -7)).thenReturn(131D);
IObjectPlacer placer = CommandObject.createPlacer(world, future, engine);
assertEquals(63, placer.getFluidHeight());
assertEquals(67, placer.getFluidHeight(12, -7));
verify(riverHead).get(12, -7);
verify(waterHead).get(12, -7);
}
}
@@ -0,0 +1,112 @@
package art.arcane.iris.command;
import art.arcane.iris.Iris;
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
import art.arcane.iris.platform.generation.PlatformChunkGenerator;
import art.arcane.iris.studio.StudioSVC;
import art.arcane.iris.studio.workspace.IrisProject;
import art.arcane.volmlib.util.director.annotations.Director;
import art.arcane.volmlib.util.localization.LanguageAudience;
import org.junit.Test;
import org.mockito.MockedStatic;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.lang.reflect.Method;
import java.io.File;
import java.util.concurrent.CompletableFuture;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CommandStudioHotloadTest {
@Test
public void hotloadAndRefreshReportWhenNoStudioIsOpen() throws Exception {
RecordingSender sender = new RecordingSender();
StudioSVC studio = mock(StudioSVC.class);
Method hotload = CommandStudio.class.getDeclaredMethod("hotload");
assertTrue(List.of(hotload.getAnnotation(Director.class).aliases()).contains("refresh"));
try (MockedStatic<Iris> iris = mockStatic(Iris.class)) {
iris.when(() -> Iris.service(StudioSVC.class)).thenReturn(studio);
hotload.invoke(new TestCommand(sender));
assertTrue(sender.messages.getLast(), sender.messages.getLast().contains("No open studio"));
}
}
@Test
public void completionFeedbackWaitsForTheHotload() {
assertCompletionFeedback(null, "Studio hotloaded.");
}
@Test
public void failedHotloadReportsFailureAndLogsTheCause() {
assertCompletionFeedback(new IllegalStateException("Invalid pack"), "Studio hotload failed: Invalid pack");
}
private void assertCompletionFeedback(Throwable failure, String expected) {
RecordingSender sender = new RecordingSender();
StudioSVC studio = mock(StudioSVC.class);
PlatformChunkGenerator generator = mock(PlatformChunkGenerator.class);
IrisProject project = new IrisProject(new File("tutorial"));
project.setActiveProvider(generator);
CompletableFuture<Void> pending = new CompletableFuture<>();
UUID audience = UUID.randomUUID();
when(studio.getActiveProject()).thenReturn(project);
when(generator.hotloadAsync()).thenReturn(pending);
try (MockedStatic<Iris> iris = mockStatic(Iris.class)) {
iris.when(() -> Iris.service(StudioSVC.class)).thenReturn(studio);
LanguageAudience.run(audience, () -> new TestCommand(sender).hotload());
assertNull(LanguageAudience.current());
verify(generator).hotloadAsync();
assertEquals(1, sender.messages.size());
assertTrue(sender.messages.getFirst().contains("Hotloading Studio"));
if (failure == null) {
pending.complete(null);
} else {
pending.completeExceptionally(failure);
iris.verify(() -> Iris.reportError(failure));
}
assertEquals(2, sender.messages.size());
assertTrue(sender.messages.getLast(), sender.messages.getLast().contains(expected));
assertEquals(List.of(audience, audience), sender.audiences);
assertNull(LanguageAudience.current());
}
}
private static final class TestCommand extends CommandStudio {
private final VolmitSender sender;
private TestCommand(VolmitSender sender) {
this.sender = sender;
}
@Override
public VolmitSender sender() {
return sender;
}
}
private static final class RecordingSender extends VolmitSender {
private final List<String> messages = new ArrayList<>();
private final List<UUID> audiences = new ArrayList<>();
private RecordingSender() {
super(null);
}
@Override
public void sendMessage(String message) {
messages.add(message);
audiences.add(LanguageAudience.current());
}
}
}
@@ -0,0 +1,99 @@
package art.arcane.iris.command;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
import art.arcane.iris.platform.generation.PlatformChunkGenerator;
import art.arcane.iris.studio.map.MapWindow;
import art.arcane.iris.studio.map.PaletteExplorerStart;
import art.arcane.iris.studio.view.GuiHost;
import art.arcane.iris.world.IrisToolbelt;
import art.arcane.iris.world.task.J;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.junit.Test;
import org.mockito.MockedStatic;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
public class StudioMapPositionTest {
@Test
public void mapCapturesItsStartingPositionOnThePlayerScheduler() {
IrisSettings previous = IrisSettings.settings;
IrisSettings.settings = new IrisSettings();
IrisSettings.settings.getGui().setUseServerLaunchedGuis(true);
World world = mock(World.class);
Player player = mock(Player.class);
VolmitSender sender = mock(VolmitSender.class);
PlatformChunkGenerator generator = mock(PlatformChunkGenerator.class);
Engine engine = mock(Engine.class);
UUID playerId = UUID.randomUUID();
UUID worldId = UUID.randomUUID();
AtomicBoolean owned = new AtomicBoolean();
AtomicReference<Runnable> task = new AtomicReference<>();
AtomicReference<PaletteExplorerStart> start = new AtomicReference<>();
when(world.getUID()).thenReturn(worldId);
when(player.getUniqueId()).thenReturn(playerId);
when(player.isOnline()).thenReturn(true);
when(player.getWorld()).thenAnswer(invocation -> {
assertTrue("world read must use the player scheduler", owned.get());
return world;
});
when(player.getLocation()).thenAnswer(invocation -> {
assertTrue("location read must use the player scheduler", owned.get());
return new Location(world, 33.25D, 91D, -72.5D);
});
when(sender.isPlayer()).thenReturn(true);
when(sender.player()).thenReturn(player);
when(generator.getEngine()).thenReturn(engine);
CommandStudio command = new CommandStudio() {
@Override
public VolmitSender sender() {
return sender;
}
};
try (MockedStatic<GuiHost> host = mockStatic(GuiHost.class);
MockedStatic<IrisToolbelt> toolbelt = mockStatic(IrisToolbelt.class);
MockedStatic<J> scheduling = mockStatic(J.class);
MockedStatic<MapWindow> windows = mockStatic(MapWindow.class)) {
host.when(GuiHost::isAvailable).thenReturn(true);
toolbelt.when(() -> IrisToolbelt.isIrisWorld(world)).thenReturn(true);
toolbelt.when(() -> IrisToolbelt.access(world)).thenReturn(generator);
scheduling.when(() -> J.runEntity(same(player), any(Runnable.class), eq(0), any(Runnable.class)))
.thenAnswer(invocation -> {
task.set(invocation.getArgument(1));
return true;
});
windows.when(() -> MapWindow.openMap(any(PaletteExplorerStart.class))).thenAnswer(invocation -> {
start.set(invocation.getArgument(0));
return null;
});
command.map(world);
assertNull(start.get());
owned.set(true);
task.get().run();
assertEquals(engine, start.get().engine());
assertEquals(playerId, start.get().playerId());
assertEquals(worldId, start.get().worldId());
assertEquals(33.25D, start.get().centerX(), 0D);
assertEquals(-72.5D, start.get().centerZ(), 0D);
} finally {
IrisSettings.settings = previous;
}
}
}
@@ -1,6 +1,7 @@
package art.arcane.iris.integration;
import art.arcane.iris.Iris;
import art.arcane.iris.IrisRuntime;
import art.arcane.volmlib.util.bukkit.papi.PlaceholderRegistration;
import org.bukkit.Bukkit;
import org.bukkit.event.HandlerList;
@@ -89,12 +90,21 @@ public class IrisPapiLifecycleTest {
when(iris.getLogger()).thenReturn(Logger.getAnonymousLogger());
doCallRealMethod().when(iris).onPlaceholderApiEnable(any());
doCallRealMethod().when(iris).onPlaceholderApiDisable(any());
Field lifecycle = Iris.class.getDeclaredField("papiLifecycleActive");
lifecycle.setAccessible(true);
lifecycle.setBoolean(iris, active);
IrisRuntime runtime = mock(IrisRuntime.class);
doCallRealMethod().when(runtime).onPlaceholderApiEnable(any());
doCallRealMethod().when(runtime).onPlaceholderApiDisable(any());
set(IrisRuntime.class, runtime, "plugin", iris);
set(IrisRuntime.class, runtime, "papiLifecycleActive", active);
set(Iris.class, iris, "runtime", runtime);
return iris;
}
private static void set(Class<?> owner, Object target, String name, Object value) throws ReflectiveOperationException {
Field field = owner.getDeclaredField(name);
field.setAccessible(true);
field.set(target, value);
}
private static Plugin namedPlugin(String name) {
Plugin plugin = mock(Plugin.class);
when(plugin.getName()).thenReturn(name);
@@ -0,0 +1,63 @@
package art.arcane.iris.platform.agent;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
public class AttachSignalTest {
private static final int SIGQUIT = 3;
private static final int SIGTERM = 15;
private static final long ACTION_BYTES = 256;
private static MethodHandle sigaction;
@BeforeClass
public static void linkSigaction() {
assumeFalse(System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win"));
sigaction = Linker.nativeLinker().downcallHandle(
Linker.nativeLinker().defaultLookup().find("sigaction").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
}
@Test
public void aConsoleThatResetsQuitGetsTheJvmHandlerBack() throws Throwable {
long jvmHandler = handler(SIGTERM);
assertNotEquals(0L, jvmHandler);
try (Arena arena = Arena.ofConfined()) {
MemorySegment original = arena.allocate(ACTION_BYTES);
assertEquals(0, (int) sigaction.invokeExact(SIGQUIT, MemorySegment.NULL, original));
try {
MemorySegment reset = arena.allocate(ACTION_BYTES);
assertEquals(0, (int) sigaction.invokeExact(SIGQUIT, reset, MemorySegment.NULL));
assertEquals(0L, handler(SIGQUIT));
assertTrue(AttachSignal.restoreJvmHandler());
assertEquals(jvmHandler, handler(SIGQUIT));
assertFalse(AttachSignal.restoreJvmHandler());
} finally {
assertEquals(0, (int) sigaction.invokeExact(SIGQUIT, original, MemorySegment.NULL));
}
}
}
private static long handler(int signal) throws Throwable {
try (Arena arena = Arena.ofConfined()) {
MemorySegment action = arena.allocate(ACTION_BYTES);
assertEquals(0, (int) sigaction.invokeExact(signal, MemorySegment.NULL, action));
return action.get(ValueLayout.JAVA_LONG, 0);
}
}
}
@@ -9,33 +9,40 @@ import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.runtime.BiomeEnvironment;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.stream.ProvisionalSampling;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.platform.generation.PlatformChunkGenerator;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.world.history.SavedBiomeUnavailableException;
import art.arcane.iris.generation.hydrology.HydrologyColumnLayer;
import art.arcane.iris.generation.hydrology.HydrologyColumnSample;
import art.arcane.iris.generation.hydrology.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.HydrologyFeatureType;
import art.arcane.volmlib.util.stream.ProceduralStream;
import art.arcane.volmlib.util.stream.interpolation.Interpolated;
import art.arcane.iris.api.terrain.IrisColumnSample;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.platform.bukkit.plugin.IrisService;
import org.bukkit.World;
import org.bukkit.generator.ChunkGenerator;
import org.junit.Test;
import org.mockito.MockedStatic;
import org.mockito.stubbing.Answer;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.IntPredicate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
@@ -112,10 +119,116 @@ public class IrisTerrainSVCTest {
}
@Test
public void acceptedHydrologyMapsToThePublicDiagnosticStates() {
assertEquals(IrisRiverState.NONE, IrisTerrainSVC.riverState(null));
assertEquals(IrisRiverState.WET, IrisTerrainSVC.riverState(river(true)));
assertEquals(IrisRiverState.DRY, IrisTerrainSVC.riverState(river(false)));
public void waterRolesMapToThePublicRiverFields() {
for (WaterRole role : WaterRole.values()) {
assertEquals(role.name(), role.wet() ? IrisRiverState.WET : IrisRiverState.NONE, IrisTerrainSVC.riverState(role));
double distance = switch (role) {
case NONE -> IrisColumnSample.UNAVAILABLE_RIVER_DISTANCE;
case CHANNEL, POND, MOUTH, CASCADE, WATERFALL, INLET -> 0D;
case SHORE, POND_SHORE -> 1D;
case BANK, DAM -> 2D;
};
assertEquals(role.name(), distance, IrisTerrainSVC.riverDistance(role), 0D);
int flow = switch (role) {
case NONE, SHORE, POND_SHORE, BANK, DAM -> IrisColumnSample.UNAVAILABLE_RIVER_FLOW;
case CHANNEL, MOUTH, CASCADE, WATERFALL -> 1;
case POND, INLET -> 0;
};
assertEquals(role.name(), flow, IrisTerrainSVC.riverFlow(role));
}
}
@Test
public void columnSamplesReportTheWaterRoleOfEachColumn() throws Exception {
assertEquals(List.of("RIVER", "WET", "0.0", "1", "6"), sampled(WaterRole.CHANNEL, 70));
assertEquals(List.of("RIVER", "WET", "0.0", "0", "6"), sampled(WaterRole.POND, 70));
assertEquals(List.of("RIVER_SHORE", "NONE", "1.0", "-1", "unavailable"), sampled(WaterRole.SHORE, 50));
assertEquals(List.of("LAND", "NONE", "2.0", "-1", "unavailable"), sampled(WaterRole.BANK, 50));
assertEquals(List.of("LAND", "NONE", "NaN", "-1", "unavailable"), sampled(WaterRole.NONE, 50));
}
@Test
public void serverThreadUnplannedColumnsAreProvisional() throws Exception {
List<IrisColumnSample> samples = sampledRow(blockX -> blockX < 16, () -> {
});
assertEquals(32, samples.size());
for (IrisColumnSample sample : samples) {
assertEquals("column " + sample.blockX(), sample.blockX() < 16, sample.provisional());
}
}
@Test
public void plannedColumnsAreFinal() throws Exception {
ProvisionalSampling.mark();
List<IrisColumnSample> samples = sampledRow(blockX -> false, () -> {
});
assertEquals(32, samples.size());
for (IrisColumnSample sample : samples) {
assertFalse("column " + sample.blockX(), sample.provisional());
}
}
@Test
public void aSinkThatReadsProvisionallyDoesNotMarkLaterColumns() throws Exception {
List<IrisColumnSample> samples = sampledRow(blockX -> false, ProvisionalSampling::mark);
assertEquals(32, samples.size());
for (IrisColumnSample sample : samples) {
assertFalse("column " + sample.blockX(), sample.provisional());
}
}
@Test
public void surfaceHeightIsUnavailableUntilTheColumnIsPlanned() throws Exception {
World world = world(engine(blockX -> blockX >= 16));
IrisTerrainSVC service = enabledService();
assertEquals(OptionalInt.empty(), service.surfaceHeight(world, 16, 0));
assertEquals(OptionalInt.of(-4), service.surfaceHeight(world, 0, 0));
}
@Test
public void surfaceKindIsUnknownUntilTheColumnIsPlanned() throws Exception {
World world = world(engine(blockX -> blockX >= 16));
IrisTerrainSVC service = enabledService();
assertEquals(IrisSurfaceKind.UNKNOWN, service.surfaceKind(world, 16, 0));
assertEquals(IrisSurfaceKind.LAND, service.surfaceKind(world, 0, 0));
}
@Test
public void surfaceBiomeReadsAreEmptyUntilTheColumnIsPlanned() throws Exception {
World world = world(engine(blockX -> blockX >= 16));
IrisTerrainSVC service = enabledService();
assertTrue(service.surfaceBiomeKey(world, 16, 0).isEmpty());
assertTrue(service.surfaceBiomeName(world, 16, 0).isEmpty());
assertTrue(service.surfaceBiomeInfo(world, 16, 0).isEmpty());
assertEquals(Optional.of("plains"), service.surfaceBiomeKey(world, 0, 0));
assertEquals(Optional.of("Plains"), service.surfaceBiomeName(world, 0, 0));
assertEquals("plains", service.surfaceBiomeInfo(world, 0, 0).orElseThrow().key());
}
@Test
public void biomeKeyIsEmptyUntilTheColumnIsPlanned() throws Exception {
World world = world(engine(blockX -> blockX >= 16));
IrisTerrainSVC service = enabledService();
assertTrue(service.biomeKey(world, 16, 64, 0).isEmpty());
assertEquals(Optional.of("plains"), service.biomeKey(world, 0, 64, 0));
}
@Test
public void regionReadsAreEmptyUntilTheColumnIsPlanned() throws Exception {
World world = world(engine(blockX -> blockX >= 16));
IrisTerrainSVC service = enabledService();
assertTrue(service.regionKey(world, 16, 0).isEmpty());
assertTrue(service.regionName(world, 16, 0).isEmpty());
assertEquals(Optional.of("temperate"), service.regionKey(world, 0, 0));
assertEquals(Optional.of("Temperate"), service.regionName(world, 0, 0));
}
@Test
@@ -219,6 +332,91 @@ public class IrisTerrainSVCTest {
}
}
private static List<String> sampled(WaterRole role, int head) throws Exception {
Engine engine = mock(Engine.class);
IrisComplex complex = mock(IrisComplex.class);
IrisBiome biome = mock(IrisBiome.class);
when(biome.getInferredType()).thenReturn(InferredType.LAND);
when(engine.getComplex()).thenReturn(complex);
when(engine.getDimension()).thenReturn(mock(IrisDimension.class));
when(engine.getHeight(0, 0)).thenReturn(60);
when(engine.getMinHeight()).thenReturn(-64);
when(engine.getSurfaceBiome(0, 0)).thenReturn(biome);
when(complex.getWaterRoleStream()).thenReturn(ProceduralStream.of((x, z) -> role, Interpolated.of(value -> 0D, value -> role)));
when(complex.getWaterHeadStream()).thenReturn(ProceduralStream.ofDouble((x, z) -> (double) head));
IrisColumnQuery query = IrisColumnQuery.rect(0, 0, 0, 0, 1, EnumSet.of(IrisColumnField.SURFACE_KIND,
IrisColumnField.RIVER_STATE, IrisColumnField.RIVER_DISTANCE, IrisColumnField.RIVER_FLOW,
IrisColumnField.RIVER_WATER_SURFACE_Y));
List<IrisColumnSample> samples = new ArrayList<>();
try (MockedStatic<IrisSettings> settings = mockStatic(IrisSettings.class)) {
settings.when(IrisSettings::get).thenReturn(new IrisSettings());
assertTrue(enabledService().sampleColumns(world(engine), query, samples::add));
}
assertEquals(1, samples.size());
IrisColumnSample sample = samples.get(0);
return List.of(sample.surfaceKind().name(), sample.riverState().name(), String.valueOf(sample.riverDistance()),
String.valueOf(sample.riverFlow()),
sample.riverWaterSurfaceY() == IrisColumnSample.UNAVAILABLE_HEIGHT ? "unavailable" : String.valueOf(sample.riverWaterSurfaceY()));
}
private static List<IrisColumnSample> sampledRow(IntPredicate unplanned, Runnable afterAccept) throws Exception {
Engine engine = engine(unplanned);
IrisColumnQuery query = IrisColumnQuery.rect(0, 0, 31, 0, 1, EnumSet.of(IrisColumnField.SURFACE_HEIGHT,
IrisColumnField.SURFACE_KIND, IrisColumnField.BIOME_KEY, IrisColumnField.RIVER_STATE));
List<IrisColumnSample> samples = new ArrayList<>();
try (MockedStatic<IrisSettings> settings = mockStatic(IrisSettings.class)) {
settings.when(IrisSettings::get).thenReturn(new IrisSettings());
assertTrue(enabledService().sampleColumns(world(engine), query, sample -> {
samples.add(sample);
afterAccept.run();
}));
}
return samples;
}
private static Engine engine(IntPredicate unplanned) {
Engine engine = mock(Engine.class);
IrisComplex complex = mock(IrisComplex.class);
IrisBiome biome = mock(IrisBiome.class);
IrisRegion region = mock(IrisRegion.class);
when(biome.getInferredType()).thenReturn(InferredType.LAND);
when(biome.getLoadKey()).thenReturn("plains");
when(biome.getName()).thenReturn("Plains");
when(region.getLoadKey()).thenReturn("temperate");
when(region.getName()).thenReturn("Temperate");
BiomeEnvironment environment = new BiomeEnvironment(1L, biome, region, mock(IrisDimension.class), mock(IrisData.class));
when(engine.getComplex()).thenReturn(complex);
when(engine.getDimension()).thenReturn(mock(IrisDimension.class));
when(engine.getMinHeight()).thenReturn(-64);
when(engine.getHeight(anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, 60));
when(engine.getSurfaceBiome(anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, biome));
when(engine.getSurfaceBiomeEnvironment(anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, environment));
when(engine.getBiome(anyInt(), anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, biome));
when(engine.getRegion(anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, region));
when(complex.getWaterRoleStream()).thenReturn(ProceduralStream.of((Double x, Double z) -> {
serverThreadRead(unplanned, x.intValue());
return WaterRole.NONE;
}, Interpolated.of(value -> 0D, value -> WaterRole.NONE)));
when(complex.getWaterHeadStream()).thenReturn(ProceduralStream.ofDouble((double x, double z) -> {
serverThreadRead(unplanned, (int) x);
return 50D;
}));
return engine;
}
private static <T> Answer<T> serverThreadAnswer(IntPredicate unplanned, T value) {
return invocation -> {
serverThreadRead(unplanned, (int) invocation.getArgument(0));
return value;
};
}
private static void serverThreadRead(IntPredicate unplanned, int blockX) {
if (unplanned.test(blockX)) {
ProvisionalSampling.mark();
}
}
private static World world(Engine engine) {
World world = mock(World.class);
ChunkGenerator generator = mock(ChunkGenerator.class, withSettings().extraInterfaces(PlatformChunkGenerator.class));
@@ -235,41 +433,4 @@ public class IrisTerrainSVCTest {
((AtomicBoolean) enabled.get(service)).set(true);
return service;
}
private static HydrologyColumnSample river(boolean connectedFluid) {
HydrologyFeatureRef feature = new HydrologyFeatureRef(
1L,
HydrologyFeatureType.SURFACE_POOL,
2L,
3L,
0,
63,
0,
1,
0,
false
);
HydrologyColumnLayer layer = new HydrologyColumnLayer(
feature,
60,
63,
63,
true,
false,
false,
connectedFluid,
false,
false,
true,
connectedFluid,
false,
"water",
"river",
"mouth",
"shore",
"dry",
"cave"
);
return new HydrologyColumnSample(0, 0, 70, 63, false, "parent", List.of(layer));
}
}
@@ -1,15 +1,10 @@
package art.arcane.iris.platform.bukkit.terrain;
import art.arcane.iris.api.terrain.IrisSurfaceKind;
import art.arcane.iris.generation.hydrology.HydrologyColumnLayer;
import art.arcane.iris.generation.hydrology.HydrologyColumnSample;
import art.arcane.iris.generation.hydrology.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.terrain.InferredType;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -69,98 +64,28 @@ public class IrisSurfaceClassifierTest {
}
@Test
public void acceptedSurfaceRolesOverrideGenericOceanAndLandKinds() {
assertEquals(IrisSurfaceKind.RIVER, IrisSurfaceClassifier.classify(
60,
63,
InferredType.SEA,
hydrology(HydrologyFeatureType.SURFACE_POOL, true, false, true)
));
assertEquals(IrisSurfaceKind.RIVER, IrisSurfaceClassifier.classify(
60,
63,
InferredType.SEA,
hydrology(HydrologyFeatureType.MOUTH, true, false, true)
));
assertEquals(IrisSurfaceKind.RIVER_SHORE, IrisSurfaceClassifier.classify(
64,
63,
InferredType.SHORE,
hydrology(HydrologyFeatureType.SURFACE_POOL, false, true, false)
));
assertEquals(IrisSurfaceKind.DRY_CHANNEL, IrisSurfaceClassifier.classify(
60,
60,
InferredType.LAND,
hydrology(HydrologyFeatureType.SURFACE_POOL, true, false, false)
));
assertEquals(IrisSurfaceKind.LAND, IrisSurfaceClassifier.classify(
60,
60,
InferredType.LAND,
hydrology(HydrologyFeatureType.SURFACE_POOL, false, false, false)
));
public void waterRolesOverrideGenericOceanAndLandKinds() {
for (WaterRole role : WaterRole.values()) {
IrisSurfaceKind expected = switch (role) {
case NONE -> IrisSurfaceKind.OCEAN;
case SHORE, POND_SHORE -> IrisSurfaceKind.RIVER_SHORE;
case BANK, DAM -> IrisSurfaceKind.LAND;
case CHANNEL, POND, MOUTH, CASCADE, WATERFALL, INLET -> IrisSurfaceKind.RIVER;
};
assertEquals(role.name(), expected, IrisSurfaceClassifier.classify(60, 63, InferredType.SEA, role));
}
}
@Test
public void voidClassificationWinsOverAcceptedRiverGeometry() {
assertEquals(IrisSurfaceKind.VOID, IrisSurfaceClassifier.classify(
0,
63,
InferredType.LAND,
hydrology(HydrologyFeatureType.SURFACE_POOL, true, false, true)
));
public void voidClassificationWinsOverWaterRoles() {
for (WaterRole role : WaterRole.values()) {
assertEquals(role.name(), IrisSurfaceKind.VOID, IrisSurfaceClassifier.classify(0, 63, InferredType.LAND, role));
}
}
@Test
public void absentRejectedCandidatesDoNotCreatePublicRiverKinds() {
assertEquals(IrisSurfaceKind.LAND, IrisSurfaceClassifier.classify(
64,
63,
InferredType.LAND,
null
));
}
private static HydrologyColumnSample hydrology(
HydrologyFeatureType type,
boolean channel,
boolean shore,
boolean connectedFluid
) {
HydrologyFeatureRef feature = new HydrologyFeatureRef(
1L,
type,
2L,
3L,
0,
63,
0,
1,
0,
false
);
HydrologyColumnLayer layer = new HydrologyColumnLayer(
feature,
60,
63,
63,
channel,
shore,
!channel && !shore,
connectedFluid,
false,
false,
true,
connectedFluid && channel,
false,
"water",
"river",
"mouth",
"shore",
"dry",
"cave"
);
return new HydrologyColumnSample(0, 0, 70, 63, false, "parent", List.of(layer));
public void columnsWithoutAWaterRoleKeepTheGenericKinds() {
assertEquals(IrisSurfaceKind.LAND, IrisSurfaceClassifier.classify(64, 63, InferredType.LAND, WaterRole.NONE));
assertEquals(IrisSurfaceKind.SHORE, IrisSurfaceClassifier.classify(64, 63, InferredType.SHORE, WaterRole.NONE));
}
}
@@ -0,0 +1,165 @@
package art.arcane.iris.studio.view;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
import art.arcane.iris.world.IrisWorld;
import art.arcane.iris.world.task.J;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.junit.Test;
import org.mockito.MockedStatic;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
public class BukkitOpenerPositionTest {
@Test
public void playerMarkersAreCapturedOnTheirEntitySchedulers() {
try (Harness harness = new Harness()) {
harness.binding.when(() -> BukkitWorldBinding.players(harness.target)).thenReturn(List.of(harness.player));
when(harness.player.getName()).thenReturn("Explorer");
assertTrue(harness.overlay.players().isEmpty());
harness.runEntity();
List<GuiMarker> markers = harness.overlay.players();
assertEquals(1, markers.size());
assertEquals("Explorer", markers.getFirst().label());
assertEquals(18.5D, markers.getFirst().worldX(), 0D);
assertEquals(-4.25D, markers.getFirst().worldZ(), 0D);
}
}
@Test
public void positionIsCapturedOnlyOnTheOwningEntityTask() {
try (Harness harness = new Harness()) {
harness.overlay.requestOpenerPosition(harness.results::add);
assertTrue(harness.results.isEmpty());
harness.runEntity();
assertEquals(List.of(OpenerPosition.inWorld(18.5D, 72D, -4.25D)), harness.results);
}
}
@Test
public void retiredEntityCompletesTheRequestOnce() {
try (Harness harness = new Harness()) {
harness.overlay.requestOpenerPosition(harness.results::add);
assertTrue("retirement callback must be registered", harness.retired != null);
harness.retired.run();
harness.retired.run();
assertEquals(List.of(OpenerPosition.OFFLINE), harness.results);
}
}
@Test
public void disconnectBeforeCaptureCompletesAsOfflineAndReconnectCanRefresh() {
try (Harness harness = new Harness()) {
harness.overlay.requestOpenerPosition(harness.results::add);
when(harness.player.isOnline()).thenReturn(false);
harness.runEntity();
assertEquals(List.of(OpenerPosition.OFFLINE), harness.results);
when(harness.player.isOnline()).thenReturn(true);
harness.overlay.requestOpenerPosition(harness.results::add);
harness.runEntity();
assertEquals(List.of(OpenerPosition.OFFLINE, OpenerPosition.inWorld(18.5D, 72D, -4.25D)), harness.results);
}
}
@Test
public void rejectedEntityTaskCompletesOnceEvenIfRetirementAlreadyRan() {
try (Harness harness = new Harness()) {
harness.reject = true;
harness.overlay.requestOpenerPosition(harness.results::add);
assertEquals(List.of(OpenerPosition.OFFLINE), harness.results);
}
}
@Test
public void changingWorldBeforeCaptureReportsOtherWorld() {
try (Harness harness = new Harness()) {
harness.overlay.requestOpenerPosition(harness.results::add);
when(harness.player.getWorld()).thenReturn(mock(World.class));
harness.runEntity();
assertEquals(List.of(OpenerPosition.IN_OTHER_WORLD), harness.results);
}
}
private static final class Harness implements AutoCloseable {
private final Player player = mock(Player.class);
private final World world = mock(World.class);
private final Engine engine = mock(Engine.class);
private final IrisWorld target = mock(IrisWorld.class);
private final UUID opener = UUID.randomUUID();
private final List<OpenerPosition> results = new ArrayList<>();
private final MockedStatic<J> scheduling = mockStatic(J.class);
private final MockedStatic<Bukkit> bukkit = mockStatic(Bukkit.class);
private final MockedStatic<BukkitWorldBinding> binding = mockStatic(BukkitWorldBinding.class);
private final BukkitVisionOverlay overlay = new BukkitVisionOverlay(engine, opener);
private Runnable task;
private Runnable retired;
private boolean entityOwned;
private boolean reject;
private Harness() {
when(engine.getWorld()).thenReturn(target);
when(player.isOnline()).thenReturn(true);
when(player.getWorld()).thenReturn(world);
when(player.getLocation()).thenAnswer(invocation -> {
assertTrue("location read outside owning entity task", entityOwned);
return new Location(world, 18.5D, 72D, -4.25D);
});
bukkit.when(() -> Bukkit.getPlayer(opener)).thenReturn(player);
binding.when(() -> BukkitWorldBinding.world(target)).thenReturn(world);
scheduling.when(() -> J.runGlobal(any(Runnable.class))).thenAnswer(invocation -> {
invocation.getArgument(0, Runnable.class).run();
return true;
});
scheduling.when(() -> J.runEntity(same(player), any(Runnable.class))).thenAnswer(invocation -> {
task = invocation.getArgument(1);
return !reject;
});
scheduling.when(() -> J.runEntity(same(player), any(Runnable.class), eq(0), any(Runnable.class)))
.thenAnswer(invocation -> {
task = invocation.getArgument(1);
retired = invocation.getArgument(3);
if (reject) {
retired.run();
}
return !reject;
});
}
private void runEntity() {
entityOwned = true;
try {
task.run();
} finally {
entityOwned = false;
}
}
@Override
public void close() {
binding.close();
bukkit.close();
scheduling.close();
}
}
}
Loaded 100 of 1836 files, more files were not shown because too many files have changed in this diff. Show more