From dd219bb58a02eee828cb43e10667fb50b9a100ad Mon Sep 17 00:00:00 2001 From: Dustin Norberg Date: Sat, 10 Oct 2026 03:41:16 -0400 Subject: [PATCH] Completed issue 71 and allowed village pages to be placed in illegal biomes adding +100 instability --- docs/INSTABILITY_SCORE.md | 4 +- docs/LEGACY_INSTABILITY_AUDIT.md | 10 +- docs/WRITING_GRAMMAR.md | 2 +- gradle.properties | 2 +- .../rivencraft/book/AgeBiomeSelection.java | 56 ++++++++ .../rivencraft/book/AgeInstability.java | 100 ++++++++++++-- .../book/AgePersistenceGameTests.java | 80 ++++++++++- .../rivencraft/book/AgeRegistrySavedData.java | 2 +- .../book/AgeStructureGameTests.java | 81 +++++++++++ .../book/AgeStructureSelection.java | 127 +++++++++++++++--- .../command/RivencraftCommands.java | 33 +++++ .../mixin/AgeStructureBiomeMixin.java | 37 +++++ .../mixin/StructurePlacementAccessor.java | 26 ++++ src/main/resources/rivencraft.mixins.json | 4 +- 14 files changed, 530 insertions(+), 34 deletions(-) create mode 100644 src/main/java/net/dnorberg/rivencraft/mixin/AgeStructureBiomeMixin.java create mode 100644 src/main/java/net/dnorberg/rivencraft/mixin/StructurePlacementAccessor.java diff --git a/docs/INSTABILITY_SCORE.md b/docs/INSTABILITY_SCORE.md index a1130ca..93b58ee 100644 --- a/docs/INSTABILITY_SCORE.md +++ b/docs/INSTABILITY_SCORE.md @@ -2,8 +2,10 @@ 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 frozen score now 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 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 forced into an unsupported selected biome adds +100. 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 added the frozen provider selection; issues #67–#70 added the current handlers. See the [runtime policy](INSTABILITY_RUNTIME.md). 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. diff --git a/docs/LEGACY_INSTABILITY_AUDIT.md b/docs/LEGACY_INSTABILITY_AUDIT.md index f0a2608..595026e 100644 --- a/docs/LEGACY_INSTABILITY_AUDIT.md +++ b/docs/LEGACY_INSTABILITY_AUDIT.md @@ -1,6 +1,6 @@ # Mystcraft Legacy instability audit (Milestone 6, issue #63) -This is the behavior contract used to implement Milestone 6. 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 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. +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 @@ -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, but that separate 400-chunk profiling system is intentionally not ported. Other modern-only Rivencraft features remain neutral. + +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)). @@ -49,7 +53,9 @@ Assets in the supplied local tree: `assets/mystcraft/textures/blocks/decay_{blac [`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. diff --git a/docs/WRITING_GRAMMAR.md b/docs/WRITING_GRAMMAR.md index 9b14006..1cceaee 100644 --- a/docs/WRITING_GRAMMAR.md +++ b/docs/WRITING_GRAMMAR.md @@ -6,7 +6,7 @@ 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. diff --git a/gradle.properties b/gradle.properties index 2685f98..7f2f5b8 100644 --- a/gradle.properties +++ b/gradle.properties @@ -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.8.2 +mod_version=0.5.8.4 immersive_portals_version=6.0.7 terrablender_version=4.1.0.8 serene_seasons_version_id=B6nTjh4b diff --git a/src/main/java/net/dnorberg/rivencraft/book/AgeBiomeSelection.java b/src/main/java/net/dnorberg/rivencraft/book/AgeBiomeSelection.java index 9b973af..0ed8b6c 100644 --- a/src/main/java/net/dnorberg/rivencraft/book/AgeBiomeSelection.java +++ b/src/main/java/net/dnorberg/rivencraft/book/AgeBiomeSelection.java @@ -88,6 +88,9 @@ public record AgeBiomeSelection(AgeTraits.BiomeDistribution distribution, List filler = profile.terrain() == AgeRuntimeProfile.Terrain.VOID && !authored.isEmpty() ? new ArrayList<>() : new ArrayList<>(availableBiomes); @@ -103,6 +106,59 @@ public record AgeBiomeSelection(AgeTraits.BiomeDistribution distribution, List available, + List authored, + AgeTraits.BiomeDistribution distribution, + List selected, + Set distinct, + long seed) { + List> 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 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 requirement = requirements.get(index); + if (selected.stream().anyMatch(requirement::contains)) continue; + List 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 choices, long seed, long salt) { + List shuffled = new ArrayList<>(choices); + java.util.Collections.shuffle(shuffled, new Random(seed ^ salt)); + return shuffled.getFirst(); + } + public static List eligible(RegistryAccess registries, AgeRuntimeProfile profile) { var registry = registries.lookupOrThrow(Registries.BIOME); if (isCave(profile)) { diff --git a/src/main/java/net/dnorberg/rivencraft/book/AgeInstability.java b/src/main/java/net/dnorberg/rivencraft/book/AgeInstability.java index 8319a45..7ff8b8f 100644 --- a/src/main/java/net/dnorberg/rivencraft/book/AgeInstability.java +++ b/src/main/java/net/dnorberg/rivencraft/book/AgeInstability.java @@ -1,15 +1,38 @@ 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 breakdown) { public static final int CURRENT_VERSION = 1; + 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 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); @@ -25,7 +48,7 @@ public record AgeInstability(int version, int score, List breakdow 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 contributions = new ArrayList<>(); if (plan == null) { @@ -40,21 +63,69 @@ public record AgeInstability(int version, int score, List 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 contributions) { + Map 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.biomeCompatible(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 +163,13 @@ public record AgeInstability(int version, int score, List 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"); + } + } + } } diff --git a/src/main/java/net/dnorberg/rivencraft/book/AgePersistenceGameTests.java b/src/main/java/net/dnorberg/rivencraft/book/AgePersistenceGameTests.java index 7692a4b..f8f9c7e 100644 --- a/src/main/java/net/dnorberg/rivencraft/book/AgePersistenceGameTests.java +++ b/src/main/java/net/dnorberg/rivencraft/book/AgePersistenceGameTests.java @@ -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 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 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(); diff --git a/src/main/java/net/dnorberg/rivencraft/book/AgeRegistrySavedData.java b/src/main/java/net/dnorberg/rivencraft/book/AgeRegistrySavedData.java index 8cec445..8300a99 100644 --- a/src/main/java/net/dnorberg/rivencraft/book/AgeRegistrySavedData.java +++ b/src/main/java/net/dnorberg/rivencraft/book/AgeRegistrySavedData.java @@ -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(), diff --git a/src/main/java/net/dnorberg/rivencraft/book/AgeStructureGameTests.java b/src/main/java/net/dnorberg/rivencraft/book/AgeStructureGameTests.java index 65e19a6..4dede11 100644 --- a/src/main/java/net/dnorberg/rivencraft/book/AgeStructureGameTests.java +++ b/src/main/java/net/dnorberg/rivencraft/book/AgeStructureGameTests.java @@ -4,6 +4,7 @@ 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; @@ -14,6 +15,8 @@ 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 +93,84 @@ 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(); + } + + private static List repeated(String feature, int count) { + return java.util.stream.IntStream.range(0, count) + .mapToObj(ignored -> new AgeFeatureSelection.Choice(id(feature), Optional.empty())) + .toList(); + } + private static ResourceLocation id(String path) { return ResourceLocation.fromNamespaceAndPath(Rivencraft.MOD_ID, path); } diff --git a/src/main/java/net/dnorberg/rivencraft/book/AgeStructureSelection.java b/src/main/java/net/dnorberg/rivencraft/book/AgeStructureSelection.java index 6542bfd..0c93e48 100644 --- a/src/main/java/net/dnorberg/rivencraft/book/AgeStructureSelection.java +++ b/src/main/java/net/dnorberg/rivencraft/book/AgeStructureSelection.java @@ -1,14 +1,17 @@ package net.dnorberg.rivencraft.book; 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; @@ -16,7 +19,11 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; 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 +105,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 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 +115,40 @@ public final class AgeStructureSelection { .get(ResourceKey.create(Registries.PLACED_FEATURE, id)).isPresent(); } + static Set 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 compatible = compatibleBiomes(feature, registries); + return compatible.isEmpty() || biomes.biomes().stream().anyMatch(compatible::contains); + } + + /** True when this exact registered structure belongs to an authored structure page. */ + public static boolean authoredStructure(Structure structure, RegistryAccess registries, + List choices) { + Set 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 randomChoices(long ageSeed, AgeRuntimeProfile profile, AgeBiomeSelection biomes, RegistryAccess registries) { List> 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 +168,31 @@ public final class AgeStructureSelection { return 3; // Structures added after Legacy are uncommon, but still discoverable. } - private static Set enabledSets(List 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 enabledSets(List choices) { + Map 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> allowedSets(Stream> sets, List choices) { - Set enabled = enabledSets(choices); + Map enabled = enabledSets(choices); return sets.filter(holder -> holder.unwrapKey() - .map(key -> allowed(key.location(), enabled)).orElse(false)); + .map(key -> allowed(key.location(), enabled.keySet())).orElse(false)) + .map(holder -> scaledHolder(holder, enabled)); } public static HolderLookup filteredLookup(HolderLookup lookup, List choices) { - Set enabled = enabledSets(choices); + Map enabled = enabledSets(choices); + Map, Holder.Reference> scaled = new HashMap<>(); return new HolderLookup<>() { @Override public Optional> get(ResourceKey key) { - return allowed(key.location(), enabled) ? lookup.get(key) : Optional.empty(); + if (!allowed(key.location(), enabled.keySet())) return Optional.empty(); + return lookup.get(key).map(holder -> scaled.computeIfAbsent(key, + ignored -> scaledReference(holder, enabled.getOrDefault(key.location(), 1)))); } @Override @@ -164,7 +202,11 @@ public final class AgeStructureSelection { @Override public Stream> listElements() { - return lookup.listElements().filter(holder -> allowed(holder.key().location(), enabled)); + return lookup.listElements() + .filter(holder -> allowed(holder.key().location(), enabled.keySet())) + .map(holder -> scaled.computeIfAbsent(holder.key(), + ignored -> scaledReference(holder, + enabled.getOrDefault(holder.key().location(), 1)))); } @Override @@ -177,4 +219,57 @@ public final class AgeStructureSelection { private static boolean allowed(ResourceLocation set, Set enabled) { return !CONTROLLED_SETS.contains(set) || enabled.contains(set); } + + private static Holder scaledHolder(Holder holder, + Map 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 scaledReference(Holder.Reference 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 { + private static final HolderOwner OWNER = new HolderOwner<>() {}; + + private ScaledReference(ResourceKey key, StructureSet value) { + super(Type.STAND_ALONE, OWNER, key, value); + } + } } diff --git a/src/main/java/net/dnorberg/rivencraft/command/RivencraftCommands.java b/src/main/java/net/dnorberg/rivencraft/command/RivencraftCommands.java index 23b1c27..11e212a 100644 --- a/src/main/java/net/dnorberg/rivencraft/command/RivencraftCommands.java +++ b/src/main/java/net/dnorberg/rivencraft/command/RivencraftCommands.java @@ -27,6 +27,17 @@ 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.argument("dimension", StringArgumentType.string()) + .suggests((context, builder) -> { + AgeRegistrySavedData.get(context.getSource().getLevel()).definitions() + .forEach(age -> builder.suggest(age.dimensionId().toString())); + return builder.buildFuture(); + }) + .executes(context -> inspectInstability(context.getSource(), + StringArgumentType.getString(context, "dimension"))))) .then(Commands.literal("unload") .then(Commands.argument("dimension", StringArgumentType.string()) .suggests((context, builder) -> { @@ -119,6 +130,28 @@ public final class RivencraftCommands { }; } + private static int inspectInstability(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; + } + 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() + + ", effective " + totals.effectiveScore()), false); + source.sendSuccess(() -> Component.literal("Mutable player bonuses: disabled (no active Legacy registration)"), + false); + return totals.effectiveScore(); + } + private static int pulseDecay(net.minecraft.commands.CommandSourceStack source, String colorName, int attempts) { DecayBlock.Color color; try { diff --git a/src/main/java/net/dnorberg/rivencraft/mixin/AgeStructureBiomeMixin.java b/src/main/java/net/dnorberg/rivencraft/mixin/AgeStructureBiomeMixin.java new file mode 100644 index 0000000..43ff2f9 --- /dev/null +++ b/src/main/java/net/dnorberg/rivencraft/mixin/AgeStructureBiomeMixin.java @@ -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 findGenerationPoint( + Structure.GenerationContext context); + + @Inject(method = "findValidGenerationPoint", at = @At("HEAD"), cancellable = true) + private void rivencraft$allowAuthoredStructureBiome(Structure.GenerationContext context, + CallbackInfoReturnable> cir) { + ChunkGenerator generator = context.chunkGenerator(); + List 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)); + } + } +} diff --git a/src/main/java/net/dnorberg/rivencraft/mixin/StructurePlacementAccessor.java b/src/main/java/net/dnorberg/rivencraft/mixin/StructurePlacementAccessor.java new file mode 100644 index 0000000..140b0f2 --- /dev/null +++ b/src/main/java/net/dnorberg/rivencraft/mixin/StructurePlacementAccessor.java @@ -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 rivencraft$exclusionZone(); +} diff --git a/src/main/resources/rivencraft.mixins.json b/src/main/resources/rivencraft.mixins.json index c2bb406..a0d089a 100644 --- a/src/main/resources/rivencraft.mixins.json +++ b/src/main/resources/rivencraft.mixins.json @@ -4,7 +4,9 @@ "package": "net.dnorberg.rivencraft.mixin", "compatibilityLevel": "JAVA_21", "mixins": [ - "AgeDungeonPlacementMixin" + "AgeDungeonPlacementMixin", + "AgeStructureBiomeMixin", + "StructurePlacementAccessor" ], "client": [ "client.ClientLevelSoundMixin",