Public Access
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
783a33456d | ||
|
|
7b5597dd47 | ||
|
|
78a0f7ee51 | ||
|
|
dd219bb58a | ||
|
|
b48cc8a6ce | ||
|
|
779699d7a9 | ||
|
|
33b9bde302 |
No files matched your search
@@ -8,9 +8,13 @@ The bootstrap, books/linking, Ages, writing-system, and Age-grammar milestones a
|
||||
The writing system uses a data-pack symbol catalog and persistent
|
||||
ordered-writing model. Linking Books and Descriptive Books create persistent
|
||||
Ages from either authored supported symbols or seeded random completion.
|
||||
Instability and the remaining unsupported Legacy symbol effects have not been
|
||||
ported yet. The [Milestone 5 acceptance record](docs/MILESTONE_5_ACCEPTANCE.md)
|
||||
lists the supported grammar, optional integrations, and limits.
|
||||
Milestone 6 instability work is in progress: Ages persist frozen instability
|
||||
scores and provider plans, and the bounded runtime implements status effects,
|
||||
colored decay, lightning, explosions, meteors, burning, and erosion. The
|
||||
[Milestone 5 acceptance record](docs/MILESTONE_5_ACCEPTANCE.md) lists the
|
||||
supported grammar, optional integrations, and limits; the
|
||||
[instability runtime policy](docs/INSTABILITY_RUNTIME.md) records the current
|
||||
effects and modern safety boundaries.
|
||||
|
||||
Milestone 4 now includes stackable blank Pages plus server-created symbol,
|
||||
unresolved-symbol, and baseline link-panel states. Page visuals follow the
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ tasks.named('wrapper', Wrapper).configure {
|
||||
version = mod_version
|
||||
group = mod_group_id
|
||||
|
||||
List<String> archivedGameTestSuites = ['linking', 'environment', 'writing', 'grammar', 'generation', 'desk', 'binder', 'mixer', 'recipe']
|
||||
List<String> archivedGameTestSuites = ['linking', 'environment', 'writing', 'grammar', 'generation', 'desk', 'binder', 'mixer', 'recipe', 'instability']
|
||||
List<String> selectedArchivedGameTestSuites = providers.gradleProperty('withArchivedGameTests')
|
||||
.map { it.toBoolean() }.orElse(false).get() ? archivedGameTestSuites
|
||||
: providers.gradleProperty('archivedGameTestSuites').orElse('').get()
|
||||
|
||||
@@ -28,6 +28,7 @@ project's GNU LGPL v3 license. Rivencraft itself uses the same license.
|
||||
| `assets/rivencraft/textures/block/{small,medium,large}_crystal_bud.png`, `crystal_cluster.png` | Minecraft 1.21.1 `textures/block/{small,medium,large}_amethyst_bud.png`, `amethyst_cluster.png` | Minecraft 1.21.1 | Original 16×16 alpha masks and silhouettes preserved; hue shifted toward Legacy blue, with brighter saturation; exported as 8-bit RGBA (not indexed PNG) |
|
||||
| `assets/rivencraft/textures/item/crystal_shard.png` | Original sprite generated with OpenAI ImageGen from the Legacy crystal palette | 2026-10-05 | Cropped and nearest-neighbor scaled to 16×16 |
|
||||
| `assets/rivencraft/sounds/linking/link-fissure.ogg` | `assets/mystcraft/sounds/linking/link-fissure.ogg` | Legacy 0.13.7.06 local extraction | Namespace/path rename only; plays when a Star Fissure returns an entity home |
|
||||
| `assets/rivencraft/sounds/entity/meteor/roar.ogg` | `assets/mystcraft/sounds/entity/meteor/roar.ogg` | Legacy 0.13.7.06 local extraction | Byte-identical copy under the Rivencraft namespace; plays during the bounded meteor descent |
|
||||
|
||||
Mystcraft Legacy identifies XCompWiz as its project developer and includes the
|
||||
full LGPL v3 text in its root `LICENSE` file. Rivencraft's root `LICENSE`
|
||||
|
||||
+3
-2
@@ -18,12 +18,13 @@ core tests when investigating an issue:
|
||||
./gradlew runGameTestServer -ParchivedGameTestSuites=desk
|
||||
./gradlew runGameTestServer -ParchivedGameTestSuites=grammar,binder
|
||||
./gradlew runGameTestServer -ParchivedGameTestSuites=generation
|
||||
./gradlew runGameTestServer -ParchivedGameTestSuites=instability
|
||||
```
|
||||
|
||||
Available suite names are `linking`, `environment`, `writing`, `grammar`,
|
||||
`generation`, `desk`, `binder`, `mixer`, and `recipe`. The `generation` archive
|
||||
`generation`, `desk`, `binder`, `mixer`, `recipe`, and `instability`. The `generation` archive
|
||||
keeps the detailed feature, structure, ore, crystal, and fissure regressions
|
||||
out of the default smoke run. Three checks formerly registered twice in the
|
||||
out of the default smoke run. The `instability` archive adds multi-player loaded-chunk selection, policy gates, and protected-block checks without rerunning the default scoring and migration tests. Three checks formerly registered twice in the
|
||||
core and their archives now run only through the core wrapper. Run all
|
||||
Rivencraft tests before a
|
||||
release or after broad cross-system changes:
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Instability controls and diagnostics (Milestone 6, issue #72)
|
||||
|
||||
The world-specific NeoForge server config (`serverconfig/rivencraft-server.toml`) is the global policy. `instability.enabled` stops all scheduled effects without changing a saved Age. `instability_providers.<id>` switches each Legacy card independently; these switches do not reroll frozen provider levels. The existing `instability_status_effects`, `instability_decay`, `instability_hazards`, `instability_meteor`, `instability_scorching`, and `instability_erosion` groups provide category policy and action limits. `instability.world_mutation`, hazard/meteor `block_damage`, `player_damage`, and `fire` settings control destructive behavior. `mobGriefing` and `doFireTick` still apply. Defaults retain the Legacy-active hazards; the scheduler, spawn protection, loaded-chunk checks, and per-effect caps remain Rivencraft safety adaptations. The dormant-in-Legacy erosion effect remains enabled for project testing but can be switched off.
|
||||
|
||||
Configuration values are read during server operation, but editing the TOML on disk does not guarantee NeoForge will reload it. Restart the server or world after changing the file; `/reload` reloads data packs, not this server config. Per-Age commands below take effect on the next scheduler pass without a restart. A stopped provider does not refund or change the Age's score or saved plan. Existing owned status-effect leases are revoked on their next 20-tick check after global, category, provider, or Age disablement. In-flight meteors are cancelled when their Age or meteor provider is disabled. Existing block changes are not rolled back.
|
||||
|
||||
Operators can inspect `/rivencraft age instability [dimension]`. The argument accepts an Age name (quote names containing spaces), a short path such as `fort`, or a full ID such as `rivencraft:age/fort`. Duplicate names require the full ID shown by `/rivencraft age list`. The command reports the frozen score and each saved contribution, the frozen provider IDs/levels and their *current* runtime eligibility, config limits, and whether this Age is enabled. "Eligible" does not promise an effect on the next tick: chance, cooldowns, loaded chunks, player presence, and protection still apply. An unavailable handler is reported as such instead of being mistaken for an active provider. Pre-scoring Ages remain neutral, and missing provider plans from older scored saves are migrated once as described in [runtime policy](INSTABILITY_RUNTIME.md). `/rivencraft age instability disable <dimension>` and `enable <dimension>` are operator-only and persist for that Age alone. Unknown dimensions are rejected. Neither command mutates a book, score, or provider plan.
|
||||
|
||||
Newly bound Descriptive Books carry only a server-written numerical potential-instability summary for their tooltip and cover. The details and live enablement stay server-side in the operator command. Older written books receive the summary when opened through the server-approved book screen; until then, an absent tooltip score means "not yet synchronized," not zero. The score does not indicate whether effects are currently enabled.
|
||||
|
||||
Manual check: create two scored Ages, disable one with the command, and inspect both. Only the selected Age should show "Age disabled"; its saved breakdown and plan should remain identical. Re-enable it, then switch an individual provider in the world config and restart. Its plan should remain identical while diagnostics show "provider config off." An old neutral Age should report score zero and no selected providers. A non-operator should be unable to invoke the mutation commands. Test tooltips both on a newly bound book and an older book after opening it once.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Environmental instability (#70)
|
||||
|
||||
The local Mystcraft Legacy 0.13.7.06 bytecode was audited for `EffectMeteor`, `EntityMeteor`, `EffectScorched`, `EffectErosion`, and their providers. The active deck registers `meteors` in destructive and `burning` (scorching) in harsh. Erosion's provider is present in bytecode but not registered in the active deck. Its old chunk-population lake routines are not run at Age creation in Rivencraft; ordinary authored lake features already own generation. The old erosion tick spread a neighboring water/lava or Forge fluid block into a random non-liquid position, excluding downward neighbors and block containers.
|
||||
|
||||
Rivencraft keeps the active `meteors` and `burning` provider IDs in frozen Age plans. Erosion does not become a deck card. For this test slice, `instability_erosion.enabled` defaults **on** as an explicit adaptation requested by the user. It runs only in Ages whose frozen instability score reaches the destructive deck threshold (10,000), and may be disabled independently. Existing Age plans are not rerolled.
|
||||
|
||||
Legacy's meteor spawned at Y=500, fell as a custom entity, broke blocks along its path, and made multiple large explosions on impact. Modern Ages can have different build heights and dynamic dimensions. Rivencraft instead records one bounded active descent per Age (16 globally), starting no more than 48 blocks above the loaded surface. Server particles show the trajectory and the byte-identical Legacy `entity/meteor/roar.ogg` plays near the impact. A single strength-3 impact reuses the capped explosion/protection hooks from #69. There is no persistent projectile entity or custom model; stopping/unloading a dimension cancels a descent rather than replaying it on restart. The saved per-Age attempt sequence and cooldown prevent immediate repeated rolls. The adaptation is intentionally less destructive than Legacy's chain of explosions.
|
||||
|
||||
Scorching checks at most eight loaded chunks and eight living-entity candidates per chunk per scheduler pass, igniting at most the configured target count. Targets must be open to sky; survival/adventure players are included by default as in Legacy, while creative/spectator players and spawn safety positions are excluded. Fire duration is four seconds per provider level, capped at twelve seconds. This affects entities, not blocks, and does not request distant chunks.
|
||||
|
||||
Erosion inspects at most eight already-loaded candidate positions per pass and can replace at most one safe block with an adjacent source fluid. It excludes block entities, protected/critical Rivencraft blocks, portals, spawn safety positions, and unloaded neighboring chunks. Break and place events with a fake player permit claim/protection hooks to veto a change; rejected placement is rolled back. World mutation and `mobGriefing` must also be enabled. The modern Y range is taken from the Age level rather than Legacy's fixed 0–127 sample.
|
||||
|
||||
The server config has independent meteor enable/block damage/player damage/fire/caps, scorching enable/player targeting/cap, and erosion enable switches. Meteor frequency preserves Legacy's 1/50,000 chance per chunk-tick across nearby loaded chunks, capped to one active descent per Age. Visual/audio effects still run when meteor block damage is disabled. No client-only class is loaded on a dedicated server. The reused roar sound is recorded in [asset provenance](ASSET_PROVENANCE.md); Legacy has no separate meteor texture in the supplied asset tree.
|
||||
|
||||
Operator checks in a loaded, sufficiently unstable Age: `/rivencraft age environment pulse meteor` starts one protected descent (200-tick cooldown), `/rivencraft age environment pulse burning` ignites the issuing survival player only when open to sky and outside spawn protection, and `/rivencraft age environment pulse erosion` converts the block being looked at if a source fluid touches its side or top. The burning test reports when rain or water would immediately extinguish the fire. Place water or lava next to a plain stone block and aim at the stone to test erosion. These commands refuse to run in the Overworld and still honor enable switches, protection hooks, and world-mutation policy. Natural meteor occurrence is intentionally rare, as in Legacy.
|
||||
@@ -4,6 +4,27 @@ Each new Age stores an `InstabilityPlan` beside its frozen `Instability` score.
|
||||
|
||||
The saved provider IDs are independent of installed handlers. A missing optional handler leaves its ID and level intact and is skipped at runtime. A syntactically invalid saved ID or unsupported plan version fails loading explicitly; an unknown but valid ID is preserved and logged once when encountered. Disabling instability or world mutation never rewrites a saved score or provider plan. Saves from #64 with a frozen score but no provider plan are selected once from that score and Age seed, then marked dirty for persistence. Older pre-score Ages remain neutral and inert.
|
||||
|
||||
From 0.5.8.11, [live block profiling](LIVE_BLOCK_INSTABILITY.md) adds a separate
|
||||
effective score and provider plan once 400 Age and Overworld chunks have been
|
||||
sampled. The authored score/plan described above remain saved as the base;
|
||||
the effective provider selection can change as block abundance is observed.
|
||||
|
||||
The server scheduler runs only for loaded `rivencraft:age/*` levels with a player present and an Age definition. It uses only chunks already loaded near those players, never requests a chunk, and rotates among eligible Ages when the per-tick cap is reached. Configuration bounds the cooldown (minimum 20 ticks), active Ages, handlers and actions per Age, effective provider level, and examined loaded chunks. A handler must claim a shared action permit before each effect. A throwing handler is logged and quarantined temporarily without stopping the server. World-mutating handlers are enabled by default to match Legacy; the setting can still disable them. These limits are guards for upcoming providers, not proof that an arbitrary third-party handler cannot misuse world APIs.
|
||||
|
||||
Issue #67 registers the non-world-mutating potion handlers; see [status-effect policy](INSTABILITY_STATUS_EFFECTS.md). Issue #68 adds configurable [colored decay](INSTABILITY_DECAY.md), enabled by default for newly generated configs. Other world hazards remain for #69–#70. The runtime rejects Overworld and preview dimension IDs; its player requirement excludes unattended snapshot chunk loaders. GameTests cover deterministic selection, save round-trips, score-only migration, unknown IDs, scope checks, fair admission, and action caps.
|
||||
Issue #67 registers the non-world-mutating potion handlers; see [status-effect policy](INSTABILITY_STATUS_EFFECTS.md). Issue #68 adds configurable [colored decay](INSTABILITY_DECAY.md), enabled by default for newly generated configs. Issue #69 adds lightning and explosions; issue #70 adds [meteor, scorching, and erosion](INSTABILITY_ENVIRONMENTAL.md). The runtime rejects Overworld and preview dimension IDs; its player requirement excludes unattended snapshot chunk loaders. GameTests cover deterministic selection, save round-trips, score-only migration, unknown IDs, scope checks, fair admission, and action caps.
|
||||
|
||||
Issue #72 adds [server config, per-Age controls, diagnostics, and book feedback](INSTABILITY_DIAGNOSTICS.md). Its operator controls never rewrite a frozen score or provider plan.
|
||||
|
||||
The Milestone 6 [regression and migration record](MILESTONE_6_REGRESSION.md)
|
||||
maps the automated acceptance checks and lists the in-game restart, optional-mod,
|
||||
and hazard-visual scenarios still requiring verification.
|
||||
|
||||
# Lightning and explosions (#69)
|
||||
|
||||
The `lightning` and `explosions` cards now run only in loaded Rivencraft Ages with players. Legacy rolled once per chunk per tick: explosions at 1/1000 and lightning at 1/5000 during thunder or 1/100000 otherwise. Each selected hazard card gets an independent roll every scheduler pass, rather than waiting for the rotating two-provider sample. The roll uses up to 81 already-loaded chunks near Age players and the exact probability of at least one Legacy opportunity over that many chunk-ticks. It permits at most one event per hazard type per pass. A per-Age saved sequence and last-event time prevent the same roll/event from replaying after a restart. Lightning also skips an existing bolt at the target.
|
||||
|
||||
Legacy used a real lightning bolt and a flaming, block-damaging strength-3 explosion. Both remain enabled by default. Unlike Legacy, the bolt is visual-only and its damage/fire are applied through separate bounded paths. The explosion uses NeoForge's normal explosion hooks plus break-event checks, with a calculator that restricts destruction to one already-loaded chunk, protects spawn, block entities, portals, decay-protected blocks and Rivencraft infrastructure, and caps affected blocks and entity damage. The visual/audio explosion still occurs when griefing is disabled. `mobGriefing` and `doFireTick` gate block changes and ignition; survival/adventure player damage is separately configurable. These are deliberate modern server-safety differences from Legacy.
|
||||
|
||||
Server config `instability_hazards` controls enablement, block damage, player damage, fire, interval, maximum nearby loaded chunks, maximum destroyed blocks, damaged entities, damage per entity, and explosion radius. `instability.world_mutation=false` also suppresses block damage and fire without suppressing visuals or entity damage. No hazard is dispatched into preview, Overworld, or another Age.
|
||||
|
||||
For an operator smoke test inside an Age, `/rivencraft age hazard pulse lightning` and `/rivencraft age hazard pulse explosion` force one event in a safe loaded chunk. They still honor the Age scope, enable switch, cooldown, spawn exclusion, game rules and damage policies. Repeat after `minimum_gap_ticks` (default 20 ticks); run the same command in the Overworld to verify that it refuses to fire. The earlier 200-tick `min_interval_ticks` test key is retired; existing configs receive the new default when NeoForge corrects them.
|
||||
@@ -2,8 +2,14 @@
|
||||
|
||||
Every newly created Age now gets a version-1 `Instability` compound inside its server-owned `rivencraft_ages` saved definition. It contains the total `Score` and an ordered `Breakdown` of reason, original page index (zero-based, or -1 for an Age-wide cause), points, and explanation. `AgeRegistrySavedData.instability(UUID)` is the read-only server query. No client tooltip or live data-pack lookup is needed to read a saved score.
|
||||
|
||||
The baseline is explicitly zero for page-free and Link-Panel-only random Ages, and for authored Ages. Incomplete writing receives seed-based completion and a zero-point explanatory entry. Supported writing defects use the provisional Milestone 6 grammar costs: duplicate/conflicting single-choice pages +500, out-of-order or misplaced pages +100. Legacy's audited bright-lighting symbol adds +500 whether authored or seed-selected. Other balance costs are not guessed for symbols that Rivencraft has not implemented. The score is not yet an active hazard or effect selection.
|
||||
The baseline is explicitly zero for page-free and Link-Panel-only random Ages, and for authored Ages. Incomplete writing receives seed-based completion and a zero-point explanatory entry. Supported writing defects use the provisional Milestone 6 grammar costs: duplicate/conflicting single-choice pages +500, out-of-order or misplaced pages +100. Legacy's audited Bright Lighting symbol adds +500 for every occurrence, including a seed-generated controller. Mineshafts, Nether Fortresses, Strongholds, and Villages add +100 for the fourth and every later occurrence. By project balance decision, Bastions, Trial Chambers, Ancient Cities, Shipwrecks, Ocean Ruins, Pillager Outposts, Ruined Portals, Nether Fossils, Buried Treasure, and Trail Ruins follow that same rule. The first three occurrences and all other audited Legacy feature symbols have no direct page cost. An authored structure may override its vanilla biome eligibility; every structure-page occurrence adds +100 if **any** selected biome is unsupported, even when another selected biome is compatible. Seed completion still prefers compatible biomes and therefore avoids that cost when it can. Other modern-only features remain neutral. The frozen score selects a deterministic, persisted provider plan through the Milestone 6 runtime. Registered handlers apply that plan only inside loaded Rivencraft Ages and remain subject to the documented scheduler and effect-specific safety bounds.
|
||||
|
||||
The score is calculated after the Age plan and effective traits are chosen, then saved with the Age identity before its dimension is generated. The same UUID returns the existing definition, including the same score, on repeated use. Spawn updates preserve it. Reload only deserializes the frozen breakdown; it never reruns the current grammar or catalog. An older Age definition without `Instability` is migrated to a persisted version-1 neutral score of zero, rather than retroactively scoring its writing. A future scoring-rule change must introduce an explicit new schema/migration policy, not silently reinterpret existing Ages. Issue #66 additionally freezes a provider selection from this score; see [runtime policy](INSTABILITY_RUNTIME.md).
|
||||
The score is calculated after the Age plan and effective traits are chosen, then saved with the Age identity before its dimension is generated. The same UUID returns the existing definition, including the same score, on repeated use. Spawn updates preserve it. Reload only deserializes the frozen breakdown; it never reruns the current grammar or catalog. An older Age definition without `Instability` is migrated to a persisted version-1 neutral score of zero, rather than retroactively scoring its writing. A future scoring-rule change must introduce an explicit new schema/migration policy, not silently reinterpret existing Ages. Issue #66 added the frozen provider selection; issues #67–#70 added the current handlers. See the [runtime policy](INSTABILITY_RUNTIME.md).
|
||||
|
||||
This is now the **authored base** score. [Live block profiling](LIVE_BLOCK_INSTABILITY.md)
|
||||
keeps its sample counts separately and may add a changing effective block score
|
||||
without rewriting the authored breakdown or its saved base provider plan.
|
||||
|
||||
Unknown or unsupported pages remain invalid for *new* Ages. Their absence from a later registry does not change an already saved score. Focused GameTests cover stable/defective writing, random baseline and bright lighting, repeated identity, save round-trip, and missing-symbol/old-save behavior.
|
||||
|
||||
`/rivencraft age instability` inspects the Age containing the command source; an optional dimension ID inspects an unloaded or different registered Age. It reports immutable base score, stability bonus, runtime penalty, and effective score. The pinned Legacy tree defines player-death and player-presence bonus classes but does not register them as default providers, so Rivencraft leaves player-driven modifiers disabled: bonus and penalty are zero and effective equals base. There is therefore no mutable bonus save to migrate in this release. No death, PvP event, player identity, or dimension transition can transfer stability between Ages. Any future opt-in mechanic must persist separately from `Instability`, define caps and reset behavior, and must not rewrite the generation plan or frozen provider plan.
|
||||
@@ -1,10 +1,10 @@
|
||||
# Mystcraft Legacy instability audit (Milestone 6, issue #63)
|
||||
|
||||
This is a behavior contract for Milestone 6, **not a completed runtime instability system**. It compares the user-provided 0.13.7.06 class files at `/home/dnorberg/Documents/mystcraft-src/mystcraft-1.12.2-0.13.7.06/` with [Mystcraft Legacy source at commit `9bc8ddc`](https://github.com/Mystcraft/Mystcraft-Legacy/tree/9bc8ddc061845df0cd5ea47f4fdef773cff786ae). Values below are source defaults, not a claim that every historical config or server used them. Rivencraft 0.5.1.0 saves a provisional writing-instability score and repaired active-page order, but has no hazard loop yet.
|
||||
This is the behavior contract used to implement Milestone 6. It is pinned to [Mystcraft Legacy source at commit `9bc8ddc`](https://github.com/Mystcraft/Mystcraft-Legacy/tree/9bc8ddc061845df0cd5ea47f4fdef773cff786ae). Values below are source defaults, not a claim that every historical config or server used them. Rivencraft now persists frozen writing-instability scores and provider plans and runs the implemented providers through a bounded, Age-scoped scheduler. The audit remains authoritative for Legacy behavior; the linked runtime documents identify modern adaptations and remaining gaps.
|
||||
|
||||
## Score, grammar, and selection in Legacy
|
||||
|
||||
Legacy's [`AgeController`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/world/AgeController.java) calculates `debug + symbol + block + book/base + bonus`, then applies difficulty 0/1/2/3 multipliers of 0.25/0.5/1/1.75. Global instability is enabled by default; an Age also has its own enable flag. The unmodified score is not simply “number of bad pages.” Block profiling may delay a usable score: `blockinstability` is null until **more than** 400 Age chunks are profiled, and `getInstabilityScore()` returns zero until then. It is recalculated after additional profiling. [`ChunkProfiler`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/world/profiling/ChunkProfiler.java) compares watched block abundance with a baseline, subtracting only positive excess above each baseline. The baseline is profiled or read from balance config; [`InstabilityDataCalculator`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/world/profiling/InstabilityDataCalculator.java) sets its default tolerance to 1.05, and default `useconfigs=false`. We should not copy its 400-chunk profiling delay or dynamic block scan into 1.21.1 without a separate performance case.
|
||||
Legacy's [`AgeController`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/world/AgeController.java) calculates `debug + symbol + block + book/base + bonus`, then applies difficulty 0/1/2/3 multipliers of 0.25/0.5/1/1.75. Global instability is enabled by default; an Age also has its own enable flag. The unmodified score is not simply “number of bad pages.” Block profiling may delay a usable score: `blockinstability` is null until **more than** 400 Age chunks are profiled, and `getInstabilityScore()` returns zero until then. It is recalculated after additional profiling. [`ChunkProfiler`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/world/profiling/ChunkProfiler.java) compares watched block abundance with a baseline, subtracting only positive excess above each baseline. The baseline is profiled or read from balance config; [`InstabilityDataCalculator`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/world/profiling/InstabilityDataCalculator.java) sets its default tolerance to 1.05, and default `useconfigs=false`. Rivencraft's later [bounded implementation](LIVE_BLOCK_INSTABILITY.md) retains the threshold and tolerance, but not Legacy's spatial accessibility formula or unbounded profiling.
|
||||
|
||||
| Input | Verified Legacy behavior | Rivencraft M6 interpretation |
|
||||
| --- | --- | --- |
|
||||
@@ -15,6 +15,10 @@ Legacy's [`AgeController`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9b
|
||||
| Unsupported/unmatched page | Legacy logs unmatched symbols during reconstruction and skips their logic; its `AgeData.getBaseInstability()` still has a TODO for calculating instability from pages. This is not a sound compatibility contract. | Remains fatal for *new* books until semantic and runtime support exists; never silently erase the page or pretend its effect applied. Existing saved books retain their IDs. |
|
||||
| Other penalties/bonuses | `AgeController.addInstability(int)` is available to symbol logic. The base/book score is persisted as a `short`; Legacy's [`InstabilityBonusManager`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/bonus/InstabilityBonusManager.java) also has dynamic player death/behavior components. | Persist a versioned score breakdown for Age writing and environmental contributions. Do not infer death/troll mechanics from the mere existence of Legacy classes. |
|
||||
|
||||
The complete Legacy `instabilityModifier` audit found direct feature-page costs only for Mineshafts, Nether Fortresses, Strongholds, and Villages. Their first three occurrences cost zero; the fourth and every later occurrence adds 100. Every other Legacy feature class inherited `SymbolBase`'s zero modifier. Rivencraft applies that exact rule to the four matching pages. By project balance decision, Bastions, Trial Chambers, Ancient Cities, Shipwrecks, Ocean Ruins, Pillager Outposts, Ruined Portals, Nether Fossils, Buried Treasure, and Trail Ruins use the same repeat rule. Matching Legacy features such as Caves, Crystal Formations, Dense Ores, Dungeons, Floating Islands, Huge Trees, Deep/Surface Lakes, Obelisks, Ravines, Skylands, Spheres, Spikes, Star Fissures, and Tendrils have no direct page cost. Legacy could still derive instability later from excess profiled blocks, especially ores. From 0.5.8.11, Rivencraft has a [bounded live block-profile adaptation](LIVE_BLOCK_INSTABILITY.md) using the 400-chunk threshold, including diamond blocks as a deliberate non-Legacy extension. Other modern-only Rivencraft features remain neutral unless they increase watched-block abundance.
|
||||
|
||||
Bright Lighting adds 500 for every authored occurrence. A generated Bright Lighting controller also adds 500. This is independent of the 500-point extra-controller cost, so two authored Bright Lighting pages produce 1,500 total: 500 for each symbol and 500 for the repeated controller.
|
||||
|
||||
Source for controller and modifier defaults: [`InstabilityData`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/InstabilityData.java), [`AgeController`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/world/AgeController.java). The local 0.13.7.06 `Modifier.class` confirms `dangling_default=100`. Legacy grammar **ranks** weight which missing symbols are selected; they are not a direct instability score or deck tier. See [grammar audit](LEGACY_AGE_GRAMMAR_AUDIT.md) and [random weights](RANDOM_AGE_WEIGHTS.md).
|
||||
|
||||
[`InstabilityController`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/InstabilityController.java) rounds its working score toward zero to the current smallest registered positive provider cost (500 by default), then rebuilds active effects when that rounded score changes. Each seeded deck preserves its saved card order; new cards are shuffled with the Age seed. For each deck it subtracts the deck entry cost, then walks cards in order, paying each provider activation cost until the next card cannot be afforded. A provider's occurrences become its level. **Deck costs are gates, not mutually exclusive severity bands**: at high score multiple decks can contribute effects. Provider `.enabled` config can remove cards. The actual effect set cannot be inferred from a score alone without the saved deck orders and enabled providers ([`Deck`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/Deck.java), [`InstabilityManager`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/InstabilityManager.java)).
|
||||
@@ -35,25 +39,27 @@ These entry costs are from [`InstabilityData.initialize()`](https://github.com/M
|
||||
|
||||
| Family | Legacy behavior | M6 disposition |
|
||||
| --- | --- | --- |
|
||||
| Player and hostile-mob potions | Local/global blindness, fatigue, hunger, nausea, poison, slowness, weakness, wither; hostile regeneration/resistance ([`EffectPotion`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectPotion.java)). | Implement in #67 with server-only, Age-scoped entity targeting and rate limits. No effects in preview/snapshot worlds. |
|
||||
| Colored decay | Blue, purple, red, white providers place advancing decay and extra-tick it; black provider is commented out. Decay handlers differ in spread/consumption ([providers](https://github.com/Mystcraft/Mystcraft-Legacy/tree/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/providers), [handlers](https://github.com/Mystcraft/Mystcraft-Legacy/tree/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/decay)). | Implement bounded, reversible-by-admin world mutation in #68; exact 1.12 spread/update rates require adaptation and tests. Exclude protected spawn/portal areas. Black/green/yellow are **not** proven active Legacy providers. |
|
||||
| Lightning and explosions | Random per-chunk strike/explosion attempts ([`EffectLightning`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectLightning.java), [`EffectExplosions`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectExplosions.java)). | Implement in #69 with explicit block-damage and fire policy; no effect outside the Age. |
|
||||
| Meteor, scorching | Meteor entity spawn and sky-exposed entity ignition ([`EffectMeteor`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectMeteor.java), [`EffectScorched`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectScorched.java)). | #70: modern meteor entity/impact needs an explicit damage budget; scorching can use modern fire/damage checks. Legacy `meteor/roar.ogg` is available. |
|
||||
| Crumble and erosion | Crumble maps blocks to weaker states; erosion spreads adjacent fluids and has extra lake-generation methods ([`EffectCrumble`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectCrumble.java), [`EffectErosion`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectErosion.java)). | #70: bounded block palette and protected-area checks. Erosion's provider is commented out in Legacy registration: treat it as deliberate opt-in adaptation, not baseline parity. |
|
||||
| Player and hostile-mob potions | Local/global blindness, fatigue, hunger, nausea, poison, slowness, weakness, wither; hostile regeneration/resistance ([`EffectPotion`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectPotion.java)). | Implemented in #67 with server-only, Age-scoped entity targeting and rate limits. No effects run in preview/snapshot worlds. |
|
||||
| Colored decay | Blue, purple, red, white providers place advancing decay and extra-tick it; black provider is commented out. Decay handlers differ in spread/consumption ([providers](https://github.com/Mystcraft/Mystcraft-Legacy/tree/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/providers), [handlers](https://github.com/Mystcraft/Mystcraft-Legacy/tree/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/instability/decay)). | Implemented in #68 as bounded world mutation with protected spawn/portal areas and configurable shutdown. Black/green/yellow remain excluded because they are **not** proven active Legacy providers. |
|
||||
| Lightning and explosions | Random per-chunk strike/explosion attempts ([`EffectLightning`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectLightning.java), [`EffectExplosions`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectExplosions.java)). | Implemented in #69 with separate damage/fire/griefing policies and loaded-Age bounds; see `INSTABILITY_RUNTIME.md`. |
|
||||
| Meteor, scorching | Meteor entity spawn and sky-exposed entity ignition ([`EffectMeteor`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectMeteor.java), [`EffectScorched`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectScorched.java)). | #70 implements a bounded meteor descent/impact and the active `burning` card; see `INSTABILITY_ENVIRONMENTAL.md`. Legacy `meteor/roar.ogg` is reused. |
|
||||
| Crumble and erosion | Crumble maps blocks to weaker states; erosion spreads adjacent fluids and has extra lake-generation methods ([`EffectCrumble`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectCrumble.java), [`EffectErosion`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectErosion.java)). | #70 implements guarded fluid spread. Erosion's provider is absent from the active Legacy deck; it is deliberately enabled by default in this test slice without adding a saved deck card, per user request. |
|
||||
| Extra ticks | Registered alongside blue/purple/red/white decay, targeting decay blocks ([`EffectExtraTicks`](https://github.com/Mystcraft/Mystcraft-Legacy/blob/9bc8ddc061845df0cd5ea47f4fdef773cff786ae/src/main/java/com/xcompwiz/mystcraft/effects/EffectExtraTicks.java)). | Implement only as a bounded decay helper in #68; do not accelerate arbitrary blocks/block entities. |
|
||||
| Other dormant code | Black decay, global burning, bedrock crumble, erosion provider are commented out. | Defer unless a later issue explicitly requests them. An authored symbol requiring one must fail clearly until supported. |
|
||||
| Other dormant code | Black decay, global burning, bedrock crumble, erosion provider are commented out; ordinary `burning` (scorching) remains active. | Erosion has been explicitly requested for #70 testing. The other dormant variants remain deferred; an authored symbol requiring one must fail clearly until supported. |
|
||||
|
||||
Assets in the supplied local tree: `assets/mystcraft/textures/blocks/decay_{black,blue,green,purple,red,white,yellow}.png`, corresponding decay block/item model JSON, and `assets/mystcraft/sounds/entity/meteor/roar.ogg`. Before importing, review attribution/license and fit modern 16×16 assets. Texture availability does not make an effect active. Use current Minecraft effects/sounds where adaptation is cleaner; no new artwork is needed for this audit.
|
||||
|
||||
## Rivencraft boundary and proposed safety contract
|
||||
## Rivencraft boundary and current safety contract
|
||||
|
||||
[`WritingGrammar`](../src/main/java/net/dnorberg/rivencraft/writing/WritingGrammar.java) classifies `INCOMPLETE` as seeded completion and supported writing defects as accepted instability. `AgeGenerationPlan.compile()` freezes the original writing, repaired active-page indexes, and a provisional writing-instability score before world generation. #64 now persists a versioned score breakdown; saved provider/deck choice remains future work. The plan must not mutate an already-created Age when a data pack changes. Server-side settings may disable execution, but should not rewrite the saved authored score.
|
||||
[`WritingGrammar`](../src/main/java/net/dnorberg/rivencraft/writing/WritingGrammar.java) classifies `INCOMPLETE` as seeded completion and supported writing defects as accepted instability. `AgeGenerationPlan.compile()` freezes the original writing, repaired active-page indexes, and a provisional writing-instability score before world generation. #64 persists the versioned score breakdown, and #66 derives and persists the provider/deck choice from that frozen score. The plan must not mutate an already-created Age when a data pack changes. Server-side settings may disable execution, but do not rewrite the saved authored score or provider plan.
|
||||
|
||||
For #65, **eligible-to-become-unstable** means a known, supported page whose semantics and resulting world are still deterministic: repeated/conflicting single-choice pages and otherwise valid out-of-order or misplaced pages. The implementation retains every original page, uses the last single-choice page, sorts active categories, and saves 500 per extra/conflicting choice or 100 per misplaced page. These are provisional Rivencraft values, not a full port of every `IAgeSymbol.instabilityModifier`. Missing branches are explicitly classified as zero-cost seeded completion; legal repeated feature/material pages are not automatically errors. **Remain fatal**: missing/duplicate/misordered Link Panel, over-capacity book, unresolved or schema-v1 display-only symbol, unsupported weather/angle/runtime profile/biome/feature, unavailable required optional mod, and any combination the compiler cannot represent safely. Binder and unbound-book previews distinguish blocked writing, seeded completion, and accepted instability before binding; the server revalidates on output. This intentionally differs from Legacy's silent unmatched-symbol skip, universal controller cost assumptions, and modifier-specific dangling costs. A full symbol-specific Legacy penalty port remains a separate balance task, not a claim of parity in this slice.
|
||||
For #65, **eligible-to-become-unstable** means a known, supported page whose semantics and resulting world are still deterministic: repeated/conflicting single-choice pages and otherwise valid out-of-order or misplaced pages. The implementation retains every original page, uses the last single-choice page, sorts active categories, and saves 500 per extra/conflicting choice or 100 per misplaced page. Issue #71 adds the audited Bright Lighting and repeat-structure modifiers described above. Missing branches are explicitly classified as zero-cost seeded completion; legal repeated feature/material pages are not automatically errors, though a fourth matching Legacy structure now receives its source-defined cost. **Remain fatal**: missing/duplicate/misordered Link Panel, over-capacity book, unresolved or schema-v1 display-only symbol, unsupported weather/angle/runtime profile/biome/feature, unavailable required optional mod, and any combination the compiler cannot represent safely. Binder and unbound-book previews distinguish blocked writing, seeded completion, and accepted instability before binding; the server revalidates on output. This intentionally differs from Legacy's silent unmatched-symbol skip, universal controller cost assumptions, and modifier-specific dangling costs.
|
||||
|
||||
Legacy includes `PlayerKilledBonus` and `PlayerTrollPenalty` classes, but the pinned source contains no default provider registration for either. Rivencraft does not activate death, PvP, player-presence, or cross-dimension credit from dormant classes. Consequently #71 has no mutable per-Age bonus state to migrate, cap, reset, or persist: the stability bonus and runtime penalty are both zero, and the effective score equals the frozen base score. `/rivencraft age instability [dimension]` reports those four values and the disabled policy explicitly. This prevents unrelated players, deaths in other dimensions, and repeated deaths from changing an Age. A future opt-in policy must use separate versioned saved data and define its cap/reset rules before it can alter runtime selection.
|
||||
|
||||
Automated #65 checks cover classification, preserved input slots on rejection, and an accepted unstable preview. The live output/one-time Age creation check is assigned to in-game testing because the GameTest storage phase stalled when that transaction ran; the test world is not retained.
|
||||
|
||||
Issue #66 establishes a server-only scheduler with bounded per-Age actions, provider calls, levels, cooldowns, loaded-chunk candidates, and rotating active-Age admission. World-mutating handlers are **off by default**. No provider effects are registered yet; #67–#70 must enforce protected spawn/link platforms, portals, and provider-specific damage/spread limits before activation. These are **Rivencraft safety adaptations**, not Legacy defaults. Expose score breakdown, selected effects, enablement, and budget suppression in server diagnostics (#72). See [runtime policy](INSTABILITY_RUNTIME.md).
|
||||
Issue #66 established a server-only scheduler with bounded per-Age actions, provider calls, levels, cooldowns, loaded-chunk candidates, and rotating active-Age admission. Issues #67–#70 registered the current status, decay, lightning, explosion, meteor, burning, and erosion handlers with protected spawn/link platforms, portal exclusions, and provider-specific damage or spread limits. Instability and world-mutating handlers are enabled by default for newly generated configs to match Legacy's active default; operators can disable them without changing a saved Age. The bounds and protection hooks are **Rivencraft safety adaptations**, not Legacy defaults. Score breakdown, selected effects, enablement, and budget suppression remain part of diagnostics issue #72. See the [runtime policy](INSTABILITY_RUNTIME.md).
|
||||
|
||||
M6 owns scoring, selection, effects, controls, and regression. M7 still owns portal/transport and broader polish; M6 must not depend on new M7 structures. An illegal biome/terrain combination that is presently unrepresentable remains a generation failure until a separate, safe compiler path exists; instability must not be used to disguise absent worldgen support. Existing pre-release saves need explicit migration behavior in #73 rather than a silent rescore.
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# Live block-instability profiling (0.5.8.11)
|
||||
|
||||
Mystcraft Legacy measures the abundance of watched blocks in generated chunks,
|
||||
compares that abundance with a baseline, and adds only positive excess to the
|
||||
Age's instability. Its `InstabilityBlockManager` and `ChunkProfiler` are
|
||||
available in the user's local 0.13.7.06 archive. Legacy's Age-side threshold
|
||||
is more than 400 profiled chunks; its default tolerance is 1.05. The Legacy watched
|
||||
blocks include coal, lapis, iron, emerald, redstone, gold and diamond ores,
|
||||
quartz ore, glowstone, and crystal blocks. Diamond **blocks** are not on that
|
||||
default list, but are included here at the player's request.
|
||||
|
||||
Rivencraft samples up to 1,024 distinct, newly generated chunks per dimension,
|
||||
at most four per server tick. It never generates a chunk merely to profile it.
|
||||
The Overworld is sampled as the baseline; an Age needs 401 samples and the
|
||||
baseline needs 500 before the live block component contributes points. Counts and sampled chunk
|
||||
positions persist per dimension, preventing reloads from double-counting.
|
||||
For each watched block, Rivencraft compares average blocks per sampled chunk
|
||||
and charges `max(0, Age average − 1.05 × Overworld average) × weight`, rounded
|
||||
to the nearest point. The block component is capped at 100,000 points.
|
||||
|
||||
Legacy weights are used for its watched blocks: coal/lapis 5, iron 60, emerald
|
||||
200, redstone 250, gold 750, diamond 4,000, quartz/crystal 20, and glowstone
|
||||
50. Deepslate variants inherit their ore's weight. Modern/high-value extensions
|
||||
include diamond, emerald, gold, iron, raw gold, raw iron and netherite storage
|
||||
blocks, plus ancient debris. Netherite blocks cost 8,000 per excess block per
|
||||
sampled chunk; ancient debris costs 4,000. Modded blocks are not automatically
|
||||
classified as valuable; this avoids charging unknown decorative materials.
|
||||
|
||||
The authored score and provider plan remain saved as the Age's immutable base.
|
||||
Only Ages created with instability schema v2 participate; existing v1 Ages
|
||||
retain their previously frozen scores/plans, including neutral pre-scoring
|
||||
Ages. This avoids silently rescoring existing worlds.
|
||||
The live block component creates a deterministic **effective** score and
|
||||
provider plan from that base plus the persisted profile; new cards can become
|
||||
active as sampled abundance rises. The command `/rivencraft age instability`
|
||||
shows both the saved base and the currently profiled block component. An
|
||||
unloaded Age has no active profile view until its dimension is loaded again.
|
||||
Turning an effect off does not delete counts or reroll the same effective plan.
|
||||
|
||||
This is not byte-for-byte Legacy profiling. Legacy has a spatial accessibility
|
||||
map and two factors per block, actively builds a dummy-world baseline, and can
|
||||
recompute after subsequent chunk profiling. Rivencraft uses a simpler
|
||||
per-chunk abundance metric, a real-world Overworld baseline, a sample/work cap,
|
||||
and a saved authored base so modern servers remain bounded and restart-safe.
|
||||
The greater-than-400-chunk activation delay is retained. Because only newly
|
||||
generated chunks are sampled, old already-explored worlds may need substantial
|
||||
new exploration before their Overworld baseline is ready. A mod that mutates
|
||||
blocks after the chunk-load event may not be reflected in the first sample.
|
||||
|
||||
## Manual check handed to the player
|
||||
|
||||
The first focused GameTest run after adding the chunk-load listener stalled in
|
||||
its initial 50-test batch and was stopped. It is **not** a passing test result.
|
||||
Do not retry that stalled scenario automatically. In a disposable world:
|
||||
|
||||
1. Create one Age with an authored Diamond Block + Rocks (or Floating Islands)
|
||||
combination and a comparison Age using Stone for the same feature. Explore
|
||||
enough distinct chunks in each Age for `/rivencraft age instability` to show
|
||||
a profiled-block contribution. Explore the Overworld too if its baseline has
|
||||
not reached 400 chunks. The diamond Age should score higher and can gain
|
||||
provider cards; the stone Age should not get a diamond-block contribution.
|
||||
2. Leave and restart the world. Re-enter both Ages and compare their scores and
|
||||
provider IDs/levels. Reloading old chunks must not increase the sample
|
||||
count or score by itself. Generating more diamond-rich chunks may change the
|
||||
effective score and provider set; disabling instability must suppress their
|
||||
effects without erasing the profile.
|
||||
3. Check a naturally generated diamond-ore Age without authored diamond-block
|
||||
features. If its ore abundance is near the Overworld baseline, it should
|
||||
receive little or no ore contribution. Check that profiling does not make
|
||||
chunk loading noticeably stall, and report any exception or server hang.
|
||||
|
||||
Do not use a valued save for this check. The game jar builds, but live chunk
|
||||
profiling still needs this player-run validation before release.
|
||||
@@ -0,0 +1,95 @@
|
||||
# Milestone 6 instability regression and migration check (#73)
|
||||
|
||||
This is the release-slice acceptance record for instability, not a promise of
|
||||
general old-save compatibility. The latter remains issue #60. Run the focused
|
||||
archive with `./gradlew build runGameTestServer -ParchivedGameTestSuites=instability`;
|
||||
it includes the default smoke suite.
|
||||
For 0.5.8.10 on 2026-10-10, that dedicated GameTest server passed all 55 required tests
|
||||
with no optional content/client integrations installed (the required Dynamic
|
||||
Dimensions and Bad Packets dependencies were present). The full archive was not run;
|
||||
it has a previously documented storage stall, so do not count it as passing.
|
||||
The 0.5.8.11 run with live block profiling stalled in its initial batch and
|
||||
was stopped; it is **not** a passing result. The live profiling scenario is
|
||||
handed to the player in [the block-profile checklist](LIVE_BLOCK_INSTABILITY.md).
|
||||
|
||||
## Automated coverage
|
||||
|
||||
| Requirement | Existing default test or focused archive |
|
||||
| --- | --- |
|
||||
| Stable writing, defective writing, score explanations, repeated use of the same book | `AgePersistenceGameTests.instabilitySeparatesStableAndDefectiveWriting` |
|
||||
| Frozen score, age-scoped writing cost, random baseline | `AgePersistenceGameTests.randomBaselineAndBrightBalanceAreFrozen`, `auditedSymbolCostsAreCountedAndAgeScoped` |
|
||||
| Complete Age definition, score and provider-plan save/load | `AgePersistenceGameTests.authoredPlanRetainsResolvedMeaningAndAgeIdentity`; `AgeInstabilityRuntimeGameTests.selectionIsDeterministicAndFrozen` |
|
||||
| Old pre-scoring Ages, score-only saves, removed symbols, unavailable handlers | `AgePersistenceGameTests.missingRegistryEntryDoesNotReinterpretAnOldAge`, `instabilitySeparatesStableAndDefectiveWriting`; `AgeInstabilityRuntimeGameTests.savedPlanSurvivesAgeUpdatesAndMissingHandlers` |
|
||||
| Per-Age controls and changed config without score/plan reroll | `AgeInstabilityRuntimeGameTests.perAgeControlsPersistWithoutChangingScoresOrOtherAges`; `Milestone6RegressionGameTests.disablingEffectsCannotRerollFrozenPlan` |
|
||||
| Hazard cooldown and attempt sequence across saved-state reload | `AgeInstabilityRuntimeGameTests.hazardCooldownAndAttemptSequenceSurviveReload` |
|
||||
| Active-Age rotation, action/tick budget | `AgeInstabilityRuntimeGameTests.ageScopeRotationAndActionBudgetAreBounded` |
|
||||
| Multiplayer loaded-chunk-only candidate selection, deduplication and cap | `Milestone6RegressionGameTests.multiplayerCandidatesStayLoadedDeduplicatedAndCapped` |
|
||||
| Decay loaded-chunk target and spawn protection | `AgeDecayGameTests.targetMustRemainInChosenLoadedChunk`, `savedSpawnAndPlatformAreProtected` |
|
||||
| Explosion policy gates and protected blocks | `Milestone6RegressionGameTests.disabledGriefAndProtectedBlocksStayUntouched` |
|
||||
| No Overworld status or decay provider | `AgeStatusEffectGameTests.overworldCannotRunAnAgeStatusProvider`; `AgeDecayGameTests.overworldCannotRunDecayProvider` |
|
||||
|
||||
These tests exercise saved-data serialization and deterministic policies. They
|
||||
do **not** simulate a complete process restart, an actual multiplayer server,
|
||||
optional-mod installation, or real terrain and hazard visuals. The three new
|
||||
checks live only in the `instability` archive to avoid duplicating default tests.
|
||||
|
||||
## Migration outcome and known gaps
|
||||
|
||||
- Pre-scoring Milestone 5 Ages load with a neutral score and no effects; they
|
||||
are not retroactively rescored under current writing rules.
|
||||
- Score-only Ages receive a deterministic provider plan once from their saved
|
||||
score and Age seed. An already-saved score and plan retain their meaning when
|
||||
pages, handlers, or runtime config change. Unknown but syntactically valid
|
||||
provider IDs are preserved and skipped if their handler is unavailable.
|
||||
- Missing symbol definitions do not reinterpret a frozen instability score.
|
||||
That check is narrower than arbitrary missing biome, block, or worldgen
|
||||
registry entries: loading a world with removed data packs is not guaranteed.
|
||||
Broad save compatibility and migration remain tracked in #60.
|
||||
- In-process roundtrips cannot prove that Age dimensions reload correctly
|
||||
after a full stop/start. Check that in a real client/server world. Do not add
|
||||
another GameTest for it if it hits the documented storage stall; hand the
|
||||
exact scenario to the player instead.
|
||||
- The dedicated GameTest run establishes classloading with no optional runtime
|
||||
flags. It does not establish classloading with every optional integration
|
||||
installed, nor the reverse of removing one from an existing save.
|
||||
|
||||
## Manual in-game matrix
|
||||
|
||||
Use a fresh test world, then keep one save for the restart and data-pack checks.
|
||||
Record the seed, mod list, age name, and `/rivencraft age instability` output
|
||||
before and after each change. Do not deliberately remove a required registry
|
||||
entry from a valued world; copy the test save first.
|
||||
|
||||
1. Bind a low-instability book and a deliberately unstable book. Reuse each
|
||||
book and verify the Age name, dimension ID, score, selected providers and
|
||||
provider levels remain unchanged. Exit the Ages, stop Minecraft completely,
|
||||
restart and re-enter; compare the same diagnostic values.
|
||||
2. With two survival players in one unstable Age and a third player in the
|
||||
Overworld, verify effects stay in the Age, follow the Age players, and do
|
||||
not appear in the Overworld. Move both Age players away, let old chunks
|
||||
unload, and confirm hazards do not keep remote chunks loaded or operate
|
||||
there. Confirm controls on one Age do not alter a second Age.
|
||||
3. Disable global instability, then world mutation, then one provider. Verify
|
||||
the suppressed effect stops and the frozen score/plan do not change after
|
||||
re-enabling or restarting. With block destruction disabled, trigger an
|
||||
explosion in an expendable Age; check that arrival platforms, portals,
|
||||
block entities and protected blocks survive. Check lightning, explosion,
|
||||
decay, status-effect, burning, meteor and erosion visuals where selected.
|
||||
4. With Biomes O' Plenty or another TerraBlender biome mod, confirm recognized
|
||||
biome pages still author an Age and the instability diagnostics remain
|
||||
stable after restart. Repeat with Serene Seasons installed, then absent in
|
||||
a disposable copy; confirm its Age season behavior and that Rivencraft
|
||||
itself still loads. JEI should display the relevant pages and recipes when
|
||||
installed, while the mod works without it.
|
||||
5. Check the book preview separately with its fallback animation, Ponder/Create,
|
||||
and Immersive Portals when available. Opening a book should not change
|
||||
player location, instability diagnostics, or ambient audio in the actual
|
||||
Age. Do not install both season mods together for this matrix.
|
||||
6. On a copied save, remove or alter a **nonessential** data pack providing
|
||||
a writing symbol or optional handler, then reload. Existing saved scores
|
||||
and provider plans must not reroll. If a referenced worldgen registry entry
|
||||
prevents load, record it against issue #60 rather than treating #73's
|
||||
frozen-instability guarantee as general missing-registry support.
|
||||
|
||||
The matrix is guidance for a player-run pass; none of these six scenarios is
|
||||
claimed as completed by the automated result above.
|
||||
+18
-1
@@ -5,6 +5,22 @@ The world-generation, dimension, registry, networking, and rendering APIs have
|
||||
changed substantially, so the work is divided into independently testable
|
||||
milestones.
|
||||
|
||||
## Porting principles
|
||||
|
||||
The primary goal is to reproduce verified Mystcraft Legacy behavior as closely
|
||||
as practical. Legacy source and the supplied 0.13.7.06 build are the behavioral
|
||||
reference for grammar, probabilities, ordering, defaults, visuals, and gameplay
|
||||
effects. A difference should be deliberate and documented rather than inferred
|
||||
from modern implementation convenience.
|
||||
|
||||
Minecraft 1.21.1 has different world heights, registries, threading, networking,
|
||||
data-pack APIs, and server protection expectations. Where an exact port would be
|
||||
unsafe, technically impossible, or incompatible with current Minecraft,
|
||||
Rivencraft preserves the player-visible intent while using bounded modern
|
||||
mechanics. New features may extend Legacy when they fit Age writing and linking,
|
||||
but extensions must be identified separately from compatibility behavior and
|
||||
must not silently change existing saved Ages.
|
||||
|
||||
## Project tracking
|
||||
|
||||
Gitea is the source of truth for project status:
|
||||
@@ -42,7 +58,8 @@ acceptance issue and all required implementation issues are complete.
|
||||
TerraBlender and Serene Seasons integration. **Complete for the supported
|
||||
subset.** See the [acceptance record](MILESTONE_5_ACCEPTANCE.md) and
|
||||
[Legacy grammar audit](LEGACY_AGE_GRAMMAR_AUDIT.md).
|
||||
6. **Instability** — deterministic validation and server-safe effects. Start with the
|
||||
6. **Instability** — deterministic validation and server-safe effects. **In
|
||||
progress.** Start with the
|
||||
[Legacy instability audit](LEGACY_INSTABILITY_AUDIT.md), which separates
|
||||
source behavior from proposed 1.21.1 safety limits.
|
||||
7. **Structures and polish** — libraries, crystals, portals, recipes, models,
|
||||
|
||||
@@ -6,9 +6,9 @@ New Binder writing has at most one Link Panel plus 252 symbol pages (the current
|
||||
|
||||
The supported order follows the representable subset of the [Legacy grammar audit](LEGACY_AGE_GRAMMAR_AUDIT.md): terrain; zero or more biome pages; biome controller; weather; season; lighting; sky effects; zero or more period or phase modifiers; one celestial page; then zero or more features, each optionally preceded by a compatible material page. Biome pages precede the controller that consumes them, and celestial modifiers precede the celestial page. Terrain, controller, weather, season, lighting, sky, and celestial are single-choice categories; identical repeats are duplicates and differing values conflict. Repeated modifiers, biome pages, feature pages, and material pages are intentional and retain their order. An unpaired material page receives a seeded compatible feature during compilation. Angle modifiers remain recognized in the schema but are rejected at binding until a sky renderer can apply sun tilt.
|
||||
|
||||
Missing terrain, controller, weather, lighting, celestial, or the controller's minimum biome count is an **incomplete** warning, not an error: the compiler retains seed-selected traits for missing branches. An omitted terrain page uses a seed-selected profile compatible with authored feature pages, so changing the Age name cannot accidentally select Flat, Void, or Cave terrain for Rocks or Lakes. If no profile can support the writing, binding still rejects it. Native consumes no authored biome pages; Single consumes one; Tiled/Grid and Tiny–Huge require two, with seeded filler when pages are missing. From 0.5.1.0, known misplaced or repeated pages no longer block creation: the book keeps its original order, while the server repairs category order, uses the last single-choice controller, and stores a writing-instability score in the Age plan. A conflicting/repeated choice adds 500; an out-of-order page or misplaced modifier adds 100. Native ignores surplus authored biome pages and Single uses the first, with the conflict recorded as instability. These are Rivencraft's provisional penalties, not a claim of exact Legacy values for every symbol. Incorrectly placed pages are **not** red-highlighted; their warning remains available as a tooltip. Unknown IDs, schema-v1 display-only symbols, unavailable dependencies/profiles, unsupported semantic effects or feature/material pairs, missing/extra Link Panels, and oversized writing still reject a new Age. The Binder disables output for those fatal errors and shows a red page indication where applicable. Rejected inputs remain removable.
|
||||
Missing terrain, controller, weather, lighting, celestial, or the controller's minimum biome count is an **incomplete** warning, not an error: the compiler retains seed-selected traits for missing branches. An omitted terrain page uses a seed-selected profile compatible with authored feature pages, so changing the Age name cannot accidentally select Flat, Void, or Cave terrain for Rocks or Lakes. If no profile can support the writing, binding still rejects it. Native consumes no authored biome pages; Single consumes one; Tiled/Grid and Tiny–Huge require two, with seeded filler when pages are missing. From 0.5.1.0, known misplaced or repeated pages no longer block creation: the book keeps its original order, while the server repairs category order, uses the last single-choice controller, and stores a writing-instability score in the Age plan. A conflicting/repeated choice adds 500; an out-of-order page or misplaced modifier adds 100. Native ignores surplus authored biome pages and Single uses the first, with the conflict recorded as instability. Audited Legacy symbol modifiers also add 500 for each Bright Lighting page and 100 for each Mineshafts, Nether Fortresses, Strongholds, or Villages occurrence after the third. Modern structures configured with the same rule are Bastions, Trial Chambers, Ancient Cities, Shipwrecks, Ocean Ruins, Pillager Outposts, Ruined Portals, Nether Fossils, Buried Treasure, and Trail Ruins. Every repeated structure page increases that structure's placement rate: probability-based structures multiply their chance, grid-based structures use a denser grid, and Strongholds add more positions to each ring and more positions overall. One page retains the vanilla placement rate. Authored structures can generate outside their vanilla biome set; each structure-page occurrence that requires this override adds 100 instability. Seed completion selects compatible biomes where possible. Other feature pages have no direct symbol cost. Incorrectly placed pages are **not** red-highlighted; their warning remains available as a tooltip. Unknown IDs, schema-v1 display-only symbols, unavailable dependencies/profiles, unsupported semantic effects or feature/material pairs, missing/extra Link Panels, and oversized writing still reject a new Age. The Binder disables output for those fatal errors and shows a red page indication where applicable. Rejected inputs remain removable.
|
||||
|
||||
The plan stores the original writing order, the authoritative semantic value of each resolved symbol, the active repaired-page indexes, the writing-instability score, the Age seed, and a copy of the selected runtime profile. An explicit terrain page overrides random terrain selection; an omitted terrain uses a seed-selected compatible profile. The built-in Standard, Amplified, Cave, Island, Flat, and Void terrain pages select their matching generation resources. Age loading uses the frozen runtime profile and does not need the original symbol definition or runtime-profile JSON, though its referenced noise, biome-preset, and dimension-type registry entries must remain available. Existing bound books without plans are not reinterpreted. Page-free and Link-Panel-only books keep the pre-existing random path. Biome and environment pages affect new Ages, and the supported feature subset below is compiled into the same frozen plan. Runtime effects for a nonzero writing-instability score are not implemented yet.
|
||||
The plan stores the original writing order, the authoritative semantic value of each resolved symbol, the active repaired-page indexes, the writing-instability score, the Age seed, and a copy of the selected runtime profile. An explicit terrain page overrides random terrain selection; an omitted terrain uses a seed-selected compatible profile. The built-in Standard, Amplified, Cave, Island, Flat, and Void terrain pages select their matching generation resources. Age loading uses the frozen runtime profile and does not need the original symbol definition or runtime-profile JSON, though its referenced noise, biome-preset, and dimension-type registry entries must remain available. Existing bound books without plans are not reinterpreted. Page-free and Link-Panel-only books keep the pre-existing random path. Biome and environment pages affect new Ages, and the supported feature subset below is compiled into the same frozen plan. Nonzero instability can select a persisted provider plan; status effects, decay, lightning, explosions, meteors, burning, and test-enabled erosion run through the bounded Age-scoped scheduler described in [the runtime policy](INSTABILITY_RUNTIME.md).
|
||||
|
||||
## Supported feature pages (issue #35)
|
||||
|
||||
|
||||
+1
-1
@@ -36,7 +36,7 @@ mod_name=Rivencraft
|
||||
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
|
||||
mod_license=LGPL-3.0-or-later
|
||||
# The mod version. Rivencraft uses the x.y.z.b policy documented in README.md.
|
||||
mod_version=0.5.6.4
|
||||
mod_version=0.5.8.11
|
||||
immersive_portals_version=6.0.7
|
||||
terrablender_version=4.1.0.8
|
||||
serene_seasons_version_id=B6nTjh4b
|
||||
|
||||
@@ -24,6 +24,8 @@ import net.dnorberg.rivencraft.book.AgeWeatherService;
|
||||
import net.dnorberg.rivencraft.book.AgeInstabilityRuntime;
|
||||
import net.dnorberg.rivencraft.book.AgeStatusEffectProviders;
|
||||
import net.dnorberg.rivencraft.book.AgeDecayProviders;
|
||||
import net.dnorberg.rivencraft.book.AgeHazardProviders;
|
||||
import net.dnorberg.rivencraft.book.AgeEnvironmentalProviders;
|
||||
import net.dnorberg.rivencraft.book.AgeRuntimeProfiles;
|
||||
import net.dnorberg.rivencraft.writing.SymbolCatalog;
|
||||
import net.neoforged.bus.api.IEventBus;
|
||||
@@ -42,6 +44,8 @@ public final class Rivencraft {
|
||||
AgeDimensionService.register();
|
||||
AgeStatusEffectProviders.register();
|
||||
AgeDecayProviders.register();
|
||||
AgeHazardProviders.register();
|
||||
AgeEnvironmentalProviders.register();
|
||||
modContainer.registerConfig(ModConfig.Type.SERVER, RivencraftConfig.SPEC);
|
||||
modContainer.registerConfig(ModConfig.Type.CLIENT, RivencraftClientConfig.SPEC);
|
||||
modEventBus.addListener(ModNetworking::register);
|
||||
@@ -58,6 +62,11 @@ public final class Rivencraft {
|
||||
NeoForge.EVENT_BUS.addListener(BookStandConversionHandler::onRightClickBlock);
|
||||
NeoForge.EVENT_BUS.addListener(AgeWeatherService::onLevelTickPost);
|
||||
NeoForge.EVENT_BUS.addListener(AgeInstabilityRuntime::onLevelTickPost);
|
||||
NeoForge.EVENT_BUS.addListener(net.dnorberg.rivencraft.book.AgeBlockInstability::onChunkLoad);
|
||||
NeoForge.EVENT_BUS.addListener(net.dnorberg.rivencraft.book.AgeBlockInstability::onServerTickPost);
|
||||
NeoForge.EVENT_BUS.addListener(net.dnorberg.rivencraft.book.AgeBlockInstability::onServerStopping);
|
||||
NeoForge.EVENT_BUS.addListener(AgeEnvironmentalProviders::onLevelTickPost);
|
||||
NeoForge.EVENT_BUS.addListener(AgeEnvironmentalProviders::onLevelUnload);
|
||||
NeoForge.EVENT_BUS.addListener(AgeStatusEffectProviders::onServerTickPost);
|
||||
NeoForge.EVENT_BUS.addListener(AgeStatusEffectProviders::onEntityTravel);
|
||||
NeoForge.EVENT_BUS.addListener(AgeStatusEffectProviders::onPlayerChangedDimension);
|
||||
@@ -68,6 +77,7 @@ public final class Rivencraft {
|
||||
NeoForge.EVENT_BUS.addListener(AgeLifecycleEvents::onPlayerLoggedOut);
|
||||
NeoForge.EVENT_BUS.addListener(AgeLifecycleEvents::onServerStopping);
|
||||
NeoForge.EVENT_BUS.addListener(AgeInstabilityRuntime::onServerStopping);
|
||||
NeoForge.EVENT_BUS.addListener(AgeEnvironmentalProviders::onServerStopping);
|
||||
NeoForge.EVENT_BUS.addListener(AgeStatusEffectProviders::onServerStopping);
|
||||
NeoForge.EVENT_BUS.addListener(RivencraftCommands::register);
|
||||
NeoForge.EVENT_BUS.addListener(AgeRuntimeProfiles::register);
|
||||
|
||||
@@ -88,6 +88,9 @@ public record AgeBiomeSelection(AgeTraits.BiomeDistribution distribution, List<R
|
||||
Random countRandom = new Random(seed ^ 0x42494F4D45434F55L);
|
||||
while (target < maximum && countRandom.nextInt(3) != 0) target++;
|
||||
}
|
||||
completeStructureBiomes(writing, registries, availableBiomes, authored, distribution,
|
||||
selected, distinct, seed);
|
||||
target = Math.max(target, distinct.size());
|
||||
// An authored Void Age must not acquire The Void as an unrequested second biome.
|
||||
List<ResourceLocation> filler = profile.terrain() == AgeRuntimeProfile.Terrain.VOID && !authored.isEmpty()
|
||||
? new ArrayList<>() : new ArrayList<>(availableBiomes);
|
||||
@@ -103,6 +106,59 @@ public record AgeBiomeSelection(AgeTraits.BiomeDistribution distribution, List<R
|
||||
return new AgeBiomeSelection(distribution, selected);
|
||||
}
|
||||
|
||||
/** Seed-completed biome branches must be able to host every authored structure page. */
|
||||
private static void completeStructureBiomes(WritingGrammar.Result writing, RegistryAccess registries,
|
||||
List<ResourceLocation> available,
|
||||
List<ResourceLocation> authored,
|
||||
AgeTraits.BiomeDistribution distribution,
|
||||
List<ResourceLocation> selected,
|
||||
Set<ResourceLocation> distinct,
|
||||
long seed) {
|
||||
List<Set<ResourceLocation>> requirements = writing.symbols().stream()
|
||||
.filter(symbol -> symbol.semantics().role() == SymbolSemantics.Role.FEATURE)
|
||||
.map(symbol -> ((SymbolSemantics.ResourceValue) symbol.semantics().value()).id())
|
||||
.filter(AgeStructureSelection::feature)
|
||||
.filter(feature -> !AgeStructureSelection.dungeons(feature))
|
||||
.distinct()
|
||||
.map(feature -> AgeStructureSelection.compatibleBiomes(feature, registries))
|
||||
.filter(requirement -> !requirement.isEmpty())
|
||||
.toList();
|
||||
if (requirements.isEmpty()) return;
|
||||
|
||||
if (distribution == AgeTraits.BiomeDistribution.SINGLE) {
|
||||
if (!authored.isEmpty()) return;
|
||||
List<ResourceLocation> candidates = available.stream()
|
||||
.filter(candidate -> requirements.stream().allMatch(requirement -> requirement.contains(candidate)))
|
||||
.toList();
|
||||
if (candidates.isEmpty()) return;
|
||||
ResourceLocation selectedBiome = deterministicChoice(candidates, seed, 0x5354525543544249L);
|
||||
selected.clear();
|
||||
distinct.clear();
|
||||
selected.add(selectedBiome);
|
||||
distinct.add(selectedBiome);
|
||||
return;
|
||||
}
|
||||
|
||||
for (int index = 0; index < requirements.size(); index++) {
|
||||
Set<ResourceLocation> requirement = requirements.get(index);
|
||||
if (selected.stream().anyMatch(requirement::contains)) continue;
|
||||
List<ResourceLocation> candidates = available.stream()
|
||||
.filter(requirement::contains)
|
||||
.filter(candidate -> !distinct.contains(candidate))
|
||||
.toList();
|
||||
if (candidates.isEmpty()) continue;
|
||||
ResourceLocation selectedBiome = deterministicChoice(candidates, seed, 0x5354525543544249L + index);
|
||||
selected.add(selectedBiome);
|
||||
distinct.add(selectedBiome);
|
||||
}
|
||||
}
|
||||
|
||||
private static ResourceLocation deterministicChoice(List<ResourceLocation> choices, long seed, long salt) {
|
||||
List<ResourceLocation> shuffled = new ArrayList<>(choices);
|
||||
java.util.Collections.shuffle(shuffled, new Random(seed ^ salt));
|
||||
return shuffled.getFirst();
|
||||
}
|
||||
|
||||
public static List<ResourceLocation> eligible(RegistryAccess registries, AgeRuntimeProfile profile) {
|
||||
var registry = registries.lookupOrThrow(Registries.BIOME);
|
||||
if (isCave(profile)) {
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package net.dnorberg.rivencraft.book;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
import net.neoforged.neoforge.event.level.ChunkEvent;
|
||||
import net.neoforged.neoforge.event.server.ServerStoppingEvent;
|
||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||
|
||||
/** Legacy-style excess-block profiling; no chunks are generated or force-loaded for sampling. */
|
||||
public final class AgeBlockInstability {
|
||||
// Legacy's watched blocks and factor-1 values; modern ore variants share their parent weight.
|
||||
// Storage blocks are deliberate extensions, including the requested diamond-block case.
|
||||
private static final Map<ResourceLocation, Integer> WEIGHTS = weights();
|
||||
private static final int MAX_PENDING = 2048;
|
||||
private static final int SAMPLES_PER_TICK = 4;
|
||||
private static final Map<MinecraftServer, ArrayDeque<Pending>> PENDING = new java.util.WeakHashMap<>();
|
||||
|
||||
private AgeBlockInstability() {}
|
||||
|
||||
static int weight(ResourceLocation id) { return WEIGHTS.getOrDefault(id, 0); }
|
||||
|
||||
public static void onChunkLoad(ChunkEvent.Load event) {
|
||||
if (!event.isNewChunk() || !(event.getLevel() instanceof ServerLevel level)
|
||||
|| !(event.getChunk() instanceof LevelChunk chunk)) return;
|
||||
boolean overworld = level.dimension() == net.minecraft.world.level.Level.OVERWORLD;
|
||||
if (!overworld && !AgeInstabilityRuntime.isAgeDimension(level.dimension().location())) return;
|
||||
// Chunk-load callbacks can occur while chunk storage is updating. Defer saved-data
|
||||
// access to a bounded server-tick lane to avoid reentering that storage path.
|
||||
synchronized (PENDING) {
|
||||
var queue = PENDING.computeIfAbsent(level.getServer(), ignored -> new ArrayDeque<>());
|
||||
if (queue.size() < MAX_PENDING) queue.addLast(new Pending(level, chunk));
|
||||
}
|
||||
}
|
||||
|
||||
public static void onServerTickPost(ServerTickEvent.Post event) {
|
||||
for (int index = 0; index < SAMPLES_PER_TICK; index++) {
|
||||
Pending pending;
|
||||
synchronized (PENDING) {
|
||||
var queue = PENDING.get(event.getServer());
|
||||
pending = queue == null ? null : queue.pollFirst();
|
||||
}
|
||||
if (pending == null) return;
|
||||
var pos = pending.chunk().getPos();
|
||||
if (pending.level().getChunkSource().hasChunk(pos.x, pos.z))
|
||||
AgeBlockProfileSavedData.get(pending.level()).sample(pending.chunk());
|
||||
}
|
||||
}
|
||||
|
||||
public static void onServerStopping(ServerStoppingEvent event) {
|
||||
synchronized (PENDING) { PENDING.remove(event.getServer()); }
|
||||
}
|
||||
|
||||
/** Zero until the Age exceeds 400 samples and the baseline reaches 500. */
|
||||
static int score(AgeBlockProfileSavedData age, AgeBlockProfileSavedData baseline) {
|
||||
return score(age.totals(), age.count(), baseline.totals(), baseline.count());
|
||||
}
|
||||
|
||||
static int score(Map<ResourceLocation, Long> age, int ageChunks,
|
||||
Map<ResourceLocation, Long> baseline, int baselineChunks) {
|
||||
if (ageChunks < AgeBlockProfileSavedData.MIN_AGE_SAMPLES
|
||||
|| baselineChunks < AgeBlockProfileSavedData.MIN_BASELINE_SAMPLES) return 0;
|
||||
double result = 0;
|
||||
for (var entry : WEIGHTS.entrySet()) {
|
||||
double excess = age.getOrDefault(entry.getKey(), 0L) / (double) ageChunks
|
||||
- 1.05 * baseline.getOrDefault(entry.getKey(), 0L) / (double) baselineChunks;
|
||||
if (excess > 0) result += excess * entry.getValue();
|
||||
}
|
||||
return (int) Math.min(100_000, Math.round(result));
|
||||
}
|
||||
|
||||
public static int score(ServerLevel level, AgeDefinition age) {
|
||||
if (age.instability().version() < 2
|
||||
|| !AgeInstabilityRuntime.isAgeDimension(level.dimension().location())
|
||||
|| !age.dimensionId().equals(level.dimension().location())) return 0;
|
||||
return score(AgeBlockProfileSavedData.get(level),
|
||||
AgeBlockProfileSavedData.get(level.getServer().overworld()));
|
||||
}
|
||||
|
||||
public static int sampledChunks(ServerLevel level) {
|
||||
return AgeBlockProfileSavedData.get(level).count();
|
||||
}
|
||||
|
||||
public static int effectiveScore(ServerLevel level, AgeDefinition age) {
|
||||
return (int) Math.min(Integer.MAX_VALUE, (long) age.instability().score() + score(level, age));
|
||||
}
|
||||
|
||||
public static AgeInstabilityPlan effectivePlan(ServerLevel level, AgeDefinition age) {
|
||||
int blockScore = score(level, age);
|
||||
if (blockScore == 0) return age.instabilityPlan();
|
||||
int combined = effectiveScore(level, age);
|
||||
AgeInstability effective = new AgeInstability(AgeInstability.CURRENT_VERSION, combined,
|
||||
java.util.List.of(new AgeInstability.Contribution("effective_block_profile", -1, combined,
|
||||
"Saved writing score plus sampled excess blocks")));
|
||||
var selected = AgeInstabilityPlan.select(effective, age.seed());
|
||||
Map<ResourceLocation, Integer> levels = new java.util.LinkedHashMap<>();
|
||||
age.instabilityPlan().providers().forEach(provider -> levels.put(provider.id(), provider.level()));
|
||||
selected.providers().forEach(provider -> levels.merge(provider.id(), provider.level(), Math::max));
|
||||
return new AgeInstabilityPlan(AgeInstabilityPlan.CURRENT_VERSION,
|
||||
levels.entrySet().stream().map(entry ->
|
||||
new AgeInstabilityPlan.ProviderLevel(entry.getKey(), entry.getValue())).toList());
|
||||
}
|
||||
|
||||
private static Map<ResourceLocation, Integer> weights() {
|
||||
Map<ResourceLocation, Integer> values = new HashMap<>();
|
||||
add(values, 5, "coal_ore", "deepslate_coal_ore", "lapis_ore", "deepslate_lapis_ore");
|
||||
add(values, 60, "iron_ore", "deepslate_iron_ore");
|
||||
add(values, 200, "emerald_ore", "deepslate_emerald_ore");
|
||||
add(values, 250, "redstone_ore", "deepslate_redstone_ore");
|
||||
add(values, 750, "gold_ore", "deepslate_gold_ore");
|
||||
add(values, 4000, "diamond_ore", "deepslate_diamond_ore", "diamond_block");
|
||||
add(values, 20, "nether_quartz_ore");
|
||||
add(values, 50, "glowstone");
|
||||
values.put(ResourceLocation.parse("rivencraft:crystal_block"), 20);
|
||||
// Valuable blocks introduced after Legacy, and storage forms authorable in Rivencraft.
|
||||
add(values, 200, "emerald_block");
|
||||
add(values, 750, "gold_block", "raw_gold_block");
|
||||
add(values, 4000, "ancient_debris");
|
||||
add(values, 60, "iron_block", "raw_iron_block");
|
||||
add(values, 8000, "netherite_block");
|
||||
return Map.copyOf(values);
|
||||
}
|
||||
|
||||
private static void add(Map<ResourceLocation, Integer> values, int weight, String... paths) {
|
||||
for (String path : paths) values.put(ResourceLocation.withDefaultNamespace(path), weight);
|
||||
}
|
||||
|
||||
private record Pending(ServerLevel level, LevelChunk chunk) {}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package net.dnorberg.rivencraft.book;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.util.datafix.DataFixTypes;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
import net.minecraft.world.level.saveddata.SavedData;
|
||||
|
||||
/** Persistent, bounded samples of generated block abundance for one dimension. */
|
||||
public final class AgeBlockProfileSavedData extends SavedData {
|
||||
static final int MIN_AGE_SAMPLES = 401;
|
||||
static final int MIN_BASELINE_SAMPLES = 500;
|
||||
static final int MAX_SAMPLES = 1024;
|
||||
private static final Factory<AgeBlockProfileSavedData> FACTORY = new Factory<>(
|
||||
AgeBlockProfileSavedData::new, AgeBlockProfileSavedData::load, DataFixTypes.SAVED_DATA_MAP_DATA);
|
||||
|
||||
private final Map<Long, Map<ResourceLocation, Integer>> samples = new HashMap<>();
|
||||
private final Map<ResourceLocation, Long> totals = new HashMap<>();
|
||||
|
||||
AgeBlockProfileSavedData() {}
|
||||
|
||||
static AgeBlockProfileSavedData get(ServerLevel level) {
|
||||
return level.getDataStorage().computeIfAbsent(FACTORY, "rivencraft_block_profile");
|
||||
}
|
||||
|
||||
int count() { return samples.size(); }
|
||||
|
||||
Map<ResourceLocation, Long> totals() { return Map.copyOf(totals); }
|
||||
|
||||
boolean sample(LevelChunk chunk) {
|
||||
if (samples.size() >= MAX_SAMPLES || samples.containsKey(chunk.getPos().toLong())) return false;
|
||||
Map<ResourceLocation, Integer> counts = new HashMap<>();
|
||||
for (var section : chunk.getSections()) {
|
||||
if (section.hasOnlyAir()) continue;
|
||||
section.getStates().count((state, amount) -> {
|
||||
ResourceLocation id = BuiltInRegistries.BLOCK.getKey(state.getBlock());
|
||||
if (AgeBlockInstability.weight(id) > 0) counts.merge(id, amount, Integer::sum);
|
||||
});
|
||||
}
|
||||
add(chunk.getPos(), counts);
|
||||
return true;
|
||||
}
|
||||
|
||||
void add(ChunkPos pos, Map<ResourceLocation, Integer> counts) {
|
||||
if (samples.size() >= MAX_SAMPLES || samples.containsKey(pos.toLong())) return;
|
||||
samples.put(pos.toLong(), Map.copyOf(counts));
|
||||
counts.forEach((id, amount) -> totals.merge(id, amount.longValue(), Long::sum));
|
||||
setDirty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompoundTag save(CompoundTag tag, HolderLookup.Provider registries) {
|
||||
ListTag entries = new ListTag();
|
||||
for (var sample : samples.entrySet()) {
|
||||
CompoundTag entry = new CompoundTag();
|
||||
entry.putLong("Chunk", sample.getKey());
|
||||
CompoundTag blocks = new CompoundTag();
|
||||
sample.getValue().forEach((id, amount) -> blocks.putInt(id.toString(), amount));
|
||||
entry.put("Blocks", blocks);
|
||||
entries.add(entry);
|
||||
}
|
||||
tag.put("Samples", entries);
|
||||
return tag;
|
||||
}
|
||||
|
||||
static AgeBlockProfileSavedData load(CompoundTag tag, HolderLookup.Provider registries) {
|
||||
AgeBlockProfileSavedData data = new AgeBlockProfileSavedData();
|
||||
ListTag entries = tag.getList("Samples", CompoundTag.TAG_COMPOUND);
|
||||
for (int index = 0; index < Math.min(entries.size(), MAX_SAMPLES); index++) {
|
||||
CompoundTag entry = entries.getCompound(index);
|
||||
CompoundTag blocks = entry.getCompound("Blocks");
|
||||
Map<ResourceLocation, Integer> counts = new HashMap<>();
|
||||
for (String key : blocks.getAllKeys()) {
|
||||
ResourceLocation id = ResourceLocation.tryParse(key);
|
||||
if (id != null && AgeBlockInstability.weight(id) > 0 && blocks.getInt(key) > 0)
|
||||
counts.put(id, blocks.getInt(key));
|
||||
}
|
||||
data.add(new ChunkPos(entry.getLong("Chunk")), counts);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,8 @@ public final class AgeDecayProviders {
|
||||
AgeDefinition age = AgeRegistrySavedData.get(level).findByDimension(level.dimension().location()).orElse(null);
|
||||
if (age == null) return -1;
|
||||
ResourceLocation id = id("decay" + color.getSerializedName());
|
||||
if (!RivencraftConfig.instabilityEnabled() || !AgeInstabilityControls.get(level).enabled(age.id())
|
||||
|| !RivencraftConfig.instabilityProviderEnabled(id)) return -1;
|
||||
int changed = 0;
|
||||
for (int i = 0; i < Math.min(count, 32); i++) {
|
||||
AgeInstabilityRuntime.Budget budget = new AgeInstabilityRuntime.Budget(1);
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
package net.dnorberg.rivencraft.book;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.WeakHashMap;
|
||||
import net.dnorberg.rivencraft.Rivencraft;
|
||||
import net.dnorberg.rivencraft.block.DecayBlock;
|
||||
import net.dnorberg.rivencraft.config.RivencraftConfig;
|
||||
import net.dnorberg.rivencraft.registry.ModSounds;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.particles.ParticleTypes;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.entity.EntityTypeTest;
|
||||
import net.minecraft.world.level.levelgen.Heightmap;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
import net.neoforged.neoforge.common.util.BlockSnapshot;
|
||||
import net.neoforged.neoforge.common.util.FakePlayerFactory;
|
||||
import net.neoforged.neoforge.event.level.BlockEvent;
|
||||
import net.neoforged.neoforge.event.level.LevelEvent;
|
||||
import net.neoforged.neoforge.event.server.ServerStoppingEvent;
|
||||
import net.neoforged.neoforge.event.tick.LevelTickEvent;
|
||||
|
||||
/** Meteor, active Legacy burning, and test-enabled Legacy erosion. */
|
||||
public final class AgeEnvironmentalProviders {
|
||||
private static final ResourceLocation METEORS = id("meteors");
|
||||
private static final ResourceLocation BURNING = id("burning");
|
||||
private static final ResourceLocation EROSION = id("erosion");
|
||||
private static final int METEOR_FLIGHT_TICKS = 30;
|
||||
private static final int MAX_ACTIVE_AGES = 16;
|
||||
private static final Direction[] FLUID_SIDES = {
|
||||
Direction.UP, Direction.NORTH, Direction.SOUTH, Direction.EAST, Direction.WEST
|
||||
};
|
||||
private static final Map<ServerLevel, Meteor> ACTIVE = new WeakHashMap<>();
|
||||
|
||||
private AgeEnvironmentalProviders() {}
|
||||
|
||||
public static void register() {
|
||||
AgeInstabilityRuntime.register(METEORS, false, AgeEnvironmentalProviders::apply);
|
||||
AgeInstabilityRuntime.register(BURNING, false, AgeEnvironmentalProviders::apply);
|
||||
AgeInstabilityRuntime.register(EROSION, true, AgeEnvironmentalProviders::apply);
|
||||
}
|
||||
|
||||
/** Operator test pulse; bypasses chance but never Age, loading, policy, or cooldown checks. */
|
||||
public static int pulseForTesting(ServerPlayer player, String effect) {
|
||||
ServerLevel level = player.serverLevel();
|
||||
if (!AgeInstabilityRuntime.isAgeDimension(level.dimension().location())) return -1;
|
||||
AgeDefinition age = AgeRegistrySavedData.get(level).findByDimension(level.dimension().location()).orElse(null);
|
||||
if (age == null) return -1;
|
||||
if (!RivencraftConfig.instabilityEnabled() || !AgeInstabilityControls.get(level).enabled(age.id())
|
||||
|| !RivencraftConfig.instabilityProviderEnabled(ResourceLocation.fromNamespaceAndPath(
|
||||
Rivencraft.MOD_ID, effect.equals("meteor") ? "meteors" : effect))) return 0;
|
||||
List<ChunkPos> chunks = AgeHazardProviders.loadedChunksNearPlayers(level, 16);
|
||||
if (chunks.isEmpty()) return 0;
|
||||
var context = new AgeInstabilityRuntime.Context(level, age, chunks,
|
||||
level.getServer().getTickCount(), new AgeInstabilityRuntime.Budget(1));
|
||||
return switch (effect) {
|
||||
case "meteor" -> RivencraftConfig.meteorEnabled() && scheduleMeteor(context, 1, true) ? 1 : 0;
|
||||
case "burning" -> {
|
||||
if (!RivencraftConfig.scorchEnabled() || !RivencraftConfig.scorchPlayers()
|
||||
|| !eligibleScorch(context, player)) yield 0;
|
||||
// Vanilla extinguishes this fire on the next entity tick in rain or water.
|
||||
// Report that explicitly instead of claiming the test pulse worked.
|
||||
if (player.isInWaterRainOrBubble()) yield -2;
|
||||
player.igniteForSeconds(4);
|
||||
yield 1;
|
||||
}
|
||||
case "erosion" -> {
|
||||
if (!RivencraftConfig.erosionEnabled() || !AgeHazardProviders.canMutate(level)
|
||||
|| AgeBlockInstability.effectiveScore(level, age) < InstabilityProviderCatalog.Deck.DESTRUCTIVE.entryCost()
|
||||
|| !(player.pick(6.0, 0.0F, false) instanceof BlockHitResult hit)) yield 0;
|
||||
BlockPos pos = hit.getBlockPos();
|
||||
yield erodeAt(context, pos) ? 1 : 0;
|
||||
}
|
||||
default -> -1;
|
||||
};
|
||||
}
|
||||
|
||||
static boolean isEnvironmental(ResourceLocation id) {
|
||||
return METEORS.equals(id) || BURNING.equals(id) || EROSION.equals(id);
|
||||
}
|
||||
|
||||
static void tickPlanned(ServerLevel level, AgeDefinition age, long tick) {
|
||||
List<AgeInstabilityPlan.ProviderLevel> cards = AgeBlockInstability.effectivePlan(level, age).providers().stream()
|
||||
.filter(card -> isEnvironmental(card.id())).toList();
|
||||
boolean optInErosion = RivencraftConfig.erosionEnabled()
|
||||
&& AgeBlockInstability.effectiveScore(level, age) >= InstabilityProviderCatalog.Deck.DESTRUCTIVE.entryCost();
|
||||
if (cards.isEmpty() && !optInErosion) return;
|
||||
List<ChunkPos> chunks = AgeHazardProviders.loadedChunksNearPlayers(level,
|
||||
RivencraftConfig.hazardsMaxChunks());
|
||||
if (chunks.isEmpty()) return;
|
||||
for (AgeInstabilityPlan.ProviderLevel card : cards) {
|
||||
int maximum = BURNING.equals(card.id()) ? RivencraftConfig.scorchMaxTargets() : 1;
|
||||
var context = new AgeInstabilityRuntime.Context(level, age, chunks, tick,
|
||||
new AgeInstabilityRuntime.Budget(maximum));
|
||||
AgeInstabilityRuntime.invoke(context, card.id(), card.level());
|
||||
}
|
||||
if (optInErosion && cards.stream().noneMatch(card -> EROSION.equals(card.id()))) {
|
||||
var context = new AgeInstabilityRuntime.Context(level, age, chunks, tick,
|
||||
new AgeInstabilityRuntime.Budget(1));
|
||||
AgeInstabilityRuntime.invoke(context, EROSION, 1);
|
||||
}
|
||||
}
|
||||
|
||||
static void apply(AgeInstabilityRuntime.Context context, ResourceLocation id, int effectiveLevel) {
|
||||
if (!matchesAge(context.age(), context.level().dimension().location())
|
||||
|| context.loadedChunks().isEmpty()) return;
|
||||
if (METEORS.equals(id)) scheduleMeteor(context, effectiveLevel, false);
|
||||
else if (BURNING.equals(id)) scorch(context, effectiveLevel);
|
||||
else if (EROSION.equals(id)) erode(context);
|
||||
}
|
||||
|
||||
static boolean matchesAge(AgeDefinition age, ResourceLocation dimension) {
|
||||
return AgeInstabilityRuntime.isAgeDimension(dimension) && age.dimensionId().equals(dimension);
|
||||
}
|
||||
|
||||
private static boolean scheduleMeteor(AgeInstabilityRuntime.Context context, int effectiveLevel, boolean force) {
|
||||
if (!RivencraftConfig.meteorEnabled() || ACTIVE.containsKey(context.level())
|
||||
|| ACTIVE.size() >= MAX_ACTIVE_AGES) return false;
|
||||
AgeHazardSavedData data = AgeHazardSavedData.get(context.level());
|
||||
long gameTime = context.level().getGameTime();
|
||||
if (!data.meteorReady(gameTime, 200)) return false;
|
||||
Random random = new Random(context.age().seed() ^ data.nextAttempt() * 0xD1B54A32D192ED03L
|
||||
^ METEORS.hashCode());
|
||||
if (!force && random.nextDouble() >= AgeHazardProviders.legacyChance(context.loadedChunks().size(),
|
||||
RivencraftConfig.instabilityCooldown(), effectiveLevel, 50000)) return false;
|
||||
int start = random.nextInt(context.loadedChunks().size());
|
||||
for (int offset = 0; offset < Math.min(16, context.loadedChunks().size()); offset++) {
|
||||
ChunkPos chunk = context.loadedChunks().get((start + offset) % context.loadedChunks().size());
|
||||
int x = chunk.getMinBlockX() + 6 + random.nextInt(4);
|
||||
int z = chunk.getMinBlockZ() + 6 + random.nextInt(4);
|
||||
int surfaceY = context.level().getHeight(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, x, z);
|
||||
BlockPos impact = new BlockPos(x, surfaceY, z);
|
||||
if (surfaceY >= context.level().getMaxBuildHeight() - 8
|
||||
|| !AgeHazardProviders.safeTarget(context, impact, 8)) continue;
|
||||
if (!context.budget().claim()) return false;
|
||||
int startY = Math.min(context.level().getMaxBuildHeight() - 2, surfaceY + 48);
|
||||
data.recordMeteor(gameTime);
|
||||
ACTIVE.put(context.level(), new Meteor(chunk, impact, startY, METEOR_FLIGHT_TICKS));
|
||||
context.level().playSound(null, impact, ModSounds.METEOR_ROAR.get(), SoundSource.WEATHER, 2.0F, 1.0F);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void onLevelTickPost(LevelTickEvent.Post event) {
|
||||
if (!(event.getLevel() instanceof ServerLevel level)) return;
|
||||
Meteor meteor = ACTIVE.get(level);
|
||||
if (meteor == null) return;
|
||||
if (!RivencraftConfig.instabilityEnabled() || !RivencraftConfig.meteorEnabled()
|
||||
|| !AgeInstabilityRuntime.isAgeDimension(level.dimension().location())
|
||||
|| level.players().isEmpty()
|
||||
|| !level.getChunkSource().hasChunk(meteor.chunk().x, meteor.chunk().z)) {
|
||||
ACTIVE.remove(level);
|
||||
return;
|
||||
}
|
||||
AgeDefinition age = AgeRegistrySavedData.get(level).findByDimension(level.dimension().location()).orElse(null);
|
||||
if (age == null || !AgeInstabilityControls.get(level).enabled(age.id())
|
||||
|| !RivencraftConfig.instabilityProviderEnabled(METEORS)) {
|
||||
ACTIVE.remove(level);
|
||||
return;
|
||||
}
|
||||
int remaining = meteor.remaining() - 1;
|
||||
if (remaining <= 0) {
|
||||
ACTIVE.remove(level); // clear before impact so an exception cannot replay it
|
||||
AgeHazardProviders.explodeBounded(level, age, meteor.chunk(), meteor.impact(),
|
||||
RivencraftConfig.meteorBlockDamage(), RivencraftConfig.meteorPlayerDamage(),
|
||||
RivencraftConfig.meteorFire(), RivencraftConfig.meteorMaxBlocks(),
|
||||
RivencraftConfig.meteorMaxEntities(), RivencraftConfig.meteorMaxDamage(), 3);
|
||||
return;
|
||||
}
|
||||
double progress = 1.0 - remaining / (double) METEOR_FLIGHT_TICKS;
|
||||
double y = meteor.startY() + (meteor.impact().getY() - meteor.startY()) * progress;
|
||||
double x = meteor.impact().getX() + 0.5 + (1.0 - progress) * 2.0;
|
||||
double z = meteor.impact().getZ() + 0.5 + (1.0 - progress) * 2.0;
|
||||
level.sendParticles(ParticleTypes.FLAME, x, y, z, 5, 0.25, 0.25, 0.25, 0.01);
|
||||
level.sendParticles(ParticleTypes.LARGE_SMOKE, x, y, z, 2, 0.3, 0.3, 0.3, 0.02);
|
||||
ACTIVE.put(level, new Meteor(meteor.chunk(), meteor.impact(), meteor.startY(), remaining));
|
||||
}
|
||||
|
||||
public static void onServerStopping(ServerStoppingEvent event) {
|
||||
ACTIVE.clear(); // an interrupted descent is cancelled, never replayed after restart
|
||||
}
|
||||
|
||||
public static void onLevelUnload(LevelEvent.Unload event) {
|
||||
if (event.getLevel() instanceof ServerLevel level) ACTIVE.remove(level);
|
||||
}
|
||||
|
||||
private static void scorch(AgeInstabilityRuntime.Context context, int effectiveLevel) {
|
||||
if (!RivencraftConfig.scorchEnabled() || RivencraftConfig.scorchMaxTargets() == 0) return;
|
||||
ServerLevel level = context.level();
|
||||
Random random = new Random(context.age().seed() ^ AgeHazardSavedData.get(level).nextAttempt()
|
||||
* 0x9E3779B97F4A7C15L ^ BURNING.hashCode());
|
||||
int start = random.nextInt(context.loadedChunks().size());
|
||||
int affected = 0;
|
||||
for (int offset = 0; offset < Math.min(8, context.loadedChunks().size()); offset++) {
|
||||
ChunkPos chunk = context.loadedChunks().get((start + offset) % context.loadedChunks().size());
|
||||
AABB bounds = new AABB(chunk.getMinBlockX(), level.getMinBuildHeight(), chunk.getMinBlockZ(),
|
||||
chunk.getMaxBlockX() + 1, level.getMaxBuildHeight(), chunk.getMaxBlockZ() + 1);
|
||||
List<LivingEntity> candidates = new ArrayList<>();
|
||||
level.getEntities(EntityTypeTest.forClass(LivingEntity.class), bounds,
|
||||
entity -> eligibleScorch(context, entity), candidates, 8);
|
||||
candidates.sort(Comparator.comparing(Entity::getUUID));
|
||||
for (LivingEntity entity : candidates) {
|
||||
if (affected >= RivencraftConfig.scorchMaxTargets() || context.budget().remaining() == 0) return;
|
||||
// Legacy sampled each chunk each tick with a 1/10 gate. With 20 ticks/pass this
|
||||
// gives at least one opportunity for nearly every inspected loaded chunk.
|
||||
if (random.nextDouble() >= AgeHazardProviders.legacyChance(1,
|
||||
RivencraftConfig.instabilityCooldown(), 1, 10)) continue;
|
||||
if (!context.budget().claim()) return;
|
||||
entity.igniteForSeconds(Math.min(12, 4 * effectiveLevel));
|
||||
affected++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean eligibleScorch(AgeInstabilityRuntime.Context context, LivingEntity entity) {
|
||||
if (!entity.isAlive() || entity.isRemoved() || entity.level() != context.level()
|
||||
|| !context.level().canSeeSky(entity.blockPosition())
|
||||
|| AgeDecayProviders.isSpawnProtected(context.age(), entity.blockPosition())) return false;
|
||||
if (entity instanceof Player player) return RivencraftConfig.scorchPlayers()
|
||||
&& !player.isCreative() && !player.isSpectator();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void erode(AgeInstabilityRuntime.Context context) {
|
||||
if (!RivencraftConfig.erosionEnabled() || !AgeHazardProviders.canMutate(context.level())) return;
|
||||
ServerLevel level = context.level();
|
||||
Random random = new Random(context.age().seed() ^ AgeHazardSavedData.get(level).nextAttempt()
|
||||
* 0xC2B2AE3D27D4EB4FL ^ EROSION.hashCode());
|
||||
for (int attempt = 0; attempt < 8; attempt++) {
|
||||
ChunkPos chunk = context.loadedChunks().get(random.nextInt(context.loadedChunks().size()));
|
||||
int x = chunk.getMinBlockX() + random.nextInt(16);
|
||||
int z = chunk.getMinBlockZ() + random.nextInt(16);
|
||||
int y = level.getMinBuildHeight() + 1 + random.nextInt(level.getHeight() - 2);
|
||||
if (erodeAt(context, new BlockPos(x, y, z))) return;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean erodeAt(AgeInstabilityRuntime.Context context, BlockPos pos) {
|
||||
ServerLevel level = context.level();
|
||||
if (!AgeDecayProviders.isLoadedTarget(level, context.loadedChunks(), pos)
|
||||
|| AgeDecayProviders.isSpawnProtected(context.age(), pos)) return false;
|
||||
BlockState prior = level.getBlockState(pos);
|
||||
if (!AgeDecayProviders.canReplace(level, pos, prior, DecayBlock.Color.BLUE)) return false;
|
||||
for (Direction direction : FLUID_SIDES) {
|
||||
BlockPos neighbor = pos.relative(direction);
|
||||
if (!AgeDecayProviders.isLoadedTarget(level, context.loadedChunks(), neighbor)) continue;
|
||||
var fluid = level.getFluidState(neighbor);
|
||||
if (fluid.isSource() && replaceFluid(context, pos, prior, fluid.createLegacyBlock())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean replaceFluid(AgeInstabilityRuntime.Context context, BlockPos pos,
|
||||
BlockState prior, BlockState fluidBlock) {
|
||||
ServerLevel level = context.level();
|
||||
var actor = FakePlayerFactory.getMinecraft(level);
|
||||
actor.setPos(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5);
|
||||
if (!prior.isAir()) {
|
||||
var breaking = new BlockEvent.BreakEvent(level, pos, prior, actor);
|
||||
NeoForge.EVENT_BUS.post(breaking);
|
||||
if (breaking.isCanceled()) return false;
|
||||
}
|
||||
if (level.getBlockState(pos) != prior || !context.budget().claim()) return false;
|
||||
var snapshot = BlockSnapshot.create(level.dimension(), level, pos);
|
||||
if (!level.setBlock(pos, fluidBlock, 3)) return false;
|
||||
var placing = new BlockEvent.EntityPlaceEvent(snapshot, prior, actor);
|
||||
NeoForge.EVENT_BUS.post(placing);
|
||||
if (placing.isCanceled()) {
|
||||
snapshot.restore();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static ResourceLocation id(String path) {
|
||||
return ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path);
|
||||
}
|
||||
|
||||
private record Meteor(ChunkPos chunk, BlockPos impact, int startY, int remaining) {}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
package net.dnorberg.rivencraft.book;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Predicate;
|
||||
import net.dnorberg.rivencraft.Rivencraft;
|
||||
import net.dnorberg.rivencraft.config.RivencraftConfig;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.tags.BlockTags;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.LightningBolt;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.Explosion;
|
||||
import net.minecraft.world.level.ExplosionDamageCalculator;
|
||||
import net.minecraft.world.level.GameRules;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.levelgen.Heightmap;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
import net.neoforged.neoforge.common.util.FakePlayerFactory;
|
||||
import net.neoforged.neoforge.event.level.BlockEvent;
|
||||
|
||||
/** Legacy hazard cards, with one loaded-chunk event and explicit damage budgets. */
|
||||
public final class AgeHazardProviders {
|
||||
private static final ResourceLocation LIGHTNING = id("lightning");
|
||||
private static final ResourceLocation EXPLOSIONS = id("explosions");
|
||||
|
||||
private AgeHazardProviders() {}
|
||||
|
||||
public static void register() {
|
||||
// Visuals and entity damage remain available when block mutation is disabled.
|
||||
AgeInstabilityRuntime.register(LIGHTNING, false, AgeHazardProviders::apply);
|
||||
AgeInstabilityRuntime.register(EXPLOSIONS, false, AgeHazardProviders::apply);
|
||||
}
|
||||
|
||||
static boolean isHazard(ResourceLocation id) {
|
||||
return LIGHTNING.equals(id) || EXPLOSIONS.equals(id);
|
||||
}
|
||||
|
||||
/** Roll every selected hazard card each scheduler pass, independently of other providers. */
|
||||
static void tickPlanned(ServerLevel level, AgeDefinition age, long tick) {
|
||||
if (!RivencraftConfig.hazardsEnabled()) return;
|
||||
List<AgeInstabilityPlan.ProviderLevel> hazards = AgeBlockInstability.effectivePlan(level, age).providers().stream()
|
||||
.filter(provider -> isHazard(provider.id())).toList();
|
||||
if (hazards.isEmpty()) return;
|
||||
List<ChunkPos> chunks = loadedChunksNearPlayers(level, RivencraftConfig.hazardsMaxChunks());
|
||||
if (chunks.isEmpty()) return;
|
||||
for (AgeInstabilityPlan.ProviderLevel hazard : hazards) {
|
||||
var context = new AgeInstabilityRuntime.Context(level, age, chunks, tick,
|
||||
new AgeInstabilityRuntime.Budget(1));
|
||||
AgeInstabilityRuntime.invoke(context, hazard.id(), hazard.level());
|
||||
}
|
||||
}
|
||||
|
||||
static List<ChunkPos> loadedChunksNearPlayers(ServerLevel level, int maximum) {
|
||||
List<ChunkPos> players = level.players().stream()
|
||||
.sorted(Comparator.comparing(Entity::getUUID))
|
||||
.map(ServerPlayer::chunkPosition).toList();
|
||||
return candidateChunks(players, maximum,
|
||||
chunk -> level.getChunkSource().hasChunk(chunk.x, chunk.z));
|
||||
}
|
||||
|
||||
/** Pure candidate selection; the caller's predicate must only report already-loaded chunks. */
|
||||
static List<ChunkPos> candidateChunks(List<ChunkPos> players, int maximum,
|
||||
Predicate<ChunkPos> loaded) {
|
||||
if (maximum <= 0) return List.of();
|
||||
Set<ChunkPos> chunks = new LinkedHashSet<>();
|
||||
for (int radius = 0; radius <= 4; radius++) {
|
||||
for (int dx = -radius; dx <= radius; dx++) {
|
||||
for (int dz = -radius; dz <= radius; dz++) {
|
||||
if (Math.max(Math.abs(dx), Math.abs(dz)) != radius) continue;
|
||||
for (ChunkPos center : players) {
|
||||
int x = center.x + dx;
|
||||
int z = center.z + dz;
|
||||
ChunkPos candidate = new ChunkPos(x, z);
|
||||
if (loaded.test(candidate)) chunks.add(candidate);
|
||||
if (chunks.size() >= maximum) return List.copyOf(chunks);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.copyOf(chunks);
|
||||
}
|
||||
|
||||
/** Operator-only test pulse; skips the random roll, not Age, cooldown, or safety checks. */
|
||||
public static int pulseForTesting(ServerPlayer player, boolean lightning) {
|
||||
ServerLevel level = player.serverLevel();
|
||||
if (!RivencraftConfig.hazardsEnabled()
|
||||
|| !AgeInstabilityRuntime.isAgeDimension(level.dimension().location())) return -1;
|
||||
AgeDefinition age = AgeRegistrySavedData.get(level).findByDimension(level.dimension().location()).orElse(null);
|
||||
if (age == null) return -1;
|
||||
if (!RivencraftConfig.instabilityEnabled() || !AgeInstabilityControls.get(level).enabled(age.id())
|
||||
|| !RivencraftConfig.instabilityProviderEnabled(lightning ? LIGHTNING : EXPLOSIONS)) return -1;
|
||||
AgeHazardSavedData data = AgeHazardSavedData.get(level);
|
||||
if (!data.ready(lightning, level.getGameTime(), RivencraftConfig.hazardsMinInterval())) return 0;
|
||||
ChunkPos center = player.chunkPosition();
|
||||
for (int dx = -1; dx <= 1; dx++) {
|
||||
for (int dz = -1; dz <= 1; dz++) {
|
||||
ChunkPos chunk = new ChunkPos(center.x + dx, center.z + dz);
|
||||
if (!level.getChunkSource().hasChunk(chunk.x, chunk.z)) continue;
|
||||
int x = chunk.getMinBlockX() + 8;
|
||||
int z = chunk.getMinBlockZ() + 8;
|
||||
int y = lightning ? level.getHeight(Heightmap.Types.MOTION_BLOCKING, x, z)
|
||||
: player.getBlockY();
|
||||
BlockPos pos = new BlockPos(x, y, z);
|
||||
var context = new AgeInstabilityRuntime.Context(level, age, List.of(chunk),
|
||||
level.getServer().getTickCount(), new AgeInstabilityRuntime.Budget(1));
|
||||
if (!safeTarget(context, pos, 8)) continue;
|
||||
data.nextAttempt();
|
||||
data.record(lightning, level.getGameTime());
|
||||
if (lightning) strike(level, age, chunk, pos);
|
||||
else explode(level, age, chunk, pos);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void apply(AgeInstabilityRuntime.Context context, ResourceLocation id, int effectiveLevel) {
|
||||
ServerLevel level = context.level();
|
||||
if (!RivencraftConfig.hazardsEnabled() || context.loadedChunks().isEmpty()
|
||||
|| !AgeInstabilityRuntime.isAgeDimension(level.dimension().location())
|
||||
|| !context.age().dimensionId().equals(level.dimension().location())) return;
|
||||
boolean lightning = id.equals(LIGHTNING);
|
||||
if (!lightning && !id.equals(EXPLOSIONS)) return;
|
||||
AgeHazardSavedData data = AgeHazardSavedData.get(level);
|
||||
long gameTime = level.getGameTime();
|
||||
if (!data.ready(lightning, gameTime, RivencraftConfig.hazardsMinInterval())) return;
|
||||
Random random = new Random(context.age().seed() ^ data.nextAttempt() * 0x9E3779B97F4A7C15L
|
||||
^ id.hashCode());
|
||||
int legacyDenominator = lightning ? level.isRaining() && level.isThundering() ? 5000 : 100000 : 1000;
|
||||
// Legacy rolled once per chunk per tick; the shared scheduler visits this Age every >=20 ticks.
|
||||
double chance = legacyChance(context.loadedChunks().size(), RivencraftConfig.instabilityCooldown(),
|
||||
effectiveLevel, legacyDenominator);
|
||||
if (random.nextDouble() >= chance) return;
|
||||
ChunkPos chunk = context.loadedChunks().get(random.nextInt(context.loadedChunks().size()));
|
||||
int margin = lightning ? 2 : 6;
|
||||
int x = chunk.getMinBlockX() + margin + random.nextInt(16 - margin * 2);
|
||||
int z = chunk.getMinBlockZ() + margin + random.nextInt(16 - margin * 2);
|
||||
int y = lightning ? level.getHeight(Heightmap.Types.MOTION_BLOCKING, x, z)
|
||||
: level.getMinBuildHeight() + 1 + random.nextInt(level.getHeight() - 2);
|
||||
BlockPos pos = new BlockPos(x, y, z);
|
||||
if (!safeTarget(context, pos, 8) || !context.budget().claim()) return;
|
||||
data.record(lightning, gameTime); // persist before dispatch so a restart cannot replay the event
|
||||
if (lightning) strike(level, context.age(), chunk, pos);
|
||||
else explode(level, context.age(), chunk, pos);
|
||||
}
|
||||
|
||||
static double legacyChance(int loadedChunks, int intervalTicks, int copies, int denominator) {
|
||||
if (loadedChunks <= 0 || intervalTicks <= 0 || copies <= 0 || denominator <= 0) return 0;
|
||||
return 1.0 - Math.pow(1.0 - 1.0 / denominator, (double) loadedChunks * intervalTicks * copies);
|
||||
}
|
||||
|
||||
static boolean safeTarget(AgeInstabilityRuntime.Context context, BlockPos pos, int spawnMargin) {
|
||||
if (!AgeDecayProviders.isLoadedTarget(context.level(), context.loadedChunks(), pos)) return false;
|
||||
BlockPos spawn = context.age().spawn();
|
||||
return spawn == null || Math.abs(pos.getX() - spawn.getX()) > spawnMargin
|
||||
|| Math.abs(pos.getZ() - spawn.getZ()) > spawnMargin;
|
||||
}
|
||||
|
||||
private static void strike(ServerLevel level, AgeDefinition age, ChunkPos chunk, BlockPos pos) {
|
||||
AABB bounds = new AABB(pos).inflate(2);
|
||||
if (!level.getEntitiesOfClass(LightningBolt.class, bounds).isEmpty()) return;
|
||||
LightningBolt bolt = EntityType.LIGHTNING_BOLT.create(level);
|
||||
if (bolt == null) return;
|
||||
bolt.setPos(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5);
|
||||
bolt.setVisualOnly(true); // vanilla bolt damage/fire bypasses our explicit budgets
|
||||
if (!level.addFreshEntity(bolt)) return;
|
||||
List<LivingEntity> targets = level.getEntitiesOfClass(LivingEntity.class, bounds,
|
||||
entity -> entity.isAlive() && entity.level() == level && eligibleEntity(entity));
|
||||
targets.sort(Comparator.comparing(Entity::getUUID));
|
||||
int count = 0;
|
||||
for (LivingEntity target : targets) {
|
||||
if (count++ >= RivencraftConfig.hazardsMaxEntities()) break;
|
||||
if (RivencraftConfig.hazardsMaxDamage() > 0)
|
||||
target.hurt(level.damageSources().lightningBolt(), Math.min(5, RivencraftConfig.hazardsMaxDamage()));
|
||||
}
|
||||
// Legacy lightning started fires. Keep it separately gated by block policy and game rule.
|
||||
if (canMutate(level) && RivencraftConfig.hazardsFire()
|
||||
&& level.getGameRules().getBoolean(GameRules.RULE_DOFIRETICK)
|
||||
&& !AgeDecayProviders.isSpawnProtected(age, pos)
|
||||
&& AgeDecayProviders.isLoadedTarget(level, List.of(chunk), pos)) ignite(level, pos);
|
||||
}
|
||||
|
||||
private static void explode(ServerLevel level, AgeDefinition age, ChunkPos chunk, BlockPos pos) {
|
||||
explodeBounded(level, age, chunk, pos, RivencraftConfig.hazardsBlockDamage(),
|
||||
RivencraftConfig.hazardsPlayerDamage(), RivencraftConfig.hazardsFire(),
|
||||
RivencraftConfig.hazardsMaxBlocks(), RivencraftConfig.hazardsMaxEntities(),
|
||||
RivencraftConfig.hazardsMaxDamage(), RivencraftConfig.hazardsExplosionRadius());
|
||||
}
|
||||
|
||||
/** Shared blast guard for meteor impacts; each effect supplies its own damage policy. */
|
||||
static void explodeBounded(ServerLevel level, AgeDefinition age, ChunkPos chunk, BlockPos pos,
|
||||
boolean blockDamage, boolean playerDamage, boolean ignite, int maxBlocks, int maxEntities,
|
||||
int maxDamage, int radius) {
|
||||
boolean grief = destructiveBlocksAllowed(RivencraftConfig.instabilityWorldMutation(),
|
||||
level.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING), blockDamage, maxBlocks);
|
||||
boolean fire = grief && ignite
|
||||
&& level.getGameRules().getBoolean(GameRules.RULE_DOFIRETICK);
|
||||
Explosion explosion = level.explode(null, null, new BoundedExplosion(level, age, chunk, grief,
|
||||
playerDamage, maxBlocks, maxEntities, maxDamage),
|
||||
pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5,
|
||||
radius, false,
|
||||
grief ? Level.ExplosionInteraction.BLOCK : Level.ExplosionInteraction.NONE);
|
||||
if (fire) {
|
||||
int ignited = 0;
|
||||
for (BlockPos affected : explosion.getToBlow()) {
|
||||
if (ignited >= 4) break;
|
||||
if (!AgeDecayProviders.isSpawnProtected(age, affected) && ignite(level, affected)) ignited++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean ignite(ServerLevel level, BlockPos pos) {
|
||||
if (!level.getBlockState(pos).isAir() || !Blocks.FIRE.defaultBlockState().canSurvive(level, pos))
|
||||
return false;
|
||||
var actor = FakePlayerFactory.getMinecraft(level);
|
||||
actor.setPos(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5);
|
||||
var snapshot = net.neoforged.neoforge.common.util.BlockSnapshot.create(level.dimension(), level, pos);
|
||||
BlockState prior = level.getBlockState(pos);
|
||||
if (!level.setBlock(pos, Blocks.FIRE.defaultBlockState(), 3)) return false;
|
||||
var place = new BlockEvent.EntityPlaceEvent(snapshot, prior, actor);
|
||||
NeoForge.EVENT_BUS.post(place);
|
||||
if (place.isCanceled()) {
|
||||
snapshot.restore();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static boolean canMutate(ServerLevel level) {
|
||||
return RivencraftConfig.instabilityWorldMutation()
|
||||
&& level.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING);
|
||||
}
|
||||
|
||||
static boolean destructiveBlocksAllowed(boolean worldMutation, boolean mobGriefing,
|
||||
boolean blockDamage, int maxBlocks) {
|
||||
return worldMutation && mobGriefing && blockDamage && maxBlocks > 0;
|
||||
}
|
||||
|
||||
static boolean protectedBlock(ServerLevel level, AgeDefinition age, BlockPos pos, BlockState state) {
|
||||
return state.isAir() || state.hasBlockEntity() || state.is(Blocks.TNT)
|
||||
|| state.is(AgeDecayProviders.PROTECTED) || state.is(BlockTags.PORTALS)
|
||||
|| AgeDecayProviders.isSpawnProtected(age, pos)
|
||||
|| state.getDestroySpeed(level, pos) < 0
|
||||
|| BuiltInRegistries.BLOCK.getKey(state.getBlock()).getNamespace().equals(Rivencraft.MOD_ID);
|
||||
}
|
||||
|
||||
private static boolean eligibleEntity(Entity entity) {
|
||||
return eligibleEntity(entity, RivencraftConfig.hazardsPlayerDamage());
|
||||
}
|
||||
|
||||
private static boolean eligibleEntity(Entity entity, boolean playerDamage) {
|
||||
return !(entity instanceof Player player) || playerDamage
|
||||
&& !player.isCreative() && !player.isSpectator();
|
||||
}
|
||||
|
||||
private static ResourceLocation id(String path) {
|
||||
return ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path);
|
||||
}
|
||||
|
||||
private static final class BoundedExplosion extends ExplosionDamageCalculator {
|
||||
private final ServerLevel level;
|
||||
private final AgeDefinition age;
|
||||
private final ChunkPos chunk;
|
||||
private final boolean grief;
|
||||
private final boolean playerDamage;
|
||||
private final int maxBlocks;
|
||||
private final int maxEntities;
|
||||
private final int maxDamage;
|
||||
private final Set<BlockPos> approved = new HashSet<>();
|
||||
private final Set<UUID> damagedEntities = new HashSet<>();
|
||||
private int damaged;
|
||||
|
||||
private BoundedExplosion(ServerLevel level, AgeDefinition age, ChunkPos chunk, boolean grief,
|
||||
boolean playerDamage, int maxBlocks, int maxEntities, int maxDamage) {
|
||||
this.level = level;
|
||||
this.age = age;
|
||||
this.chunk = chunk;
|
||||
this.grief = grief;
|
||||
this.playerDamage = playerDamage;
|
||||
this.maxBlocks = maxBlocks;
|
||||
this.maxEntities = maxEntities;
|
||||
this.maxDamage = maxDamage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Float> getBlockExplosionResistance(Explosion explosion, BlockGetter reader,
|
||||
BlockPos pos, BlockState state, FluidState fluid) {
|
||||
if (!inLoadedChunk(pos)) return Optional.of(Float.MAX_VALUE);
|
||||
return super.getBlockExplosionResistance(explosion, reader, pos, state, fluid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldBlockExplode(Explosion explosion, BlockGetter reader, BlockPos pos,
|
||||
BlockState state, float power) {
|
||||
if (!grief || !inLoadedChunk(pos) || protectedBlock(level, age, pos, state)) return false;
|
||||
if (approved.contains(pos)) return true;
|
||||
if (approved.size() >= maxBlocks) return false;
|
||||
var actor = FakePlayerFactory.getMinecraft(level);
|
||||
actor.setPos(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5);
|
||||
var event = new BlockEvent.BreakEvent(level, pos, state, actor);
|
||||
NeoForge.EVENT_BUS.post(event);
|
||||
if (event.isCanceled()) return false;
|
||||
approved.add(pos.immutable());
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldDamageEntity(Explosion explosion, Entity entity) {
|
||||
if (damaged >= maxEntities || !eligibleEntity(entity, playerDamage)
|
||||
|| maxDamage == 0) return false;
|
||||
damaged++;
|
||||
damagedEntities.add(entity.getUUID());
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getEntityDamageAmount(Explosion explosion, Entity entity) {
|
||||
return Math.min(super.getEntityDamageAmount(explosion, entity), maxDamage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getKnockbackMultiplier(Entity entity) {
|
||||
return damagedEntities.contains(entity.getUUID()) ? 1.0F : 0.0F;
|
||||
}
|
||||
|
||||
private boolean inLoadedChunk(BlockPos pos) {
|
||||
return level.isInWorldBounds(pos) && new ChunkPos(pos).equals(chunk)
|
||||
&& level.getChunkSource().hasChunk(chunk.x, chunk.z);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package net.dnorberg.rivencraft.book;
|
||||
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.util.datafix.DataFixTypes;
|
||||
import net.minecraft.world.level.saveddata.SavedData;
|
||||
|
||||
/** Per-Age hazard sequence and cooldowns survive unloads and server restarts. */
|
||||
public final class AgeHazardSavedData extends SavedData {
|
||||
private static final Factory<AgeHazardSavedData> FACTORY = new Factory<>(AgeHazardSavedData::new,
|
||||
AgeHazardSavedData::load, DataFixTypes.SAVED_DATA_MAP_DATA);
|
||||
private long attempts;
|
||||
private long lastLightning = Long.MIN_VALUE;
|
||||
private long lastExplosion = Long.MIN_VALUE;
|
||||
private long lastMeteor = Long.MIN_VALUE;
|
||||
|
||||
public static AgeHazardSavedData get(ServerLevel level) {
|
||||
return level.getDataStorage().computeIfAbsent(FACTORY, "rivencraft_hazards");
|
||||
}
|
||||
|
||||
public long nextAttempt() {
|
||||
setDirty();
|
||||
return attempts++;
|
||||
}
|
||||
|
||||
public boolean ready(boolean lightning, long gameTime, int interval) {
|
||||
long last = lightning ? lastLightning : lastExplosion;
|
||||
return last == Long.MIN_VALUE || gameTime < last || gameTime - last >= interval;
|
||||
}
|
||||
|
||||
public void record(boolean lightning, long gameTime) {
|
||||
if (lightning) lastLightning = gameTime;
|
||||
else lastExplosion = gameTime;
|
||||
setDirty();
|
||||
}
|
||||
|
||||
public boolean meteorReady(long gameTime, int interval) {
|
||||
return lastMeteor == Long.MIN_VALUE || gameTime < lastMeteor || gameTime - lastMeteor >= interval;
|
||||
}
|
||||
|
||||
public void recordMeteor(long gameTime) {
|
||||
lastMeteor = gameTime;
|
||||
setDirty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompoundTag save(CompoundTag tag, HolderLookup.Provider registries) {
|
||||
tag.putLong("Attempts", attempts);
|
||||
tag.putLong("LastLightning", lastLightning);
|
||||
tag.putLong("LastExplosion", lastExplosion);
|
||||
tag.putLong("LastMeteor", lastMeteor);
|
||||
return tag;
|
||||
}
|
||||
|
||||
static AgeHazardSavedData load(CompoundTag tag, HolderLookup.Provider registries) {
|
||||
AgeHazardSavedData data = new AgeHazardSavedData();
|
||||
data.attempts = Math.max(0L, tag.getLong("Attempts"));
|
||||
if (tag.contains("LastLightning")) data.lastLightning = tag.getLong("LastLightning");
|
||||
if (tag.contains("LastExplosion")) data.lastExplosion = tag.getLong("LastExplosion");
|
||||
if (tag.contains("LastMeteor")) data.lastMeteor = tag.getLong("LastMeteor");
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,42 @@
|
||||
package net.dnorberg.rivencraft.book;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import net.dnorberg.rivencraft.writing.WritingGrammar;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
/** Frozen, server-owned score. Only new Age creation consults the current symbol catalog. */
|
||||
public record AgeInstability(int version, int score, List<Contribution> breakdown) {
|
||||
public static final int CURRENT_VERSION = 1;
|
||||
public static final int CURRENT_VERSION = 2;
|
||||
private static final int BRIGHT_LIGHTING_COST = 500;
|
||||
private static final int EXCESS_LEGACY_STRUCTURE_COST = 100;
|
||||
private static final int FORCED_STRUCTURE_BIOME_COST = 100;
|
||||
private static final Map<ResourceLocation, String> COUNTED_STRUCTURES = Map.ofEntries(
|
||||
Map.entry(id("mineshafts"), "Mineshafts"),
|
||||
Map.entry(id("nether_fortresses"), "Nether Fortresses"),
|
||||
Map.entry(id("strongholds"), "Strongholds"),
|
||||
Map.entry(id("villages"), "Villages"),
|
||||
Map.entry(id("bastions"), "Bastions"),
|
||||
Map.entry(id("trial_chambers"), "Trial Chambers"),
|
||||
Map.entry(id("ancient_cities"), "Ancient Cities"),
|
||||
Map.entry(id("shipwrecks"), "Shipwrecks"),
|
||||
Map.entry(id("ocean_ruins"), "Ocean Ruins"),
|
||||
Map.entry(id("pillager_outposts"), "Pillager Outposts"),
|
||||
Map.entry(id("ruined_portals"), "Ruined Portals"),
|
||||
Map.entry(id("nether_fossils"), "Nether Fossils"),
|
||||
Map.entry(id("buried_treasure"), "Buried Treasure"),
|
||||
Map.entry(id("trail_ruins"), "Trail Ruins")
|
||||
);
|
||||
|
||||
public AgeInstability {
|
||||
if (version != CURRENT_VERSION) throw new IllegalArgumentException("Unsupported instability version " + version);
|
||||
if (version < 1 || version > CURRENT_VERSION)
|
||||
throw new IllegalArgumentException("Unsupported instability version " + version);
|
||||
breakdown = List.copyOf(breakdown);
|
||||
if (score < 0 || score != breakdown.stream().mapToInt(Contribution::points).sum()) {
|
||||
throw new IllegalArgumentException("Instability score does not match breakdown");
|
||||
@@ -21,11 +45,11 @@ public record AgeInstability(int version, int score, List<Contribution> breakdow
|
||||
|
||||
/** Pre-scoring saves are explicitly neutral, never rescored from current data packs. */
|
||||
public static AgeInstability legacyNeutral() {
|
||||
return new AgeInstability(CURRENT_VERSION, 0,
|
||||
return new AgeInstability(1, 0,
|
||||
List.of(new Contribution("legacy_neutral", -1, 0, "Age predates frozen instability scoring")));
|
||||
}
|
||||
|
||||
static AgeInstability compute(AgeGenerationPlan plan, AgeTraits traits) {
|
||||
static AgeInstability compute(AgeGenerationPlan plan, AgeTraits traits, RegistryAccess registries) {
|
||||
Objects.requireNonNull(traits, "traits");
|
||||
List<Contribution> contributions = new ArrayList<>();
|
||||
if (plan == null) {
|
||||
@@ -40,21 +64,69 @@ public record AgeInstability(int version, int score, List<Contribution> breakdow
|
||||
contributions.add(new Contribution(diagnostic.code().name().toLowerCase(java.util.Locale.ROOT),
|
||||
diagnostic.index(), diagnostic.instability(), diagnostic.message()));
|
||||
}
|
||||
addAuditedSymbolCosts(plan, registries, contributions);
|
||||
}
|
||||
// Legacy's bright-lighting symbol adds +500. Other balance costs are deferred
|
||||
// until their corresponding authored symbols and audited values exist.
|
||||
if (traits.lighting() == AgeTraits.Lighting.BRIGHT) {
|
||||
int pageIndex = plan == null ? -1 : plan.activeSymbols().stream()
|
||||
.filter(symbol -> symbol.semantics().role()
|
||||
== net.dnorberg.rivencraft.writing.SymbolSemantics.Role.LIGHTING)
|
||||
.mapToInt(AgeGenerationPlan.ResolvedSymbol::index).findFirst().orElse(-1);
|
||||
contributions.add(new Contribution("bright_lighting", pageIndex, 500,
|
||||
pageIndex < 0 ? "Seeded bright lighting" : "Authored bright lighting"));
|
||||
// A missing lighting controller is seed-completed. Legacy runs the generated
|
||||
// symbol's own modifier, so a generated Bright Lighting choice still costs 500.
|
||||
if (traits.lighting() == AgeTraits.Lighting.BRIGHT && (plan == null || plan.symbols().stream()
|
||||
.noneMatch(symbol -> symbol.semantics().role()
|
||||
== net.dnorberg.rivencraft.writing.SymbolSemantics.Role.LIGHTING))) {
|
||||
contributions.add(new Contribution("bright_lighting", -1, BRIGHT_LIGHTING_COST,
|
||||
"Seeded bright lighting"));
|
||||
}
|
||||
return new AgeInstability(CURRENT_VERSION,
|
||||
contributions.stream().mapToInt(Contribution::points).sum(), contributions);
|
||||
}
|
||||
|
||||
private static void addAuditedSymbolCosts(AgeGenerationPlan plan, RegistryAccess registries,
|
||||
List<Contribution> contributions) {
|
||||
Map<ResourceLocation, Integer> structureCounts = new HashMap<>();
|
||||
for (AgeGenerationPlan.ResolvedSymbol symbol : plan.symbols()) {
|
||||
if (symbol.semantics().role()
|
||||
== net.dnorberg.rivencraft.writing.SymbolSemantics.Role.LIGHTING
|
||||
&& symbol.semantics().value()
|
||||
instanceof net.dnorberg.rivencraft.writing.SymbolSemantics.ChoiceValue choice
|
||||
&& choice.id().equals("bright")) {
|
||||
contributions.add(new Contribution("bright_lighting", symbol.index(), BRIGHT_LIGHTING_COST,
|
||||
"Authored bright lighting"));
|
||||
continue;
|
||||
}
|
||||
if (symbol.semantics().role()
|
||||
!= net.dnorberg.rivencraft.writing.SymbolSemantics.Role.FEATURE
|
||||
|| !(symbol.semantics().value()
|
||||
instanceof net.dnorberg.rivencraft.writing.SymbolSemantics.ResourceValue resource)) continue;
|
||||
String name = COUNTED_STRUCTURES.get(resource.id());
|
||||
if (name == null) continue;
|
||||
int count = structureCounts.merge(resource.id(), 1, Integer::sum);
|
||||
if (AgeStructureSelection.requiresBiomeOverride(resource.id(), plan.biomeSelection(), registries)) {
|
||||
contributions.add(new Contribution("forced_biome_" + resource.id().getPath(), symbol.index(),
|
||||
FORCED_STRUCTURE_BIOME_COST,
|
||||
name + " occurrence " + count + " is forced into an unsupported biome"));
|
||||
}
|
||||
int cost = featureCost(resource.id(), count);
|
||||
if (cost > 0) {
|
||||
contributions.add(new Contribution("excess_" + resource.id().getPath(), symbol.index(),
|
||||
cost,
|
||||
name + " occurrence " + count + " exceeds Legacy's first three free occurrences"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int featureCost(ResourceLocation feature, int occurrence) {
|
||||
if (occurrence < 1) throw new IllegalArgumentException("Feature occurrence must be positive");
|
||||
return COUNTED_STRUCTURES.containsKey(feature) && occurrence > 3
|
||||
? EXCESS_LEGACY_STRUCTURE_COST : 0;
|
||||
}
|
||||
|
||||
/** Current totals exposed to diagnostics. Player-driven mutable bonuses are deliberately disabled. */
|
||||
public Totals totals() {
|
||||
return new Totals(score, 0, 0, score);
|
||||
}
|
||||
|
||||
private static ResourceLocation id(String path) {
|
||||
return ResourceLocation.fromNamespaceAndPath("rivencraft", path);
|
||||
}
|
||||
|
||||
public CompoundTag save() {
|
||||
CompoundTag tag = new CompoundTag();
|
||||
tag.putInt("Version", version);
|
||||
@@ -92,4 +164,13 @@ public record AgeInstability(int version, int score, List<Contribution> breakdow
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record Totals(int baseScore, int stabilityBonus, int instabilityPenalty, int effectiveScore) {
|
||||
public Totals {
|
||||
if (baseScore < 0 || stabilityBonus < 0 || instabilityPenalty < 0
|
||||
|| effectiveScore != Math.max(0, baseScore + instabilityPenalty - stabilityBonus)) {
|
||||
throw new IllegalArgumentException("Invalid instability totals");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package net.dnorberg.rivencraft.book;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.util.datafix.DataFixTypes;
|
||||
import net.minecraft.world.level.saveddata.SavedData;
|
||||
|
||||
/** Per-world operator overrides. Absence means enabled; scores and plans stay immutable. */
|
||||
public final class AgeInstabilityControls extends SavedData {
|
||||
private static final String DATA_NAME = "rivencraft_instability_controls";
|
||||
private static final Factory<AgeInstabilityControls> FACTORY = new Factory<>(
|
||||
AgeInstabilityControls::new, AgeInstabilityControls::load, DataFixTypes.SAVED_DATA_MAP_DATA);
|
||||
private final Set<UUID> disabled = new HashSet<>();
|
||||
|
||||
public static AgeInstabilityControls get(ServerLevel level) {
|
||||
return level.getServer().overworld().getDataStorage().computeIfAbsent(FACTORY, DATA_NAME);
|
||||
}
|
||||
|
||||
public boolean enabled(UUID ageId) {
|
||||
return !disabled.contains(ageId);
|
||||
}
|
||||
|
||||
public boolean setEnabled(UUID ageId, boolean enabled) {
|
||||
boolean changed = enabled ? disabled.remove(ageId) : disabled.add(ageId);
|
||||
if (changed) setDirty();
|
||||
return changed;
|
||||
}
|
||||
|
||||
static AgeInstabilityControls load(CompoundTag tag, HolderLookup.Provider registries) {
|
||||
AgeInstabilityControls controls = new AgeInstabilityControls();
|
||||
ListTag entries = tag.getList("DisabledAges", CompoundTag.TAG_COMPOUND);
|
||||
for (int index = 0; index < entries.size(); index++) {
|
||||
CompoundTag entry = entries.getCompound(index);
|
||||
if (entry.hasUUID("Id")) controls.disabled.add(entry.getUUID("Id"));
|
||||
}
|
||||
return controls;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompoundTag save(CompoundTag tag, HolderLookup.Provider registries) {
|
||||
ListTag entries = new ListTag();
|
||||
disabled.stream().sorted().forEach(id -> {
|
||||
CompoundTag entry = new CompoundTag();
|
||||
entry.putUUID("Id", id);
|
||||
entries.add(entry);
|
||||
});
|
||||
tag.put("DisabledAges", entries);
|
||||
return tag;
|
||||
}
|
||||
}
|
||||
@@ -52,41 +52,55 @@ public final class AgeInstabilityRuntime {
|
||||
if (!admitted(state.eligible, level.dimension().location(), tick / cooldown,
|
||||
RivencraftConfig.instabilityMaxAges())) return;
|
||||
AgeDefinition age = AgeRegistrySavedData.get(level).findByDimension(level.dimension().location()).orElse(null);
|
||||
if (age == null || age.instabilityPlan().providers().isEmpty()) return;
|
||||
if (age == null || AgeBlockInstability.effectivePlan(level, age).providers().isEmpty()
|
||||
|| !AgeInstabilityControls.get(level).enabled(age.id())) return;
|
||||
// Legacy's per-chunk hazards must not wait for the rotating two-provider sample.
|
||||
AgeHazardProviders.tickPlanned(level, age, tick);
|
||||
AgeEnvironmentalProviders.tickPlanned(level, age, tick);
|
||||
List<ChunkPos> chunks = loadedChunksNearPlayers(level, RivencraftConfig.instabilityMaxChunks());
|
||||
if (chunks.isEmpty()) return;
|
||||
Budget budget = new Budget(RivencraftConfig.instabilityMaxActions());
|
||||
Context context = new Context(level, age, chunks, tick, budget);
|
||||
List<AgeInstabilityPlan.ProviderLevel> providers = age.instabilityPlan().providers();
|
||||
List<AgeInstabilityPlan.ProviderLevel> providers = AgeBlockInstability.effectivePlan(level, age).providers();
|
||||
int first = (int) Math.floorMod(tick / cooldown + age.seed(), providers.size());
|
||||
int ran = 0;
|
||||
for (int offset = 0; offset < providers.size() && ran < RivencraftConfig.instabilityMaxProviders()
|
||||
&& budget.remaining() > 0; offset++) {
|
||||
AgeInstabilityPlan.ProviderLevel provider = providers.get((first + offset) % providers.size());
|
||||
Handler handler = HANDLERS.get(provider.id());
|
||||
if (handler == null) {
|
||||
if (!InstabilityProviderCatalog.contains(provider.id()) && UNKNOWN_LOGGED.add(provider.id())) {
|
||||
Rivencraft.LOGGER.warn("Saved Age references unknown instability provider {}; skipping it",
|
||||
provider.id());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (handler.worldMutating() && !RivencraftConfig.instabilityWorldMutation()) continue;
|
||||
long retryAfter = FAILURES.computeIfAbsent(level, ignored -> new HashMap<>())
|
||||
.getOrDefault(provider.id(), 0L);
|
||||
if (tick < retryAfter) continue;
|
||||
ran++;
|
||||
try {
|
||||
handler.effect().apply(context, provider.id(),
|
||||
Math.min(provider.level(), RivencraftConfig.instabilityMaxLevel()));
|
||||
} catch (RuntimeException exception) {
|
||||
FAILURES.get(level).put(provider.id(), tick + Math.max(200L, cooldown * 10L));
|
||||
Rivencraft.LOGGER.error("Instability provider {} failed in Age {}; temporarily quarantined",
|
||||
provider.id(), age.id(), exception);
|
||||
}
|
||||
if (AgeHazardProviders.isHazard(provider.id())
|
||||
|| AgeEnvironmentalProviders.isEnvironmental(provider.id())) continue;
|
||||
if (invoke(context, provider.id(), provider.level())) ran++;
|
||||
}
|
||||
}
|
||||
|
||||
/** Shared handler guard, including quarantine, for rotating and per-chunk provider lanes. */
|
||||
static boolean invoke(Context context, ResourceLocation id, int level) {
|
||||
if (!RivencraftConfig.instabilityEnabled()
|
||||
|| !AgeInstabilityControls.get(context.level()).enabled(context.age().id())) return false;
|
||||
Handler handler = HANDLERS.get(id);
|
||||
if (handler == null) {
|
||||
if (!InstabilityProviderCatalog.contains(id) && UNKNOWN_LOGGED.add(id)) {
|
||||
Rivencraft.LOGGER.warn("Saved Age references unknown instability provider {}; skipping it", id);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (!policyAllowsProvider(RivencraftConfig.instabilityProviderEnabled(id),
|
||||
RivencraftConfig.instabilityWorldMutation(), handler.worldMutating())) return false;
|
||||
long retryAfter = FAILURES.computeIfAbsent(context.level(), ignored -> new HashMap<>())
|
||||
.getOrDefault(id, 0L);
|
||||
if (context.serverTick() < retryAfter) return false;
|
||||
try {
|
||||
handler.effect().apply(context, id,
|
||||
Math.min(level, RivencraftConfig.instabilityMaxLevel()));
|
||||
} catch (RuntimeException exception) {
|
||||
FAILURES.get(context.level()).put(id, context.serverTick()
|
||||
+ Math.max(200L, RivencraftConfig.instabilityCooldown() * 10L));
|
||||
Rivencraft.LOGGER.error("Instability provider {} failed in Age {}; temporarily quarantined",
|
||||
id, context.age().id(), exception);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void onServerStopping(ServerStoppingEvent event) {
|
||||
TICKS.remove(event.getServer());
|
||||
FAILURES.clear();
|
||||
@@ -97,6 +111,45 @@ public final class AgeInstabilityRuntime {
|
||||
return id.getNamespace().equals(Rivencraft.MOD_ID) && id.getPath().startsWith("age/");
|
||||
}
|
||||
|
||||
static boolean policyAllowsProvider(boolean providerEnabled, boolean worldMutation,
|
||||
boolean mutatingHandler) {
|
||||
return providerEnabled && (!mutatingHandler || worldMutation);
|
||||
}
|
||||
|
||||
/** Current runtime state, distinct from the Age's immutable score and provider selection. */
|
||||
public static String providerStatus(ServerLevel level, AgeDefinition age, ResourceLocation id) {
|
||||
if (!RivencraftConfig.instabilityEnabled()) return "global config off";
|
||||
if (!AgeInstabilityControls.get(level).enabled(age.id())) return "Age disabled";
|
||||
Handler handler = HANDLERS.get(id);
|
||||
if (handler == null) return "handler unavailable";
|
||||
if (!RivencraftConfig.instabilityProviderEnabled(id)) return "provider config off";
|
||||
if (handler.worldMutating() && !RivencraftConfig.instabilityWorldMutation()) return "world mutation off";
|
||||
String path = id.getPath();
|
||||
if (path.startsWith("decay") && !RivencraftConfig.decayEnabled()) return "decay config off";
|
||||
if ((path.equals("lightning") || path.equals("explosions")) && !RivencraftConfig.hazardsEnabled())
|
||||
return "hazards config off";
|
||||
if (path.equals("meteors") && !RivencraftConfig.meteorEnabled()) return "meteor config off";
|
||||
if (path.equals("burning") && !RivencraftConfig.scorchEnabled()) return "burning config off";
|
||||
if (path.equals("erosion") && !RivencraftConfig.erosionEnabled()) return "erosion config off";
|
||||
if (!path.startsWith("decay") && !path.equals("lightning") && !path.equals("explosions")
|
||||
&& !path.equals("meteors") && !path.equals("burning") && !path.equals("erosion")
|
||||
&& !path.equals("crumble") && !RivencraftConfig.statusEffectsEnabled())
|
||||
return "status effects config off";
|
||||
if (path.startsWith("enemy") && !RivencraftConfig.statusEffectsHostiles())
|
||||
return "hostile status effects config off";
|
||||
if (!path.startsWith("enemy") && !path.startsWith("decay") && !path.equals("lightning")
|
||||
&& !path.equals("explosions") && !path.equals("meteors") && !path.equals("burning")
|
||||
&& !path.equals("erosion") && !RivencraftConfig.statusEffectsPlayers()
|
||||
&& !RivencraftConfig.statusEffectsNonplayers())
|
||||
return "status effect targets disabled";
|
||||
ServerLevel ageLevel = level.getServer().getLevel(AgeDimensionService.dimensionKey(age));
|
||||
if (ageLevel == null) return "Age unloaded";
|
||||
if (ageLevel.players().isEmpty()) return "no players in Age";
|
||||
long retryAfter = FAILURES.getOrDefault(ageLevel, Map.of()).getOrDefault(id, 0L);
|
||||
if (ageLevel.getServer().getTickCount() < retryAfter) return "quarantined until tick " + retryAfter;
|
||||
return "eligible; chance, cooldown, and protection still apply";
|
||||
}
|
||||
|
||||
static boolean admitted(List<ResourceLocation> eligible, ResourceLocation id, long run,
|
||||
int maximum) {
|
||||
int index = eligible.indexOf(id);
|
||||
@@ -111,7 +164,8 @@ public final class AgeInstabilityRuntime {
|
||||
for (ServerLevel level : server.getAllLevels()) {
|
||||
ResourceLocation id = level.dimension().location();
|
||||
if (isAgeDimension(id) && !level.players().isEmpty()
|
||||
&& registry.findByDimension(id).filter(age -> !age.instabilityPlan().providers().isEmpty())
|
||||
&& registry.findByDimension(id).filter(age -> !AgeBlockInstability.effectivePlan(level, age).providers().isEmpty())
|
||||
.filter(age -> AgeInstabilityControls.get(level).enabled(age.id()))
|
||||
.isPresent()) eligible.add(id);
|
||||
}
|
||||
eligible.sort(Comparator.comparing(ResourceLocation::toString));
|
||||
|
||||
@@ -8,6 +8,7 @@ import net.minecraft.gametest.framework.GameTest;
|
||||
import net.minecraft.gametest.framework.GameTestHelper;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.neoforged.neoforge.gametest.GameTestHolder;
|
||||
import net.neoforged.neoforge.gametest.PrefixGameTestTemplate;
|
||||
|
||||
@@ -58,6 +59,53 @@ public final class AgeInstabilityRuntimeGameTests {
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void perAgeControlsPersistWithoutChangingScoresOrOtherAges(GameTestHelper helper) {
|
||||
UUID first = UUID.randomUUID();
|
||||
UUID second = UUID.randomUUID();
|
||||
AgeInstabilityControls controls = new AgeInstabilityControls();
|
||||
helper.assertTrue(controls.enabled(first) && controls.enabled(second),
|
||||
"Ages must be enabled by default");
|
||||
helper.assertTrue(controls.setEnabled(first, false) && !controls.enabled(first)
|
||||
&& controls.enabled(second), "Disabling one Age must not change another");
|
||||
AgeInstabilityControls restored = AgeInstabilityControls.load(
|
||||
controls.save(new CompoundTag(), helper.getLevel().registryAccess()),
|
||||
helper.getLevel().registryAccess());
|
||||
helper.assertTrue(!restored.enabled(first) && restored.enabled(second),
|
||||
"The per-Age override must survive a save round trip");
|
||||
helper.assertTrue(restored.setEnabled(first, true) && restored.enabled(first),
|
||||
"Re-enabling must remove the override");
|
||||
|
||||
var oldAge = new AgeDefinition(first, "Old Age", 1L, AgeGenerationProfiles.STANDARD,
|
||||
AgeDefinition.CURRENT_GENERATION_VERSION, 0L, AgeDefinition.dimensionId(first), null,
|
||||
AgeTraits.LEGACY_DEFAULTS);
|
||||
helper.assertValueEqual(oldAge.instability().score(), 0,
|
||||
"A pre-scoring Age must remain neutral regardless of runtime controls");
|
||||
helper.assertTrue(oldAge.instabilityPlan().providers().isEmpty(),
|
||||
"Runtime controls must not generate providers for old Ages");
|
||||
AgeInstabilityControls live = AgeInstabilityControls.get(helper.getLevel());
|
||||
live.setEnabled(first, false);
|
||||
helper.assertValueEqual(AgeInstabilityRuntime.providerStatus(helper.getLevel(), oldAge,
|
||||
ResourceLocation.parse("rivencraft:poison")), "Age disabled",
|
||||
"Diagnostics must distinguish an Age override from the saved plan");
|
||||
live.setEnabled(first, true);
|
||||
helper.assertValueEqual(AgeInstabilityRuntime.providerStatus(helper.getLevel(), oldAge,
|
||||
ResourceLocation.parse("example:missing_handler")), "handler unavailable",
|
||||
"Unknown saved providers must not be reported as active");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void instabilityControlCommandsRequireOperatorPermission(GameTestHelper helper) {
|
||||
var server = helper.getLevel().getServer();
|
||||
var command = server.getCommands().getDispatcher().getRoot().getChild("rivencraft");
|
||||
helper.assertTrue(command != null, "Rivencraft commands must be registered on a dedicated server");
|
||||
helper.assertTrue(!command.canUse(server.createCommandSourceStack().withPermission(0))
|
||||
&& command.canUse(server.createCommandSourceStack().withPermission(2)),
|
||||
"Non-operators cannot reach Age instability enable/disable commands");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void ageScopeRotationAndActionBudgetAreBounded(GameTestHelper helper) {
|
||||
ResourceLocation first = ResourceLocation.parse("rivencraft:age/first");
|
||||
@@ -78,4 +126,89 @@ public final class AgeInstabilityRuntimeGameTests {
|
||||
helper.assertValueEqual(budget.remaining(), 0, "The budget must not go negative");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void hazardCooldownAndAttemptSequenceSurviveReload(GameTestHelper helper) {
|
||||
AgeHazardSavedData data = new AgeHazardSavedData();
|
||||
helper.assertTrue(data.ready(true, 1000, 200) && data.ready(false, 1000, 200),
|
||||
"Each hazard type starts eligible independently");
|
||||
helper.assertValueEqual(data.nextAttempt(), 0L, "First hazard roll has a stable sequence");
|
||||
data.record(true, 1000);
|
||||
helper.assertTrue(!data.ready(true, 1199, 200) && data.ready(false, 1199, 200),
|
||||
"Lightning cooldown must not suppress explosions");
|
||||
AgeHazardSavedData restored = AgeHazardSavedData.load(
|
||||
data.save(new CompoundTag(), helper.getLevel().registryAccess()),
|
||||
helper.getLevel().registryAccess());
|
||||
helper.assertValueEqual(restored.nextAttempt(), 1L, "Restart must not replay the previous roll");
|
||||
helper.assertTrue(!restored.ready(true, 1199, 200) && restored.ready(true, 1200, 200),
|
||||
"Reloaded cooldown must still enforce the minimum interval");
|
||||
helper.assertTrue(restored.meteorReady(1200, 200), "Meteor cooldown starts independently");
|
||||
restored.recordMeteor(1200);
|
||||
AgeHazardSavedData meteorReloaded = AgeHazardSavedData.load(
|
||||
restored.save(new CompoundTag(), helper.getLevel().registryAccess()),
|
||||
helper.getLevel().registryAccess());
|
||||
helper.assertTrue(!meteorReloaded.meteorReady(1399, 200)
|
||||
&& meteorReloaded.meteorReady(1400, 200),
|
||||
"A meteor attempt must not replay immediately after restart");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void environmentalCardsPreserveLegacyDeckAndAgeScope(GameTestHelper helper) {
|
||||
helper.assertTrue(InstabilityProviderCatalog.contains(ResourceLocation.parse("rivencraft:meteors"))
|
||||
&& InstabilityProviderCatalog.contains(ResourceLocation.parse("rivencraft:burning")),
|
||||
"Meteor and burning must retain their audited Legacy deck cards");
|
||||
helper.assertTrue(!InstabilityProviderCatalog.contains(ResourceLocation.parse("rivencraft:erosion")),
|
||||
"Enabling dormant erosion must not silently change frozen provider selection");
|
||||
var level = helper.getLevel();
|
||||
var budget = new AgeInstabilityRuntime.Budget(1);
|
||||
var age = new AgeDefinition(UUID.randomUUID(), "Fixture", 1L, AgeGenerationProfiles.STANDARD,
|
||||
AgeDefinition.CURRENT_GENERATION_VERSION, 0L,
|
||||
ResourceLocation.parse("rivencraft:age/fixture"), null,
|
||||
AgeTraits.LEGACY_DEFAULTS, null, null, List.of(), AgeInstability.legacyNeutral(),
|
||||
AgeInstabilityPlan.empty());
|
||||
var context = new AgeInstabilityRuntime.Context(level, age, List.of(new net.minecraft.world.level.ChunkPos(0, 0)),
|
||||
level.getServer().getTickCount(), budget);
|
||||
helper.assertTrue(AgeEnvironmentalProviders.matchesAge(age, age.dimensionId())
|
||||
&& !AgeEnvironmentalProviders.matchesAge(age, ResourceLocation.parse("rivencraft:age/other"))
|
||||
&& !AgeEnvironmentalProviders.matchesAge(age, level.dimension().location()),
|
||||
"One player's environmental Age effects must not leak into another Age or the Overworld");
|
||||
for (String path : List.of("meteors", "burning", "erosion")) {
|
||||
AgeEnvironmentalProviders.apply(context, ResourceLocation.parse("rivencraft:" + path), 1);
|
||||
}
|
||||
helper.assertValueEqual(budget.remaining(), 1,
|
||||
"Environmental effects must never run in the GameTest Overworld");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void burningPersistsOnDrySurvivalPlayer(GameTestHelper helper) {
|
||||
var player = helper.makeMockServerPlayerInLevel();
|
||||
player.setGameMode(GameType.SURVIVAL);
|
||||
player.igniteForSeconds(4);
|
||||
helper.assertTrue(player.getRemainingFireTicks() >= 79,
|
||||
"Burning should set at least four seconds of server-side fire ticks");
|
||||
helper.runAfterDelay(2, () -> {
|
||||
helper.assertTrue(player.isOnFire() && player.getRemainingFireTicks() > 0,
|
||||
"A dry survival player should remain on fire after Minecraft ticks the entity");
|
||||
helper.succeed();
|
||||
});
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void hazardRollMatchesLegacyChunkOpportunity(GameTestHelper helper) {
|
||||
double oneChunk = AgeHazardProviders.legacyChance(1, 1, 1, 1000);
|
||||
double nearby = AgeHazardProviders.legacyChance(81, 20, 1, 1000);
|
||||
double thunder = AgeHazardProviders.legacyChance(81, 20, 1, 5000);
|
||||
double clear = AgeHazardProviders.legacyChance(81, 20, 1, 100000);
|
||||
helper.assertTrue(Math.abs(oneChunk - 0.001) < 0.000001,
|
||||
"One chunk tick must retain Legacy's 1/1000 explosion roll");
|
||||
helper.assertTrue(nearby > 0.79 && nearby < 0.82,
|
||||
"Nearby loaded chunks must produce frequent bounded explosions");
|
||||
helper.assertTrue(thunder > clear && clear > 0,
|
||||
"Legacy lightning must be more frequent in thunder than clear weather");
|
||||
helper.assertTrue(AgeHazardProviders.legacyChance(0, 20, 1, 1000) == 0,
|
||||
"Unloaded chunks must never produce a hazard opportunity");
|
||||
helper.succeed();
|
||||
}
|
||||
}
|
||||
@@ -125,13 +125,91 @@ public final class AgePersistenceGameTests {
|
||||
AgeInstability bright = AgeInstability.compute(null, new AgeTraits(
|
||||
AgeTraits.LEGACY_DEFAULTS.biomeDistribution(), AgeTraits.Lighting.BRIGHT,
|
||||
AgeTraits.LEGACY_DEFAULTS.weather(), AgeTraits.LEGACY_DEFAULTS.celestialPeriod(),
|
||||
AgeTraits.LEGACY_DEFAULTS.celestialAngle(), AgeTraits.LEGACY_DEFAULTS.celestialPhase()));
|
||||
AgeTraits.LEGACY_DEFAULTS.celestialAngle(), AgeTraits.LEGACY_DEFAULTS.celestialPhase()),
|
||||
helper.getLevel().registryAccess());
|
||||
helper.assertValueEqual(bright.score(), 500, "Bright lighting has the audited Legacy cost");
|
||||
helper.assertValueEqual(AgeInstability.load(bright.save()), bright,
|
||||
"A score must survive its own versioned round trip");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void auditedSymbolCostsAreCountedAndAgeScoped(GameTestHelper helper) {
|
||||
List<String> legacyStructures = List.of("mineshafts", "nether_fortresses", "strongholds", "villages");
|
||||
for (String structure : legacyStructures) {
|
||||
AgeDefinition three = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(),
|
||||
new AgeReference(UUID.randomUUID(), "Three " + structure), structureWriting(structure, 3));
|
||||
AgeDefinition four = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(),
|
||||
new AgeReference(UUID.randomUUID(), "Four " + structure), structureWriting(structure, 4));
|
||||
helper.assertValueEqual(three.instability().score(), 0,
|
||||
"The first three " + structure + " pages retain Legacy's zero cost");
|
||||
helper.assertValueEqual(four.instability().score(), 100,
|
||||
"The fourth " + structure + " page must add Legacy's 100-point cost");
|
||||
helper.assertTrue(four.instability().breakdown().stream().anyMatch(part ->
|
||||
part.reason().equals("excess_" + structure) && part.pageIndex() == 8),
|
||||
"The excess structure cost must identify its authored page");
|
||||
}
|
||||
for (String structure : List.of("bastions", "trial_chambers", "ancient_cities", "shipwrecks",
|
||||
"ocean_ruins", "pillager_outposts", "ruined_portals", "nether_fossils", "buried_treasure",
|
||||
"trail_ruins")) {
|
||||
ResourceLocation id = ResourceLocation.fromNamespaceAndPath("rivencraft", structure);
|
||||
helper.assertTrue(AgeInstability.featureCost(id, 1) == 0
|
||||
&& AgeInstability.featureCost(id, 3) == 0
|
||||
&& AgeInstability.featureCost(id, 4) == 100
|
||||
&& AgeInstability.featureCost(id, 5) == 100,
|
||||
structure + " must follow the selected Legacy Mineshaft repeat rule");
|
||||
}
|
||||
helper.assertValueEqual(AgeInstability.featureCost(
|
||||
ResourceLocation.parse("rivencraft:trial_chambers"), 4), 100,
|
||||
"Modern repeated structures must use the same deterministic scoring path");
|
||||
helper.assertValueEqual(AgeInstability.featureCost(ResourceLocation.parse("rivencraft:dungeons"), 4), 0,
|
||||
"A Legacy-neutral feature must remain neutral when repeated");
|
||||
|
||||
OrderedWriting duplicateBright = new OrderedWriting(List.of(
|
||||
WritingEntry.linkPanel(),
|
||||
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:terrain/standard"))),
|
||||
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:lighting/bright"))),
|
||||
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:lighting/bright")))
|
||||
));
|
||||
AgeDefinition bright = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(),
|
||||
new AgeReference(UUID.randomUUID(), "Double Bright"), duplicateBright);
|
||||
helper.assertValueEqual(bright.instability().score(), 1500,
|
||||
"Each Bright Lighting page costs 500 and the extra controller costs another 500");
|
||||
helper.assertValueEqual(bright.instability().breakdown().stream()
|
||||
.filter(part -> part.reason().equals("bright_lighting")).count(), 2L,
|
||||
"Every authored Bright Lighting occurrence must retain its own cost");
|
||||
|
||||
AgeInstability.Totals totals = bright.instability().totals();
|
||||
helper.assertValueEqual(totals.baseScore(), 1500, "Diagnostics must expose the immutable base score");
|
||||
helper.assertTrue(totals.stabilityBonus() == 0 && totals.instabilityPenalty() == 0
|
||||
&& totals.effectiveScore() == totals.baseScore(),
|
||||
"Dormant player bonus classes must not create mutable, cross-Age credit");
|
||||
AgeDefinition restored = AgeRegistrySavedData.load(
|
||||
AgeRegistrySavedData.get(helper.getLevel()).save(new CompoundTag(), helper.getLevel().registryAccess()),
|
||||
helper.getLevel().registryAccess()).find(bright.id()).orElseThrow();
|
||||
helper.assertValueEqual(restored.instability().totals(), totals,
|
||||
"The base/adjustment diagnostic must remain identical after reload");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
private static OrderedWriting structureWriting(String structure, int count) {
|
||||
boolean nether = structure.equals("nether_fortresses");
|
||||
List<WritingEntry> entries = new java.util.ArrayList<>(List.of(
|
||||
WritingEntry.linkPanel(),
|
||||
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse(
|
||||
nether ? "rivencraft:terrain/cave" : "rivencraft:terrain/standard"))),
|
||||
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse(
|
||||
nether ? "rivencraft:biome/nether_wastes" : "rivencraft:biome/plains"))),
|
||||
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:biome/single"))),
|
||||
WritingEntry.symbol(new SymbolReference(ResourceLocation.parse("rivencraft:lighting/normal")))
|
||||
));
|
||||
for (int index = 0; index < count; index++) {
|
||||
entries.add(WritingEntry.symbol(new SymbolReference(
|
||||
ResourceLocation.parse("rivencraft:feature/" + structure))));
|
||||
}
|
||||
return new OrderedWriting(entries);
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void missingRegistryEntryDoesNotReinterpretAnOldAge(GameTestHelper helper) {
|
||||
UUID id = UUID.randomUUID();
|
||||
|
||||
@@ -135,7 +135,7 @@ public final class AgeRegistrySavedData extends SavedData {
|
||||
AgeTraits traits = AgeTraits.select(seed);
|
||||
AgeGenerationPlan plan = AgeGenerationPlan.compile(writing, seed, seedProfile, traits, registries);
|
||||
AgeTraits effectiveTraits = AgeEnvironmentCompiler.apply(plan, traits);
|
||||
AgeInstability instability = AgeInstability.compute(plan, effectiveTraits);
|
||||
AgeInstability instability = AgeInstability.compute(plan, effectiveTraits, registries);
|
||||
AgeInstabilityPlan instabilityPlan = AgeInstabilityPlan.select(instability, seed);
|
||||
AgeDefinition created = new AgeDefinition(
|
||||
reference.id(),
|
||||
|
||||
@@ -75,7 +75,7 @@ public final class AgeStatusEffectProviders {
|
||||
candidates.sort(Comparator.comparing(Entity::getUUID));
|
||||
LivingEntity target = candidates.get(random.nextInt(candidates.size()));
|
||||
if (!context.budget().claim() || !target.addEffect(instance)) return;
|
||||
leases.add(new Lease(new WeakReference<>(target), instance,
|
||||
leases.add(new Lease(id, new WeakReference<>(target), instance,
|
||||
context.serverTick() + duration, spec.target()));
|
||||
}
|
||||
|
||||
@@ -100,7 +100,12 @@ public final class AgeStatusEffectProviders {
|
||||
if (event.getServer().getTickCount() % 20 != 0) return;
|
||||
boolean disabled = !RivencraftConfig.instabilityEnabled() || !RivencraftConfig.statusEffectsEnabled();
|
||||
long tick = event.getServer().getTickCount();
|
||||
for (var entry : LEASES.entrySet()) prune(entry.getKey(), entry.getValue(), tick, disabled);
|
||||
for (var entry : LEASES.entrySet()) {
|
||||
AgeDefinition age = AgeRegistrySavedData.get(entry.getKey())
|
||||
.findByDimension(entry.getKey().dimension().location()).orElse(null);
|
||||
prune(entry.getKey(), entry.getValue(), tick, disabled || age == null
|
||||
|| !AgeInstabilityControls.get(entry.getKey()).enabled(age.id()));
|
||||
}
|
||||
LEASES.values().removeIf(List::isEmpty);
|
||||
}
|
||||
|
||||
@@ -146,7 +151,8 @@ public final class AgeStatusEffectProviders {
|
||||
iterator.remove();
|
||||
continue;
|
||||
}
|
||||
boolean revoke = removeAll || entity.level() != level
|
||||
boolean revoke = removeAll || !RivencraftConfig.instabilityProviderEnabled(lease.provider())
|
||||
|| entity.level() != level
|
||||
|| !allowedByPolicy(lease.target(), entity);
|
||||
if (revoke || tick >= lease.expiresAt()) {
|
||||
removeOwnedEffect(entity, lease);
|
||||
@@ -208,11 +214,11 @@ public final class AgeStatusEffectProviders {
|
||||
|
||||
private enum Target { GENERAL, HOSTILE }
|
||||
private record Spec(Holder<MobEffect> effect, int legacyDuration, boolean global, Target target) {}
|
||||
private record Lease(WeakReference<LivingEntity> entity, MobEffectInstance instance, long expiresAt,
|
||||
private record Lease(ResourceLocation provider, WeakReference<LivingEntity> entity, MobEffectInstance instance, long expiresAt,
|
||||
Target target, int amplifier, int originalDuration) {
|
||||
private Lease(WeakReference<LivingEntity> entity, MobEffectInstance instance, long expiresAt,
|
||||
private Lease(ResourceLocation provider, WeakReference<LivingEntity> entity, MobEffectInstance instance, long expiresAt,
|
||||
Target target) {
|
||||
this(entity, instance, expiresAt, target, instance.getAmplifier(), instance.getDuration());
|
||||
this(provider, entity, instance, expiresAt, target, instance.getAmplifier(), instance.getDuration());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,16 +4,22 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import net.dnorberg.rivencraft.Rivencraft;
|
||||
import net.dnorberg.rivencraft.mixin.StructurePlacementAccessor;
|
||||
import net.dnorberg.rivencraft.writing.OrderedWriting;
|
||||
import net.dnorberg.rivencraft.writing.SymbolReference;
|
||||
import net.dnorberg.rivencraft.writing.WritingEntry;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.world.level.biome.Biomes;
|
||||
import net.minecraft.world.level.biome.FixedBiomeSource;
|
||||
import net.minecraft.world.level.chunk.ChunkGeneratorStructureState;
|
||||
import net.minecraft.gametest.framework.GameTest;
|
||||
import net.minecraft.gametest.framework.GameTestHelper;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.level.levelgen.structure.BuiltinStructureSets;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureSet;
|
||||
import net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement;
|
||||
import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadStructurePlacement;
|
||||
import net.neoforged.neoforge.gametest.GameTestHolder;
|
||||
import net.neoforged.neoforge.gametest.PrefixGameTestTemplate;
|
||||
|
||||
@@ -90,6 +96,166 @@ public final class AgeStructureGameTests {
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void repeatedStructurePagesIncreasePlacementFrequency(GameTestHelper helper) {
|
||||
var lookup = helper.getLevel().registryAccess().lookupOrThrow(Registries.STRUCTURE_SET);
|
||||
|
||||
RandomSpreadStructurePlacement oneVillage = (RandomSpreadStructurePlacement) lookup
|
||||
.getOrThrow(BuiltinStructureSets.VILLAGES).value().placement();
|
||||
RandomSpreadStructurePlacement twoVillages = (RandomSpreadStructurePlacement) AgeStructureSelection
|
||||
.filteredLookup(lookup, repeated("villages", 2)).getOrThrow(BuiltinStructureSets.VILLAGES)
|
||||
.value().placement();
|
||||
helper.assertTrue(oneVillage.spacing() == 34 && twoVillages.spacing() == 24,
|
||||
"A second Village page must approximately double density by reducing grid spacing");
|
||||
|
||||
RandomSpreadStructurePlacement oneMineshaft = (RandomSpreadStructurePlacement) lookup
|
||||
.getOrThrow(BuiltinStructureSets.MINESHAFTS).value().placement();
|
||||
RandomSpreadStructurePlacement twoMineshafts = (RandomSpreadStructurePlacement) AgeStructureSelection
|
||||
.filteredLookup(lookup, repeated("mineshafts", 2)).getOrThrow(BuiltinStructureSets.MINESHAFTS)
|
||||
.value().placement();
|
||||
float oneFrequency = ((StructurePlacementAccessor) oneMineshaft).rivencraft$frequency();
|
||||
float twoFrequency = ((StructurePlacementAccessor) twoMineshafts).rivencraft$frequency();
|
||||
helper.assertTrue(oneMineshaft.spacing() == 1 && twoMineshafts.spacing() == 1
|
||||
&& Math.abs(twoFrequency - oneFrequency * 2.0F) < 0.000001F,
|
||||
"A second Mineshaft page must double its per-chunk probability");
|
||||
|
||||
ConcentricRingsStructurePlacement oneStronghold = (ConcentricRingsStructurePlacement) lookup
|
||||
.getOrThrow(BuiltinStructureSets.STRONGHOLDS).value().placement();
|
||||
ConcentricRingsStructurePlacement twoStrongholds = (ConcentricRingsStructurePlacement) AgeStructureSelection
|
||||
.filteredLookup(lookup, repeated("strongholds", 2)).getOrThrow(BuiltinStructureSets.STRONGHOLDS)
|
||||
.value().placement();
|
||||
helper.assertTrue(twoStrongholds.distance() == oneStronghold.distance()
|
||||
&& twoStrongholds.spread() == oneStronghold.spread() * 2
|
||||
&& twoStrongholds.count() == oneStronghold.count() * 2,
|
||||
"A second Stronghold page must double positions per ring and total positions");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void repeatedStructuresConstrainSeedCompletedBiomes(GameTestHelper helper) {
|
||||
OrderedWriting fourVillages = new OrderedWriting(new java.util.ArrayList<>(java.util.stream.Stream.concat(
|
||||
java.util.stream.Stream.of(WritingEntry.linkPanel()),
|
||||
java.util.stream.IntStream.range(0, 4).mapToObj(ignored -> page("feature/villages")))
|
||||
.toList()));
|
||||
try {
|
||||
AgeRegistrySavedData.validateNewWriting(helper.getLevel(), "four", fourVillages);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
helper.fail("Four Village pages without explicit biome pages must use compatible seeded completion: "
|
||||
+ exception.getMessage());
|
||||
}
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void authoredVillagesOverrideBiomeWithInstability(GameTestHelper helper) {
|
||||
OrderedWriting writing = new OrderedWriting(List.of(WritingEntry.linkPanel(),
|
||||
page("terrain/standard"), page("biome/the_end"), page("biome/single"),
|
||||
page("feature/villages"), page("feature/villages")));
|
||||
AgeDefinition age;
|
||||
try {
|
||||
age = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(),
|
||||
new AgeReference(java.util.UUID.randomUUID(), "Forced End Villages"), writing);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
helper.fail("Authored Villages must be allowed outside vanilla Village biomes: "
|
||||
+ exception.getMessage());
|
||||
return;
|
||||
}
|
||||
helper.assertValueEqual(age.instability().score(), 200,
|
||||
"Each of two Villages forced into The End biome must add 100 instability");
|
||||
helper.assertValueEqual(age.instability().breakdown().stream()
|
||||
.filter(part -> part.reason().equals("forced_biome_villages")).count(), 2L,
|
||||
"Every forced Village occurrence must retain its own instability contribution");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void mixedEndAndTaigaVillagesChargeForEndPortion(GameTestHelper helper) {
|
||||
for (String firstBiome : List.of("the_end", "plains")) {
|
||||
var writing = new OrderedWriting(List.of(WritingEntry.linkPanel(),
|
||||
page("terrain/standard"), page("biome/" + firstBiome), page("biome/taiga"),
|
||||
page("biome/tiled"), page("lighting/normal"),
|
||||
page("feature/villages"), page("feature/villages")));
|
||||
var age = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(),
|
||||
new AgeReference(java.util.UUID.randomUUID(), "Mixed " + firstBiome), writing);
|
||||
int expected = firstBiome.equals("the_end") ? 200 : 0;
|
||||
helper.assertValueEqual(age.instability().score(), expected,
|
||||
"Each Village page must charge 100 if any selected biome needs the override");
|
||||
helper.assertValueEqual(age.instability().breakdown().stream()
|
||||
.filter(part -> part.reason().equals("forced_biome_villages")).count(),
|
||||
firstBiome.equals("the_end") ? 2L : 0L,
|
||||
"Compatible Taiga must not erase the End portion's forced-biome charges");
|
||||
}
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void forcedVillageSurvivesStructureStateBiomeGate(GameTestHelper helper) {
|
||||
var registries = helper.getLevel().registryAccess();
|
||||
var sets = registries.lookupOrThrow(Registries.STRUCTURE_SET);
|
||||
var end = new FixedBiomeSource(registries.lookupOrThrow(Registries.BIOME).getOrThrow(Biomes.THE_END));
|
||||
var villages = repeated("villages", 1);
|
||||
var random = helper.getLevel().getChunkSource().randomState();
|
||||
var baseline = ChunkGeneratorStructureState.createForNormal(random, 42L, end,
|
||||
AgeStructureSelection.filteredLookup(sets, villages, end));
|
||||
helper.assertTrue(baseline.possibleStructureSets().stream()
|
||||
.noneMatch(holder -> holder.unwrapKey().filter(BuiltinStructureSets.VILLAGES::equals).isPresent()),
|
||||
"Vanilla rejects a Village structure set in a single End biome before the biome mixin runs");
|
||||
|
||||
var planned = ChunkGeneratorStructureState.createForNormal(random, 42L,
|
||||
AgeStructureSelection.planningBiomes(end, sets, villages),
|
||||
AgeStructureSelection.filteredLookup(sets, villages, end));
|
||||
helper.assertTrue(planned.possibleStructureSets().stream()
|
||||
.anyMatch(holder -> holder.unwrapKey().filter(BuiltinStructureSets.VILLAGES::equals).isPresent()),
|
||||
"The authored Village must survive the structure-state biome gate");
|
||||
var village = sets.getOrThrow(BuiltinStructureSets.VILLAGES).value().structures().getFirst().structure();
|
||||
helper.assertTrue(!planned.getPlacementsForStructure(village).isEmpty(),
|
||||
"The forced Village must have an actual placement in the Age structure state");
|
||||
helper.assertTrue(planned.possibleStructureSets().stream().noneMatch(holder -> holder.unwrapKey()
|
||||
.filter(BuiltinStructureSets.DESERT_PYRAMIDS::equals).isPresent()),
|
||||
"Planning biomes must not enable unrelated desert structures in the End Age");
|
||||
helper.assertTrue(end.possibleBiomes().size() == 1 && end.possibleBiomes().contains(
|
||||
registries.lookupOrThrow(Registries.BIOME).getOrThrow(Biomes.THE_END)),
|
||||
"The actual Age biome source must remain End-only");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void otherAuthoredStructuresOverrideBiomeWithInstability(GameTestHelper helper) {
|
||||
var registries = helper.getLevel().registryAccess();
|
||||
var sets = registries.lookupOrThrow(Registries.STRUCTURE_SET);
|
||||
var end = new FixedBiomeSource(registries.lookupOrThrow(Registries.BIOME).getOrThrow(Biomes.THE_END));
|
||||
var random = helper.getLevel().getChunkSource().randomState();
|
||||
for (var entry : Map.of("shipwrecks", BuiltinStructureSets.SHIPWRECKS,
|
||||
"trial_chambers", BuiltinStructureSets.TRIAL_CHAMBERS).entrySet()) {
|
||||
String feature = entry.getKey();
|
||||
var choices = repeated(feature, 1);
|
||||
var planned = ChunkGeneratorStructureState.createForNormal(random, 42L,
|
||||
AgeStructureSelection.planningBiomes(end, sets, choices),
|
||||
AgeStructureSelection.filteredLookup(sets, choices, end));
|
||||
helper.assertTrue(planned.possibleStructureSets().stream()
|
||||
.anyMatch(holder -> holder.unwrapKey().filter(entry.getValue()::equals).isPresent()),
|
||||
"Authored " + feature + " must survive the structure-state biome gate");
|
||||
var structure = sets.getOrThrow(entry.getValue()).value().structures().getFirst().structure();
|
||||
helper.assertTrue(!planned.getPlacementsForStructure(structure).isEmpty(),
|
||||
"Authored " + feature + " must have a placement in the End Age");
|
||||
|
||||
var writing = new OrderedWriting(List.of(WritingEntry.linkPanel(),
|
||||
page("terrain/standard"), page("biome/the_end"), page("biome/single"),
|
||||
page("feature/" + feature)));
|
||||
var age = AgeRegistrySavedData.resolveOrCreate(helper.getLevel(),
|
||||
new AgeReference(java.util.UUID.randomUUID(), "Forced " + feature), writing);
|
||||
helper.assertValueEqual(age.instability().score(), 100,
|
||||
"An authored " + feature + " outside its normal biomes must add 100 instability");
|
||||
}
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
private static List<AgeFeatureSelection.Choice> repeated(String feature, int count) {
|
||||
return java.util.stream.IntStream.range(0, count)
|
||||
.mapToObj(ignored -> new AgeFeatureSelection.Choice(id(feature), Optional.<ResourceLocation>empty()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static ResourceLocation id(String path) {
|
||||
return ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path);
|
||||
}
|
||||
|
||||
@@ -1,22 +1,33 @@
|
||||
package net.dnorberg.rivencraft.book;
|
||||
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
import net.dnorberg.rivencraft.mixin.StructurePlacementAccessor;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderOwner;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.BiomeSource;
|
||||
import net.minecraft.world.level.biome.Climate;
|
||||
import net.minecraft.world.level.levelgen.structure.BuiltinStructureSets;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureSet;
|
||||
import net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement;
|
||||
import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadStructurePlacement;
|
||||
import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement;
|
||||
|
||||
/** Frozen Age structure-page choices and their vanilla structure-set gate. */
|
||||
public final class AgeStructureSelection {
|
||||
@@ -98,14 +109,9 @@ public final class AgeStructureSelection {
|
||||
var set = registries.lookupOrThrow(Registries.STRUCTURE_SET)
|
||||
.get(ResourceKey.create(Registries.STRUCTURE_SET, setId));
|
||||
if (set.isEmpty()) return "Feature " + feature + " requires missing structure set " + setId;
|
||||
if (biomes == null) return null;
|
||||
Set<ResourceLocation> selected = Set.copyOf(biomes.biomes());
|
||||
boolean compatible = set.orElseThrow().value().structures().stream()
|
||||
.flatMap(entry -> entry.structure().value().biomes().stream())
|
||||
.map(holder -> holder.unwrapKey().map(ResourceKey::location).orElse(null))
|
||||
.anyMatch(selected::contains);
|
||||
return compatible ? null : "Feature " + feature
|
||||
+ " needs at least one biome allowed by structure set " + setId;
|
||||
// Authored structures intentionally override vanilla biome eligibility. An
|
||||
// incompatible selection is legal writing and receives instability instead.
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean placedExists(RegistryAccess registries, ResourceLocation id) {
|
||||
@@ -113,10 +119,47 @@ public final class AgeStructureSelection {
|
||||
.get(ResourceKey.create(Registries.PLACED_FEATURE, id)).isPresent();
|
||||
}
|
||||
|
||||
static Set<ResourceLocation> compatibleBiomes(ResourceLocation feature, RegistryAccess registries) {
|
||||
ResourceLocation structureSet = setId(feature);
|
||||
if (structureSet == null) return Set.of();
|
||||
return registries.lookupOrThrow(Registries.STRUCTURE_SET)
|
||||
.get(ResourceKey.create(Registries.STRUCTURE_SET, structureSet)).stream()
|
||||
.flatMap(holder -> holder.value().structures().stream())
|
||||
.flatMap(entry -> entry.structure().value().biomes().stream())
|
||||
.flatMap(holder -> holder.unwrapKey().stream())
|
||||
.map(ResourceKey::location)
|
||||
.collect(java.util.stream.Collectors.toUnmodifiableSet());
|
||||
}
|
||||
|
||||
public static boolean biomeCompatible(ResourceLocation feature, AgeBiomeSelection biomes,
|
||||
RegistryAccess registries) {
|
||||
Set<ResourceLocation> compatible = compatibleBiomes(feature, registries);
|
||||
return compatible.isEmpty() || biomes.biomes().stream().anyMatch(compatible::contains);
|
||||
}
|
||||
|
||||
/** A mixed pool still needs the authored override wherever its structure is not normally allowed. */
|
||||
public static boolean requiresBiomeOverride(ResourceLocation feature, AgeBiomeSelection biomes,
|
||||
RegistryAccess registries) {
|
||||
Set<ResourceLocation> compatible = compatibleBiomes(feature, registries);
|
||||
return !compatible.isEmpty() && biomes.biomes().stream().anyMatch(biome -> !compatible.contains(biome));
|
||||
}
|
||||
|
||||
/** True when this exact registered structure belongs to an authored structure page. */
|
||||
public static boolean authoredStructure(Structure structure, RegistryAccess registries,
|
||||
List<AgeFeatureSelection.Choice> choices) {
|
||||
Set<ResourceLocation> enabled = enabledSets(choices).keySet();
|
||||
var sets = registries.lookupOrThrow(Registries.STRUCTURE_SET);
|
||||
return enabled.stream().map(id -> ResourceKey.create(Registries.STRUCTURE_SET, id))
|
||||
.flatMap(key -> sets.get(key).stream())
|
||||
.flatMap(holder -> holder.value().structures().stream())
|
||||
.anyMatch(entry -> entry.structure().value() == structure);
|
||||
}
|
||||
|
||||
public static List<AgeFeatureSelection.Choice> randomChoices(long ageSeed, AgeRuntimeProfile profile,
|
||||
AgeBiomeSelection biomes, RegistryAccess registries) {
|
||||
List<LegacyRankChoice.Option<ResourceLocation>> eligible = new ArrayList<>(FEATURES.stream()
|
||||
.filter(id -> error(id, profile, biomes, registries) == null)
|
||||
.filter(id -> dungeons(id) || biomeCompatible(id, biomes, registries))
|
||||
.map(id -> new LegacyRankChoice.Option<>(id, randomRank(id))).toList());
|
||||
Random random = new Random(ageSeed ^ 0x5354525543545552L);
|
||||
int count = random.nextInt(3);
|
||||
@@ -136,25 +179,47 @@ public final class AgeStructureSelection {
|
||||
return 3; // Structures added after Legacy are uncommon, but still discoverable.
|
||||
}
|
||||
|
||||
private static Set<ResourceLocation> enabledSets(List<AgeFeatureSelection.Choice> choices) {
|
||||
return choices.stream().filter(choice -> feature(choice.id()) && !dungeons(choice.id()))
|
||||
.map(choice -> setId(choice.id())).collect(java.util.stream.Collectors.toUnmodifiableSet());
|
||||
private static Map<ResourceLocation, Integer> enabledSets(List<AgeFeatureSelection.Choice> choices) {
|
||||
Map<ResourceLocation, Integer> counts = new HashMap<>();
|
||||
choices.stream().filter(choice -> feature(choice.id()) && !dungeons(choice.id()))
|
||||
.forEach(choice -> counts.merge(setId(choice.id()), 1, Integer::sum));
|
||||
return Map.copyOf(counts);
|
||||
}
|
||||
|
||||
public static Stream<Holder<StructureSet>> allowedSets(Stream<Holder<StructureSet>> sets,
|
||||
List<AgeFeatureSelection.Choice> choices) {
|
||||
Set<ResourceLocation> enabled = enabledSets(choices);
|
||||
return allowedSets(sets, choices, null);
|
||||
}
|
||||
|
||||
public static Stream<Holder<StructureSet>> allowedSets(Stream<Holder<StructureSet>> sets,
|
||||
List<AgeFeatureSelection.Choice> choices,
|
||||
BiomeSource actualBiomes) {
|
||||
Map<ResourceLocation, Integer> enabled = enabledSets(choices);
|
||||
return sets.filter(holder -> holder.unwrapKey()
|
||||
.map(key -> allowed(key.location(), enabled)).orElse(false));
|
||||
.map(key -> allowed(key.location(), enabled.keySet())
|
||||
&& (actualBiomes == null || enabled.containsKey(key.location())
|
||||
|| hasActualBiome(holder.value(), actualBiomes))).orElse(false))
|
||||
.map(holder -> scaledHolder(holder, enabled));
|
||||
}
|
||||
|
||||
public static HolderLookup<StructureSet> filteredLookup(HolderLookup<StructureSet> lookup,
|
||||
List<AgeFeatureSelection.Choice> choices) {
|
||||
Set<ResourceLocation> enabled = enabledSets(choices);
|
||||
return filteredLookup(lookup, choices, null);
|
||||
}
|
||||
|
||||
public static HolderLookup<StructureSet> filteredLookup(HolderLookup<StructureSet> lookup,
|
||||
List<AgeFeatureSelection.Choice> choices,
|
||||
BiomeSource actualBiomes) {
|
||||
Map<ResourceLocation, Integer> enabled = enabledSets(choices);
|
||||
Map<ResourceKey<StructureSet>, Holder.Reference<StructureSet>> scaled = new HashMap<>();
|
||||
return new HolderLookup<>() {
|
||||
@Override
|
||||
public Optional<Holder.Reference<StructureSet>> get(ResourceKey<StructureSet> key) {
|
||||
return allowed(key.location(), enabled) ? lookup.get(key) : Optional.empty();
|
||||
if (!allowed(key.location(), enabled.keySet())) return Optional.empty();
|
||||
return lookup.get(key).filter(holder -> actualBiomes == null || enabled.containsKey(key.location())
|
||||
|| hasActualBiome(holder.value(), actualBiomes))
|
||||
.map(holder -> scaled.computeIfAbsent(key,
|
||||
ignored -> scaledReference(holder, enabled.getOrDefault(key.location(), 1))));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -164,7 +229,13 @@ public final class AgeStructureSelection {
|
||||
|
||||
@Override
|
||||
public Stream<Holder.Reference<StructureSet>> listElements() {
|
||||
return lookup.listElements().filter(holder -> allowed(holder.key().location(), enabled));
|
||||
return lookup.listElements()
|
||||
.filter(holder -> allowed(holder.key().location(), enabled.keySet()))
|
||||
.filter(holder -> actualBiomes == null || enabled.containsKey(holder.key().location())
|
||||
|| hasActualBiome(holder.value(), actualBiomes))
|
||||
.map(holder -> scaled.computeIfAbsent(holder.key(),
|
||||
ignored -> scaledReference(holder,
|
||||
enabled.getOrDefault(holder.key().location(), 1))));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -177,4 +248,101 @@ public final class AgeStructureSelection {
|
||||
private static boolean allowed(ResourceLocation set, Set<ResourceLocation> enabled) {
|
||||
return !CONTROLLED_SETS.contains(set) || enabled.contains(set);
|
||||
}
|
||||
|
||||
private static boolean hasActualBiome(StructureSet set, BiomeSource actualBiomes) {
|
||||
Set<Holder<Biome>> present = actualBiomes.possibleBiomes();
|
||||
return set.structures().stream().flatMap(entry -> entry.structure().value().biomes().stream())
|
||||
.anyMatch(present::contains);
|
||||
}
|
||||
|
||||
/** Only the structure planner sees these extra biomes; terrain and weather keep the real source. */
|
||||
public static BiomeSource planningBiomes(BiomeSource actual, HolderLookup<StructureSet> sets,
|
||||
List<AgeFeatureSelection.Choice> choices) {
|
||||
Set<ResourceLocation> enabled = enabledSets(choices).keySet();
|
||||
List<Holder<Biome>> structureBiomes = enabled.stream()
|
||||
.map(id -> sets.get(ResourceKey.create(Registries.STRUCTURE_SET, id)))
|
||||
.flatMap(Optional::stream)
|
||||
.flatMap(holder -> holder.value().structures().stream())
|
||||
.flatMap(entry -> entry.structure().value().biomes().stream())
|
||||
.distinct().toList();
|
||||
return structureBiomes.isEmpty() ? actual : new PlanningBiomeSource(actual, structureBiomes);
|
||||
}
|
||||
|
||||
private static final class PlanningBiomeSource extends BiomeSource {
|
||||
private final BiomeSource actual;
|
||||
private final List<Holder<Biome>> structureBiomes;
|
||||
|
||||
private PlanningBiomeSource(BiomeSource actual, List<Holder<Biome>> structureBiomes) {
|
||||
this.actual = actual;
|
||||
this.structureBiomes = structureBiomes;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected MapCodec<? extends BiomeSource> codec() {
|
||||
throw new UnsupportedOperationException("Structure-planning biome sources are never serialized");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Stream<Holder<Biome>> collectPossibleBiomes() {
|
||||
return Stream.concat(actual.possibleBiomes().stream(), structureBiomes.stream());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Holder<Biome> getNoiseBiome(int x, int y, int z, Climate.Sampler sampler) {
|
||||
return actual.getNoiseBiome(x, y, z, sampler);
|
||||
}
|
||||
}
|
||||
|
||||
private static Holder<StructureSet> scaledHolder(Holder<StructureSet> holder,
|
||||
Map<ResourceLocation, Integer> enabled) {
|
||||
int occurrences = holder.unwrapKey().map(key -> enabled.getOrDefault(key.location(), 1)).orElse(1);
|
||||
return occurrences == 1 ? holder : Holder.direct(scaled(holder.value(), occurrences));
|
||||
}
|
||||
|
||||
private static Holder.Reference<StructureSet> scaledReference(Holder.Reference<StructureSet> holder,
|
||||
int occurrences) {
|
||||
if (occurrences == 1) return holder;
|
||||
return new ScaledReference(holder.key(), scaled(holder.value(), occurrences));
|
||||
}
|
||||
|
||||
static StructureSet scaled(StructureSet set, int occurrences) {
|
||||
if (occurrences < 1) throw new IllegalArgumentException("Structure occurrence count must be positive");
|
||||
if (occurrences == 1) return set;
|
||||
StructurePlacement placement = set.placement();
|
||||
StructurePlacementAccessor base = (StructurePlacementAccessor) placement;
|
||||
if (placement instanceof RandomSpreadStructurePlacement random) {
|
||||
float originalFrequency = base.rivencraft$frequency();
|
||||
float frequency = Math.min(1.0F, originalFrequency * occurrences);
|
||||
double frequencyFactor = originalFrequency > 0.0F ? frequency / originalFrequency : 1.0;
|
||||
double spacingFactor = occurrences / frequencyFactor;
|
||||
int spacing = Math.max(1, (int) Math.round(random.spacing() / Math.sqrt(spacingFactor)));
|
||||
int separation = spacing == 1 ? 0 : Math.min(spacing - 1,
|
||||
(int) Math.round((double) random.separation() * spacing / random.spacing()));
|
||||
return new StructureSet(set.structures(), new RandomSpreadStructurePlacement(
|
||||
base.rivencraft$locateOffset(), base.rivencraft$frequencyReductionMethod(), frequency,
|
||||
base.rivencraft$salt(), base.rivencraft$exclusionZone(), spacing, separation,
|
||||
random.spreadType()));
|
||||
}
|
||||
if (placement instanceof ConcentricRingsStructurePlacement rings) {
|
||||
int count = saturatedMultiply(rings.count(), occurrences, 4095);
|
||||
int spread = Math.min(count, saturatedMultiply(rings.spread(), occurrences, 1023));
|
||||
return new StructureSet(set.structures(), new ConcentricRingsStructurePlacement(
|
||||
base.rivencraft$locateOffset(), base.rivencraft$frequencyReductionMethod(),
|
||||
base.rivencraft$frequency(), base.rivencraft$salt(), base.rivencraft$exclusionZone(),
|
||||
rings.distance(), spread, count, rings.preferredBiomes()));
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
private static int saturatedMultiply(int value, int multiplier, int maximum) {
|
||||
return (int) Math.min(maximum, (long) value * multiplier);
|
||||
}
|
||||
|
||||
private static final class ScaledReference extends Holder.Reference<StructureSet> {
|
||||
private static final HolderOwner<StructureSet> OWNER = new HolderOwner<>() {};
|
||||
|
||||
private ScaledReference(ResourceKey<StructureSet> key, StructureSet value) {
|
||||
super(Type.STAND_ALONE, OWNER, key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package net.dnorberg.rivencraft.book;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import net.dnorberg.rivencraft.registry.ModBlocks;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.gametest.framework.GameTest;
|
||||
import net.minecraft.gametest.framework.GameTestHelper;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.neoforged.neoforge.gametest.GameTestHolder;
|
||||
import net.neoforged.neoforge.gametest.PrefixGameTestTemplate;
|
||||
|
||||
/** Focused safety gaps; score and migration cases remain in the default suite. */
|
||||
@GameTestHolder("rivencraft_archive_instability")
|
||||
@PrefixGameTestTemplate(false)
|
||||
public final class Milestone6RegressionGameTests {
|
||||
private Milestone6RegressionGameTests() {}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void multiplayerCandidatesStayLoadedDeduplicatedAndCapped(GameTestHelper helper) {
|
||||
ChunkPos first = new ChunkPos(0, 0);
|
||||
ChunkPos second = new ChunkPos(8, 0);
|
||||
ChunkPos unloaded = new ChunkPos(0, 1);
|
||||
Set<ChunkPos> loaded = Set.of(first, second, new ChunkPos(1, 0));
|
||||
var selected = AgeHazardProviders.candidateChunks(List.of(first, second, first), 2, loaded::contains);
|
||||
helper.assertValueEqual(selected, List.of(first, second),
|
||||
"Two players in different loaded areas must each contribute one candidate before expansion");
|
||||
helper.assertTrue(!selected.contains(unloaded) && selected.stream().distinct().count() == 2,
|
||||
"Unloaded and duplicate chunks must never enter the effect context");
|
||||
helper.assertValueEqual(AgeHazardProviders.candidateChunks(List.of(first, second), 1, loaded::contains),
|
||||
List.of(first), "The per-attempt chunk cap must be obeyed with multiple players");
|
||||
helper.assertTrue(AgeHazardProviders.candidateChunks(List.of(first), 0, loaded::contains).isEmpty(),
|
||||
"A zero work budget must not inspect chunks");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void disablingEffectsCannotRerollFrozenPlan(GameTestHelper helper) {
|
||||
AgeInstability score = new AgeInstability(AgeInstability.CURRENT_VERSION, 20_000,
|
||||
List.of(new AgeInstability.Contribution("fixture", -1, 20_000, "regression score")));
|
||||
AgeInstabilityPlan plan = AgeInstabilityPlan.select(score, 741L);
|
||||
UUID id = UUID.randomUUID();
|
||||
AgeDefinition age = new AgeDefinition(id, "Policy fixture", 741L, AgeGenerationProfiles.STANDARD,
|
||||
AgeDefinition.CURRENT_GENERATION_VERSION, 0L, AgeDefinition.dimensionId(id), null,
|
||||
AgeTraits.LEGACY_DEFAULTS, null, null, List.of(), score, plan);
|
||||
AgeInstabilityControls controls = new AgeInstabilityControls();
|
||||
controls.setEnabled(id, false);
|
||||
helper.assertTrue(!controls.enabled(id) && controls.enabled(UUID.randomUUID()),
|
||||
"An Age override must not spill into another Age");
|
||||
helper.assertTrue(!AgeInstabilityRuntime.policyAllowsProvider(false, true, false)
|
||||
&& !AgeInstabilityRuntime.policyAllowsProvider(true, false, true)
|
||||
&& AgeInstabilityRuntime.policyAllowsProvider(true, false, false),
|
||||
"Per-provider disable and world-mutation disable must block only their intended effects");
|
||||
controls.setEnabled(id, true);
|
||||
helper.assertValueEqual(age.instability(), score, "Controls must not change the frozen score");
|
||||
helper.assertValueEqual(age.instabilityPlan(), plan, "Controls must not reroll the frozen provider plan");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void disabledGriefAndProtectedBlocksStayUntouched(GameTestHelper helper) {
|
||||
helper.assertTrue(!AgeHazardProviders.destructiveBlocksAllowed(false, true, true, 16)
|
||||
&& !AgeHazardProviders.destructiveBlocksAllowed(true, false, true, 16)
|
||||
&& !AgeHazardProviders.destructiveBlocksAllowed(true, true, false, 16)
|
||||
&& !AgeHazardProviders.destructiveBlocksAllowed(true, true, true, 0),
|
||||
"Every disabled destructive policy must prevent block damage");
|
||||
helper.assertTrue(AgeHazardProviders.destructiveBlocksAllowed(true, true, true, 1),
|
||||
"The enabled path must still have a bounded block budget");
|
||||
BlockPos spawn = helper.absolutePos(new BlockPos(1, 1, 1));
|
||||
BlockPos far = spawn.offset(12, 0, 12);
|
||||
UUID id = UUID.randomUUID();
|
||||
AgeDefinition age = new AgeDefinition(id, "Protected fixture", 1L, AgeGenerationProfiles.STANDARD,
|
||||
AgeDefinition.CURRENT_GENERATION_VERSION, 0L, AgeDefinition.dimensionId(id), spawn,
|
||||
AgeTraits.LEGACY_DEFAULTS);
|
||||
var level = helper.getLevel();
|
||||
helper.assertTrue(AgeHazardProviders.protectedBlock(level, age, spawn, Blocks.STONE.defaultBlockState()),
|
||||
"Arrival blocks must be protected from an explosion");
|
||||
for (var state : List.of(Blocks.CHEST.defaultBlockState(), Blocks.NETHER_PORTAL.defaultBlockState(),
|
||||
Blocks.BEDROCK.defaultBlockState(), ModBlocks.CLOUD_PLATFORM.get().defaultBlockState())) {
|
||||
helper.assertTrue(AgeHazardProviders.protectedBlock(level, age, far, state),
|
||||
"Block entities, portals, unbreakable blocks, and Rivencraft blocks must be protected");
|
||||
}
|
||||
helper.assertTrue(!AgeHazardProviders.protectedBlock(level, age, far, Blocks.STONE.defaultBlockState()),
|
||||
"Ordinary stone outside the protected arrival area remains eligible");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void generatedDiamondBlocksIncreaseLiveInstability(GameTestHelper helper) {
|
||||
var diamond = net.minecraft.resources.ResourceLocation.parse("minecraft:diamond_block");
|
||||
var ore = net.minecraft.resources.ResourceLocation.parse("minecraft:diamond_ore");
|
||||
helper.assertValueEqual(AgeBlockInstability.score(Map.of(diamond, 4000L), 400,
|
||||
Map.of(ore, 2000L), 500), 0,
|
||||
"Legacy's 400-chunk threshold must gate the live block component");
|
||||
int score = AgeBlockInstability.score(Map.of(diamond, 4010L, ore, 1604L), 401,
|
||||
Map.of(ore, 2000L), 500);
|
||||
helper.assertValueEqual(score, 40_000,
|
||||
"Ten generated diamond blocks per sampled chunk add substantial instability");
|
||||
helper.assertValueEqual(AgeBlockInstability.score(Map.of(ore, 1604L), 401,
|
||||
Map.of(ore, 2000L), 500), 0,
|
||||
"Natural ore abundance equal to the baseline must remain free");
|
||||
var effective = new AgeInstability(AgeInstability.CURRENT_VERSION, score,
|
||||
List.of(new AgeInstability.Contribution("block_profile", -1, score, "sampled excess")));
|
||||
helper.assertTrue(!AgeInstabilityPlan.select(effective, 64L).providers().isEmpty(),
|
||||
"A new effective score must unlock providers without replacing the authored base plan");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void blockProfileSamplesPersistWithoutDoubleCounting(GameTestHelper helper) {
|
||||
var data = new AgeBlockProfileSavedData();
|
||||
var diamond = net.minecraft.resources.ResourceLocation.parse("minecraft:diamond_block");
|
||||
data.add(new ChunkPos(3, 4), Map.of(diamond, 12));
|
||||
data.add(new ChunkPos(3, 4), Map.of(diamond, 100));
|
||||
helper.assertValueEqual(data.count(), 1, "A reloaded chunk must not be sampled twice");
|
||||
helper.assertValueEqual(data.totals().get(diamond), 12L, "Duplicate loads cannot inflate abundance");
|
||||
var restored = AgeBlockProfileSavedData.load(data.save(new net.minecraft.nbt.CompoundTag(),
|
||||
helper.getLevel().registryAccess()), helper.getLevel().registryAccess());
|
||||
helper.assertValueEqual(restored.count(), 1, "The profiled chunk set must survive restart");
|
||||
helper.assertValueEqual(restored.totals(), data.totals(), "Block counts must survive restart");
|
||||
helper.succeed();
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import net.dnorberg.rivencraft.client.screen.DescriptiveBookScreen;
|
||||
import net.dnorberg.rivencraft.block.entity.BookStandBlockEntity;
|
||||
import net.dnorberg.rivencraft.registry.ModBlocks;
|
||||
import net.dnorberg.rivencraft.registry.ModItems;
|
||||
import net.dnorberg.rivencraft.registry.ModDataComponents;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
@@ -87,8 +88,12 @@ public final class ClientBookInteractionHandler {
|
||||
currentBook = minecraft.player.getItemInHand(hand);
|
||||
}
|
||||
// Ignore delayed replies if the player has moved or replaced the book.
|
||||
ItemStack currentWithoutSummary = currentBook.copy();
|
||||
ItemStack replyWithoutSummary = payload.book().copy();
|
||||
currentWithoutSummary.remove(ModDataComponents.AGE_INSTABILITY_SCORE.get());
|
||||
replyWithoutSummary.remove(ModDataComponents.AGE_INSTABILITY_SCORE.get());
|
||||
if (!currentBook.is(ModItems.DESCRIPTIVE_BOOK.get())
|
||||
|| !ItemStack.isSameItemSameComponents(currentBook, payload.book())) {
|
||||
|| !ItemStack.isSameItemSameComponents(currentWithoutSummary, replyWithoutSummary)) {
|
||||
return;
|
||||
}
|
||||
minecraft.setScreen(payload.fromStand()
|
||||
|
||||
@@ -54,6 +54,7 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo
|
||||
private final List<SymbolDisplayMetadata> writingSymbols;
|
||||
private final boolean pageFree;
|
||||
private final String author;
|
||||
private final Integer instabilityScore;
|
||||
private final InteractionHand hand;
|
||||
private final BlockPos bookStandPos;
|
||||
private DestinationPreviewRenderer preview;
|
||||
@@ -74,6 +75,7 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo
|
||||
this.writingSymbols = List.copyOf(writingSymbols);
|
||||
pageFree = writing.entries().stream().noneMatch(entry -> entry.kind() == WritingEntry.Kind.SYMBOL);
|
||||
author = book.get(ModDataComponents.BOOK_AUTHOR.get());
|
||||
instabilityScore = book.get(ModDataComponents.AGE_INSTABILITY_SCORE.get());
|
||||
this.hand = hand;
|
||||
bookStandPos = null;
|
||||
}
|
||||
@@ -88,6 +90,7 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo
|
||||
this.writingSymbols = List.copyOf(writingSymbols);
|
||||
pageFree = writing.entries().stream().noneMatch(entry -> entry.kind() == WritingEntry.Kind.SYMBOL);
|
||||
author = book.get(ModDataComponents.BOOK_AUTHOR.get());
|
||||
instabilityScore = book.get(ModDataComponents.AGE_INSTABILITY_SCORE.get());
|
||||
hand = InteractionHand.MAIN_HAND;
|
||||
this.bookStandPos = bookStandPos.immutable();
|
||||
}
|
||||
@@ -250,7 +253,12 @@ public final class DescriptiveBookScreen extends Screen implements ExplorableBoo
|
||||
int detailsY = drawWrappedWithoutShadow(graphics,
|
||||
author == null || author.isBlank()
|
||||
? Component.translatable("screen.rivencraft.age.unknown_author")
|
||||
: Component.literal(author), x + 10, nameEnd + 2, 100) + 10;
|
||||
: Component.literal(author), x + 10, nameEnd + 2, 100) + 4;
|
||||
if (instabilityScore != null) {
|
||||
detailsY = drawWrappedWithoutShadow(graphics,
|
||||
Component.translatable("item.rivencraft.descriptive_book.instability", instabilityScore),
|
||||
x, detailsY, 110, instabilityScore > 0 ? UNRESOLVED_TEXT_COLOR : BOOK_TEXT_COLOR) + 6;
|
||||
}
|
||||
if (!pageFree) return;
|
||||
if (generationProfile != null) {
|
||||
Component profileName = generationProfile.getNamespace().equals("rivencraft")
|
||||
|
||||
@@ -5,12 +5,21 @@ import com.mojang.brigadier.arguments.IntegerArgumentType;
|
||||
import net.dnorberg.rivencraft.block.DecayBlock;
|
||||
import net.dnorberg.rivencraft.book.AgeDefinition;
|
||||
import net.dnorberg.rivencraft.book.AgeDecayProviders;
|
||||
import net.dnorberg.rivencraft.book.AgeHazardProviders;
|
||||
import net.dnorberg.rivencraft.book.AgeEnvironmentalProviders;
|
||||
import net.dnorberg.rivencraft.book.AgeDimensionService;
|
||||
import net.dnorberg.rivencraft.book.AgeRegistrySavedData;
|
||||
import net.dnorberg.rivencraft.book.AgeInstabilityControls;
|
||||
import net.dnorberg.rivencraft.book.AgeInstabilityRuntime;
|
||||
import net.dnorberg.rivencraft.config.RivencraftConfig;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Administrative commands for inspecting and safely unloading persistent Ages. */
|
||||
public final class RivencraftCommands {
|
||||
@@ -23,13 +32,26 @@ public final class RivencraftCommands {
|
||||
.then(Commands.literal("age")
|
||||
.then(Commands.literal("list")
|
||||
.executes(context -> listAges(context.getSource())))
|
||||
.then(Commands.literal("instability")
|
||||
.executes(context -> inspectInstability(context.getSource(),
|
||||
context.getSource().getLevel().dimension().location().toString()))
|
||||
.then(Commands.literal("enable")
|
||||
.then(Commands.argument("dimension", StringArgumentType.string())
|
||||
.suggests((context, builder) -> suggestAges(context.getSource(), builder))
|
||||
.executes(context -> setInstability(context.getSource(),
|
||||
StringArgumentType.getString(context, "dimension"), true))))
|
||||
.then(Commands.literal("disable")
|
||||
.then(Commands.argument("dimension", StringArgumentType.string())
|
||||
.suggests((context, builder) -> suggestAges(context.getSource(), builder))
|
||||
.executes(context -> setInstability(context.getSource(),
|
||||
StringArgumentType.getString(context, "dimension"), false))))
|
||||
.then(Commands.argument("dimension", StringArgumentType.string())
|
||||
.suggests((context, builder) -> suggestAges(context.getSource(), builder))
|
||||
.executes(context -> inspectInstability(context.getSource(),
|
||||
StringArgumentType.getString(context, "dimension")))))
|
||||
.then(Commands.literal("unload")
|
||||
.then(Commands.argument("dimension", StringArgumentType.string())
|
||||
.suggests((context, builder) -> {
|
||||
AgeRegistrySavedData.get(context.getSource().getLevel()).definitions()
|
||||
.forEach(age -> builder.suggest(age.dimensionId().toString()));
|
||||
return builder.buildFuture();
|
||||
})
|
||||
.suggests((context, builder) -> suggestAges(context.getSource(), builder))
|
||||
.executes(context -> unloadAge(
|
||||
context.getSource(),
|
||||
StringArgumentType.getString(context, "dimension")
|
||||
@@ -46,7 +68,25 @@ public final class RivencraftCommands {
|
||||
.then(Commands.argument("attempts", IntegerArgumentType.integer(1, 32))
|
||||
.executes(context -> pulseDecay(context.getSource(),
|
||||
StringArgumentType.getString(context, "color"),
|
||||
IntegerArgumentType.getInteger(context, "attempts")))))))));
|
||||
IntegerArgumentType.getInteger(context, "attempts")))))))
|
||||
.then(Commands.literal("hazard")
|
||||
.then(Commands.literal("pulse")
|
||||
.then(Commands.literal("lightning")
|
||||
.executes(context -> pulseHazard(context.getSource(), true)))
|
||||
.then(Commands.literal("explosion")
|
||||
.executes(context -> pulseHazard(context.getSource(), false)))))
|
||||
.then(environmentCommand())));
|
||||
}
|
||||
|
||||
private static LiteralArgumentBuilder<CommandSourceStack> environmentCommand() {
|
||||
return Commands.literal("environment")
|
||||
.then(Commands.literal("pulse")
|
||||
.then(Commands.literal("meteor")
|
||||
.executes(context -> pulseEnvironment(context.getSource(), "meteor")))
|
||||
.then(Commands.literal("burning")
|
||||
.executes(context -> pulseEnvironment(context.getSource(), "burning")))
|
||||
.then(Commands.literal("erosion")
|
||||
.executes(context -> pulseEnvironment(context.getSource(), "erosion"))));
|
||||
}
|
||||
|
||||
private static int listAges(net.minecraft.commands.CommandSourceStack source) {
|
||||
@@ -67,16 +107,8 @@ public final class RivencraftCommands {
|
||||
}
|
||||
|
||||
private static int unloadAge(net.minecraft.commands.CommandSourceStack source, String requestedDimension) {
|
||||
ResourceLocation dimension = ResourceLocation.tryParse(requestedDimension);
|
||||
if (dimension == null) {
|
||||
source.sendFailure(Component.literal("Invalid dimension id: " + requestedDimension));
|
||||
return 0;
|
||||
}
|
||||
AgeDefinition age = AgeRegistrySavedData.get(source.getLevel()).findByDimension(dimension).orElse(null);
|
||||
if (age == null) {
|
||||
source.sendFailure(Component.literal("Unknown Rivencraft Age: " + dimension));
|
||||
return 0;
|
||||
}
|
||||
AgeDefinition age = resolveAge(source, requestedDimension);
|
||||
if (age == null) return 0;
|
||||
|
||||
AgeDimensionService.UnloadResult result = AgeDimensionService.unload(source.getServer(), age);
|
||||
return switch (result) {
|
||||
@@ -97,6 +129,114 @@ public final class RivencraftCommands {
|
||||
};
|
||||
}
|
||||
|
||||
private static int inspectInstability(CommandSourceStack source, String requestedDimension) {
|
||||
AgeDefinition age = resolveAge(source, requestedDimension);
|
||||
if (age == null) return 0;
|
||||
var ageLevel = source.getServer().getLevel(net.minecraft.resources.ResourceKey.create(
|
||||
net.minecraft.core.registries.Registries.DIMENSION, age.dimensionId()));
|
||||
int blockScore = ageLevel == null ? 0 : net.dnorberg.rivencraft.book.AgeBlockInstability.score(ageLevel, age);
|
||||
var selectedPlan = ageLevel == null ? age.instabilityPlan()
|
||||
: net.dnorberg.rivencraft.book.AgeBlockInstability.effectivePlan(ageLevel, age);
|
||||
var totals = age.instability().totals();
|
||||
source.sendSuccess(() -> Component.literal(age.name() + " — " + age.dimensionId()), false);
|
||||
source.sendSuccess(() -> Component.literal("Instability: base " + totals.baseScore()
|
||||
+ ", stability bonus " + totals.stabilityBonus()
|
||||
+ ", penalty " + totals.instabilityPenalty()
|
||||
+ ", profiled blocks +" + blockScore
|
||||
+ ", effective " + Math.min(Integer.MAX_VALUE,
|
||||
(long) totals.effectiveScore() + blockScore)), false);
|
||||
if (age.instability().version() >= 2) {
|
||||
int ageSamples = ageLevel == null ? 0
|
||||
: net.dnorberg.rivencraft.book.AgeBlockInstability.sampledChunks(ageLevel);
|
||||
int baselineSamples = net.dnorberg.rivencraft.book.AgeBlockInstability.sampledChunks(
|
||||
source.getServer().overworld());
|
||||
source.sendSuccess(() -> Component.literal("Block profile: Age " + ageSamples
|
||||
+ "/401, Overworld baseline " + baselineSamples + "/500"
|
||||
+ (ageLevel == null ? " (Age unloaded)" : "")), false);
|
||||
}
|
||||
boolean enabled = AgeInstabilityControls.get(source.getLevel()).enabled(age.id());
|
||||
source.sendSuccess(() -> Component.literal("Runtime: " + (enabled ? "Age enabled" : "Age disabled")
|
||||
+ ", global " + (RivencraftConfig.instabilityEnabled() ? "enabled" : "disabled")
|
||||
+ "; saved score and plan are unchanged by controls"), false);
|
||||
source.sendSuccess(() -> Component.literal("Score breakdown (saved schema v"
|
||||
+ age.instability().version() + "):"), false);
|
||||
age.instability().breakdown().forEach(part -> source.sendSuccess(() -> Component.literal(
|
||||
" " + (part.pageIndex() < 0 ? "Age" : "page " + (part.pageIndex() + 1))
|
||||
+ " +" + part.points() + " " + part.reason() + ": " + part.detail()), false));
|
||||
source.sendSuccess(() -> Component.literal("Selected providers (effective plan v"
|
||||
+ selectedPlan.version() + "): " + selectedPlan.providers().size()), false);
|
||||
selectedPlan.providers().forEach(provider -> source.sendSuccess(() -> Component.literal(
|
||||
" " + provider.id() + " level " + provider.level() + " — "
|
||||
+ AgeInstabilityRuntime.providerStatus(ageLevel == null ? source.getLevel() : ageLevel,
|
||||
age, provider.id())), false));
|
||||
if (selectedPlan.providers().isEmpty()) source.sendSuccess(() -> Component.literal(
|
||||
" No providers selected; an old neutral Age stays neutral."), false);
|
||||
source.sendSuccess(() -> Component.literal("Limits: cooldown " + RivencraftConfig.instabilityCooldown()
|
||||
+ " ticks, " + RivencraftConfig.instabilityMaxAges() + " Ages/tick, "
|
||||
+ RivencraftConfig.instabilityMaxProviders() + " providers/Age, "
|
||||
+ RivencraftConfig.instabilityMaxActions() + " actions/Age, level cap "
|
||||
+ RivencraftConfig.instabilityMaxLevel()), false);
|
||||
source.sendSuccess(() -> Component.literal("Mutable player bonuses: disabled (no active Legacy registration)"),
|
||||
false);
|
||||
return (int) Math.min(Integer.MAX_VALUE, (long) totals.effectiveScore() + blockScore);
|
||||
}
|
||||
|
||||
private static java.util.concurrent.CompletableFuture<com.mojang.brigadier.suggestion.Suggestions> suggestAges(
|
||||
CommandSourceStack source, com.mojang.brigadier.suggestion.SuggestionsBuilder builder) {
|
||||
AgeRegistrySavedData.get(source.getLevel()).definitions()
|
||||
.forEach(age -> {
|
||||
builder.suggest(age.dimensionId().toString());
|
||||
if (!age.name().contains(" ")) builder.suggest(age.name());
|
||||
});
|
||||
return builder.buildFuture();
|
||||
}
|
||||
|
||||
/** Bare input is an Age name or short path, never a minecraft-namespace resource ID. */
|
||||
static List<AgeDefinition> matchingAges(List<AgeDefinition> ages, String requested) {
|
||||
String input = requested.strip();
|
||||
if (input.isEmpty()) return List.of();
|
||||
if (input.contains(":")) {
|
||||
ResourceLocation id = ResourceLocation.tryParse(input);
|
||||
return id == null ? List.of() : ages.stream()
|
||||
.filter(age -> age.dimensionId().equals(id)).toList();
|
||||
}
|
||||
List<AgeDefinition> names = ages.stream()
|
||||
.filter(age -> age.name().equalsIgnoreCase(input)).toList();
|
||||
if (!names.isEmpty()) return names;
|
||||
String path = input.toLowerCase(Locale.ROOT);
|
||||
if (!path.startsWith("age/")) path = "age/" + path;
|
||||
String expectedPath = path;
|
||||
return ages.stream().filter(age -> age.dimensionId().getPath().equals(expectedPath)).toList();
|
||||
}
|
||||
|
||||
private static AgeDefinition resolveAge(CommandSourceStack source, String requested) {
|
||||
List<AgeDefinition> matches = matchingAges(
|
||||
AgeRegistrySavedData.get(source.getLevel()).definitions(), requested);
|
||||
if (matches.size() == 1) return matches.getFirst();
|
||||
if (matches.size() > 1) {
|
||||
source.sendFailure(Component.literal("Ambiguous Age name '" + requested
|
||||
+ "'. Use its full dimension ID from /rivencraft age list."));
|
||||
} else {
|
||||
source.sendFailure(Component.literal("Unknown Rivencraft Age '" + requested
|
||||
+ "'. Use its name or dimension ID from /rivencraft age list."));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static int setInstability(CommandSourceStack source, String requestedDimension, boolean enabled) {
|
||||
if (!source.hasPermission(2)) {
|
||||
source.sendFailure(Component.literal("Operator permission is required to change Age instability."));
|
||||
return 0;
|
||||
}
|
||||
AgeDefinition age = resolveAge(source, requestedDimension);
|
||||
if (age == null) return 0;
|
||||
boolean changed = AgeInstabilityControls.get(source.getLevel()).setEnabled(age.id(), enabled);
|
||||
source.sendSuccess(() -> Component.literal(age.name() + " instability "
|
||||
+ (enabled ? "enabled" : "disabled") + (changed ? "" : " (already set)")
|
||||
+ ". The saved score and provider plan are unchanged."), true);
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static int pulseDecay(net.minecraft.commands.CommandSourceStack source, String colorName, int attempts) {
|
||||
DecayBlock.Color color;
|
||||
try {
|
||||
@@ -118,4 +258,32 @@ public final class RivencraftCommands {
|
||||
+ " block(s) converted in " + attempts + " bounded attempt(s)."), true);
|
||||
return changed;
|
||||
}
|
||||
|
||||
private static int pulseHazard(net.minecraft.commands.CommandSourceStack source, boolean lightning) {
|
||||
if (source.getPlayer() == null) {
|
||||
source.sendFailure(Component.literal("Run this command as a player standing in an Age."));
|
||||
return 0;
|
||||
}
|
||||
int result = AgeHazardProviders.pulseForTesting(source.getPlayer(), lightning);
|
||||
if (result < 0) source.sendFailure(Component.literal("Enter a loaded Age and enable instability_hazards.enabled first."));
|
||||
else if (result == 0) source.sendFailure(Component.literal("Hazard is on cooldown or no safe loaded target is available."));
|
||||
else source.sendSuccess(() -> Component.literal("Triggered one bounded "
|
||||
+ (lightning ? "lightning strike" : "explosion") + " in this Age."), true);
|
||||
return Math.max(0, result);
|
||||
}
|
||||
|
||||
private static int pulseEnvironment(CommandSourceStack source, String effect) {
|
||||
if (source.getPlayer() == null) {
|
||||
source.sendFailure(Component.literal("Run this command as a player standing in an Age."));
|
||||
return 0;
|
||||
}
|
||||
int result = AgeEnvironmentalProviders.pulseForTesting(source.getPlayer(), effect);
|
||||
if (result == -2) source.sendFailure(Component.literal(
|
||||
"Burning is extinguished by rain or water. Move to a dry, sky-exposed spot and retry."));
|
||||
else if (result < 0) source.sendFailure(Component.literal("Enter a loaded Age to test the environmental effect."));
|
||||
else if (result == 0) source.sendFailure(Component.literal(
|
||||
"No eligible target, effect disabled, or meteor on cooldown. For erosion, aim at a block beside source fluid."));
|
||||
else source.sendSuccess(() -> Component.literal("Triggered " + effect + " in this Age."), true);
|
||||
return Math.max(0, result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package net.dnorberg.rivencraft.command;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import net.dnorberg.rivencraft.Rivencraft;
|
||||
import net.dnorberg.rivencraft.book.AgeDefinition;
|
||||
import net.dnorberg.rivencraft.book.AgeGenerationProfiles;
|
||||
import net.dnorberg.rivencraft.book.AgeTraits;
|
||||
import net.minecraft.gametest.framework.GameTest;
|
||||
import net.minecraft.gametest.framework.GameTestHelper;
|
||||
import net.neoforged.neoforge.gametest.GameTestHolder;
|
||||
import net.neoforged.neoforge.gametest.PrefixGameTestTemplate;
|
||||
|
||||
/** Command-facing Age lookup regression checks. */
|
||||
@GameTestHolder(Rivencraft.MOD_ID)
|
||||
@PrefixGameTestTemplate(false)
|
||||
public final class RivencraftCommandsGameTests {
|
||||
private RivencraftCommandsGameTests() {}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void bareAgeNameDoesNotBecomeMinecraftResourceId(GameTestHelper helper) {
|
||||
AgeDefinition fort = age("Fort", "fort");
|
||||
AgeDefinition tower = age("Tower", "tower");
|
||||
List<AgeDefinition> ages = List.of(fort, tower);
|
||||
for (String query : List.of("fort", "Fort", "age/fort", "rivencraft:age/fort")) {
|
||||
helper.assertValueEqual(RivencraftCommands.matchingAges(ages, query), List.of(fort),
|
||||
"Age lookup must accept its name, short path, and full dimension ID");
|
||||
}
|
||||
helper.assertTrue(RivencraftCommands.matchingAges(ages, "minecraft:fort").isEmpty(),
|
||||
"An explicit wrong namespace must not resolve to a Rivencraft Age");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
@GameTest(template = "empty")
|
||||
public static void duplicateNamesRequireFullDimensionId(GameTestHelper helper) {
|
||||
AgeDefinition first = age("Fort", "fort");
|
||||
AgeDefinition second = age("Fort", "fort_2");
|
||||
List<AgeDefinition> ages = List.of(first, second);
|
||||
helper.assertValueEqual(RivencraftCommands.matchingAges(ages, "fort").size(), 2,
|
||||
"Duplicate display names must remain ambiguous, not silently pick an Age");
|
||||
helper.assertValueEqual(RivencraftCommands.matchingAges(ages, "rivencraft:age/fort_2"),
|
||||
List.of(second), "A full dimension ID must select the intended duplicate");
|
||||
helper.succeed();
|
||||
}
|
||||
|
||||
private static AgeDefinition age(String name, String path) {
|
||||
UUID id = UUID.randomUUID();
|
||||
return new AgeDefinition(id, name, 1L, AgeGenerationProfiles.STANDARD,
|
||||
AgeDefinition.CURRENT_GENERATION_VERSION, 0L,
|
||||
net.minecraft.resources.ResourceLocation.parse("rivencraft:age/" + path), null,
|
||||
AgeTraits.LEGACY_DEFAULTS);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
package net.dnorberg.rivencraft.config;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.neoforged.neoforge.common.ModConfigSpec;
|
||||
|
||||
/** Server-configurable gameplay policies. */
|
||||
@@ -35,6 +38,28 @@ public final class RivencraftConfig {
|
||||
private static final ModConfigSpec.IntValue STATUS_EFFECTS_MAX_DURATION;
|
||||
private static final ModConfigSpec.BooleanValue DECAY_ENABLED;
|
||||
private static final ModConfigSpec.IntValue DECAY_MAX_ATTEMPTS;
|
||||
private static final ModConfigSpec.BooleanValue HAZARDS_ENABLED;
|
||||
private static final ModConfigSpec.BooleanValue HAZARDS_BLOCK_DAMAGE;
|
||||
private static final ModConfigSpec.BooleanValue HAZARDS_PLAYER_DAMAGE;
|
||||
private static final ModConfigSpec.BooleanValue HAZARDS_FIRE;
|
||||
private static final ModConfigSpec.IntValue HAZARDS_MIN_INTERVAL;
|
||||
private static final ModConfigSpec.IntValue HAZARDS_MAX_CHUNKS;
|
||||
private static final ModConfigSpec.IntValue HAZARDS_MAX_BLOCKS;
|
||||
private static final ModConfigSpec.IntValue HAZARDS_MAX_ENTITIES;
|
||||
private static final ModConfigSpec.IntValue HAZARDS_MAX_DAMAGE;
|
||||
private static final ModConfigSpec.IntValue HAZARDS_EXPLOSION_RADIUS;
|
||||
private static final ModConfigSpec.BooleanValue METEOR_ENABLED;
|
||||
private static final ModConfigSpec.BooleanValue METEOR_BLOCK_DAMAGE;
|
||||
private static final ModConfigSpec.BooleanValue METEOR_PLAYER_DAMAGE;
|
||||
private static final ModConfigSpec.BooleanValue METEOR_FIRE;
|
||||
private static final ModConfigSpec.IntValue METEOR_MAX_BLOCKS;
|
||||
private static final ModConfigSpec.IntValue METEOR_MAX_ENTITIES;
|
||||
private static final ModConfigSpec.IntValue METEOR_MAX_DAMAGE;
|
||||
private static final ModConfigSpec.BooleanValue SCORCH_ENABLED;
|
||||
private static final ModConfigSpec.BooleanValue SCORCH_PLAYERS;
|
||||
private static final ModConfigSpec.IntValue SCORCH_MAX_TARGETS;
|
||||
private static final ModConfigSpec.BooleanValue EROSION_ENABLED;
|
||||
private static final Map<String, ModConfigSpec.BooleanValue> INSTABILITY_PROVIDERS = new HashMap<>();
|
||||
|
||||
static {
|
||||
ModConfigSpec.Builder builder = new ModConfigSpec.Builder();
|
||||
@@ -97,6 +122,71 @@ public final class RivencraftConfig {
|
||||
DECAY_MAX_ATTEMPTS = builder.comment("Maximum six-neighbor decay conversion attempts per provider call; at most one block changes.")
|
||||
.defineInRange("max_attempts_per_call", 4, 1, 6);
|
||||
builder.pop();
|
||||
builder.push("instability_hazards");
|
||||
HAZARDS_ENABLED = builder.comment("Run Legacy lightning and explosion cards in loaded Ages.")
|
||||
.define("enabled", true);
|
||||
HAZARDS_BLOCK_DAMAGE = builder.comment("Allow explosions to destroy blocks. Also requires instability.world_mutation and mobGriefing.")
|
||||
.define("block_damage", true);
|
||||
HAZARDS_PLAYER_DAMAGE = builder.comment("Allow lightning and explosions to hurt survival/adventure players.")
|
||||
.define("player_damage", true);
|
||||
HAZARDS_FIRE = builder.comment("Allow lightning and explosions to ignite blocks when doFireTick is enabled.")
|
||||
.define("fire", true);
|
||||
HAZARDS_MIN_INTERVAL = builder.comment("Minimum game ticks between hazard events of each type in one Age.",
|
||||
"Renamed from min_interval_ticks so existing 200-tick test configs receive the Legacy-rate default.")
|
||||
.defineInRange("minimum_gap_ticks", 20, 20, 12000);
|
||||
HAZARDS_MAX_CHUNKS = builder.comment("Maximum already-loaded chunks sampled around Age players per hazard roll.")
|
||||
.defineInRange("max_loaded_chunks", 81, 1, 169);
|
||||
HAZARDS_MAX_BLOCKS = builder.comment("Maximum distinct blocks one instability explosion may destroy.")
|
||||
.defineInRange("max_explosion_blocks", 16, 0, 64);
|
||||
HAZARDS_MAX_ENTITIES = builder.comment("Maximum entities damaged by one hazard event.")
|
||||
.defineInRange("max_damaged_entities", 8, 0, 32);
|
||||
HAZARDS_MAX_DAMAGE = builder.comment("Maximum damage per entity from one hazard event.")
|
||||
.defineInRange("max_entity_damage", 12, 0, 40);
|
||||
HAZARDS_EXPLOSION_RADIUS = builder.comment("Explosion strength. Legacy used 3; capped to remain inside one loaded chunk.")
|
||||
.defineInRange("explosion_radius", 3, 1, 3);
|
||||
builder.pop();
|
||||
builder.push("instability_meteor");
|
||||
METEOR_ENABLED = builder.comment("Allow the active Legacy meteor card in loaded Ages.")
|
||||
.define("enabled", true);
|
||||
METEOR_BLOCK_DAMAGE = builder.comment("Allow meteor impacts to destroy blocks; also requires instability.world_mutation and mobGriefing.")
|
||||
.define("block_damage", true);
|
||||
METEOR_PLAYER_DAMAGE = builder.comment("Allow meteor impacts to hurt survival/adventure players.")
|
||||
.define("player_damage", true);
|
||||
METEOR_FIRE = builder.comment("Allow meteor impacts to ignite blocks when doFireTick is enabled.")
|
||||
.define("fire", true);
|
||||
METEOR_MAX_BLOCKS = builder.comment("Maximum blocks destroyed by one meteor impact.")
|
||||
.defineInRange("max_impact_blocks", 24, 0, 64);
|
||||
METEOR_MAX_ENTITIES = builder.comment("Maximum entities damaged by one meteor impact.")
|
||||
.defineInRange("max_damaged_entities", 8, 0, 32);
|
||||
METEOR_MAX_DAMAGE = builder.comment("Maximum damage per entity from one meteor impact.")
|
||||
.defineInRange("max_entity_damage", 12, 0, 40);
|
||||
builder.pop();
|
||||
builder.push("instability_scorching");
|
||||
SCORCH_ENABLED = builder.comment("Allow Legacy's active burning card to ignite sky-exposed entities.")
|
||||
.define("enabled", true);
|
||||
SCORCH_PLAYERS = builder.comment("Allow burning to affect survival/adventure players.")
|
||||
.define("affect_players", true);
|
||||
SCORCH_MAX_TARGETS = builder.comment("Maximum entities ignited per Age scheduler pass.")
|
||||
.defineInRange("max_targets_per_pass", 4, 0, 16);
|
||||
builder.pop();
|
||||
builder.push("instability_erosion");
|
||||
EROSION_ENABLED = builder.comment("Enable Legacy's dormant erosion effect for testing; no saved provider card is added.",
|
||||
"Ages with a destructive instability score may spread adjacent fluid into one safe block per pass.")
|
||||
.define("enabled", true);
|
||||
builder.pop();
|
||||
builder.push("instability_providers");
|
||||
for (String provider : new String[] {
|
||||
"blindness", "blindness_global", "enemyregen_global", "enemyresist_global",
|
||||
"fatigue", "fatigue_global", "hunger", "hunger_global", "nausea", "nausea_global",
|
||||
"poison", "poison_global", "slow", "slow_global", "weakness", "weakness_global",
|
||||
"wither", "wither_global", "burning", "crumble", "decayblue", "decaypurple",
|
||||
"decayred", "decaywhite", "explosions", "lightning", "meteors", "erosion"
|
||||
}) {
|
||||
INSTABILITY_PROVIDERS.put(provider, builder.comment(
|
||||
"Allow this saved provider to run. Disabling it does not change an Age's frozen plan.")
|
||||
.define(provider, true));
|
||||
}
|
||||
builder.pop();
|
||||
SPEC = builder.build();
|
||||
}
|
||||
|
||||
@@ -120,6 +210,11 @@ public final class RivencraftConfig {
|
||||
}
|
||||
|
||||
public static boolean instabilityEnabled() { return INSTABILITY_ENABLED.get(); }
|
||||
public static boolean instabilityProviderEnabled(ResourceLocation id) {
|
||||
ModConfigSpec.BooleanValue value = id.getNamespace().equals("rivencraft")
|
||||
? INSTABILITY_PROVIDERS.get(id.getPath()) : null;
|
||||
return value != null && value.get();
|
||||
}
|
||||
public static boolean instabilityWorldMutation() { return INSTABILITY_WORLD_MUTATION.get(); }
|
||||
public static int instabilityCooldown() { return INSTABILITY_COOLDOWN.get(); }
|
||||
public static int instabilityMaxAges() { return INSTABILITY_MAX_AGES.get(); }
|
||||
@@ -136,4 +231,25 @@ public final class RivencraftConfig {
|
||||
public static int statusEffectsMaxDuration() { return STATUS_EFFECTS_MAX_DURATION.get(); }
|
||||
public static boolean decayEnabled() { return DECAY_ENABLED.get(); }
|
||||
public static int decayMaxAttempts() { return DECAY_MAX_ATTEMPTS.get(); }
|
||||
public static boolean hazardsEnabled() { return HAZARDS_ENABLED.get(); }
|
||||
public static boolean hazardsBlockDamage() { return HAZARDS_BLOCK_DAMAGE.get(); }
|
||||
public static boolean hazardsPlayerDamage() { return HAZARDS_PLAYER_DAMAGE.get(); }
|
||||
public static boolean hazardsFire() { return HAZARDS_FIRE.get(); }
|
||||
public static int hazardsMinInterval() { return HAZARDS_MIN_INTERVAL.get(); }
|
||||
public static int hazardsMaxChunks() { return HAZARDS_MAX_CHUNKS.get(); }
|
||||
public static int hazardsMaxBlocks() { return HAZARDS_MAX_BLOCKS.get(); }
|
||||
public static int hazardsMaxEntities() { return HAZARDS_MAX_ENTITIES.get(); }
|
||||
public static int hazardsMaxDamage() { return HAZARDS_MAX_DAMAGE.get(); }
|
||||
public static int hazardsExplosionRadius() { return HAZARDS_EXPLOSION_RADIUS.get(); }
|
||||
public static boolean meteorEnabled() { return METEOR_ENABLED.get(); }
|
||||
public static boolean meteorBlockDamage() { return METEOR_BLOCK_DAMAGE.get(); }
|
||||
public static boolean meteorPlayerDamage() { return METEOR_PLAYER_DAMAGE.get(); }
|
||||
public static boolean meteorFire() { return METEOR_FIRE.get(); }
|
||||
public static int meteorMaxBlocks() { return METEOR_MAX_BLOCKS.get(); }
|
||||
public static int meteorMaxEntities() { return METEOR_MAX_ENTITIES.get(); }
|
||||
public static int meteorMaxDamage() { return METEOR_MAX_DAMAGE.get(); }
|
||||
public static boolean scorchEnabled() { return SCORCH_ENABLED.get(); }
|
||||
public static boolean scorchPlayers() { return SCORCH_PLAYERS.get(); }
|
||||
public static int scorchMaxTargets() { return SCORCH_MAX_TARGETS.get(); }
|
||||
public static boolean erosionEnabled() { return EROSION_ENABLED.get(); }
|
||||
}
|
||||
@@ -112,6 +112,11 @@ public final class DescriptiveBookItem extends Item {
|
||||
? Component.translatable("item.rivencraft.descriptive_book.unwritten")
|
||||
: Component.translatable("item.rivencraft.descriptive_book.age", age.name());
|
||||
tooltipComponents.add(status.withStyle(ChatFormatting.GRAY));
|
||||
Integer instability = stack.get(ModDataComponents.AGE_INSTABILITY_SCORE.get());
|
||||
if (age != null && instability != null) {
|
||||
tooltipComponents.add(Component.translatable("item.rivencraft.descriptive_book.instability", instability)
|
||||
.withStyle(instability > 0 ? ChatFormatting.DARK_RED : ChatFormatting.DARK_GREEN));
|
||||
}
|
||||
stack.getOrDefault(ModDataComponents.LINK_PROPERTIES.get(), LinkProperties.NONE)
|
||||
.forDescriptiveBook().appendTooltip(tooltipComponents);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package net.dnorberg.rivencraft.mixin;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import net.dnorberg.rivencraft.book.AgeFeatureSelection;
|
||||
import net.dnorberg.rivencraft.book.AgeStructureSelection;
|
||||
import net.dnorberg.rivencraft.world.AgeFeatureChunkGenerator;
|
||||
import net.dnorberg.rivencraft.world.AgeFlatChunkGenerator;
|
||||
import net.minecraft.world.level.chunk.ChunkGenerator;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Shadow;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
/** Lets explicitly authored structures generate outside their vanilla biome sets. */
|
||||
@Mixin(Structure.class)
|
||||
public abstract class AgeStructureBiomeMixin {
|
||||
@Shadow
|
||||
protected abstract Optional<Structure.GenerationStub> findGenerationPoint(
|
||||
Structure.GenerationContext context);
|
||||
|
||||
@Inject(method = "findValidGenerationPoint", at = @At("HEAD"), cancellable = true)
|
||||
private void rivencraft$allowAuthoredStructureBiome(Structure.GenerationContext context,
|
||||
CallbackInfoReturnable<Optional<Structure.GenerationStub>> cir) {
|
||||
ChunkGenerator generator = context.chunkGenerator();
|
||||
List<AgeFeatureSelection.Choice> features;
|
||||
if (generator instanceof AgeFeatureChunkGenerator age) features = age.ageFeatures();
|
||||
else if (generator instanceof AgeFlatChunkGenerator age) features = age.ageFeatures();
|
||||
else return;
|
||||
if (AgeStructureSelection.authoredStructure((Structure) (Object) this,
|
||||
context.registryAccess(), features)) {
|
||||
cir.setReturnValue(findGenerationPoint(context));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package net.dnorberg.rivencraft.mixin;
|
||||
|
||||
import java.util.Optional;
|
||||
import net.minecraft.core.Vec3i;
|
||||
import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.gen.Accessor;
|
||||
|
||||
/** Exposes immutable placement settings so per-Age structure density can preserve vanilla behavior. */
|
||||
@Mixin(StructurePlacement.class)
|
||||
public interface StructurePlacementAccessor {
|
||||
@Accessor("locateOffset")
|
||||
Vec3i rivencraft$locateOffset();
|
||||
|
||||
@Accessor("frequencyReductionMethod")
|
||||
StructurePlacement.FrequencyReductionMethod rivencraft$frequencyReductionMethod();
|
||||
|
||||
@Accessor("frequency")
|
||||
float rivencraft$frequency();
|
||||
|
||||
@Accessor("salt")
|
||||
int rivencraft$salt();
|
||||
|
||||
@Accessor("exclusionZone")
|
||||
Optional<StructurePlacement.ExclusionZone> rivencraft$exclusionZone();
|
||||
}
|
||||
@@ -111,6 +111,11 @@ public final class ModNetworking {
|
||||
access.stack().set(ModDataComponents.AGE_GENERATION_PROFILE.get(), definition.generationProfile());
|
||||
access.sync().run();
|
||||
}
|
||||
if (definition != null && !java.util.Objects.equals(
|
||||
access.stack().get(ModDataComponents.AGE_INSTABILITY_SCORE.get()), definition.instability().score())) {
|
||||
access.stack().set(ModDataComponents.AGE_INSTABILITY_SCORE.get(), definition.instability().score());
|
||||
access.sync().run();
|
||||
}
|
||||
// Requests run on the same server thread as Age creation. A request queued
|
||||
// during generation can only open the finished book, never a stale client copy.
|
||||
player.inventoryMenu.broadcastChanges();
|
||||
@@ -170,8 +175,10 @@ public final class ModNetworking {
|
||||
|
||||
access.stack().set(ModDataComponents.AGE_REFERENCE.get(), reference);
|
||||
access.stack().set(ModDataComponents.BOOK_AUTHOR.get(), player.getGameProfile().getName());
|
||||
AgeRegistrySavedData.get(player.serverLevel()).find(reference.id()).ifPresent(definition ->
|
||||
access.stack().set(ModDataComponents.AGE_GENERATION_PROFILE.get(), definition.generationProfile()));
|
||||
AgeRegistrySavedData.get(player.serverLevel()).find(reference.id()).ifPresent(definition -> {
|
||||
access.stack().set(ModDataComponents.AGE_GENERATION_PROFILE.get(), definition.generationProfile());
|
||||
access.stack().set(ModDataComponents.AGE_INSTABILITY_SCORE.get(), definition.instability().score());
|
||||
});
|
||||
access.stack().set(DataComponents.CUSTOM_NAME, Component.literal(title));
|
||||
access.sync().run();
|
||||
player.level().playSound(null, player.blockPosition(), SoundEvents.BOOK_PAGE_TURN, SoundSource.PLAYERS, 1.0F, 1.0F);
|
||||
|
||||
@@ -81,6 +81,13 @@ public final class ModDataComponents {
|
||||
.networkSynchronized(ByteBufCodecs.STRING_UTF8)
|
||||
.cacheEncoding()
|
||||
.build());
|
||||
/** Server-written display summary only; detailed scoring and provider plans remain server-owned. */
|
||||
public static final DeferredHolder<DataComponentType<?>, DataComponentType<Integer>> AGE_INSTABILITY_SCORE =
|
||||
DATA_COMPONENTS.register("age_instability_score", () -> DataComponentType.<Integer>builder()
|
||||
.persistent(Codec.intRange(0, Integer.MAX_VALUE))
|
||||
.networkSynchronized(ByteBufCodecs.VAR_INT)
|
||||
.cacheEncoding()
|
||||
.build());
|
||||
public static final DeferredHolder<DataComponentType<?>, DataComponentType<Integer>> INK_REMAINING =
|
||||
DATA_COMPONENTS.register("ink_remaining", () -> DataComponentType.<Integer>builder()
|
||||
.persistent(Codec.intRange(0, 16))
|
||||
|
||||
@@ -15,6 +15,7 @@ public final class ModSounds {
|
||||
|
||||
public static final DeferredHolder<SoundEvent, SoundEvent> LINK = register("linking.link");
|
||||
public static final DeferredHolder<SoundEvent, SoundEvent> LINK_FISSURE = register("linking.link-fissure");
|
||||
public static final DeferredHolder<SoundEvent, SoundEvent> METEOR_ROAR = register("entity.meteor.roar");
|
||||
|
||||
private ModSounds() {
|
||||
}
|
||||
|
||||
@@ -110,8 +110,10 @@ public final class AgeFeatureChunkGenerator extends NoiseBasedChunkGenerator {
|
||||
|
||||
@Override
|
||||
public ChunkGeneratorStructureState createState(HolderLookup<StructureSet> sets, RandomState random, long seed) {
|
||||
return ChunkGeneratorStructureState.createForNormal(random, seed, getBiomeSource(),
|
||||
AgeStructureSelection.filteredLookup(sets, features));
|
||||
BiomeSource actual = getBiomeSource();
|
||||
return ChunkGeneratorStructureState.createForNormal(random, seed,
|
||||
AgeStructureSelection.planningBiomes(actual, sets, features),
|
||||
AgeStructureSelection.filteredLookup(sets, features, actual));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -72,8 +72,9 @@ public final class AgeFlatChunkGenerator extends ChunkGenerator {
|
||||
Stream<Holder<StructureSet>> entries = settings.structureOverrides()
|
||||
.map(HolderSet::stream)
|
||||
.orElseGet(() -> structures.listElements().map(holder -> (Holder<StructureSet>) holder));
|
||||
return ChunkGeneratorStructureState.createForFlat(random, seed, biomeSource,
|
||||
AgeStructureSelection.allowedSets(entries, features));
|
||||
return ChunkGeneratorStructureState.createForFlat(random, seed,
|
||||
AgeStructureSelection.planningBiomes(biomeSource, structures, features),
|
||||
AgeStructureSelection.allowedSets(entries, features, biomeSource));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"item.rivencraft.descriptive_book": "Descriptive Book",
|
||||
"item.rivencraft.descriptive_book.unwritten": "Unwritten",
|
||||
"item.rivencraft.descriptive_book.age": "%s",
|
||||
"item.rivencraft.descriptive_book.instability": "Instability: %s (potential)",
|
||||
"item.rivencraft.linking_book": "Linking Book",
|
||||
"item.rivencraft.linking_book.unbound": "Unbound — sneak-use to bind",
|
||||
"item.rivencraft.linking_book.destination": "%s (%s, %s, %s)",
|
||||
|
||||
@@ -10,5 +10,9 @@
|
||||
"linking.link-fissure": {
|
||||
"category": "player",
|
||||
"sounds": [{"name": "rivencraft:linking/link-fissure"}]
|
||||
},
|
||||
"entity.meteor.roar": {
|
||||
"category": "hostile",
|
||||
"sounds": [{"name": "rivencraft:entity/meteor/roar"}]
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -4,7 +4,9 @@
|
||||
"package": "net.dnorberg.rivencraft.mixin",
|
||||
"compatibilityLevel": "JAVA_21",
|
||||
"mixins": [
|
||||
"AgeDungeonPlacementMixin"
|
||||
"AgeDungeonPlacementMixin",
|
||||
"AgeStructureBiomeMixin",
|
||||
"StructurePlacementAccessor"
|
||||
],
|
||||
"client": [
|
||||
"client.ClientLevelSoundMixin",
|
||||
|
||||
Reference in new issue
Block a user