diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 91b7e509..84f9a5ba 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -126,9 +126,9 @@ jobs: if-no-files-found: error retention-days: 30 path: | - build/libs/OreSpawn-4.1.1.114041.jar - build/libs/OreSpawn-4.1.1.114041-sources.jar - build/libs/OreSpawn-4.1.1.114041-javadoc.jar + build/libs/OreSpawn-4.1.7.114041.jar + build/libs/OreSpawn-4.1.7.114041-sources.jar + build/libs/OreSpawn-4.1.7.114041-javadoc.jar build/release/SHA256SUMS CHANGELOG.txt diff --git a/CHANGELOG.txt b/CHANGELOG.txt index adedd8fa..76f446ba 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,3 +1,29 @@ +Version 4.1.7.114041 + +* Add chunk surveys, rule explanations and guarded clear/undo tools with clickable previews. +* Keep completed retrogen revisions through repeated saves, OFF/ON changes and server restarts. +* Add optional natural rock formations and preserve edited provider templates. +* Keep native aquatic decoration working with custom background fluids; preserve later lakes and springs. +* Keep saved ore settings without enabling duplicate provider defaults. +* Refresh release checksums when their jars change and keep Eclipse launches production-only. + +Version 4.1.6.114041 + +* Keep saved ore settings when a provider renames a recognised rule. Add the + matching modern rule as a disabled alternative rather than another ore pass. + +* Show vanilla ores in Ore Sources before world creation, even when Manage + Vanilla Ores is off. +* Keep vanilla ore placement unchanged with management off. With it on, + imported rules replace their matching defaults without a second pass. +* Keep saved Ore Sources choices and use a shared placement channel for new + built-in patterns. Explicit channels still stay separate. +* Keep imported provider rules and back up affected profiles before removing + untouched duplicates. Keep edited rules and flag them for review. +* Choose sulfur and lithium defaults after mods finish loading, including + Base Electric. Existing worlds keep their choices. +* Fix the Austrian German language ID and add Pirate Speak menu and guide text. + Version 4.1.1.114041 * Fixed a crash when opening or editing OreSpawn's settings in development runs. diff --git a/README.md b/README.md index 84dbcb95..67364a37 100644 --- a/README.md +++ b/README.md @@ -14,14 +14,23 @@ Its OS3 compatibility layer preserves ranged legacy block budgets, exclusive legacy height ceilings, and the historical "all dimensions except Nether and End" policy used by mods such as Base Metals. +Recognised provider rule renames keep the saved ore settings and add the modern +rule as a disabled, editable alternative, avoiding an extra generation pass. +See [retained provider rules](docs/MIGRATION.md#retained-provider-rules). + This is not the unrelated mod that adds mobs and dimensions under the same name. -This branch builds target-qualified version `4.1.1.114041` for Minecraft 1.14.4 +This branch builds target-qualified version `4.1.7.114041` for Minecraft 1.14.4 and Forge. It adds material-group ore arbitration, exact biome replacements, and a directory for installed provider mods to the OreSpawn 4.0.16 base. See the [versioning policy](docs/VERSIONS.md) for the encoding and release convention. +The 4.1.7 update adds [admin and distribution tools](docs/ADMIN_TOOLS.md), +optional provider-defined [natural rock formations](docs/ROCK_FORMATIONS.md), +and fixes for saved ore rules and completed retrogen work. Existing worlds keep +their saved choices; new formations do not appear just because the mod is updated. + I've fixed a crash when opening or editing OreSpawn's settings in development runs. The fix has also been checked in a normal Forge installation. @@ -144,3 +153,7 @@ Public developer and AI integration guidance lives in `docs/` and is included in the built jar. OreSpawn is licensed under LGPL-2.1. + +## Distribution tools and formations + +The [admin guide](docs/ADMIN_TOOLS.md) covers loaded-chunk surveys and guarded clear/undo. The [formation guide](docs/ROCK_FORMATIONS.md) explains optional natural rock formations. Existing worlds keep their saved choices. diff --git a/build.gradle b/build.gradle index 4c657e55..a6d1ae3d 100644 --- a/build.gradle +++ b/build.gradle @@ -18,7 +18,7 @@ plugins { group = project.mod_group version = project.mod_version -base.archivesName = 'OreSpawn' +base.archivesName = project.mod_artifact def versionParts = project.mod_version.toString().tokenize('.') if (versionParts.size() != 4 || !versionParts.every { it ==~ /\d+/ }) { @@ -36,8 +36,8 @@ if (versionParts[3] != expectedTargetVersion) { ext.functional_version = versionParts[0..2].join('.') ext.display_version = project.mod_version ext.release_tag = project.mod_version -def expectedMavenGroup = 'zone.moddev.mc.orespawn' -def expectedMavenArtifact = 'OreSpawn' +def expectedMavenGroup = project.mod_group +def expectedMavenArtifact = project.mod_artifact def expectedMavenCoordinate = "${expectedMavenGroup}:${expectedMavenArtifact}:${project.version}" java { @@ -264,6 +264,9 @@ tasks.named('processResources', ProcessResources) { dependsOn prepareBundledDocumentation filteringCharset = 'UTF-8' inputs.property('version', project.version) + ['mod_id', 'mod_name', 'mod_license', 'mod_issue_url', 'mod_url', 'mod_authors', 'mod_description'].each { key -> + inputs.property(key, project.property(key)) + } inputs.property('minecraft_version', project.minecraft_version) inputs.property('forge_version_range', project.forge_version_range) inputs.property('loader_version_range', project.loader_version_range) @@ -271,6 +274,13 @@ tasks.named('processResources', ProcessResources) { filesMatching('META-INF/mods.toml') { expand([ version: project.version, + mod_id: project.mod_id, + mod_name: project.mod_name, + mod_license: project.mod_license, + mod_issue_url: project.mod_issue_url, + mod_url: project.mod_url, + mod_authors: project.mod_authors, + mod_description: project.mod_description, minecraft_version: project.minecraft_version, forge_version_range: project.forge_version_range, loader_version_range: project.loader_version_range, @@ -316,3 +326,6 @@ apply from: 'gradle/verification/packaged-forge.gradle' apply from: 'gradle/verification/ore-sources.gradle' apply from: 'gradle/verification/native-ores.gradle' apply from: 'gradle/verification/performance.gradle' + +apply from: 'gradle/verification/admin-tools.gradle' +apply from: 'gradle/verification/parity.gradle' diff --git a/docs/ADMIN_TOOLS.md b/docs/ADMIN_TOOLS.md new file mode 100644 index 00000000..87f5627b --- /dev/null +++ b/docs/ADMIN_TOOLS.md @@ -0,0 +1,131 @@ +# Admin and distribution tools + +Use these tools in a disposable Creative world while tuning a pack. Surveys +do not generate terrain or enable OreSpawn's vanilla-ore management. Clearing +is different: it changes saved blocks, including matching player-placed rocks. + +## Measure what actually generated + +``` +/orespawn help +/orespawn status verbose +/orespawn chunk +/orespawn chunk -2 3 +/orespawn survey 1 +/orespawn survey 2 --y 0 48 --block minecraft:redstone_ore +/orespawn survey 0 --center -2 3 --block minecraft:diorite +/orespawn explain minecraft:redstone_ore 100 20 -40 +/orespawn retrogen status +/orespawn jobs +/orespawn jobs +/orespawn cancel +``` + +New diagnostic commands require permission level 2. Ordinary `status` remains +available without operator permission. Existing `reload`, `retrogen [radius]` +and `dump-biomes` commands keep their behaviour. `retrogen status` never queues +work, enables retrogen or writes a generation marker. Its completed flag is +session bookkeeping, not a claim about a chunk's complete history. + +Chunk coordinates are block coordinates divided by 16, rounding down, including +negative coordinates. Without coordinates, commands use the player's chunk; +the console uses Overworld spawn. Shared options are `--center `, +`--dimension `, `--y ` and the survey +filter `--block `. Heights are inclusive. Radius +defaults to 1 and is limited to 8: a square of `(2 * radius + 1)` chunks per side. + +Only chunks already loaded are visited. The tool records skipped chunks and +chunks that unload during a scan. A partial report is not a complete regional +sample. Scans happen over a recorded interval, not at one atomic world instant. +For a fair comparison, use the same seed, dimensions, coordinates, height range +and coverage, and avoid mining or construction while collecting the sample. + +Reports are stored in the world's `orespawn/diagnostics/reports//`. +Long chat summaries end in `...`; the saved reports are not shortened. +Check `jobs ` for export completion or I/O failure. JSON records block +states and categories, exact Y levels, biome columns, per-chunk counts, coverage +and the active profile fingerprint. CSV files provide the same count tables. +Total sampled volume includes air; non-air volume is reported separately. A +block filter restricts both those denominators to the matching sample. + +Known ores come from native identities, configured outputs and exact block-tag registrations. Blocks are counted once even if several providers +share them. All observed states are exported, including unclassified blocks. +Configured fluid outputs are listed separately from ores. Reports do not +identify which mod historically placed a block or declare that a distribution +is statistically correct from a small sample. + +`explain` uses OreSpawn's actual baked placement budget, host tests and +chunk-centre biome checks. Frequency means expected attempts per chunk, not +guaranteed blocks. Weighted host tests, random geometry, exposure rolls and +private extension checks still affect results. A rock under the cursor today +is not necessarily the host that existed during original generation. Chunk +geology information is labelled as a current base-geology prediction, not +saved formation provenance. +`chunk` also records observed block states down the centre column, every 16 +blocks and at the selected range's endpoints. These sparse samples are not a +whole-chunk count; use `survey 0` for that. + +## Expose one chunk, with a way back + +``` +/orespawn clearchunk --center -2 3 +/orespawn clearchunk confirm +/orespawn undo +/orespawn undo confirm +/orespawn jobs backups +``` + +Clearing and undo require permission level 4. Player operators must be Creative +or Spectator; clearing is refused while a Survival/Adventure player occupies +the target chunk. Keep the surrounding lighting area loaded. The aliases +`/clearchunk` and `/clearchunks` are registered only if another mod has not +claimed them. Both mean one chunk, not a region. + +The first command only scans and prints a preview; no blocks change yet. +Review the coordinates, height range and removal count, then open chat (T by +default) and click **Confirm clearing**. That click sends the confirmation +command. **Cancel** dismisses the preview without changing blocks; **Details** +opens the job report. Hover over a link to see its exact command. The commands +above also work when typed, and the server console prints a copyable command. + +After clearing, the **Undo…** link starts a restoration preview, not an +immediate restore. Review it and click **Confirm undo** to restore the blocks. +Tokens expire after 120 seconds and belong to their operator and snapshot. +A changed profile or snapshot requires a new preview. There is no immediate, unconfirmed clear mode. + +Clearing removes recognised native/provider host rocks and background fluids. +Known ore outputs, configured fluid deposits, bedrock, tile entities and +unrecognised blocks are protected. Protection wins if a state is both an ore +and a host. When a configured deposit uses ordinary water or lava, the same +fluid elsewhere is protected too: there is no reliable historical provenance. + +Before the first write, the tool writes, flushes and verifies an immutable +checksummed journal under `orespawn/diagnostics/backups//`. +If that fails, no clearing occurs. Backups are not automatically deleted. +They remain on disk after restarts; `jobs backups` gives their directory. +Journals record the Minecraft version and are not interchangeable with backups +from other Minecraft versions, whose height and block-state encodings differ. + +Undo validates every recorded state and checks the current blocks before +restoring anything. Already-restored cells are harmless; other intervening +edits cause a conflict rather than being overwritten. Work can be cancelled +or interrupted, so always inspect its final job status. A partial edit remains +recoverable from its original journal and never resumes by itself after restart. +Cancellation stops block writes, then finishes bounded lighting cleanup. If +the chunk or its lighting area unloads, the report records the interruption +and the journal remains available for checked recovery instead of claiming completion. +Only unfinished height and lighting cleanup is retained with the chunk. It resumes +in bounded steps when its lighting area is loaded; block edits never resume by themselves. + +Undo restores recorded block states, not entity movement, elapsed time, mining +or changes made elsewhere. Fluids from outside the selection can later flow +back in. It is not a substitute for a full world backup. + +One server job runs at a time, yielding after 16,384 block visits or a 4 ms +cooperative budget. File output runs separately and touches no live world. +No command expands the loaded chunk set to finish a report or an edit. +Reports stop with an explicit error above 500,000 count-table rows; individual +sidecars are limited to 32 MiB. Reduce the area or height range if you hit a +limit. Existing backups are never removed to make room. +The file-worker backlog is capped at 32 tasks. A full queue reports failure; +it never runs file output on the server thread or starts an unbacked edit. diff --git a/docs/API.md b/docs/API.md index a3167e06..fd3928df 100644 --- a/docs/API.md +++ b/docs/API.md @@ -50,7 +50,7 @@ coverage with `OreDefinition.Builder.dimensionSelector(...)` and `OreDimensionSelector.ALL_EXCEPT_NETHER_AND_END`. Explicit dimensions override that selector and prevent duplicate placement. -The builder emits provider schema 5. Legacy provider schemas 1-4 remain +The builder emits provider schema 5, or schema 6 when it declares rock formations. Legacy provider schemas 1-4 remain readable. Schema 4 is required for biome palettes and dimension materials; schema 5 adds explicit material and placement-channel IDs. API major remains 1. @@ -166,3 +166,11 @@ runs during generation. `OreSpawnOreIntegration` remains as a deprecated facade for early ore-provider integrations. New code should use `OreSpawnApi`. + +## Formation and background controls + +New integrations can use `mergeNewEntriesIntoExistingWorlds(false)` on the +provider builder and `backgroundGenerationScale(value)` on an ore dimension. +Both preserve existing behavior when omitted. Formation declarations and the +read-only `GeologyColumn.formationAt(y)` query are described in +[Natural formations](ROCK_FORMATIONS.md). diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 67053ba6..025fc24b 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -9,6 +9,9 @@ OreSpawn uses three JSON contracts: | `config/-orespawn.json` | 5 | Optional authoritative provider override | A provider may package schema 5 at `data//orespawn/provider.json`. +Providers that declare `rock_formations` use schema 6; all existing schemas +remain supported. Formation materials use flattened block IDs and optional +exact `properties`, not numeric metadata. Legacy provider schemas 1-4 remain accepted. Fluid deposits require schema 3; biome palettes and dimension materials require schema 4. Explicit ore material and placement-channel IDs require schema 5. @@ -185,6 +188,9 @@ Each enabled ore dimension uses: | `placement_channel` | registry ID | Independent placement budget shared by equivalent ores in consolidated modes | At least one of `host_families`, `host_blocks`, or `host_tags` must be present. +On 1.14.4, plain stone, granite, diorite, and andesite are separate block +IDs. Use `host_blocks: ["minecraft:stone"]` for plain stone only; no +pre-flattening metadata is needed. Hosts may be plain registry IDs or weighted objects such as `{"tag":"forge:stone","weight":0.75}`. Optional `geomes`, biome include/exclude IDs, and biome-dictionary include/exclude arrays @@ -264,3 +270,6 @@ ordinary solid blocks, and hostless rules are rejected before generation. Copying a world's `serverconfig/orespawn-worldgen.json` to the same location in a dedicated server world reproduces its choices when the same referenced mods, blocks, biomes, dimensions, and tags are installed. +See [Natural formations](ROCK_FORMATIONS.md) for substrate bodies and +[Admin tools](ADMIN_TOOLS.md) for measured distribution reports. Neither +changes existing terrain merely by installing this update. diff --git a/docs/MIGRATION.md b/docs/MIGRATION.md index 209465f3..212c1bfe 100644 --- a/docs/MIGRATION.md +++ b/docs/MIGRATION.md @@ -1,5 +1,54 @@ # Migration +## Completed Retrogen Work + +Completed revisions survive normal saves, repeated restarts and turning retrogen +off and on. Changing the configured revision does not mark a chunk complete until +that work actually runs. An explicit retrogen command or `force` can request another +pass; leave force off for ordinary play. + +Forge 1.14 saves the whole chunk document but supplies only its `Level` section +when loading it. OreSpawn keeps its marker in both locations and reads older +root-only markers when needed. This does not regenerate stone layers or add new +formations to existing chunks. No system can infer a completed pass whose marker +was already lost by an earlier save. + +## Retained Provider Rules + +An older profile can keep an ore rule after its provider renames that rule. +OreSpawn must not add a second generation pass just because the ID changed. +The merge recognises OreSpawn's imported `orespawn:legacy//...` +rules and the following exact Base Metals replacements: + +- `basemetals:legacy/_ore` to `basemetals:ore/` for + coldiron, adamantine, starsteel, tin, lead, zinc, silver, mercury, nickel + and platinum. + +A match needs one saved rule and one provider candidate with the same single +output, default metadata, and dimension/selector and effective placement-channel +footprint. Conflicting provider ownership, mixed outputs, different deep outputs +and ambiguous matches are not treated as replacements. A generic mod's +`legacy/` name is not enough evidence. + +For a recognised match, the missing modern rule is added as a complete, +disabled alternative. The saved rule keeps its rates, hosts, heights, pattern, +enablement and source choices, including disabled and zero-rate settings. +Fresh worlds still use the provider's normal defaults. + +You can enable the alternative in the ore settings. Later merges retain that +choice, existing modern rules and recorded deletions. A recorded deletion of +one of the historical Base Metals IDs also leaves its mapped replacement +disabled. Deleted imports without an exact mapping are not guessed from their +names. + +This repair does not automatically remove an already-saved historical +Base Metals/modern pair: both may have been selected deliberately. Review +ambiguous or previously affected profiles before changing their choices. +It does not alter generated chunks, public APIs or saved formats. + +The existing OS1 import repair still applies when its own provenance and +backup checks are met; this rule-rename check does not replace it. + ## Provider-Aware OS3 Imports When an OreSpawn 2/3 file is named for an installed provider, the migrator now @@ -11,6 +60,18 @@ and are called out in `orespawn-migration/migration-report.txt` for manual review. Files owned by mods without an active provider retain the original legacy-ID behaviour. +Importing a rule does not turn on **Manage Vanilla Ores**. With that +setting off, Minecraft still generates its own ores and the imported vanilla +rules remain available in the profile for later use. Turning it on lets an +active imported rule replace the modern default for that ore and dimension. + +If a saved world has a proven legacy rule and an unchanged duplicate from the +same provider, OreSpawn keeps the imported rule and backs up the profile as +`serverconfig/orespawn-worldgen.pre-legacy-ore-repair.bak` before removing the +duplicate. Edited or ambiguous rules are kept and noted in the log. Old +metadata is not used to guess a new block ID, and existing chunks are not +regenerated by the repair. + Migration is non-destructive. OreSpawn writes `config/orespawn-worldgen.json` only when that target does not already exist and retains every source file. When legacy OreSpawn rules are translated, a concise player-facing summary is @@ -108,3 +169,15 @@ On Minecraft 1.14.4, revision 10 converts only untouched managed-ore signatures to the target's native height range, frequency, quantity, pattern, and exposure behavior. It also restores the separate Badlands gold rule. Hand-edited rules and explicitly stored Custom values are preserved. +## Retrogen and geology in 4.1.7 + +Completed retrogen revisions now survive ordinary saves, reloads and periods +with retrogen disabled. Changing the configured revision does not mark an +unprocessed chunk complete. Force and the explicit retrogen command still +request another pass; this fix cannot recover completion markers already +lost before the update. + +Profiles without `rock_formations` stay without them. New provider formations +are not merged into existing worlds. No formation or material retrogen is +introduced. Saved ore rates, hosts, source choices and deliberate deletions +remain intact. diff --git a/docs/PLAYER_GUIDE.md b/docs/PLAYER_GUIDE.md index 69628f75..8f58b42a 100644 --- a/docs/PLAYER_GUIDE.md +++ b/docs/PLAYER_GUIDE.md @@ -115,3 +115,10 @@ The report explains what was detected and retained, including any missing rock IDs or fallback values. OreSpawn leaves the old configuration and generated chunks untouched. A fresh world does not inherit this behavior merely because an old Mineralogy config is still present in the instance. +## Checking a modpack's distribution + +Operators can use `/orespawn survey 1` to count blocks in loaded chunks, +`/orespawn chunk` for a local report and `/orespawn explain ` +to inspect eligibility. These do not load new terrain or turn on vanilla-ore +management. See [Admin tools](ADMIN_TOOLS.md) before using clearing or undo; +those commands change blocks and are intended for disposable test worlds. diff --git a/docs/PROVIDERS.md b/docs/PROVIDERS.md index 46f75b22..be546dcb 100644 --- a/docs/PROVIDERS.md +++ b/docs/PROVIDERS.md @@ -124,3 +124,25 @@ referenced biome; ordinary compatibility hints belong in `similar_biomes`. See `examples/examplemod-orespawn.json` for rocks, weighted ore output, a fluid deposit, a custom dimension, biome palette, world materials, and a selectable template. + +Ore Sources chooses defaults once mods finish loading. Both `baseelectric` +and `electricadvantage` are recognised for sulfur and lithium, but +automatic balancing still requires loaded providers with an exact shared +ore tag. Existing worlds keep their saved choices. + +## New-world and background controls + +Schema 6 additionally supports `rock_formations`; see [natural formations](ROCK_FORMATIONS.md). +Ordinary providers still use schema 5. API major 1, global schema 8 and world +schema 7 are unchanged. + +`merge_new_entries_into_existing_worlds: false` keeps later provider entries +out of already-created profiles. It does not remove entries, enable disabled +rules or overwrite saved settings. Formations are never added implicitly to an +existing world, regardless of this flag. + +An ore dimension can declare `background_generation_scale` from 0 to 1. +Its own rule remains unscaled; matching ordinary managed sources and native +ore generation are reduced. Explicit material IDs restrict this to the +standard placement channel, leaving separate deposit channels alone. +OreSpawn cannot suppress an independent generator outside its hooks. diff --git a/docs/README.md b/docs/README.md index 56a50056..3df80ec3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -18,6 +18,8 @@ provider guides give the exact Java and JSON contracts. - [Templates](TEMPLATES.md) - [Biomes and world materials](BIOMES.md) - [Dimensions](DIMENSIONS.md) +- [Natural rock formations](ROCK_FORMATIONS.md) +- [Admin commands and distribution reports](ADMIN_TOOLS.md) - [Migration](MIGRATION.md) - [Troubleshooting](TROUBLESHOOTING.md) - [Versioning and release conventions](VERSIONS.md) diff --git a/docs/ROCK_FORMATIONS.md b/docs/ROCK_FORMATIONS.md new file mode 100644 index 00000000..8e43af7f --- /dev/null +++ b/docs/ROCK_FORMATIONS.md @@ -0,0 +1,64 @@ +# Natural rock formations (1.14.4) + +Vanilla granite/diorite/andesite patches are country-rock decoration, not +metal ores. `OreSpawnApi.isNativeStonePatchPass()` is a thread-local read-only +pass query so expanded natural-rock blocks can decline that decoration while +remaining ordinary metal-ore hosts. Each wrapped feature restores the previous +pass state when it returns, including after an exception. World reset also clears +the flag. Height caches hold only weak world references. Old profiles without formations +never activate it. Early placement also accepts plain/natural vanilla stone +variants spilled in from a neighbour, but not polished stone, infested blocks, +ore, structures, fluids or tile entities. This makes the formation substrate +independent of whether that native patch ran before or after its chunk. + +Provider schema 6 adds `rock_formations`. Older provider schemas and the ordinary +`rocks` layer catalogue keep their existing behavior. A formation is a natural +substrate body, not an ore promise. Every declaration captures an explicit +`algorithm_revision`, enabled state, priority, deterministic salt, geometry and +resolved output materials. Definitions are copied into a new world's profile. + +Existing profiles with no section stay without formations, including later +chunks. An existing unprofiled world also starts without them. There is no +formation retrogen. Explicit pack/world entries win over provider defaults. +Providers can supply their own defaults and tuning templates. This does not +add formations to the existing Mineralogy 1.14 release or provide a Realistic +Deposits port; those mods must declare formations before the feature can use them. +Disabling physical terrain or choosing Cyano suppresses +the formation pass. The exact vanilla Overworld generator supports normal, +Amplified and Large Biomes worlds, with the same lava-lake +protection in each. Custom generators, including subclasses of the vanilla +generator, are left unchanged and receive no formation prediction or native patch protection. + +Built-in compilers: `orespawn:alkaline_complex`, `granitic_contact`, +`ultramafic_alteration`, `barren_pipe`, `quartz_vein`, `weathering_profile`. +The built-in algorithm revision is 1. All default rules are Overworld-only. +Bodies stay within their deterministic region; coordinates use floor division, +including negative regions. Weathering evaluates warm, wet climate and the +parent below the profile. It does not turn any clay into a bauxite setting. + +`WorldgenProvider.Builder.rockFormation(id, type, definition)` declares a body. +`RockFormationRegistry.register(type, compiler)` registers an immutable compiler +during initialization. Compilation resolves blocks, families and settings once; +the registry freezes on first compilation. A prepared column returns either a +baked `FormationMaterial` or null for unchanged country rock. No world mutation +belongs in a compiler. A compiler must be deterministic and must not obtain +chunks, resolve registries or read configuration while sampling. + +The early terrain pass and `GeologyColumn.rockAt`/`familyAt` share that prepared +evaluator. `formationAt(y)` is an additive, read-only query exposing the winning +formation ID, algorithm revision, immediate parent state and material. An empty +family marks vein fill or regolith that does not belong to an ordinary layer family. +The query describes planned natural substrate: caves, fluids, structures, ores +and subsequent decorations can leave protected gaps in the realised body. + +Placement only exchanges the exact predicted original country rock in the +current chunk, before OreSpawn ores. It preserves tile entities, structure +bounding boxes, caves, fluids and other ores. No compensation fills protected +gaps. Reload requires a restart for formation geometry or policy changes. + +Formation integrations require OreSpawn 4.1.7 or newer. Older provider +definitions continue to use their existing API and schema contracts. + +Material blocks use flattened IDs, such as `minecraft:granite`. Optional +`properties` select an exact state, for example `{"axis":"x"}` for a log. +Legacy metadata is not a substitute for a flattened block ID. diff --git a/docs/TEMPLATES.md b/docs/TEMPLATES.md index 0eb7104b..d5141b22 100644 --- a/docs/TEMPLATES.md +++ b/docs/TEMPLATES.md @@ -24,3 +24,7 @@ auto-switch after installation or provider updates. Use namespaced template IDs such as `examplemod:ancient_sea`. Translation keys for the selector belong to the provider resource pack. +Templates may set `preserve_formation_overrides: true` when tuning stock +formations. This keeps authored world edits, disabled rules, deliberate +removals and external provider files intact. Without the option, template +overlays retain their existing behavior. diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 69fa71a8..e105815a 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -63,3 +63,10 @@ Provider mods suppress native generation only after - `/orespawn reload` reloads providers and the active world profile. - `/orespawn retrogen [radius]` queues currently loaded chunks only. - `/orespawn dump-biomes` writes `config/orespawn-biomes.txt`. +## Check what actually generated + +Use `/orespawn survey 0` for a loaded chunk's measured counts. A rule's +frequency is an expected attempt rate, not a guaranteed number of blocks. +`/orespawn explain ` reports the active rule and host checks without +consuming generation randomness. Surveys report incomplete coverage instead +of loading chunks. See [Admin tools](ADMIN_TOOLS.md) for examples. diff --git a/docs/VERSIONS.md b/docs/VERSIONS.md index 6052c92e..cbbacf9c 100644 --- a/docs/VERSIONS.md +++ b/docs/VERSIONS.md @@ -51,8 +51,7 @@ Examples: | Minecraft | Loader | Target | Example full OreSpawn version | | --- | --- | ---: | --- | -| 1.13.2 | Forge | `113021` | `4.0.16.113021` | -| 1.14.4 | Forge | `114041` | `4.1.1.114041` | +| 1.14.4 | Forge | `114041` | `4.1.7.114041` | | 1.20.6 | Forge | `120061` | `4.0.6.120061` | | 1.21.11 | Forge | `121111` | `4.0.6.121111` | | 26.1.2 | Forge | `2601021` | `4.0.6.2601021` | diff --git a/docs/schemas/orespawn-provider.schema.json b/docs/schemas/orespawn-provider.schema.json index 1416edfa..997a1542 100644 --- a/docs/schemas/orespawn-provider.schema.json +++ b/docs/schemas/orespawn-provider.schema.json @@ -4,9 +4,11 @@ "type": "object", "required": ["schema_version", "provider_modid", "provider_revision"], "properties": { - "schema_version": { "enum": [1, 2, 3, 4, 5] }, + "schema_version": { "enum": [1, 2, 3, 4, 5, 6] }, "provider_modid": { "type": "string", "pattern": "^[a-z][a-z0-9_.-]+$" }, "provider_revision": { "type": "integer", "minimum": 1 }, + "merge_new_entries_into_existing_worlds": { "type": "boolean" }, + "rock_formations": { "type": "object", "additionalProperties": { "$ref": "profile-common.schema.json#/$defs/rockFormation" } }, "rocks": { "type": "object", "additionalProperties": { "$ref": "profile-common.schema.json#/$defs/rock" } }, "ores": { "type": "object", "additionalProperties": { "$ref": "profile-common.schema.json#/$defs/ore" } }, "fluid_deposits": { "type": "object", "additionalProperties": { "$ref": "profile-common.schema.json#/$defs/fluidDeposit" } }, @@ -27,12 +29,17 @@ "required_mods": { "type": "array", "uniqueItems": true, "items": { "type": "string" } }, "auto_select": { "type": "boolean" }, "auto_select_priority": { "type": "integer" }, + "preserve_formation_overrides": { "type": "boolean" }, "profile": { "type": "object" } } } } }, "allOf": [ + { + "if": { "properties": { "schema_version": { "maximum": 5 } } }, + "then": { "properties": { "rock_formations": false } } + }, { "if": { "properties": { "schema_version": { "const": 1 } } }, "then": { @@ -66,6 +73,7 @@ } ], "anyOf": [ + { "required": ["rock_formations"], "properties": { "rock_formations": { "minProperties": 1 } } }, { "required": ["rocks"], "properties": { "rocks": { "minProperties": 1 } } }, { "required": ["ores"], "properties": { "ores": { "minProperties": 1 } } }, { "required": ["geomes"], "properties": { "geomes": { "minProperties": 1 } } }, diff --git a/docs/schemas/profile-common.schema.json b/docs/schemas/profile-common.schema.json index c76a11e9..8744208a 100644 --- a/docs/schemas/profile-common.schema.json +++ b/docs/schemas/profile-common.schema.json @@ -11,6 +11,7 @@ "default_template": { "$ref": "#/$defs/optionalRegistryId" }, "selected_template": { "$ref": "#/$defs/registryId" }, "formations": { "$ref": "#/$defs/formations" }, + "rock_formations": { "type": "object", "additionalProperties": { "$ref": "#/$defs/rockFormation" } }, "rocks": { "type": "object", "additionalProperties": { "$ref": "#/$defs/rock" } }, "geomes": { "type": "object", "minProperties": 1, "additionalProperties": { "$ref": "#/$defs/geome" } }, "biomes": { "type": "object", "additionalProperties": { "$ref": "#/$defs/weights" } }, @@ -121,6 +122,7 @@ "type": "object", "required": ["enabled", "min_y", "max_y", "frequency"], "properties": { + "background_generation_scale": { "type": "number", "minimum": 0, "maximum": 1 }, "enabled": { "type": "boolean" }, "min_y": { "type": "integer", "minimum": -2048, "maximum": 2048 }, "max_y": { "type": "integer", "minimum": -2048, "maximum": 2048 }, @@ -389,6 +391,103 @@ "layers": { "type": "integer", "minimum": 1, "maximum": 5 }, "dimensions": { "$ref": "#/$defs/registryIds" } } + }, + "rockFormation": { + "type": "object", + "required": [ + "type", + "algorithm_revision", + "materials" + ], + "properties": { + "type": { + "$ref": "#/$defs/registryId" + }, + "algorithm_revision": { + "type": "integer", + "minimum": 1 + }, + "enabled": { + "type": "boolean" + }, + "priority": { + "type": "integer" + }, + "salt": { + "type": "integer" + }, + "dimensions": { + "$ref": "#/$defs/registryIds" + }, + "geomes": { + "type": "array", + "items": { + "type": "string" + } + }, + "spacing_chunks": { + "type": "integer", + "minimum": 8, + "maximum": 65536 + }, + "chance": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "min_y": { + "type": "integer", + "minimum": 5, + "maximum": 240 + }, + "max_y": { + "type": "integer", + "minimum": 5, + "maximum": 240 + }, + "radius_min": { + "type": "integer", + "minimum": 2 + }, + "radius_max": { + "type": "integer", + "minimum": 2 + }, + "height": { + "type": "integer", + "minimum": 4, + "maximum": 128 + }, + "cover": { + "type": "integer", + "minimum": 4, + "maximum": 240 + }, + "materials": { + "type": "object", + "minProperties": 1, + "additionalProperties": { + "type": "object", + "required": [ + "block" + ], + "properties": { + "block": { + "$ref": "#/$defs/registryId" + }, + "family": { + "$ref": "#/$defs/family" + }, + "properties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } + } } } } diff --git a/gradle.properties b/gradle.properties index c83bf774..e3460445 100644 --- a/gradle.properties +++ b/gradle.properties @@ -19,7 +19,7 @@ mcp_version=20190829.143755 mod_id=orespawn mod_name=MMD OreSpawn mod_license=LGPL-2.1 -mod_version=4.1.1.114041 +mod_version=4.1.7.114041 mod_group=zone.moddev.mc.orespawn mod_authors=SkyBlade1978, dshadowwolf, the MMD Team mod_description=Configurable, provider-driven terrain, ore, and deposit generation. @@ -30,3 +30,11 @@ java_version=8 java_toolchain_version=8.0.502+7 gradle_java_version=17 curseforge_project_id=245586 +mod_artifact=OreSpawn +mod_vendor=Minecraft Mod Development +mod_license_name=GNU Lesser General Public License, Version 2.1 +mod_license_url=https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt +mod_url=https://github.com/MinecraftModDevelopmentMods/OreSpawn +mod_issue_url=https://github.com/MinecraftModDevelopmentMods/OreSpawn/issues +mod_scm_connection=scm:git:https://github.com/MinecraftModDevelopmentMods/OreSpawn.git +mod_scm_developer_connection=scm:git:ssh://git@github.com/MinecraftModDevelopmentMods/OreSpawn.git diff --git a/gradle/README.md b/gradle/README.md index d71d5acc..a41937f2 100644 --- a/gradle/README.md +++ b/gradle/README.md @@ -13,6 +13,8 @@ the small `oreSpawnBuild` helper map declared by the root build. | `verification/native-ores.gradle` | Managed Nether quartz with tag and block hosts, reloads and new-terrain-only edits. | | `verification/packaged-forge.gradle` | Finished-jar tests in disposable official Forge installations. | | `verification/performance.gradle` | Matched vanilla, Cyano and Sky benchmarks and completed-world hash comparisons. | +| `verification/admin-tools.gradle` | Guarded clear/undo, survey, interruption and restart checks in disposable saves. | +| `verification/parity.gradle` | Completed retrogen markers, formations, native density and background-fluid checks. | | `release/artifacts.gradle` | Reobfuscated jars, artifact audits, documentation parity and checksums. | | `release/publishing.gradle` | Maven publication, coordinates and credential checks. | | `ide/eclipse.gradle` | Buildship setup, generated launches and production-classpath verification. | @@ -59,3 +61,8 @@ using the group's placement rule. These dummy providers appear only in this named client and the automated ore-source checks. They do not enter ordinary Eclipse launches or release jars. The manual profile has no automatic world creation or shutdown probe. + +Run `adminIntegrationTest`, `retrogenParityTest` and `generationParityTest` with +`packagedForgeServerRuntime` to exercise those opt-in checks. They use their own +build directories, not the ordinary client's saves. The retrogen fixture includes +the root-only chunk markers written by older Forge 1.14 builds. diff --git a/gradle/ide/eclipse.gradle b/gradle/ide/eclipse.gradle index 0aedaa2f..8ef013f6 100644 --- a/gradle/ide/eclipse.gradle +++ b/gradle/ide/eclipse.gradle @@ -252,7 +252,7 @@ tasks.register('verifyEclipseProductionClasspath') { 'META-INF/orespawn/docs/README.md', 'META-INF/orespawn/docs/VERSIONS.md' ].each { relative -> - if (!new File('bin/main', relative).isFile()) { + if (!new File(file('bin/main'), relative).isFile()) { throw new GradleException("Eclipse output is missing ${relative}") } } @@ -267,6 +267,8 @@ tasks.register('verifyEclipseProductionClasspath') { 'src/test', 'bin/test', 'build/classes/java/test', 'biomeIntegrationTest', 'clientIntegrationTest', 'oreSourceMineralsTest', 'oreSourceAdvantageTest', 'worldHashTest', + 'adminIntegrationTest', 'admintoolsprobe', 'admin-fixture', + 'parityIntegrationTest', 'parityprobe', 'parity-fixture', 'nativeOreIntegrationTest', 'nativeoreprobe', 'native-ore-fixture', 'surfaceprobe', 'clientprobe', 'worldhashprobe', 'oresource-minerals', 'oresource-advantage', 'junit-', 'opentest4j-', @@ -390,3 +392,8 @@ tasks.register('verifyCommandPortability') { tasks.named('check') { dependsOn tasks.named('verifyCommandPortability') } tasks.named('check') { dependsOn tasks.named('verifyMavenCoordinates') } + +// Finish launch/classpath generation before copying processed resources into Eclipse's output. +prepareEclipseResources.configure { + mustRunAfter tasks.named('eclipseClasspath'), tasks.named('genEclipseRuns'), syncForge28EclipseLaunches +} diff --git a/gradle/release/artifacts.gradle b/gradle/release/artifacts.gradle index 4a1175da..c8b3c063 100644 --- a/gradle/release/artifacts.gradle +++ b/gradle/release/artifacts.gradle @@ -28,11 +28,11 @@ tasks.named('jar', Jar) { manifest { attributes([ 'Specification-Title' : 'OreSpawn', - 'Specification-Vendor' : 'SkyBlade1978', + 'Specification-Vendor' : project.mod_vendor, 'Specification-Version' : '1', 'Implementation-Title' : base.archivesName.get(), 'Implementation-Version' : project.version, - 'Implementation-Vendor' : 'SkyBlade1978', + 'Implementation-Vendor' : project.mod_vendor, 'OreSpawn-API-Version' : '1', 'FMLAT' : 'accesstransformer.cfg', 'Maven-Artifact' : expectedMavenCoordinate, @@ -91,7 +91,7 @@ def preparedReleaseDir = providers.gradleProperty('preparedReleaseDir') tasks.register('verifyReleaseConfiguration') { group = 'verification' doLast { - if (project.mod_version != '4.1.1.114041' + if (project.mod_version != '4.1.7.114041' || project.mod_group != expectedMavenGroup || project.minecraft_version != '1.14.4' || project.forge_version != '28.2.26' @@ -105,9 +105,9 @@ tasks.register('verifyReleaseConfiguration') { throw new GradleException('Unexpected dispatcher or Java target metadata') } List expectedPublicArtifacts = [ - 'OreSpawn-4.1.1.114041.jar', - 'OreSpawn-4.1.1.114041-sources.jar', - 'OreSpawn-4.1.1.114041-javadoc.jar' + 'OreSpawn-4.1.7.114041.jar', + 'OreSpawn-4.1.7.114041-sources.jar', + 'OreSpawn-4.1.7.114041-javadoc.jar' ] if (base.archivesName.get() != expectedMavenArtifact || expectedReleaseFiles.get().collect { it.toString() } != expectedPublicArtifacts) { @@ -124,7 +124,7 @@ tasks.register('verifyReleaseConfiguration') { 'src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyMineralogyProfileMigration.java', 'README.md', 'CHANGELOG.txt' ].each { path -> - if (!file(path).getText('UTF-8').contains('4.1.1.114041')) { + if (!file(path).getText('UTF-8').contains('4.1.7.114041')) { throw new GradleException("Release identity missing from ${path}") } } @@ -179,8 +179,8 @@ def verifyDocumentationParity = tasks.register('verifyDocumentationParity') { dependsOn releaseJar doLast { List expected = documentationFiles() - if (expected.size() != 20 || !expected.contains('VERSIONS.md')) { - throw new GradleException("Expected exactly 20 tracked guide files including VERSIONS.md, found ${expected}") + if (expected.size() != 22 || !expected.contains('VERSIONS.md')) { + throw new GradleException("Expected exactly 22 tracked guide files including VERSIONS.md, found ${expected}") } assertDocumentationTree(bundledDocumentationDirectory.asFile, expected, 'generated resources') @@ -233,7 +233,7 @@ tasks.register('verifyReleaseArtifacts') { [ 'src/test/', 'src/biomeIntegrationTest/', 'src/clientIntegrationTest/', 'src/oreSourceMineralsTest/', 'src/oreSourceAdvantageTest/', 'src/worldHashTest/', - 'agent-notes/', 'surfaceprobe', 'clientprobe', 'worldhashprobe', + 'agent-notes/', 'surfaceprobe', 'clientprobe', 'admintoolsprobe', 'adminIntegrationTest', 'admin-fixture', 'parityprobe', 'parityIntegrationTest', 'parity-fixture', 'worldhashprobe', 'nativeoreprobe', 'native-ore-fixture', 'nativeOreIntegrationTest', 'oresource-minerals', 'oresource-advantage', 'ci-fixtures/', 'org/junit/', 'org/mockito/', 'net/bytebuddy/', @@ -322,6 +322,7 @@ tasks.register('writeReleaseChecksums') { group = 'verification' dependsOn tasks.named('verifyReleaseArtifacts') def outputFile = layout.buildDirectory.file('release/SHA256SUMS') + inputs.files(releaseJar, tasks.named('sourcesJar'), tasks.named('javadocJar')) outputs.file(outputFile) doLast { File output = outputFile.get().asFile diff --git a/gradle/release/publishing.gradle b/gradle/release/publishing.gradle index d911b18e..e12313be 100644 --- a/gradle/release/publishing.gradle +++ b/gradle/release/publishing.gradle @@ -31,13 +31,13 @@ publishing { artifact(tasks.named('javadocJar')) } pom { - name = 'MMD OreSpawn' + name = project.mod_name description = project.mod_description - url = 'https://github.com/MinecraftModDevelopmentMods/OreSpawn' + url = project.mod_url licenses { license { - name = 'GNU Lesser General Public License, Version 2.1' - url = 'https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt' + name = project.mod_license_name + url = project.mod_license_url } } } diff --git a/gradle/verification/admin-tools.gradle b/gradle/verification/admin-tools.gradle new file mode 100644 index 00000000..00e81ceb --- /dev/null +++ b/gradle/verification/admin-tools.gradle @@ -0,0 +1,85 @@ +// Compile this separately: destructive test fixtures must never join normal game launches. +def shared = project.ext.oreSpawnBuild +def classesDirectory = layout.buildDirectory.dir('admin-fixture/classes') +def compile = tasks.register('compileAdminProbe', JavaCompile) { + dependsOn tasks.named('classes') + source fileTree('src/adminIntegrationTest/java') + classpath = files(sourceSets.main.output, sourceSets.main.compileClasspath) + destinationDirectory = classesDirectory +} +def fixture = tasks.register('adminProbeJar', Jar) { + dependsOn compile + archiveFileName = 'adminprobe.jar' + destinationDirectory = layout.buildDirectory.dir('admin-fixture') + from classesDirectory + from 'src/adminIntegrationTest/resources' +} +def packaged = renamer.classes(fixture) { + map.from minecraft.dependency.toSrgFile + output = layout.buildDirectory.file('admin-fixture/adminprobe-reobf.jar') +} +shared.adminProbeJar = packaged + +def runtime = providers.gradleProperty('packagedForgeServerRuntime') +def label = providers.gradleProperty('adminIntegrationLabel').orElse('standalone').get() +if (!(label ==~ /[a-z0-9-]+/)) throw new GradleException('Use a simple admin integration label') +def runDirectory = layout.buildDirectory.dir("admin-integration-${label}").get().asFile +def prepare = tasks.register('prepareAdminIntegration') { + dependsOn shared.releaseJar, packaged + doLast { + // This is a dedicated build fixture, never the IDE's run directory or a player save. + delete runDirectory + runDirectory.mkdirs() + copy { from shared.releaseJar; from packaged; into new File(runDirectory, 'mods') } + if (providers.gradleProperty('adminIntegrationModJars').isPresent()) { + providers.gradleProperty('adminIntegrationModJars').get().split(';').each { path -> + File mod = file(path) + if (!mod.isFile()) throw new GradleException("Missing test mod: ${mod}") + copy { from mod; into new File(runDirectory, 'mods') } + } + } + new File(runDirectory, 'eula.txt').setText('eula=true\n', 'UTF-8') + new File(runDirectory, 'server.properties').setText('''\ +level-name=admin-tools-test +level-seed=4192643144957839458 +level-type=default +online-mode=false +server-port=0 +allow-nether=true +generate-structures=false +spawn-protection=0 +max-tick-time=-1 +''', 'UTF-8') + } +} +def previous = prepare +['Fresh', 'Reload', 'ReloadAgain'].each { phase -> + def dependency = previous + previous = tasks.register("adminIntegration${phase}", Exec) { + group = 'verification' + dependsOn dependency + doFirst { + if (!runtime.isPresent()) throw new GradleException('Pass -PpackagedForgeServerRuntime=') + File launcher = new File(file(runtime.get()), 'forge-1.14.4-28.2.26.jar') + if (!launcher.isFile()) throw new GradleException("Missing official Forge launcher: ${launcher}") + workingDir runDirectory + commandLine shared.java8Launcher.get().executablePath.asFile.absolutePath, + '-Xms512m', '-Xmx2g', '-Dadmin.probe.collision=true', "-Dadmin.probe.phase=${phase}", + '-jar', launcher.absolutePath, 'nogui' + } + doLast { + File marker = new File(runDirectory, "admin-probe-${phase}.json") + if (new File(runDirectory, 'admin-probe-failed.json').exists() + || !marker.isFile() || !new groovy.json.JsonSlurper().parse(marker).passed) + throw new GradleException("Admin ${phase} did not pass; retain this run for investigation") + shared.assertRuntimeLogsClean(runDirectory, "Admin ${phase}", [] as Set) + copy { from new File(runDirectory, 'logs/latest.log'); into new File(runDirectory, 'audit-logs'); rename { "${phase}.log" } } + copy { from marker; into new File(runDirectory, 'audit-logs'); rename { "${phase}.json" } } + } + } +} +tasks.register('adminIntegrationTest') { + group = 'verification' + description = 'Checks real surveys, guarded clear/undo, interruptions and repeated process recovery.' + dependsOn previous +} diff --git a/gradle/verification/native-ores.gradle b/gradle/verification/native-ores.gradle index 7f6ea204..c4034dbe 100644 --- a/gradle/verification/native-ores.gradle +++ b/gradle/verification/native-ores.gradle @@ -61,8 +61,10 @@ max-tick-time=-1 File launcher = new File(file(serverRuntime.get()), 'forge-1.14.4-28.2.26.jar') if (!launcher.isFile()) throw new GradleException("Missing official Forge launcher: ${launcher}") workingDir runDirectory + // Keep the chunk worker budget the same on every host for this exact-count comparison. commandLine shared.java8Launcher.get().executablePath.asFile.absolutePath, - '-Xms512m', '-Xmx2g', "-Dnativeoreprobe.phase=${phase.toLowerCase()}", + '-XX:ActiveProcessorCount=2', '-Xms512m', '-Xmx2g', + "-Dnativeoreprobe.phase=${phase.toLowerCase()}", "-Dnativeoreprobe.host=${scenario.toLowerCase()}", '-jar', launcher.absolutePath, 'nogui' } doLast { diff --git a/gradle/verification/parity.gradle b/gradle/verification/parity.gradle new file mode 100644 index 00000000..a57708d0 --- /dev/null +++ b/gradle/verification/parity.gradle @@ -0,0 +1,114 @@ +// Use a separate test mod so production launches and jars contain no probe code. +def shared = project.ext.oreSpawnBuild +def classesDirectory = layout.buildDirectory.dir('parity-fixture/classes') +def compile = tasks.register('compileParityProbe', JavaCompile) { + dependsOn tasks.named('classes') + source fileTree('src/parityIntegrationTest/java') + classpath = files(sourceSets.main.output, sourceSets.main.compileClasspath) + destinationDirectory = classesDirectory +} +def fixture = tasks.register('parityProbeJar', Jar) { + dependsOn compile + archiveFileName = 'parityprobe.jar' + destinationDirectory = layout.buildDirectory.dir('parity-fixture') + from classesDirectory + from 'src/parityIntegrationTest/resources' +} +def packaged = renamer.classes(fixture) { + map.from minecraft.dependency.toSrgFile + output = layout.buildDirectory.file('parity-fixture/parityprobe-reobf.jar') +} +shared.parityProbeJar = packaged +def runtime = providers.gradleProperty('packagedForgeServerRuntime') +def directory = layout.buildDirectory.dir('retrogen-parity').get().asFile +def previous = tasks.register('prepareRetrogenParity') { + dependsOn shared.releaseJar, packaged + doLast { + delete directory + directory.mkdirs() + copy { from shared.releaseJar; from packaged; into new File(directory, 'mods') } + new File(directory, 'eula.txt').setText('eula=true\n', 'UTF-8') + new File(directory, 'server.properties').setText('level-name=retrogen-parity-world\nlevel-seed=1756013778856393773\nlevel-type=default\nonline-mode=false\nserver-port=0\ngenerate-structures=false\nmax-tick-time=-1\n', 'UTF-8') + } +} +['Fresh', 'Reload', 'ReloadAgain', 'StripLevel', 'LegacyReload', 'Off', 'On', 'Revision', 'RevisionReload', 'Force', 'ForceOff'].each { phase -> + def dependency = previous + previous = tasks.register("retrogenParity${phase}", Exec) { + group = 'verification' + dependsOn dependency + doFirst { + if (!runtime.isPresent()) throw new GradleException('Pass -PpackagedForgeServerRuntime=') + workingDir directory + commandLine shared.java8Launcher.get().executablePath.asFile.absolutePath, '-Xms512m', '-Xmx2g', + "-Dparity.phase=${phase}", '-jar', new File(file(runtime.get()), 'forge-1.14.4-28.2.26.jar').absolutePath, 'nogui' + } + doLast { + File marker = new File(directory, "retrogen-${phase}.json") + if (!marker.isFile() || new File(directory, 'retrogen-failed.json').exists() + || !new groovy.json.JsonSlurper().parse(marker).passed) throw new GradleException("Retrogen ${phase} did not pass") + shared.assertRuntimeLogsClean(directory, "Retrogen ${phase}", [] as Set) + copy { from new File(directory, 'logs/latest.log'); into new File(directory, 'audit-logs'); rename { "${phase}.log" } } + } + } +} +tasks.register('retrogenParityTest') { + group = 'verification' + description = 'Checks mined ores and completed revisions through repeated saves, OFF/ON, revisions, force and process restarts.' + dependsOn previous +} + +def generationRuns = [] +[ + Formations: ['formations', 'native', 'default'], + FormationsAmplified: ['formations', 'native', 'amplified'], + FormationsLargeBiomes: ['formations', 'native', 'largeBiomes'], + FluidsNative: ['fluids', 'native', 'default'], + FluidsWater: ['fluids', 'water', 'default'], + FluidsLuminous: ['fluids', 'luminous_water', 'default'] +].each { label, options -> + File runDirectory = layout.buildDirectory.dir("generation-parity-${label}").get().asFile + def prior = tasks.register("prepareGeneration${label}") { + dependsOn shared.releaseJar, packaged + doLast { + delete runDirectory + runDirectory.mkdirs() + copy { from shared.releaseJar; from packaged; into new File(runDirectory, 'mods') } + new File(runDirectory, 'eula.txt').setText('eula=true\n', 'UTF-8') + new File(runDirectory, 'server.properties').setText("level-name=generation-parity-world\nlevel-seed=1756013778856393773\nlevel-type=${options[2]}\nonline-mode=false\nserver-port=0\ngenerate-structures=false\nmax-tick-time=-1\n", 'UTF-8') + } + } + ['Fresh', 'Reload'].each { phase -> + def dependency = prior + prior = tasks.register("generation${label}${phase}", Exec) { + group = 'verification' + dependsOn dependency + doFirst { + if (!runtime.isPresent()) throw new GradleException('Pass -PpackagedForgeServerRuntime=') + workingDir runDirectory + commandLine shared.java8Launcher.get().executablePath.asFile.absolutePath, '-Xms512m', '-Xmx2g', '-XX:ActiveProcessorCount=2', + "-Dparity.mode=${options[0]}", "-Dparity.fluid=${options[1]}", "-Dparity.phase=${phase}", + '-jar', new File(file(runtime.get()), 'forge-1.14.4-28.2.26.jar').absolutePath, 'nogui' + } + doLast { + File marker = new File(runDirectory, "generation-${phase}.json") + if (!marker.isFile() || !new groovy.json.JsonSlurper().parse(marker).passed) + throw new GradleException("Generation ${label} ${phase} did not pass") + shared.assertRuntimeLogsClean(runDirectory, "Generation ${label} ${phase}", [] as Set) + copy { from new File(runDirectory, 'logs/latest.log'); into new File(runDirectory, 'audit-logs'); rename { "${phase}.log" } } + } + } + } + generationRuns.add(prior) +} +tasks.register('generationParityTest') { + group = 'verification' + description = 'Checks generated formations, native sampler agreement, fluid provenance and exact reloads.' + dependsOn generationRuns + doLast { + def parse = { label -> new groovy.json.JsonSlurper().parse(file("${buildDir}/generation-parity-${label}/generation-Fresh.json")) } + def nativeResult = parse('FluidsNative'), optimized = parse('FluidsWater') + if (nativeResult.normalized_blocks_sha256 != optimized.normalized_blocks_sha256 + || nativeResult.pending_fluid_ticks != optimized.pending_fluid_ticks) + throw new GradleException('Optimized fluid changed normalized terrain or scheduled extra fluid updates') + } +} diff --git a/src/adminIntegrationTest/java/local/adminprobe/AdminProbe.java b/src/adminIntegrationTest/java/local/adminprobe/AdminProbe.java new file mode 100644 index 00000000..28963aad --- /dev/null +++ b/src/adminIntegrationTest/java/local/adminprobe/AdminProbe.java @@ -0,0 +1,457 @@ +package local.adminprobe; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; +import net.minecraft.block.BlockState; +import zone.moddev.mc.orespawn.commands.admin.AdminSource; +import net.minecraft.entity.Entity; +import net.minecraft.block.Blocks; +import net.minecraft.item.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.server.MinecraftServer; +import net.minecraft.tileentity.ChestTileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.StringTextComponent; +import net.minecraft.world.World; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.ChunkSection; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.event.server.FMLServerAboutToStartEvent; +import net.minecraftforge.fml.event.server.FMLServerStartedEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.event.TickEvent; +import zone.moddev.mc.orespawn.commands.admin.AdminJobs; +import zone.moddev.mc.orespawn.commands.admin.DiagnosticCatalog; +import zone.moddev.mc.orespawn.commands.admin.DiagnosticFiles; +import zone.moddev.mc.orespawn.commands.admin.DiagnosticStates; +import zone.moddev.mc.orespawn.commands.admin.EditJournal; +import zone.moddev.mc.orespawn.worldgen.WorldGeologyProfileManager; + +/** Destructive fixtures are confined to the explicitly named disposable save. */ +@Mod("admintoolsprobe") +public final class AdminProbe { + private MinecraftServer server; + private ServerWorld world; + private Chunk chunk; + private Sender sender; + private int stage, ticks, loaded, maxObservedVisits, scheduledBefore, dropsBefore; + private String pending, baseline, profile, rng, clearId, corruptId, token, initialConflict, retrogenBefore; + private BlockState depositState; + private EditJournal journal; + private boolean ready; + private net.minecraft.world.chunk.ChunkStatus statusBeforeRepeat; + private final JsonObject evidence = new JsonObject(); + private final com.google.gson.JsonArray ambientDrops = new com.google.gson.JsonArray(); + private int scheduledAtEnd, dropsAtEnd; + private String rngAtEnd; + private long adminWindowStart; + private final java.util.List activeTickNanos = new java.util.ArrayList<>(); + private static final int CX = -40, CZ = -40; + private int lightingWaitTicks; + private static final com.mojang.brigadier.Command PROBE_ALIAS = context -> 666; + private Chunk loadedChunk() { + return world.getChunkProvider().chunkExists(CX, CZ) + ? (Chunk) world.getChunkProvider().func_225313_a(CX, CZ) : null; + } + private int execute(Object target, String command) { + Sender output = target instanceof Sender ? (Sender) target : new Sender("player-probe", 4); + net.minecraft.command.ICommandSource feedback = new net.minecraft.command.ICommandSource() { + public void sendMessage(ITextComponent text) { output.sendMessage(text); } + public boolean shouldReceiveFeedback() { return true; } + public boolean shouldReceiveErrors() { return true; } + public boolean allowLogging() { return false; } + }; + net.minecraft.command.CommandSource source = new net.minecraft.command.CommandSource(feedback, + output.getPositionVector(), net.minecraft.util.math.Vec2f.ZERO, world, output.permission, + output.name, output.getDisplayName(), server, target instanceof Entity ? (Entity) target : null); + return server.getCommandManager().handleCommand(source, command); + } + + public AdminProbe() { MinecraftForge.EVENT_BUS.register(this); } + @SubscribeEvent public void before(FMLServerAboutToStartEvent event) { + if (Boolean.getBoolean("admin.probe.collision")) event.getServer().getCommandManager().getDispatcher().register( + net.minecraft.command.Commands.literal("clearchunks").executes(PROBE_ALIAS)); + } + @SubscribeEvent public void start(FMLServerStartedEvent event) throws Exception { + server = event.getServer(); world = server.forgeGetWorldMap().get(net.minecraft.world.dimension.DimensionType.OVERWORLD); + if (!world.getSaveHandler().getWorldDirectory().getName().equals("admin-tools-test")) throw new AssertionError("Not a disposable save"); + sender = new Sender("admin-probe", 4); + for (int x = CX - 2; x <= CX + 2; x++) for (int z = CZ - 2; z <= CZ + 2; z++) { world.forceChunk(x, z, true); world.getChunk(x, z); } + chunk = loadedChunk(); + net.minecraft.nbt.CompoundNBT rules = world.getGameRules().write(); + rules.putString("randomTickSpeed", "0"); world.getGameRules().read(rules); + world.getGameRules().get(net.minecraft.world.GameRules.DO_DAYLIGHT_CYCLE).set(false, server); + world.getWorldInfo().setRaining(false); world.getWorldInfo().setRainTime(999999); + net.minecraft.tags.TagCollection tags = net.minecraft.tags.BlockTags.getCollection(); + java.util.Map> tagBuilders = new java.util.LinkedHashMap<>(); + tags.getTagMap().forEach((id, tag) -> tagBuilders.put(id, net.minecraft.tags.Tag.Builder.create() + .add(tag.getAllElements().toArray(new net.minecraft.block.Block[0])))); + tagBuilders.put(new net.minecraft.util.ResourceLocation("forge:ores/admin_probe"), + net.minecraft.tags.Tag.Builder.create().add(Blocks.LIGHT_BLUE_WOOL)); + tags.registerAll(tagBuilders); + Path checkpoint = java.nio.file.Paths.get("restart-checkpoint.json"); + if (Files.isRegularFile(checkpoint)) { + JsonObject saved = DiagnosticFiles.read(checkpoint); + baseline = saved.get("baseline").getAsString(); clearId = saved.get("backup").getAsString(); + stage = 30; pending = begin("orespawn undo " + clearId); + } else { + if (!chunk.getTileEntityMap().isEmpty()) throw new AssertionError("Fixture chunk unexpectedly has a block entity"); + for (int index = 0; index < 65536; index++) put(index, index < 256 ? Blocks.BEDROCK.getDefaultState() + : index < 32768 ? Blocks.STONE.getDefaultState() : Blocks.AIR.getDefaultState()); + put(8 << 8, Blocks.DIAMOND_ORE.getDefaultState()); put((8 << 8) + 1, Blocks.GOLD_BLOCK.getDefaultState()); + put((8 << 8) + 2, Blocks.LIGHT_BLUE_WOOL.getDefaultState()); + put((8 << 8) + 4, Blocks.LAVA.getDefaultState()); + put((8 << 8) + 6, Blocks.GRASS_BLOCK.getDefaultState()); + put(250 << 8, Blocks.GRASS_BLOCK.getDefaultState()); + for (java.util.Map.Entry entry : WorldGeologyProfileManager.activeProfile().toJson().getAsJsonObject("fluid_deposits").entrySet()) { + JsonObject rule = entry.getValue().getAsJsonObject(); + if (rule.has("block")) { + net.minecraft.block.Block block = net.minecraftforge.registries.ForgeRegistries.BLOCKS.getValue(new net.minecraft.util.ResourceLocation(rule.get("block").getAsString())); + if (block != null && block != Blocks.AIR) { depositState = block.getDefaultState(); put((8 << 8) + 3, depositState); break; } + } + } + world.setBlockState(pos((8 << 8) + 5), Blocks.CHEST.getDefaultState(), 2); + ((ChestTileEntity) world.getTileEntity(pos((8 << 8) + 5))).setInventorySlotContents(0, new ItemStack(Items.COAL, 37)); + java.util.Arrays.fill(chunk.getBiomes(), net.minecraft.world.biome.Biomes.DESERT); + for (int i = 0; i < 64; i++) chunk.getBiomes()[i] = net.minecraft.world.biome.Biomes.PLAINS; + net.minecraft.world.gen.Heightmap.func_222690_a(chunk, java.util.EnumSet.allOf(net.minecraft.world.gen.Heightmap.Type.class)); chunk.markDirty(); + initialLight = world.getChunkProvider().getLightManager().lightChunk(chunk, false); + stage = -1; ready = true; return; + } + ready = true; + } + + private java.util.concurrent.CompletableFuture initialLight; + private void beginChecks() throws Exception { + require(world.getLightFor(net.minecraft.world.LightType.BLOCK, pos((8 << 8) + 4)) == 15, "Lava-light fixture was not established"); + baseline = hash(); profile = WorldGeologyProfileManager.activeProfile().toJson().toString(); + loaded = world.getChunkProvider().getLoadedChunkCount(); rng = randomState(); + ProbeOperator unsafePlayer = new ProbeOperator(); unsafePlayer.setPosition(CX * 16 + 8, 130, CZ * 16 + 8); + require(execute(unsafePlayer, "orespawn clearchunk --center " + CX + " " + CZ) == 0, "Survival operator accepted"); + world.getPlayers().add(unsafePlayer); + try { require(execute(sender, "orespawn clearchunk --center " + CX + " " + CZ) == 0, "Occupied Survival chunk accepted"); } + finally { world.getPlayers().remove(unsafePlayer); } + evidence.addProperty("survival_operator_and_occupant_rejected", true); + require(execute(new Sender("non-op", 0), "orespawn survey") == 0, "Non-operator survey accepted"); + require(execute(new Sender("level-two", 2), "orespawn clearchunk") == 0, "Level-two clear accepted"); + loaded = world.getChunkProvider().getLoadedChunkCount(); rng = randomState(); + retrogenBefore = zone.moddev.mc.orespawn.worldgen.OreRetrogenManager.diagnosticStatus(world, new net.minecraft.util.math.ChunkPos(CX, CZ)).toString(); + scheduledBefore = scheduled(); dropsBefore = drops(); + command("orespawn help"); command("orespawn status verbose"); command("orespawn chunk --center " + CX + " " + CZ); + command("orespawn retrogen status --center " + CX + " " + CZ); + for (java.util.Map.Entry entry : WorldGeologyProfileManager.activeProfile().toJson().getAsJsonObject("ores").entrySet()) { + JsonObject rule = entry.getValue().getAsJsonObject(); + if ("minecraft:iron_ore".equals(rule.has("block") ? rule.get("block").getAsString() : entry.getKey())) { + command("orespawn explain " + entry.getKey() + " " + (CX * 16) + " 8 " + (CZ * 16)); + JsonObject explanation = zone.moddev.mc.orespawn.worldgen.OreSpawnOreGeneration.diagnosticRule(world, pos(8 << 8), new net.minecraft.util.ResourceLocation(entry.getKey())); + boolean managed = WorldGeologyProfileManager.activeProfile().manageVanillaOres(); + if (rule.has("native_generation") && rule.get("native_generation").getAsBoolean()) { + if (!managed) require(!explanation.get("in_effective_placement_budget").getAsBoolean() + && "vanilla_management_off".equals(explanation.get("reason").getAsString()), "OFF explanation is incorrect"); + else if (!Boolean.getBoolean("admin.probe.stack")) require(explanation.get("in_effective_placement_budget").getAsBoolean(), "ON explanation omitted native placement"); + evidence.addProperty("native_explanation_manage_vanilla", managed); + } + break; + } + } + if (Boolean.getBoolean("admin.probe.collision")) require(server.getCommandManager().getDispatcher().getRoot().getChild("clearchunks").getCommand() == PROBE_ALIAS, "Alias collision overwritten"); + require(rng.equals(randomState()), "Immediate diagnostics consumed world RNG"); + String cancelled = begin("orespawn survey 8 --center " + CX + " " + CZ); + command("orespawn cancel " + cancelled); + pending = begin("orespawn survey 0 --center " + CX + " " + CZ + " --y 0 15"); + String surveyRandom = randomState(); AdminJobs.tick(); + require(surveyRandom.equals(randomState()), "Survey step consumed world RNG"); + } + + @SubscribeEvent(priority=net.minecraftforge.eventbus.api.EventPriority.HIGHEST) + public void beforeEnd(TickEvent.ServerTickEvent event) throws Exception { + if (!ready || event.phase != TickEvent.Phase.END) return; + scheduledAtEnd = scheduled(); dropsAtEnd = drops(); rngAtEnd = randomState(); + adminWindowStart = System.nanoTime(); + } + + @SubscribeEvent public void entityJoined(net.minecraftforge.event.entity.EntityJoinWorldEvent event) { + if (!ready || !(event.getEntity() instanceof net.minecraft.entity.item.ItemEntity)) return; + JsonObject item = new JsonObject(); + item.addProperty("position", event.getEntity().posX + "," + event.getEntity().posY + "," + event.getEntity().posZ); + com.google.gson.JsonArray trace = new com.google.gson.JsonArray(); + for (StackTraceElement frame : Thread.currentThread().getStackTrace()) { + if (frame.getClassName().startsWith("zone.moddev.mc.orespawn.commands.admin.")) + throw new AssertionError("Admin command spawned an item drop: " + frame); + if (trace.size() < 18) trace.add(new com.google.gson.JsonPrimitive(frame.toString())); + } + item.add("trace", trace); + if (ambientDrops.size() < 20) ambientDrops.add(item); + } + + @SubscribeEvent(priority=net.minecraftforge.eventbus.api.EventPriority.LOWEST) + public void tick(TickEvent.ServerTickEvent event) { + if (!ready || event.phase != TickEvent.Phase.END) return; + try { + if (stage == -1) { + if (!initialLight.isDone()) { require(++lightingWaitTicks < 400, "Initial lighting timed out"); return; } + initialLight.join(); stage = 0; beginChecks(); return; + } + long elapsed = System.nanoTime() - adminWindowStart; + if (pending != null && !AdminJobs.jobs(pending).has("status")) activeTickNanos.add(elapsed); + if (++ticks > 10000) throw new AssertionError("Qualification timed out"); + require(scheduled() <= scheduledAtEnd, "Admin tick scheduled an update flood"); + require(drops() <= dropsAtEnd, "Admin tick spawned item drops"); + require(randomState().equals(rngAtEnd), "Admin tick consumed world RNG"); + JsonObject result = AdminJobs.jobs(pending); + if (result.has("maximum_block_visits_per_tick")) maxObservedVisits = Math.max(maxObservedVisits, result.get("maximum_block_visits_per_tick").getAsInt()); + if (stage == 19 && result.has("edited_cells") && result.get("edited_cells").getAsInt() > 0 && !result.has("status")) { + for (int x = CX - 2; x <= CX + 2; x++) for (int z = CZ - 2; z <= CZ + 2; z++) world.forceChunk(x, z, false); stage = 20; return; + } + if (stage == 11 && result.has("edited_cells") && result.get("edited_cells").getAsInt() > 0 && !result.has("status")) { + command("orespawn cancel " + pending); + require(!hash().equals(baseline), "Cancelled edit never wrote blocks"); + stage = 15; + return; + } + if (stage == 15 && result.has("status") && "written".equals(result.has("export") ? result.get("export").getAsString() : "")) { + require("cancelled".equals(result.get("status").getAsString()), "Cancellation cleanup failed: " + result); + int observedLight = world.getLightFor(net.minecraft.world.LightType.BLOCK, pos((8 << 8) + 4)); + int expectedLight = nativeLight(pos((8 << 8) + 4)); + evidence.addProperty("cancel_observed_block_light", observedLight); + evidence.addProperty("cancel_native_expected_block_light", expectedLight); + require(chunk.getBlockState(pos((8 << 8) + 4)).getBlock() == Blocks.AIR, "Cancellation fixture emitter was not removed"); + require(observedLight == expectedLight, "Cancellation left inconsistent block light"); + JsonObject checkpoint = new JsonObject(); checkpoint.addProperty("baseline", baseline); checkpoint.addProperty("backup", pending); + DiagnosticFiles.write(java.nio.file.Paths.get("restart-checkpoint.json").toAbsolutePath(), checkpoint); + evidence.addProperty("partial_cancel", true); complete("initial"); return; + } + if (!result.has("status") || !"written".equals(result.has("export") ? result.get("export").getAsString() : "")) return; + String status = result.get("status").getAsString(); + if (stage == 0) { + require("complete".equals(status), "Survey failed: " + result); + JsonObject saved = DiagnosticFiles.read(AdminJobs.root(world).resolve("reports").resolve(pending).resolve("report.json")); + require(saved.getAsJsonObject("counts").get("sampled_volume").getAsInt() == 4096, "Wrong volume"); + require(saved.getAsJsonObject("counts").getAsJsonObject("blocks").get(DiagnosticStates.key(Blocks.DIAMOND_ORE.getDefaultState())).getAsInt() == 1, "Wrong ore count"); + require(hash().equals(baseline) && profile.equals(WorldGeologyProfileManager.activeProfile().toJson().toString()), "Read-only mutation"); + require(loaded == world.getChunkProvider().getLoadedChunkCount(), "Read-only chunk load"); + require(retrogenBefore.equals(zone.moddev.mc.orespawn.worldgen.OreRetrogenManager.diagnosticStatus(world, new net.minecraft.util.math.ChunkPos(CX, CZ)).toString()), "Read-only retrogen bookkeeping changed"); + evidence.addProperty("read_only_hash_profile_rng_loaded_count", true); + stage = 13; pending = begin("orespawn survey 1 --center 999999 999999"); + } else if (stage == 13) { + require("partial".equals(status) && result.get("sampled_chunks").getAsInt() == 0, "Unloaded area did not report partial coverage"); + require(world.getChunkProvider().getLoadedChunkCount() == loaded, "Survey loaded an absent chunk"); + stage = 14; pending = begin("orespawn survey 0 --center " + CX + " " + CZ + " --block minecraft:light_blue_wool"); + } else if (stage == 14) { + JsonObject saved = DiagnosticFiles.read(AdminJobs.root(world).resolve("reports").resolve(pending).resolve("report.json")); + require(saved.getAsJsonObject("counts").get("sampled_volume").getAsInt() == 1, "Metadata filter counted the wrong cells"); + evidence.addProperty("unloaded_coverage_metadata_filter_and_read_cancel", true); + stage = 1; pending = preview(); + } else if (stage == 1) { + token = result.get("confirmation_token").getAsString(); + put((8 << 8) + 10, Blocks.GOLD_BLOCK.getDefaultState()); + stage = 2; pending = begin("orespawn clearchunk confirm " + token); + } else if (stage == 2) { + require("failed".equals(status) && result.get("edited_cells").getAsInt() == 0, "Stale preview wrote blocks"); + put((8 << 8) + 10, Blocks.STONE.getDefaultState()); stage = 3; pending = preview(); + } else if (stage == 3) { + token = result.get("confirmation_token").getAsString(); + require(execute(new Sender("other-operator", 4), "orespawn clearchunk confirm " + token) == 0, "Foreign token accepted"); + stage = 4; pending = begin("orespawn clearchunk confirm " + token); + Path occupied = AdminJobs.root(world).resolve("backups").resolve(pending).resolve("journal.json"); + JsonObject sentinel = new JsonObject(); sentinel.addProperty("negative_fixture", "occupied backup target"); DiagnosticFiles.write(occupied, sentinel); + } else if (stage == 4) { + require("failed".equals(status) && hash().equals(baseline), "Backup failure did not fail closed"); + evidence.addProperty("stale_foreign_token_and_backup_failure", true); + stage = 5; pending = preview(); + } else if (stage == 5) { + token = result.get("confirmation_token").getAsString(); stage = 6; + pending = begin("orespawn clearchunk confirm " + token); clearId = pending; + } else if (stage == 6) { + require("complete".equals(status) && !hash().equals(baseline), "Clear did not complete: " + result); + journal = EditJournal.read(DiagnosticFiles.readBackup(AdminJobs.root(world).resolve("backups").resolve(clearId).resolve("journal.json"))); + DiagnosticCatalog catalog = new DiagnosticCatalog(WorldGeologyProfileManager.activeProfile().toJson()); + for (EditJournal.Cell cell : journal.cells) require(catalog.removable(DiagnosticStates.resolve(cell.before), false), "Protected state in journal"); + require(chunk.getBlockState(pos(8 << 8)).getBlock() == Blocks.DIAMOND_ORE, "Ore removed"); + require(chunk.getBlockState(pos((8 << 8) + 1)).getBlock() == Blocks.GOLD_BLOCK, "Unknown block removed"); + require(chunk.getBlockState(pos((8 << 8) + 2)).getBlock() == Blocks.LIGHT_BLUE_WOOL, "Tagged ore state removed"); + if (depositState != null) { + require(chunk.getBlockState(pos((8 << 8) + 3)).equals(depositState), "Configured fluid deposit removed"); + evidence.addProperty("real_fluid_deposit_preserved", true); + } + inventory(); + require(chunk.getSections()[15].isEmpty() && !chunk.getSections()[15].needsRandomTickAny(), "Empty-section/random-tick accounting differs"); + corruptId = UUID.randomUUID().toString(); + JsonObject corrupt = new JsonObject(); corrupt.addProperty("format", 1); corrupt.addProperty("sha256", "bad"); corrupt.add("payload", journal.json()); + DiagnosticFiles.write(AdminJobs.root(world).resolve("backups").resolve(corruptId).resolve("journal.json"), corrupt); + stage = 7; pending = begin("orespawn undo " + corruptId); + } else if (stage == 7) { + require("failed".equals(status), "Corrupt backup accepted"); + put(journal.cells.get(0).index, Blocks.GOLD_BLOCK.getDefaultState()); initialConflict = hash(); + stage = 8; pending = begin("orespawn undo " + clearId); + } else if (stage == 8) { + require("failed".equals(status) && hash().equals(initialConflict), "Undo conflict overwrote an edit"); + put(journal.cells.get(0).index, Blocks.AIR.getDefaultState()); stage = 9; pending = begin("orespawn undo " + clearId); + } else if (stage == 9) { + require("preview".equals(status), "Undo preview failed: " + result); + stage = 10; pending = begin("orespawn undo " + clearId + " confirm " + result.get("confirmation_token").getAsString()); + } else if (stage == 10) { + require("complete".equals(status) && hash().equals(baseline), "Undo did not restore exact states: " + result); + require(!chunk.getSections()[15].isEmpty() && chunk.getSections()[15].needsRandomTickAny(), "Undo lost section/random-tick accounting"); + require(world.getLightFor(net.minecraft.world.LightType.BLOCK, pos((8 << 8) + 4)) == 15, "Undo did not restore emitted light"); + inventory(); evidence.addProperty("clear_undo_corruption_conflicts_inventory", true); + statusBeforeRepeat = chunk.getStatus(); + stage = 16; pending = begin("orespawn undo " + clearId); + } else if (stage == 16) { + require("preview".equals(status), "Repeated undo preview failed"); + stage = 17; pending = begin("orespawn undo " + clearId + " confirm " + result.get("confirmation_token").getAsString()); + } else if (stage == 17) { + require("complete".equals(status) && result.get("edited_cells").getAsInt() == 0, "Repeated undo changed cells"); + require(hash().equals(baseline) && chunk.getStatus() == statusBeforeRepeat, "Repeated undo changed states or lighting flags"); + evidence.addProperty("idempotent_undo", true); + stage = 24; pending = begin("orespawn clearchunk --center " + CX + " " + CZ + " --y 0 0"); + } else if (stage == 24) { + require("preview".equals(status) && result.get("removal_cells").getAsInt() == 0, "Expected an empty clearing selection"); + statusBeforeRepeat = chunk.getStatus(); + stage = 25; pending = begin("orespawn clearchunk confirm " + result.get("confirmation_token").getAsString()); + } else if (stage == 25) { + require("complete".equals(status) && result.get("edited_cells").getAsInt() == 0 && chunk.getStatus() == statusBeforeRepeat, + "Empty clear changed blocks or lighting flags"); + evidence.addProperty("empty_selection_and_random_tick_accounting", true); + stage = 18; pending = preview(); + } else if (stage == 18) { + stage = 19; pending = begin("orespawn clearchunk confirm " + result.get("confirmation_token").getAsString()); + } else if (stage == 20) { + require("failed".equals(status) && loadedChunk() == null, "Unload did not stop the edit"); + clearId = pending; chunk = (Chunk) world.getChunk(CX, CZ); + // The command must not load neighbours. The fixture explicitly keeps its lighting area available. + for (int x = CX - 2; x <= CX + 2; x++) for (int z = CZ - 2; z <= CZ + 2; z++) + { world.forceChunk(x, z, true); world.getChunk(x, z); } + require(zone.moddev.mc.orespawn.commands.admin.AdminLighting.isPending(world, chunk) + || world.getLightFor(net.minecraft.world.LightType.BLOCK, pos((8 << 8) + 4)) == nativeLight(pos((8 << 8) + 4)), + "Interrupted chunk lost its lighting recovery marker"); + stage = 26; return; + } else if (stage == 26) { + if (zone.moddev.mc.orespawn.commands.admin.AdminLighting.isPending(world, chunk)) { + require(++lightingWaitTicks < 400, "Interrupted lighting cleanup did not finish with its area loaded"); + return; + } + require(world.getLightFor(net.minecraft.world.LightType.BLOCK, pos((8 << 8) + 4)) == nativeLight(pos((8 << 8) + 4)), + "Reloaded chunk lighting was not repaired"); + stage = 21; pending = begin("orespawn undo " + clearId); + } else if (stage == 21) { + require("preview".equals(status), "Unload recovery preview failed: " + result); + stage = 22; pending = begin("orespawn undo " + clearId + " confirm " + result.get("confirmation_token").getAsString()); + } else if (stage == 22) { + require("complete".equals(status) && hash().equals(baseline), "Unload recovery did not restore blocks"); + evidence.addProperty("chunk_unload_interrupt_and_recovery", true); + JsonObject wrongWorld = journal.json(); wrongWorld.addProperty("world", "another-world"); + corruptId = UUID.randomUUID().toString(); + DiagnosticFiles.backup(AdminJobs.root(world).resolve("backups").resolve(corruptId).resolve("journal.json"), wrongWorld); + stage = 23; pending = begin("orespawn undo " + corruptId); + } else if (stage == 23) { + require("failed".equals(status) && hash().equals(baseline), "Wrong-world journal was accepted"); + evidence.addProperty("world_bound_journal", true); + stage = 12; pending = preview(); + } else if (stage == 12) { + stage = 11; pending = begin("orespawn clearchunk confirm " + result.get("confirmation_token").getAsString()); + } else if (stage == 30) { + require("preview".equals(status), "Restart recovery preview failed: " + result); + stage = 31; pending = begin("orespawn undo " + clearId + " confirm " + result.get("confirmation_token").getAsString()); + } else if (stage == 31) { + require("complete".equals(status) && hash().equals(baseline), "Restart recovery differs from original"); + require(world.getLightFor(net.minecraft.world.LightType.BLOCK, pos((8 << 8) + 4)) == 15, "Restart recovery did not restore emitted light"); + inventory(); evidence.addProperty("exact_restart_recovery", true); complete("reload"); + } + } catch (Throwable failure) { + failure.printStackTrace(); ready = false; + try { evidence.addProperty("failed", failure.toString()); evidence.addProperty("stage", stage); DiagnosticFiles.write(java.nio.file.Paths.get("admin-probe-failed.json").toAbsolutePath(), evidence); } catch (Exception ignored) { } + server.initiateShutdown(false); + } + } + + private String preview() { return begin("orespawn clearchunk --center " + CX + " " + CZ); } + private void command(String command) { require(execute(sender, command) > 0, "Command rejected: " + command); } + private String begin(String command) { + Set before = new HashSet<>(); AdminJobs.jobs(null).entrySet().forEach(e -> before.add(e.getKey())); + command(command); + for (java.util.Map.Entry entry : AdminJobs.jobs(null).entrySet()) + if (!before.contains(entry.getKey())) return entry.getKey(); + throw new AssertionError("No new job for " + command); + } + private BlockPos pos(int index) { return new BlockPos(CX * 16 + (index & 15), index >>> 8, CZ * 16 + ((index >>> 4) & 15)); } + private void put(int index, BlockState state) { + ChunkSection[] sections = chunk.getSections(); int section = index >>> 12; + if (sections[section] == null) sections[section] = new ChunkSection(section * 16); + sections[section].setBlockState(index & 15, (index >>> 8) & 15, (index >>> 4) & 15, state); chunk.markDirty(); + } + private String hash() throws Exception { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (int i = 0; i < 65536; i++) { hash.update(DiagnosticStates.key(chunk.getBlockState(pos(i))).getBytes("UTF-8")); hash.update((byte) 0); } + StringBuilder result = new StringBuilder(); for (byte item : hash.digest()) result.append(String.format("%02x", item & 255)); return result.toString(); + } + private String randomState() throws Exception { + java.lang.reflect.Field seed = java.util.Random.class.getDeclaredField("seed"); seed.setAccessible(true); + return String.valueOf(((AtomicLong) seed.get(world.rand)).get()); + } + private void inventory() { + ChestTileEntity chest = (ChestTileEntity) world.getTileEntity(pos((8 << 8) + 5)); + require(chest != null && chest.getStackInSlot(0).getCount() == 37, "Inventory changed"); + } + private int nativeLight(BlockPos position) { + // The fixture has one emitter in otherwise opaque terrain; no sky light is involved. + return chunk.getBlockState(position).getBlock() == Blocks.LAVA ? 15 : 0; + } + private int scheduled() { + java.util.List entries = world.getPendingBlockTicks().func_223188_a(chunk.getPos(), false, false); + return entries == null ? 0 : entries.size(); + } + private int drops() { + int count = 0; + return (int) world.getEntities().filter(entity -> entity instanceof net.minecraft.entity.item.ItemEntity).count(); + } + private void complete(String phase) throws Exception { + ready = false; evidence.addProperty("passed", true); evidence.addProperty("phase", phase); + evidence.addProperty("max_visits", maxObservedVisits); require(maxObservedVisits <= 16384, "Visit budget exceeded"); + evidence.addProperty("profile", DiagnosticFiles.fingerprint(WorldGeologyProfileManager.activeProfile().toJson())); + evidence.add("ambient_item_spawns", ambientDrops); + evidence.addProperty("per_admin_tick_rng_scheduled_updates_and_drops", true); + java.util.Collections.sort(activeTickNanos); + require(!activeTickNanos.isEmpty(), "No active-job timing captured"); + evidence.addProperty("active_job_ticks", activeTickNanos.size()); + evidence.addProperty("active_job_tick_p95_ms", activeTickNanos.get((int) Math.ceil(activeTickNanos.size() * .95) - 1) / 1000000.0); + evidence.addProperty("active_job_tick_max_ms", activeTickNanos.get(activeTickNanos.size() - 1) / 1000000.0); + DiagnosticFiles.write(java.nio.file.Paths.get("admin-probe-" + System.getProperty("admin.probe.phase", phase) + ".json").toAbsolutePath(), evidence); + System.out.println("ADMIN_TOOLS_PASS " + phase + " " + evidence); server.initiateShutdown(false); + } + private static void require(boolean condition, String message) { if (!condition) throw new AssertionError(message); } + private final class Sender implements AdminSource { + final String name; final int permission; + Sender(String name, int permission) { this.name = name; this.permission = permission; } + public String getName() { return name; } + public ITextComponent getDisplayName() { return new StringTextComponent(name); } + public void sendMessage(ITextComponent text) { System.out.println("ADMIN_FEEDBACK " + text.getString()); } + public boolean canUseCommand(int required, String command) { return permission >= required; } + public BlockPos getPosition() { return pos(10 << 8); } + public Vec3d getPositionVector() { return new Vec3d(CX * 16, 10, CZ * 16); } + public ServerWorld getEntityWorld() { return world; } + public Entity getCommandSenderEntity() { return null; } + public boolean sendCommandFeedback() { return true; } + public MinecraftServer getServer() { return server; } + } + + private final class ProbeOperator extends net.minecraft.entity.player.ServerPlayerEntity { + ProbeOperator() { + super(AdminProbe.this.server, AdminProbe.this.world, + new com.mojang.authlib.GameProfile(UUID.randomUUID(), "AdminModeProbe"), + new net.minecraft.server.management.PlayerInteractionManager(AdminProbe.this.world)); + } + @Override public void sendMessage(ITextComponent text) { System.out.println("ADMIN_PLAYER_FEEDBACK " + text.getString()); } + } +} diff --git a/src/adminIntegrationTest/resources/META-INF/mods.toml b/src/adminIntegrationTest/resources/META-INF/mods.toml new file mode 100644 index 00000000..3801914d --- /dev/null +++ b/src/adminIntegrationTest/resources/META-INF/mods.toml @@ -0,0 +1,14 @@ +modLoader="javafml" +loaderVersion="[28,)" +license="LGPL-2.1" +[[mods]] +modId="admintoolsprobe" +version="1" +displayName="OreSpawn admin integration checks" +description="Disposable-world checks; never installed with the player mod." +[[dependencies.admintoolsprobe]] +modId="orespawn" +mandatory=true +versionRange="[4.1.7,5)" +ordering="AFTER" +side="BOTH" diff --git a/src/adminIntegrationTest/resources/pack.mcmeta b/src/adminIntegrationTest/resources/pack.mcmeta new file mode 100644 index 00000000..a212f8ab --- /dev/null +++ b/src/adminIntegrationTest/resources/pack.mcmeta @@ -0,0 +1 @@ +{"pack":{"description":"OreSpawn integration-test resources","pack_format":4}} diff --git a/src/clientIntegrationTest/java/zone/moddev/mc/orespawn/client/ClientProbeTestMod.java b/src/clientIntegrationTest/java/zone/moddev/mc/orespawn/client/ClientProbeTestMod.java index 83ecb411..e5934961 100644 --- a/src/clientIntegrationTest/java/zone/moddev/mc/orespawn/client/ClientProbeTestMod.java +++ b/src/clientIntegrationTest/java/zone/moddev/mc/orespawn/client/ClientProbeTestMod.java @@ -17,6 +17,7 @@ import net.minecraft.client.gui.screen.MainMenuScreen; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.Widget; +import net.minecraft.client.resources.I18n; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.GameType; import net.minecraft.world.WorldSettings; @@ -28,6 +29,7 @@ import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.event.TickEvent; import zone.moddev.mc.orespawn.worldgen.WorldGeologyProfile; +import zone.moddev.mc.orespawn.worldgen.WorldGeologyProfileManager; /** Build-only client probe. It is compiled and packaged outside every release artifact. */ @Mod(ClientProbeTestMod.MODID) @@ -46,6 +48,7 @@ public final class ClientProbeTestMod { private int editorFrames; private boolean worldSettingsOpened; private boolean longEditorRoundTrip; + private boolean vanillaOreSourcesVerified; private List worldCreationButtons; public ClientProbeTestMod() { @@ -114,6 +117,21 @@ private void handleClientTick() { worldSettingsOpened = true; validateCaptions((OreSpawnWorldSettingsScreen) minecraft.currentScreen); validateLongEditorRoundTrip(minecraft, minecraft.currentScreen); + String localizedCaption = System.getProperty("clientprobe.recommendedCaption", ""); + if (!localizedCaption.isEmpty()) { + String actual = I18n.format("button.orespawn.recommended"); + if (!localizedCaption.equals(actual)) { + throw new IllegalStateException("Unexpected Recommended Defaults caption: " + actual); + } + Properties values = new Properties(); + values.setProperty("recommended", actual); + try (FileOutputStream output = new FileOutputStream("client-locale-pass.properties")) { + values.store(output, "OreSpawn localized editor check"); + } + minecraft.shutdown(); + nextState(10); + break; + } nextState(3); } break; @@ -195,8 +213,8 @@ private Button nextNavigationButton(OreSpawnWorldSettingsScreen root) { Button button = (Button) widget; String caption = TextFormatting.getTextWithoutFormattingCodes(button.getMessage()); if (!attemptedButtons.add(caption)) continue; - String lower = caption.toLowerCase(java.util.Locale.ROOT); - if (lower.equals("done") || lower.equals("cancel") || lower.contains("recommended")) continue; + if (I18n.format("gui.done").equals(caption) || I18n.format("gui.cancel").equals(caption) + || I18n.format("button.orespawn.recommended").equals(caption)) continue; return button; } return null; @@ -217,7 +235,7 @@ private static void validateCaptions(OreSpawnScreen screen) { } } - private static void validateOreSourcesRoute(Minecraft minecraft, OreSpawnScreen materials) { + private void validateOreSourcesRoute(Minecraft minecraft, OreSpawnScreen materials) { Button ores = buttonWithCaption(materials, net.minecraft.client.resources.I18n.format("tab.orespawn.ores")); if (ores == null) throw new IllegalStateException("Missing ORES tab"); @@ -232,6 +250,10 @@ private static void validateOreSourcesRoute(Minecraft minecraft, OreSpawnScreen throw new IllegalStateException("Ore Sources route did not open"); } OreSourceListScreen opened = (OreSourceListScreen) minecraft.currentScreen; + if (!vanillaOreSourcesVerified && Boolean.getBoolean("clientprobe.vanillaOreSources")) { + validateVanillaOreSources(opened); + vanillaOreSourcesVerified = true; + } Button addGroup = buttonWithCaption(opened, "+"); if (addGroup == null) throw new IllegalStateException("Missing Add Group control"); addGroup.onPress(); @@ -246,6 +268,55 @@ private static void validateOreSourcesRoute(Minecraft minecraft, OreSpawnScreen } } + private static void validateVanillaOreSources(OreSourceListScreen screen) { + WorldGeologyProfile pending = WorldGeologyProfileManager.pendingNewWorldProfile(); + if (pending.manageVanillaOres()) { + throw new IllegalStateException("The standalone Show All check must run with vanilla management off"); + } + validateVanillaOreRows(screen); + GeologyEditorSession session = new GeologyEditorSession(pending); + JsonObject before = session.profile().rootCopy(); + for (GeologyEditorSession.OreSourceGroup group : session.oreSourceGroups()) { + if (group.hasManagedPlacementSource() || !"keep_separate".equals(group.mode)) { + throw new IllegalStateException("Show All should not put OreSpawn in charge of vanilla generation"); + } + } + if (!before.equals(session.profile().rootCopy())) { + throw new IllegalStateException("Listing vanilla ores must not change the profile"); + } + System.out.println("VANILLA_ORE_SOURCES_PASS management=off rows=8 profile=unchanged"); + } + + private static void validateVanillaOreRows(OreSourceListScreen screen) { + if (firstList(screen).size() != 0) { + throw new IllegalStateException("Routine vanilla ores should start hidden"); + } + Button showAll = buttonWithCaption(screen, I18n.format("button.orespawn.show_all")); + if (showAll == null) throw new IllegalStateException("Missing Show All control"); + showAll.onPress(); + CompactScrollList groups = firstList(screen); + String[] expected = { "Coal", "Diamond", "Emerald", "Gold", "Iron", "Lapis", "Quartz", "Redstone" }; + if (groups.size() != expected.length) { + throw new IllegalStateException("Show All should list eight vanilla ores, found " + groups.size()); + } + for (int row = 0; row < expected.length; row++) { + if (!groups.rowText(row).startsWith(expected[row] + " - ")) { + throw new IllegalStateException("Unexpected vanilla ore row: " + groups.rowText(row)); + } + } + Button hideSingles = buttonWithCaption(screen, I18n.format("button.orespawn.ore_source.hide_single")); + if (hideSingles == null) throw new IllegalStateException("Missing Hide Singles control"); + hideSingles.onPress(); + if (firstList(screen).size() != 0) throw new IllegalStateException("Hide Singles should hide vanilla ores"); + } + + private static CompactScrollList firstList(OreSpawnScreen screen) { + for (Widget widget : screen.qualificationButtons()) { + if (widget instanceof CompactScrollList) return (CompactScrollList) widget; + } + throw new IllegalStateException("Missing Groups list"); + } + private static Button buttonWithCaption(OreSpawnScreen screen, String caption) { for (Widget widget : screen.qualificationButtons()) { if (widget instanceof Button && caption.equals( @@ -359,7 +430,7 @@ private static void pressDone(OreSpawnScreen screen) { for (Widget widget : screen.qualificationButtons()) { if (!(widget instanceof Button)) continue; String caption = TextFormatting.getTextWithoutFormattingCodes(((Button) widget).getMessage()); - if ("done".equalsIgnoreCase(caption)) { + if (I18n.format("gui.done").equals(caption)) { ((Button) widget).onPress(); return; } @@ -379,6 +450,7 @@ private void writeMarker() throws IOException { Properties values = new Properties(); values.setProperty("world_settings_opened", Boolean.toString(worldSettingsOpened)); values.setProperty("long_editor_roundtrip", Boolean.toString(longEditorRoundTrip)); + values.setProperty("vanilla_ore_sources_verified", Boolean.toString(vanillaOreSourcesVerified)); values.setProperty("editor_routes", Integer.toString(editorRoutes.size())); values.setProperty("editor_classes", editorRoutes.toString()); values.setProperty("first_world_rendered", Boolean.toString(firstWorldFrames >= 8)); diff --git a/src/main/java/zone/moddev/mc/orespawn/OreSpawn.java b/src/main/java/zone/moddev/mc/orespawn/OreSpawn.java index beaaa78d..8e7c1e02 100644 --- a/src/main/java/zone/moddev/mc/orespawn/OreSpawn.java +++ b/src/main/java/zone/moddev/mc/orespawn/OreSpawn.java @@ -67,7 +67,14 @@ public OreSpawn() { MinecraftForge.EVENT_BUS.addListener(OreRetrogenManager::onChunkSave); MinecraftForge.EVENT_BUS.addListener(OreRetrogenManager::onServerTick); MinecraftForge.EVENT_BUS.addListener(OreSpawnCommands::register); + MinecraftForge.EVENT_BUS.addListener(zone.moddev.mc.orespawn.commands.admin.AdminCommandRegistration::tick); + MinecraftForge.EVENT_BUS.addListener(zone.moddev.mc.orespawn.commands.admin.AdminCommandRegistration::unload); + MinecraftForge.EVENT_BUS.addListener(zone.moddev.mc.orespawn.commands.admin.AdminCommandRegistration::stopped); + MinecraftForge.EVENT_BUS.addListener(zone.moddev.mc.orespawn.commands.admin.AdminLighting::onSave); + MinecraftForge.EVENT_BUS.addListener(zone.moddev.mc.orespawn.commands.admin.AdminLighting::onLoad); + MinecraftForge.EVENT_BUS.addListener(zone.moddev.mc.orespawn.commands.admin.AdminLighting::onChunkAvailable); WorldgenBenchmark.register(); + zone.moddev.mc.orespawn.worldgen.AquiferMaterialSubstitution.register(); } private void loadComplete(final FMLLoadCompleteEvent event) { @@ -87,7 +94,7 @@ private void processInterMod(final InterModProcessEvent event) { // Files are authoritative, so scan them before accepting API submissions. WorldgenIntegrationManager.initialize(); WorldgenIntegrationManager.processImcMessages(); - GeomeConfig.bake(); + GeomeConfig.bakeBeforeLoadComplete(); OreSpawnOreGeneration.refreshWorldConfig(); FlatBedrockFeature.refreshWorldConfig(); OreRetrogenManager.refreshWorldConfig(); @@ -96,7 +103,7 @@ private void processInterMod(final InterModProcessEvent event) { private void setup(final FMLCommonSetupEvent event) { OreSpawnConfig.bake(); WorldgenIntegrationManager.initialize(); - GeomeConfig.bake(); + GeomeConfig.bakeBeforeLoadComplete(); logGeomeSampler(); BiomeWorldgenBootstrap.registerCodecs(); DocumentationExporter.exportBundledGuide(); diff --git a/src/main/java/zone/moddev/mc/orespawn/api/CompiledRockFormation.java b/src/main/java/zone/moddev/mc/orespawn/api/CompiledRockFormation.java new file mode 100644 index 00000000..f105a0c4 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/api/CompiledRockFormation.java @@ -0,0 +1,7 @@ +package zone.moddev.mc.orespawn.api; + +/** Baked thread-safe formation evaluator. Null means the column misses this body. */ +@FunctionalInterface +public interface CompiledRockFormation { + RockFormationColumn prepare(RockFormationContext context); +} diff --git a/src/main/java/zone/moddev/mc/orespawn/api/FormationMaterial.java b/src/main/java/zone/moddev/mc/orespawn/api/FormationMaterial.java new file mode 100644 index 00000000..4c052732 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/api/FormationMaterial.java @@ -0,0 +1,16 @@ +package zone.moddev.mc.orespawn.api; + +import net.minecraft.block.BlockState; +import java.util.Optional; + +/** Baked natural substrate. A null family denotes regolith or vein fill, not a layer family. */ +public final class FormationMaterial { + private final BlockState state; + private final Optional family; + public FormationMaterial(BlockState state, GeologyFamily family) { + this.state = java.util.Objects.requireNonNull(state); + this.family = Optional.ofNullable(family); + } + public BlockState state() { return state; } + public Optional family() { return family; } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/api/FormationSample.java b/src/main/java/zone/moddev/mc/orespawn/api/FormationSample.java new file mode 100644 index 00000000..bcd0542b --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/api/FormationSample.java @@ -0,0 +1,19 @@ +package zone.moddev.mc.orespawn.api; + +import net.minecraft.util.ResourceLocation; +import net.minecraft.block.BlockState; + +/** Read-only provenance of the natural substrate, before ores and structures. */ +public final class FormationSample { + private final ResourceLocation id; + private final int revision; + private final BlockState parent; + private final FormationMaterial material; + public FormationSample(ResourceLocation id, int revision, BlockState parent, FormationMaterial material) { + this.id = id; this.revision = revision; this.parent = parent; this.material = material; + } + public ResourceLocation id() { return id; } + public int revision() { return revision; } + public BlockState parent() { return parent; } + public FormationMaterial material() { return material; } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/api/GeologyColumn.java b/src/main/java/zone/moddev/mc/orespawn/api/GeologyColumn.java index dab9fdff..c3f87b4c 100644 --- a/src/main/java/zone/moddev/mc/orespawn/api/GeologyColumn.java +++ b/src/main/java/zone/moddev/mc/orespawn/api/GeologyColumn.java @@ -15,4 +15,6 @@ public interface GeologyColumn { int surfaceY(); BlockState rockAt(int y); Optional familyAt(int y); + /** Predicted natural formation here, excluding later ore and player changes. */ + default Optional formationAt(int y) { return Optional.empty(); } } diff --git a/src/main/java/zone/moddev/mc/orespawn/api/OreSpawnApi.java b/src/main/java/zone/moddev/mc/orespawn/api/OreSpawnApi.java index ce13afd7..b8b6d35c 100644 --- a/src/main/java/zone/moddev/mc/orespawn/api/OreSpawnApi.java +++ b/src/main/java/zone/moddev/mc/orespawn/api/OreSpawnApi.java @@ -53,4 +53,9 @@ public static Optional createSampler(ServerWorld level) { } return Optional.of(OreSpawnGeologySampler.create(level)); } + + /** True only while a wrapped native granite, diorite or andesite pass is running. */ + public static boolean isNativeStonePatchPass() { + return zone.moddev.mc.orespawn.worldgen.NativeStonePatchContext.active(); + } } diff --git a/src/main/java/zone/moddev/mc/orespawn/api/OreSpawnGeologySampler.java b/src/main/java/zone/moddev/mc/orespawn/api/OreSpawnGeologySampler.java index 1c4a415e..34cb2419 100644 --- a/src/main/java/zone/moddev/mc/orespawn/api/OreSpawnGeologySampler.java +++ b/src/main/java/zone/moddev/mc/orespawn/api/OreSpawnGeologySampler.java @@ -55,15 +55,17 @@ static GeologySampler create(ServerWorld level) { @Override public GeologyColumn sampleColumn(int blockX, int blockZ, int surfaceY) { - BlockPos position = new BlockPos(blockX, surfaceY, blockZ); - Biome biome = level.getBiome(position); + // Sample the generator's biome source without loading a world chunk. + Biome biome = level.getChunkProvider().getChunkGenerator().getBiomeProvider() + .getBiome(blockX, blockZ); ResourceLocation biomeId = WorldIds.biome(biome); if (biomeId == null) biomeId = new ResourceLocation("orespawn", "unregistered_biome"); if (mode == GeologyMode.LEGACY) { return new CyanoColumn(biomeId, blockX, blockZ, surfaceY); } GeomeGeology.ColumnSample sample = sky.sampleColumn(biome, biomeId, blockX, blockZ); - return new SkyColumn(biomeId, blockX, blockZ, surfaceY, sample); + return zone.moddev.mc.orespawn.worldgen.NaturalFormations.wrap(level, + new SkyColumn(biomeId, blockX, blockZ, surfaceY, sample), biome); } private abstract class BaseColumn implements GeologyColumn { diff --git a/src/main/java/zone/moddev/mc/orespawn/api/RockFormationColumn.java b/src/main/java/zone/moddev/mc/orespawn/api/RockFormationColumn.java new file mode 100644 index 00000000..d00e4810 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/api/RockFormationColumn.java @@ -0,0 +1,9 @@ +package zone.moddev.mc.orespawn.api; + +/** Prepared immutable column; return null where this formation does not apply. No per-block allocation. */ +@FunctionalInterface +public interface RockFormationColumn { + FormationMaterial at(int y); + /** Optional alteration parent; null uses the preceding natural column at this Y. */ + default net.minecraft.block.BlockState parentAt(int y) { return null; } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/api/RockFormationContext.java b/src/main/java/zone/moddev/mc/orespawn/api/RockFormationContext.java new file mode 100644 index 00000000..e72e2539 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/api/RockFormationContext.java @@ -0,0 +1,24 @@ +package zone.moddev.mc.orespawn.api; + +import java.util.function.IntSupplier; + +/** Column-scoped base geology and lazy, non-chunk-loading natural land elevation. */ +public final class RockFormationContext { + private final long seed; + private final GeologyColumn base; + private final float temperature, rainfall; + private final IntSupplier surface; + private int height = Integer.MIN_VALUE; + public RockFormationContext(long seed, GeologyColumn base, float temperature, float rainfall, IntSupplier surface) { + this.seed = seed; this.base = base; this.temperature = temperature; this.rainfall = rainfall; this.surface = surface; + } + public long seed() { return seed; } + public GeologyColumn base() { return base; } + public float temperature() { return temperature; } + public float rainfall() { return rainfall; } + /** Highest natural solid terrain Y, or -1 for wet/unsupported terrain. */ + public int surfaceY() { + if (height == Integer.MIN_VALUE) height = surface.getAsInt(); + return height; + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/api/RockFormationRegistry.java b/src/main/java/zone/moddev/mc/orespawn/api/RockFormationRegistry.java new file mode 100644 index 00000000..87e0ed4c --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/api/RockFormationRegistry.java @@ -0,0 +1,25 @@ +package zone.moddev.mc.orespawn.api; + +import com.google.gson.JsonObject; +import net.minecraft.util.ResourceLocation; +import java.util.Map; +import java.util.LinkedHashMap; +import java.util.function.Function; + +/** Register compilers during mod initialization, before provider discovery freezes. */ +public final class RockFormationRegistry { + private static final Map> TYPES = new LinkedHashMap<>(); + private static boolean frozen; + private RockFormationRegistry() { } + public static synchronized void register(ResourceLocation type, Function compiler) { + if (frozen || TYPES.containsKey(type)) throw new IllegalStateException("Frozen or duplicate rock formation type: " + type); + TYPES.put(java.util.Objects.requireNonNull(type), java.util.Objects.requireNonNull(compiler)); + } + public static synchronized CompiledRockFormation compile(ResourceLocation type, JsonObject definition) { + frozen = true; + Function compiler = TYPES.get(type); + if (compiler == null) throw new IllegalArgumentException("Unknown rock formation type: " + type); + return compiler.apply(definition); + } + public static synchronized boolean contains(ResourceLocation type) { return TYPES.containsKey(type); } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/api/WorldgenProvider.java b/src/main/java/zone/moddev/mc/orespawn/api/WorldgenProvider.java index eb933cae..e482f130 100644 --- a/src/main/java/zone/moddev/mc/orespawn/api/WorldgenProvider.java +++ b/src/main/java/zone/moddev/mc/orespawn/api/WorldgenProvider.java @@ -12,11 +12,13 @@ import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; +import java.util.OptionalDouble; import java.util.Set; import java.util.function.Consumer; import com.google.gson.JsonArray; import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; import net.minecraft.util.ResourceLocation; @@ -28,11 +30,14 @@ public final class WorldgenProvider { private final String modId; private final int revision; + private final boolean mergeNewEntriesIntoExistingWorlds; private final JsonObject definition; - private WorldgenProvider(String modId, int revision, JsonObject definition) { + private WorldgenProvider(String modId, int revision, boolean mergeNewEntriesIntoExistingWorlds, + JsonObject definition) { this.modId = modId; this.revision = revision; + this.mergeNewEntriesIntoExistingWorlds = mergeNewEntriesIntoExistingWorlds; this.definition = JsonCopies.copy(definition); } @@ -48,7 +53,16 @@ public int revision() { return revision; } - /** Returns a defensive JSON representation matching provider schema 5. */ + /** + * Whether provider entries introduced after a world was created may be merged + * into that world's saved profile. Providers default to the historical + * merge-enabled behaviour. + */ + public boolean mergeNewEntriesIntoExistingWorlds() { + return mergeNewEntriesIntoExistingWorlds; + } + + /** Returns defensive provider JSON; formation contributors use schema 6. */ public JsonObject toJson() { return JsonCopies.copy(definition); } @@ -56,6 +70,7 @@ public JsonObject toJson() { public static final class Builder { private final String modId; private final int revision; + private boolean mergeNewEntriesIntoExistingWorlds = true; private final LinkedHashMap rocks = new LinkedHashMap<>(); private final LinkedHashMap ores = new LinkedHashMap<>(); private final LinkedHashMap fluidDeposits = @@ -69,6 +84,16 @@ public static final class Builder { private final LinkedHashMap dimensionMaterials = new LinkedHashMap<>(); private final LinkedHashMap templates = new LinkedHashMap<>(); + private final LinkedHashMap rockFormations = new LinkedHashMap<>(); + + /** Declares a natural substrate formation. Settings and materials are baked before generation. */ + public Builder rockFormation(ResourceLocation id, ResourceLocation type, JsonObject definition) { + JsonObject value = JsonCopies.copy(Objects.requireNonNull(definition)); + value.addProperty("type", Objects.requireNonNull(type).toString()); + if (rockFormations.putIfAbsent(Objects.requireNonNull(id), value) != null) + throw new IllegalArgumentException("Duplicate rock formation " + id); + return this; + } private Builder(String modId, int revision) { this.modId = requireModId(modId); @@ -78,6 +103,16 @@ private Builder(String modId, int revision) { this.revision = revision; } + /** + * Controls whether newly declared entries are added to already-created world + * profiles. Set this to false when definitions capture structural add-on + * configuration that must only take effect for new worlds. + */ + public Builder mergeNewEntriesIntoExistingWorlds(boolean value) { + mergeNewEntriesIntoExistingWorlds = value; + return this; + } + public Builder rock(RockDefinition rock) { putUnique(rocks, rock.id(), rock, "rock"); return this; @@ -198,21 +233,26 @@ public WorldgenProvider build() { if (rocks.isEmpty() && ores.isEmpty() && fluidDeposits.isEmpty() && geomes.isEmpty() && biomeRules.isEmpty() && terrainDimensions.isEmpty() && biomePalettes.isEmpty() - && dimensionMaterials.isEmpty() && templates.isEmpty()) { + && dimensionMaterials.isEmpty() && templates.isEmpty() && rockFormations.isEmpty()) { throw new IllegalStateException("A provider must declare at least one contribution"); } requireOwned(rocks.keySet(), "rock"); requireOwned(ores.keySet(), "ore"); requireOwned(fluidDeposits.keySet(), "fluid deposit"); requireOwned(geomes.keySet(), "geome"); - requireOwned(terrainDimensions.keySet(), "terrain dimension"); + // Terrain-dimension keys identify Minecraft dimensions. Unlike provider-owned + // rocks, ores, palettes and templates, they are intentionally not namespaced + // to the provider (for example minecraft:overworld or minecraft:the_end). requireOwned(biomePalettes.keySet(), "biome palette"); requireOwned(dimensionMaterials.keySet(), "dimension materials"); requireOwned(templates.keySet(), "template"); + requireOwned(rockFormations.keySet(), "rock formation"); JsonObject root = new JsonObject(); - root.addProperty("schema_version", 5); + root.addProperty("schema_version", rockFormations.isEmpty() ? 5 : 6); root.addProperty("provider_modid", modId); root.addProperty("provider_revision", revision); + root.addProperty("merge_new_entries_into_existing_worlds", + mergeNewEntriesIntoExistingWorlds); root.add("rocks", object(rocks)); root.add("ores", object(ores)); root.add("fluid_deposits", object(fluidDeposits)); @@ -222,7 +262,12 @@ public WorldgenProvider build() { root.add("biome_palettes", object(biomePalettes)); root.add("dimension_materials", object(dimensionMaterials)); root.add("templates", object(templates)); - return new WorldgenProvider(modId, revision, root); + if (!rockFormations.isEmpty()) { + JsonObject formations = new JsonObject(); + rockFormations.forEach((id, value) -> formations.add(id.toString(), JsonCopies.copy(value))); + root.add("rock_formations", formations); + } + return new WorldgenProvider(modId, revision, mergeNewEntriesIntoExistingWorlds, root); } private void requireOwned(Collection ids, String type) { @@ -378,7 +423,7 @@ private OreDefinition(Builder builder) { public static Builder builder(ResourceLocation id, ResourceLocation block) { return new Builder(id, block); } public ResourceLocation id() { return id; } public ResourceLocation block() { return block; } - /** Material shared by interchangeable ore outputs. */ + /** Stable semantic material shared by interchangeable ore outputs. */ public Optional material() { return Optional.ofNullable(material); } public boolean enabled() { return enabled; } public List outputs() { return outputs; } @@ -410,7 +455,7 @@ public JsonObject toJson() { for (Entry entry : dimensionSelectors.entrySet()) { selectors.add(entry.getKey().id().toString(), entry.getValue().toJson()); } - if (selectors.size() > 0) json.add("dimension_selectors", selectors); + if (selectors.entrySet().size() > 0) json.add("dimension_selectors", selectors); return json; } @@ -434,6 +479,7 @@ private Builder(ResourceLocation id, ResourceLocation block) { this.block = Objects.requireNonNull(block, "block"); } public Builder enabled(boolean value) { enabled = value; return this; } + /** Declares the semantic material used for source arbitration. */ public Builder material(ResourceLocation value) { material = Objects.requireNonNull(value); return this; } public Builder nativeGeneration(boolean value) { nativeGeneration = value; return this; } public Builder suppressVanilla(boolean value) { suppressVanilla = value; return this; } @@ -543,6 +589,7 @@ public static final class OreDimensionDefinition implements JsonDefinition { private final Set excludedBiomeDictionary; private final Map hostBlockWeights; private final Map hostTagWeights; + private final Double backgroundGenerationScale; private OreDimensionDefinition(Builder builder) { dimension = builder.dimension; @@ -574,6 +621,7 @@ private OreDimensionDefinition(Builder builder) { new LinkedHashSet<>(builder.excludedBiomeDictionary)); hostBlockWeights = immutableMap(builder.hostBlockWeights); hostTagWeights = immutableMap(builder.hostTagWeights); + backgroundGenerationScale = builder.backgroundGenerationScale; } public static Builder builder(ResourceLocation dimension) { return new Builder(dimension); } @@ -582,13 +630,13 @@ private OreDimensionDefinition(Builder builder) { public int minY() { return minY; } public int maxY() { return maxY; } public double attempts() { return frequency; } - /** Fixed quantity used by older consumers that do not support a range. */ + /** Compatibility value for consumers that only understand a fixed quantity. */ public int quantity() { return (minQuantity + maxQuantity + 1) / 2; } public int minQuantity() { return minQuantity; } public int maxQuantity() { return maxQuantity; } public OrePattern pattern() { return pattern; } public ResourceLocation patternType() { return patternType; } - /** Placement frequency, shape and host budget are selected per channel. */ + /** Stable channel whose placement budget is arbitrated independently. */ public ResourceLocation placementChannel() { return placementChannel; } public JsonObject patternSettings() { return JsonCopies.copy(patternSettings); } public OreHeightDistribution heightDistribution() { return heightDistribution; } @@ -606,6 +654,15 @@ private OreDimensionDefinition(Builder builder) { public Set excludedBiomeDictionary() { return excludedBiomeDictionary; } public Map hostBlockWeights() { return hostBlockWeights; } public Map hostTagWeights() { return hostTagWeights; } + /** + * Optional scale applied to other OreSpawn-managed generation and vanilla + * generation for this rule's primary output in this dimension. The rule + * declaring the controller remains unscaled. + */ + public OptionalDouble backgroundGenerationScale() { + return backgroundGenerationScale == null ? OptionalDouble.empty() + : OptionalDouble.of(backgroundGenerationScale.doubleValue()); + } @Override public JsonObject toJson() { @@ -635,15 +692,19 @@ public JsonObject toJson() { json.addProperty("vertical_spread", verticalSpread); json.addProperty("node_size", nodeSize); JsonArray families = new JsonArray(); - for (GeologyFamily family : hostFamilies) { families.add(family.configName()); } + for (GeologyFamily family : hostFamilies) { families.add(new JsonPrimitive(family.configName())); } json.add("host_families", families); json.add("geomes", weights(geomes)); - json.add("host_blocks", weightedIds(hostBlocks, hostBlockWeights, "block")); + JsonArray hosts = weightedIds(hostBlocks, hostBlockWeights, "block"); + json.add("host_blocks", hosts); json.add("host_tags", weightedIds(hostTags, hostTagWeights, "tag")); json.add("biome_ids", ids(biomeIds)); json.add("excluded_biome_ids", ids(excludedBiomeIds)); json.add("biome_dictionary", strings(biomeDictionary)); json.add("excluded_biome_dictionary", strings(excludedBiomeDictionary)); + if (backgroundGenerationScale != null) { + json.addProperty("background_generation_scale", backgroundGenerationScale); + } return json; } @@ -674,6 +735,7 @@ public static final class Builder { private final Set excludedBiomeDictionary = new LinkedHashSet<>(); private final Map hostBlockWeights = new LinkedHashMap<>(); private final Map hostTagWeights = new LinkedHashMap<>(); + private Double backgroundGenerationScale; private Builder(ResourceLocation dimension) { this.dimension = Objects.requireNonNull(dimension, "dimension"); } public Builder enabled(boolean value) { enabled = value; return this; } @@ -694,6 +756,7 @@ public Builder pattern(ResourceLocation type, JsonObject settings) { patternSettings = JsonCopies.copy(Objects.requireNonNull(settings, "settings")); return this; } + /** Overrides the placement-budget channel for this dimension rule. */ public Builder placementChannel(ResourceLocation value) { placementChannel = Objects.requireNonNull(value); return this; @@ -705,6 +768,8 @@ public Builder placementChannel(ResourceLocation value) { public Builder hostFamily(GeologyFamily value) { hostFamilies.add(value); return this; } public Builder geomeWeight(ResourceLocation geome, double value) { geomes.put(geome, value); return this; } public Builder hostBlock(ResourceLocation value) { hostBlocks.add(value); return this; } + + public Builder hostTag(ResourceLocation value) { hostTags.add(value); return this; } public Builder biome(ResourceLocation value) { biomeIds.add(value); return this; } public Builder excludeBiome(ResourceLocation value) { excludedBiomeIds.add(value); return this; } @@ -712,6 +777,14 @@ public Builder placementChannel(ResourceLocation value) { public Builder excludeBiomeDictionary(String value) { excludedBiomeDictionary.add(nonBlank(value)); return this; } + /** + * Scales background generation for the same primary resource and dimension. + * The declaring rule is the controller and is not itself scaled. + */ + public Builder backgroundGenerationScale(double value) { + backgroundGenerationScale = value; + return this; + } public Builder hostBlock(ResourceLocation value, double weight) { hostBlocks.add(value); hostBlockWeights.put(value, replacementWeight(weight)); @@ -729,11 +802,16 @@ public OreDimensionDefinition build() { || minQuantity < 1 || minQuantity > maxQuantity || maxQuantity > 64 || !Double.isFinite(discardChanceOnAirExposure) || discardChanceOnAirExposure < 0.0D || discardChanceOnAirExposure > 1.0D + || (backgroundGenerationScale != null + && (!Double.isFinite(backgroundGenerationScale) + || backgroundGenerationScale < 0.0D + || backgroundGenerationScale > 1.0D)) || spread < 0 || spread > 64 || verticalSpread < 0 || verticalSpread > 64 || nodeSize < 1 || nodeSize > 32) { throw new IllegalStateException("Invalid ore placement values for " + dimension); } - if (enabled && hostFamilies.isEmpty() && hostBlocks.isEmpty() && hostTags.isEmpty()) { + if (enabled && hostFamilies.isEmpty() && hostBlocks.isEmpty() + && hostTags.isEmpty()) { throw new IllegalStateException("Enabled ore dimension has no hosts: " + dimension); } return new OreDimensionDefinition(this); @@ -890,7 +968,7 @@ public JsonObject toJson() { json.addProperty("min_solid_cover", minSolidCover); json.addProperty("min_solid_shell", minSolidShell); JsonArray families = new JsonArray(); - for (GeologyFamily family : hostFamilies) families.add(family.configName()); + for (GeologyFamily family : hostFamilies) families.add(new JsonPrimitive(family.configName())); json.add("host_families", families); json.add("host_blocks", ids(hostBlocks)); json.add("host_tags", ids(hostTags)); @@ -1057,7 +1135,7 @@ public JsonObject toJson() { json.addProperty("enabled", enabled); json.add("biome_ids", ids(biomeIds)); JsonArray namespaces = new JsonArray(); - for (String namespace : biomeNamespaces) { namespaces.add(namespace); } + for (String namespace : biomeNamespaces) { namespaces.add(new JsonPrimitive(namespace)); } json.add("biome_namespaces", namespaces); json.add("host_blocks", ids(hostBlocks)); json.add("host_tags", ids(hostTags)); @@ -1258,6 +1336,7 @@ public static final class GeologyTemplate implements JsonDefinition { private final Set requiredMods; private final boolean autoSelect; private final int autoSelectPriority; + private final boolean preserveFormationOverrides; private final JsonObject profile; private GeologyTemplate(Builder builder) { @@ -1267,6 +1346,7 @@ private GeologyTemplate(Builder builder) { requiredMods = Collections.unmodifiableSet(new LinkedHashSet<>(builder.requiredMods)); autoSelect = builder.autoSelect; autoSelectPriority = builder.autoSelectPriority; + preserveFormationOverrides = builder.preserveFormationOverrides; profile = JsonCopies.copy(builder.profile); } @@ -1284,10 +1364,11 @@ public JsonObject toJson() { json.addProperty("name_key", nameKey); json.addProperty("description_key", descriptionKey); JsonArray mods = new JsonArray(); - for (String mod : requiredMods) { mods.add(mod); } + for (String mod : requiredMods) { mods.add(new JsonPrimitive(mod)); } json.add("required_mods", mods); json.addProperty("auto_select", autoSelect); json.addProperty("auto_select_priority", autoSelectPriority); + if (preserveFormationOverrides) json.addProperty("preserve_formation_overrides", true); json.add("profile", JsonCopies.copy(profile)); return json; } @@ -1299,6 +1380,7 @@ public static final class Builder { private final Set requiredMods = new LinkedHashSet<>(); private boolean autoSelect; private int autoSelectPriority; + private boolean preserveFormationOverrides; private final JsonObject profile = new JsonObject(); private Builder(ResourceLocation id) { this.id = Objects.requireNonNull(id, "id"); @@ -1306,6 +1388,8 @@ private Builder(ResourceLocation id) { descriptionKey = nameKey + ".description"; } public Builder translationKeys(String name, String description) { nameKey = name; descriptionKey = description; return this; } + /** Tune stock formations only; keep authored overrides, removals and external providers. */ + public Builder preserveFormationOverrides(boolean value) { preserveFormationOverrides = value; return this; } public Builder requiresMod(String value) { requiredMods.add(requireModId(value)); return this; } public Builder autoSelect(boolean value) { autoSelect = value; return this; } public Builder autoSelectPriority(int value) { autoSelectPriority = value; return this; } @@ -1357,13 +1441,13 @@ private static JsonObject weights(Map values) { private static JsonArray ids(Collection values) { JsonArray json = new JsonArray(); - for (ResourceLocation value : values) { json.add(value.toString()); } + for (ResourceLocation value : values) { json.add(new JsonPrimitive(value.toString())); } return json; } /** - * A provider's biome palette, which supplements or replaces the biomes chosen by a dimension. - * No separate biome framework is required. + * A provider-owned set of biomes which can augment or replace an existing + * dimension biome source without depending on a particular biome framework. */ public static final class BiomePaletteDefinition implements JsonDefinition { private final ResourceLocation id; @@ -1703,7 +1787,7 @@ public DimensionMaterialsDefinition build() { private static JsonArray strings(Collection values) { JsonArray json = new JsonArray(); - for (String value : values) { json.add(value); } + for (String value : values) { json.add(new JsonPrimitive(value)); } return json; } @@ -1713,7 +1797,7 @@ private static JsonArray weightedIds(Collection values, for (ResourceLocation value : values) { Double weight = weights.get(value); if (weight == null || weight.doubleValue() == 1.0D) { - json.add(value.toString()); + json.add(new JsonPrimitive(value.toString())); } else { JsonObject entry = new JsonObject(); entry.addProperty(idKey, value.toString()); diff --git a/src/main/java/zone/moddev/mc/orespawn/client/GeologyEditorSession.java b/src/main/java/zone/moddev/mc/orespawn/client/GeologyEditorSession.java index 30f9642e..346d88be 100644 --- a/src/main/java/zone/moddev/mc/orespawn/client/GeologyEditorSession.java +++ b/src/main/java/zone/moddev/mc/orespawn/client/GeologyEditorSession.java @@ -405,7 +405,7 @@ List oreSourceGroups() { List result = new ArrayList<>(); for (Entry entry : section("ore_source_policies").entrySet()) { if (!entry.getValue().isJsonObject()) continue; - JsonObject policy = entry.getValue().getAsJsonObject(); + JsonObject policy = OreSourceEditorView.policy(root, entry.getValue().getAsJsonObject()); String material = string(policy, "material", ""); String domain = string(policy, "domain", ""); if (!validResource(material) || !validResource(domain)) continue; @@ -455,6 +455,7 @@ List oreSourceGroups() { candidates, decimalMap(policy, "outputs"), stringMap(policy, "placement_sources")); if (!bool(policy, "dormant", false)) result.add(group); } + OreSourceEditorView.addVanillaPreviews(root, result); Collections.sort(result, (left, right) -> { int name = left.displayName.compareToIgnoreCase(right.displayName); if (name != 0) return name; @@ -977,8 +978,8 @@ private static boolean hasManagedPlacementSource(JsonObject policy) { } private static void refreshOreSourceStatus(JsonObject policy) { - Set missing = new HashSet<>(); - Set inactivePlacements = new HashSet<>(); + Set loaded = new HashSet<>(); + Set loadedPlacements = new HashSet<>(); boolean external = false; boolean review = bool(policy, "review_required", false); if (policy.has("candidates") && policy.get("candidates").isJsonArray()) { @@ -986,8 +987,10 @@ private static void refreshOreSourceStatus(JsonObject policy) { if (!element.isJsonObject()) continue; JsonObject candidate = element.getAsJsonObject(); String sourceId = string(candidate, "source_id", ""); - if (!bool(candidate, "loaded", false)) missing.add(sourceId); - if (!bool(candidate, "placement_active", false)) inactivePlacements.add(sourceId); + if (bool(candidate, "loaded", false)) { + loaded.add(sourceId); + loadedPlacements.add(sourceId + "|" + string(candidate, "placement_channel", "orespawn:standard")); + } external |= bool(candidate, "external", false) && bool(candidate, "loaded", false); } } @@ -999,10 +1002,10 @@ private static void refreshOreSourceStatus(JsonObject policy) { return; } for (String id : outputs.keySet()) { - if (missing.contains(id)) { policy.addProperty("status", "missing_source"); return; } + if (!loaded.contains(id)) { policy.addProperty("status", "missing_source"); return; } } - for (String id : placements.values()) { - if (missing.contains(id) || inactivePlacements.contains(id)) { + for (Entry placement : placements.entrySet()) { + if (!loadedPlacements.contains(placement.getValue() + "|" + placement.getKey())) { policy.addProperty("status", "missing_source"); return; } } @@ -1046,11 +1049,20 @@ static final class OreSourceGroup { final List candidates; final Map outputs; final Map placements; + final boolean preview; OreSourceGroup(String key, String material, String domain, String displayName, List blockTagEntries, boolean curated, String mode, String outputMode, String status, List candidates, Map outputs, Map placements) { + this(key, material, domain, displayName, blockTagEntries, curated, mode, outputMode, status, + candidates, outputs, placements, false); + } + + OreSourceGroup(String key, String material, String domain, String displayName, + List blockTagEntries, boolean curated, String mode, String outputMode, String status, + List candidates, Map outputs, + Map placements, boolean preview) { this.key = key; this.material = material; this.domain = domain; @@ -1063,6 +1075,7 @@ static final class OreSourceGroup { this.candidates = Collections.unmodifiableList(new ArrayList<>(candidates)); this.outputs = outputs; this.placements = placements; + this.preview = preview; } List channels() { diff --git a/src/main/java/zone/moddev/mc/orespawn/client/OreSourceEditorView.java b/src/main/java/zone/moddev/mc/orespawn/client/OreSourceEditorView.java new file mode 100644 index 00000000..0a778a4b --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/client/OreSourceEditorView.java @@ -0,0 +1,169 @@ +package zone.moddev.mc.orespawn.client; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import net.minecraft.tags.BlockTags; +import net.minecraft.util.ResourceLocation; +import zone.moddev.mc.orespawn.client.GeologyEditorSession.OreSourceCandidate; +import zone.moddev.mc.orespawn.client.GeologyEditorSession.OreSourceGroup; +import zone.moddev.mc.orespawn.util.JsonCopies; + +/** Builds the editor's view without rewriting the world's saved choices. */ +final class OreSourceEditorView { + private static final String STANDARD = "orespawn:standard"; + private static final Set OLD_CHANNELS = new HashSet<>(Arrays.asList( + "orespawn:default", "orespawn:vein", "orespawn:normal_cloud", + "orespawn:precision", "orespawn:clusters", "orespawn:underfluids")); + + private OreSourceEditorView() { } + + static void addVanillaPreviews(JsonObject root, List groups) { + // Forge ships these tags, but Create New World can open before server data loads. + // Keep these rows out of the profile so they never participate in world generation. + addVanillaPreview(root, groups, "coal", "Coal", "coal_ore", "minecraft:overworld"); + addVanillaPreview(root, groups, "diamond", "Diamond", "diamond_ore", "minecraft:overworld"); + addVanillaPreview(root, groups, "emerald", "Emerald", "emerald_ore", "minecraft:overworld"); + addVanillaPreview(root, groups, "gold", "Gold", "gold_ore", "minecraft:overworld"); + addVanillaPreview(root, groups, "iron", "Iron", "iron_ore", "minecraft:overworld"); + addVanillaPreview(root, groups, "lapis", "Lapis", "lapis_ore", "minecraft:overworld"); + addVanillaPreview(root, groups, "quartz", "Quartz", "nether_quartz_ore", "minecraft:the_nether"); + addVanillaPreview(root, groups, "redstone", "Redstone", "redstone_ore", "minecraft:overworld"); + } + + private static void addVanillaPreview(JsonObject root, List groups, + String name, String label, String block, String domain) { + String blockId = "minecraft:" + block; + String material = "orespawn:" + name; + String key = material + '|' + domain; + String tag = "forge:ores/" + name; + JsonObject ore = object(object(root, "ores"), blockId); + String output = text(ore, "block"); + if (!flag(ore, "native_generation", false) || !object(ore, "dimensions").has(domain) + || ore.has("material") || (!output.isEmpty() && !blockId.equals(output)) + || BlockTags.getCollection().get(new ResourceLocation(tag)) != null) return; + for (OreSourceGroup group : groups) { + if (key.equals(group.key)) return; + if (domain.equals(group.domain) && group.candidates.stream() + .anyMatch(candidate -> blockId.equals(candidate.registryId))) return; + } + + List tags = Collections.singletonList(tag); + boolean managed = flag(root, "manage_vanilla_ores", false) && flag(ore, "enabled", true) + && flag(object(object(ore, "dimensions"), domain), "enabled", true); + OreSourceCandidate candidate = new OreSourceCandidate(blockId, "minecraft", "Minecraft", "1.14.4", + blockId, 0, STANDARD, tags, true, managed, false, false, false); + groups.add(new OreSourceGroup(key, material, domain, label, tags, false, "keep_separate", "custom", + "separate", Collections.singletonList(candidate), Collections.singletonMap(blockId, 1.0D), + Collections.emptyMap(), true)); + } + + private static boolean flag(JsonObject object, String key, boolean fallback) { + return object.has(key) && object.get(key).isJsonPrimitive() ? object.get(key).getAsBoolean() : fallback; + } + + static JsonObject policy(JsonObject root, JsonObject saved) { + JsonObject view = JsonCopies.copy(saved); + JsonObject placements = object(view, "placement_sources"); + JsonArray candidates = view.has("candidates") && view.get("candidates").isJsonArray() + ? view.getAsJsonArray("candidates") : new JsonArray(); + String domain = text(view, "domain"); + List aliases = new ArrayList<>(); + + for (Map.Entry entry : placements.entrySet()) { + String channel = entry.getKey(); + if (!OLD_CHANNELS.contains(channel) || !entry.getValue().isJsonPrimitive()) continue; + + String source = entry.getValue().getAsString(); + if (inferredAlias(root, source, domain, channel) + && loadedCandidate(candidates, source, STANDARD) != null) { + aliases.add(channel); + } + } + + // More than one old pattern may have been selected deliberately. Keep + // those rows separate rather than choosing a winner on the player's behalf. + boolean combine = placements.has(STANDARD) || aliases.size() == 1; + if (combine) { + for (String alias : aliases) { + if (!placements.has(STANDARD)) placements.add(STANDARD, placements.get(alias)); + placements.remove(alias); + } + } + + JsonArray visible = new JsonArray(); + for (JsonElement element : candidates) { + if (!element.isJsonObject()) continue; + JsonObject candidate = element.getAsJsonObject(); + String source = text(candidate, "source_id"); + String channel = text(candidate, "placement_channel"); + JsonObject current = loadedCandidate(candidates, source, STANDARD); + + if (!combine && !aliases.isEmpty() && STANDARD.equals(channel) && current != null) { + boolean projected = false; + for (String alias : aliases) { + if (!inferredAlias(root, source, domain, alias)) continue; + + JsonObject retained = JsonCopies.copy(current); + retained.addProperty("placement_channel", alias); + visible.add(retained); + projected = true; + } + if (projected) continue; + } + + if (current != null && OLD_CHANNELS.contains(channel) + && inferredAlias(root, source, domain, channel)) { + continue; + } + visible.add(candidate); + } + + view.add("candidates", visible); + view.add("placement_sources", placements); + return view; + } + + private static boolean inferredAlias(JsonObject root, String source, String domain, String channel) { + JsonObject ore = object(object(root, "ores"), source); + JsonObject dimensions = object(ore, "dimensions"); + JsonObject rule = dimensions.has(domain) ? object(dimensions, domain) + : object(object(ore, "dimension_selectors"), domain); + if (rule.has("placement_channel")) return false; + + JsonElement pattern = rule.get("pattern"); + if (pattern == null || (!pattern.isJsonObject() && !pattern.isJsonPrimitive())) return false; + return channel.equals(pattern.isJsonObject() + ? text(pattern.getAsJsonObject(), "type") : pattern.getAsString()); + } + + private static JsonObject loadedCandidate(JsonArray candidates, String source, String channel) { + for (JsonElement element : candidates) { + if (!element.isJsonObject()) continue; + JsonObject candidate = element.getAsJsonObject(); + if (source.equals(text(candidate, "source_id")) + && channel.equals(text(candidate, "placement_channel")) + && candidate.has("loaded") && candidate.get("loaded").getAsBoolean()) { + return candidate; + } + } + return null; + } + + private static JsonObject object(JsonObject parent, String key) { + return parent.has(key) && parent.get(key).isJsonObject() + ? parent.getAsJsonObject(key) : new JsonObject(); + } + + private static String text(JsonObject parent, String key) { + return parent.has(key) && parent.get(key).isJsonPrimitive() ? parent.get(key).getAsString() : ""; + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/client/OreSourceGroupSettingsScreen.java b/src/main/java/zone/moddev/mc/orespawn/client/OreSourceGroupSettingsScreen.java index 84206091..35efa19c 100644 --- a/src/main/java/zone/moddev/mc/orespawn/client/OreSourceGroupSettingsScreen.java +++ b/src/main/java/zone/moddev/mc/orespawn/client/OreSourceGroupSettingsScreen.java @@ -150,11 +150,10 @@ protected void init() { @Override protected String rowText(int index) { String channel = channels.get(index); List choices = OreSourceListScreen.placementCandidates(group, channel); - String selected = group.placements.get(channel); - int choice = OreSourceListScreen.indexOf(choices, selected); - String source = choice < 0 + OreSourceCandidate selected = selectedPlacementCandidate(group, channel); + String source = selected == null ? I18n.format("label.orespawn.ore_source.missing") - : OreSourceListScreen.candidateLabel(choices.get(choice)); + : OreSourceListScreen.candidateLabel(selected); return channelLabel(channel) + (placementSelectable(group, channel) ? " > " : " = ") + placementSourceLabel(source, choices.size()); } @@ -187,6 +186,9 @@ protected void init() { lines.add(I18n.format("tooltip.orespawn.ore_source.placement_rules")); if ("keep_separate".equals(group.mode)) { lines.add(I18n.format("tooltip.orespawn.ore_source.placement_requires_consolidated")); + } else if (selectedPlacementCandidate(group, channel) != null + && !selectedPlacementCandidate(group, channel).active) { + lines.add(I18n.format("tooltip.orespawn.ore_source.output_only")); } else if (choices.isEmpty()) { lines.add(I18n.format("tooltip.orespawn.ore_source.placement_missing")); } else if (choices.size() == 1) { @@ -323,6 +325,16 @@ static boolean placementSelectable(OreSourceGroup group, String channel) { && OreSourceListScreen.placementCandidates(group, channel).size() > 1; } + static OreSourceCandidate selectedPlacementCandidate(OreSourceGroup group, String channel) { + String selected = group.placements.get(channel); + for (OreSourceCandidate candidate : group.candidates) { + if (candidate.loaded && candidate.sourceId.equals(selected) && candidate.channel.equals(channel)) { + return candidate; + } + } + return null; + } + static String placementStatus(OreSourceGroup group, List channels) { if (channels.isEmpty()) return I18n.format("label.orespawn.ore_source.no_placement_rules"); if ("keep_separate".equals(group.mode)) { @@ -331,7 +343,11 @@ static String placementStatus(OreSourceGroup group, List channels) { boolean selectable = false; for (String channel : channels) { int choices = OreSourceListScreen.placementCandidates(group, channel).size(); - if (choices == 0) return I18n.format("tooltip.orespawn.ore_source.placement_missing"); + if (choices == 0) { + return I18n.format(selectedPlacementCandidate(group, channel) == null + ? "tooltip.orespawn.ore_source.placement_missing" + : "tooltip.orespawn.ore_source.output_only"); + } selectable |= choices > 1; } return I18n.format(selectable ? "tooltip.orespawn.ore_source.placement_select" diff --git a/src/main/java/zone/moddev/mc/orespawn/client/OreSourceListScreen.java b/src/main/java/zone/moddev/mc/orespawn/client/OreSourceListScreen.java index 2072b99c..435e95bd 100644 --- a/src/main/java/zone/moddev/mc/orespawn/client/OreSourceListScreen.java +++ b/src/main/java/zone/moddev/mc/orespawn/client/OreSourceListScreen.java @@ -152,7 +152,7 @@ private void initGroups(final List groups) { return groupTooltip(groups.get(index)); } - @Override protected int rowActionWidth(int index) { return 16; } + @Override protected int rowActionWidth(int index) { return groups.get(index).preview ? 0 : 16; } @Override protected void drawRowAction(Minecraft minecraft, int index, int x, int y, int actionWidth, int rowHeight, boolean hovered) { @@ -198,6 +198,7 @@ private void initOutputs(final OreSourceGroup group) { outputScroll = 0; rebuild(); })); + modeButton.active = !group.preview; OreSpawnScreenLayout.explain(this, modeButton, "tooltip.orespawn.ore_source.output_mode"); if (acceptWidth > 0) { Button accept = addButton(OreSpawnScreenLayout.button(this, font, diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/OreSpawnCommands.java b/src/main/java/zone/moddev/mc/orespawn/commands/OreSpawnCommands.java index c81c57c8..cc1c14dd 100644 --- a/src/main/java/zone/moddev/mc/orespawn/commands/OreSpawnCommands.java +++ b/src/main/java/zone/moddev/mc/orespawn/commands/OreSpawnCommands.java @@ -39,6 +39,8 @@ public static void register(FMLServerStartingEvent event) { IntegerArgumentType.getInteger(context, "radius"))))) .then(Commands.literal("dump-biomes").requires(source -> source.hasPermissionLevel(2)) .executes(context -> dumpBiomes(context.getSource())))); + zone.moddev.mc.orespawn.commands.admin.AdminCommandRegistration.register( + event.getServer().getCommandManager().getDispatcher()); } private static int status(net.minecraft.command.CommandSource source) { diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminCommandRegistration.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminCommandRegistration.java new file mode 100644 index 00000000..f1ecd237 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminCommandRegistration.java @@ -0,0 +1,77 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; +import net.minecraft.command.CommandSource; +import net.minecraft.command.Commands; +import zone.moddev.mc.orespawn.worldgen.WorldGeologyProfileManager; + +/** Adds diagnostics without replacing the existing status, reload or explicit retrogen commands. */ +public final class AdminCommandRegistration { + private AdminCommandRegistration() { } + + public static void register(CommandDispatcher dispatcher) { + LiteralArgumentBuilder root = Commands.literal("orespawn"); + for (String action : new String[]{"help", "chunk", "survey", "explain", "jobs", "cancel", "clearchunk", "undo"}) { + int permission = action.equals("clearchunk") || action.equals("undo") ? 4 : 2; + root.then(command(action, action, permission)); + } + root.then(Commands.literal("status").then(command("verbose", "status verbose", 2))); + root.then(Commands.literal("retrogen").requires(source -> source.hasPermissionLevel(2)) + .then(command("status", "retrogen status", 2))); + dispatcher.register(root); + for (String alias : new String[]{"clearchunk", "clearchunks"}) { + if (dispatcher.getRoot().getChild(alias) == null) + dispatcher.register(command(alias, "clearchunk", 4)); + } + } + + private static LiteralArgumentBuilder command(String literal, String action, int permission) { + return Commands.literal(literal).requires(source -> source.hasPermissionLevel(permission)) + .executes(context -> execute(context.getSource(), action)) + .then(Commands.argument("arguments", StringArgumentType.greedyString()) + .suggests((context, builder) -> { + String remaining = builder.getRemaining(); + int split = remaining.lastIndexOf(' '); + com.mojang.brigadier.suggestion.SuggestionsBuilder tail = builder.createOffset( + builder.getStart() + split + 1); + java.util.Set choices = new java.util.TreeSet<>(java.util.Arrays.asList( + "--dimension", "--center", "--y", "--block", "preview", "confirm", "cancel", "backups")); + com.google.gson.JsonObject profile = WorldGeologyProfileManager.activeProfile().rootCopy(); + if (action.equals("explain") && profile.has("ores")) + profile.getAsJsonObject("ores").entrySet().forEach(entry -> choices.add(entry.getKey())); + if (remaining.contains("--dimension")) + context.getSource().getServer().forgeGetWorldMap().values().forEach( + world -> choices.add(zone.moddev.mc.orespawn.worldgen.WorldIds.dimension(world).toString())); + for (String choice : choices) + if (choice.startsWith(tail.getRemaining())) tail.suggest(choice); + return tail.buildFuture(); + }) + .executes(context -> execute(context.getSource(), action + " " + + StringArgumentType.getString(context, "arguments")))); + } + + private static int execute(CommandSource source, String command) throws CommandSyntaxException { + try { + return AdminCommands.handle(source.getServer(), AdminSource.from(source), command.split("\\s+")) ? 1 : 0; + } catch (AdminFailure failure) { + throw new SimpleCommandExceptionType(failure.message).create(); + } + } + + public static void tick(net.minecraftforge.event.TickEvent.ServerTickEvent event) { + if (event.phase == net.minecraftforge.event.TickEvent.Phase.END) { + AdminJobs.pollExports(); + AdminJobs.tick(); + } + } + public static void unload(net.minecraftforge.event.world.WorldEvent.Unload event) { AdminJobs.unload(event.getWorld().getWorld()); } + public static void stopped(net.minecraftforge.fml.event.server.FMLServerStoppedEvent event) { + AdminJobs.shutdown(); + AdminLighting.clear(); + + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminCommands.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminCommands.java new file mode 100644 index 00000000..538e2b30 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminCommands.java @@ -0,0 +1,236 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import net.minecraft.entity.player.ServerPlayerEntity; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.util.text.TranslationTextComponent; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.biome.Biome; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.registries.ForgeRegistries; +import zone.moddev.mc.orespawn.OreSpawn; +import zone.moddev.mc.orespawn.worldgen.GeomeConfig; +import zone.moddev.mc.orespawn.worldgen.OreRetrogenManager; +import zone.moddev.mc.orespawn.worldgen.OreSpawnOreGeneration; +import zone.moddev.mc.orespawn.worldgen.WorldGeologyProfile; +import zone.moddev.mc.orespawn.worldgen.WorldGeologyProfileManager; +import zone.moddev.mc.orespawn.worldgen.WorldIds; + +/** Target-native command adapter; selection never asks a chunk provider to load terrain. */ +public final class AdminCommands { + public static final List ACTIONS = Arrays.asList("help", "status", "chunk", "survey", "explain", "retrogen", "jobs", "cancel", "clearchunk", "undo", "reload", "dump-biomes"); + private AdminCommands() { } + + public static boolean handle(MinecraftServer server, AdminSource sender, String[] args) throws AdminFailure { + if (args.length == 0) return false; + String action = args[0]; + boolean verbose = "status".equals(action) && args.length == 2 && "verbose".equals(args[1]); + boolean retrogen = "retrogen".equals(action) && args.length > 1 && "status".equals(args[1]); + if (!verbose && !retrogen && !Arrays.asList("help", "chunk", "survey", "explain", "jobs", "cancel", "clearchunk", "undo").contains(action)) return false; + if (!sender.canUseCommand(2, "orespawn")) throw new AdminFailure("commands.generic.permission"); + if (("clearchunk".equals(action) || "undo".equals(action)) && !sender.canUseCommand(4, "orespawn")) + throw new AdminFailure("commands.generic.permission"); + try { + if ("help".equals(action)) { + for (String key : new String[]{"help", "options", "safety", "scope"}) sender.sendMessage(new TranslationTextComponent("commands.orespawn." + key)); + return true; + } + if ("jobs".equals(action)) { + if (args.length > 2) throw new IllegalArgumentException("Use jobs [job-id|backups]"); + if (args.length == 2 && "backups".equals(args[1])) AdminJobs.listBackups(sender, new Selection(sender, new String[0]).world); + else data(sender, AdminJobs.jobs(args.length == 2 ? args[1] : null)); + return true; + } + if ("cancel".equals(action)) { + if (args.length != 2) throw new IllegalArgumentException("Use cancel "); + AdminJobs.cancel(sender, args[1]); return true; + } + if ("clearchunk".equals(action) && args.length == 3 && "confirm".equals(args[1])) { + started(sender, AdminJobs.confirm(sender, args[2], false)); return true; + } + if ("clearchunk".equals(action) && args.length == 3 && "cancel".equals(args[1])) { + boolean cancelled = AdminJobs.cancelPreview(sender, args[2]); + sender.sendMessage(new TranslationTextComponent("commands.orespawn." + (cancelled ? "preview_cancelled" : "preview_inactive"))); + return true; + } + if ("undo".equals(action) && args.length == 4 && "confirm".equals(args[2])) { + // The backup ID must match the preview as well as its token. + started(sender, AdminJobs.confirmUndo(sender, args[1], args[3])); return true; + } + Selection selected = new Selection(sender, Arrays.copyOfRange(args, retrogen ? 2 : 1, args.length)); + if (verbose) { + JsonObject data = status(); + data(sender, data); + AdminJobs.publish(sender, selected.world, data); + } else if (retrogen) { + selected.chunkArguments(); + JsonObject data = OreRetrogenManager.diagnosticStatus(selected.world, new ChunkPos(selected.cx, selected.cz)); + data(sender, data); + AdminJobs.publish(sender, selected.world, data); + } else if ("chunk".equals(action)) { + selected.chunkArguments(); + JsonObject data = chunk(selected); + data(sender, data); + AdminJobs.publish(sender, selected.world, data); + } else if ("explain".equals(action)) { + if (selected.words.size() != 1 && selected.words.size() != 4) throw new IllegalArgumentException("Use explain [x y z]"); + BlockPos position = selected.words.size() == 4 ? new BlockPos(integer(selected.words.get(1), -30000000, 30000000), + integer(selected.words.get(2), 0, selected.world.getHeight() - 1), integer(selected.words.get(3), -30000000, 30000000)) : selected.block; + JsonObject data = OreSpawnOreGeneration.diagnosticRule(selected.world, position, new ResourceLocation(selected.words.get(0))); + JsonObject chat = zone.moddev.mc.orespawn.util.JsonCopies.copy(data); chat.remove("configured_rule"); + data(sender, chat); + AdminJobs.publish(sender, selected.world, data); + } else if ("survey".equals(action)) { + if (selected.words.size() > 1) throw new IllegalArgumentException("Use survey [radius]"); + int radius = selected.words.isEmpty() ? 1 : integer(selected.words.get(0), 0, 8); + started(sender, AdminJobs.start(sender, selected.world, selected.cx, selected.cz, radius, selected.minY, selected.maxY, selected.filter, false)); + } else if ("clearchunk".equals(action)) { + if (selected.words.size() == 1 && "preview".equals(selected.words.get(0))) selected.words.clear(); + selected.chunkArguments(); + if (!selected.filter.isEmpty()) throw new IllegalArgumentException("Block filters apply to surveys, not clearing"); + AdminJobs.start(sender, selected.world, selected.cx, selected.cz, 0, selected.minY, selected.maxY, "", true); + sender.sendMessage(new TranslationTextComponent("commands.orespawn.preview_started")); + } else if ("undo".equals(action)) { + if (selected.words.size() != 1) throw new IllegalArgumentException("Use undo [--dimension id]"); + AdminJobs.undo(sender, selected.world, selected.words.get(0)); + sender.sendMessage(new TranslationTextComponent("commands.orespawn.preview_started")); + } + return true; + } catch (RuntimeException e) { throw new AdminFailure("commands.orespawn.failed", e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()); } + } + + private static void started(AdminSource sender, String id) { AdminFeedback.started(sender, id); } + + private static void data(AdminSource sender, JsonObject value) { + // Chat is a short summary; the files keep the complete diagnostic data. + String text = value.toString(); + if (text.length() > 1024) text = text.substring(0, 1021) + "..."; + sender.sendMessage(new TranslationTextComponent("commands.orespawn.data", text)); + } + + public static JsonObject status() { + WorldGeologyProfile profile = WorldGeologyProfileManager.activeProfile(); + JsonObject data = new JsonObject(); + data.addProperty("version", OreSpawn.VERSION); data.addProperty("api", 1); + data.addProperty("provider_schema", 5); data.addProperty("global_schema", 8); data.addProperty("world_schema", 7); + data.addProperty("mode", profile.geologyMode().name()); data.addProperty("manage_vanilla_ores", profile.manageVanillaOres()); + data.addProperty("profile", DiagnosticFiles.fingerprint(profile.toJson())); + data.addProperty("providers", zone.moddev.mc.orespawn.integration.WorldgenIntegrationManager.activeProviderIds().toString()); + data.addProperty("generation_revision", profile.generationRevision()); + JsonObject versions = new JsonObject(); + for (String provider : zone.moddev.mc.orespawn.integration.WorldgenIntegrationManager.activeProviderIds()) { + java.util.Optional mod = net.minecraftforge.fml.ModList.get().getModContainerById(provider); + versions.addProperty(provider, mod.isPresent() ? mod.get().getModInfo().getVersion().toString() : "provider ID is not a loaded mod ID"); + } + data.add("provider_versions", versions); + if (profile.toJson().has("formations")) data.add("formations", profile.toJson().get("formations")); + return data; + } + + private static JsonObject chunk(Selection selected) { + Chunk chunk = AdminWorldAccess.loaded(selected.world, selected.cx, selected.cz); + JsonObject data = new JsonObject(); + data.addProperty("dimension", WorldIds.dimension(selected.world).toString()); + data.addProperty("dimension_id", selected.world.dimension.getType().getId()); + data.addProperty("chunk_x", selected.cx); data.addProperty("chunk_z", selected.cz); + data.addProperty("loaded", chunk != null); + data.addProperty("geology_mode", WorldGeologyProfileManager.activeProfile().geologyMode().name()); + data.addProperty("predicted_base_geome", "unavailable"); + if (chunk == null) return data; + data.addProperty("populated", chunk.getStatus().isAtLeast(net.minecraft.world.chunk.ChunkStatus.FEATURES)); data.addProperty("light_populated", chunk.getStatus().isAtLeast(net.minecraft.world.chunk.ChunkStatus.LIGHT)); + data.addProperty("min_y", 0); data.addProperty("max_y", selected.world.getHeight() - 1); + int low = Integer.MAX_VALUE, high = Integer.MIN_VALUE; + Map biomes = new TreeMap<>(); + for (int i = 0; i < 256; i++) { + int height = AdminWorldAccess.height(chunk, i & 15, i >>> 4); low = Math.min(low, height); high = Math.max(high, height); + Biome biome = chunk.getBiomes()[i]; + biomes.merge(biome == null ? "unknown" : String.valueOf(WorldIds.biome(biome)), 1, Integer::sum); + } + data.addProperty("lowest_surface_y", low - 1); data.addProperty("highest_surface_y", high - 1); + data.add("observed_column_samples", columnSamples(chunk::getBlockState, selected.cx, selected.cz, selected.minY, selected.maxY)); + JsonObject histogram = new JsonObject(); biomes.forEach(histogram::addProperty); data.add("biome_columns", histogram); + data.add("retrogen", OreRetrogenManager.diagnosticStatus(selected.world, new ChunkPos(selected.cx, selected.cz))); + Biome biome = chunk.getBiomes()[136]; + zone.moddev.mc.orespawn.worldgen.BakedGeomeConfig config = GeomeConfig.baked(WorldIds.dimension(selected.world)); + if (config != null && biome != null && WorldGeologyProfileManager.activeProfile().geologyMode() == zone.moddev.mc.orespawn.OreSpawnConfig.GeologyMode.GEOME) { + zone.moddev.mc.orespawn.worldgen.GeomeGeology.ColumnSample sample = new zone.moddev.mc.orespawn.worldgen.GeomeGeology(selected.world.getSeed(), config) + .sampleColumn(biome, WorldIds.biome(biome), (selected.cx << 4) + 8, (selected.cz << 4) + 8); + data.addProperty("predicted_base_geome", sample.geomeName()); + data.addProperty("geology_note", "Current base-geology prediction, not saved historical provenance or private formation checks"); + } + return data; + } + + static com.google.gson.JsonArray columnSamples(java.util.function.Function states, + int cx, int cz, int minY, int maxY) { + com.google.gson.JsonArray samples = new com.google.gson.JsonArray(); + int x = (cx << 4) + 8, z = (cz << 4) + 8; + for (int y = minY; ; y = Math.min(y + 16, maxY)) { + JsonObject sample = new JsonObject(); + sample.addProperty("x", x); sample.addProperty("y", y); sample.addProperty("z", z); + sample.addProperty("state", DiagnosticStates.key(states.apply(new BlockPos(x, y, z)))); + samples.add(sample); + if (y == maxY) return samples; + } + } + + public static int integer(String text, int minimum, int maximum) { + int number = Integer.parseInt(text); + if (number < minimum || number > maximum) throw new IllegalArgumentException("Value outside " + minimum + ".." + maximum); + return number; + } + + private static MinecraftServer serverOf(AdminSource sender) { return WorldGeologyProfileManager.activeServer(); } + + static final class Selection { + ServerWorld world; + BlockPos block; + int cx, cz, minY, maxY; + String filter = ""; + final List words = new ArrayList<>(); + Selection(AdminSource sender, String[] args) { + world = sender.getCommandSenderEntity() instanceof ServerPlayerEntity ? (ServerWorld) sender.getEntityWorld() : AdminWorldAccess.overworld(serverOf(sender)); + boolean center = false; + for (int i = 0; i < args.length; i++) { + String value = args[i]; + if ("--dimension".equals(value)) { + String id = args[++i]; ServerWorld found = null; + for (ServerWorld loaded : WorldGeologyProfileManager.activeServer().forgeGetWorldMap().values()) if (String.valueOf(loaded.dimension.getType().getId()).equals(id) + || WorldIds.dimension(loaded).toString().equals(id)) found = loaded; + if (found == null) throw new IllegalArgumentException("Dimension is not loaded"); + world = found; + } else if ("--center".equals(value)) { cx = integer(args[++i], -1874999, 1874999); cz = integer(args[++i], -1874999, 1874999); center = true; } + else if ("--y".equals(value)) { minY = integer(args[++i], 0, 255); maxY = integer(args[++i], 0, 255) + 1; } + else if ("--block".equals(value)) filter = args[++i]; + else if (value.startsWith("--")) throw new IllegalArgumentException("Unknown option " + value); + else words.add(value); + } + if (world == null || world.getHeight() > 256) throw new IllegalArgumentException("Unsupported or inactive dimension"); + block = sender.getCommandSenderEntity() instanceof ServerPlayerEntity && sender.getEntityWorld() == world ? sender.getPosition() : world.getSpawnPoint(); + if (!center) { cx = block.getX() >> 4; cz = block.getZ() >> 4; } + maxY = maxY == 0 ? world.getHeight() - 1 : maxY - 1; + if (minY > maxY || maxY >= world.getHeight()) throw new IllegalArgumentException("Invalid height range"); + if (!filter.isEmpty()) { + com.mojang.brigadier.StringReader reader = new com.mojang.brigadier.StringReader(filter); + try { + new net.minecraft.command.arguments.BlockStateParser(reader, false).parse(false); + if (reader.canRead()) throw new IllegalArgumentException("Unexpected block filter suffix"); + } catch (com.mojang.brigadier.exceptions.CommandSyntaxException ex) { + throw new IllegalArgumentException("Invalid block filter: " + filter, ex); + } + } + } + void chunkArguments() { + if (words.size() == 2) { cx = integer(words.get(0), -1874999, 1874999); cz = integer(words.get(1), -1874999, 1874999); } + else if (!words.isEmpty()) throw new IllegalArgumentException("Use [chunkX chunkZ] or --center chunkX chunkZ"); + } + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminFailure.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminFailure.java new file mode 100644 index 00000000..71f4ea02 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminFailure.java @@ -0,0 +1,13 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.TranslationTextComponent; + +/** Keeps translated command failures intact until Brigadier displays them. */ +final class AdminFailure extends RuntimeException { + final ITextComponent message; + AdminFailure(String key, Object... arguments) { + super(key); + message = new TranslationTextComponent(key, arguments); + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminFeedback.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminFeedback.java new file mode 100644 index 00000000..a1292ded --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminFeedback.java @@ -0,0 +1,93 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import java.util.ArrayList; +import java.util.List; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.StringTextComponent; +import net.minecraft.util.text.TranslationTextComponent; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.util.text.event.ClickEvent; +import net.minecraft.util.text.event.HoverEvent; + +/** Keeps routine chat short while leaving exact commands and reports available. */ +public final class AdminFeedback { + private AdminFeedback() { } + + static ITextComponent action(String key, String command, TextFormatting colour) { + ITextComponent text = new TranslationTextComponent("commands.orespawn." + key); + text.getStyle().setColor(colour).setBold(true).setUnderlined(true) + .setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command)) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, + new TranslationTextComponent("commands.orespawn.action_hint", command))); + return text; + } + + static String confirmation(String token, boolean undo, String backupId) { + return undo ? "/orespawn undo " + backupId + " confirm " + token : "/orespawn clearchunk confirm " + token; + } + + static ITextComponent details(String id) { + return action("details", "/orespawn jobs " + id, TextFormatting.AQUA); + } + + static List previewLines(String id, String token, boolean undo, String backupId, + String dimension, int cx, int cz, int minY, int maxY, int changes, int preserved) { + List lines = new ArrayList<>(); + ITextComponent title = new TranslationTextComponent("commands.orespawn.preview_title"); + title.getStyle().setColor(TextFormatting.YELLOW).setBold(true); + lines.add(title); + lines.add(new TranslationTextComponent("commands.orespawn.preview_location", dimensionLabel(dimension), cx, cz, minY, maxY)); + lines.add(new TranslationTextComponent("commands.orespawn." + (undo ? "preview_undo_counts" : "preview_clear_counts"), changes, preserved)); + ITextComponent warning = new TranslationTextComponent("commands.orespawn." + (undo ? "preview_undo_warning" : "preview_warning")); + warning.getStyle().setColor(TextFormatting.YELLOW); + lines.add(warning); + ITextComponent expiry = new TranslationTextComponent("commands.orespawn.preview_expiry"); + expiry.getStyle().setColor(TextFormatting.GRAY); + lines.add(expiry); + ITextComponent buttons = new StringTextComponent(""); + buttons.appendSibling(action(undo ? "confirm_undo" : "confirm_clear", confirmation(token, undo, backupId), TextFormatting.RED)); + buttons.appendText(" ").appendSibling(action("preview_cancel", "/orespawn clearchunk cancel " + token, TextFormatting.GRAY)); + buttons.appendText(" ").appendSibling(details(id)); + lines.add(buttons); + return lines; + } + + public static void preview(AdminSource sender, String id, String token, boolean undo, String backupId, + String dimension, int cx, int cz, int minY, int maxY, int changes, int preserved) { + for (ITextComponent line : previewLines(id, token, undo, backupId, dimension, cx, cz, minY, maxY, changes, preserved)) sender.sendMessage(line); + consoleCommand(sender, confirmation(token, undo, backupId)); + } + + static void started(AdminSource sender, String id) { + sender.sendMessage(new TranslationTextComponent("commands.orespawn.started", details(id))); + consoleCommand(sender, "/orespawn jobs " + id); + } + + static void completed(AdminSource sender, String id, int edited, boolean undo, String backupId, String dimension) { + if (undo) sender.sendMessage(new TranslationTextComponent("commands.orespawn.complete_undo", edited, details(id))); + else { + String command = "/orespawn undo " + backupId + " --dimension " + dimension; + sender.sendMessage(new TranslationTextComponent("commands.orespawn.complete_clear", edited, + action("undo_preview", command, TextFormatting.AQUA), details(id))); + consoleCommand(sender, command); + } + } + + static void result(AdminSource sender, String id, String status, String message) { + String shortMessage = message.length() > 1024 ? message.substring(0, 1021) + "..." : message; + sender.sendMessage(new TranslationTextComponent("commands.orespawn.job_result", details(id), status, shortMessage)); + consoleCommand(sender, "/orespawn jobs " + id); + } + + private static void consoleCommand(AdminSource sender, String command) { + // Server consoles cannot click chat, so they still need a copyable command. + if (!(sender.getCommandSenderEntity() instanceof PlayerEntity)) sender.sendMessage(new StringTextComponent(command)); + } + + private static ITextComponent dimensionLabel(String dimension) { + if ("minecraft:overworld".equals(dimension) || "minecraft:the_nether".equals(dimension) || "minecraft:the_end".equals(dimension)) + return new TranslationTextComponent("value.orespawn.dimension." + dimension.substring("minecraft:".length())); + return new StringTextComponent(dimension); + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminJobs.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminJobs.java new file mode 100644 index 00000000..09696c61 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminJobs.java @@ -0,0 +1,535 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import net.minecraft.block.BlockState; +import net.minecraft.entity.player.ServerPlayerEntity; +import net.minecraft.block.Blocks; +import net.minecraft.network.play.server.SChunkDataPacket; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.util.text.TranslationTextComponent; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.biome.Biome; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.ChunkSection; +import zone.moddev.mc.orespawn.worldgen.WorldGeologyProfileManager; +import zone.moddev.mc.orespawn.worldgen.WorldIds; + +/** One cooperative server job; the file worker never receives a world or chunk. */ +public final class AdminJobs { + public static final int MAX_VISITS = 16384; + public static final long TICK_NANOS = 4000000L; + private static final Map HISTORY = new LinkedHashMap<>(); + private static final Map PREVIEWS = new LinkedHashMap<>(); + private static ExecutorService files; + private static Job active; + private AdminJobs() { } + + private static ExecutorService files() { + if (files == null || files.isShutdown()) files = newFileWorker(); + return files; + } + + static ExecutorService newFileWorker() { + return new java.util.concurrent.ThreadPoolExecutor(1, 1, 0L, java.util.concurrent.TimeUnit.MILLISECONDS, + new java.util.concurrent.ArrayBlockingQueue<>(32), task -> { + Thread thread = new Thread(task, "OreSpawn diagnostic files"); thread.setDaemon(true); return thread; + }, new java.util.concurrent.ThreadPoolExecutor.AbortPolicy()); + } + + private static Future queueReport(java.util.concurrent.Callable writer) { + try { return files().submit(writer); } + catch (java.util.concurrent.RejectedExecutionException e) { + java.util.concurrent.CompletableFuture failed = new java.util.concurrent.CompletableFuture<>(); + failed.completeExceptionally(e); + return failed; + } + } + + public static String owner(AdminSource sender) { + return sender.getCommandSenderEntity() == null ? "console:" + sender.getName() + : sender.getCommandSenderEntity().getUniqueID().toString(); + } + + public static Path root(ServerWorld world) { + return AdminWorldAccess.overworld(world.getServer()).getSaveHandler().getWorldDirectory() + .toPath().toAbsolutePath().normalize().resolve("orespawn/diagnostics"); + } + + private static String worldKey(ServerWorld world) { + return DiagnosticFiles.hash((root(world).toString() + ":" + world.getSeed()).getBytes(StandardCharsets.UTF_8)); + } + + public static String start(AdminSource sender, ServerWorld world, int cx, int cz, + int radius, int minY, int maxY, String filter, boolean preview) { + ensureIdle(); + if (preview) safePlayers(sender, world, cx, cz); + Job job = new Job(sender, world, cx, cz, radius, minY, maxY, filter, preview ? "clear_preview" : "survey"); + active = job; + return job.id; + } + + public static String undo(AdminSource sender, ServerWorld world, String backupId) { + ensureIdle(); + Path backup = DiagnosticFiles.child(root(world).resolve("backups"), backupId).resolve("journal.json"); + Job job = new Job(sender, world, 0, 0, 0, 0, world.getHeight() - 1, "", "undo_read"); + job.future = files().submit(() -> EditJournal.read(DiagnosticFiles.readBackup(backup))); + job.backupId = backupId; + active = job; + return job.id; + } + + public static String confirm(AdminSource sender, String token, boolean undo) { + ensureIdle(); + Preview preview = PREVIEWS.get(token); + if (preview == null || preview.undo != undo || !preview.lease.accepts(owner(sender), profileHash(), System.nanoTime())) + throw new IllegalArgumentException("Preview expired, profile changed or operator does not match"); + safePlayers(sender, preview.world, preview.cx, preview.cz); + PREVIEWS.remove(token); + Job job = new Job(sender, preview.world, preview.cx, preview.cz, 0, preview.minY, preview.maxY, "", "verify"); + if (!job.catalog.fingerprint().equals(preview.catalogFingerprint)) throw new IllegalArgumentException("Material identities changed; request a new preview"); + job.journal = preview.journal; + job.expectedHash = preview.snapshot; + job.undo = undo; + job.backupId = undo ? preview.backupId : job.id; + active = job; + return job.id; + } + + public static String confirmUndo(AdminSource sender, String backupId, String token) { + Preview preview = PREVIEWS.get(token); + if (preview == null || !backupId.equals(preview.backupId)) throw new IllegalArgumentException("Backup does not match this preview"); + return confirm(sender, token, true); + } + + public static boolean cancelPreview(AdminSource sender, String token) { + if (!sender.canUseCommand(4, "orespawn")) throw new IllegalArgumentException("Permission level 4 is required"); + Preview preview = PREVIEWS.get(token); + if (preview == null) return false; + if (!preview.owner.equals(owner(sender))) throw new IllegalArgumentException("This preview belongs to another operator"); + PREVIEWS.remove(token); + return true; + } + + private static void ensureIdle() { if (active != null) throw new IllegalStateException("A diagnostic job is already running"); } + private static String profileHash() { return DiagnosticFiles.fingerprint(WorldGeologyProfileManager.activeProfile().toJson()); } + + static void safePlayers(AdminSource sender, ServerWorld world, int cx, int cz) { + if (!sender.canUseCommand(4, "orespawn")) throw new IllegalArgumentException("Permission level 4 is required"); + if (sender.getCommandSenderEntity() instanceof ServerPlayerEntity && !((ServerPlayerEntity) sender.getCommandSenderEntity()).isSpectator() + && !((ServerPlayerEntity) sender.getCommandSenderEntity()).isCreative()) throw new IllegalArgumentException("Use Creative or Spectator mode"); + for (net.minecraft.entity.player.PlayerEntity player : world.getPlayers()) + if ((player.getPosition().getX() >> 4) == cx && (player.getPosition().getZ() >> 4) == cz + && !player.isSpectator() && !player.isCreative()) + throw new IllegalArgumentException("A Survival or Adventure player occupies this chunk"); + } + + public static JsonObject jobs(String id) { + if (id != null) { + if (active != null && active.id.equals(id)) return active.summary(); + JsonObject result = HISTORY.get(id); + if (result == null) throw new IllegalArgumentException("Unknown job; saved reports remain in the world's diagnostics directory"); + return zone.moddev.mc.orespawn.util.JsonCopies.copy(result); + } + JsonObject result = new JsonObject(); + if (active != null) result.add(active.id, active.summary()); + HISTORY.forEach(result::add); + return result; + } + + public static String publish(AdminSource sender, ServerWorld world, JsonObject value) { + String id = UUID.randomUUID().toString(); + Path directory = DiagnosticFiles.child(root(world).resolve("reports"), id); + JsonObject snapshot = zone.moddev.mc.orespawn.util.JsonCopies.copy(value); + snapshot.addProperty("format", 1); snapshot.addProperty("id", id); + snapshot.addProperty("generated_utc_ms", System.currentTimeMillis()); + snapshot.addProperty("profile", profileHash()); + Future output = queueReport(() -> { DiagnosticFiles.write(directory.resolve("report.json"), snapshot); return null; }); + JsonObject summary = new JsonObject(); summary.addProperty("status", "complete"); + summary.addProperty("export", "pending"); summary.addProperty("report_directory", directory.toString()); + exportResults.put(id, output); HISTORY.put(id, summary); + while (HISTORY.size() > 32) { String oldest = HISTORY.keySet().iterator().next(); HISTORY.remove(oldest); exportResults.remove(oldest); } + sender.sendMessage(new TranslationTextComponent("commands.orespawn.report", id, directory.toString())); + return id; + } + + public static void listBackups(AdminSource sender, ServerWorld world) { + Path directory = root(world).resolve("backups"); + sender.sendMessage(new TranslationTextComponent("commands.orespawn.backups", directory.toString())); + } + + public static void cancel(AdminSource sender, String id) { + if (active == null || !active.id.equals(id)) throw new IllegalArgumentException("No such running job"); + if (!owner(sender).equals(owner(active.sender)) && !sender.canUseCommand(4, "orespawn")) + throw new IllegalArgumentException("Only the owner or a level 4 operator can cancel this job"); + active.requestStop("cancelled", "Cancelled; any partial edit remains in its backup journal"); + } + + public static void tick() { + long deadline = System.nanoTime() + TICK_NANOS; + int visits = AdminLighting.tick(deadline, MAX_VISITS); + if (active == null) return; + Job job = active; + try { + while (active == job && visits < MAX_VISITS && System.nanoTime() < deadline) { + if (!job.step()) break; + visits++; + } + job.maxVisits = Math.max(job.maxVisits, visits); + } catch (Exception e) { job.requestStop("failed", e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()); } + } + + public static void unload(net.minecraft.world.World world) { + if (!(world instanceof ServerWorld)) return; + if (active != null && active.world == world) active.finish("interrupted", "Dimension unloaded; no automatic resume"); + PREVIEWS.values().removeIf(preview -> preview.world == world); + } + + public static void shutdown() { + if (active != null) active.finish("interrupted", "Server stopped; no automatic resume"); + PREVIEWS.clear(); HISTORY.clear(); exportResults.clear(); + if (files != null) files.shutdown(); + } + + private static final class Preview { + final ServerWorld world; + final int cx, cz, minY, maxY; + final String owner, snapshot, profile, backupId, catalogFingerprint; + final EditJournal journal; + final boolean undo; + final PreviewLease lease; + Preview(Job job) { + world = job.world; cx = job.cx; cz = job.cz; minY = job.minY; maxY = job.maxY; + owner = owner(job.sender); snapshot = job.hash(); profile = job.profile; journal = job.journal; + undo = job.undo; backupId = job.backupId; + catalogFingerprint = job.catalog.fingerprint(); + lease = new PreviewLease(owner, profile, System.nanoTime()); + } + } + + private static final class Job { + final String id = UUID.randomUUID().toString(); + final AdminSource sender; + final ServerWorld world; + final long started = System.currentTimeMillis(); + final String profile; + final String filter; + final java.util.function.Predicate filterTest; + final DiagnosticCatalog catalog; + final Path directory; + final String dimension; + final SurveyCounts counts = new SurveyCounts(); + final JsonArray skipped = new JsonArray(); + final List positions = new ArrayList<>(); + final List changes = new ArrayList<>(); + final Map stateKeys = new IdentityHashMap<>(); + final Map resolved = new java.util.HashMap<>(); + int cx, cz, minY, maxY, position, cursor, edited, editCursor, lightCursor, sampledChunks, maxVisits; + String phase, expectedHash, backupId, finishedHash; + String terminalStatus = "complete", terminalMessage; + boolean undo, changed, scanningUndo, lightingComplete; + Chunk chunk; + MessageDigest digest; + EditJournal journal; + Future future; + + Job(AdminSource sender, ServerWorld world, int cx, int cz, int radius, + int minY, int maxY, String filter, String phase) { + this.sender = sender; this.world = world; this.cx = cx; this.cz = cz; + this.minY = minY; this.maxY = maxY; this.filter = filter; this.phase = phase; + this.filterTest = DiagnosticStates.filter(filter); + this.profile = profileHash(); + this.directory = root(world); this.dimension = WorldIds.dimension(world).toString(); + this.catalog = new DiagnosticCatalog(WorldGeologyProfileManager.activeProfile().toJson()); + for (int x = cx - radius; x <= cx + radius; x++) for (int z = cz - radius; z <= cz + radius; z++) positions.add(new ChunkPos(x, z)); + resetDigest(); + } + + private void resetDigest() { + try { digest = MessageDigest.getInstance("SHA-256"); } catch (java.security.NoSuchAlgorithmException e) { throw new IllegalStateException(e); } + finishedHash = null; + } + String hash() { + if (finishedHash == null) { + byte[] value = digest.digest(); + StringBuilder result = new StringBuilder(); + for (byte item : value) result.append(String.format(java.util.Locale.ROOT, "%02x", item & 255)); + finishedHash = result.toString(); + } + return finishedHash; + } + private String key(BlockState state) { return stateKeys.computeIfAbsent(state, DiagnosticStates::key); } + private BlockPos pos(int index) { return new BlockPos((cx << 4) + (index & 15), index >>> 8, (cz << 4) + ((index >>> 4) & 15)); } + private boolean loaded() { return chunk != null && AdminWorldAccess.loaded(world, cx, cz) == chunk; } + + boolean step() throws Exception { + if (world.getServer() != WorldGeologyProfileManager.activeServer()) throw new IOException("World is no longer active"); + if ("undo_read".equals(phase)) { + if (!future.isDone()) return false; + journal = (EditJournal) future.get(); + if (!worldKey(world).equals(journal.header.get("world").getAsString()) + || !WorldIds.dimension(world).toString().equals(journal.header.get("dimension").getAsString())) + throw new IOException("Backup belongs to another world or dimension"); + cx = journal.header.get("chunk_x").getAsInt(); cz = journal.header.get("chunk_z").getAsInt(); + positions.clear(); positions.add(new ChunkPos(cx, cz)); + safePlayers(sender, world, cx, cz); + undo = true; scanningUndo = true; phase = "undo_preview"; + return true; + } + if ("backup".equals(phase)) { + if (!future.isDone()) return false; + future.get(); + cursor = 0; position = 0; chunk = null; resetDigest(); phase = "verify_after_backup"; + return true; + } + if ("edit".equals(phase)) return edit(); + if ("light".equals(phase)) { + if (!loaded()) throw new IOException("Chunk unloaded during lighting; use the retained journal to recover"); + if (lightCursor < journal.cells.size()) { + if (!AdminWorldAccess.checkLight(world, pos(journal.cells.get(lightCursor++).index))) throw new IOException("Lighting area unloaded; cleanup remains pending"); + return true; + } + if (!AdminLighting.complete(world, chunk)) return false; + lightingComplete = true; + chunk.markDirty(); + finish(terminalStatus, terminalMessage == null ? "Changed " + edited + " cells; backup " + backupId : terminalMessage); return false; + } + if (scanningUndo) { + if (chunk == null) chunk = AdminWorldAccess.loaded(world, cx, cz); + if (!loaded()) throw new IOException("Undo requires the existing chunk to be loaded"); + if (editCursor < journal.cells.size()) { + EditJournal.Cell cell = journal.cells.get(editCursor++); + resolved.computeIfAbsent(cell.before, DiagnosticStates::resolve); + resolved.computeIfAbsent(cell.after, DiagnosticStates::resolve); + BlockState state = chunk.getBlockState(pos(cell.index)); + if (!EditJournal.canUndo(key(state), cell) || state.getBlock().hasTileEntity(state)) throw new IOException("Undo conflict; no blocks restored"); + return true; + } + scanningUndo = false; editCursor = 0; + } + return scan(); + } + + private boolean scan() throws Exception { + boolean survey = "survey".equals(phase); + if (position >= positions.size()) { scanned(); return false; } + ChunkPos at = positions.get(position); + cx = at.x; cz = at.z; + if (chunk == null) { + chunk = AdminWorldAccess.loaded(world, cx, cz); + if (chunk == null) { + if (!survey) throw new IOException("Target chunk is not loaded"); + skipped.add(new com.google.gson.JsonPrimitive(cx + "," + cz + ":unloaded")); position++; return true; + } + cursor = minY << 8; + } + if (!loaded()) { + if (!survey) throw new IOException("Target chunk unloaded"); + skipped.add(new com.google.gson.JsonPrimitive(cx + "," + cz + ":unloaded_during_scan")); position++; chunk = null; return true; + } + if (cursor >= (maxY + 1) * 256) { sampledChunks++; position++; chunk = null; return true; } + BlockPos pos = pos(cursor); + BlockState state = chunk.getBlockState(pos); + String key = key(state); + digest.update(key.getBytes(StandardCharsets.UTF_8)); digest.update((byte) 0); + if (survey || "clear_preview".equals(phase)) { + String category = catalog.category(state); + if (matches(state)) { + Biome biome = chunk.getBiomes()[((cursor >>> 4) & 15) * 16 + (cursor & 15)]; + counts.add(key, category, pos.getY(), biome == null ? "unknown" : String.valueOf(WorldIds.biome(biome)), cx, cz); + } + if (!survey && catalog.removable(state, state.getBlock().hasTileEntity(state) || chunk.getTileEntityMap().containsKey(pos))) { + if (!state.equals(resolved.computeIfAbsent(key, DiagnosticStates::resolve))) + throw new IOException("This state cannot be restored exactly: " + key); + changes.add(new EditJournal.Cell(cursor, key, key(Blocks.AIR.getDefaultState()))); + } + } + cursor++; + return true; + } + + private boolean matches(BlockState state) { return filterTest.test(state); } + + private void scanned() throws Exception { + if ("survey".equals(phase)) { finish(skipped.size() == 0 ? "complete" : "partial", "Measured blocks, not generator attribution"); return; } + if ("clear_preview".equals(phase)) { + JsonObject header = new JsonObject(); + header.addProperty("minecraft_version", net.minecraftforge.versions.mcp.MCPVersion.getMCVersion()); + header.addProperty("orespawn_version", zone.moddev.mc.orespawn.OreSpawn.VERSION); + header.addProperty("world", worldKey(world)); header.addProperty("dimension", WorldIds.dimension(world).toString()); + header.addProperty("chunk_x", cx); header.addProperty("chunk_z", cz); + header.addProperty("profile", profile); header.addProperty("operator", owner(sender)); header.addProperty("snapshot", hash()); + header.addProperty("min_y", minY); header.addProperty("max_y", maxY); + header.addProperty("catalog", catalog.fingerprint()); + journal = new EditJournal(header, changes); + } + if ("clear_preview".equals(phase) || "undo_preview".equals(phase)) { + String token = UUID.randomUUID().toString(); + while (PREVIEWS.size() >= 32) PREVIEWS.remove(PREVIEWS.keySet().iterator().next()); + PREVIEWS.put(token, new Preview(this)); + JsonObject report = summary(); report.addProperty("confirmation_token", token); + report.addProperty("warning", "This changes matching player-placed terrain too. Undo restores blocks, not entities or elapsed time. Use a disposable world."); + report.addProperty("removal_cells", journal.cells.size()); + report.addProperty("preserved_cells", ((maxY - minY + 1) * 256) - journal.cells.size()); + finish("preview", "chunk=" + cx + "," + cz + "; y=" + minY + ".." + maxY + "; cells=" + journal.cells.size() + + "; preserved=" + (((maxY - minY + 1) * 256) - journal.cells.size()) + + "; " + (undo ? "/orespawn undo " + backupId + " confirm " : "/orespawn clearchunk confirm ") + token, report); + return; + } + if (!profile.equals(profileHash()) || !hash().equals(expectedHash)) throw new IOException("Snapshot or profile changed; request a new preview"); + if (!catalog.fingerprint().equals(new DiagnosticCatalog(WorldGeologyProfileManager.activeProfile().toJson()).fingerprint())) + throw new IOException("Material identities changed; request a new preview"); + safePlayers(sender, world, cx, cz); + chunk = AdminWorldAccess.loaded(world, cx, cz); + if (!loaded()) throw new IOException("Chunk unloaded"); + if (!world.isAreaLoaded(new BlockPos((cx << 4) - 17, 0, (cz << 4) - 17), + new BlockPos((cx << 4) + 32, world.getHeight() - 1, (cz << 4) + 32))) + throw new IOException("Keep the surrounding lighting area loaded before editing"); + if (!undo && !"verify_after_backup".equals(phase)) { + Path target = DiagnosticFiles.child(directory.resolve("backups"), backupId).resolve("journal.json"); + JsonObject payload = journal.json(); + future = files().submit(() -> { DiagnosticFiles.backup(target, payload); return null; }); phase = "backup"; + } else { phase = "edit"; editCursor = 0; } + } + + private boolean edit() throws IOException { + if (!loaded()) throw new IOException("Chunk unloaded; partial edit is recoverable from its journal"); + safePlayers(sender, world, cx, cz); + if (editCursor >= journal.cells.size()) { + if (!changed) { finish("complete", "No recorded cells needed changes; backup " + backupId); return false; } + AdminWorldAccess.repairHeightmaps(chunk); chunk.markDirty(); phase = "light"; return true; + } + EditJournal.Cell cell = journal.cells.get(editCursor++); + BlockPos pos = pos(cell.index); + BlockState state = chunk.getBlockState(pos); + String current = key(state); + if (undo && current.equals(cell.before)) return true; + if (!current.equals(undo ? cell.after : cell.before) || state.getBlock().hasTileEntity(state) + || chunk.getTileEntityMap().containsKey(pos)) throw new IOException("Intervening edit; stopped without overwriting it"); + String destination = undo ? cell.before : cell.after; + BlockState replacement = resolved.computeIfAbsent(destination, DiagnosticStates::resolve); + ChunkSection[] sections = chunk.getSections(); + int section = cell.index >>> 12; + if (sections[section] == null) sections[section] = new ChunkSection(section << 4); + sections[section].setBlockState(pos.getX() & 15, pos.getY() & 15, pos.getZ() & 15, replacement); + AdminLighting.changed(world, chunk, pos); + + changed = true; edited++; chunk.markDirty(); + return true; + } + + JsonObject summary() { + JsonObject result = new JsonObject(); + result.addProperty("format", 1); result.addProperty("id", id); result.addProperty("phase", phase); + result.addProperty("owner", owner(sender)); result.addProperty("dimension", dimension); + result.addProperty("chunk_x", cx); result.addProperty("chunk_z", cz); + result.addProperty("min_y", minY); result.addProperty("max_y", maxY); result.addProperty("profile", profile); + result.addProperty("started_utc_ms", started); result.addProperty("sampled_chunks", sampledChunks); + result.addProperty("requested_chunks", positions.size()); result.addProperty("edited_cells", edited); + result.addProperty("maximum_block_visits_per_tick", maxVisits); + if (backupId != null) result.addProperty("backup_id", backupId); + return result; + } + + void requestStop(String status, String message) { + if (active != this) return; + if (changed && "light".equals(phase) && !"failed".equals(status)) { + terminalStatus = status; terminalMessage = message; + return; + } + if (changed && loaded() && !"light".equals(phase)) { + terminalStatus = status; terminalMessage = message; + AdminWorldAccess.repairHeightmaps(chunk); chunk.markDirty(); + lightCursor = 0; phase = "light"; + return; + } + finish(status, message); + } + + void finish(String status, String message) { finish(status, message, summary()); } + void finish(String status, String message, JsonObject report) { + if (active != this) return; + if (lightingComplete && chunk != null) AdminLighting.complete(world, chunk); + if (changed && !lightingComplete && chunk != null) AdminLighting.recover(world, chunk); + report.addProperty("lighting_complete", !changed || lightingComplete); + report.addProperty("lighting_recovery_pending", changed && chunk != null && AdminLighting.isPending(world, chunk)); + try { syncChunk(); } + catch (RuntimeException e) { + status = "failed"; + message = "The edit is journaled, but client synchronisation failed: " + e.getMessage(); + org.apache.logging.log4j.LogManager.getLogger().warn("Could not synchronise OreSpawn edit {}", id, e); + } + report.addProperty("status", status); report.addProperty("message", message); + report.addProperty("finished_utc_ms", System.currentTimeMillis()); report.add("skipped_chunks", skipped); + JsonObject saved = zone.moddev.mc.orespawn.util.JsonCopies.copy(report); + SurveyCounts outputCounts = counts; + Path target = DiagnosticFiles.child(directory.resolve("reports"), id); + Future output = queueReport(() -> { + saved.add("counts", outputCounts.json()); + DiagnosticFiles.write(target.resolve("report.json"), saved); + for (Map.Entry file : outputCounts.csv().entrySet()) DiagnosticFiles.writeText(target.resolve(file.getKey()), file.getValue()); + return null; + }); + report.addProperty("report_directory", target.toString()); + // I/O completion is visible through jobs; a pending export is never reported as written. + report.addProperty("export", "pending"); + exportResults.put(id, output); + HISTORY.put(id, report); + while (HISTORY.size() > 32) { String oldest = HISTORY.keySet().iterator().next(); HISTORY.remove(oldest); exportResults.remove(oldest); } + active = null; + try { + if ("preview".equals(status)) AdminFeedback.preview(sender, id, report.get("confirmation_token").getAsString(), undo, backupId, + dimension, cx, cz, minY, maxY, journal.cells.size(), ((maxY - minY + 1) * 256) - journal.cells.size()); + else if ("complete".equals(status) && backupId != null) AdminFeedback.completed(sender, id, edited, undo, backupId, dimension); + else AdminFeedback.result(sender, id, status, message); + } + catch (RuntimeException e) { org.apache.logging.log4j.LogManager.getLogger().warn("OreSpawn job {} finished, but its operator feedback was unavailable", id, e); } + } + + private void syncChunk() { + if (changed && loaded()) { + if (!lightingComplete) AdminWorldAccess.repairHeightmaps(chunk); + chunk.markDirty(); + List watchers = world.getChunkProvider().chunkManager + .getTrackingPlayers(chunk.getPos(), false).collect(java.util.stream.Collectors.toList()); + if (!watchers.isEmpty()) { + SChunkDataPacket packet = new SChunkDataPacket(chunk, 65535); + watchers.forEach(player -> { + player.connection.sendPacket(packet); + if (lightingComplete) player.connection.sendPacket(new net.minecraft.network.play.server.SUpdateLightPacket( + chunk.getPos(), world.getChunkProvider().getLightManager())); + }); + } + } + } + } + + private static final Map> exportResults = new LinkedHashMap<>(); + public static void pollExports() { + PREVIEWS.values().removeIf(preview -> preview.lease.expired(System.nanoTime())); + for (Map.Entry> entry : exportResults.entrySet()) { + if (!entry.getValue().isDone() || !HISTORY.containsKey(entry.getKey())) continue; + JsonObject result = HISTORY.get(entry.getKey()); + if (!"pending".equals(result.get("export").getAsString())) continue; + try { entry.getValue().get(); result.addProperty("export", "written"); } + catch (Exception e) { + result.addProperty("export", "failed: " + e.getMessage()); + org.apache.logging.log4j.LogManager.getLogger().warn("Could not export OreSpawn diagnostic report {}", entry.getKey(), e); + } + } + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminLighting.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminLighting.java new file mode 100644 index 00000000..e4a4dddd --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminLighting.java @@ -0,0 +1,142 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import java.util.BitSet; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.event.world.ChunkDataEvent; + +/** Retains unfinished height/light work across unloads without resuming block edits. */ +public final class AdminLighting { + private static final String TAG = "OreSpawnAdminLighting"; + private static final Map PENDING = new ConcurrentHashMap<>(); + private AdminLighting() { } + + static void changed(ServerWorld world, Chunk chunk, BlockPos position) { + Pending pending = PENDING.computeIfAbsent(new Key(world, chunk.getPos().x, chunk.getPos().z), ignored -> new Pending(chunk)); + synchronized (pending) { + pending.cells.set((position.getY() << 8) | ((position.getZ() & 15) << 4) | (position.getX() & 15)); + pending.heightsReady = false; + pending.light = null; + } + } + static boolean complete(ServerWorld world, Chunk chunk) { + Key key = new Key(world, chunk.getPos().x, chunk.getPos().z); + Pending pending = PENDING.get(key); + if (pending == null) return true; + synchronized (pending) { + if (pending.light == null) pending.light = world.getChunkProvider().getLightManager().lightChunk(chunk, false); + if (!pending.light.isDone()) return false; + pending.light.join(); + PENDING.remove(key, pending); + return true; + } + } + public static boolean isPending(ServerWorld world, Chunk chunk) { + return PENDING.containsKey(new Key(world, chunk.getPos().x, chunk.getPos().z)); + } + static void recover(ServerWorld world, Chunk chunk) { + Pending pending = PENDING.get(new Key(world, chunk.getPos().x, chunk.getPos().z)); + if (pending != null) synchronized (pending) { pending.recovery = true; } + } + public static void onChunkAvailable(net.minecraftforge.event.world.ChunkEvent.Load event) { + if (!(event.getWorld() instanceof ServerWorld) || !(event.getChunk() instanceof Chunk)) return; + Chunk chunk = (Chunk) event.getChunk(); + PENDING.computeIfPresent(new Key((ServerWorld) event.getWorld(), chunk.getPos().x, chunk.getPos().z), (key, previous) -> { + synchronized (previous) { + if (previous.chunk == chunk) { previous.recovery = true; return previous; } + Pending next = new Pending(chunk); + next.cells.or(previous.cells); next.recovery = true; + return next; + } + }); + } + public static void onSave(ChunkDataEvent.Save event) { + if (!(event.getWorld() instanceof ServerWorld) || !(event.getChunk() instanceof Chunk)) return; + Chunk chunk = (Chunk) event.getChunk(); + Pending pending = PENDING.get(new Key((ServerWorld) event.getWorld(), chunk.getPos().x, chunk.getPos().z)); + if (pending == null) { event.getData().remove(TAG); event.getData().getCompound("Level").remove(TAG); return; } + CompoundNBT marker = new CompoundNBT(); + synchronized (pending) { marker.putIntArray("cells", pending.cells.stream().toArray()); } + marker.putInt("format", 1); + marker.putBoolean("relight_required", true); + event.getData().put(TAG, marker); + CompoundNBT levelData = event.getData().getCompound("Level"); + levelData.put(TAG, marker.copy()); event.getData().put("Level", levelData); + } + public static void onLoad(ChunkDataEvent.Load event) { + if (!(event.getWorld() instanceof ServerWorld) || !(event.getChunk() instanceof Chunk)) return; + Chunk chunk = (Chunk) event.getChunk(); + Key key = new Key((ServerWorld) event.getWorld(), chunk.getPos().x, chunk.getPos().z); + PENDING.remove(key); + CompoundNBT marker = event.getData().getCompound(TAG); + if (marker.getInt("format") != 1 || !marker.contains("cells", 11)) return; + Pending pending = new Pending(chunk); + for (int cell : marker.getIntArray("cells")) { + if (cell < 0 || cell >= 65536) { + org.apache.logging.log4j.LogManager.getLogger().warn( + "Invalid interrupted admin-lighting marker at {}; use its edit journal for checked recovery", chunk.getPos()); + return; + } + pending.cells.set(cell); + } + if (!pending.cells.isEmpty() || marker.getBoolean("relight_required")) { pending.recovery = true; PENDING.put(key, pending); } + } + + /** Uses the caller's shared tick budget and only the chunks already available. */ + static int tick(long deadline, int maximumVisits) { + int visits = 0; + for (Map.Entry entry : PENDING.entrySet()) { + if (System.nanoTime() >= deadline || visits >= maximumVisits) break; + Key key = entry.getKey(); Pending pending = entry.getValue(); + if (!pending.recovery || AdminWorldAccess.loaded(key.world, key.x, key.z) != pending.chunk) continue; + if (!key.world.isAreaLoaded(new BlockPos((key.x << 4) - 17, 0, (key.z << 4) - 17), + new BlockPos((key.x << 4) + 32, 255, (key.z << 4) + 32))) continue; + synchronized (pending) { + if (!pending.heightsReady) { + AdminWorldAccess.repairHeightmaps(pending.chunk); + pending.heightsReady = true; + } + for (int cell = pending.cells.nextSetBit(0); cell >= 0 && System.nanoTime() < deadline + && visits < maximumVisits; cell = pending.cells.nextSetBit(cell + 1)) { + BlockPos at = new BlockPos((key.x << 4) + (cell & 15), cell >>> 8, + (key.z << 4) + ((cell >>> 4) & 15)); + if (!AdminWorldAccess.checkLight(key.world, at)) break; + pending.cells.clear(cell); visits++; + } + pending.chunk.markDirty(); + if (pending.cells.isEmpty()) { + try { complete(key.world, pending.chunk); } + catch (java.util.concurrent.CompletionException | java.util.concurrent.CancellationException failure) { + // Keep the saved marker and journal; a failed lighting worker must not crash the server tick. + pending.recovery = false; + org.apache.logging.log4j.LogManager.getLogger().warn( + "Could not finish interrupted OreSpawn lighting at {}; its journal remains available", pending.chunk.getPos(), failure); + } + } + } + } + return visits; + } + public static void clear() { PENDING.clear(); } + + private static final class Pending { + final Chunk chunk; final BitSet cells = new BitSet(65536); + boolean recovery, heightsReady; + java.util.concurrent.CompletableFuture light; + Pending(Chunk chunk) { this.chunk = chunk; } + } + private static final class Key { + final ServerWorld world; final int x, z; + Key(ServerWorld world, int x, int z) { this.world = world; this.x = x; this.z = z; } + @Override public int hashCode() { return (System.identityHashCode(world) * 31 + x) * 31 + z; } + @Override public boolean equals(Object value) { + if (!(value instanceof Key)) return false; + Key other = (Key) value; + return world == other.world && x == other.x && z == other.z; + } + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminSource.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminSource.java new file mode 100644 index 00000000..97d11546 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminSource.java @@ -0,0 +1,28 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import net.minecraft.command.CommandSource; +import net.minecraft.entity.Entity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.world.server.ServerWorld; + +/** The small part of a command source that a running diagnostic job needs. */ +public interface AdminSource { + String getName(); + Entity getCommandSenderEntity(); + ServerWorld getEntityWorld(); + BlockPos getPosition(); + boolean canUseCommand(int level, String command); + void sendMessage(ITextComponent message); + + static AdminSource from(CommandSource source) { + return new AdminSource() { + public String getName() { return source.getName(); } + public Entity getCommandSenderEntity() { return source.getEntity(); } + public ServerWorld getEntityWorld() { return source.getWorld(); } + public BlockPos getPosition() { return new BlockPos(source.getPos()); } + public boolean canUseCommand(int level, String command) { return source.hasPermissionLevel(level); } + public void sendMessage(ITextComponent message) { source.sendFeedback(message, false); } + }; + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminWorldAccess.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminWorldAccess.java new file mode 100644 index 00000000..db8df963 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminWorldAccess.java @@ -0,0 +1,37 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.IChunk; +import net.minecraft.world.dimension.DimensionType; +import net.minecraft.world.gen.Heightmap; + +/** Loaded-only access for jobs; none of these lookups may request new terrain. */ +final class AdminWorldAccess { + private AdminWorldAccess() { } + static Chunk loaded(ServerWorld world, int x, int z) { + return world.getChunkProvider().func_225313_a(x, z); + } + static ServerWorld overworld(MinecraftServer server) { + return server.forgeGetWorldMap().get(DimensionType.OVERWORLD); + } + static int height(Chunk chunk, int x, int z) { + return chunk.getTopBlockY(Heightmap.Type.WORLD_SURFACE, x, z) + 1; + } + static void repairHeightmaps(Chunk chunk) { + Heightmap.func_222690_a(chunk, java.util.EnumSet.allOf(Heightmap.Type.class)); + net.minecraft.world.lighting.WorldLightManager light = chunk.getWorld().getChunkProvider().getLightManager(); + net.minecraft.world.chunk.ChunkSection[] sections = chunk.getSections(); + for (int y = 0; y < sections.length; y++) + light.updateSectionStatus(net.minecraft.util.math.SectionPos.from(chunk.getPos(), y), + net.minecraft.world.chunk.ChunkSection.isEmpty(sections[y])); + chunk.markDirty(); + } + + static boolean checkLight(ServerWorld world, net.minecraft.util.math.BlockPos pos) { + if (loaded(world, pos.getX() >> 4, pos.getZ() >> 4) == null) return false; + world.getChunkProvider().getLightManager().checkBlock(pos); + return true; + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/admin/DiagnosticCatalog.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/DiagnosticCatalog.java new file mode 100644 index 00000000..c74ac124 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/DiagnosticCatalog.java @@ -0,0 +1,131 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.util.HashSet; +import java.util.Set; +import net.minecraft.block.Block; +import net.minecraft.block.BlockState; +import net.minecraft.block.Blocks; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.registries.ForgeRegistries; +import zone.moddev.mc.orespawn.worldgen.NaturalFormations; + +/** Conservative identities: an ore/deposit match always wins over terrain. */ +public final class DiagnosticCatalog { + private final Set ores = new HashSet<>(); + private final Set deposits = new HashSet<>(); + private final Set rocks = new HashSet<>(); + private final Set terrain = new HashSet<>(); + private final Set backgroundFluids = new HashSet<>(); + + public DiagnosticCatalog(JsonObject profile) { + for (Block block : new Block[] {Blocks.COAL_ORE, Blocks.IRON_ORE, Blocks.GOLD_ORE, + Blocks.DIAMOND_ORE, Blocks.EMERALD_ORE, Blocks.LAPIS_ORE, Blocks.REDSTONE_ORE, + Blocks.REDSTONE_ORE, Blocks.NETHER_QUARTZ_ORE}) ores.addAll(block.getStateContainer().getValidStates()); + for (Block block : new Block[] {Blocks.STONE, Blocks.GRANITE, Blocks.POLISHED_GRANITE, Blocks.DIORITE, + Blocks.POLISHED_DIORITE, Blocks.ANDESITE, Blocks.POLISHED_ANDESITE, Blocks.DIRT, Blocks.GRASS_BLOCK, Blocks.SAND, + Blocks.GRAVEL, Blocks.SANDSTONE, Blocks.RED_SANDSTONE, Blocks.NETHERRACK, + Blocks.END_STONE, Blocks.CLAY, Blocks.TERRACOTTA, Blocks.WHITE_TERRACOTTA, + Blocks.MYCELIUM, Blocks.SNOW_BLOCK, Blocks.SNOW}) terrain.add(block); + backgroundFluids.add(Blocks.WATER); backgroundFluids.add(Blocks.WATER); + backgroundFluids.add(Blocks.LAVA); backgroundFluids.add(Blocks.LAVA); + object(profile, "ores").entrySet().forEach(entry -> { + if (!entry.getValue().isJsonObject()) return; + JsonObject rule = definition(entry.getValue().getAsJsonObject(), entry.getKey()); + addState(rule, "block", "metadata", ores); + addState(rule, "deep_output", "deep_output_metadata", ores); + if (rule.has("outputs") && rule.get("outputs").isJsonArray()) + for (JsonElement output : rule.getAsJsonArray("outputs")) + if (output.isJsonObject()) addState(output.getAsJsonObject(), "block", "metadata", ores); + }); + object(profile, "rocks").entrySet().forEach(entry -> { + if (entry.getValue().isJsonObject()) addState(definition(entry.getValue().getAsJsonObject(), entry.getKey()), "block", "metadata", rocks); + }); + object(profile, "ore_source_policies").entrySet().forEach(entry -> { + if (!entry.getValue().isJsonObject()) return; + JsonObject policy = entry.getValue().getAsJsonObject(); + if (!policy.has("candidates") || !policy.get("candidates").isJsonArray()) return; + for (JsonElement candidate : policy.getAsJsonArray("candidates")) + if (candidate.isJsonObject()) addState(candidate.getAsJsonObject(), "registry_id", "metadata", ores); + }); + NaturalFormations.materials().forEach(material -> rocks.add(material.state())); + object(profile, "fluid_deposits").entrySet().forEach(entry -> { + if (entry.getValue().isJsonObject()) { + Block block = block(entry.getValue().getAsJsonObject(), "block"); + if (block != null) deposits.add(block); + } + }); + object(profile, "dimension_materials").entrySet().forEach(entry -> { + if (entry.getValue().isJsonObject()) { + for (String key : new String[]{"default_fluid", "deep_aquifer_fluid"}) { + Block block = block(entry.getValue().getAsJsonObject(), key); + if (block != null && block.getDefaultState().getMaterial().isLiquid()) backgroundFluids.add(block); + } + } + }); + if (deposits.contains(Blocks.WATER) || deposits.contains(Blocks.WATER)) { + deposits.add(Blocks.WATER); deposits.add(Blocks.WATER); + } + if (deposits.contains(Blocks.LAVA) || deposits.contains(Blocks.LAVA)) { + deposits.add(Blocks.LAVA); deposits.add(Blocks.LAVA); + } + // Exact ore tags are the flattened equivalent of legacy Ore Dictionary registrations. + net.minecraft.tags.BlockTags.getCollection().getTagMap().forEach((id, tag) -> { + if (id.getPath().equals("ores") || id.getPath().startsWith("ores/")) + for (Block block : tag.getAllElements()) ores.addAll(block.getStateContainer().getValidStates()); + }); + } + + public String category(BlockState state) { + if (ores.contains(state)) return "ore"; + if (deposits.contains(state.getBlock())) return "fluid_deposit"; + if (state.isAir()) return "air"; + if (terrain.contains(state.getBlock()) || rocks.contains(state) || backgroundFluids.contains(state.getBlock())) return "terrain"; + return "unclassified"; + } + + public boolean removable(BlockState state, boolean tileEntity) { + return !tileEntity && state.getBlock() != Blocks.BEDROCK && "terrain".equals(category(state)); + } + + public String fingerprint() { + java.util.TreeSet identities = new java.util.TreeSet<>(); + ores.forEach(state -> identities.add("ore:" + DiagnosticStates.key(state))); + rocks.forEach(state -> identities.add("rock:" + DiagnosticStates.key(state))); + deposits.forEach(block -> identities.add("deposit:" + ForgeRegistries.BLOCKS.getKey(block))); + terrain.forEach(block -> identities.add("terrain:" + ForgeRegistries.BLOCKS.getKey(block))); + backgroundFluids.forEach(block -> identities.add("fluid:" + ForgeRegistries.BLOCKS.getKey(block))); + return DiagnosticFiles.hash(String.join("\n", identities).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + private static void addState(JsonObject object, String key, String metadata, Set target) { + Block block = block(object, key); + if (block != null) try { + int value = object.has(metadata) ? object.get(metadata).getAsInt() : 0; + JsonObject state = new JsonObject(); state.addProperty("block", ForgeRegistries.BLOCKS.getKey(block).toString()); + if (object.has("properties")) state.add("properties", object.get("properties")); + target.add(zone.moddev.mc.orespawn.util.ConfiguredBlockState.read(state)); + } catch (RuntimeException ignored) { target.add(block.getDefaultState()); } + } + + private static JsonObject definition(JsonObject source, String fallback) { + JsonObject copy = zone.moddev.mc.orespawn.util.JsonCopies.copy(source); + if (!copy.has("block")) copy.addProperty("block", fallback); + return copy; + } + + private static Block block(JsonObject object, String key) { + try { + if (!object.has(key) || object.get(key).isJsonNull()) return null; + ResourceLocation id = new ResourceLocation(object.get(key).getAsString()); + if (!ForgeRegistries.BLOCKS.containsKey(id)) return null; + Block block = ForgeRegistries.BLOCKS.getValue(id); + return block == Blocks.AIR ? null : block; + } catch (RuntimeException ignored) { return null; } + } + + private static JsonObject object(JsonObject parent, String key) { + return parent.has(key) && parent.get(key).isJsonObject() ? parent.getAsJsonObject(key) : new JsonObject(); + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/admin/DiagnosticFiles.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/DiagnosticFiles.java new file mode 100644 index 00000000..1995bb97 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/DiagnosticFiles.java @@ -0,0 +1,109 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Locale; +import java.util.TreeSet; + +/** Small, verified sidecars; never edits a Minecraft region or profile file. */ +public final class DiagnosticFiles { + private static final Gson JSON = new GsonBuilder().setPrettyPrinting().create(); + private DiagnosticFiles() { } + + public static String fingerprint(JsonElement value) { + return hash(canonical(value).getBytes(StandardCharsets.UTF_8)); + } + + private static String canonical(JsonElement value) { + if (value.isJsonObject()) { + StringBuilder result = new StringBuilder("{"); + TreeSet keys = new TreeSet<>(); + value.getAsJsonObject().entrySet().forEach(e -> keys.add(e.getKey())); + for (String key : keys) result.append(JSON.toJson(key)).append(':') + .append(canonical(value.getAsJsonObject().get(key))).append(','); + return result.append('}').toString(); + } + if (value.isJsonArray()) { + StringBuilder result = new StringBuilder("["); + for (JsonElement item : value.getAsJsonArray()) result.append(canonical(item)).append(','); + return result.append(']').toString(); + } + return value.toString(); + } + + public static String hash(byte[] data) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(data); + StringBuilder text = new StringBuilder(); + for (byte item : digest) text.append(String.format(Locale.ROOT, "%02x", item & 255)); + return text.toString(); + } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } + } + + public static Path child(Path root, String id) { + if (!id.matches("[a-zA-Z0-9_-]{1,80}")) throw new IllegalArgumentException("Invalid report or backup ID"); + Path result = root.resolve(id).normalize(); + if (!result.getParent().equals(root.normalize())) throw new IllegalArgumentException("Invalid path"); + return result; + } + + public static void write(Path target, JsonObject value) throws IOException { + writeText(target, JSON.toJson(value) + "\n"); + } + + public static void writeText(Path target, String value) throws IOException { + Files.createDirectories(target.getParent()); + Path temporary = Files.createTempFile(target.getParent(), "diagnostic-", ".tmp"); + try { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + if (bytes.length > 32 * 1024 * 1024) throw new IOException("Diagnostic file exceeds 32 MiB; reduce the survey area"); + try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) channel.write(buffer); + channel.force(true); + } + if (!java.util.Arrays.equals(bytes, Files.readAllBytes(temporary))) throw new IOException("Write verification failed"); + // A backup is never replaced. Lack of atomic moves is a hard failure. + if (Files.exists(target)) throw new IOException("File already exists: " + target.getFileName()); + Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE); + } finally { Files.deleteIfExists(temporary); } + } + + public static JsonObject read(Path path) throws IOException { + if (Files.size(path) > 32L * 1024 * 1024) throw new IOException("Diagnostic file is too large"); + try { return new JsonParser().parse(new String(Files.readAllBytes(path), StandardCharsets.UTF_8)).getAsJsonObject(); } + catch (RuntimeException e) { throw new IOException("Invalid diagnostic file", e); } + } + + public static void backup(Path target, JsonObject payload) throws IOException { + JsonObject envelope = new JsonObject(); + envelope.addProperty("format", 1); + envelope.addProperty("sha256", fingerprint(payload)); + envelope.add("payload", payload); + write(target, envelope); + if (!fingerprint(readBackup(target)).equals(fingerprint(payload))) throw new IOException("Backup verification failed"); + } + + public static JsonObject readBackup(Path target) throws IOException { + JsonObject envelope = read(target); + try { + JsonObject payload = envelope.getAsJsonObject("payload"); + if (envelope.get("format").getAsInt() != 1 + || !fingerprint(payload).equals(envelope.get("sha256").getAsString())) throw new IOException("Backup checksum mismatch"); + return payload; + } catch (RuntimeException e) { throw new IOException("Invalid backup envelope", e); } + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/admin/DiagnosticStates.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/DiagnosticStates.java new file mode 100644 index 00000000..4ae4b672 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/DiagnosticStates.java @@ -0,0 +1,74 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import java.util.Map; +import java.util.TreeMap; +import net.minecraft.block.Block; +import net.minecraft.state.IProperty; +import net.minecraft.block.BlockState; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.registries.ForgeRegistries; + +/** Registry names and properties remain meaningful when numeric IDs change. */ +public final class DiagnosticStates { + private DiagnosticStates() { } + + static java.util.function.Predicate filter(String filter) { + if (filter.isEmpty()) return state -> true; + com.mojang.brigadier.StringReader reader = new com.mojang.brigadier.StringReader(filter); + try { + net.minecraft.command.arguments.BlockStateParser parsed = + new net.minecraft.command.arguments.BlockStateParser(reader, false).parse(false); + if (reader.canRead()) throw new IllegalArgumentException("Unexpected block filter suffix"); + Block block = parsed.getState().getBlock(); + Map, Comparable> properties = new java.util.LinkedHashMap<>(parsed.getProperties()); + return state -> { + if (state.getBlock() != block) return false; + for (Map.Entry, Comparable> entry : properties.entrySet()) + if (!entry.getValue().equals(state.getValues().get(entry.getKey()))) return false; + return true; + }; + } catch (com.mojang.brigadier.exceptions.CommandSyntaxException ex) { + throw new IllegalArgumentException("Invalid block filter: " + filter, ex); + } + } + + public static String key(BlockState state) { + ResourceLocation id = ForgeRegistries.BLOCKS.getKey(state.getBlock()); + if (id == null) throw new IllegalArgumentException("Unregistered block state"); + Map properties = new TreeMap<>(); + for (Map.Entry, Comparable> entry : state.getValues().entrySet()) + properties.put(entry.getKey().getName(), propertyName(entry.getKey(), entry.getValue())); + StringBuilder key = new StringBuilder(id.toString()).append('['); + properties.forEach((name, value) -> key.append(name).append('=').append(value).append(',')); + return key.append(']').toString(); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static String propertyName(IProperty property, Comparable value) { return property.getName(value); } + + public static BlockState resolve(String key) { + int start = key.indexOf('['); + if (start < 1 || !key.endsWith("]")) throw new IllegalArgumentException("Invalid block state"); + ResourceLocation id = new ResourceLocation(key.substring(0, start)); + if (!ForgeRegistries.BLOCKS.containsKey(id)) throw new IllegalArgumentException("Missing block " + id); + Block block = ForgeRegistries.BLOCKS.getValue(id); + BlockState state = block.getDefaultState(); + for (String pair : key.substring(start + 1, key.length() - 1).split(",")) { + if (pair.isEmpty()) continue; + String[] parts = pair.split("=", -1); + if (parts.length != 2) throw new IllegalArgumentException("Invalid property"); + IProperty property = block.getStateContainer().getProperty(parts[0]); + if (property == null) throw new IllegalArgumentException("Missing property " + parts[0]); + state = withProperty(state, property, parts[1]); + } + if (!key(state).equals(key)) throw new IllegalArgumentException("Incomplete or noncanonical state"); + return state; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static BlockState withProperty(BlockState state, IProperty property, String value) { + java.util.Optional parsed = property.parseValue(value); + if (!parsed.isPresent()) throw new IllegalArgumentException("Invalid property value"); + return state.with(property, (Comparable) parsed.get()); + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/admin/EditJournal.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/EditJournal.java new file mode 100644 index 00000000..0c521c61 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/EditJournal.java @@ -0,0 +1,73 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import zone.moddev.mc.orespawn.util.JsonCopies; + +/** The immutable write-ahead plan is also sufficient to recover a partial edit. */ +public final class EditJournal { + public final JsonObject header; + public final List cells; + + public EditJournal(JsonObject header, List cells) { + this.header = JsonCopies.copy(header); + this.cells = Collections.unmodifiableList(new ArrayList<>(cells)); + validate(); + } + + private void validate() { + if (!header.has("minecraft_version") || !net.minecraftforge.versions.mcp.MCPVersion.getMCVersion().equals(header.get("minecraft_version").getAsString())) + throw new IllegalArgumentException("This journal belongs to a different Minecraft version"); + for (String key : new String[]{"world", "dimension", "chunk_x", "chunk_z", "profile", "operator", "snapshot"}) + if (!header.has(key)) throw new IllegalArgumentException("Incomplete edit journal: " + key); + if (cells.size() > 65536) throw new IllegalArgumentException("Edit exceeds one 1.13 chunk"); + Set positions = new HashSet<>(); + for (Cell cell : cells) { + if (cell.index < 0 || cell.index >= 65536 || !positions.add(cell.index)) + throw new IllegalArgumentException("Invalid or repeated journal position"); + if (cell.before.equals(cell.after)) throw new IllegalArgumentException("Journal contains an unchanged cell"); + } + } + + public JsonObject json() { + JsonObject result = JsonCopies.copy(header); + JsonArray changes = new JsonArray(); + for (Cell cell : cells) { + JsonObject change = new JsonObject(); + change.addProperty("index", cell.index); + change.addProperty("before", cell.before); + change.addProperty("after", cell.after); + changes.add(change); + } + result.add("changes", changes); + return result; + } + + public static EditJournal read(JsonObject object) { + JsonObject header = JsonCopies.copy(object); + header.remove("changes"); + List cells = new ArrayList<>(); + for (JsonElement value : object.getAsJsonArray("changes")) { + JsonObject cell = value.getAsJsonObject(); + cells.add(new Cell(cell.get("index").getAsInt(), cell.get("before").getAsString(), cell.get("after").getAsString())); + } + return new EditJournal(header, cells); + } + + public static boolean canUndo(String current, Cell cell) { + return current.equals(cell.after) || current.equals(cell.before); + } + + public static final class Cell { + public final int index; + public final String before; + public final String after; + public Cell(int index, String before, String after) { this.index = index; this.before = before; this.after = after; } + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/admin/PreviewLease.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/PreviewLease.java new file mode 100644 index 00000000..d0369ef0 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/PreviewLease.java @@ -0,0 +1,14 @@ +package zone.moddev.mc.orespawn.commands.admin; + +/** A confirmation is short-lived and cannot be borrowed by another operator. */ +final class PreviewLease { + static final long LIFETIME = 120000000000L; + private final String owner; + private final String profile; + private final long issued; + PreviewLease(String owner, String profile, long issued) { this.owner = owner; this.profile = profile; this.issued = issued; } + boolean expired(long now) { return now - issued >= LIFETIME || now - issued < 0; } + boolean accepts(String operator, String currentProfile, long now) { + return owner.equals(operator) && profile.equals(currentProfile) && !expired(now); + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/commands/admin/SurveyCounts.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/SurveyCounts.java new file mode 100644 index 00000000..024c4111 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/SurveyCounts.java @@ -0,0 +1,75 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import com.google.gson.JsonObject; +import java.util.Map; +import java.util.TreeMap; + +/** Counts observed cells, not attempts or inferred vein sizes. */ +public final class SurveyCounts { + private final Map blocks = new TreeMap<>(); + private final Map heights = new TreeMap<>(); + private final Map biomes = new TreeMap<>(); + private final Map chunks = new TreeMap<>(); + private final Map categories = new TreeMap<>(); + private long volume; + private long nonAir; + private final int rowLimit; + public SurveyCounts() { this(500000); } + SurveyCounts(int rowLimit) { this.rowLimit = rowLimit; } + + public void add(String state, String category, int y, String biome, int chunkX, int chunkZ) { + String heightKey = y + "\t" + state, biomeKey = biome + "\t" + state, chunkKey = chunkX + "," + chunkZ + "\t" + state; + int rows = blocks.size() + heights.size() + biomes.size() + chunks.size(); + int additions = (blocks.containsKey(state) ? 0 : 1) + (heights.containsKey(heightKey) ? 0 : 1) + + (biomes.containsKey(biomeKey) ? 0 : 1) + (chunks.containsKey(chunkKey) ? 0 : 1); + if (rows + additions > rowLimit) throw new IllegalStateException("Survey report is too large; reduce the radius or height range"); + volume++; + if (!"air".equals(category)) nonAir++; + categories.put(state, category); + increment(blocks, state); + increment(heights, heightKey); + increment(biomes, biomeKey); + increment(chunks, chunkKey); + } + + private static void increment(Map values, String key) { values.merge(key, 1L, Long::sum); } + public long volume() { return volume; } + + public JsonObject json() { + JsonObject result = new JsonObject(); + result.addProperty("sampled_volume", volume); + result.addProperty("non_air_volume", nonAir); + result.add("blocks", json(blocks)); + result.add("by_y", json(heights)); + result.add("by_biome", json(biomes)); + result.add("by_chunk", json(chunks)); + JsonObject classified = new JsonObject(); + categories.forEach(classified::addProperty); + result.add("categories", classified); + return result; + } + + private static JsonObject json(Map values) { + JsonObject result = new JsonObject(); + values.forEach(result::addProperty); + return result; + } + + public Map csv() { + Map files = new TreeMap<>(); + files.put("blocks.csv", csv("state", blocks)); + files.put("height.csv", csv("y,state", heights)); + files.put("biomes.csv", csv("biome,state", biomes)); + files.put("chunks.csv", csv("chunk,state", chunks)); + return files; + } + + private static String csv(String header, Map rows) { + StringBuilder text = new StringBuilder(header).append(",count\n"); + rows.forEach((key, count) -> { + for (String field : key.split("\t", -1)) text.append('"').append(field.replace("\"", "\"\"")).append("\","); + text.append(count).append('\n'); + }); + return text.toString(); + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/documentation/DocumentationExporter.java b/src/main/java/zone/moddev/mc/orespawn/documentation/DocumentationExporter.java index 9ad46e67..5ec60024 100644 --- a/src/main/java/zone/moddev/mc/orespawn/documentation/DocumentationExporter.java +++ b/src/main/java/zone/moddev/mc/orespawn/documentation/DocumentationExporter.java @@ -27,6 +27,8 @@ public final class DocumentationExporter { "TEMPLATES.md", "DIMENSIONS.md", "BIOMES.md", + "ROCK_FORMATIONS.md", + "ADMIN_TOOLS.md", "MIGRATION.md", "TROUBLESHOOTING.md", "VERSIONS.md", diff --git a/src/main/java/zone/moddev/mc/orespawn/integration/LegacyOreReplacements.java b/src/main/java/zone/moddev/mc/orespawn/integration/LegacyOreReplacements.java new file mode 100644 index 00000000..e8aa29c5 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/integration/LegacyOreReplacements.java @@ -0,0 +1,228 @@ +package zone.moddev.mc.orespawn.integration; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import zone.moddev.mc.orespawn.util.JsonCopies; + +/** Keeps a saved imported rule in charge when its provider starts supplying a native default. */ +final class LegacyOreReplacements { + private static final Logger LOGGER = LogManager.getLogger(); + private static final String REPLACEMENTS = "legacy_ore_replacements"; + private static final String REVIEW = "legacy_ore_review"; + + static final class Result { + final Set suppressed = new HashSet<>(); + boolean changed; + } + + private LegacyOreReplacements() {} + + static Result reconcile(JsonObject profile, String provider, JsonObject ores, JsonObject defaults, + JsonObject active, JsonObject manifest, Set known, boolean allowRemoval) { + Result result = new Result(); + JsonObject previous = object(manifest, REPLACEMENTS); + JsonObject replacements = JsonCopies.copy(previous); + JsonObject review = new JsonObject(); + Map> imports = new HashMap<>(); + for (Map.Entry entry : ores.entrySet()) { + String id = entry.getKey(); + JsonObject ore = object(ores, id); + String output = output(ore); + if (output != null && isLegacyImport(provider, id, ore, known.contains(id))) { + imports.computeIfAbsent(output, ignored -> new ArrayList<>()).add(id); + } + } + if (imports.isEmpty() && previous.entrySet().isEmpty() && !manifest.has(REVIEW)) return result; + + Map countByOutput = new HashMap<>(); + for (Map.Entry entry : defaults.entrySet()) { + JsonObject ore = object(defaults, entry.getKey()); + if (!isLegacyImport(provider, entry.getKey(), ore, true)) { + String output = output(ore); + if (output != null) countByOutput.merge(output, 1, Integer::sum); + } + } + for (Map.Entry entry : defaults.entrySet()) { + String id = entry.getKey(); + JsonObject nativeOre = object(defaults, id); + if (isLegacyImport(provider, id, nativeOre, true)) continue; + String remembered = text(previous, id); + String output = output(nativeOre); + List matches = imports.getOrDefault(output, Collections.emptyList()); + if (remembered.isEmpty() && matches.isEmpty()) continue; + + if (remembered.isEmpty() && (matches.size() != 1 || countByOutput.getOrDefault(output, 0) != 1)) { + flag(review, manifest, provider, id, "ambiguous_import"); + result.suppressed.add(id); + continue; + } + String legacyId = remembered.isEmpty() ? matches.get(0) : remembered; + if (id.equals(legacyId)) continue; + boolean removedImport = !remembered.isEmpty() && known.contains(legacyId) && !ores.has(legacyId); + if (!removedImport && !isLegacyImport(provider, legacyId, object(ores, legacyId), + known.contains(legacyId))) continue; + if (active.has(id) && !entry.getValue().equals(active.get(id))) { + flag(review, manifest, provider, id, "provider_override_differs"); + continue; + } + if (ores.has(id)) { + if (!allowRemoval) continue; + // Never undo an edited rule or a selection that depends on it. + JsonObject expected = JsonCopies.copy(nativeOre); + expected.addProperty("source_provider", provider); + JsonObject saved = JsonCopies.copy(object(ores, id)); + saved.remove("orphaned_provider"); + // Ore Sources can add empty scope objects while reading a rule. + removeEmptyScopes(expected); + removeEmptyScopes(saved); + List disposablePolicies = stockPolicyReferences(profile, id, legacyId); + if (!known.contains(id) || !ores.has(legacyId) || !ores.get(id).isJsonObject() + || !expected.equals(saved) || disposablePolicies == null) { + flag(review, manifest, provider, id, "saved_rule_or_policy_differs"); + continue; + } + ores.remove(id); + JsonObject policies = object(profile, "ore_source_policies"); + for (String key : disposablePolicies) policies.remove(key); + result.changed = true; + LOGGER.info("Kept imported ore rule {} and removed untouched duplicate {}", legacyId, id); + } + replacements.addProperty(id, legacyId); + result.suppressed.add(id); + result.changed |= known.add(legacyId); + // The provider still supplies a counterpart for the imported rule. + JsonObject imported = object(ores, legacyId); + if (imported.has("orphaned_provider")) { + imported.remove("orphaned_provider"); + result.changed = true; + } + } + result.changed |= update(manifest, REPLACEMENTS, replacements); + result.changed |= update(manifest, REVIEW, review); + return result; + } + + private static void removeEmptyScopes(JsonObject rule) { + for (String key : new String[] { "dimensions", "dimension_selectors" }) { + JsonElement scope = rule.get(key); + if (scope != null && scope.isJsonObject() && scope.getAsJsonObject().entrySet().isEmpty()) { + rule.remove(key); + } + } + } + + static boolean retains(JsonObject manifest, String id, Set currentDefaults) { + JsonObject replacements = object(manifest, REPLACEMENTS); + for (Map.Entry entry : replacements.entrySet()) { + if (currentDefaults.contains(entry.getKey()) && id.equals(text(replacements, entry.getKey()))) { + return true; + } + } + return false; + } + + private static boolean isLegacyImport(String provider, String id, JsonObject ore, boolean known) { + String block = text(ore, "block"); + if (!block.startsWith(provider + ":") || !"false".equals(text(ore, "native_generation"))) return false; + + // The importer puts the source file's owner in the fallback ID. + if (id.startsWith("orespawn:legacy/" + provider + "/") + && "legacy".equals(text(ore, "source_mod")) + && "true".equals(text(ore, "suppress_vanilla"))) return true; + + // A converted OS1 profile can have come from an older Minecraft version. + if (!known || !provider.equals(text(ore, "source_mod"))) return false; + if ("os1".equals(text(ore, "legacy_import"))) return true; + String prefix = provider + ":legacy/" + block.replace(':', '_'); + return provider.equals(text(ore, "source_provider")) && id.startsWith(prefix) + && id.substring(prefix.length()).matches("_[0-9]+"); + } + + private static String output(JsonObject ore) { + String block = text(ore, "block"); + String variant = metadata(ore); + if (block.isEmpty() || variant == null) return null; + if (ore.has("deep_output") && !block.equals(text(ore, "deep_output"))) return null; + if (ore.has("outputs")) { + JsonElement value = ore.get("outputs"); + if (!value.isJsonArray()) return null; + JsonArray outputs = value.getAsJsonArray(); + if (outputs.size() != 1 || !outputs.get(0).isJsonObject()) return null; + JsonObject only = outputs.get(0).getAsJsonObject(); + if (!block.equals(text(only, "block")) || !variant.equals(metadata(only))) return null; + } + return block + "#" + variant; + } + + private static String metadata(JsonObject ore) { + if (!ore.has("metadata")) return "0"; + String meta = text(ore, "metadata"); + // A nonzero pre-flattening metadata value is not proof of a matching 1.13 block. + return "0".equals(meta) ? meta : null; + } + + /** Only remove the fallback policy generated for a lone native rule. */ + private static List stockPolicyReferences(JsonObject profile, String nativeId, String legacyId) { + List disposable = new ArrayList<>(); + JsonObject imported = object(object(profile, "ores"), legacyId); + for (Map.Entry entry : object(profile, "ore_source_policies").entrySet()) { + if (!entry.getValue().isJsonObject()) continue; + JsonObject policy = entry.getValue().getAsJsonObject(); + JsonObject outputs = object(policy, "outputs"); + JsonObject placements = object(policy, "placement_sources"); + if (!outputs.has(nativeId) && !placements.entrySet().stream() + .anyMatch(place -> nativeId.equals(text(placements, place.getKey())))) continue; + String domain = text(policy, "domain"); + if (!entry.getKey().equals(text(policy, "material") + "|" + domain) || policy.has("dormant") + || object(imported, "dimensions").has(domain) || object(imported, "dimension_selectors").has(domain) + || !"keep_separate".equals(text(policy, "mode")) || !"custom".equals(text(policy, "output_mode")) + || !"separate".equals(text(policy, "status")) || !"false".equals(text(policy, "review_required")) + || outputs.entrySet().size() != 1 || !unitWeight(outputs.get(nativeId)) + || placements.entrySet().size() != 1 + || !nativeId.equals(text(placements, "orespawn:standard"))) return null; + disposable.add(entry.getKey()); + } + return disposable; + } + + private static boolean unitWeight(JsonElement value) { + return value != null && value.isJsonPrimitive() && value.getAsJsonPrimitive().isNumber() + && value.getAsDouble() == 1.0D; + } + + private static void flag(JsonObject review, JsonObject manifest, String provider, String id, String reason) { + review.addProperty(id, reason); + if (!reason.equals(text(object(manifest, REVIEW), id))) { + LOGGER.warn("Review legacy ore overlap for provider {} and rule {} ({}); saved settings were kept", + provider, id, reason); + } + } + + private static boolean update(JsonObject manifest, String key, JsonObject value) { + if (value.equals(object(manifest, key))) return false; + if (value.entrySet().isEmpty()) manifest.remove(key); + else manifest.add(key, value); + return true; + } + + private static JsonObject object(JsonObject root, String key) { + JsonElement value = root.get(key); + return value != null && value.isJsonObject() ? value.getAsJsonObject() : new JsonObject(); + } + + private static String text(JsonObject root, String key) { + JsonElement value = root.get(key); + return value != null && value.isJsonPrimitive() ? value.getAsString() : ""; + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/integration/RetainedProviderOreDefaults.java b/src/main/java/zone/moddev/mc/orespawn/integration/RetainedProviderOreDefaults.java new file mode 100644 index 00000000..c69bb006 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/integration/RetainedProviderOreDefaults.java @@ -0,0 +1,181 @@ +package zone.moddev.mc.orespawn.integration; + +import java.util.HashSet; +import java.util.Arrays; +import java.util.Collections; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import net.minecraft.util.ResourceLocation; + +/** Conservative matching at provider merge time, never in chunk generation. */ +final class RetainedProviderOreDefaults { + + private static final ResourceLocation STANDARD = parseIdentifier("orespawn:standard"); + + private static final Set BASE_METALS_LEGACY_MATERIALS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "coldiron", "adamantine", "starsteel", "tin", "lead", "zinc", + "silver", "mercury", "nickel", "platinum"))); + + private static final class Placement { + final String kind; + final String dimension; + final String channel; + + Placement(String kind, String dimension, String channel) { + this.kind = kind; + this.dimension = dimension; + this.channel = channel; + } + + @Override + public boolean equals(Object value) { + if (!(value instanceof Placement)) return false; + Placement other = (Placement) value; + return kind.equals(other.kind) && dimension.equals(other.dimension) && channel.equals(other.channel); + } + + @Override + public int hashCode() { + return Objects.hash(kind, dimension, channel); + } + } + + private RetainedProviderOreDefaults() {} + + static String predecessor(String owner, String currentId, JsonObject current, + JsonObject defaults, JsonObject saved, Set known) { + String output = singletonOutput(currentId, current); + Set scope = placements(current); + if (output == null || scope == null || scope.isEmpty()) return null; + String historical = historicalPredecessor(owner, currentId, output); + if (historical != null && known.contains(historical) && !saved.has(historical)) return historical; + + int replacements = 0; + for (Map.Entry entry : defaults.entrySet()) { + if (equivalentOutputAndScope(entry.getKey(), entry.getValue(), output, scope)) replacements++; + } + if (replacements != 1) return null; + + String retained = null; + for (Map.Entry entry : saved.entrySet()) { + if (!equivalentOutputAndScope(entry.getKey(), entry.getValue(), output, scope)) continue; + if (retained != null) return null; + retained = entry.getKey(); + } + return retained != null && declaredPredecessor(owner, currentId, output, retained, saved.getAsJsonObject(retained)) + ? retained : null; + } + + private static boolean declaredPredecessor(String owner, String currentId, String output, String savedId, JsonObject saved) { + String importedPrefix = "orespawn:legacy/" + owner + "/"; + boolean imported = savedId.startsWith(importedPrefix) && savedId.length() > importedPrefix.length(); + if (saved.has("source_provider")) { + if (!owner.equals(text(saved.get("source_provider")))) return false; + } else if (saved.has("source_mod")) { + String fallbackOwner = text(saved.get("source_mod")); + if (!owner.equals(fallbackOwner) && !(imported && "legacy".equals(fallbackOwner))) return false; + } + if (imported) return true; + return savedId.equals(historicalPredecessor(owner, currentId, output)); + } + + private static String historicalPredecessor(String owner, String currentId, String output) { + // Base Metals' maintained 1.10/1.12 providers declared these IDs themselves. + // A generic provider's "legacy/" prefix is not evidence of a replacement. + if (!owner.equals("basemetals")) return null; + for (String material : BASE_METALS_LEGACY_MATERIALS) { + if (currentId.equals("basemetals:ore/" + material) + && output.equals("basemetals:" + material + "_ore")) return "basemetals:legacy/" + material + "_ore"; + } + return null; + } + + private static boolean equivalentOutputAndScope(String id, JsonElement rule, String output, Set scope) { + return rule.isJsonObject() && output.equals(singletonOutput(id, rule.getAsJsonObject())) + && scope.equals(placements(rule.getAsJsonObject())); + } + + private static String singletonOutput(String id, JsonObject rule) { + String output = rule.has("block") ? text(rule.get("block")) : id; + ResourceLocation parsed = output == null ? null : parseIdentifier(output); + if (parsed == null || !defaultMetadata(rule)) return null; + output = parsed.toString(); + if (rule.has("deep_output") && !output.equals(text(rule.get("deep_output")))) return null; + if (rule.has("outputs")) { + JsonElement values = rule.get("outputs"); + if (!values.isJsonArray() || values.getAsJsonArray().size() != 1 + || !values.getAsJsonArray().get(0).isJsonObject()) return null; + JsonObject only = values.getAsJsonArray().get(0).getAsJsonObject(); + if (!output.equals(text(only.get("block"))) || !defaultMetadata(only)) return null; + } + return output; + } + + private static boolean defaultMetadata(JsonObject rule) { + JsonElement metadata = rule.get("metadata"); + return metadata == null || metadata.isJsonPrimitive() && metadata.getAsJsonPrimitive().isNumber() + && metadata.getAsBigDecimal().signum() == 0; + } + + private static Set placements(JsonObject rule) { + Set result = new HashSet<>(); + for (String kind : Arrays.asList("dimensions", "dimension_selectors")) { + JsonElement table = rule.get(kind); + if (table == null) continue; + if (!table.isJsonObject()) return null; + for (Map.Entry entry : table.getAsJsonObject().entrySet()) { + if (parseIdentifier(entry.getKey()) == null || !entry.getValue().isJsonObject()) return null; + // Disabled and zero-rate placements are saved choices too. + result.add(new Placement(kind, entry.getKey(), channel(entry.getValue().getAsJsonObject()))); + } + } + return result; + } + + private static String channel(JsonObject placement) { + ResourceLocation explicit = identifier(placement.get("placement_channel")); + if (explicit != null) return explicit.toString(); + JsonElement pattern = placement.get("pattern"); + ResourceLocation type = pattern != null && pattern.isJsonObject() + ? identifier(pattern.getAsJsonObject().get("type")) : null; + String legacy = text(pattern); + if (type == null && legacy != null && legacy.indexOf(':') >= 0) type = parseIdentifier(legacy); + return type == null ? "orespawn:standard" : patternChannel(type).toString(); + } + + private static ResourceLocation patternChannel(ResourceLocation pattern) { + if ("orespawn".equals(pattern.getNamespace())) { + switch (pattern.getPath()) { + case "default": + case "vein": + case "normal_cloud": + case "precision": + case "clusters": + case "underfluids": + return STANDARD; + default: + break; + } + } + return pattern; + } + + private static ResourceLocation parseIdentifier(String value) { + try { return value == null || value.trim().isEmpty() ? null : new ResourceLocation(value); } + catch (RuntimeException ignored) { return null; } + } + + private static ResourceLocation identifier(JsonElement value) { + String name = text(value); + return name == null ? null : parseIdentifier(name); + } + + private static String text(JsonElement value) { + return value != null && value.isJsonPrimitive() && value.getAsJsonPrimitive().isString() + ? value.getAsString() : null; + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/integration/WorldgenIntegrationManager.java b/src/main/java/zone/moddev/mc/orespawn/integration/WorldgenIntegrationManager.java index 938e25bd..879ad807 100644 --- a/src/main/java/zone/moddev/mc/orespawn/integration/WorldgenIntegrationManager.java +++ b/src/main/java/zone/moddev/mc/orespawn/integration/WorldgenIntegrationManager.java @@ -59,7 +59,7 @@ public final class WorldgenIntegrationManager { static { Collections.addAll(MERGED_SECTIONS, "rocks", "ores", "geomes", "biome_rules", "terrain_dimensions", "fluid_deposits", "biome_palettes", - "dimension_materials"); + "dimension_materials", "rock_formations"); } private static final Map API_PROVIDERS = new LinkedHashMap<>(); @@ -220,13 +220,24 @@ private static void copyOwnedDefaults(ProviderDefinition provider, String sectio /** Merge new provider-owned defaults without overwriting pack or world values. */ public static synchronized boolean mergeProviderDefinitions(JsonObject target) { + return mergeProviderDefinitions(target, false); + } + + /** Only saved-world callers may remove a duplicate, after arranging a profile backup. */ + public static synchronized boolean mergeSavedProviderDefinitions(JsonObject target) { + return mergeProviderDefinitions(target, true); + } + + private static boolean mergeProviderDefinitions(JsonObject target, boolean savedWorld) { JsonObject manifests = object(target, "providers"); JsonObject legacyOreManifests = object(target, "ore_providers"); boolean changed = false; for (ProviderDefinition provider : ACTIVE_PROVIDERS.values()) { JsonObject manifest = object(manifests, provider.modId); - if (!bool(manifest, "profile_defaults_applied", false) + boolean mergeNewEntries = !savedWorld + || bool(provider.root, "merge_new_entries_into_existing_worlds", true); + if (mergeNewEntries && !bool(manifest, "profile_defaults_applied", false) && provider.root.has("profile_defaults") && provider.root.get("profile_defaults").isJsonObject()) { mergeOverlay(target, provider.root.getAsJsonObject("profile_defaults")); @@ -237,24 +248,40 @@ public static synchronized boolean mergeProviderDefinitions(JsonObject target) { changed = true; } for (String sectionName : MERGED_SECTIONS) { + // New substrate definitions must not silently change an existing world's geology. + if (savedWorld && "rock_formations".equals(sectionName)) continue; String targetName = "biome_rules".equals(sectionName) ? "biomes" : sectionName; JsonObject targetSection = object(target, targetName); JsonObject providerSection = provider.section(sectionName); String knownKey = "known_" + sectionName; Set known = stringSet(manifest.get(knownKey)); Set current = JsonCopies.keys(providerSection); + LegacyOreReplacements.Result replacements = "ores".equals(sectionName) + ? LegacyOreReplacements.reconcile(target, provider.modId, targetSection, + nativeOreDefaults(provider.modId, providerSection), providerSection, manifest, known, savedWorld) + : new LegacyOreReplacements.Result(); + changed |= replacements.changed; for (Entry entry : providerSection.entrySet()) { String id = entry.getKey(); - if (!targetSection.has(id) && !known.contains(id)) { + if (replacements.suppressed.contains(id)) continue; + if (mergeNewEntries && !targetSection.has(id) && !known.contains(id)) { JsonObject value = JsonCopies.copy(entry.getValue().getAsJsonObject()); + if ("ores".equals(sectionName)) { + String retained = RetainedProviderOreDefaults.predecessor( + provider.modId, id, value, providerSection, targetSection, known); + if (retained != null) { + value.addProperty("enabled", false); + LOGGER.info("Preserved saved ore choice '{}'; added provider alternative '{}' disabled", retained, id); + } + } if (!"biome_rules".equals(sectionName)) { value.addProperty("source_provider", provider.modId); } targetSection.add(id, value); changed = true; } - known.add(id); + if (targetSection.has(id)) known.add(id); if (targetSection.has(id) && targetSection.get(id).isJsonObject()) { targetSection.getAsJsonObject(id).remove("orphaned_provider"); } @@ -262,7 +289,9 @@ public static synchronized boolean mergeProviderDefinitions(JsonObject target) { for (String knownId : known) { if (!current.contains(knownId) && targetSection.has(knownId) - && targetSection.get(knownId).isJsonObject()) { + && !("ores".equals(sectionName) && LegacyOreReplacements.retains(manifest, knownId, current)) + && targetSection.get(knownId).isJsonObject() + && !bool(targetSection.getAsJsonObject(knownId), "orphaned_provider", false)) { targetSection.getAsJsonObject(knownId).addProperty("orphaned_provider", true); changed = true; } @@ -286,6 +315,7 @@ public static synchronized boolean mergeProviderDefinitions(JsonObject target) { } JsonObject manifest = manifestEntry.getValue().getAsJsonObject(); for (String sectionName : MERGED_SECTIONS) { + if ("rock_formations".equals(sectionName) && !target.has(sectionName)) continue; String targetName = "biome_rules".equals(sectionName) ? "biomes" : sectionName; JsonObject targetSection = object(target, targetName); for (String knownId : stringSet(manifest.get("known_" + sectionName))) { @@ -305,6 +335,19 @@ public static synchronized boolean mergeProviderDefinitions(JsonObject target) { return changed; } + private static JsonObject nativeOreDefaults(String providerId, JsonObject activeOres) { + if (!FILE_PROVIDERS.containsKey(providerId)) return activeOres; + JsonObject shipped = installedProviderRoot(providerId); + JsonElement ores = shipped == null ? null : shipped.get("ores"); + return ores != null && ores.isJsonObject() ? ores.getAsJsonObject() : new JsonObject(); + } + + private static JsonObject installedProviderRoot(String providerId) { + JsonObject root = RESOURCE_PROVIDERS.get(providerId); + WorldgenProvider apiProvider = API_PROVIDERS.get(providerId); + return root == null && apiProvider != null ? apiProvider.toJson() : root; + } + public static synchronized List templates() { return Collections.unmodifiableList(new ArrayList<>(TEMPLATES.values())); } @@ -332,12 +375,34 @@ public static synchronized JsonObject applyTemplate(JsonObject base, ResourceLoc throw new IllegalArgumentException("Unknown or unavailable OreSpawn template: " + templateId); } JsonObject result = JsonCopies.copy(base); - mergeOverlay(result, template.profile); + JsonObject overlay = JsonCopies.copy(template.profile); + if (template.preserveFormationOverrides && overlay.has("rock_formations")) { + JsonObject tuning = overlay.getAsJsonObject("rock_formations"); + overlay.remove("rock_formations"); + applyStockFormationTuning(result, tuning); + } + mergeOverlay(result, overlay); applyLegacyTemplateOil(result, template.profile); result.addProperty("selected_template", templateId.toString()); return result; } + static void applyStockFormationTuning(JsonObject target, JsonObject tuning) { + JsonObject current = optionalObject(target, "rock_formations"); + for (Entry edit : tuning.entrySet()) { + String owner = new ResourceLocation(edit.getKey()).getNamespace(); + if (FILE_PROVIDERS.containsKey(owner) || !current.has(edit.getKey())) continue; + JsonObject packaged = RESOURCE_PROVIDERS.get(owner); + if (packaged == null) continue; + JsonObject stock = optionalObject(packaged, "rock_formations"); + if (!stock.has(edit.getKey()) || !current.get(edit.getKey()).isJsonObject()) continue; + JsonObject authored = JsonCopies.copy(current.getAsJsonObject(edit.getKey())); + authored.remove("source_provider"); + if (!authored.equals(stock.get(edit.getKey()))) continue; + mergeOverlay(current.getAsJsonObject(edit.getKey()), edit.getValue().getAsJsonObject()); + } + } + /** Internal migration lookup. Null means the owner is not an active installed provider. */ public static synchronized List findProviderOreRulesByOutput(String providerModId, String outputBlock) { ProviderDefinition provider = ACTIVE_PROVIDERS.get(providerModId); @@ -467,13 +532,7 @@ private static void rebuildActiveProviders() { continue; } JsonObject root = FILE_PROVIDERS.get(providerId); - if (root == null) { - root = RESOURCE_PROVIDERS.get(providerId); - } - if (root == null) { - WorldgenProvider apiProvider = API_PROVIDERS.get(providerId); - root = apiProvider == null ? null : apiProvider.toJson(); - } + if (root == null) root = installedProviderRoot(providerId); if (root == null || !ModList.get().isLoaded(providerId)) { continue; } @@ -493,7 +552,7 @@ private static void rebuildActiveProviders() { static void validateProvider(String providerId, JsonObject root) { int schema = integer(root, "schema_version", -1); - if (schema != 1 && schema != 2 && schema != 3 && schema != 4 && schema != 5) { + if (schema < 1 || schema > 6) { throw new JsonSyntaxException("unsupported schema_version"); } if (!providerId.equals(string(root, "provider_modid", ""))) { @@ -517,6 +576,9 @@ static void validateProvider(String providerId, JsonObject root) { if (schema < 3 && root.has("fluid_deposits")) { throw new JsonSyntaxException("fluid_deposits requires provider schema 3"); } + if (schema < 6 && root.has("rock_formations")) { + throw new JsonSyntaxException("rock_formations requires provider schema 6"); + } if (schema < 4 && (root.has("biome_palettes") || root.has("dimension_materials"))) { throw new JsonSyntaxException("biome palettes and dimension materials require provider schema 4"); } @@ -529,7 +591,7 @@ static void validateProvider(String providerId, JsonObject root) { if (!entry.getValue().isJsonObject()) { throw new JsonSyntaxException(section + " entry is not an object: " + entry.getKey()); } - if (!"biome_rules".equals(section)) { + if (!"biome_rules".equals(section) && !"terrain_dimensions".equals(section)) { validateOwnedId(providerId, entry.getKey(), section); } else { new ResourceLocation(entry.getKey()); @@ -550,6 +612,18 @@ static void validateProvider(String providerId, JsonObject root) { validateBiomePalette(entry.getKey(), entry.getValue().getAsJsonObject()); } else if ("dimension_materials".equals(section)) { validateDimensionMaterials(entry.getKey(), entry.getValue().getAsJsonObject()); + } else if ("rock_formations".equals(section)) { + JsonObject formation = entry.getValue().getAsJsonObject(); + new ResourceLocation(string(formation, "type", "")); + if (integer(formation, "algorithm_revision", 0) < 1) + throw new JsonSyntaxException("Formation requires algorithm_revision: " + entry.getKey()); + for (Entry material : requiredObject(formation, "materials").entrySet()) { + JsonObject value = material.getValue().getAsJsonObject(); + Block output = zone.moddev.mc.orespawn.util.ConfiguredBlockState.read(value).getBlock(); + if (output == Blocks.AIR || output == Blocks.BEDROCK) + throw new JsonSyntaxException("Invalid formation output: " + material.getKey()); + if (value.has("family")) RockFamily.fromConfigName(value.get("family").getAsString()); + } } } } @@ -631,12 +705,14 @@ private static void validateOreRule(String idText, Entry en int maxY = integer(rule, "max_y", Integer.MIN_VALUE); double frequency = decimal(rule, "frequency", -1.0D); double discardChance = decimal(rule, "discard_chance_on_air_exposure", 0.0D); + double backgroundScale = decimal(rule, "background_generation_scale", 1.0D); int[] quantities = validateQuantityRange(rule); int minQuantity = quantities[0]; int maxQuantity = quantities[1]; if (minY < -2048 || maxY > 2048 || minY > maxY || frequency < 0.0D || frequency > 64.0D || !Double.isFinite(discardChance) || discardChance < 0.0D || discardChance > 1.0D + || !Double.isFinite(backgroundScale) || backgroundScale < 0.0D || backgroundScale > 1.0D || minQuantity < 1 || minQuantity > maxQuantity || maxQuantity > 64) { throw new JsonSyntaxException("invalid ore placement for " + idText + " in " + entry.getKey()); } @@ -958,7 +1034,8 @@ private static void readTemplates(ProviderDefinition provider) { + id.getPath() + ".description"), JsonCopies.copy(json.getAsJsonObject("profile")), available, bool(json, "auto_select", false), - integer(json, "auto_select_priority", 0))); + integer(json, "auto_select_priority", 0), + bool(json, "preserve_formation_overrides", false))); } } @@ -1151,9 +1228,11 @@ public static final class TemplateDefinition { private final boolean available; private final boolean autoSelect; private final int autoSelectPriority; + private final boolean preserveFormationOverrides; TemplateDefinition(ResourceLocation id, String nameKey, String descriptionKey, - JsonObject profile, boolean available, boolean autoSelect, int autoSelectPriority) { + JsonObject profile, boolean available, boolean autoSelect, int autoSelectPriority, + boolean preserveFormationOverrides) { this.id = id; this.nameKey = nameKey; this.descriptionKey = descriptionKey; @@ -1161,6 +1240,7 @@ public static final class TemplateDefinition { this.available = available; this.autoSelect = autoSelect; this.autoSelectPriority = autoSelectPriority; + this.preserveFormationOverrides = preserveFormationOverrides; } public ResourceLocation id() { return id; } diff --git a/src/main/java/zone/moddev/mc/orespawn/util/ConfiguredBlockState.java b/src/main/java/zone/moddev/mc/orespawn/util/ConfiguredBlockState.java new file mode 100644 index 00000000..8b1ecdea --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/util/ConfiguredBlockState.java @@ -0,0 +1,38 @@ +package zone.moddev.mc.orespawn.util; + +import com.google.gson.JsonObject; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import net.minecraft.block.BlockState; +import net.minecraft.command.arguments.BlockStateParser; + +/** Reads exact flattened block states using Minecraft's own property validation. */ +public final class ConfiguredBlockState { + private ConfiguredBlockState() { } + + public static BlockState read(JsonObject json) { + if (json.has("metadata") && json.get("metadata").getAsInt() != 0) { + throw new IllegalArgumentException("Use flattened block IDs and properties, not legacy metadata"); + } + StringBuilder text = new StringBuilder(json.get("block").getAsString()); + if (json.has("properties") && json.getAsJsonObject("properties").size() != 0) { + text.append('['); + boolean first = true; + for (java.util.Map.Entry entry + : json.getAsJsonObject("properties").entrySet()) { + if (!first) text.append(','); + text.append(entry.getKey()).append('=').append(entry.getValue().getAsString()); + first = false; + } + text.append(']'); + } + StringReader reader = new StringReader(text.toString()); + try { + BlockState state = new BlockStateParser(reader, false).parse(false).getState(); + if (reader.canRead()) throw new IllegalArgumentException("Unexpected block-state suffix: " + text); + return state; + } catch (CommandSyntaxException ex) { + throw new IllegalArgumentException("Invalid block state: " + text, ex); + } + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/AquiferMaterialSubstitution.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/AquiferMaterialSubstitution.java new file mode 100644 index 00000000..727c0824 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/AquiferMaterialSubstitution.java @@ -0,0 +1,291 @@ +package zone.moddev.mc.orespawn.worldgen; + +import java.util.BitSet; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import net.minecraft.block.BlockState; +import net.minecraft.world.World; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.ChunkPrimer; +import net.minecraft.world.gen.ChunkGenerator; +import net.minecraft.world.chunk.ChunkSection; +import net.minecraft.world.chunk.IChunk; +import net.minecraft.world.IWorld; +import net.minecraft.world.gen.OverworldChunkGenerator; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +/** + * Replaces recorded Overworld terrain fluid at the start of decoration, after + * native density, surface and cave generation. Matching lighting properties + * keep the section writes compatible with native height and light data. + * The mask intersects native density with the fluid still present before decoration, + * leaving later lakes, springs and decorators outside this pass. + */ +public final class AquiferMaterialSubstitution { + private static final Logger LOGGER = LogManager.getLogger(); + private static final Map NATIVE_FLUIDS = + Collections.synchronizedMap(new IdentityHashMap()); + private static final Map PLANS = + Collections.synchronizedMap(new IdentityHashMap()); + private static final PendingMasks PENDING = new PendingMasks(); + + private static final java.util.Set DIMENSIONS = ConcurrentHashMap.newKeySet(); + private static final net.minecraft.util.math.BlockPos LIGHT_POS = new net.minecraft.util.math.BlockPos(0, 0, 0); + private static final net.minecraft.world.IBlockReader LIGHT_READER = new net.minecraft.world.IBlockReader() { + public net.minecraft.tileentity.TileEntity getTileEntity(net.minecraft.util.math.BlockPos pos) { return null; } + public BlockState getBlockState(net.minecraft.util.math.BlockPos pos) { return net.minecraft.block.Blocks.AIR.getDefaultState(); } + public net.minecraft.fluid.IFluidState getFluidState(net.minecraft.util.math.BlockPos pos) { return net.minecraft.fluid.Fluids.EMPTY.getDefaultState(); } + }; + private static net.minecraft.world.gen.feature.ConfiguredFeature configured; + public static void register() { + configured = net.minecraft.world.biome.Biome.createDecoratedFeature( + new SubstitutionFeature(), new net.minecraft.world.gen.feature.NoFeatureConfig(), + net.minecraft.world.gen.placement.Placement.NOPE, + net.minecraft.world.gen.placement.IPlacementConfig.NO_PLACEMENT_CONFIG); + } + static boolean enabledFor(net.minecraft.util.ResourceLocation dimension) { return DIMENSIONS.contains(dimension); } + static net.minecraft.world.gen.feature.ConfiguredFeature configuredFeature() { return configured; } + + /** Native aquatic decorators still see the fluid used to build the terrain. Writes remain real. */ + static IWorld nativeDecorationView(IWorld world) { + if (!(world.getWorld() instanceof ServerWorld)) return world; + ChunkGenerator generator = ((ServerWorld) world.getWorld()).getChunkProvider().getChunkGenerator(); + Plan plan = PLANS.get(generator); + if (plan == null || !plan.deferred) return world; + return new NativeAquiferView(world, plan.nativeFluid, plan.selectedFluid); + } + + private static final class SubstitutionFeature extends ContextFeature { + SubstitutionFeature() { super(net.minecraft.world.gen.feature.NoFeatureConfig::deserialize); } + @Override boolean place(FeaturePlaceContext context) { + return !WorldgenBenchmark.isVanillaBaseline() && apply(context.level(), context.decorationChunk()); + } + } + + private AquiferMaterialSubstitution() { + } + + static void configure(ServerWorld world, BlockState selected) { + DIMENSIONS.remove(WorldIds.dimension(world)); + ChunkGenerator raw = world.getChunkProvider().getChunkGenerator(); + if (raw == null || raw.getClass() != OverworldChunkGenerator.class) { + PLANS.remove(raw); + PENDING.remove(raw); + return; + } + + OverworldChunkGenerator generator = (OverworldChunkGenerator) raw; + BlockState nativeFluid; + synchronized (NATIVE_FLUIDS) { + nativeFluid = NATIVE_FLUIDS.get(generator); + if (nativeFluid == null) { + nativeFluid = generator.defaultFluid; + NATIVE_FLUIDS.put(generator, nativeFluid); + } + } + generator.defaultFluid = nativeFluid; + PLANS.remove(raw); + PENDING.remove(raw); + + if (selected == null || sameState(selected, nativeFluid)) return; + if (lightCompatible(nativeFluid, selected)) { + PLANS.put(raw, new Plan(nativeFluid, selected, true)); + DIMENSIONS.add(WorldIds.dimension(world)); + return; + } + + generator.defaultFluid = selected; + PLANS.put(raw, new Plan(nativeFluid, selected, false)); + LOGGER.warn("Dimension '{}' uses aquifer fluid '{}' with opacity/light {}/{} instead of " + + "native '{}' at {}/{}; using the compatible generator path, which may generate more slowly", + WorldIds.dimension(world), selected, selected.getOpacity(LIGHT_READER, LIGHT_POS), selected.getLightValue(), + nativeFluid, nativeFluid.getOpacity(LIGHT_READER, LIGHT_POS), nativeFluid.getLightValue()); + } + + private static final Map CAPTURED = + Collections.synchronizedMap(new java.util.WeakHashMap()); + + static void capture(ChunkGenerator generator, IChunk chunk) { + Plan plan = PLANS.get(generator); + if (plan == null || !plan.deferred || generator.getClass() != OverworldChunkGenerator.class) return; + // Do not reinterpret later lake water if a decorated chunk is visited again. + if (CAPTURED.put(chunk, Boolean.TRUE) != null) return; + OverworldChunkGenerator nativeGenerator = (OverworldChunkGenerator) generator; + BitSet mask = captureMask(chunk, plan.nativeFluid, nativeGenerator.getSeaLevel()); + NativeDensityTerrain.Data density = NativeDensityTerrain.chunk(nativeGenerator, chunk.getPos().x, chunk.getPos().z); + for (int index = mask.nextSetBit(0); index >= 0; index = mask.nextSetBit(index + 1)) + if (!density.nativeFluid(localX(index), localY(index), localZ(index))) mask.clear(index); + if (!mask.isEmpty()) PENDING.put(generator, chunk.getPos().x, chunk.getPos().z, + new Pending(plan.nativeFluid, plan.selectedFluid, mask)); + } + + static boolean apply(IWorld region, IChunk chunk) { + if (!(region.getWorld() instanceof ServerWorld)) return false; + ServerWorld world = (ServerWorld) region.getWorld(); + ChunkGenerator generator = ((ServerWorld) world).getChunkProvider().getChunkGenerator(); + capture(generator, chunk); + Pending pending = PENDING.take(generator, chunk.getPos().x, chunk.getPos().z); + if (pending == null) return false; + + ChunkSection[] sections = chunk.getSections(); + int changed = applyToSections(pending, sections); + if (changed > 0 && chunk instanceof Chunk) ((Chunk) chunk).setModified(true); + else if (changed > 0 && chunk instanceof ChunkPrimer) ((ChunkPrimer) chunk).setModified(true); + return changed > 0; + } + + static int applyToSections(Pending pending, ChunkSection[] sections) { + int changed = 0; + for (int index = pending.mask.nextSetBit(0); index >= 0; + index = pending.mask.nextSetBit(index + 1)) { + int y = localY(index); + ChunkSection section = sections[y >> 4]; + if (section == null) continue; + int x = localX(index); + int z = localZ(index); + BlockState current = section.getBlockState(x, y & 15, z); + if (!sameState(current, pending.nativeFluid)) continue; + section.setBlockState(x, y & 15, z, pending.selectedFluid); + changed++; + } + return changed; + } + + static BitSet captureMask(IChunk primer, BlockState nativeFluid, int seaLevel) { + int maximumY = Math.max(0, Math.min(256, seaLevel)); + BitSet result = new BitSet(16 * 16 * maximumY); + if (!nativeFluid.isAir() && (primer.getClass() == ChunkPrimer.class || primer.getClass() == Chunk.class)) { + ChunkSection[] sections = primer.getSections(); + for (int base = 0; base < maximumY; base += 16) { + ChunkSection section = sections[base >> 4]; + if (section == null) continue; + int height = Math.min(16, maximumY - base); + for (int y = 0; y < height; y++) for (int z = 0; z < 16; z++) for (int x = 0; x < 16; x++) { + if (sameState(section.getBlockState(x, y, z), nativeFluid)) result.set(index(x, base + y, z)); + } + } + return result; + } + // Custom chunk views may reinterpret reads; do not bypass their implementation. + net.minecraft.util.math.BlockPos.MutableBlockPos cursor = new net.minecraft.util.math.BlockPos.MutableBlockPos(); + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = 0; y < maximumY; y++) { + if (sameState(primer.getBlockState(cursor.setPos(x, y, z)), nativeFluid)) { + result.set(index(x, y, z)); + } + } + } + } + return result; + } + + static boolean lightCompatible(BlockState nativeFluid, BlockState selectedFluid) { + return !nativeFluid.getBlock().isVariableOpacity() && !selectedFluid.getBlock().isVariableOpacity() + && nativeFluid.getOpacity(LIGHT_READER, LIGHT_POS) == selectedFluid.getOpacity(LIGHT_READER, LIGHT_POS) + && nativeFluid.getLightValue() == selectedFluid.getLightValue(); + } + + static int index(int x, int y, int z) { + // Y-major order keeps below-sea masks compact and visits section cells contiguously. + return (y << 8) | (z << 4) | x; + } + + static int localX(int index) { return index & 15; } + static int localY(int index) { return index >> 8; } + static int localZ(int index) { return (index >> 4) & 15; } + + static void clear() { + synchronized (NATIVE_FLUIDS) { + for (Map.Entry entry : NATIVE_FLUIDS.entrySet()) { + entry.getKey().defaultFluid = entry.getValue(); + } + NATIVE_FLUIDS.clear(); + } + DIMENSIONS.clear(); + PLANS.clear(); + PENDING.clear(); + CAPTURED.clear(); + NativeDensityTerrain.clear(); + } + + static int pendingCount() { return PENDING.size(); } + + private static boolean sameState(BlockState first, BlockState second) { + return first == second || (first != null && first.equals(second)); + } + + private static final class Plan { + final BlockState nativeFluid; + final BlockState selectedFluid; + final boolean deferred; + + Plan(BlockState nativeFluid, BlockState selectedFluid, boolean deferred) { + this.nativeFluid = nativeFluid; + this.selectedFluid = selectedFluid; + this.deferred = deferred; + } + } + + static final class Pending { + final BlockState nativeFluid; + final BlockState selectedFluid; + final BitSet mask; + + Pending(BlockState nativeFluid, BlockState selectedFluid, BitSet mask) { + this.nativeFluid = nativeFluid; + this.selectedFluid = selectedFluid; + this.mask = (BitSet) mask.clone(); + } + } + + static final class PendingMasks { + private final Map masks = new ConcurrentHashMap<>(); + + void put(ChunkGenerator generator, int x, int z, Pending pending) { + masks.put(new ChunkKey(generator, x, z), pending); + } + + Pending take(ChunkGenerator generator, int x, int z) { + return masks.remove(new ChunkKey(generator, x, z)); + } + + void remove(ChunkGenerator generator) { + for (ChunkKey key : masks.keySet()) { + if (key.generator == generator) masks.remove(key); + } + } + + void clear() { masks.clear(); } + int size() { return masks.size(); } + } + + private static final class ChunkKey { + final ChunkGenerator generator; + final int x; + final int z; + + ChunkKey(ChunkGenerator generator, int x, int z) { + this.generator = generator; + this.x = x; + this.z = z; + } + + @Override public int hashCode() { + return ((31 * System.identityHashCode(generator)) + x) * 31 + z; + } + + @Override public boolean equals(Object value) { + if (this == value) return true; + if (!(value instanceof ChunkKey)) return false; + ChunkKey other = (ChunkKey) value; + return generator == other.generator && x == other.x && z == other.z; + } + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/BakedGeomeConfig.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/BakedGeomeConfig.java index b5f52a9c..8d55ad68 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/BakedGeomeConfig.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/BakedGeomeConfig.java @@ -21,6 +21,7 @@ public final class BakedGeomeConfig { private static final int LEGACY_MAX_Y = 255; private static final int FORMATION_BUCKETS = 256; private static final int PICKER_SCALE = 1000; + private static final RockFamily[] FAMILIES = RockFamily.values(); private static final BlockState FALLBACK = Blocks.STONE.getDefaultState(); final GeomeDefinition[] geomes; @@ -84,6 +85,13 @@ public final class BakedGeomeConfig { sedimentaryBlocks = buildBlockSet(rocks, true, false); oreReplaceableBlocks = buildBlockSet(rocks, false, true); rockFamilies = buildFamilyMap(rocks); + for (zone.moddev.mc.orespawn.api.FormationMaterial material : NaturalFormations.materials()) { + if (!material.family().isPresent()) continue; + RockFamily family = RockFamily.valueOf(material.family().get().name()); + oreReplaceableBlocks.add(material.state().getBlock()); + rockFamilies.put(material.state().getBlock(), family); + if (family == RockFamily.SEDIMENTARY) sedimentaryBlocks.add(material.state().getBlock()); + } if (formations.usesStableLayers()) { buildStablePickers(rocks); @@ -139,7 +147,7 @@ RockFamily pickFamily(int geomeIndex, int y, int formationValue, int diversitySl if (formations.usesStableLayers()) { int index = stableFamilyIndex(geomeIndex, clampStableY(y), formationValue & 0xFF, diversitySlot & (familyDiversitySlots - 1)); - return RockFamily.values()[stableFamilyChoices[index] & 0xFF]; + return FAMILIES[stableFamilyChoices[index] & 0xFF]; } int[] thresholds = legacyFamilyThresholds[geomeIndex][clampLegacyY(y)]; @@ -151,7 +159,7 @@ RockFamily pickFamily(int geomeIndex, int y, int formationValue, int diversitySl int value = positive(formationValue) % total; for (int i = 0; i < thresholds.length; i++) { if (value < thresholds[i]) { - return RockFamily.values()[i]; + return FAMILIES[i]; } } return RockFamily.SEDIMENTARY; @@ -168,10 +176,8 @@ RockFamily pickStableFamilyAtWorldY(int geomeIndex, int worldY, int formationY, int boundedFormationY = clampStableValue(formationY); double bestScore = Double.NEGATIVE_INFINITY; RockFamily bestFamily = preferred; - for (RockFamily family : RockFamily.values()) { - if (!hasEligibleStableRock(geomeIndex, family, worldY, formationY)) { - continue; - } + for (RockFamily family : FAMILIES) { + if (!hasEligibleStableRock(geomeIndex, family, worldY, formationY)) continue; double weight = Math.pow(geomes[geomeIndex].familyWeights[family.ordinal()], 2.5D) * familyDepthWeight(family, boundedFormationY); if (weight <= 0.0D) { @@ -237,12 +243,15 @@ RockFamily familyOf(BlockState state) { } public BlockState[] statesForFamily(RockFamily... families) { + java.util.Set available = new java.util.LinkedHashSet<>(Arrays.asList(rockStates)); + for (zone.moddev.mc.orespawn.api.FormationMaterial m : NaturalFormations.materials()) + if (m.family().isPresent()) available.add(m.state()); int mask = 0; for (RockFamily family : families) { mask |= 1 << family.ordinal(); } int count = 0; - for (BlockState state : rockStates) { + for (BlockState state : available) { RockFamily family = rockFamilies.get(state.getBlock()); if (family != null && (mask & (1 << family.ordinal())) != 0) { count++; @@ -250,7 +259,7 @@ public BlockState[] statesForFamily(RockFamily... families) { } BlockState[] result = new BlockState[count]; int index = 0; - for (BlockState state : rockStates) { + for (BlockState state : available) { RockFamily family = rockFamilies.get(state.getBlock()); if (family != null && (mask & (1 << family.ordinal())) != 0) { result[index++] = state; @@ -263,6 +272,8 @@ void addRockBlocks(Set target) { for (BlockState state : rockStates) { target.add(state.getBlock()); } + for (zone.moddev.mc.orespawn.api.FormationMaterial material : NaturalFormations.materials()) + if (material.family().isPresent()) target.add(material.state().getBlock()); } int geomeCount() { @@ -339,9 +350,9 @@ private double[] biomeWeightsFor(Biome biome, ResourceLocation biomeId) { private void buildStablePickers(RockEntry[] rocks) { stableFamilyChoices = new byte[geomes.length * HEIGHT * FORMATION_BUCKETS * familyDiversitySlots]; - stableRockChoices = new int[geomes.length * RockFamily.values().length * HEIGHT * FORMATION_BUCKETS]; + stableRockChoices = new int[geomes.length * FAMILIES.length * HEIGHT * FORMATION_BUCKETS]; Arrays.fill(stableRockChoices, -1); - int familyCount = RockFamily.values().length; + int familyCount = FAMILIES.length; familyRockIndexes = groupRockIndexes(rocks); stableRockLogWeights = new double[geomes.length][rocks.length][HEIGHT]; stableRockPriorities = new double[geomes.length][rocks.length][FORMATION_BUCKETS]; @@ -365,7 +376,7 @@ private void buildStablePickers(RockEntry[] rocks) { } } - for (RockFamily family : RockFamily.values()) { + for (RockFamily family : FAMILIES) { int familyIndex = family.ordinal(); for (int y = MIN_Y; y <= MAX_Y; y++) { int yIndex = y - MIN_Y; @@ -403,7 +414,7 @@ private void buildStablePickers(RockEntry[] rocks) { if (familyDiversitySlots == 1) { double bestFamilyScore = Double.NEGATIVE_INFINITY; int bestFamily = RockFamily.SEDIMENTARY.ordinal(); - for (RockFamily family : RockFamily.values()) { + for (RockFamily family : FAMILIES) { int familyIndex = family.ordinal(); double familyScore = familyLogWeights[geome][familyIndex][yIndex] + familyPriorities[geome][familyIndex][bucket]; @@ -418,7 +429,7 @@ private void buildStablePickers(RockEntry[] rocks) { quotas, remaining, remainders, bonusAwarded); } - for (RockFamily family : RockFamily.values()) { + for (RockFamily family : FAMILIES) { int familyIndex = family.ordinal(); double bestRockScore = Double.NEGATIVE_INFINITY; int bestRock = -1; @@ -468,7 +479,7 @@ private void fillBalancedFamilyCycle(int geome, int yIndex, int bucket, Arrays.fill(bonusAwarded, false); double totalWeight = 0.0D; - for (RockFamily family : RockFamily.values()) { + for (RockFamily family : FAMILIES) { totalWeight += familyWeights[geome][family.ordinal()][yIndex]; } if (totalWeight <= 0.0D) { @@ -481,7 +492,7 @@ private void fillBalancedFamilyCycle(int geome, int yIndex, int bucket, int allocated = 0; // Largest-remainder apportionment turns the continuous weights into an exact cycle quota. - for (RockFamily family : RockFamily.values()) { + for (RockFamily family : FAMILIES) { int familyIndex = family.ordinal(); double exactSlots = familyWeights[geome][familyIndex][yIndex] * familyDiversitySlots / totalWeight; @@ -495,7 +506,7 @@ private void fillBalancedFamilyCycle(int geome, int yIndex, int bucket, int bestFamily = -1; double bestRemainder = Double.NEGATIVE_INFINITY; double bestPriority = Double.NEGATIVE_INFINITY; - for (RockFamily family : RockFamily.values()) { + for (RockFamily family : FAMILIES) { int familyIndex = family.ordinal(); if (familyWeights[geome][familyIndex][yIndex] <= 0.0D || bonusAwarded[familyIndex]) { continue; @@ -522,7 +533,7 @@ private void fillBalancedFamilyCycle(int geome, int yIndex, int bucket, // Interleave quota copies so a favored family is spread through the cycle. for (int slot = 0; slot < familyDiversitySlots; slot++) { boolean hasAlternative = false; - for (RockFamily family : RockFamily.values()) { + for (RockFamily family : FAMILIES) { int familyIndex = family.ordinal(); if (familyIndex != previousFamily && remaining[familyIndex] > 0) { hasAlternative = true; @@ -533,7 +544,7 @@ private void fillBalancedFamilyCycle(int geome, int yIndex, int bucket, int bestFamily = -1; int bestScore = Integer.MIN_VALUE; double bestPriority = Double.NEGATIVE_INFINITY; - for (RockFamily family : RockFamily.values()) { + for (RockFamily family : FAMILIES) { int familyIndex = family.ordinal(); if (remaining[familyIndex] <= 0 || (hasAlternative && familyIndex == previousFamily)) { @@ -557,8 +568,8 @@ private void fillBalancedFamilyCycle(int geome, int yIndex, int bucket, } private static int[][] groupRockIndexes(RockEntry[] rocks) { - int[][] indexes = new int[RockFamily.values().length][]; - for (RockFamily family : RockFamily.values()) { + int[][] indexes = new int[FAMILIES.length][]; + for (RockFamily family : FAMILIES) { int count = 0; for (RockEntry rock : rocks) { if (rock.family == family) { @@ -609,12 +620,12 @@ private static double unitDouble(long value) { } private void buildLegacyPickers(RockEntry[] rocks) { - legacyFamilyThresholds = new int[geomes.length][LEGACY_MAX_Y + 1][RockFamily.values().length]; - legacyRockPickers = new WeightedBlockPicker[geomes.length][RockFamily.values().length][LEGACY_MAX_Y + 1]; + legacyFamilyThresholds = new int[geomes.length][LEGACY_MAX_Y + 1][FAMILIES.length]; + legacyRockPickers = new WeightedBlockPicker[geomes.length][FAMILIES.length][LEGACY_MAX_Y + 1]; for (int geome = 0; geome < geomes.length; geome++) { for (int y = 0; y <= LEGACY_MAX_Y; y++) { int familyTotal = 0; - for (RockFamily family : RockFamily.values()) { + for (RockFamily family : FAMILIES) { WeightedBlockPicker picker = buildLegacyRockPicker(rocks, geome, family, y); legacyRockPickers[geome][family.ordinal()][y] = picker; @@ -680,7 +691,7 @@ private int stableFamilyIndex(int geome, int yIndex, int bucket, int diversitySl } private int stableRockIndex(int geome, int family, int yIndex, int bucket) { - return ((((geome * RockFamily.values().length) + family) * HEIGHT + yIndex) * FORMATION_BUCKETS) + return ((((geome * FAMILIES.length) + family) * HEIGHT + yIndex) * FORMATION_BUCKETS) + bucket; } diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/BiomeFeatureInstaller.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/BiomeFeatureInstaller.java index 07b2adb1..b5893dcc 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/BiomeFeatureInstaller.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/BiomeFeatureInstaller.java @@ -30,11 +30,18 @@ static void install(BakedBiomeWorldgen config, ResourceLocation dimension) { boolean vanillaOreGate = OreSpawnOreGeneration.needsVanillaOreGate(dimension); boolean surfaces = config != null && config.hasSurfaces(); boolean flatBedrock = FlatBedrockFeature.enabledFor(dimension); + boolean aquifers = AquiferMaterialSubstitution.enabledFor(dimension); if (!terrain && !managedOres && !fluidDeposits && !vanillaOreGate - && !surfaces && !flatBedrock) return; + && !surfaces && !flatBedrock && !aquifers) return; for (Biome biome : ForgeRegistries.BIOMES.getValues()) { installFeatures(biome, terrain, managedOres, fluidDeposits, vanillaOreGate, surfaces, flatBedrock); + if (aquifers) { + for (GenerationStage.Decoration stage : GenerationStage.Decoration.values()) + VanillaSpringCompatibility.rewriteFeatureList(biome.getFeatures(stage), false, true); + placeUniqueAt(biome.getFeatures(GenerationStage.Decoration.RAW_GENERATION), + AquiferMaterialSubstitution.configuredFeature(), 0); + } } } diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/BiomeWorldgenManager.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/BiomeWorldgenManager.java index 80007700..ebde46b4 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/BiomeWorldgenManager.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/BiomeWorldgenManager.java @@ -39,6 +39,8 @@ final class BiomeWorldgenManager { private static final Logger LOGGER = LogManager.getLogger(); private static volatile Map baked = Collections.emptyMap(); + private static final Set> WARNED_CUSTOM_FLUID_GENERATORS = + Collections.newSetFromMap(new IdentityHashMap, Boolean>()); private static final Map ORIGINAL_DEFAULT_FLUIDS = new IdentityHashMap<>(); private static final Set WARNED_DEEP_FLUID_DIMENSIONS = @@ -66,9 +68,9 @@ static synchronized void apply(MinecraftServer server, WorldGeologyProfile profi BakedBiomeWorldgen dimension = bake(level, profile.rootCopy()); ResourceLocation dimensionId = WorldIds.dimension(level); if (dimension != null) next.put(dimensionId, dimension); - BiomeFeatureInstaller.install(dimension, dimensionId); installBiomeSource(level, dimension); installAquiferMaterials(level, dimension == null ? null : dimension.materials); + BiomeFeatureInstaller.install(dimension, dimensionId); } baked = Collections.unmodifiableMap(next); } @@ -84,9 +86,9 @@ static synchronized void apply(ServerWorld level, WorldGeologyProfile profile) { ResourceLocation dimensionId = WorldIds.dimension(level); if (dimension == null) next.remove(dimensionId); else next.put(dimensionId, dimension); - BiomeFeatureInstaller.install(dimension, dimensionId); installBiomeSource(level, dimension); installAquiferMaterials(level, dimension == null ? null : dimension.materials); + BiomeFeatureInstaller.install(dimension, dimensionId); baked = Collections.unmodifiableMap(next); } @@ -96,6 +98,8 @@ static synchronized void clear() { entry.getKey().defaultFluid = entry.getValue(); } ORIGINAL_DEFAULT_FLUIDS.clear(); + WARNED_CUSTOM_FLUID_GENERATORS.clear(); + AquiferMaterialSubstitution.clear(); WARNED_DEEP_FLUID_DIMENSIONS.clear(); baked = Collections.emptyMap(); } @@ -285,22 +289,23 @@ private static void installBiomeSource(ServerWorld level, BakedBiomeWorldgen con generator.biomeProvider = overlay; } - private static void installAquiferMaterials(ServerWorld level, DimensionMaterials materials) { - ChunkGenerator raw = level.getChunkProvider().getChunkGenerator(); - if (!(raw instanceof NoiseChunkGenerator)) return; - NoiseChunkGenerator generator = (NoiseChunkGenerator) raw; - BlockState original = ORIGINAL_DEFAULT_FLUIDS.computeIfAbsent(generator, - ignored -> generator.defaultFluid); - generator.defaultFluid = materials != null && materials.defaultFluid != null - ? materials.defaultFluid : original; - if (materials != null && materials.deepFluid != null - && !materials.deepFluid.equals(generator.defaultFluid) - && materials.deepFluidMaxY >= 0 - && WARNED_DEEP_FLUID_DIMENSIONS.add(WorldIds.dimension(level))) { - LOGGER.warn("Dimension '{}' requests a distinct deep aquifer fluid below Y {}, but Minecraft 1.14.4 only exposes one generator fluid; preserving the profile value and using default_fluid for generation", - WorldIds.dimension(level), materials.deepFluidMaxY); - } - } + private static void installAquiferMaterials(ServerWorld level, DimensionMaterials materials) { + ChunkGenerator raw = level.getChunkProvider().getChunkGenerator(); + if (!(raw instanceof NoiseChunkGenerator) + || (raw instanceof net.minecraft.world.gen.OverworldChunkGenerator + && raw.getClass() != net.minecraft.world.gen.OverworldChunkGenerator.class)) { + if (materials != null && materials.defaultFluid != null && WARNED_CUSTOM_FLUID_GENERATORS.add(raw)) + LOGGER.warn("Dimension '{}' uses independent generator '{}'; keeping its fluid setting without changing native terrain", + WorldIds.dimension(level), raw == null ? "unknown" : raw.getClass().getName()); + return; + } + NoiseChunkGenerator generator = (NoiseChunkGenerator) raw; + BlockState original = ORIGINAL_DEFAULT_FLUIDS.computeIfAbsent(generator, ignored -> generator.defaultFluid); + BlockState selected = materials != null && materials.defaultFluid != null ? materials.defaultFluid : original; + if (raw.getClass() == net.minecraft.world.gen.OverworldChunkGenerator.class) + AquiferMaterialSubstitution.configure(level, selected); + else generator.defaultFluid = selected; + } private static Surface surface(JsonObject json) { BlockState top = state(json, "top_block", false); diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/BuiltinRockFormation.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/BuiltinRockFormation.java new file mode 100644 index 00000000..f5a564d9 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/BuiltinRockFormation.java @@ -0,0 +1,150 @@ +package zone.moddev.mc.orespawn.worldgen; + +import com.google.gson.*; +import java.util.*; +import net.minecraft.block.Block; +import net.minecraft.block.BlockState; +import net.minecraft.block.Blocks; +import net.minecraft.util.ResourceLocation; +import zone.moddev.mc.orespawn.api.*; + +/** Immutable deterministic bodies in region coordinates, not independent random stone bands. */ +final class BuiltinRockFormation implements CompiledRockFormation { + private final int type; + private final long salt; + private final int spacing, minY, maxY, minRadius, maxRadius, height, cover; + private final double chance; + private final Set geomes = new HashSet<>(); + private final Set dimensions = new HashSet<>(); + private final Map outputs = new HashMap<>(); + private final FormationMaterial syenite, nepheline, carbonatite, granite, skarn, greisen, serpentinite, + pipe, quartz, ferricrete, clay, saprolitic; + private final Set carbonates = new HashSet<>(), ultramafics = new HashSet<>(), weatherParents = new HashSet<>(); + BuiltinRockFormation(String type, JsonObject rule) { + this.type = Arrays.asList("alkaline_complex", "granitic_contact", "ultramafic_alteration", + "barren_pipe", "quartz_vein", "weathering_profile").indexOf(type); + if (this.type < 0) throw new IllegalArgumentException("Unknown formation type " + type); + if (integer(rule, "algorithm_revision", 1) != 1) throw new IllegalArgumentException("Unsupported formation algorithm"); + salt = rule.has("salt") ? rule.get("salt").getAsLong() : type.hashCode(); + int chunks = integer(rule, "spacing_chunks", 32); + if (chunks < 8 || chunks > 65536) throw new IllegalArgumentException("Invalid formation spacing"); + spacing = chunks * 16; + minY = integer(rule, "min_y", 12); maxY = integer(rule, "max_y", 64); + minRadius = integer(rule, "radius_min", 12); maxRadius = integer(rule, "radius_max", 28); + height = integer(rule, "height", 40); cover = integer(rule, "cover", 8); + chance = rule.has("chance") ? rule.get("chance").getAsDouble() : .12; + if (spacing < 128 || maxRadius * 1.1 >= spacing / 4 || minRadius < 2 || maxRadius < minRadius + || minY < 5 || maxY > 240 || minY > maxY || height < 4 || height > 128 + || cover < 4 || !Double.isFinite(chance) || chance < 0 || chance > 1) + throw new IllegalArgumentException("Invalid rock formation geometry"); + if (rule.has("geomes")) for (JsonElement g : rule.getAsJsonArray("geomes")) + geomes.add(new ResourceLocation(g.getAsString().indexOf(':') < 0 ? "orespawn:" + g.getAsString() : g.getAsString())); + if (rule.has("dimensions")) for (JsonElement d : rule.getAsJsonArray("dimensions")) + dimensions.add(new ResourceLocation(d.getAsString())); + else dimensions.add(new ResourceLocation("minecraft:overworld")); + JsonObject materials = rule.getAsJsonObject("materials"); + if (materials == null || materials.entrySet().isEmpty()) throw new IllegalArgumentException("Formation has no materials"); + for (Map.Entry e : materials.entrySet()) { + JsonObject m = e.getValue().getAsJsonObject(); + ResourceLocation id = new ResourceLocation(m.get("block").getAsString()); + if (!net.minecraftforge.registries.ForgeRegistries.BLOCKS.containsKey(id)) throw new IllegalArgumentException("Missing formation material: " + id); + Block block = net.minecraftforge.registries.ForgeRegistries.BLOCKS.getValue(id); + if (block == Blocks.AIR || block == Blocks.BEDROCK) throw new IllegalArgumentException("Invalid formation output: " + id); + GeologyFamily family = m.has("family") ? GeologyFamily.valueOf(m.get("family").getAsString().toUpperCase(Locale.ROOT)) : null; + outputs.put(e.getKey(), new FormationMaterial( + zone.moddev.mc.orespawn.util.ConfiguredBlockState.read(m), family)); + } + String[][] required = {{"syenite", "nepheline_syenite", "carbonatite"}, {"granite", "skarn", "greisen"}, + {"serpentinite"}, {"pipe"}, {"vein_quartz"}, {"ferricrete", "lateritic_clay", "saprolitic_rock"}}; + for (String role : required[this.type]) if (!outputs.containsKey(role)) + throw new IllegalArgumentException("Missing formation material role " + role); + syenite = outputs.get("syenite"); nepheline = outputs.get("nepheline_syenite"); + carbonatite = outputs.get("carbonatite"); granite = outputs.get("granite"); + skarn = outputs.get("skarn"); greisen = outputs.get("greisen"); serpentinite = outputs.get("serpentinite"); + pipe = outputs.get("pipe"); quartz = outputs.get("vein_quartz"); ferricrete = outputs.get("ferricrete"); + clay = outputs.get("lateritic_clay"); saprolitic = outputs.get("saprolitic_rock"); + collect(carbonates, "limestone", "dolomite"); + collect(ultramafics, "peridotite"); + collect(weatherParents, "peridotite", "syenite", "nepheline_syenite", "granite"); + } + private static void collect(Set into, String... names) { + for (String name : names) { + ResourceLocation key = new ResourceLocation("mineralogy", name); + if (net.minecraftforge.registries.ForgeRegistries.BLOCKS.containsKey(key)) into.add(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getValue(key)); + } + } + static int integer(JsonObject rule, String key, int fallback) { return rule.has(key) ? rule.get(key).getAsInt() : fallback; } + static long mix(long value) { + value = (value ^ (value >>> 30)) * 0xbf58476d1ce4e5b9L; + value = (value ^ (value >>> 27)) * 0x94d049bb133111ebL; + return value ^ (value >>> 31); + } + static double unit(long hash) { return (hash >>> 11) * 0x1.0p-53; } + @Override public RockFormationColumn prepare(RockFormationContext c) { + if (!dimensions.contains(c.base().dimension())) return null; + if (!geomes.isEmpty() && !geomes.contains(c.base().geome())) return null; + int x = c.base().blockX(), z = c.base().blockZ(); + int rx = Math.floorDiv(x, spacing), rz = Math.floorDiv(z, spacing); + long h = mix(c.seed() ^ salt ^ mix(rx) ^ Long.rotateLeft(mix(rz), 27)); + if (unit(h) >= chance) return null; + int cx = rx * spacing + spacing / 2 + (int) (unit(mix(h + 1)) * spacing / 2) - spacing / 4; + int cz = rz * spacing + spacing / 2 + (int) (unit(mix(h + 2)) * spacing / 2) - spacing / 4; + double radius = minRadius + unit(mix(h + 3)) * (maxRadius - minRadius); + double dx = (x - cx) / radius, dz = (z - cz) / (radius * .75); + double horizontal = dx * dx + dz * dz; + if (horizontal > 1.15) return null; + int surface = c.surfaceY(); + if (surface < 12) return null; + // One body has one elevation: terrain may clip it, but must not bend an + // intrusion up and down independently in each surface-height column. + int centre = minY + (int) (unit(mix(h + 4)) * (maxY - minY + 1)); + final long identity = h; + final BlockState weatherParent = type == 5 ? c.base().rockAt(surface - 18) : null; + final boolean weatherable = type == 5 && (weatherParents.contains(weatherParent.getBlock()) + || weatherParent.equals(Blocks.GRANITE.getDefaultState())); + return new RockFormationColumn() { + @Override public FormationMaterial at(int y) { + if (y < 5 || y > surface - 3) return null; + BlockState parent = c.base().rockAt(y); + Block host = parent.getBlock(); + double vertical = (y - centre) / (height * .5); + double body = horizontal + vertical * vertical; + switch (type) { + case 0: + if (y > surface - cover || body > 1) return null; + if (body < .16 && unit(mix(identity + 7)) < .3) return carbonatite; + return unit(mix(identity + 8)) < .35 && body < .6 ? nepheline : syenite; + case 1: + if (y > surface - cover || body > 1.18) return null; + if (body > .82) return carbonates.contains(host) ? skarn : null; + if (vertical > .3 && Math.abs((x - cx) + (z - cz) * .5) < 4) return greisen; + return granite; + case 2: + return body <= 1 && ultramafics.contains(host) + ? serpentinite : null; + case 3: + if (y > surface - cover || y < 8 || y > maxY + height) return null; + double taper = .2 + .8 * Math.max(0, Math.min(1, (y - 8.0) / (maxY + height - 8.0))); + return horizontal < taper * taper ? pipe : null; + case 4: + if (y > surface - cover || body > 1) return null; + return Math.abs((x - cx) * .65 + z - cz + Math.sin(y * .19) * 2) < 1.5 + ? quartz : null; + case 5: + if (c.temperature() < .8F || c.rainfall() < .6F || horizontal > 1) return null; + int depth = surface - y; + if (depth < 3 || depth > 15) return null; + // Parent is assessed below the whole weathering profile, never by a generic clay identity. + if (!weatherable) return null; + return depth <= 5 ? ferricrete : depth <= 9 ? clay : saprolitic; + default: throw new IllegalStateException("Uncompiled formation"); + } + } + @Override public BlockState parentAt(int y) { + if (type == 5) return weatherParent; + if (type == 1 && at(y) == greisen) return granite.state(); + return null; + } + }; + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/ConfiguredFeatureInspector.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/ConfiguredFeatureInspector.java index 4d399e19..7ddb1ca9 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/ConfiguredFeatureInspector.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/ConfiguredFeatureInspector.java @@ -16,6 +16,13 @@ /** Traverses the inline configured-feature graphs used by Minecraft 1.14. */ final class ConfiguredFeatureInspector { + @SuppressWarnings({"rawtypes", "unchecked"}) + static boolean placeRoot(net.minecraft.world.gen.feature.Feature feature, + net.minecraft.world.gen.feature.IFeatureConfig config, FeaturePlaceContext context) { + return ((net.minecraft.world.gen.feature.Feature) feature).place(context.level(), + context.chunkGenerator(), context.random(), context.origin(), config); + } + private ConfiguredFeatureInspector() { } @@ -33,6 +40,8 @@ private static Block firstOreOutput(ConfiguredFeature feature, Set> visited) { if (feature == null || !visited.add(feature)) return null; Object config = feature.config; + Block wrapped = VanillaOreFeatureGate.wrappedOutput(feature.feature, feature.config); + if (wrapped != null) return wrapped; if (config instanceof OreFeatureConfig) return ((OreFeatureConfig) config).state.getBlock(); if (config instanceof DecoratedFeatureConfig) { return firstOreOutput(((DecoratedFeatureConfig) config).feature, visited); @@ -71,6 +80,11 @@ private static boolean outputsAny(ConfiguredFeature feature, Set> visited, Block[] blocks) { if (feature == null || !visited.add(feature)) return false; Object config = feature.config; + Block wrapped = VanillaOreFeatureGate.wrappedOutput(feature.feature, feature.config); + if (wrapped != null) { + for (Block block : blocks) if (wrapped == block) return true; + return false; + } if (config instanceof OreFeatureConfig) { Block output = ((OreFeatureConfig) config).state.getBlock(); for (Block block : blocks) if (output == block) return true; diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/FeaturePlaceContext.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/FeaturePlaceContext.java index dd58a48f..1581bf9d 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/FeaturePlaceContext.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/FeaturePlaceContext.java @@ -44,4 +44,13 @@ BlockPos origin() { FC config() { return config; } + + net.minecraft.world.chunk.IChunk decorationChunk() { + if (level instanceof net.minecraft.world.gen.WorldGenRegion) { + net.minecraft.world.gen.WorldGenRegion region = (net.minecraft.world.gen.WorldGenRegion) level; + return region.getChunk(region.getMainChunkX(), region.getMainChunkZ()); + } + return level.getChunk(origin.getX() >> 4, origin.getZ() >> 4, + net.minecraft.world.chunk.ChunkStatus.EMPTY, false); + } } diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/GeomeConfig.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/GeomeConfig.java index 50481861..5ccedea0 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/GeomeConfig.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/GeomeConfig.java @@ -99,26 +99,37 @@ private GeomeConfig() { } public static synchronized BakedGeomeConfig bake() { + return bakeGlobal(true); + } + + public static synchronized BakedGeomeConfig bakeBeforeLoadComplete() { + // Features need provisional settings before every mod has submitted its ores. + return bakeGlobal(false); + } + + private static BakedGeomeConfig bakeGlobal(boolean chooseOreSourceDefaults) { JsonObject root = loadConfig(); boolean changed = OreSpawnOreIntegration.mergeProviderOres(root); changed |= FluidDepositMigration.normalize(root); - changed |= OreSourcePolicies.initialize(root, false); + if (chooseOreSourceDefaults) changed |= OreSourcePolicies.initialize(root, false); if (changed) { writeProviderMerge(root); } globalBaseConfigRoot = JsonCopies.copy(root); globalBaseProfile = WorldGeologyProfile.fromGlobalConfig(root, - OreSpawnConfig.geologyMode(), OreSpawnConfig.placeCrudeOil()); - root = applyFreshWorldTemplate(root); - globalConfigRoot = JsonCopies.copy(root); - globalProfile = WorldGeologyProfile.fromGlobalConfig(root, - OreSpawnConfig.geologyMode(), OreSpawnConfig.placeCrudeOil()); - bakeDimensions(root); + OreSpawnConfig.geologyMode(), OreSpawnConfig.placeCrudeOil(), false); + JsonObject effective = applyFreshWorldTemplate(root); + globalConfigRoot = JsonCopies.copy(effective); + globalProfile = effective == root ? globalBaseProfile : WorldGeologyProfile.fromGlobalConfig(effective, + OreSpawnConfig.geologyMode(), OreSpawnConfig.placeCrudeOil(), chooseOreSourceDefaults); + NaturalFormations.install(effective); + bakeDimensions(effective); return bakedConfig; } public static synchronized BakedGeomeConfig applyWorldProfile(WorldGeologyProfile profile) { JsonObject effective = profile.toGeomeConfigJson(); + NaturalFormations.install(effective); bakeDimensions(effective); return bakedConfig; } diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyConfigMigrator.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyConfigMigrator.java index 324346bc..0557f242 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyConfigMigrator.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyConfigMigrator.java @@ -359,7 +359,7 @@ private static void writeReport(Path config, List lines) { private static void writeUpgradeReport(Path config, int imported, List detail) { List lines = new ArrayList<>(); - lines.add("OreSpawn 4.1.1.114041 Upgrade Report"); + lines.add("OreSpawn 4.1.7.114041 Upgrade Report"); lines.add("================================"); lines.add(""); lines.add("RESULT: Legacy OreSpawn settings were imported into the OS4 profile."); diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyMineralogyProfileMigration.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyMineralogyProfileMigration.java index cf918720..2074c1db 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyMineralogyProfileMigration.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyMineralogyProfileMigration.java @@ -197,7 +197,7 @@ private static void writeUpgradeReport(Path worldRoot, Path configPath, Path report = worldRoot.resolve("serverconfig/orespawn-upgrade-report.txt"); List missing = missingBlocks(igneous, metamorphic, sedimentary); List lines = new ArrayList<>(); - lines.add("OreSpawn 4.1.1.114041 Upgrade Report"); + lines.add("OreSpawn 4.1.7.114041 Upgrade Report"); lines.add("================================"); lines.add(""); lines.add("RESULT: Existing Mineralogy " + identity.version + " world detected."); diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/MmdOreConflictCatalog.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/MmdOreConflictCatalog.java index 38b282dd..6cf901c0 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/MmdOreConflictCatalog.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/MmdOreConflictCatalog.java @@ -14,7 +14,7 @@ final class MmdOreConflictCatalog { private static final Set ORDINARY = Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList( "basemetals", "modernmetals", "basegems", "baseminerals", "fantasymetals", - "electricadvantage", "steamadvantage", "poweradvantage", "mineralogy"))); + "baseelectric", "electricadvantage", "steamadvantage", "poweradvantage", "mineralogy"))); private static final Map> PRIORITIES = priorities(); private MmdOreConflictCatalog() { } @@ -56,9 +56,9 @@ static boolean automaticallyBalance(Map> tagsByOwn private static Map> priorities() { Map> result = new LinkedHashMap<>(); result.put("sulfur", Collections.unmodifiableList(Arrays.asList( - "mineralogy", "baseminerals", "electricadvantage"))); + "mineralogy", "baseminerals", "baseelectric", "electricadvantage"))); result.put("lithium", Collections.unmodifiableList(Arrays.asList( - "baseminerals", "electricadvantage"))); + "baseminerals", "baseelectric", "electricadvantage"))); return Collections.unmodifiableMap(result); } } diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/NativeAquaticCompatibility.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/NativeAquaticCompatibility.java new file mode 100644 index 00000000..66d49bef --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/NativeAquaticCompatibility.java @@ -0,0 +1,34 @@ +package zone.moddev.mc.orespawn.worldgen; + +import net.minecraft.world.gen.feature.Feature; +import net.minecraft.world.gen.feature.IFeatureConfig; + +/** Preserves native decoration that checks for the exact water block, rather than its fluid. */ +final class NativeAquaticCompatibility extends ContextFeature { + static final NativeAquaticCompatibility FEATURE = new NativeAquaticCompatibility(); + private NativeAquaticCompatibility() { + super(data -> { throw new IllegalStateException("Native decoration wrappers are installed in biome feature lists"); }); + } + static boolean accepts(Feature feature) { + return feature == Feature.LAKE || feature == Feature.SEAGRASS || feature == Feature.KELP || feature == Feature.SEA_PICKLE + || feature == Feature.CORAL_TREE || feature == Feature.CORAL_CLAW || feature == Feature.CORAL_MUSHROOM + || feature == Feature.SWAMP_TREE || feature == Feature.ICEBERG || feature == Feature.BLUE_ICE + || feature == Feature.OCEAN_MONUMENT || feature == Feature.OCEAN_RUIN + || feature == Feature.BURIED_TREASURE || feature == Feature.STRONGHOLD || feature == Feature.VILLAGE + || feature == Feature.WATERLILY || feature == Feature.REED || feature == Feature.DISK + || feature == Feature.FREEZE_TOP_LAYER; + } + @Override boolean place(FeaturePlaceContext context) { + return ConfiguredFeatureInspector.placeRoot(context.config().feature, context.config().config, + new FeaturePlaceContext<>(AquiferMaterialSubstitution.nativeDecorationView(context.level()), + context.chunkGenerator(), context.random(), context.origin(), context.config())); + } + static final class Config implements IFeatureConfig { + final Feature feature; + final IFeatureConfig config; + Config(Feature feature, IFeatureConfig config) { this.feature = feature; this.config = config; } + @Override public com.mojang.datafixers.Dynamic serialize(com.mojang.datafixers.types.DynamicOps ops) { + throw new UnsupportedOperationException("Native decoration wrappers are rebuilt from biome feature lists"); + } + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/NativeAquiferView.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/NativeAquiferView.java new file mode 100644 index 00000000..c9be4f66 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/NativeAquiferView.java @@ -0,0 +1,107 @@ +package zone.moddev.mc.orespawn.worldgen; + +import java.util.Random; +import java.util.function.Predicate; +import net.minecraft.block.Block; +import net.minecraft.block.BlockState; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.fluid.Fluid; +import net.minecraft.fluid.IFluidState; +import net.minecraft.particles.IParticleData; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Direction; +import net.minecraft.util.SoundCategory; +import net.minecraft.util.SoundEvent; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.shapes.VoxelShape; +import net.minecraft.world.DifficultyInstance; +import net.minecraft.world.LightType; +import net.minecraft.world.ITickList; +import net.minecraft.world.IWorld; +import net.minecraft.world.World; +import net.minecraft.world.biome.Biome; +import net.minecraft.world.border.WorldBorder; +import net.minecraft.world.chunk.IChunk; +import net.minecraft.world.chunk.AbstractChunkProvider; +import net.minecraft.world.chunk.ChunkStatus; +import net.minecraft.world.dimension.Dimension; +import net.minecraft.world.gen.Heightmap; +import net.minecraft.world.gen.WorldGenRegion; +import net.minecraft.world.storage.WorldInfo; + +/** A native decorator's read view. Writes and all other world operations stay real. */ +final class NativeAquiferView implements IWorld { + private final IWorld world; + private final BlockState nativeFluid, selectedFluid; + private final boolean directFluidReads; + + NativeAquiferView(IWorld world, BlockState nativeFluid, BlockState selectedFluid) { + this.world = world; + this.nativeFluid = nativeFluid; + this.selectedFluid = selectedFluid; + this.directFluidReads = world.getClass() == WorldGenRegion.class; + } + + @Override public BlockState getBlockState(BlockPos pos) { + BlockState state = world.getBlockState(pos); + return state.equals(selectedFluid) ? nativeFluid : state; + } + + @Override public IFluidState getFluidState(BlockPos pos) { + BlockState state = world.getBlockState(pos); + if (state.equals(selectedFluid)) return nativeFluid.getFluidState(); + // The native region obtains its fluid from this same block state. A custom + // world view can override that relationship, so keep its own fluid lookup. + return directFluidReads ? state.getFluidState() : world.getFluidState(pos); + } + + @Override public TileEntity getTileEntity(BlockPos pos) { return world.getTileEntity(pos); } + @Override public boolean isAirBlock(BlockPos pos) { return world.isAirBlock(pos); } + @Override public boolean setBlockState(BlockPos pos, BlockState state, int flags) { return world.setBlockState(pos, state, flags); } + @Override public boolean removeBlock(BlockPos pos, boolean moving) { return world.removeBlock(pos, moving); } + @Override public boolean destroyBlock(BlockPos pos, boolean drops) { return world.destroyBlock(pos, drops); } + @Override public boolean addEntity(Entity entity) { return world.addEntity(entity); } + @Override public long getSeed() { return world.getSeed(); } + @Override public ITickList getPendingBlockTicks() { return world.getPendingBlockTicks(); } + @Override public ITickList getPendingFluidTicks() { return world.getPendingFluidTicks(); } + @Override public IChunk getChunk(int x, int z) { return world.getChunk(x, z); } + @Override public World getWorld() { return world.getWorld(); } + @Override public WorldInfo getWorldInfo() { return world.getWorldInfo(); } + @Override public DifficultyInstance getDifficultyForLocation(BlockPos pos) { return world.getDifficultyForLocation(pos); } + @Override public AbstractChunkProvider getChunkProvider() { return world.getChunkProvider(); } + @Override public Random getRandom() { return world.getRandom(); } + @Override public void notifyNeighbors(BlockPos pos, Block block) { world.notifyNeighbors(pos, block); } + @Override public BlockPos getSpawnPoint() { return world.getSpawnPoint(); } + @Override public void playSound(PlayerEntity player, BlockPos pos, SoundEvent sound, SoundCategory category, float volume, float pitch) { + world.playSound(player, pos, sound, category, volume, pitch); + } + @Override public void addParticle(IParticleData particle, double x, double y, double z, double dx, double dy, double dz) { + world.addParticle(particle, x, y, z, dx, dy, dz); + } + @Override public Biome getBiome(BlockPos pos) { return world.getBiome(pos); } + @Override public int getLightFor(LightType type, BlockPos pos) { return world.getLightFor(type, pos); } + @Override public int getLightSubtracted(BlockPos pos, int amount) { return world.getLightSubtracted(pos, amount); } + @Override public boolean chunkExists(int x, int z) { return world.chunkExists(x, z); } + @Override public boolean canBlockSeeSky(BlockPos pos) { return world.canBlockSeeSky(pos); } + @Override public IChunk getChunk(int x, int z, ChunkStatus status, boolean load) { return world.getChunk(x, z, status, load); } + @Override public BlockPos getHeight(Heightmap.Type type, BlockPos pos) { return world.getHeight(type, pos); } + @Override public boolean hasBlockState(BlockPos pos, Predicate predicate) { return predicate.test(getBlockState(pos)); } + @Override public void playEvent(PlayerEntity player, int event, BlockPos pos, int data) { world.playEvent(player, event, pos, data); } + @Override public java.util.List getPlayers() { return world.getPlayers(); } + @Override public java.util.List getEntitiesInAABBexcluding(Entity entity, net.minecraft.util.math.AxisAlignedBB box, + Predicate predicate) { return world.getEntitiesInAABBexcluding(entity, box, predicate); } + @Override public java.util.List getEntitiesWithinAABB(Class type, + net.minecraft.util.math.AxisAlignedBB box, Predicate predicate) { return world.getEntitiesWithinAABB(type, box, predicate); } + @Override public int getHeight(Heightmap.Type type, int x, int z) { return world.getHeight(type, x, z); } + @Override public PlayerEntity getClosestPlayer(double x, double y, double z, double distance, Predicate predicate) { + return world.getClosestPlayer(x, y, z, distance, predicate); + } + @Override public int getSkylightSubtracted() { return world.getSkylightSubtracted(); } + @Override public WorldBorder getWorldBorder() { return world.getWorldBorder(); } + @Override public boolean checkNoEntityCollision(Entity entity, VoxelShape shape) { return world.checkNoEntityCollision(entity, shape); } + @Override public int getStrongPower(BlockPos pos, Direction direction) { return world.getStrongPower(pos, direction); } + @Override public boolean isRemote() { return world.isRemote(); } + @Override public int getSeaLevel() { return world.getSeaLevel(); } + @Override public Dimension getDimension() { return world.getDimension(); } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/NativeDensityTerrain.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/NativeDensityTerrain.java new file mode 100644 index 00000000..4624125d --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/NativeDensityTerrain.java @@ -0,0 +1,100 @@ +package zone.moddev.mc.orespawn.worldgen; + +import java.lang.ref.WeakReference; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.WeakHashMap; +import net.minecraft.util.math.MathHelper; +import net.minecraft.world.biome.provider.BiomeProvider; +import net.minecraft.world.gen.NoiseChunkGenerator; +import net.minecraft.world.gen.OverworldChunkGenerator; +import net.minecraftforge.fml.common.ObfuscationReflectionHelper; + +/** Shares vanilla density columns between formation heights and background-fluid masks. */ +final class NativeDensityTerrain { + private static final Map CACHES = new WeakHashMap<>(); + private NativeDensityTerrain() { } + + static synchronized Data chunk(OverworldChunkGenerator generator, int x, int z) { + Cache cache = CACHES.get(generator); + if (cache == null || cache.provider.get() != generator.biomeProvider) { + cache = new Cache(generator.biomeProvider); + CACHES.put(generator, cache); + } + long key = ((long) x << 32) ^ (z & 0xffffffffL); + Data data = cache.chunks.get(key); + if (data == null) { + data = new Data(generator, x, z); + cache.chunks.put(key, data); + } + return data; + } + + static synchronized void clear() { CACHES.clear(); } + + private static final class Cache { + final WeakReference provider; + final Map chunks = new LinkedHashMap(128, .75F, true) { + @Override protected boolean removeEldestEntry(Map.Entry entry) { return size() > 512; } + }; + Cache(BiomeProvider provider) { this.provider = new WeakReference<>(provider); } + } + + private static final class NativeColumn { + static final Method FILL = find(); + + private static Method find() { + // This method has no MCP name on 1.14. Use Forge's remapper if a workspace gives it one. + try { + Method method = NoiseChunkGenerator.class.getDeclaredMethod("func_222548_a", + double[].class, int.class, int.class); + method.setAccessible(true); + return method; + } catch (NoSuchMethodException mappedWorkspace) { + return ObfuscationReflectionHelper.findMethod(NoiseChunkGenerator.class, + "func_222548_a", double[].class, int.class, int.class); + } + } + } + + static final class Data { + // Vanilla 1.14 Overworld terrain interpolates 4-by-8 density cells. + private final double[][][] noise = new double[5][5][33]; + private final short[] heights = new short[256]; + private final int seaLevel; + + Data(OverworldChunkGenerator generator, int cx, int cz) { + seaLevel = generator.getSeaLevel(); + Arrays.fill(heights, (short) -2); + try { + for (int x = 0; x < 5; x++) for (int z = 0; z < 5; z++) + NativeColumn.FILL.invoke(generator, noise[x][z], cx * 4 + x, cz * 4 + z); + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException("Could not sample native Overworld density", failure); + } + } + + double density(int x, int y, int z) { + int nx = x >> 2, nz = z >> 2, ny = y >> 3; + return MathHelper.lerp3((y & 7) / 8.0, (x & 3) / 4.0, (z & 3) / 4.0, + noise[nx][nz][ny], noise[nx][nz][ny + 1], + noise[nx + 1][nz][ny], noise[nx + 1][nz][ny + 1], + noise[nx][nz + 1][ny], noise[nx][nz + 1][ny + 1], + noise[nx + 1][nz + 1][ny], noise[nx + 1][nz + 1][ny + 1]); + } + + boolean nativeFluid(int x, int y, int z) { return y >= 0 && y < seaLevel && !(density(x, y, z) > 0.0); } + + synchronized int terrainTop(int x, int z) { + int index = z * 16 + x; + if (heights[index] != -2) return heights[index]; + for (int y = 255; y >= 0; y--) { + if (density(x, y, z) > 0.0) return heights[index] = (short) y; + if (y < seaLevel) return heights[index] = -1; + } + return heights[index] = -1; + } + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/NativeStonePatchContext.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/NativeStonePatchContext.java new file mode 100644 index 00000000..9bc5246f --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/NativeStonePatchContext.java @@ -0,0 +1,18 @@ +package zone.moddev.mc.orespawn.worldgen; + +import net.minecraft.block.Block; +import net.minecraft.block.Blocks; + +/** Lets rock blocks distinguish native stone decoration from metal ore placement. */ +public final class NativeStonePatchContext { + private static final ThreadLocal ACTIVE = ThreadLocal.withInitial(() -> Boolean.FALSE); + private NativeStonePatchContext() { } + public static boolean active() { return ACTIVE.get(); } + static boolean enter(boolean enabled, Block output) { + boolean previous = ACTIVE.get(); + ACTIVE.set(enabled && (output == Blocks.GRANITE || output == Blocks.DIORITE || output == Blocks.ANDESITE)); + return previous; + } + static void restore(boolean previous) { ACTIVE.set(previous); } + static void clear() { ACTIVE.remove(); } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/NaturalFormations.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/NaturalFormations.java new file mode 100644 index 00000000..ac1a8fd3 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/NaturalFormations.java @@ -0,0 +1,192 @@ +package zone.moddev.mc.orespawn.worldgen; + +import java.util.*; +import com.google.gson.*; +import net.minecraft.block.Block; +import net.minecraft.block.BlockState; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.biome.Biome; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.IChunk; +import net.minecraft.world.IWorld; +import net.minecraft.world.gen.Heightmap; +import net.minecraft.world.gen.WorldGenRegion; +import net.minecraft.world.gen.feature.structure.StructureStart; +import zone.moddev.mc.orespawn.api.*; +import zone.moddev.mc.orespawn.util.JsonCopies; + +/** One baked natural-substrate path shared by terrain and the public sampler. */ +public final class NaturalFormations { + public static final String SECTION = "rock_formations"; + private static final String[] TYPES = {"alkaline_complex", "granitic_contact", "ultramafic_alteration", + "barren_pipe", "quartz_vein", "weathering_profile"}; + private static final Map SURFACES = new WeakHashMap<>(); + private static volatile List rules = Collections.emptyList(); + private static volatile Map materials = Collections.emptyMap(); + private static String fingerprint = ""; + static { + for (String type : TYPES) RockFormationRegistry.register(new ResourceLocation("orespawn", type), + json -> new BuiltinRockFormation(type, json)); + } + private NaturalFormations() { } + static synchronized void install(JsonObject profile) { + JsonObject section = profile.has(SECTION) ? profile.getAsJsonObject(SECTION) : new JsonObject(); + String json = section.toString(); + if (fingerprint.equals(json)) return; + List baked = new ArrayList<>(); + Map all = new LinkedHashMap<>(); + for (Map.Entry entry : section.entrySet()) { + JsonObject def = entry.getValue().getAsJsonObject(); + if (def.has("enabled") && !def.get("enabled").getAsBoolean()) continue; + ResourceLocation type = new ResourceLocation(def.get("type").getAsString()); + if (!RockFormationRegistry.contains(type)) { + org.apache.logging.log4j.LogManager.getLogger().warn( + "Formation '{}' needs unavailable type '{}'; keeping its settings without placing it", entry.getKey(), type); + continue; + } + boolean missing = false; + for (Map.Entry material : def.getAsJsonObject("materials").entrySet()) { + ResourceLocation id = new ResourceLocation(material.getValue().getAsJsonObject().get("block").getAsString()); + if (!net.minecraftforge.registries.ForgeRegistries.BLOCKS.containsKey(id)) missing = true; + } + if (missing) { + org.apache.logging.log4j.LogManager.getLogger().warn( + "Formation '{}' has unavailable material blocks; keeping its settings without placing it", entry.getKey()); + continue; + } + CompiledRockFormation compiler = RockFormationRegistry.compile(type, JsonCopies.copy(def)); + baked.add(new Rule(new ResourceLocation(entry.getKey()), BuiltinRockFormation.integer(def, "priority", 0), + BuiltinRockFormation.integer(def, "algorithm_revision", 1), compiler)); + for (Map.Entry value : def.getAsJsonObject("materials").entrySet()) { + JsonObject m = value.getValue().getAsJsonObject(); + Block block = net.minecraftforge.registries.ForgeRegistries.BLOCKS.getValue(new ResourceLocation(m.get("block").getAsString())); + FormationMaterial material = new FormationMaterial(zone.moddev.mc.orespawn.util.ConfiguredBlockState.read(m), + m.has("family") ? GeologyFamily.valueOf(m.get("family").getAsString().toUpperCase(Locale.ROOT)) : null); + FormationMaterial prior = all.put(material.state(), material); + if (prior != null && !prior.family().equals(material.family())) + throw new IllegalArgumentException("Conflicting formation material families"); + } + } + baked.sort(Comparator.comparingInt((Rule r) -> r.priority).thenComparing(r -> r.id.toString())); + rules = Collections.unmodifiableList(baked); + materials = Collections.unmodifiableMap(all); + fingerprint = json; + synchronized (SURFACES) { SURFACES.clear(); } + } + public static Collection materials() { return materials.values(); } + static boolean hasConfiguredFormations() { return !rules.isEmpty(); } + static boolean enabledForPlacement(net.minecraft.world.World world) { + return !rules.isEmpty() && world instanceof ServerWorld + && NaturalTerrainSurface.nativeGenerator((ServerWorld) world) != null + && zone.moddev.mc.orespawn.OreSpawnConfig.placeOreSpawnRock() + && WorldGeologyProfileManager.activeProfile().geologyMode() + == zone.moddev.mc.orespawn.OreSpawnConfig.GeologyMode.GEOME; + } + static FormationMaterial material(BlockState state) { return materials.get(state); } + public static GeologyColumn wrap(ServerWorld world, GeologyColumn base, Biome biome) { + BakedTerrainDimension terrain = GeomeConfig.terrainDimension(base.dimension()); + if (!enabledForPlacement(world) || terrain == null || !terrain.acceptsBiome(base.biome())) return base; + NaturalTerrainSurface surface; + synchronized (SURFACES) { surface = SURFACES.computeIfAbsent(world, NaturalTerrainSurface::new); } + final NaturalTerrainSurface heights = surface; + GeologyColumn current = base; + for (Rule rule : rules) { + RockFormationContext context = new RockFormationContext(world.getSeed(), current, + biome.getDefaultTemperature(), biome.getDownfall(), () -> heights.at(base.blockX(), base.blockZ())); + RockFormationColumn column = rule.compiled.prepare(context); + if (column != null) current = new Column(current, rule, column); + } + return current; + } + static void apply(IWorld region, IChunk chunk, BakedTerrainDimension terrain) { + if (!(region.getWorld() instanceof ServerWorld)) return; + ServerWorld world = (ServerWorld) region.getWorld(); + if (!enabledForPlacement(world)) return; + GeologySampler sampler = OreSpawnApi.createSampler(world).get(); + List boxes = structures(region, chunk); + if (boxes == null) return; + BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(); + boolean changed = false; + for (int dx = 0; dx < 16; dx++) for (int dz = 0; dz < 16; dz++) { + int x = chunk.getPos().x * 16 + dx, z = chunk.getPos().z * 16 + dz; + GeologyColumn column = sampler.sampleColumn(x, z, (chunk.getTopBlockY(Heightmap.Type.WORLD_SURFACE_WG, dx, dz) + 1) - 1); + if (!(column instanceof Column)) continue; + GeologyColumn country = column; + while (country instanceof Column) country = ((Column) country).base; + for (int y = 5; y < (chunk.getTopBlockY(Heightmap.Type.WORLD_SURFACE_WG, dx, dz) + 1); y++) { + BlockState target = column.rockAt(y), parent = country.rockAt(y); + if (target.equals(parent) || protectedAt(boxes, x, y, z)) continue; + pos.setPos(x, y, z); + BlockState current = chunk.getBlockState(pos); + // Native stone patches can spill over a chunk boundary before this pass. + // They are country rock, so the planned formation still takes precedence. + if ((!current.equals(parent) && !nativeStoneVariant(current)) + || chunk.getDeferredTileEntity(pos) != null + || (chunk instanceof Chunk && ((Chunk) chunk).getTileEntity(pos, Chunk.CreateEntityType.CHECK) != null)) continue; + chunk.setBlockState(pos, target, false); + changed = true; + } + } + if (changed && chunk instanceof Chunk) ((Chunk) chunk).setModified(true); + else if (changed && chunk instanceof net.minecraft.world.chunk.ChunkPrimer) + ((net.minecraft.world.chunk.ChunkPrimer) chunk).setModified(true); + } + static boolean nativeStoneVariant(BlockState state) { + Block block = state.getBlock(); + return block == net.minecraft.block.Blocks.STONE || block == net.minecraft.block.Blocks.GRANITE + || block == net.minecraft.block.Blocks.DIORITE || block == net.minecraft.block.Blocks.ANDESITE; + } + + private static List structures(IWorld world, IChunk chunk) { + List boxes = new ArrayList<>(); + for (StructureStart start : chunk.getStructureStarts().values()) + if (start != null && start.isValid()) boxes.add(start.getBoundingBox()); + for (Map.Entry entry : chunk.getStructureReferences().entrySet()) { + for (long packed : entry.getValue()) { + int x = (int) packed, z = (int) (packed >>> 32); + if (world instanceof WorldGenRegion && !((WorldGenRegion) world).chunkExists(x, z)) + return null; // An unavailable structure start makes this chunk unsafe to change. + if (!(world instanceof WorldGenRegion) + && !((ServerWorld) world.getWorld()).getChunkProvider().chunkExists(x, z)) return null; + StructureStart start = world.getChunk(x, z).getStructureStart(entry.getKey()); + if (start == null) return null; + if (start.isValid()) boxes.add(start.getBoundingBox()); + } + } + return boxes; + } + + private static boolean protectedAt(List boxes, int x, int y, int z) { + for (net.minecraft.util.math.MutableBoundingBox box : boxes) + if (x >= box.minX && x <= box.maxX && y >= box.minY && y <= box.maxY + && z >= box.minZ && z <= box.maxZ) return true; + return false; + } + private static final class Rule { + final ResourceLocation id; final int priority, revision; final CompiledRockFormation compiled; + Rule(ResourceLocation id, int priority, int revision, CompiledRockFormation compiled) { + this.id = id; this.priority = priority; this.revision = revision; this.compiled = compiled; + } + } + private static final class Column implements GeologyColumn { + final GeologyColumn base; final Rule rule; final RockFormationColumn column; + Column(GeologyColumn base, Rule rule, RockFormationColumn column) { this.base = base; this.rule = rule; this.column = column; } + public ResourceLocation dimension() { return base.dimension(); } + public ResourceLocation biome() { return base.biome(); } + public ResourceLocation geome() { return base.geome(); } + public int blockX() { return base.blockX(); } + public int blockZ() { return base.blockZ(); } + public int surfaceY() { return base.surfaceY(); } + public BlockState rockAt(int y) { FormationMaterial m = column.at(y); return m == null ? base.rockAt(y) : m.state(); } + public Optional familyAt(int y) { FormationMaterial m = column.at(y); return m == null ? base.familyAt(y) : m.family(); } + public Optional formationAt(int y) { + FormationMaterial m = column.at(y); + if (m == null) return base.formationAt(y); + BlockState parent = column.parentAt(y); + return Optional.of(new FormationSample(rule.id, rule.revision, parent == null ? base.rockAt(y) : parent, m)); + } + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/NaturalTerrainSurface.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/NaturalTerrainSurface.java new file mode 100644 index 00000000..6bfd2908 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/NaturalTerrainSurface.java @@ -0,0 +1,27 @@ +package zone.moddev.mc.orespawn.worldgen; + +import java.lang.ref.WeakReference; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.gen.ChunkGenerator; +import net.minecraft.world.gen.OverworldChunkGenerator; + +/** Native density heights, cached without requesting or constructing world chunks. */ +final class NaturalTerrainSurface { + private final WeakReference world; + NaturalTerrainSurface(ServerWorld world) { this.world = new WeakReference<>(world); } + + static OverworldChunkGenerator nativeGenerator(ServerWorld world) { + ChunkGenerator generator = world.getChunkProvider().getChunkGenerator(); + // Custom subclasses can change terrain or population order independently. + return generator != null && generator.getClass() == OverworldChunkGenerator.class + ? (OverworldChunkGenerator) generator : null; + } + + int at(int x, int z) { + ServerWorld world = this.world.get(); + if (world == null) return -1; + OverworldChunkGenerator generator = nativeGenerator(world); + if (generator == null) return -1; + return NativeDensityTerrain.chunk(generator, x >> 4, z >> 4).terrainTop(x & 15, z & 15); + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/OreRetrogenManager.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/OreRetrogenManager.java index f9293baa..8de099ba 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/OreRetrogenManager.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/OreRetrogenManager.java @@ -1,25 +1,25 @@ package zone.moddev.mc.orespawn.worldgen; +import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import net.minecraft.nbt.CompoundNBT; -import net.minecraft.util.ResourceLocation; import net.minecraft.world.server.ServerWorld; import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.chunk.ChunkStatus; import net.minecraft.world.chunk.Chunk; -import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.world.ChunkDataEvent; +import net.minecraftforge.event.TickEvent; -/** Updates existing chunks in small batches, using markers to avoid repeating ore and bedrock work. */ +/** Updates loaded chunks in small batches and retains the revision each chunk actually completed. */ public final class OreRetrogenManager { private static final String ROOT_TAG = "OreSpawn"; private static final String REVISION_TAG = "generation_revision"; private static final ConcurrentLinkedQueue QUEUE = new ConcurrentLinkedQueue<>(); private static final Set QUEUED = ConcurrentHashMap.newKeySet(); - private static final Set COMPLETE = ConcurrentHashMap.newKeySet(); + private static final Map COMPLETE = new ConcurrentHashMap<>(); + private static final Set GENERATED_THIS_SESSION = ConcurrentHashMap.newKeySet(); private static volatile Settings settings = Settings.DISABLED; private OreRetrogenManager() { @@ -34,25 +34,46 @@ public static void refreshWorldConfig() { public static void onChunkLoad(ChunkDataEvent.Load event) { Settings current = settings; - if ((!current.oreEnabled && !current.bedrockEnabled) - || event.getStatus() != ChunkStatus.Type.LEVELCHUNK + if (event.getStatus() != net.minecraft.world.chunk.ChunkStatus.Type.LEVELCHUNK || !(event.getWorld() instanceof ServerWorld) || !(event.getChunk() instanceof Chunk)) return; ServerWorld level = (ServerWorld) event.getWorld(); Chunk chunk = (Chunk) event.getChunk(); + ChunkKey key = new ChunkKey(level, chunkKey(chunk.getPos())); CompoundNBT marker = event.getData().getCompound(ROOT_TAG); - if (!current.force && marker.getInt(REVISION_TAG) == current.revision) return; - enqueue(level, chunk); + if (!marker.contains(REVISION_TAG, 3) && event.getData().contains("Status", 8)) { + // Forge 28 loads Level but saves the whole document. Older releases wrote only at the root. + try { + CompoundNBT disk = level.getChunkProvider().chunkManager.readChunk(chunk.getPos()); + if (disk != null) marker = disk.getCompound(ROOT_TAG); + } catch (java.io.IOException failure) { + org.apache.logging.log4j.LogManager.getLogger().warn( + "Could not read the older OreSpawn marker for {}; skipping automatic retrogen", chunk.getPos(), failure); + return; + } + } + Integer revision = marker.contains(REVISION_TAG, 3) && marker.getInt(REVISION_TAG) >= 0 + ? marker.getInt(REVISION_TAG) : null; + // Minecraft builds fresh NBT on every save, so keep loaded markers even while retrogen is off. + if (revision == null) COMPLETE.remove(key); + else COMPLETE.put(key, revision); + if ((!current.oreEnabled && !current.bedrockEnabled) + || (!current.force && revision != null && revision == current.revision)) return; + enqueue(level, chunk, false); } public static void onChunkSave(ChunkDataEvent.Save event) { if (!(event.getWorld() instanceof ServerWorld)) return; ServerWorld level = (ServerWorld) event.getWorld(); - ChunkKey key = new ChunkKey(WorldIds.dimension(level), event.getChunk().getPos().asLong()); - if (!COMPLETE.contains(key)) return; + ChunkKey key = new ChunkKey(level, chunkKey(event.getChunk().getPos())); + Integer revision = COMPLETE.get(key); + if (revision == null) return; CompoundNBT marker = event.getData().getCompound(ROOT_TAG); - marker.putInt(REVISION_TAG, settings.revision); + marker.putInt(REVISION_TAG, revision); event.getData().put(ROOT_TAG, marker); + CompoundNBT levelData = event.getData().getCompound("Level"); + levelData.put(ROOT_TAG, marker.copy()); + event.getData().put("Level", levelData); } public static void onServerTick(TickEvent.ServerTickEvent event) { @@ -60,28 +81,40 @@ public static void onServerTick(TickEvent.ServerTickEvent event) { for (int i = 0; i < settings.chunksPerTick; i++) { QueuedChunk queued = QUEUE.poll(); if (queued == null) return; - QUEUED.remove(queued.key); - if (queued.level.getChunkProvider().getChunk(queued.chunk.getPos().x, - queued.chunk.getPos().z, ChunkStatus.FULL, false) != queued.chunk) continue; - Settings current = settings; - if (current.oreEnabled) OreSpawnOreGeneration.retrogen(queued.level, queued.chunk); - if (current.bedrockEnabled) FlatBedrockFeature.flattenChunk(queued.level, queued.chunk); - queued.chunk.setModified(true); - COMPLETE.add(queued.key); + try { + Settings current = settings; + if (!current.oreEnabled && !current.bedrockEnabled) continue; + ChunkPos queuedPos = queued.chunk.getPos(); + if (loadedChunk(queued.level, queuedPos.x, queuedPos.z) != queued.chunk) continue; + Integer revision = COMPLETE.get(queued.key); + if (!queued.explicit && !current.force && revision != null && revision == current.revision) continue; + if (current.oreEnabled) OreSpawnOreGeneration.retrogen(queued.level, queued.chunk); + if (current.bedrockEnabled) FlatBedrockFeature.flattenChunk(queued.level, queued.chunk); + COMPLETE.put(queued.key, current.revision); + GENERATED_THIS_SESSION.add(queued.key); + queued.chunk.setModified(true); + } finally { + QUEUED.remove(queued.key); + } } } - static void markGenerated(ResourceLocation dimension, ChunkPos chunk) { - COMPLETE.add(new ChunkKey(dimension, chunk.asLong())); + static void markGenerated(ServerWorld level, ChunkPos chunk) { + ChunkKey key = new ChunkKey(level, chunkKey(chunk)); + COMPLETE.put(key, settings.revision); + GENERATED_THIS_SESSION.add(key); + } + + static boolean generatedThisSession(ServerWorld level, ChunkPos chunk) { + return GENERATED_THIS_SESSION.contains(new ChunkKey(level, chunkKey(chunk))); } public static int queueLoadedArea(ServerWorld level, ChunkPos center, int radius) { int count = 0; for (int x = center.x - radius; x <= center.x + radius; x++) { for (int z = center.z - radius; z <= center.z + radius; z++) { - net.minecraft.world.chunk.IChunk loaded = level.getChunkProvider() - .getChunk(x, z, ChunkStatus.FULL, false); - if (loaded instanceof Chunk && enqueue(level, (Chunk) loaded)) count++; + Chunk chunk = loadedChunk(level, x, z); + if (chunk != null && enqueue(level, chunk, true)) count++; } } return count; @@ -91,20 +124,48 @@ public static int queuedCount() { return QUEUE.size(); } + /** Session bookkeeping only; this does not load NBT, enqueue work or write a marker. */ + public static com.google.gson.JsonObject diagnosticStatus(ServerWorld level, ChunkPos position) { + Settings current = settings; + ChunkKey key = new ChunkKey(level, chunkKey(position)); + com.google.gson.JsonObject result = new com.google.gson.JsonObject(); + result.addProperty("enabled", current.oreEnabled); + result.addProperty("bedrock_enabled", current.bedrockEnabled); + result.addProperty("force", current.force); + result.addProperty("configured_revision", current.revision); + result.addProperty("chunks_per_tick", current.chunksPerTick); + result.addProperty("queue_size", QUEUE.size()); + result.addProperty("chunk_queued", QUEUED.contains(key)); + result.addProperty("chunk_generation_completed_this_session", GENERATED_THIS_SESSION.contains(key)); + result.addProperty("persisted_marker", "unknown: not read by this command"); + return result; + } + + public static void clear() { QUEUE.clear(); QUEUED.clear(); COMPLETE.clear(); + GENERATED_THIS_SESSION.clear(); settings = Settings.DISABLED; } - private static boolean enqueue(ServerWorld level, Chunk chunk) { - ChunkKey key = new ChunkKey(WorldIds.dimension(level), chunk.getPos().asLong()); + private static boolean enqueue(ServerWorld level, Chunk chunk, boolean explicit) { + ChunkKey key = new ChunkKey(level, chunkKey(chunk.getPos())); if (!QUEUED.add(key)) return false; - QUEUE.add(new QueuedChunk(level, chunk, key)); + QUEUE.add(new QueuedChunk(level, chunk, key, explicit)); return true; } + private static Chunk loadedChunk(ServerWorld level, int x, int z) { + return level.getChunkProvider().func_225313_a(x, z); + } + + private static long chunkKey(ChunkPos pos) { + return ((long) pos.x & 0xFFFFFFFFL) | (((long) pos.z & 0xFFFFFFFFL) << 32); + } + + private static final class Settings { static final Settings DISABLED = new Settings(false, false, false, 1, 0); final boolean oreEnabled; @@ -126,26 +187,28 @@ private static final class QueuedChunk { final ServerWorld level; final Chunk chunk; final ChunkKey key; - QueuedChunk(ServerWorld level, Chunk chunk, ChunkKey key) { + final boolean explicit; + QueuedChunk(ServerWorld level, Chunk chunk, ChunkKey key, boolean explicit) { this.level = level; this.chunk = chunk; this.key = key; + this.explicit = explicit; } } private static final class ChunkKey { - final ResourceLocation dimension; + final ServerWorld level; final long position; - ChunkKey(ResourceLocation dimension, long position) { - this.dimension = dimension; + ChunkKey(ServerWorld level, long position) { + this.level = level; this.position = position; } - @Override public int hashCode() { return (31 * dimension.hashCode()) + Long.hashCode(position); } + @Override public int hashCode() { return (31 * System.identityHashCode(level)) + Long.hashCode(position); } @Override public boolean equals(Object value) { if (this == value) return true; if (!(value instanceof ChunkKey)) return false; ChunkKey other = (ChunkKey) value; - return position == other.position && dimension.equals(other.dimension); + return position == other.position && level == other.level; } } } diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSourcePolicies.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSourcePolicies.java index 641feaf0..8d8346ca 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSourcePolicies.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSourcePolicies.java @@ -166,11 +166,48 @@ static ResourceLocation placementChannel(JsonObject rule) { ? rule.getAsJsonObject("pattern") : null; if (pattern != null) { ResourceLocation type = resource(string(pattern, "type", "")); - if (type != null) return type; + if (type != null) return patternChannel(type); } String legacy = string(rule, "pattern", ""); ResourceLocation type = legacy.indexOf(':') >= 0 ? resource(legacy) : null; - return type != null ? type : STANDARD; + return type != null ? patternChannel(type) : STANDARD; + } + + static ResourceLocation patternChannel(ResourceLocation pattern) { + if ("orespawn".equals(pattern.getNamespace())) { + switch (pattern.getPath()) { + case "default": + case "vein": + case "normal_cloud": + case "precision": + case "clusters": + case "underfluids": + return STANDARD; + default: + break; + } + } + return pattern; + } + + static boolean legacyChannelSelection(JsonObject profile, ResourceLocation source, + ResourceLocation domain, ResourceLocation savedChannel, ResourceLocation currentChannel) { + if (!STANDARD.equals(currentChannel) || STANDARD.equals(savedChannel) + || !STANDARD.equals(patternChannel(savedChannel))) return false; + JsonObject ore = readObject(readObject(profile, "ores"), source.toString()); + JsonObject dimensions = readObject(ore, "dimensions"); + JsonObject rule = dimensions.has(domain.toString()) ? readObject(dimensions, domain.toString()) + : readObject(readObject(ore, "dimension_selectors"), domain.toString()); + // A saved inferred name may still select its original rule. An explicit channel wins. + if (rule.has("placement_channel")) return false; + JsonElement pattern = rule.get("pattern"); + String oldChannel = pattern != null && pattern.isJsonObject() + ? string(pattern.getAsJsonObject(), "type", "") : string(rule, "pattern", ""); + return savedChannel.toString().equals(oldChannel); + } + + private static JsonObject readObject(JsonObject parent, String key) { + return parent.has(key) && parent.get(key).isJsonObject() ? parent.getAsJsonObject(key) : new JsonObject(); } static Inference inferMaterial(Iterable blockTags) { @@ -195,11 +232,12 @@ private static Map discover(JsonObject root) { for (Entry oreEntry : ores.entrySet()) { if (!oreEntry.getValue().isJsonObject()) continue; JsonObject ore = oreEntry.getValue().getAsJsonObject(); - boolean oreActive = bool(ore, "enabled", true) - && (!bool(ore, "native_generation", false) || manageVanillaOres); ResourceLocation blockId = resource(string(ore, "block", oreEntry.getKey())); Block block = blockId == null ? null : ForgeRegistries.BLOCKS.getValue(blockId); if (block == null || block == Blocks.AIR) continue; + boolean nativeOrImportedVanilla = bool(ore, "native_generation", false) + || OreSpawnOreGeneration.isImportedVanillaOre(resource(oreEntry.getKey()), block, ore); + boolean oreActive = bool(ore, "enabled", true) && (!nativeOrImportedVanilla || manageVanillaOres); int metadata = integer(ore, "metadata", 0); Inference inferred = inferMaterial(root, blockTags(block)); ResourceLocation material = resource(string(ore, "material", "")); diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSpawnOreGeneration.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSpawnOreGeneration.java index 4366eeca..942218b5 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSpawnOreGeneration.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSpawnOreGeneration.java @@ -20,33 +20,30 @@ import zone.moddev.mc.orespawn.OreSpawn; import zone.moddev.mc.orespawn.api.CompiledOrePattern; import zone.moddev.mc.orespawn.api.GeologySampler; -import zone.moddev.mc.orespawn.api.OreGenerationContext; import zone.moddev.mc.orespawn.api.OreDimensionSelector; +import zone.moddev.mc.orespawn.api.OreGenerationContext; import zone.moddev.mc.orespawn.api.OreSpawnApi; -import zone.moddev.mc.orespawn.api.OrePlacementContext; import zone.moddev.mc.orespawn.init.OreSpawnPatterns; import net.minecraft.util.math.BlockPos; import net.minecraft.util.registry.Registry; import net.minecraft.util.ResourceLocation; import net.minecraft.world.server.ServerWorld; -import net.minecraft.tags.BlockTags; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.IWorld; +import net.minecraft.world.chunk.IChunk; +import net.minecraft.world.gen.WorldGenRegion; +import net.minecraft.world.gen.feature.ConfiguredFeature; +import net.minecraft.world.gen.placement.Placement; +import net.minecraft.world.gen.feature.NoFeatureConfig; +import net.minecraft.world.gen.placement.IPlacementConfig; +import net.minecraft.tags.BlockTags; import net.minecraft.world.biome.Biome; import net.minecraft.block.Block; import net.minecraft.block.Blocks; import net.minecraft.block.BlockState; -import net.minecraft.world.chunk.IChunk; import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.gen.GenerationStage; -import net.minecraft.world.gen.WorldGenRegion; -import net.minecraft.world.gen.feature.ConfiguredFeature; -import net.minecraft.world.gen.feature.Feature; -import net.minecraft.world.gen.feature.NoFeatureConfig; -import net.minecraft.world.gen.placement.Placement; -import net.minecraft.world.gen.placement.NoPlacementConfig; import net.minecraft.fluid.Fluid; import net.minecraftforge.registries.ForgeRegistries; @@ -55,6 +52,8 @@ /** One dynamic feature for every OreSpawn-managed ore and dimension. */ public final class OreSpawnOreGeneration extends ContextFeature { + /** Send worldgen changes without triggering neighbour updates. */ + private static final int GENERATION_WRITE_FLAGS = 2; private static final Logger LOGGER = LogManager.getLogger(); public static final OreSpawnOreGeneration FEATURE = new OreSpawnOreGeneration(); private static final BakedOre[] NO_ORES = new BakedOre[0]; @@ -65,8 +64,15 @@ public final class OreSpawnOreGeneration extends ContextFeature private static Map resolvedHostRules = Collections.emptyMap(); private static volatile Map oresByDimension = EMPTY_DIMENSIONS; private static volatile Map> vanillaTakeoverOutputs = Collections.emptyMap(); + private static volatile Map> backgroundGenerationScales = + Collections.emptyMap(); + private static volatile Map> materialBackgroundGenerationScales = + Collections.emptyMap(); private static volatile BakedOre[] selectorOres = NO_ORES; private static volatile Set selectorVanillaTakeoverOutputs = Collections.emptySet(); + private static volatile Map selectorBackgroundGenerationScales = Collections.emptyMap(); + private static volatile Map selectorMaterialBackgroundGenerationScales = + Collections.emptyMap(); private static volatile BakedGeomeConfig geomeConfig; private static volatile GeomeGeology classifier; private static volatile long classifierSeed = Long.MIN_VALUE; @@ -74,13 +80,101 @@ public final class OreSpawnOreGeneration extends ContextFeature ThreadLocal.withInitial(GenerationScratch::new); private OreSpawnOreGeneration() { - super(NoFeatureConfig::deserialize); + super(NoFeatureConfig::deserialize); setRegistryName(OreSpawn.MODID, "managed_ores"); } + /** Reads the same baked placement budget used by generation without rolling an attempt. */ + public static JsonObject diagnosticRule(ServerWorld level, BlockPos position, ResourceLocation ruleId) { + IChunk chunk = (level.getChunkProvider().chunkExists(position.getX() >> 4, position.getZ() >> 4) + ? (Chunk) level.getChunkProvider().func_225313_a(position.getX() >> 4, position.getZ() >> 4) : null); + if (chunk == null) throw new IllegalArgumentException("The target chunk is not loaded"); + ResourceLocation dimension = WorldIds.dimension(level); + JsonObject result = new JsonObject(); + result.addProperty("rule", ruleId.toString()); + result.addProperty("dimension", dimension.toString()); + result.addProperty("at", position.getX() + "," + position.getY() + "," + position.getZ()); + JsonObject root = WorldGeologyProfileManager.activeProfile().rootCopy(); + JsonObject definition = objectOrEmpty(objectOrEmpty(root, "ores"), ruleId.toString()); + if (definition.entrySet().isEmpty()) throw new IllegalArgumentException("Unknown managed ore rule " + ruleId); + result.addProperty("manage_vanilla_ores", bool(root, "manage_vanilla_ores", false)); + result.addProperty("configured_enabled", bool(definition, "enabled", true)); + result.add("configured_rule", zone.moddev.mc.orespawn.util.JsonCopies.copy(definition)); + JsonObject explicit = objectOrEmpty(definition, "dimensions"); + JsonObject dimensionRule = explicit.has(dimension.toString()) ? objectOrEmpty(explicit, dimension.toString()) + : selectorAllows(dimension) + ? objectOrEmpty(objectOrEmpty(definition, "dimension_selectors"), OreDimensionSelector.ALL_EXCEPT_NETHER_AND_END.id().toString()) : new JsonObject(); + result.addProperty("configured_dimension_present", !dimensionRule.entrySet().isEmpty()); + result.addProperty("configured_dimension_enabled", !dimensionRule.entrySet().isEmpty() && bool(dimensionRule, "enabled", true)); + JsonObject sourcePolicies = new JsonObject(); + for (Entry policy : objectOrEmpty(root, OreSourcePolicies.SECTION).entrySet()) { + if (!policy.getValue().isJsonObject()) continue; + JsonObject value = policy.getValue().getAsJsonObject(); + if (!value.has("candidates") || !value.get("candidates").isJsonArray()) continue; + for (JsonElement candidate : value.getAsJsonArray("candidates")) { + if (candidate.isJsonObject() && ruleId.toString().equals(string(candidate.getAsJsonObject(), "source_id", ""))) { + JsonObject selection = new JsonObject(); + for (String key : new String[]{"mode", "output_mode", "outputs", "placement_sources", "dormant"}) + if (value.has(key)) selection.add(key, zone.moddev.mc.orespawn.util.JsonCopies.copy(value.get(key))); + sourcePolicies.add(policy.getKey(), selection); + break; + } + } + } + result.add("source_policies", sourcePolicies); + BakedOre selected = null; + for (BakedOre candidate : oresForDimension(dimension)) { + if (candidate.ruleId.equals(ruleId)) { selected = candidate; break; } + for (BakedSource source : candidate.arbitrationSources) if (source.sourceId.equals(ruleId.toString())) selected = candidate; + } + result.addProperty("in_effective_placement_budget", selected != null); + if (selected == null) { + ResourceLocation outputId = resource(string(definition, "block", ruleId.toString())); + Block output = outputId == null ? null : ForgeRegistries.BLOCKS.getValue(outputId); + boolean vanillaOff = !bool(root, "manage_vanilla_ores", false) && output != null + && (bool(definition, "native_generation", false) || isImportedVanillaOre(ruleId, output, definition)); + result.addProperty("reason", !bool(definition, "enabled", true) ? "disabled" + : vanillaOff ? "vanilla_management_off" : "dimension_disabled_invalid_or_not_selected_by_source_policy"); + } else { + Biome biome = chunk.getBiomes()[8 * 16 + 8]; + ResourceLocation biomeId = biome == null ? null : WorldIds.biome(biome); + BlockState host = chunk.getBlockState(position); + Double chance = selected.hostStates.get(host); + if (chance == null) chance = selected.hostBlocks.get(host.getBlock()); + RockFamily family = geomeConfig.familyOf(host); + boolean familyMatches = family != null && geomeConfig.isOreReplaceable(host) + && (selected.familyMask & (1 << family.ordinal())) != 0; + double hostChance = chance == null ? (familyMatches ? 1.0D : 0.0D) : chance; + double frequency = scaledManagedFrequency(selected.frequency, selected.backgroundController, + channelBackgroundScale(selected.materialDeclared ? selected.material : null, selected.channel, + materialBackgroundScale(dimension, selected.materialDeclared ? selected.material : null), + backgroundScale(dimension, selected.output.getBlock()))); + if (WorldIds.OVERWORLD.equals(dimension) && biome != null) { + int geome = new GeomeGeology(level.getSeed(), geomeConfig).classifyColumn(biome, biomeId, + (chunk.getPos().x << 4) + 8, (chunk.getPos().z << 4) + 8, new double[geomeConfig.geomeCount()]); + frequency *= selected.geomeWeights[geome]; + } + result.addProperty("placement_source", selected.ruleId.toString()); + result.addProperty("placement_channel", selected.channel.toString()); + result.addProperty("biome_test_uses_chunk_centre", true); + result.addProperty("biome", String.valueOf(biomeId)); + result.addProperty("biome_matches", biome != null && selected.acceptsBiome(biome, biomeId)); + result.addProperty("height_matches", position.getY() >= selected.minY && position.getY() <= selected.maxY); + result.addProperty("min_y", selected.minY); result.addProperty("max_y", selected.maxY); + result.addProperty("min_quantity", selected.minQuantity); result.addProperty("max_quantity", selected.maxQuantity); + result.addProperty("current_host_state", net.minecraft.command.arguments.BlockStateParser.toString(host)); + result.addProperty("current_host_family", family == null ? "unclassified" : family.name()); + result.addProperty("current_host_chance", hostChance); + result.addProperty("expected_attempts_per_chunk", frequency); + result.addProperty("retrogen_rule_enabled", selected.retrogen); + } + result.addProperty("limitation", "Eligibility is not a placement prediction. Random geometry, exposure rolls and private extension checks are not evaluated; current blocks do not identify their historical generator."); + return result; + } + public static void registerConfiguredFeatures() { configuredFeature = net.minecraft.world.biome.Biome.createDecoratedFeature( - FEATURE, new NoFeatureConfig(), Placement.NOPE, new NoPlacementConfig()); + FEATURE, new NoFeatureConfig(), Placement.NOPE, net.minecraft.world.gen.placement.IPlacementConfig.NO_PLACEMENT_CONFIG); VanillaOreFeatureGate.register(); refreshWorldConfig(); } @@ -101,8 +195,12 @@ private static void refreshWorldConfig(Map previous) { resolvedHostRules = resolved; oresByDimension = baked.byDimension; vanillaTakeoverOutputs = baked.vanillaOutputs; + backgroundGenerationScales = baked.backgroundGenerationScales; + materialBackgroundGenerationScales = baked.materialBackgroundGenerationScales; selectorOres = baked.selectorOres; selectorVanillaTakeoverOutputs = baked.selectorVanillaOutputs; + selectorBackgroundGenerationScales = baked.selectorBackgroundGenerationScales; + selectorMaterialBackgroundGenerationScales = baked.selectorMaterialBackgroundGenerationScales; synchronized (CLASSIFIER_LOCK) { classifier = null; classifierSeed = Long.MIN_VALUE; @@ -116,6 +214,28 @@ static boolean takesOverVanillaOre(ResourceLocation dimension, Block output) { return !WorldgenBenchmark.isVanillaBaseline() && outputs != null && outputs.contains(output); } + static boolean allowsVanillaOre(ResourceLocation dimension, Block output, long worldSeed, + int chunkX, int chunkZ) { + if (takesOverVanillaOre(dimension, output)) return false; + double scale = backgroundScale(dimension, output); + if (scale >= 1.0D) return true; + if (scale <= 0.0D) return false; + ResourceLocation outputId = ForgeRegistries.BLOCKS.getKey(output); + return passesBackgroundScale(dimension, outputId, worldSeed, chunkX, chunkZ, scale); + } + + static boolean passesBackgroundScale(ResourceLocation dimension, ResourceLocation outputId, + long worldSeed, int chunkX, int chunkZ, double scale) { + if (scale >= 1.0D) return true; + if (scale <= 0.0D) return false; + long identity = ((long) dimension.toString().hashCode() << 32) + ^ (outputId == null ? 0L : outputId.toString().hashCode() & 0xFFFFFFFFL); + long chunk = ((long) chunkX & 0xFFFFFFFFL) | (((long) chunkZ & 0xFFFFFFFFL) << 32); + long value = mix(worldSeed, chunk, identity); + double sample = (double) (value >>> 11) * 0x1.0p-53; + return sample < scale; + } + static boolean hasManagedOres(ResourceLocation dimension) { return oresForDimension(dimension).length != 0; } @@ -124,7 +244,8 @@ static boolean needsVanillaOreGate(ResourceLocation dimension) { if (WorldGeologyProfileManager.activeProfile().suppressAllOreFeatures()) return true; Set outputs = vanillaTakeoverOutputs.get(dimension); if (outputs == null && selectorAllows(dimension)) outputs = selectorVanillaTakeoverOutputs; - return outputs != null && !outputs.isEmpty(); + Map scales = scalesForDimension(dimension); + return (outputs != null && !outputs.isEmpty()) || !scales.isEmpty(); } @Override @@ -142,9 +263,11 @@ boolean place(FeaturePlaceContext context) { setCenter(scratch.cursor, chunk); Biome biome = world.getBiome(scratch.cursor); ResourceLocation biomeId = WorldIds.biome(biome); - boolean changed = generateChunk(world, chunk, biome, biomeId, dimension, + boolean changed = generateChunk((ServerWorld) world.getWorld(), world, chunk, biome, biomeId, dimension, world.getSeed(), context.random(), ores, false, scratch); - OreRetrogenManager.markGenerated(dimension, chunk.getPos()); + if (world.getWorld() instanceof ServerWorld) { + OreRetrogenManager.markGenerated((ServerWorld) world.getWorld(), chunk.getPos()); + } return changed; } @@ -158,7 +281,7 @@ static boolean retrogen(ServerWorld level, Chunk chunk) { setCenter(scratch.cursor, chunk); Biome biome = level.getBiome(scratch.cursor); ResourceLocation biomeId = WorldIds.biome(biome); - return generateChunk(null, chunk, biome, biomeId, dimension, level.getSeed(), + return generateChunk(level, null, chunk, biome, biomeId, dimension, level.getSeed(), new Random(seed), ores, true, scratch); } @@ -167,13 +290,14 @@ private static void setCenter(BlockPos.MutableBlockPos cursor, IChunk chunk) { cursor.setPos(chunkPos.getXStart() + 8, 0, chunkPos.getZStart() + 8); } - private static boolean generateChunk(IWorld world, IChunk chunk, Biome biome, + private static boolean generateChunk(ServerWorld level, IWorld world, IChunk chunk, Biome biome, ResourceLocation biomeId, ResourceLocation dimension, long worldSeed, Random random, BakedOre[] ores, boolean retrogenOnly, GenerationScratch scratch) { ChunkPos chunkPos = chunk.getPos(); int centerX = chunkPos.getXStart() + 8; int centerZ = chunkPos.getZStart() + 8; + Optional geologySampler = scratch.geologySampler(level, dimension); int geome = -1; if (WorldIds.OVERWORLD.equals(dimension)) { geome = classifier(worldSeed).classifyColumn(biome, biomeId, centerX, centerZ, @@ -186,18 +310,22 @@ private static boolean generateChunk(IWorld world, IChunk chunk, Biome biome, if (!ore.acceptsBiome(biome, biomeId)) { continue; } - double frequency = ore.frequency; + ResourceLocation scalingMaterial = ore.materialDeclared ? ore.material : null; + double scale = channelBackgroundScale(scalingMaterial, ore.channel, + materialBackgroundScale(dimension, scalingMaterial), + backgroundScale(dimension, ore.output.getBlock())); + double frequency = scaledManagedFrequency(ore.frequency, ore.backgroundController, scale); if (geome >= 0) { frequency *= ore.geomeWeights[geome]; } int attempts = attemptsForFrequency(random, frequency); for (int attempt = 0; attempt < attempts; attempt++) { - changed |= placeAttempt(world, chunk, random, ore, geome, - dimension, worldSeed, attempt, scratch); + changed |= placeAttempt(world, chunk, random, ore, geome, dimension, + worldSeed, attempt, geologySampler, scratch); } } if (changed) { - chunk.setModified(true); + markChanged(chunk); } return changed; } @@ -211,8 +339,24 @@ private static long mix(long seed, long chunk, long revision) { return value ^ (value >>> 31); } + static long ordinaryOutputIdentity(ChunkPos chunk, int attemptIndex, + ResourceLocation ruleId, ResourceLocation channel) { + return mix(chunkKey(chunk), attemptIndex, + ((long) ruleId.hashCode() << 32) ^ (channel.hashCode() & 0xFFFFFFFFL)); + } + + static double outputSelectionSample(long worldSeed, ResourceLocation dimension, + ResourceLocation material, ResourceLocation channel, long outputIdentity) { + long value = mix(worldSeed, outputIdentity, + ((long) material.hashCode() << 32) + ^ (channel.hashCode() & 0xFFFFFFFFL) ^ dimension.hashCode()); + return (double) (value >>> 11) * 0x1.0p-53; + } + private static boolean placeAttempt(IWorld world, IChunk chunk, Random random, - BakedOre ore, int geome, ResourceLocation dimension, long worldSeed, int attempt, + BakedOre ore, int geome, ResourceLocation dimension, long worldSeed, + int attemptIndex, + Optional geologySampler, GenerationScratch scratch) { int minY = Math.max(ore.minY, 0); int maxY = Math.min(ore.maxY, 256 - 1); @@ -223,12 +367,8 @@ private static boolean placeAttempt(IWorld world, IChunk chunk, Random random, int y = ore.heightDistribution.sample(random, minY, maxY); int z = chunk.getPos().getZStart() + random.nextInt(16); int quantity = sampleQuantity(random, ore.minQuantity, ore.maxQuantity); - scratch.patternContext.initialize(world, chunk, random, ore, geome, - dimension, worldSeed, - ore.arbitrationSources.length == 0 ? null - : ore.outputSource(worldSeed, chunk.getPos().asLong(), attempt), - x, y, z, minY, maxY, - quantity); + scratch.patternContext.initialize(world, chunk, random, ore, geome, dimension, worldSeed, + attemptIndex, geologySampler, x, y, z, minY, maxY, quantity); return ore.pattern.place(scratch.patternContext); } @@ -252,8 +392,30 @@ private static BakedOre[] oresForDimension(ResourceLocation dimension) { return exact != null ? exact : selectorAllows(dimension) ? selectorOres : NO_ORES; } + private static Map scalesForDimension(ResourceLocation dimension) { + Map exact = backgroundGenerationScales.get(dimension); + return exact != null ? exact + : selectorAllows(dimension) ? selectorBackgroundGenerationScales : Collections.emptyMap(); + } + + private static double backgroundScale(ResourceLocation dimension, Block output) { + Double scale = scalesForDimension(dimension).get(output); + return scale == null ? 1.0D : scale.doubleValue(); + } + + private static double materialBackgroundScale(ResourceLocation dimension, ResourceLocation material) { + if (material == null) return 1.0D; + Map exact = materialBackgroundGenerationScales.get(dimension); + if (exact == null && selectorAllows(dimension)) exact = selectorMaterialBackgroundGenerationScales; + Double scale = exact == null ? null : exact.get(material); + return scale == null ? 1.0D : scale.doubleValue(); + } + private static boolean insideChunk(IChunk chunk, int x, int y, int z) { - ChunkPos pos = chunk.getPos(); + return insideChunk(chunk.getPos(), x, y, z); + } + + static boolean insideChunk(ChunkPos pos, int x, int y, int z) { return x >= pos.getXStart() && x <= pos.getXEnd() && z >= pos.getZStart() && z <= pos.getZEnd() && y >= 0 && y < 256; @@ -282,25 +444,31 @@ private static BakedOres bakeOres(JsonObject profile, BakedGeomeConfig config, Block output = oreId == null ? null : ForgeRegistries.BLOCKS.getValue(oreId); JsonObject dimensions = objectOrEmpty(oreJson, "dimensions"); JsonObject selectors = objectOrEmpty(oreJson, "dimension_selectors"); - if (output == null || output == Blocks.AIR || (dimensions.size() == 0 && selectors.size() == 0)) { + if (output == null || output == Blocks.AIR || (dimensions.entrySet().size() == 0 && selectors.entrySet().size() == 0)) { reportBakeProblem("Ignoring invalid OreSpawn-managed ore '{}'", oreEntry.getKey()); continue; } - BlockState deepOutput = blockState(oreJson, "deep_output", output.getDefaultState()); + BlockState outputState = state(output, integer(oreJson, "metadata", 0)); + BlockState deepOutput = blockState(oreJson, "deep_output", "deep_output_metadata", outputState); if (deepOutput == null) { reportBakeProblem("Ignoring OreSpawn-managed ore '{}' because its deep output is invalid", oreEntry.getKey()); continue; } int deepOutputMaxY = integer(oreJson, "deep_output_max_y", -1); - BakedOutput[] outputs = bakeOutputs(oreJson, output.getDefaultState()); + BakedOutput[] outputs = bakeOutputs(oreJson, outputState); ResourceLocation ruleId = resource(oreEntry.getKey()); if (ruleId == null) ruleId = oreId; outputBundles.put(ruleId.toString(), new BakedOutputBundle( - output.getDefaultState(), deepOutput, deepOutputMaxY, outputs)); - if (!oreEnabled || (nativeGeneration && !manageVanillaOres)) continue; - ResourceLocation material = OreSourcePolicies.material(profile, oreJson, output); - BakedOreRule rule = new BakedOreRule(output, manageVanillaOres && suppressVanilla); + outputState, deepOutput, deepOutputMaxY, outputs)); + boolean importedVanilla = !nativeGeneration && isImportedVanillaOre(ruleId, output, oreJson); + // Keep imported settings, but leave their vanilla ores alone while management is off. + if (!oreEnabled || (!manageVanillaOres && (nativeGeneration || importedVanilla))) continue; + ResourceLocation material = OreSourcePolicies.material(profile, oreJson, + output); + boolean materialDeclared = resource(string(oreJson, "material", "")) != null; + BakedOreRule rule = new BakedOreRule(ruleId, output, material, materialDeclared, + manageVanillaOres && (importedVanilla || suppressVanilla), nativeGeneration, importedVanilla); for (Entry dimensionEntry : dimensions.entrySet()) { ResourceLocation dimensionId = resource(dimensionEntry.getKey()); @@ -318,10 +486,9 @@ private static BakedOres bakeOres(JsonObject profile, BakedGeomeConfig config, if (!bool(dimension, "enabled", true)) { continue; } - BakedOre baked = bakeOre(ruleId, material, dimensionId, - output.getDefaultState(), deepOutput, deepOutputMaxY, outputs, - dimension, config, resolvedTags, retrogen, - previous.get(ruleId + "|" + dimensionId)); + BakedOre baked = bakeOre(ruleId, material, materialDeclared, dimensionId, + outputState, deepOutput, + deepOutputMaxY, outputs, dimension, config, resolvedTags, retrogen, previous.get(ruleId + "|" + dimensionId)); if (baked != null) { resolved.put(ruleId + "|" + dimensionId, baked); rule.explicit.put(dimensionId, baked); @@ -341,11 +508,9 @@ private static BakedOres bakeOres(JsonObject profile, BakedGeomeConfig config, if (!selectorEntry.getValue().isJsonObject()) continue; JsonObject selector = selectorEntry.getValue().getAsJsonObject(); if (!bool(selector, "enabled", true)) continue; - rule.selector = bakeOre(ruleId, material, selectorId, - output.getDefaultState(), deepOutput, deepOutputMaxY, outputs, - selector, config, resolvedTags, retrogen, - previous.get(ruleId + "|" + selectorId)); - if (rule.selector != null) resolved.put(ruleId + "|" + selectorId, rule.selector); + rule.selector = bakeOre(ruleId, material, materialDeclared, selectorId, + outputState, deepOutput, + deepOutputMaxY, outputs, selector, config, resolvedTags, retrogen, previous.get(ruleId + "|" + selectorId)); if (rule.selector == null) { reportBakeProblem("Ignoring invalid selector rule for OreSpawn-managed ore '{}'", oreEntry.getKey()); @@ -356,29 +521,50 @@ private static BakedOres bakeOres(JsonObject profile, BakedGeomeConfig config, Map result = new HashMap<>(); Map> vanillaOutputs = new HashMap<>(); + Map> generationScales = new HashMap<>(); + Map> materialScales = new HashMap<>(); for (ResourceLocation dimension : explicitDimensions) { List combined = new ArrayList<>(); Set suppressed = Collections.newSetFromMap(new IdentityHashMap()); + Map scales = new IdentityHashMap<>(); + Map semanticScales = new HashMap<>(); for (BakedOreRule rule : rules) { BakedOre selected = selectRule(rule.explicit, rule.explicitDimensions, rule.selector, dimension); if (selected != null) { combined.add(selected); if (rule.suppressVanilla) suppressed.add(rule.output); + if (selected.backgroundController) { + mergeBackgroundScale(scales, rule.output, selected.backgroundGenerationScale); + if (rule.materialDeclared) mergeBackgroundScale(semanticScales, + rule.material, selected.backgroundGenerationScale); + } } } combined = arbitrate(profile, combined, outputBundles); + combined = preferImportedVanilla(rules, combined); result.put(dimension, combined.toArray(new BakedOre[combined.size()])); vanillaOutputs.put(dimension, Collections.unmodifiableSet(suppressed)); + generationScales.put(dimension, Collections.unmodifiableMap(scales)); + materialScales.put(dimension, Collections.unmodifiableMap(semanticScales)); } List selectorList = new ArrayList<>(); Set selectorOutputs = Collections.newSetFromMap(new IdentityHashMap()); + Map selectorScales = new IdentityHashMap<>(); + Map selectorMaterialScales = new HashMap<>(); for (BakedOreRule rule : rules) { if (rule.selector == null) continue; selectorList.add(rule.selector); if (rule.suppressVanilla) selectorOutputs.add(rule.output); + if (rule.selector.backgroundController) { + mergeBackgroundScale(selectorScales, rule.output, + rule.selector.backgroundGenerationScale); + if (rule.materialDeclared) mergeBackgroundScale(selectorMaterialScales, + rule.material, rule.selector.backgroundGenerationScale); + } } selectorList = arbitrate(profile, selectorList, outputBundles); + selectorList = preferImportedVanilla(rules, selectorList); BakedOre[] selectorResult = selectorList.toArray(new BakedOre[selectorList.size()]); LOGGER.info("Baked {} OreSpawn-managed ore definitions across {} dimensions", rules.size(), result.size()); @@ -387,8 +573,42 @@ private static BakedOres bakeOres(JsonObject profile, BakedGeomeConfig config, immutableVanillaOutputs.put(entry.getKey(), Collections.unmodifiableSet(entry.getValue())); } return new BakedOres(Collections.unmodifiableMap(result), - Collections.unmodifiableMap(immutableVanillaOutputs), selectorResult, - Collections.unmodifiableSet(selectorOutputs)); + Collections.unmodifiableMap(immutableVanillaOutputs), + Collections.unmodifiableMap(generationScales), + Collections.unmodifiableMap(materialScales), selectorResult, + Collections.unmodifiableSet(selectorOutputs), + Collections.unmodifiableMap(selectorScales), + Collections.unmodifiableMap(selectorMaterialScales)); + } + + static boolean isImportedVanillaOre(ResourceLocation ruleId, Block output, JsonObject ore) { + // A provider-aware import may keep the provider's modern ID instead of a legacy path. + if (ruleId == null || (!ruleId.getPath().startsWith("legacy/") + && !"legacy".equals(string(ore, "source_mod", "")))) return false; + + return output == Blocks.COAL_ORE || output == Blocks.IRON_ORE || output == Blocks.GOLD_ORE + || output == Blocks.REDSTONE_ORE || output == Blocks.LAPIS_ORE + || output == Blocks.DIAMOND_ORE || output == Blocks.EMERALD_ORE || output == Blocks.NETHER_QUARTZ_ORE; + } + + private static List preferImportedVanilla(List rules, List ores) { + Map definitions = new HashMap<>(); + for (BakedOreRule rule : rules) definitions.put(rule.ruleId, rule); + + Set outputs = Collections.newSetFromMap(new IdentityHashMap()); + for (BakedOre ore : ores) { + BakedOreRule rule = definitions.get(ore.ruleId); + if (rule != null && rule.importedVanilla) outputs.add(rule.output); + } + if (outputs.isEmpty()) return ores; + + // Apply saved Ore Sources choices first, then remove any duplicate modern defaults. + List result = new ArrayList<>(); + for (BakedOre ore : ores) { + BakedOreRule rule = definitions.get(ore.ruleId); + if (rule == null || !rule.nativeGeneration || !outputs.contains(rule.output)) result.add(ore); + } + return result; } private static List arbitrate(JsonObject profile, List original, @@ -399,31 +619,44 @@ private static List arbitrate(JsonObject profile, List origi Map> groups = new LinkedHashMap<>(); for (BakedOre ore : original) { if (ore.material != null) groups.computeIfAbsent( - OreSourcePolicies.key(ore.material, ore.policyDomain), ignored -> new ArrayList<>()).add(ore); + OreSourcePolicies.key(ore.material, ore.policyDomain), + ignored -> new ArrayList<>()).add(ore); } Map> replacements = new HashMap<>(); for (Entry> entry : groups.entrySet()) { + BakedOre first = entry.getValue().get(0); String key = entry.getKey(); if (!policies.has(key) || !policies.get(key).isJsonObject()) continue; JsonObject policy = policies.getAsJsonObject(key); if (!"consolidated".equals(string(policy, "mode", "keep_separate"))) continue; + Map weights = positiveWeights(objectOrEmpty(policy, "outputs")); List sources = new ArrayList<>(); - for (Entry output : positiveWeights(objectOrEmpty(policy, "outputs")).entrySet()) { - BakedOutputBundle bundle = outputBundles.get(output.getKey()); - if (bundle == null) bundle = candidateBundle(policy, output.getKey()); - if (bundle != null) sources.add(new BakedSource(bundle, output.getValue())); + Set sourceIds = new HashSet<>(); + for (Entry selectedOutput : weights.entrySet()) { + BakedOutputBundle bundle = outputBundles.get(selectedOutput.getKey()); + if (bundle == null) bundle = candidateBundle(policy, selectedOutput.getKey()); + if (bundle != null && sourceIds.add(selectedOutput.getKey())) { + sources.add(new BakedSource(selectedOutput.getKey(), bundle, + selectedOutput.getValue().doubleValue())); + } } - Map available = new HashMap<>(); - for (BakedOre ore : entry.getValue()) available.put(ore.ruleId.toString(), ore); + if (sources.isEmpty()) { + replacements.put(key, Collections.emptyList()); + continue; + } + Map available = new LinkedHashMap<>(); + for (BakedOre candidate : entry.getValue()) available.put(candidate.ruleId, candidate.channel); + Map placements = selectedPlacementRules( + profile, first.material, first.policyDomain, available); List selected = new ArrayList<>(); - for (Entry placement : objectOrEmpty(policy, "placement_sources").entrySet()) { - ResourceLocation channel = resource(placement.getKey()); - String sourceId; - try { sourceId = placement.getValue().getAsString(); } - catch (RuntimeException invalid) { continue; } - BakedOre ore = available.get(sourceId); - if (ore != null && channel != null && channel.equals(ore.channel) && !sources.isEmpty()) { - selected.add(ore.withSources(sources)); + for (Entry placement : placements.entrySet()) { + ResourceLocation source = placement.getValue(); + ResourceLocation channel = available.get(source); + for (BakedOre candidate : entry.getValue()) { + if (channel.equals(candidate.channel) && source.equals(candidate.ruleId)) { + selected.add(candidate.withSources(sources)); + break; + } } } replacements.put(key, selected); @@ -432,15 +665,95 @@ private static List arbitrate(JsonObject profile, List origi List result = new ArrayList<>(); Set emitted = new HashSet<>(); for (BakedOre ore : original) { - String key = ore.material == null ? null + String groupKey = ore.material == null ? null : OreSourcePolicies.key(ore.material, ore.policyDomain); - List selected = key == null ? null : replacements.get(key); - if (selected == null) result.add(ore); - else if (emitted.add(key)) result.addAll(selected); + List replacement = groupKey == null ? null : replacements.get(groupKey); + if (replacement == null) result.add(ore); + else if (emitted.add(groupKey)) result.addAll(replacement); } return result; } + /** Returns null for the behaviour-preserving separate mode. */ + static Map selectedPlacementRules(JsonObject profile, + ResourceLocation material, ResourceLocation domain, + Map availableSourceChannels) { + if (!profile.has(OreSourcePolicies.SECTION) + || !profile.get(OreSourcePolicies.SECTION).isJsonObject()) return null; + JsonObject policies = profile.getAsJsonObject(OreSourcePolicies.SECTION); + String key = OreSourcePolicies.key(material, domain); + if (!policies.has(key) || !policies.get(key).isJsonObject()) return null; + JsonObject policy = policies.getAsJsonObject(key); + if (!"consolidated".equals(string(policy, "mode", "keep_separate"))) return null; + Map result = new LinkedHashMap<>(); + JsonObject placements = objectOrEmpty(policy, "placement_sources"); + + for (Entry placement : placements.entrySet()) { + ResourceLocation channel = resource(placement.getKey()); + ResourceLocation source; + try { source = resource(placement.getValue().getAsString()); } + catch (RuntimeException invalid) { continue; } + + if (channel == null || source == null) { + continue; + } + + ResourceLocation currentChannel = availableSourceChannels.get(source); + boolean retainedAlias = !placements.has(OreSourcePolicies.STANDARD.toString()) + && legacyChannelSelection(profile, source, domain, channel, currentChannel); + + if (channel.equals(currentChannel) || retainedAlias) { + result.put(channel, source); + } + } + return Collections.unmodifiableMap(result); + } + + private static boolean legacyChannelSelection(JsonObject profile, ResourceLocation source, + ResourceLocation domain, ResourceLocation savedChannel, ResourceLocation currentChannel) { + if (!OreSourcePolicies.STANDARD.equals(currentChannel) + || !OreSourcePolicies.STANDARD.equals(OreSourcePolicies.patternChannel(savedChannel))) { + return false; + } + + JsonObject ore = objectOrEmpty(objectOrEmpty(profile, "ores"), source.toString()); + JsonObject dimensions = objectOrEmpty(ore, "dimensions"); + JsonObject placement = dimensions.has(domain.toString()) + ? objectOrEmpty(dimensions, domain.toString()) + : objectOrEmpty(objectOrEmpty(ore, "dimension_selectors"), domain.toString()); + + // Honour the old inferred name without changing a saved selection. A newer + // explicit channel or standard-channel choice must not fall back to this alias. + if (placement.has("placement_channel")) { + return false; + } + + JsonObject pattern = objectOrEmpty(placement, "pattern"); + ResourceLocation oldChannel = resource(pattern.has("type") + ? string(pattern, "type", "") : string(placement, "pattern", "")); + return savedChannel.equals(oldChannel); + } + + static int weightedIndex(double sample, double... weights) { + double total = 0.0D; + for (double weight : weights) if (Double.isFinite(weight) && weight > 0.0D) total += weight; + if (total <= 0.0D) return -1; + double choice = weightedChoice(sample, total); + int last = -1; + for (int index = 0; index < weights.length; index++) { + double weight = weights[index]; + if (!Double.isFinite(weight) || weight <= 0.0D) continue; + last = index; + choice -= weight; + if (choice < 0.0D) return index; + } + return last; + } + + private static double weightedChoice(double sample, double total) { + return Math.max(0.0D, Math.min(Math.nextDown(1.0D), sample)) * total; + } + private static Map positiveWeights(JsonObject values) { Map result = new LinkedHashMap<>(); for (Entry entry : values.entrySet()) { @@ -463,7 +776,7 @@ private static BakedOutputBundle candidateBundle(JsonObject policy, String sourc ResourceLocation id = resource(string(candidate, "registry_id", "")); Block block = id == null ? null : ForgeRegistries.BLOCKS.getValue(id); if (block == null || block == Blocks.AIR) return null; - BlockState state = block.getDefaultState(); + BlockState state = state(block, integer(candidate, "metadata", 0)); return new BakedOutputBundle(state, state, -1, new BakedOutput[] { new BakedOutput(state, 1.0D, Integer.MIN_VALUE, Integer.MAX_VALUE) }); @@ -472,18 +785,30 @@ private static BakedOutputBundle candidateBundle(JsonObject policy, String sourc } private static void reportBakeProblem(String message, Object... arguments) { - // Registries and data-pack tags are incomplete during startup's provisional bakes. - // Log at debug level until the server-thread bake can tell whether a rule is valid. - if (WorldGeologyProfileManager.activeServer() == null - || WorldGeologyProfileManager.worldTagsPending()) { + // Loading invokes provisional bakes before the server's registries and + // data-pack tags are authoritative. Keep diagnostics available at debug + // level then, but warn once the server-thread bake can make a real + // validity decision. + if (WorldGeologyProfileManager.activeServer() == null || WorldGeologyProfileManager.worldTagsPending()) { LOGGER.debug(message, arguments); } else { LOGGER.warn(message, arguments); } } - static ConfiguredFeature configuredFeature() { - return configuredFeature; + static double scaledManagedFrequency(double frequency, boolean controller, double scale) { + return controller ? frequency : frequency * scale; + } + + static double channelBackgroundScale(ResourceLocation material, ResourceLocation channel, + double materialScale, double legacyBlockScale) { + if (material == null) return legacyBlockScale; + return OreSourcePolicies.STANDARD.equals(channel) ? materialScale : 1.0D; + } + + static void mergeBackgroundScale(Map scales, T output, double scale) { + Double previous = scales.get(output); + if (previous == null || scale < previous.doubleValue()) scales.put(output, scale); } private static JsonObject objectOrEmpty(JsonObject root, String key) { @@ -491,7 +816,8 @@ private static JsonObject objectOrEmpty(JsonObject root, String key) { } private static BakedOre bakeOre(ResourceLocation ruleId, ResourceLocation material, - ResourceLocation domain, BlockState output, BlockState deepOutput, int deepOutputMaxY, + boolean materialDeclared, ResourceLocation policyDomain, + BlockState output, BlockState deepOutput, int deepOutputMaxY, BakedOutput[] outputs, JsonObject json, BakedGeomeConfig config, Map> resolvedTags, boolean retrogen, BakedOre previous) { @@ -499,9 +825,10 @@ private static BakedOre bakeOre(ResourceLocation ruleId, ResourceLocation materi // Only rules that depend entirely on tags need the post-load retry. if (previous != null) { Map explicitHosts = new IdentityHashMap<>(); - addBlocks(explicitHosts, json.get("host_blocks")); - if (previous.familyMask != 0 || !explicitHosts.isEmpty()) - return previous.withMaterial(material); + Map explicitStates = new HashMap<>(); + addBlocks(explicitHosts, explicitStates, json.get("host_blocks")); + if (previous.familyMask != 0 || !explicitHosts.isEmpty() || !explicitStates.isEmpty()) + return previous.withMaterial(material, materialDeclared); } int minY = integer(json, "min_y", 0); int maxY = integer(json, "max_y", 255); @@ -518,7 +845,8 @@ private static BakedOre bakeOre(ResourceLocation ruleId, ResourceLocation materi } Map hostBlocks = new IdentityHashMap<>(); - addBlocks(hostBlocks, json.get("host_blocks")); + Map hostStates = new HashMap<>(); + addBlocks(hostBlocks, hostStates, json.get("host_blocks")); addTags(hostBlocks, json.get("host_tags"), resolvedTags); int familyMask = 0; if (json.has("host_families") && json.get("host_families").isJsonArray()) { @@ -530,7 +858,7 @@ private static BakedOre bakeOre(ResourceLocation ruleId, ResourceLocation materi } } } - if (hostBlocks.isEmpty() && familyMask == 0) { + if (!hasHostTargets(hostBlocks, hostStates, familyMask)) { return null; } CompiledOrePattern pattern; @@ -547,6 +875,10 @@ private static BakedOre bakeOre(ResourceLocation ruleId, ResourceLocation materi int nodeSize = boundedInteger(json, "node_size", 4, 1, 32); double discardChanceOnAirExposure = Math.max(0.0D, Math.min(1.0D, decimal(json, "discard_chance_on_air_exposure", 0.0D))); + boolean backgroundController = json.has("background_generation_scale"); + double backgroundGenerationScale = backgroundController + ? Math.max(0.0D, Math.min(1.0D, + decimal(json, "background_generation_scale", 1.0D))) : 1.0D; double[] geomeWeights = new double[config.geomeCount()]; java.util.Arrays.fill(geomeWeights, 1.0D); @@ -563,13 +895,20 @@ private static BakedOre bakeOre(ResourceLocation ruleId, ResourceLocation materi Set includedDictionaryBiomes = resolveBiomeDictionary(json, "biome_dictionary"); Set excludedDictionaryBiomes = resolveBiomeDictionary(json, "excluded_biome_dictionary"); - return new BakedOre(ruleId, material, domain, - OreSourcePolicies.placementChannel(json), output, deepOutput, deepOutputMaxY, outputs, + return new BakedOre(ruleId, material, materialDeclared, policyDomain, + OreSourcePolicies.placementChannel(json), + output, deepOutput, deepOutputMaxY, outputs, minY, maxY, Math.min(64.0D, frequency), minQuantity, maxQuantity, pattern, heightDistribution, discardChanceOnAirExposure, spread, verticalSpread, nodeSize, - hostBlocks, familyMask, geomeWeights, includedBiomeIds, excludedBiomeIds, - includedDictionaryBiomes, excludedDictionaryBiomes, retrogen); + hostBlocks, hostStates, familyMask, geomeWeights, includedBiomeIds, excludedBiomeIds, + includedDictionaryBiomes, excludedDictionaryBiomes, retrogen, + backgroundController, backgroundGenerationScale); + } + + static boolean hasHostTargets(Map blocks, + Map states, int familyMask) { + return !blocks.isEmpty() || !states.isEmpty() || familyMask != 0; } private static BakedOutput[] bakeOutputs(JsonObject ore, BlockState fallback) { @@ -586,7 +925,7 @@ private static BakedOutput[] bakeOutputs(JsonObject ore, BlockState fallback) { int minY = integer(value, "min_y", Integer.MIN_VALUE); int maxY = integer(value, "max_y", Integer.MAX_VALUE); if (block != null && block != Blocks.AIR && weight > 0.0D && minY <= maxY) { - result.add(new BakedOutput(block.getDefaultState(), weight, minY, maxY)); + result.add(new BakedOutput(state(block, integer(value, "metadata", 0)), weight, minY, maxY)); } } return result.isEmpty() @@ -594,7 +933,8 @@ private static BakedOutput[] bakeOutputs(JsonObject ore, BlockState fallback) { : result.toArray(new BakedOutput[result.size()]); } - private static void addBlocks(Map target, JsonElement element) { + private static void addBlocks(Map target, Map exact, + JsonElement element) { if (element == null || !element.isJsonArray()) { return; } @@ -603,8 +943,13 @@ private static void addBlocks(Map target, JsonElement element) { ResourceLocation id = resource(object == null ? value.getAsString() : string(object, "block", "")); Block block = id == null ? null : ForgeRegistries.BLOCKS.getValue(id); if (block != null && block != Blocks.AIR) { - target.put(block, Math.max(0.0D, Math.min(1.0D, - object == null ? 1.0D : decimal(object, "weight", 1.0D)))); + double weight = Math.max(0.0D, Math.min(1.0D, + object == null ? 1.0D : decimal(object, "weight", 1.0D))); + if (object != null && object.has("properties")) { + exact.put(zone.moddev.mc.orespawn.util.ConfiguredBlockState.read(object), weight); + } else { + target.put(block, weight); + } } } } @@ -726,18 +1071,29 @@ private static int boundedInteger(JsonObject json, String key, int fallback, int return Math.max(min, Math.min(max, integer(json, key, fallback))); } - private static BlockState blockState(JsonObject json, String key, BlockState fallback) { + private static BlockState blockState(JsonObject json, String key, String metadataKey, + BlockState fallback) { if (!json.has(key)) { return fallback; } ResourceLocation id = resource(string(json, key, "")); Block block = id == null ? null : ForgeRegistries.BLOCKS.getValue(id); - return block == null || block == Blocks.AIR ? null : block.getDefaultState(); + return block == null || block == Blocks.AIR ? null : state(block, integer(json, metadataKey, 0)); + } + + private static BlockState state(Block block, int metadata) { + // Earlier 1.13 profiles ignored legacy metadata. Keep their flattened identity unchanged. + return block.getDefaultState(); + } + + static ConfiguredFeature configuredFeature() { + return configuredFeature; } private static final class BakedOre { final ResourceLocation ruleId; final ResourceLocation material; + final boolean materialDeclared; final ResourceLocation policyDomain; final ResourceLocation channel; final BlockState output; @@ -756,6 +1112,7 @@ private static final class BakedOre { final int verticalSpread; final int nodeSize; final Map hostBlocks; + final Map hostStates; final int familyMask; final double[] geomeWeights; final Set includedBiomeIds; @@ -763,40 +1120,49 @@ private static final class BakedOre { final Set includedDictionaryBiomes; final Set excludedDictionaryBiomes; final boolean retrogen; + final boolean backgroundController; + final double backgroundGenerationScale; + final BakedOutputBundle outputBundle; final BakedSource[] arbitrationSources; - final long sourceSalt; - BakedOre(ResourceLocation ruleId, ResourceLocation material, + BakedOre(ResourceLocation ruleId, ResourceLocation material, boolean materialDeclared, ResourceLocation policyDomain, ResourceLocation channel, BlockState output, BlockState deepOutput, int deepOutputMaxY, BakedOutput[] outputs, int minY, int maxY, double frequency, int minQuantity, int maxQuantity, CompiledOrePattern pattern, OreHeightDistribution heightDistribution, double discardChanceOnAirExposure, int spread, int verticalSpread, int nodeSize, - Map hostBlocks, int familyMask, double[] geomeWeights, + Map hostBlocks, Map hostStates, + int familyMask, double[] geomeWeights, Set includedBiomeIds, Set excludedBiomeIds, Set includedDictionaryBiomes, Set excludedDictionaryBiomes, - boolean retrogen) { - this(ruleId, material, policyDomain, channel, output, deepOutput, deepOutputMaxY, outputs, + boolean retrogen, boolean backgroundController, + double backgroundGenerationScale) { + this(ruleId, material, materialDeclared, policyDomain, channel, + output, deepOutput, deepOutputMaxY, outputs, minY, maxY, frequency, minQuantity, maxQuantity, pattern, heightDistribution, - discardChanceOnAirExposure, spread, verticalSpread, nodeSize, hostBlocks, - familyMask, geomeWeights, includedBiomeIds, excludedBiomeIds, - includedDictionaryBiomes, excludedDictionaryBiomes, retrogen, new BakedSource[0]); + discardChanceOnAirExposure, spread, verticalSpread, nodeSize, hostBlocks, hostStates, + familyMask, geomeWeights, includedBiomeIds, excludedBiomeIds, + includedDictionaryBiomes, excludedDictionaryBiomes, retrogen, backgroundController, + backgroundGenerationScale, new BakedSource[0]); } - private BakedOre(ResourceLocation ruleId, ResourceLocation material, + private BakedOre(ResourceLocation ruleId, ResourceLocation material, boolean materialDeclared, ResourceLocation policyDomain, ResourceLocation channel, BlockState output, BlockState deepOutput, int deepOutputMaxY, BakedOutput[] outputs, int minY, int maxY, double frequency, int minQuantity, int maxQuantity, CompiledOrePattern pattern, OreHeightDistribution heightDistribution, double discardChanceOnAirExposure, int spread, int verticalSpread, int nodeSize, - Map hostBlocks, int familyMask, double[] geomeWeights, + Map hostBlocks, Map hostStates, + int familyMask, double[] geomeWeights, Set includedBiomeIds, Set excludedBiomeIds, Set includedDictionaryBiomes, Set excludedDictionaryBiomes, - boolean retrogen, BakedSource[] arbitrationSources) { + boolean retrogen, boolean backgroundController, + double backgroundGenerationScale, BakedSource[] arbitrationSources) { this.ruleId = ruleId; this.material = material; + this.materialDeclared = materialDeclared; this.policyDomain = policyDomain; this.channel = channel; this.output = output; @@ -815,6 +1181,7 @@ private BakedOre(ResourceLocation ruleId, ResourceLocation material, this.verticalSpread = verticalSpread; this.nodeSize = nodeSize; this.hostBlocks = hostBlocks; + this.hostStates = hostStates; this.familyMask = familyMask; this.geomeWeights = geomeWeights; this.includedBiomeIds = includedBiomeIds; @@ -822,36 +1189,38 @@ private BakedOre(ResourceLocation ruleId, ResourceLocation material, this.includedDictionaryBiomes = includedDictionaryBiomes; this.excludedDictionaryBiomes = excludedDictionaryBiomes; this.retrogen = retrogen; + this.backgroundController = backgroundController; + this.backgroundGenerationScale = backgroundGenerationScale; + this.outputBundle = new BakedOutputBundle(output, deepOutput, deepOutputMaxY, outputs); this.arbitrationSources = arbitrationSources; - this.sourceSalt = material == null ? 0L - : ((long) material.hashCode() << 32) ^ channel.hashCode(); } + BakedOre withMaterial(ResourceLocation nextMaterial, boolean declared) { + return new BakedOre(ruleId, nextMaterial, declared, policyDomain, channel, + output, deepOutput, deepOutputMaxY, outputs, + minY, maxY, frequency, minQuantity, maxQuantity, pattern, heightDistribution, + discardChanceOnAirExposure, spread, verticalSpread, nodeSize, hostBlocks, hostStates, + familyMask, geomeWeights, includedBiomeIds, excludedBiomeIds, + includedDictionaryBiomes, excludedDictionaryBiomes, retrogen, backgroundController, + backgroundGenerationScale, arbitrationSources); + } + BakedOre withSources(List sources) { - return new BakedOre(ruleId, material, policyDomain, channel, - output, deepOutput, deepOutputMaxY, outputs, minY, maxY, frequency, - minQuantity, maxQuantity, pattern, heightDistribution, discardChanceOnAirExposure, - spread, verticalSpread, nodeSize, hostBlocks, familyMask, geomeWeights, - includedBiomeIds, excludedBiomeIds, includedDictionaryBiomes, - excludedDictionaryBiomes, retrogen, - sources.toArray(new BakedSource[sources.size()])); - } - - BakedOre withMaterial(ResourceLocation nextMaterial) { - return new BakedOre(ruleId, nextMaterial, policyDomain, channel, - output, deepOutput, deepOutputMaxY, outputs, minY, maxY, frequency, - minQuantity, maxQuantity, pattern, heightDistribution, discardChanceOnAirExposure, - spread, verticalSpread, nodeSize, hostBlocks, familyMask, geomeWeights, - includedBiomeIds, excludedBiomeIds, includedDictionaryBiomes, - excludedDictionaryBiomes, retrogen); - } - - BakedOutputBundle outputSource(long worldSeed, long chunkIdentity, int attempt) { - if (arbitrationSources.length == 0) return null; + return new BakedOre(ruleId, material, materialDeclared, policyDomain, channel, + output, deepOutput, deepOutputMaxY, outputs, + minY, maxY, frequency, minQuantity, maxQuantity, pattern, heightDistribution, + discardChanceOnAirExposure, spread, verticalSpread, nodeSize, hostBlocks, hostStates, + familyMask, geomeWeights, includedBiomeIds, excludedBiomeIds, + includedDictionaryBiomes, excludedDictionaryBiomes, retrogen, backgroundController, + backgroundGenerationScale, sources.toArray(new BakedSource[sources.size()])); + } + + BakedOutputBundle outputSource(long worldSeed, ResourceLocation dimension, long identity) { + if (arbitrationSources.length == 0) return outputBundle; double total = 0.0D; for (BakedSource source : arbitrationSources) total += source.weight; - long sample = mix(worldSeed ^ sourceSalt, chunkIdentity, attempt); - double choice = (sample >>> 11) * 0x1.0p-53 * total; + double choice = weightedChoice(outputSelectionSample( + worldSeed, dimension, material, channel, identity), total); for (BakedSource source : arbitrationSources) { choice -= source.weight; if (choice < 0.0D) return source.bundle; @@ -859,22 +1228,9 @@ BakedOutputBundle outputSource(long worldSeed, long chunkIdentity, int attempt) return arbitrationSources[arbitrationSources.length - 1].bundle; } - BlockState outputAt(int y, Random random) { - if (y <= deepOutputMaxY) return deepOutput; - double total = 0.0D; - for (BakedOutput candidate : outputs) if (candidate.acceptsY(y)) total += candidate.weight; - if (total <= 0.0D) return output; - double choice = random.nextDouble() * total; - for (BakedOutput candidate : outputs) { - if (!candidate.acceptsY(y)) continue; - choice -= candidate.weight; - if (choice <= 0.0D) return candidate.state; - } - return output; - } - boolean accepts(BlockState state, Random random, BakedGeomeConfig config) { - Double chance = hostBlocks.get(state.getBlock()); + Double chance = hostStates.get(state); + if (chance == null) chance = hostBlocks.get(state.getBlock()); if (chance != null) { return chance >= 1.0D || random.nextDouble() < chance; } @@ -893,23 +1249,37 @@ boolean acceptsBiome(Biome biome, ResourceLocation biomeId) { } private static final class BakedOreRule { + final ResourceLocation ruleId; final Block output; + final ResourceLocation material; + final boolean materialDeclared; final boolean suppressVanilla; + final boolean nativeGeneration; + final boolean importedVanilla; final Map explicit = new HashMap<>(); final Set explicitDimensions = new HashSet<>(); BakedOre selector; - BakedOreRule(Block output, boolean suppressVanilla) { + BakedOreRule(ResourceLocation ruleId, Block output, ResourceLocation material, + boolean materialDeclared, + boolean suppressVanilla, boolean nativeGeneration, boolean importedVanilla) { + this.ruleId = ruleId; this.output = output; + this.material = material; + this.materialDeclared = materialDeclared; this.suppressVanilla = suppressVanilla; + this.nativeGeneration = nativeGeneration; + this.importedVanilla = importedVanilla; } } private static final class BakedSource { + final String sourceId; final BakedOutputBundle bundle; final double weight; - BakedSource(BakedOutputBundle bundle, double weight) { + BakedSource(String sourceId, BakedOutputBundle bundle, double weight) { + this.sourceId = sourceId; this.bundle = bundle; this.weight = weight; } @@ -964,20 +1334,33 @@ boolean acceptsY(int y) { private static final class BakedOres { static final BakedOres EMPTY = new BakedOres(EMPTY_DIMENSIONS, Collections.emptyMap(), - NO_ORES, Collections.emptySet()); + Collections.emptyMap(), Collections.emptyMap(), NO_ORES, Collections.emptySet(), + Collections.emptyMap(), Collections.emptyMap()); final Map byDimension; final Map> vanillaOutputs; + final Map> backgroundGenerationScales; + final Map> materialBackgroundGenerationScales; final BakedOre[] selectorOres; final Set selectorVanillaOutputs; + final Map selectorBackgroundGenerationScales; + final Map selectorMaterialBackgroundGenerationScales; BakedOres(Map byDimension, - Map> vanillaOutputs, BakedOre[] selectorOres, - Set selectorVanillaOutputs) { + Map> vanillaOutputs, + Map> backgroundGenerationScales, + Map> materialBackgroundGenerationScales, + BakedOre[] selectorOres, Set selectorVanillaOutputs, + Map selectorBackgroundGenerationScales, + Map selectorMaterialBackgroundGenerationScales) { this.byDimension = byDimension; this.vanillaOutputs = vanillaOutputs; + this.backgroundGenerationScales = backgroundGenerationScales; + this.materialBackgroundGenerationScales = materialBackgroundGenerationScales; this.selectorOres = selectorOres; this.selectorVanillaOutputs = selectorVanillaOutputs; + this.selectorBackgroundGenerationScales = selectorBackgroundGenerationScales; + this.selectorMaterialBackgroundGenerationScales = selectorMaterialBackgroundGenerationScales; } } @@ -985,6 +1368,10 @@ private static final class GenerationScratch { final BlockPos.MutableBlockPos cursor = new BlockPos.MutableBlockPos(); final PatternContext patternContext = new PatternContext(cursor); private double[] geomeValues = new double[0]; + private ServerWorld samplerLevel; + private ResourceLocation samplerDimension; + private BakedGeomeConfig samplerConfig; + private Optional geologySampler = Optional.empty(); double[] geomeValues(int count) { if (geomeValues.length != count) { @@ -992,6 +1379,19 @@ private static final class GenerationScratch { } return geomeValues; } + + Optional geologySampler(ServerWorld level, ResourceLocation dimension) { + BakedGeomeConfig activeConfig = WorldIds.OVERWORLD.equals(dimension) + ? GeomeConfig.baked() : GeomeConfig.baked(dimension); + if (level != samplerLevel || !dimension.equals(samplerDimension) + || activeConfig != samplerConfig) { + samplerLevel = level; + samplerDimension = dimension; + samplerConfig = activeConfig; + geologySampler = level == null ? Optional.empty() : OreSpawnApi.createSampler(level); + } + return geologySampler; + } } private static final class PatternContext implements OreGenerationContext { @@ -1001,24 +1401,23 @@ private static final class PatternContext implements OreGenerationContext { private IChunk chunk; private Random random; private BakedOre ore; - private BakedOutputBundle selectedOutput; - private BakedOutputBundle identifiedOutput; - private long identifiedOutputIdentity; - private boolean hasIdentifiedOutput; + private int geome; private ResourceLocation dimension; private long worldSeed; private int chunkX; private int chunkZ; - private net.minecraft.server.MinecraftServer samplerServer; - private ResourceLocation samplerDimension; - private Optional sampler = Optional.empty(); - private int geome; + private boolean nativeChunkReads; + private Optional geologySampler = Optional.empty(); private int originX; private int originY; private int originZ; private int minY; private int maxY; private int quantity; + private BakedOutputBundle ordinaryOutput; + private BakedOutputBundle identifiedOutput; + private long identifiedOutputIdentity; + private boolean hasIdentifiedOutput; PatternContext(BlockPos.MutableBlockPos cursor) { this.cursor = cursor; @@ -1026,26 +1425,31 @@ private static final class PatternContext implements OreGenerationContext { void initialize(IWorld world, IChunk chunk, Random random, BakedOre ore, int geome, ResourceLocation dimension, long worldSeed, - BakedOutputBundle selectedOutput, + int attemptIndex, + Optional geologySampler, int originX, int originY, int originZ, int minY, int maxY, int quantity) { this.world = world; this.chunk = chunk; + this.nativeChunkReads = world == null || world.getClass() == WorldGenRegion.class; this.random = random; this.ore = ore; - this.selectedOutput = selectedOutput; - this.identifiedOutput = null; - this.hasIdentifiedOutput = false; + this.geome = geome; this.dimension = dimension; this.worldSeed = worldSeed; - this.chunkX = chunk.getPos().x; - this.chunkZ = chunk.getPos().z; - this.geome = geome; + ChunkPos chunkPos = chunk.getPos(); + this.chunkX = chunkPos.x; + this.chunkZ = chunkPos.z; + this.geologySampler = geologySampler; this.originX = originX; this.originY = originY; this.originZ = originZ; this.minY = minY; this.maxY = maxY; this.quantity = quantity; + long attemptIdentity = ordinaryOutputIdentity(chunkPos, attemptIndex, ore.ruleId, ore.channel); + this.ordinaryOutput = ore.outputSource(worldSeed, dimension, attemptIdentity); + this.identifiedOutput = null; + this.hasIdentifiedOutput = false; } @Override public Random random() { return random; } @@ -1062,23 +1466,7 @@ void initialize(IWorld world, IChunk chunk, Random random, BakedOre ore, int geo @Override public ResourceLocation dimension() { return dimension; } @Override public int chunkX() { return chunkX; } @Override public int chunkZ() { return chunkZ; } - @Override public Optional geologySampler() { - net.minecraft.server.MinecraftServer server = WorldGeologyProfileManager.activeServer(); - if (server != samplerServer || !dimension.equals(samplerDimension)) { - samplerServer = server; - samplerDimension = dimension; - sampler = Optional.empty(); - if (server != null) { - for (ServerWorld level : server.forgeGetWorldMap().values()) { - if (dimension.equals(WorldIds.dimension(level))) { - sampler = OreSpawnApi.createSampler(level); - break; - } - } - } - } - return sampler; - } + @Override public Optional geologySampler() { return geologySampler; } @Override public boolean inside(int x, int y, int z) { @@ -1095,54 +1483,38 @@ public boolean inside(int x, int y, int z) { public boolean isFluid(int x, int y, int z, Fluid fluid) { if (!inside(x, y, z)) return false; cursor.setPos(x, y, z); - BlockState state = world == null ? chunk.getBlockState(cursor) : world.getBlockState(cursor); + BlockState state = stateAt(cursor); return state.getFluidState().getFluid() == fluid; } @Override public boolean tryPlace(int x, int y, int z) { - // The ordinary pattern path runs for every candidate block in a vein. - if (!inside(x, y, z)) return false; - cursor.setPos(x, y, z); - BlockState existing = world == null ? chunk.getBlockState(cursor) : world.getBlockState(cursor); - if (!ore.accepts(existing, random, geomeConfig)) return false; - if (ore.discardChanceOnAirExposure > 0.0D - && random.nextDouble() < ore.discardChanceOnAirExposure - && isAdjacentToAir(x, y, z)) { - return false; - } - BlockState output = selectedOutput == null - ? ore.outputAt(y, random) : selectedOutput.outputAt(y, random); - if (world == null) chunk.setBlockState(cursor, output, false); - else world.setBlockState(cursor, output, 2); - return true; + return tryPlaceWithOutput(x, y, z, ordinaryOutput); } @Override public boolean tryPlace(int x, int y, int z, long outputIdentity) { if (!hasIdentifiedOutput || identifiedOutputIdentity != outputIdentity) { identifiedOutputIdentity = outputIdentity; - identifiedOutput = ore.outputSource(worldSeed, outputIdentity, 0); + identifiedOutput = ore.outputSource(worldSeed, dimension, outputIdentity); hasIdentifiedOutput = true; } return tryPlaceWithOutput(x, y, z, identifiedOutput); } - private boolean tryPlaceWithOutput(int x, int y, int z, - BakedOutputBundle outputSource) { + private boolean tryPlaceWithOutput(int x, int y, int z, BakedOutputBundle outputSource) { if (!inside(x, y, z)) return false; cursor.setPos(x, y, z); - BlockState existing = world == null ? chunk.getBlockState(cursor) : world.getBlockState(cursor); + BlockState existing = stateAt(cursor); if (!ore.accepts(existing, random, geomeConfig)) return false; if (ore.discardChanceOnAirExposure > 0.0D && random.nextDouble() < ore.discardChanceOnAirExposure && isAdjacentToAir(x, y, z)) { return false; } - BlockState output = outputSource == null - ? ore.outputAt(y, random) : outputSource.outputAt(y, random); + BlockState output = outputSource.outputAt(y, random); if (world == null) chunk.setBlockState(cursor, output, false); - else world.setBlockState(cursor, output, 2); + else world.setBlockState(cursor.toImmutable(), output, GENERATION_WRITE_FLAGS); return true; } @@ -1159,9 +1531,31 @@ private boolean isAir(int x, int y, int z) { if (world == null && !insideChunk(chunk, x, y, z)) { return false; } + if (world instanceof WorldGenRegion && !((WorldGenRegion) world).chunkExists(x >> 4, z >> 4)) { + return false; + } airCursor.setPos(x, y, z); - return (world == null ? chunk.getBlockState(airCursor) : world.getBlockState(airCursor)).isAir(); + return stateAt(airCursor).isAir(); + } + + private BlockState stateAt(BlockPos position) { + // Native region reads resolve this same chunk again for every ore cell. + // Keep custom world views and neighbouring chunk reads on their own path. + if (nativeChunkReads && (position.getX() >> 4) == chunkX && (position.getZ() >> 4) == chunkZ) { + return chunk.getBlockState(position); + } + return world == null ? chunk.getBlockState(position) : world.getBlockState(position); } } + private static void markChanged(IChunk chunk) { + if (chunk instanceof Chunk) ((Chunk) chunk).setModified(true); + else if (chunk instanceof net.minecraft.world.chunk.ChunkPrimer) + ((net.minecraft.world.chunk.ChunkPrimer) chunk).setModified(true); + } + + private static long chunkKey(ChunkPos pos) { + return ((long) pos.x & 0xFFFFFFFFL) | (((long) pos.z & 0xFFFFFFFFL) << 32); + } + } diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/StoneReplacer.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/StoneReplacer.java index c05fcce8..25568295 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/StoneReplacer.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/StoneReplacer.java @@ -72,6 +72,7 @@ boolean place(FeaturePlaceContext context) { geology.legacy.replaceStoneInChunk(world, chunk, terrain); } else { geology.sky.replaceStoneInChunk(world, chunk, terrain); + NaturalFormations.apply(world, chunk, terrain); } return true; } diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/VanillaLakeCompatibility.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/VanillaLakeCompatibility.java new file mode 100644 index 00000000..e4b871be --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/VanillaLakeCompatibility.java @@ -0,0 +1,69 @@ +package zone.moddev.mc.orespawn.worldgen; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import net.minecraft.block.BlockState; +import net.minecraft.block.Blocks; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IWorld; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.gen.WorldGenRegion; +import net.minecraft.world.gen.feature.Feature; +import net.minecraft.world.gen.feature.LakesConfig; +import zone.moddev.mc.orespawn.api.FormationSample; +import zone.moddev.mc.orespawn.api.GeologyColumn; +import zone.moddev.mc.orespawn.api.GeologySampler; +import zone.moddev.mc.orespawn.api.OreSpawnApi; + +/** Restores only a native lava lake's plain-stone rim where it covered a planned formation. */ +final class VanillaLakeCompatibility extends ContextFeature { + static final VanillaLakeCompatibility FEATURE = new VanillaLakeCompatibility(); + private VanillaLakeCompatibility() { super(LakesConfig::deserialize); } + + @Override boolean place(FeaturePlaceContext context) { + IWorld world = context.level(); + if (context.config().state.getBlock() != Blocks.LAVA + || !(world.getWorld() instanceof ServerWorld) + || !NaturalFormations.enabledForPlacement(world.getWorld())) + return delegate(context); + Optional sampler = OreSpawnApi.createSampler((ServerWorld) world.getWorld()); + if (!sampler.isPresent()) return delegate(context); + BlockPos origin = context.origin(); + while (origin.getY() > 5 && world.isAirBlock(origin)) origin = origin.down(); + if (origin.getY() <= 4) return delegate(context); + // Unlike 1.10's WorldGenLakes, this native feature does not subtract eight from X/Z. + origin = origin.down(4); + Map original = new LinkedHashMap<>(); + for (int x = 0; x < 16; x++) for (int z = 0; z < 16; z++) { + GeologyColumn column = null; + for (int y = 0; y < 8; y++) { + BlockPos at = origin.add(x, y, z); + if (!readable(world, at)) continue; + BlockState state = world.getBlockState(at); + if (NaturalFormations.material(state) == null || world.getTileEntity(at) != null) continue; + if (column == null) column = sampler.get().sampleColumn(at.getX(), at.getZ(), 64); + Optional sample = column.formationAt(at.getY()); + if (sample.isPresent() && sample.get().material().state().equals(state)) original.put(at, state); + } + } + boolean generated = delegate(context); + for (Map.Entry entry : original.entrySet()) { + BlockPos at = entry.getKey(); + if (readable(world, at) && world.getBlockState(at).equals(Blocks.STONE.getDefaultState()) + && world.getTileEntity(at) == null) world.setBlockState(at, entry.getValue(), 2); + } + return generated; + } + + private static boolean delegate(FeaturePlaceContext context) { + return Feature.LAKE.place(AquiferMaterialSubstitution.nativeDecorationView(context.level()), context.chunkGenerator(), + context.random(), context.origin(), context.config()); + } + + private static boolean readable(IWorld world, BlockPos at) { + return at.getY() >= 0 && at.getY() < 256 && (world instanceof WorldGenRegion + ? ((WorldGenRegion) world).chunkExists(at.getX() >> 4, at.getZ() >> 4) + : ((ServerWorld) world.getWorld()).getChunkProvider().chunkExists(at.getX() >> 4, at.getZ() >> 4)); + } +} diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/VanillaOreFeatureGate.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/VanillaOreFeatureGate.java index b9b75180..dbdaa1e1 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/VanillaOreFeatureGate.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/VanillaOreFeatureGate.java @@ -29,6 +29,10 @@ static void register() { // Minecraft 1.14 stores configured features inline. Wrap them when installing the biome lists. } + static Block wrappedOutput(Feature feature, IFeatureConfig config) { + return feature == GATE && config instanceof GateConfig ? ((GateConfig) config).output : null; + } + static boolean wrapFeatureList(List> features) { boolean changed = false; for (int index = 0; index < features.size(); index++) { @@ -52,10 +56,17 @@ private static final class GateFeature extends ContextFeature { boolean place(FeaturePlaceContext context) { WorldGeologyProfileManager.resolveFreshPoliciesBeforeGeneration(); if (WorldGeologyProfileManager.activeProfile().suppressAllOreFeatures()) return false; - if (OreSpawnOreGeneration.takesOverVanillaOre( - WorldIds.dimension(context.level()), context.config().output)) return false; - return context.config().delegate.place(context.level(), context.chunkGenerator(), - context.random(), context.origin()); + net.minecraft.util.math.ChunkPos chunk = context.decorationChunk().getPos(); + if (!OreSpawnOreGeneration.allowsVanillaOre(WorldIds.dimension(context.level()), + context.config().output, context.level().getSeed(), chunk.x, chunk.z)) return false; + boolean previous = NativeStonePatchContext.enter( + NaturalFormations.enabledForPlacement(context.level().getWorld()), context.config().output); + try { + return context.config().delegate.place(context.level(), context.chunkGenerator(), + context.random(), context.origin()); + } finally { + NativeStonePatchContext.restore(previous); + } } } diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/VanillaSpringCompatibility.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/VanillaSpringCompatibility.java index c7d01afb..ad8b81d5 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/VanillaSpringCompatibility.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/VanillaSpringCompatibility.java @@ -48,11 +48,15 @@ static boolean isHost(Block block) { return Block.isRock(block) || providerRocks.contains(block); } - static boolean rewriteFeatureList(List> features) { + static boolean rewriteFeatureList(List> features) { + return rewriteFeatureList(features, true, false); + } + + static boolean rewriteFeatureList(List> features, boolean springs, boolean aquifers) { boolean changed = false; for (int index = 0; index < features.size(); index++) { ConfiguredFeature original = features.get(index); - ConfiguredFeature rewritten = rewrite(original); + ConfiguredFeature rewritten = rewrite(original, springs, aquifers); if (rewritten != original) { features.set(index, rewritten); changed = true; @@ -61,16 +65,22 @@ static boolean rewriteFeatureList(List> features) { return changed; } - private static ConfiguredFeature rewrite(ConfiguredFeature root) { + private static ConfiguredFeature rewrite(ConfiguredFeature root, boolean springs, boolean aquifers) { if (root == null) return null; - if (root.feature == Feature.SPRING_FEATURE && root.config instanceof LiquidsConfig) { + if (springs && NaturalFormations.hasConfiguredFormations() && root.feature == Feature.LAKE + && root.config instanceof net.minecraft.world.gen.feature.LakesConfig) + return configured(VanillaLakeCompatibility.FEATURE, root.config); + if (aquifers && NativeAquaticCompatibility.accepts(root.feature)) + return configured(NativeAquaticCompatibility.FEATURE, + new NativeAquaticCompatibility.Config(root.feature, (IFeatureConfig) root.config)); + if (springs && root.feature == Feature.SPRING_FEATURE && root.config instanceof LiquidsConfig) { return new ConfiguredFeature<>(FEATURE, (LiquidsConfig) root.config); } Object config = root.config; if (config instanceof DecoratedFeatureConfig) { DecoratedFeatureConfig decorated = (DecoratedFeatureConfig) config; - ConfiguredFeature child = rewrite(decorated.feature); + ConfiguredFeature child = rewrite(decorated.feature, springs, aquifers); return child == decorated.feature ? root : configured(root.feature, new DecoratedFeatureConfig(child, decorated.decorator)); } @@ -79,11 +89,11 @@ private static ConfiguredFeature rewrite(ConfiguredFeature root) { boolean changed = false; List> choices = new ArrayList<>(random.features.size()); for (ConfiguredRandomFeatureList choice : random.features) { - ConfiguredFeature child = rewrite(configured(choice.feature, choice.config)); + ConfiguredFeature child = rewrite(configured(choice.feature, choice.config), springs, aquifers); changed |= child.feature != choice.feature || child.config != choice.config; choices.add(randomChoice(child, choice.chance)); } - ConfiguredFeature fallback = rewrite(random.defaultFeature); + ConfiguredFeature fallback = rewrite(random.defaultFeature, springs, aquifers); changed |= fallback != random.defaultFeature; return changed ? configured(root.feature, new MultipleRandomFeatureConfig(choices, fallback)) : root; @@ -91,31 +101,31 @@ private static ConfiguredFeature rewrite(ConfiguredFeature root) { if (config instanceof MultipleWithChanceRandomFeatureConfig) { MultipleWithChanceRandomFeatureConfig random = (MultipleWithChanceRandomFeatureConfig) config; - List> choices = rewrite(random.features); + List> choices = rewrite(random.features, springs, aquifers); return choices == random.features ? root : configured(root.feature, new MultipleWithChanceRandomFeatureConfig(choices, random.count)); } if (config instanceof SingleRandomFeature) { SingleRandomFeature random = (SingleRandomFeature) config; - List> choices = rewrite(random.features); + List> choices = rewrite(random.features, springs, aquifers); return choices == random.features ? root : configured(root.feature, new SingleRandomFeature(choices)); } if (config instanceof TwoFeatureChoiceConfig) { TwoFeatureChoiceConfig choice = (TwoFeatureChoiceConfig) config; - ConfiguredFeature whenTrue = rewrite(choice.trueFeature); - ConfiguredFeature whenFalse = rewrite(choice.falseFeature); + ConfiguredFeature whenTrue = rewrite(choice.trueFeature, springs, aquifers); + ConfiguredFeature whenFalse = rewrite(choice.falseFeature, springs, aquifers); return whenTrue == choice.trueFeature && whenFalse == choice.falseFeature ? root : configured(root.feature, new TwoFeatureChoiceConfig(whenTrue, whenFalse)); } return root; } - private static List> rewrite(List> originals) { + private static List> rewrite(List> originals, boolean springs, boolean aquifers) { List> rewritten = null; for (int index = 0; index < originals.size(); index++) { ConfiguredFeature original = originals.get(index); - ConfiguredFeature value = rewrite(original); + ConfiguredFeature value = rewrite(original, springs, aquifers); if (value != original && rewritten == null) rewritten = new ArrayList<>(originals); if (rewritten != null) rewritten.set(index, value); } diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/WorldGeologyProfile.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/WorldGeologyProfile.java index 370c3252..e3331460 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/WorldGeologyProfile.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/WorldGeologyProfile.java @@ -71,8 +71,13 @@ public static WorldGeologyProfile recommended(boolean placeFluidDeposits) { public static WorldGeologyProfile fromGlobalConfig(JsonObject globalRoot, GeologyMode geologyMode, boolean placeFluidDeposits) { + return fromGlobalConfig(globalRoot, geologyMode, placeFluidDeposits, true); + } + + static WorldGeologyProfile fromGlobalConfig(JsonObject globalRoot, + GeologyMode geologyMode, boolean placeFluidDeposits, boolean chooseOreSourceDefaults) { JsonObject root = JsonCopies.copy(globalRoot); - OreSourcePolicies.initialize(root, false); + if (chooseOreSourceDefaults) OreSourcePolicies.initialize(root, false); if (!root.has("geology_mode")) { root.addProperty("geology_mode", geologyMode.name().toLowerCase(Locale.ROOT)); } @@ -102,6 +107,7 @@ public static WorldGeologyProfile fromJson(JsonObject json, WorldGeologyProfile // Schema 1 stored only mode, oil and formations. // Fill the missing fields from the active pack profile. JsonObject migrated = fallback.rootCopy(); + migrated.remove(NaturalFormations.SECTION); copyIfPresent(json, migrated, "geology_mode"); copyIfPresent(json, migrated, "place_crude_oil"); copyIfPresent(json, migrated, "formations"); diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/WorldGeologyProfileManager.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/WorldGeologyProfileManager.java index 405c7374..f988baac 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/WorldGeologyProfileManager.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/WorldGeologyProfileManager.java @@ -20,7 +20,6 @@ import com.google.gson.JsonSyntaxException; import zone.moddev.mc.orespawn.OreSpawnConfig; import zone.moddev.mc.orespawn.OreSpawnConfig.GeologyMode; -import zone.moddev.mc.orespawn.api.OreSpawnOreIntegration; import zone.moddev.mc.orespawn.integration.WorldgenIntegrationManager; import net.minecraft.server.MinecraftServer; @@ -111,9 +110,9 @@ public static synchronized boolean reloadActiveProfile() { .resolve("serverconfig").resolve(PROFILE_FILE_NAME); WorldGeologyProfile profile = readProfile(profilePath, globalProfile()); JsonObject merged = profile.rootCopy(); - boolean changed = OreSpawnOreIntegration.mergeProviderOres(merged); + boolean changed = WorldgenIntegrationManager.mergeSavedProviderDefinitions(merged); changed |= OreSourcePolicies.initialize(merged, true); - if (changed) { + if (changed && preserveBeforeLegacyOreRepair(profilePath, profile, merged)) { profile = profile.withRoot(merged); writeProfile(profilePath, profile); } @@ -137,9 +136,9 @@ public static void onServerAboutToStart(FMLServerAboutToStartEvent event) { profile = readProfile(profilePath, fallback); JsonObject merged = profile.rootCopy(); String beforeMerge = merged.toString(); - OreSpawnOreIntegration.mergeProviderOres(merged); + WorldgenIntegrationManager.mergeSavedProviderDefinitions(merged); OreSourcePolicies.initialize(merged, true); - if (!beforeMerge.equals(merged.toString())) { + if (!beforeMerge.equals(merged.toString()) && preserveBeforeLegacyOreRepair(profilePath, profile, merged)) { profile = profile.withRoot(merged); writeProfile(profilePath, profile); LOGGER.info("Merged new OreSpawn worldgen-provider definitions into '{}'", profilePath); @@ -261,7 +260,10 @@ static WorldGeologyProfile initializeNewWorldPolicies(WorldGeologyProfile profil boolean generatedWorld) { JsonObject initialized = profile.rootCopy(); // A world with generated chunks keeps its original ore budgets on upgrade. - if (generatedWorld) initialized.remove(OreSourcePolicies.SECTION); + if (generatedWorld) { + initialized.remove(OreSourcePolicies.SECTION); + initialized.remove(NaturalFormations.SECTION); + } OreSourcePolicies.initialize(initialized, generatedWorld); return profile.withRoot(initialized); } @@ -412,6 +414,25 @@ static WorldGeologyProfile readProfile(Path path, WorldGeologyProfile fallback) } } + private static boolean preserveBeforeLegacyOreRepair(Path path, WorldGeologyProfile before, JsonObject merged) { + JsonElement priorOres = before.rootCopy().get("ores"); + if (priorOres == null || !priorOres.isJsonObject() || !Files.isRegularFile(path)) return true; + JsonObject original = priorOres.getAsJsonObject(); + JsonObject current = merged.getAsJsonObject("ores"); + for (java.util.Map.Entry rule : original.entrySet()) { + if (current != null && current.has(rule.getKey())) continue; + Path backup = path.resolveSibling("orespawn-worldgen.pre-legacy-ore-repair.bak"); + try { + if (!Files.exists(backup)) Files.copy(path, backup); + return true; + } catch (IOException e) { + LOGGER.warn("Could not back up '{}'; legacy ore repair was not applied", path, e); + return false; + } + } + return true; + } + private static boolean preserveBeforeOreDefaultsRefresh(Path path) { Path backup = path.resolveSibling("orespawn-worldgen.pre-ore-revision-" + GeomeConfig.oreDefaultsRevision() + ".bak"); diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/math/PerlinNoise2D.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/math/PerlinNoise2D.java index 0a5fdcb0..29b0437c 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/math/PerlinNoise2D.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/math/PerlinNoise2D.java @@ -15,8 +15,8 @@ public PerlinNoise2D(long seed, float initialRange, float initialSize, int numOv for (int i = 0; i < layers.length; i++) { seed = scramble(seed); layers[i] = new NoiseLayer2D(seed, initialSize, initialRange); - initialSize *= 0.5; - initialRange *= 0.5; + initialSize *= 0.5F; + initialRange *= 0.5F; } } diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml index cd1fba9a..aabf1155 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/mods.toml @@ -1,64 +1,29 @@ -# This is an example mods.toml file. It contains the data relating to the loading mods. -# There are several mandatory fields (#mandatory), and many more that are optional (#optional). -# The overall format is standard TOML format, v0.5.0. -# Note that there are a couple of TOML lists in this file. -# Find more information on toml format here: https://github.com/toml-lang/toml -# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml -modLoader="javafml" #mandatory -# A version range to match for said mod loader - for regular FML @Mod it will be the forge version -loaderVersion="${loader_version_range}" #mandatory -# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties. -# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here. -license="LGPL-2.1" -# A URL to refer people to when problems occur with this mod -issueTrackerURL="https://github.com/SkyBlade1978/OreSpawn/issues" #optional -# A list of mods - how many allowed here is determined by the individual mod loader -[[mods]] #mandatory -# The modid of the mod -modId="orespawn" #mandatory -# The version number of the mod -version="${version}" #mandatory -# A display name for the mod -displayName="MMD OreSpawn" #mandatory -# A URL to query for updates for this mod. See the JSON update specification https://docs.minecraftforge.net/en/latest/misc/updatechecker/ -#updateJSONURL="https://change.me.example.invalid/updates.json" #optional -# A URL for the "homepage" for this mod, displayed in the mod UI -displayURL="https://github.com/SkyBlade1978/OreSpawn" #optional -# A file name (in the root of the mod JAR) containing a logo for display -#logoFile="examplemod.png" #optional -# A text field displayed in the mod UI -credits="The original OreSpawn contributors, the Mineralogy contributors, Forge, and the MMD Team" #optional -# A text field displayed in the mod UI -authors="SkyBlade1978, dshadowwolf, and the MMD Team" #optional -# Display Test controls the display for your mod in the server connection screen -# MATCH_VERSION means that your mod will cause a red X if the versions on client and server differ. This is the default behaviour and should be what you choose if you have server and client elements to your mod. -# IGNORE_SERVER_VERSION means that your mod will not cause a red X if it's present on the server but not on the client. This is what you should use if you're a server only mod. -# IGNORE_ALL_VERSION means that your mod will not cause a red X if it's present on the client or the server. This is a special case and should only be used if your mod has no server component. -# NONE means that no display test is set on your mod. You need to do this yourself, see IExtensionPoint.DisplayTest for more information. You can define any scheme you wish with this value. -# IMPORTANT NOTE: this is NOT an instruction as to which environments (CLIENT or DEDICATED SERVER) your mod loads on. Your mod should load (and maybe do nothing!) whereever it finds itself. -#displayTest="MATCH_VERSION" # MATCH_VERSION is the default if nothing is specified (#optional) +# Values come from gradle.properties. Eclipse and release jars use the processed copy. +modLoader="javafml" +loaderVersion="${loader_version_range}" +license="${mod_license}" +issueTrackerURL="${mod_issue_url}" -# The description text for the mod (multi line!) (#mandatory) -description='''A configurable, provider-driven engine for terrain, ores, and underground deposits.''' -# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional. -[[dependencies.orespawn]] #optional -# the modid of the dependency -modId="forge" #mandatory -# Does this dependency have to exist - if not, ordering below must be specified -mandatory=true #mandatory -# The version range of the dependency -versionRange="${forge_version_range}" #mandatory -# An ordering relationship for the dependency - BEFORE or AFTER required if the dependency is not mandatory -# BEFORE - This mod is loaded BEFORE the dependency -# AFTER - This mod is loaded AFTER the dependency +[[mods]] +modId="${mod_id}" +version="${version}" +displayName="${mod_name}" +displayURL="${mod_url}" +credits="The original OreSpawn contributors, the Mineralogy contributors, Forge, and the MMD Team" +authors="${mod_authors}" +description='''${mod_description}''' + +# Forge and Minecraft are required; the ranges keep this jar on its own target. +[[dependencies.orespawn]] +modId="forge" +mandatory=true +versionRange="${forge_version_range}" ordering="NONE" -# Side this dependency is applied on - BOTH, CLIENT, or SERVER side="BOTH" -# Here's another dependency + [[dependencies.orespawn]] modId="minecraft" mandatory=true -# This version range declares a minimum of the current minecraft version up to but not including the next major version versionRange="${minecraft_version_range}" ordering="NONE" side="BOTH" diff --git a/src/main/resources/assets/orespawn/lang/de_au.json b/src/main/resources/assets/orespawn/lang/de_at.json similarity index 95% rename from src/main/resources/assets/orespawn/lang/de_au.json rename to src/main/resources/assets/orespawn/lang/de_at.json index 1cfed7ef..9fe43fa6 100644 --- a/src/main/resources/assets/orespawn/lang/de_au.json +++ b/src/main/resources/assets/orespawn/lang/de_at.json @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "Abdeckung", "option.orespawn.biome.fallback_weight": "Gewicht des ursprünglichen Bioms", "option.orespawn.biome.include_namespaces": "Eingeschlossene Namensräume (kommagetrennt)", - "option.orespawn.biome.exclude_namespaces": "Ausgeschlossene Namensräume (kommagetrennt)" + "option.orespawn.biome.exclude_namespaces": "Ausgeschlossene Namensräume (kommagetrennt)", + "commands.orespawn.help": "OreSpawn-Werkzeuge: status verbose; chunk [x z]; survey [Radius]; explain [x y z]; retrogen status; jobs; cancel ; clearchunk; undo .", + "commands.orespawn.options": "Optionen: --dimension , --center , --y , --block . Suchradius: 0–8 (Standard 1).", + "commands.orespawn.safety": "Das Freilegen entfernt auch gesetzte Landschaftsblöcke. Nutze eine Testwelt. Stufe 4, Kreativ-/Zuschauermodus, Vorschau und geprüfte Sicherung sind nötig. undo setzt weder Wesen noch Zeit zurück.", + "commands.orespawn.scope": "Untersuchungen lesen nur geladene Chunks. Berichte zeigen vorhandene Blöcke, nicht deren ursprünglichen Generator oder garantierte künftige Platzierung.", + "commands.orespawn.data": "Daten: %s", + "commands.orespawn.report": "Bericht %s: %s", + "commands.orespawn.started": "Auftrag gestartet. %s", + "commands.orespawn.preview_started": "Vorschau wird vorbereitet; keine Blöcke werden geändert.", + "commands.orespawn.preview_title": "Nur Vorschau — nichts geändert.", + "commands.orespawn.preview_location": "%s | Chunk %s, %s | Höhe %s–%s", + "commands.orespawn.preview_clear_counts": "%s Blöcke entfernen; %s behalten.", + "commands.orespawn.preview_undo_counts": "Bis zu %s Blöcke wiederherstellen; %s andere behalten.", + "commands.orespawn.preview_warning": "Entfernt auch passende, von Spielern gesetzte Blöcke. Nutze eine Testwelt.", + "commands.orespawn.preview_undo_warning": "Rückgängig stellt nur Blöcke wieder her, nicht Entitäten oder vergangene Zeit.", + "commands.orespawn.preview_expiry": "Chat öffnen und unten wählen. Gültig für 2 Min.", + "commands.orespawn.confirm_clear": "[Löschen bestätigen]", + "commands.orespawn.confirm_undo": "[Rückgängig bestätigen]", + "commands.orespawn.preview_cancel": "[Abbrechen]", + "commands.orespawn.preview_cancelled": "Vorschau abgebrochen. Keine Blöcke geändert.", + "commands.orespawn.preview_inactive": "Diese Vorschau ist nicht mehr aktiv.", + "commands.orespawn.action_hint": "Zum Ausführen anklicken: %s", + "commands.orespawn.details": "[Infos]", + "commands.orespawn.complete_clear": "%s Blöcke entfernt. %s %s", + "commands.orespawn.complete_undo": "%s Blöcke wiederhergestellt. %s", + "commands.orespawn.undo_preview": "[Rückgängig…]", + "commands.orespawn.job_result": "Auftrag %s — %s: %s", + "commands.orespawn.backups": "Sicherungen bleiben auch nach Neustarts hier: %s. Wiederherstellen: /orespawn undo .", + "commands.orespawn.failed": "OreSpawn konnte das nicht ausführen: %s" } diff --git a/src/main/resources/assets/orespawn/lang/de_de.json b/src/main/resources/assets/orespawn/lang/de_de.json index 1cfed7ef..9fe43fa6 100644 --- a/src/main/resources/assets/orespawn/lang/de_de.json +++ b/src/main/resources/assets/orespawn/lang/de_de.json @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "Abdeckung", "option.orespawn.biome.fallback_weight": "Gewicht des ursprünglichen Bioms", "option.orespawn.biome.include_namespaces": "Eingeschlossene Namensräume (kommagetrennt)", - "option.orespawn.biome.exclude_namespaces": "Ausgeschlossene Namensräume (kommagetrennt)" + "option.orespawn.biome.exclude_namespaces": "Ausgeschlossene Namensräume (kommagetrennt)", + "commands.orespawn.help": "OreSpawn-Werkzeuge: status verbose; chunk [x z]; survey [Radius]; explain [x y z]; retrogen status; jobs; cancel ; clearchunk; undo .", + "commands.orespawn.options": "Optionen: --dimension , --center , --y , --block . Suchradius: 0–8 (Standard 1).", + "commands.orespawn.safety": "Das Freilegen entfernt auch gesetzte Landschaftsblöcke. Nutze eine Testwelt. Stufe 4, Kreativ-/Zuschauermodus, Vorschau und geprüfte Sicherung sind nötig. undo setzt weder Wesen noch Zeit zurück.", + "commands.orespawn.scope": "Untersuchungen lesen nur geladene Chunks. Berichte zeigen vorhandene Blöcke, nicht deren ursprünglichen Generator oder garantierte künftige Platzierung.", + "commands.orespawn.data": "Daten: %s", + "commands.orespawn.report": "Bericht %s: %s", + "commands.orespawn.started": "Auftrag gestartet. %s", + "commands.orespawn.preview_started": "Vorschau wird vorbereitet; keine Blöcke werden geändert.", + "commands.orespawn.preview_title": "Nur Vorschau — nichts geändert.", + "commands.orespawn.preview_location": "%s | Chunk %s, %s | Höhe %s–%s", + "commands.orespawn.preview_clear_counts": "%s Blöcke entfernen; %s behalten.", + "commands.orespawn.preview_undo_counts": "Bis zu %s Blöcke wiederherstellen; %s andere behalten.", + "commands.orespawn.preview_warning": "Entfernt auch passende, von Spielern gesetzte Blöcke. Nutze eine Testwelt.", + "commands.orespawn.preview_undo_warning": "Rückgängig stellt nur Blöcke wieder her, nicht Entitäten oder vergangene Zeit.", + "commands.orespawn.preview_expiry": "Chat öffnen und unten wählen. Gültig für 2 Min.", + "commands.orespawn.confirm_clear": "[Löschen bestätigen]", + "commands.orespawn.confirm_undo": "[Rückgängig bestätigen]", + "commands.orespawn.preview_cancel": "[Abbrechen]", + "commands.orespawn.preview_cancelled": "Vorschau abgebrochen. Keine Blöcke geändert.", + "commands.orespawn.preview_inactive": "Diese Vorschau ist nicht mehr aktiv.", + "commands.orespawn.action_hint": "Zum Ausführen anklicken: %s", + "commands.orespawn.details": "[Infos]", + "commands.orespawn.complete_clear": "%s Blöcke entfernt. %s %s", + "commands.orespawn.complete_undo": "%s Blöcke wiederhergestellt. %s", + "commands.orespawn.undo_preview": "[Rückgängig…]", + "commands.orespawn.job_result": "Auftrag %s — %s: %s", + "commands.orespawn.backups": "Sicherungen bleiben auch nach Neustarts hier: %s. Wiederherstellen: /orespawn undo .", + "commands.orespawn.failed": "OreSpawn konnte das nicht ausführen: %s" } diff --git a/src/main/resources/assets/orespawn/lang/en_ca.json b/src/main/resources/assets/orespawn/lang/en_ca.json index e495e4a4..40737272 100644 --- a/src/main/resources/assets/orespawn/lang/en_ca.json +++ b/src/main/resources/assets/orespawn/lang/en_ca.json @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "Coverage", "option.orespawn.biome.fallback_weight": "Original-biome weight", "option.orespawn.biome.include_namespaces": "Included namespaces (comma-separated)", - "option.orespawn.biome.exclude_namespaces": "Excluded namespaces (comma-separated)" + "option.orespawn.biome.exclude_namespaces": "Excluded namespaces (comma-separated)", + "commands.orespawn.help": "OreSpawn tools: status verbose; chunk [x z]; survey [radius]; explain [x y z]; retrogen status; jobs; cancel ; clearchunk; undo .", + "commands.orespawn.options": "Options: --dimension , --center , --y , --block . Survey radius: 0–8 (default 1).", + "commands.orespawn.safety": "Clearing changes player-placed terrain too. Use a disposable world. Level 4, Creative/Spectator, a preview and a verified backup are required. Undo cannot reverse entities or time.", + "commands.orespawn.scope": "Surveys inspect loaded chunks only. Reports describe observed blocks, not their historical generator or guaranteed future placement.", + "commands.orespawn.data": "Data: %s", + "commands.orespawn.report": "Report %s: %s", + "commands.orespawn.started": "Job started. %s", + "commands.orespawn.preview_started": "Preparing preview; no blocks will change.", + "commands.orespawn.preview_title": "Preview only — nothing changed.", + "commands.orespawn.preview_location": "%s | Chunk %s, %s | Y %s–%s", + "commands.orespawn.preview_clear_counts": "Clear %s blocks; keep %s.", + "commands.orespawn.preview_undo_counts": "Restore up to %s blocks; keep %s others.", + "commands.orespawn.preview_warning": "Also clears matching player-placed terrain. Use a test world.", + "commands.orespawn.preview_undo_warning": "Undo restores blocks, not entities or elapsed time.", + "commands.orespawn.preview_expiry": "Open chat to choose below. Expires in 2 min.", + "commands.orespawn.confirm_clear": "[Confirm clearing]", + "commands.orespawn.confirm_undo": "[Confirm undo]", + "commands.orespawn.preview_cancel": "[Cancel]", + "commands.orespawn.preview_cancelled": "Preview cancelled. No blocks changed.", + "commands.orespawn.preview_inactive": "This preview is no longer active.", + "commands.orespawn.action_hint": "Click to run: %s", + "commands.orespawn.details": "[Details]", + "commands.orespawn.complete_clear": "Cleared %s blocks. %s %s", + "commands.orespawn.complete_undo": "Restored %s blocks. %s", + "commands.orespawn.undo_preview": "[Undo…]", + "commands.orespawn.job_result": "Job %s — %s: %s", + "commands.orespawn.backups": "Backups remain here across restarts: %s. Use /orespawn undo .", + "commands.orespawn.failed": "OreSpawn could not do that: %s" } diff --git a/src/main/resources/assets/orespawn/lang/en_en.json b/src/main/resources/assets/orespawn/lang/en_en.json deleted file mode 100644 index e495e4a4..00000000 --- a/src/main/resources/assets/orespawn/lang/en_en.json +++ /dev/null @@ -1,512 +0,0 @@ -{ - "tooltip.orespawn.fluid.add_deposit": "Choose an installed fluid block and create a new underground fluid-deposit rule for it.", - "tooltip.orespawn.assignment.ore": "Assign this installed block as an ore, then edit its dimensions, deposit shape, hosts, and geome rules.", - "tooltip.orespawn.assignment.rock_family": "Assign this installed block as a rock in the selected family, then edit its depth and geome rules.", - "tooltip.orespawn.picker.mod_filter": "Limit the installed block list to one mod namespace, or choose All Mods.", - "tooltip.orespawn.material.add_block": "Choose an installed, unassigned block and create a rock or ore rule for the current tab.", - "tooltip.orespawn.material.safe_only": "Hide blocks with block entities or unusual collision and show only ordinary full solid blocks.", - "tooltip.orespawn.material.show_all": "Include blocks with block entities or unusual collision that are normally hidden because terrain replacement may be unsafe.", - "tooltip.orespawn.material.tab.unassigned": "Show installed blocks that are not yet assigned as an OreSpawn rock, ore, or fluid.", - "tooltip.orespawn.material.tab.ores": "Show configured ore entries and open their dimension, shape, host, and geome rules.", - "tooltip.orespawn.material.tab.igneous": "Show intrusive and volcanic igneous rocks and open their generation rules.", - "tooltip.orespawn.material.tab.metamorphic": "Show rocks classified as metamorphic and open their generation rules.", - "tooltip.orespawn.material.tab.sedimentary": "Show rocks classified as sedimentary and open their generation rules.", - "tooltip.orespawn.geome.new_id.dictionary": "Enter a Forge biome type name used by the installed biome dictionary.", - "tooltip.orespawn.geome.new_id.biomes": "Enter an installed biome registry ID, for example minecraft:plains.", - "tooltip.orespawn.geome.new_id.geomes": "Enter a new geome name. OreSpawn stores it in lowercase.", - "tooltip.orespawn.geome.tab.dictionary": "Map Forge biome type names to the geomes they should favour.", - "tooltip.orespawn.geome.tab.biomes": "Map exact biome registry IDs to the geomes they should favour.", - "tooltip.orespawn.geome.tab.geomes": "Edit named geology regions and their base and rock-family weights.", - "tooltip.orespawn.geome.biome_weight": "Influence this biome or biome type adds to the named geome. Valid range: 0 to 1000; 0 adds no influence.", - "tooltip.orespawn.geome.entry_weight": "Relative chance for this rock, ore, or fluid deposit inside the named geome. Valid range: 0 to 1000; 0 excludes it.", - "tooltip.orespawn.geome.family_weight": "Relative preference for this rock family inside the geome. Valid range: 0 to 1000; 0 excludes the family.", - "tooltip.orespawn.geome.base_weight": "Base chance for this geome before biome influences are added. Valid range: 0 to 1000; 0 leaves only biome influence.", - "tooltip.orespawn.numeric.rock_layer_thickness": "Base thickness of legacy Cyano rock layers. Whole numbers from 1 to 255 are accepted.", - "tooltip.orespawn.numeric.rock_layer_noise": "Amount of vertical variation in legacy Cyano rock layers. Valid range: 1 to 32767.", - "tooltip.orespawn.numeric.geome_size": "Horizontal size of legacy Cyano geome regions. Whole numbers from 4 to 32767 are accepted.", - "tooltip.orespawn.numeric.continuity": "Chance that a formation keeps its identity across a boundary. Valid range: 0 to 1.", - "tooltip.orespawn.numeric.edge_octaves": "Number of detail-noise layers combined at formation edges. Whole numbers from 1 to 8 are accepted.", - "tooltip.orespawn.numeric.edge_amplitude": "Maximum vertical displacement caused by boundary detail. Valid range: 0 to 256.", - "tooltip.orespawn.numeric.edge_wavelength": "Horizontal wavelength of small-scale boundary detail. Valid range: 8 to 512.", - "tooltip.orespawn.numeric.waviness_amplitude": "Maximum vertical displacement caused by broad layer waviness. Valid range: 0 to 512.", - "tooltip.orespawn.numeric.waviness_wavelength": "Horizontal wavelength of broad vertical layer bends. Valid range: 32 to 2048.", - "tooltip.orespawn.numeric.vertical_thickness": "Typical vertical thickness of a Sky stratum. Whole numbers from 1 to 192 are accepted.", - "tooltip.orespawn.numeric.family_region_wavelength": "Horizontal wavelength of rock-family regions. Larger values make broader regions. Valid range: 16 to 8192.", - "tooltip.orespawn.numeric.stratum_wavelength": "Horizontal wavelength of Sky strata. The editor accepts 16 to 8192; Stable Layers effectively uses at least 32.", - "tooltip.orespawn.advanced.fluid_deposits": "Open the configured underground fluid pockets and their dimension-specific placement rules.", - "tooltip.orespawn.advanced.cyano": "Edit the legacy Cyano engine's region size, layer variation, and layer thickness.", - "tooltip.orespawn.advanced.formations": "Edit the exact Sky formation values used when a formation control is set to Custom.", - "tooltip.orespawn.main.fluid_editor": "Open each configured fluid deposit to edit dimensions, rarity, size, hosts, biome filters, and geome weights.", - "tooltip.orespawn.main.advanced": "Open exact numeric controls for custom Sky formations, legacy Cyano layers, and configured fluid deposits.", - "tooltip.orespawn.main.biomes_materials": "Configure optional biome placement plus dimension-wide aquifer, snow, ice, and surface-material overrides.", - "tooltip.orespawn.main.configure_strata": "Create editable rock rules for Minecraft's standard stone, granite, diorite, and andesite strata.", - "tooltip.orespawn.main.materials": "Open the current rock and ore rules to edit families, depth ranges, hosts, deposit shapes, and per-geome weights.", - "tooltip.orespawn.main.recommended": "Set the geology engine and formation controls to the recommended Sky and Average choices. Detailed rock, ore, biome, and fluid rules are left unchanged.", - "tooltip.orespawn.main.template": "Select a complete geology setup supplied by an installed mod or mod pack. Pack Defaults keeps the pack's normal selection.", - "tooltip.orespawn.enabled": "Enable or disable this entry without deleting its saved settings.", - "tooltip.orespawn.weight": "Relative chance compared with other eligible entries. Valid range: 0 to 1000; 0 prevents selection and larger values make this entry more likely.", - "tooltip.orespawn.geome_weights": "Set this entry's relative chance in each Overworld geome. A weight of 0 prevents it there.", - "tooltip.orespawn.host_family": "Allow generation in blocks assigned to this rock family. An enabled rule needs at least one family, block, or tag host.", - "tooltip.orespawn.host_blocks": "Comma-separated block registry IDs that may be replaced, for example minecraft:stone.", - "tooltip.orespawn.host_tags": "Comma-separated block-tag registry IDs whose blocks may be replaced, for example forge:stone.", - "tooltip.orespawn.fluid.dimension_settings": "Open the first configured dimension. Use the dimension list below to open a specific dimension.", - "tooltip.orespawn.fluid.available_dimension": "Choose an installed dimension to add, then edit its placement, host, and biome rules.", - "tooltip.orespawn.fluid.min_y": "Lowest Y allowed for the deposit center. The editor accepts 0 to 255, but the value must also be inside the target dimension's build height and must not exceed Maximum Y.", - "tooltip.orespawn.fluid.max_y": "Highest Y allowed for the deposit center. The editor accepts 0 to 255, but the value must also be inside the target dimension's build height and must not be below Minimum Y.", - "tooltip.orespawn.fluid.frequency": "Average deposit attempts per chunk. 0 disables attempts; decimals are allowed up to 64.", - "tooltip.orespawn.fluid.min_radius": "Smallest horizontal radius selected for a deposit lobe. Valid range: 1 to 64.", - "tooltip.orespawn.fluid.max_radius": "Largest horizontal radius selected for a deposit lobe. It must be at least Minimum Radius and no more than 64.", - "tooltip.orespawn.fluid.min_vertical_radius": "Smallest vertical radius selected for a deposit lobe. Valid range: 1 to 64.", - "tooltip.orespawn.fluid.max_vertical_radius": "Largest vertical radius selected for a deposit lobe. It must be at least Minimum Vertical Radius and no more than 64.", - "tooltip.orespawn.fluid.max_lobes": "Maximum rounded lobes joined into one deposit. 1 creates a single pocket; valid range: 1 to 16.", - "tooltip.orespawn.fluid.min_solid_cover": "Minimum solid blocks required above a deposit. 0 disables extra roof protection; valid range: 0 to 64.", - "tooltip.orespawn.fluid.min_solid_shell": "Minimum solid blocks required around the sides and floor. 0 disables extra shell protection; valid range: 0 to 64.", - "tooltip.orespawn.fluid.biome_ids": "If set, deposits may generate only in these comma-separated biome registry IDs. Leave blank for no exact-biome restriction.", - "tooltip.orespawn.fluid.excluded_biome_ids": "Deposits never generate in these comma-separated biome registry IDs. Exclusions override inclusions.", - "tooltip.orespawn.fluid.biome_dictionary": "Include biomes matching these comma-separated Forge biome type names, for example OCEAN. Leave blank for no type restriction.", - "tooltip.orespawn.fluid.excluded_biome_dictionary": "Exclude biomes matching these comma-separated Forge biome type names. Exclusions override inclusions.", - "tooltip.orespawn.ore.min_y": "Lowest Y at which an ore placement attempt may start. The editor accepts 0 to 255, but the value must also be inside the target dimension's build height and must not exceed Maximum Y.", - "tooltip.orespawn.ore.max_y": "Highest Y at which an ore placement attempt may start. The editor accepts 0 to 255, but the value must also be inside the target dimension's build height and must not be below Minimum Y.", - "tooltip.orespawn.ore.frequency": "Average ore placement attempts per chunk. 0 disables attempts; decimals are allowed up to 64.", - "tooltip.orespawn.ore.min_quantity": "Smallest block budget assigned to one deposit attempt. Valid range: 1 to 64.", - "tooltip.orespawn.ore.max_quantity": "Largest block budget assigned to one deposit attempt. It must be at least Minimum Block Budget and no more than 64.", - "tooltip.orespawn.ore.discard_air_exposure": "Chance to reject ore that would touch air. 0 keeps exposed ore; 1 rejects every exposed placement.", - "tooltip.orespawn.ore.pattern": "Choose the deposit shape. Pattern-specific controls below are enabled only when the selected pattern uses them.", - "tooltip.orespawn.ore.height_distribution": "Choose how placement attempts are distributed between Minimum Y and Maximum Y.", - "tooltip.orespawn.ore.spread": "Horizontal range used by cluster and cloud patterns. Valid range: 0 to 64.", - "tooltip.orespawn.ore.vertical_spread": "Vertical range used by cluster and cloud patterns. Valid range: 0 to 64.", - "tooltip.orespawn.ore.node_size": "Block budget for each node in the Clusters pattern. Valid range: 1 to 32.", - "tooltip.orespawn.rock.family": "Classify this rock as sedimentary, metamorphic, intrusive igneous, or volcanic igneous for geome and depth preferences.", - "tooltip.orespawn.rock.depth_peak": "Y level where this rock receives its strongest depth preference. Valid range: 0 to 255.", - "tooltip.orespawn.rock.depth_spread": "How gradually the rock's depth preference falls away from Depth Peak. Larger values cover a broader vertical range; valid range: 1 to 512.", - "tooltip.orespawn.rock.min_y": "Lowest Y where this rock may replace terrain. Valid range: 0 to 255; it must not exceed Maximum Y.", - "tooltip.orespawn.rock.max_y": "Highest Y where this rock may replace terrain. Valid range: 0 to 255; it must not be below Minimum Y.", - "tooltip.orespawn.rock.ore_replaceable": "Allow OreSpawn-managed ores to replace this rock when it is selected as a host family.", - "tooltip.orespawn.biome.dimension": "Select the dimension whose biome-placement and world-material settings are shown.", - "tooltip.orespawn.biome.palette_enabled": "Enable provider-supplied biome placement in this dimension. Turning it off preserves the saved biome entries.", - "tooltip.orespawn.biome.mode": "Augment mixes configured biomes with the original biome. Replace chooses only from eligible configured biomes.", - "tooltip.orespawn.biome.scope": "Choose which existing biome namespaces may be replaced: all biomes, Minecraft only, or selected mod namespaces.", - "tooltip.orespawn.biome.region_size": "Controls the horizontal size of biome-placement regions. Larger values create broader, less frequent boundaries.", - "tooltip.orespawn.biome.entries": "Open this dimension's biome entries to configure weights, climate limits, similarity rules, and surface materials.", - "tooltip.orespawn.biome.dimension_materials": "Configure dimension-wide aquifer fluids plus snow and ice replacements.", - "tooltip.orespawn.biome.geome_influences": "Map installed biomes to relative geome weights used by Sky geology.", - "tooltip.orespawn.biome.similar_biomes": "Allow this output only when the original biome matches one of these IDs. An empty list allows any biome within the climate limits.", - "tooltip.orespawn.biome.required_similar_biomes": "Like Similar Biomes, but this output is disabled if any listed biome is not installed.", - "tooltip.orespawn.biome.min_temperature": "Lowest original-biome temperature eligible for this output. Valid range: -2 to 2.", - "tooltip.orespawn.biome.max_temperature": "Highest original-biome temperature eligible for this output. Valid range: -2 to 2.", - "tooltip.orespawn.biome.min_downfall": "Lowest original-biome downfall eligible for this output. Valid range: 0 to 1.", - "tooltip.orespawn.biome.max_downfall": "Highest original-biome downfall eligible for this output. Valid range: 0 to 1.", - "tooltip.orespawn.biome.top_block": "Replace this biome's top surface block. Not set keeps the generated biome's normal top block.", - "tooltip.orespawn.biome.filler_block": "Replace the blocks immediately below the top surface. Filler Depth controls how many layers are changed.", - "tooltip.orespawn.biome.underwater_block": "Replace the biome's exposed underwater surface block. Not set keeps the normal block.", - "tooltip.orespawn.biome.ceiling_block": "Replace the biome's ceiling surface block in dimensions that generate ceilings. Not set keeps the normal block.", - "tooltip.orespawn.biome.filler_depth": "Number of layers below the top block that use Filler Block. Valid range: 0 to 16.", - "tooltip.orespawn.material.default_fluid": "Replace the normal aquifer fluid below sea level across every biome in this dimension. Not set keeps the generator's original fluid. Existing chunks are unchanged; fluids with unusual lighting may generate more slowly.", - "tooltip.orespawn.material.deep_aquifer_fluid": "Unavailable in Minecraft 1.14.4; the stored value is retained for later versions.", - "tooltip.orespawn.material.deep_aquifer_y": "Unavailable in Minecraft 1.14.4; the stored value is retained for later versions.", - "tooltip.orespawn.material.snow_block": "Replace vanilla snow placed near the surface in this dimension. Not set keeps normal snow.", - "tooltip.orespawn.material.ice_block": "Replace ordinary vanilla ice placed near the surface in this dimension. Not set keeps normal ice.", - "option.orespawn.min_quantity": "Minimum Block Budget", - "option.orespawn.max_quantity": "Maximum Block Budget", - "value.orespawn.dimension.all_except_nether_end": "All except Nether and End", - "option.orespawn.host_blocks_short": "Host Blocks", - "option.orespawn.host_tags_short": "Host Block Tags", - "option.orespawn.biome_ids_short": "Included Biomes", - "option.orespawn.excluded_biome_ids_short": "Excluded Biomes", - "option.orespawn.biome_dictionary_short": "Included Biome Types", - "option.orespawn.excluded_biome_dictionary_short": "Excluded Biome Types", - "screen.orespawn.world_settings": "OreSpawn Geology", - "button.orespawn.world_settings": "OreSpawn...", - "button.orespawn.configure_strata": "Configure Rock Strata...", - "button.orespawn.fluid_deposit_details": "Fluid Deposits...", - "button.orespawn.fluid_deposits_count": "Fluid Deposits: %s / %s", - "screen.orespawn.fluid_deposits": "Fluid Deposits", - "screen.orespawn.fluid_deposit": "Fluid Deposit", - "screen.orespawn.fluid_deposit_dimension": "Fluid Deposit Dimension", - "option.orespawn.fluid_deposits": "Fluid Deposits", - "option.orespawn.output_fluid": "Output Fluid Block", - "option.orespawn.biome_ids": "Biome IDs (comma separated)", - "option.orespawn.excluded_biome_ids": "Excluded Biome IDs (comma separated)", - "option.orespawn.biome_dictionary": "Biome Types (comma separated)", - "option.orespawn.excluded_biome_dictionary": "Excluded Biome Types (comma separated)", - "tooltip.orespawn.fluid_deposits": "ON generates configured covered underground fluid pockets. OFF keeps their settings but does not place them.", - "error.orespawn.host_required": "Choose at least one host family, block, or tag.", - "error.orespawn.invalid_values": "Check the values and registry IDs.", - "button.orespawn.recommended": "Recommended Defaults", - "button.orespawn.advanced": "Advanced Settings...", - "button.orespawn.help": "Help & Guide", - "button.orespawn.previous": "Previous", - "button.orespawn.next": "Next", - "button.orespawn.materials": "Rocks & Ores...", - "button.orespawn.geomes": "Geomes & Biomes...", - "button.orespawn.formation_details": "Custom Shapes...", - "button.orespawn.cyano_details": "Cyano Settings...", - "button.orespawn.geome_weights": "Geome Weights...", - "button.orespawn.search": "Search", - "button.orespawn.show_all": "Show All", - "button.orespawn.safe_only": "Safe Only", - "button.orespawn.add": "Add", - "button.orespawn.add_block": "Add Block...", - "button.orespawn.reset": "Reset", - "button.orespawn.unassign": "Unassign", - "button.orespawn.remove": "Remove", - "button.orespawn.remove_dimension": "Remove Dimension", - "screen.orespawn.numeric_settings": "Detailed Geology Settings", - "screen.orespawn.materials": "Worldgen Materials", - "screen.orespawn.assign_block": "Assign Block", - "screen.orespawn.choose_block": "Choose Installed Block", - "screen.orespawn.rock_entry": "Rock Settings", - "screen.orespawn.geome_weights": "Geome Weights", - "screen.orespawn.ore_entry": "Ore Settings", - "screen.orespawn.ore_dimension": "Ore Dimension Settings", - "screen.orespawn.geomes": "Geomes & Biome Influences", - "screen.orespawn.geome_entry": "Geome Settings", - "screen.orespawn.advanced": "Advanced Geology Settings", - "screen.orespawn.guide": "OreSpawn Player Guide", - "guide.orespawn.welcome.title": "Welcome to OreSpawn", - "guide.orespawn.welcome.1": "OreSpawn is a world-building engine used by other mods. Installed alone, it leaves terrain and vanilla ores unchanged.", - "guide.orespawn.welcome.2": "Provider mods can supply rocks, ores, fluid deposits, and ready-made settings. Ore-only mods do not have to add rock layers.", - "guide.orespawn.welcome.3": "Recommended Defaults restores the choices supplied by your installed mods and mod pack. It is the safest place to start.", - "guide.orespawn.world.title": "Choose Your Geology", - "guide.orespawn.world.1": "Your choices are copied into this world when it is created. A template loads a complete setup supplied by a mod or mod pack.", - "guide.orespawn.world.2": "Rock layers are optional. Sky makes biome-influenced geological regions called geomes. Cyano (Legacy) uses the classic older layer engine.", - "guide.orespawn.world.3": "Formation Reach controls width. Layer Thickness controls depth. Waviness bends layers, Edge Detail roughens their borders, and Continuity keeps formations together.", - "guide.orespawn.rocks.title": "Rocks and Geomes", - "guide.orespawn.rocks.1": "Sedimentary, metamorphic, and igneous rocks form in different places and at different depths. Geomes decide which families suit each region.", - "guide.orespawn.rocks.2": "Open Rocks & Ores to edit a block. Removing a rock only stops it appearing in new terrain; the block and its recipes stay available for old worlds.", - "guide.orespawn.rocks.3": "Configure Rock Strata starts with stone, granite, diorite, and andesite. Add Block can deliberately include mod rocks or special vanilla blocks.", - "guide.orespawn.ores.title": "Ores", - "guide.orespawn.ores.1": "Manage Vanilla Ores lets OreSpawn replace Minecraft's normal ore features with the rules shown here. Leave it off to keep vanilla placement.", - "guide.orespawn.ores.2": "Attempts per Chunk controls how often an ore tries to generate. Minimum and Maximum Block Budget control the possible size of each deposit.", - "guide.orespawn.ores.3": "Minimum and Maximum Y set depth. Hosts choose which rock families, blocks, or block tags may be replaced; geome weights favour particular regions.", - "guide.orespawn.mods.title": "Using Other Mods", - "guide.orespawn.mods.1": "Blocks and biomes from installed mods appear in the pickers. OreSpawn does not need a hard dependency just to use their registry names.", - "guide.orespawn.mods.2": "Provider mods and mod packs can supply ready-made rocks, ores, biome influences, dimensions, and templates. OreSpawn validates them before generation.", - "guide.orespawn.mods.3": "Full registry IDs, such as minecraft:granite, identify blocks safely. Missing blocks or invalid settings are rejected before a world is generated.", - "guide.orespawn.server.title": "Worlds and Servers", - "guide.orespawn.server.1": "Your choices are saved in serverconfig/orespawn-worldgen.json inside the world. Keep that file when moving the world to a dedicated server.", - "guide.orespawn.server.2": "Changes affect newly generated chunks only. Land you have already explored is never rewritten.", - "guide.orespawn.server.3": "A server needs the same mods used by the profile. For a new server world, a pack author may instead prepare config/orespawn-worldgen.json.", - "tab.orespawn.sedimentary": "Sedimentary", - "tab.orespawn.metamorphic": "Metamorphic", - "tab.orespawn.igneous": "Igneous", - "tab.orespawn.ores": "Ores", - "tab.orespawn.unassigned": "Unassigned", - "tab.orespawn.geomes": "Geomes", - "tab.orespawn.biomes": "Biomes", - "tab.orespawn.dictionary": "Biome Types", - "tab.orespawn.placement": "Placement", - "tab.orespawn.pattern": "Pattern", - "tab.orespawn.hosts": "Hosts", - "option.orespawn.geology_mode": "Geology", - "option.orespawn.template": "Template", - "option.orespawn.manage_vanilla_ores": "Manage Vanilla Ores", - "option.orespawn.search": "Search", - "option.orespawn.block_id": "Block registry ID", - "option.orespawn.registry_id": "Registry ID", - "option.orespawn.dimension": "Dimension ID", - "option.orespawn.available_dimension": "Available Dimension", - "option.orespawn.mod_filter": "Mod", - "option.orespawn.enabled": "Enabled", - "option.orespawn.family": "Rock Family", - "option.orespawn.weight": "Selection Weight", - "option.orespawn.depth_peak": "Preferred Y", - "option.orespawn.depth_spread": "Depth Spread", - "option.orespawn.min_y": "Minimum Y", - "option.orespawn.max_y": "Maximum Y", - "option.orespawn.frequency": "Attempts / Chunk", - "option.orespawn.ore_richness": "Ore Richness", - "option.orespawn.quantity": "Block Budget", - "option.orespawn.pattern": "Deposit Pattern", - "option.orespawn.height_distribution": "Height Distribution", - "option.orespawn.discard_air_exposure": "Air-Exposure Discard", - "option.orespawn.spread": "Horizontal Spread", - "option.orespawn.vertical_spread": "Vertical Spread", - "option.orespawn.node_size": "Cluster Node Size", - "option.orespawn.ore_replaceable": "Accepts Ores", - "option.orespawn.host_blocks": "Additional Host Blocks (comma separated)", - "option.orespawn.host_tags": "Host Block Tags (comma separated)", - "option.orespawn.base_weight": "Regional Base Weight", - "option.orespawn.stratum_wavelength": "Stratum Wavelength", - "option.orespawn.family_region_wavelength": "Family Region Wavelength", - "option.orespawn.waviness_wavelength": "Waviness Wavelength", - "option.orespawn.waviness_amplitude": "Waviness Amplitude", - "option.orespawn.edge_wavelength": "Edge Wavelength", - "option.orespawn.edge_amplitude": "Edge Amplitude", - "option.orespawn.edge_octaves": "Edge Octaves", - "option.orespawn.continuity": "Continuity", - "option.orespawn.geome_size": "Cyano Region Size", - "option.orespawn.rock_layer_noise": "Cyano Layer Reach", - "option.orespawn.rock_layer_thickness": "Cyano Layer Thickness", - "option.orespawn.min_radius": "Minimum Radius", - "option.orespawn.max_radius": "Maximum Radius", - "option.orespawn.min_vertical_radius": "Minimum Vertical Radius", - "option.orespawn.max_vertical_radius": "Maximum Vertical Radius", - "option.orespawn.max_lobes": "Maximum Lobes", - "option.orespawn.min_solid_cover": "Minimum Solid Cover", - "option.orespawn.min_solid_shell": "Minimum Solid Shell", - "option.orespawn.horizontal_size": "Formation Reach", - "option.orespawn.vertical_thickness": "Layer Thickness", - "option.orespawn.waviness": "Waviness", - "option.orespawn.edge_irregularity": "Edge Detail", - "option.orespawn.formation_continuity": "Continuity", - "value.orespawn.geology_mode.geome": "Sky", - "value.orespawn.geology_mode.legacy": "Cyano (Legacy)", - "value.orespawn.template.none": "Pack Defaults", - "value.orespawn.intrusive": "Igneous (Intrusive)", - "value.orespawn.volcanic": "Igneous (Volcanic)", - "value.orespawn.all_mods": "All Mods", - "value.orespawn.dimension.overworld": "Overworld", - "value.orespawn.dimension.the_nether": "The Nether", - "value.orespawn.dimension.the_end": "The End", - "label.orespawn.adding_to": "Add to %s", - "value.orespawn.family.sedimentary": "Sedimentary", - "value.orespawn.family.metamorphic": "Metamorphic", - "value.orespawn.family.igneous_intrusive": "Igneous (Intrusive)", - "value.orespawn.family.igneous_volcanic": "Igneous (Volcanic)", - "value.orespawn.ore_pattern.vein": "Vein", - "value.orespawn.ore_pattern.cluster": "Clusters", - "value.orespawn.ore_pattern.cloud": "Cloud", - "value.orespawn.height_distribution.uniform": "Uniform", - "value.orespawn.height_distribution.triangle": "Triangular", - "value.orespawn.height_distribution.bottom_triangle": "Bottom-Biased Triangle", - "value.orespawn.height_distribution.uniform_bottom_triangle": "Uniform + Bottom Triangle", - "value.orespawn.ore_richness.ultra_poor": "Ultra Poor", - "value.orespawn.ore_richness.poor": "Poor", - "value.orespawn.ore_richness.average": "Average", - "value.orespawn.ore_richness.rich": "Rich", - "value.orespawn.ore_richness.ultra_rich": "Ultra Rich", - "value.orespawn.preset.tiny": "Tiny", - "value.orespawn.preset.small": "Small", - "value.orespawn.preset.average": "Average", - "value.orespawn.preset.large": "Large", - "value.orespawn.preset.huge": "Huge", - "value.orespawn.preset.custom": "Custom", - "tooltip.orespawn.geology_mode": "Sky uses biome-influenced geomes. Cyano (Legacy) uses the original Cyano rock-layer engine.", - "tooltip.orespawn.manage_vanilla_ores": "ON disables Minecraft's normal ore features and generates those ores with OreSpawn's configured rules. OFF keeps vanilla ore placement.", - "tooltip.orespawn.ore_richness": "Scales attempts per chunk from this ore's installed-pack default. Each step halves or doubles abundance, up to the 64-attempt safety limit; depth and deposit shape stay unchanged.", - "tooltip.orespawn.available_dimension": "Lists dimensions from the current world settings and installed mod data. The registry ID below remains editable for server-only dimensions.", - "tooltip.orespawn.horizontal_size": "Controls how far individual rock formations persist horizontally.", - "tooltip.orespawn.vertical_thickness": "Controls the typical vertical thickness of rock layers.", - "tooltip.orespawn.waviness": "Controls the broad vertical slope and curvature of rock layers.", - "tooltip.orespawn.edge_irregularity": "Adds independent small-scale detail along layer boundaries.", - "tooltip.orespawn.formation_continuity": "Controls how often formations retain their identity across regional and geome boundaries.", - "value.orespawn.ore_pattern.default": "Compact", - "value.orespawn.ore_pattern.normal_cloud": "Cloud", - "value.orespawn.ore_pattern.precision": "Precision", - "value.orespawn.ore_pattern.clusters": "Clusters", - "value.orespawn.ore_pattern.underfluids": "Under Fluids", - "message.orespawn.external_pattern_read_only": "Settings for this registered pattern are read-only here.", - "screen.orespawn.biomes_world_materials": "Biomes & World Materials", - "screen.orespawn.biome_palette": "Biome Palette", - "screen.orespawn.choose_biome": "Choose Installed Biome", - "screen.orespawn.biome_placement": "Biome Settings", - "screen.orespawn.biome_references": "Similar Biomes", - "screen.orespawn.dimension_materials": "%s Materials", - "button.orespawn.biomes_world_materials": "Biomes & World Materials...", - "button.orespawn.biome_palette_count": "Biomes: %s", - "button.orespawn.dimension_materials": "World Materials...", - "button.orespawn.geome_influences": "Geome Influences...", - "button.orespawn.add_biome": "Add Biome...", - "button.orespawn.similar_biomes": "Similar: %s", - "button.orespawn.required_biomes": "Required: %s", - "button.orespawn.clear": "Clear", - "button.orespawn.biome_selected": "%s (selected)", - "button.orespawn.biome_available": "%s", - "option.orespawn.biome_palette": "Biome Palette", - "option.orespawn.biome_mode": "Placement Mode", - "option.orespawn.biome_scope": "Replacement Scope", - "option.orespawn.biome_region_size": "Region Size", - "option.orespawn.min_temperature": "Minimum Temperature", - "option.orespawn.max_temperature": "Maximum Temperature", - "option.orespawn.min_downfall": "Minimum Downfall", - "option.orespawn.max_downfall": "Maximum Downfall", - "option.orespawn.filler_depth": "Filler Depth", - "option.orespawn.top_block": "Top: %s", - "option.orespawn.filler_block": "Filler: %s", - "option.orespawn.underwater_block": "Underwater: %s", - "option.orespawn.ceiling_block": "Ceiling: %s", - "option.orespawn.default_fluid": "Aquifer Fluid: %s", - "option.orespawn.deep_aquifer_fluid": "Deep Aquifer: %s", - "option.orespawn.deep_aquifer_y": "Deep Aquifer Below Y", - "option.orespawn.snow_block": "Snow: %s", - "option.orespawn.ice_block": "Ice: %s", - "value.orespawn.not_set": "Not set", - "value.orespawn.biome_mode.augment": "Augment", - "value.orespawn.biome_mode.replace": "Replace", - "value.orespawn.biome_scope.all": "All Biomes", - "value.orespawn.biome_scope.minecraft_only": "Minecraft Only", - "value.orespawn.biome_scope.selected_namespaces": "Selected Mods", - "tab.orespawn.biome_placement": "Placement", - "tab.orespawn.biome_surface": "Surface", - "tab.orespawn.biome_climate": "Climate", - "guide.orespawn.biomes.title": "Biomes", - "guide.orespawn.biomes.1": "Provider mods can offer new biomes. Augment mixes them with the existing world, while Replace uses only the configured choices where the rule applies.", - "guide.orespawn.biomes.2": "Scope decides which existing biome namespaces can be replaced. Minecraft Only protects every modded biome; Selected Mods changes only namespaces you choose.", - "guide.orespawn.biomes.3": "Region Size controls broad patches. Each biome can use weight, climate limits, similar-biome hints, and optional top, filler, underwater, and ceiling blocks.", - "guide.orespawn.patterns.title": "Ore Shapes and Visibility", - "guide.orespawn.patterns.1": "Compact makes familiar blobs. Veins stretch through rock, Clusters form groups, Clouds spread broadly, and Under Fluids favours blocks beneath liquids.", - "guide.orespawn.patterns.2": "Height Distribution controls where attempts land between Minimum and Maximum Y. Uniform spreads them evenly; triangle choices favour particular depths.", - "guide.orespawn.patterns.3": "Air-Exposure Discard hides some ore touching caves. 0 keeps every exposed attempt and 1 rejects all exposed attempts; values between are chances.", - "guide.orespawn.fluids.title": "Fluid Deposits", - "guide.orespawn.fluids.1": "Fluid Deposits create covered underground pockets of water, lava, oil, or another installed fluid. They are separate from oceans and World Materials.", - "guide.orespawn.fluids.2": "Attempts per Chunk controls rarity. Horizontal and Vertical Radius set deposit size, while Lobes join several rounded pockets into a less regular shape.", - "guide.orespawn.fluids.3": "Solid Cover protects the roof and Solid Shell protects the sides and floor from caves. Hosts and biome rules decide where a deposit is allowed.", - "guide.orespawn.materials.title": "World Materials", - "guide.orespawn.materials.1": "World Materials changes background materials across a whole dimension. Use Fluid Deposits instead when you only want occasional underground pockets.", - "guide.orespawn.materials.2": "Aquifer Fluid changes the normal fluid used below sea level. Deep Aquifer uses a second fluid below the chosen Y level.", - "guide.orespawn.materials.3": "Snow and Ice replace vanilla snow and ordinary ice near the surface. Not set leaves Minecraft's normal material unchanged.", - "button.orespawn.dimension_materials_named": "%s Materials...", - "label.orespawn.dimension_materials.scope": "Applies to every biome in newly generated %s terrain.", - "button.orespawn.mods": "Mods", - "button.orespawn.mod.configure": "Configure", - "tooltip.orespawn.main.mods": "View loaded mods integrated with OreSpawn.", - "screen.orespawn.mods": "OreSpawn Mods", - "tooltip.orespawn.mod.configure": "Open %s configuration.", - "tooltip.orespawn.mod.unavailable": "%s does not provide an OreSpawn-linked configuration screen.", - "label.orespawn.mod.id_version": "%s - Mod version %s", - "label.orespawn.mod.additional_lineage": "Also detected through OreSpawn %s compatibility.", - "label.orespawn.mod.status": "Status: %s", - "label.orespawn.mod.os4_version": "Native OS4 - schema %s, provider revision %s", - "label.orespawn.mod.os4": "Native OS4 provider", - "label.orespawn.mod.legacy_version": "OreSpawn %s compatibility -> OS4 schema %s, provider revision %s", - "label.orespawn.mod.legacy": "OreSpawn %s compatibility -> OS4", - "label.orespawn.mod.config_only": "Client configuration integration", - "label.orespawn.mod.none": "No loaded OreSpawn integrations were found.", - "label.orespawn.mod.integration_status": "%s - %s", - "status.orespawn.mod.active": "Active", - "status.orespawn.mod.pending": "Pending", - "status.orespawn.mod.inactive": "Inactive", - "status.orespawn.mod.rejected": "Rejected", - "status.orespawn.mod.config_only": "Configuration screen only", - "error.orespawn.mod.screen_missing": "%s did not create a configuration screen.", - "error.orespawn.mod.screen_failed": "Could not open %s configuration (%s).", - "button.orespawn.ore_sources": "Ore Sources...", - "tooltip.orespawn.ore_sources": "Review equivalent ore outputs without multiplying placement frequency.", - "screen.orespawn.ore_sources": "Ore Sources", - "screen.orespawn.ore_source_detail": "Ore Source Policy", - "label.orespawn.ore_source.none": "No equivalent managed ore sources were found.", - "label.orespawn.ore_source.row": "%s - %s - %s candidates - %s", - "label.orespawn.ore_source.intro": "Choose how equivalent ores generate.", - "label.orespawn.ore_source.summary": "%s candidates - %s", - "button.orespawn.ore_source.review": "Review...", - "button.orespawn.ore_source.configure": "Configure...", - "label.orespawn.ore_source.material": "Material: %s", - "label.orespawn.ore_source.domain": "Dimension/domain: %s", - "label.orespawn.ore_source.channels": "Placement channels: %s", - "label.orespawn.ore_source.missing": "Missing placement source", - "label.orespawn.ore_source.owner": "Owner: %s, version %s", - "label.orespawn.ore_source.registry": "Registry output: %s, metadata %s", - "label.orespawn.ore_source.dictionary": "Block tags: %s", - "option.orespawn.ore_source.mode": "Mode: %s", - "option.orespawn.ore_source.channel": "Channel: %s", - "option.orespawn.ore_source.placement": "Placement source: %s", - "option.orespawn.ore_source.weight": "Weight", - "mode.orespawn.ore_source.consolidated": "Consolidated", - "mode.orespawn.ore_source.keep_separate": "Keep Separate", - "status.orespawn.ore_source.consolidated": "Consolidated", - "status.orespawn.ore_source.separate": "Separate", - "status.orespawn.ore_source.review_required": "Review required", - "status.orespawn.ore_source.missing_source": "Missing source", - "status.orespawn.ore_source.external_generation": "External generation", - "tooltip.orespawn.ore_source.open": "Open this material policy.", - "tooltip.orespawn.ore_source.mode": "Consolidated uses one placement budget per channel. Keep Separate preserves every configured rule.", - "tooltip.orespawn.ore_source.channel": "Placement engines are arbitrated independently.", - "tooltip.orespawn.ore_source.placement": "Choose the rule that owns frequency, shape, hosts, filters and height for this channel.", - "tooltip.orespawn.ore_source.weight": "Positive relative chance of selecting this output for a whole vein or identified deposit body.", - "tooltip.orespawn.ore_source.external": "This mod registers generation outside OreSpawn; OreSpawn reports it but cannot suppress it.", - "tooltip.orespawn.ore_source.controlled": "OreSpawn controls this configured placement and output source.", - "tooltip.orespawn.ore_source.enrichment": "This entry is enrichment, not an interchangeable ore source.", - "tooltip.orespawn.ore_source.missing": "This source is unavailable. Its saved selection will be restored if the owning mod returns.", - "error.orespawn.ore_source.weight": "Output weights must be positive numbers.", - "button.orespawn.back": "Back", - "button.orespawn.ore_source.all_groups": "All Groups", - "button.orespawn.ore_source.add_group": "Add Group", - "button.orespawn.ore_source.accept": "Accept", - "tooltip.orespawn.ore_source.accept": "Keep the current Keep Original policy unchanged and mark this group as reviewed. It is saved only when the main editor's Done is used.", - "button.orespawn.ore_source.delete_group": "Delete", - "button.orespawn.ore_source.dissolve_group": "Dissolve Group", - "button.orespawn.ore_source.confirm_dissolve": "Confirm Dissolve", - "button.orespawn.ore_source.move": "Move", - "button.orespawn.ore_source.advanced": "Advanced...", - "button.orespawn.ore_source.hide_advanced": "Hide Advanced", - "option.orespawn.ore_source.group_name": "Group name", - "option.orespawn.ore_source.alias": "Block tag", - "option.orespawn.ore_source.output_mode": "Output: %s", - "mode.orespawn.ore_source.keep_original": "Keep Original", - "mode.orespawn.ore_source.balanced": "Balanced", - "mode.orespawn.ore_source.single": "Single", - "mode.orespawn.ore_source.custom": "Custom", - "label.orespawn.ore_source.no_aliases": "No block tags", - "status.orespawn.ore_source.external_short": "external", - "status.orespawn.ore_source.missing_short": "missing", - "status.orespawn.ore_source.output_only": "output only", - "tooltip.orespawn.ore_source.output_only": "This provider output is available, but its placement rule is inactive.", - "tooltip.orespawn.ore_source.output_mode": "Keep Original preserves every rule. Balanced shares equally, Single chooses one block, and Custom enables weighted choices.", - "tooltip.orespawn.ore_source.alias": "Add an exact block tag ID, such as forge:ores/sulfur. Press Move again to confirm reassignment from another group.", - "tooltip.orespawn.ore_source.reset_group": "Restore this curated group name and block tag entries.", - "tooltip.orespawn.ore_source.delete_group": "Delete this empty custom group without rewriting generated chunks.", - "tooltip.orespawn.ore_source.dissolve_group": "Return every entry to its inferred or curated group. Press twice to confirm.", - "error.orespawn.ore_source.confirm_dissolve": "Press Confirm Dissolve to return every block tag entry to its original group.", - "error.orespawn.ore_source.alias": "Use an exact block tag ID such as forge:ores/sulfur.", - "error.orespawn.ore_source.alias_owned": "%s already owns this entry. Press Move to reassign it.", - "error.orespawn.ore_source.manage_vanilla_first": "Enable Manage Vanilla Ores before moving a native vanilla ore into another group.", - "error.orespawn.ore_source.defaults_write": "Could not save material-group defaults.", - "screen.orespawn.ore_source.group_settings": "Ore Source Group Settings", - "label.orespawn.ore_source.groups": "Groups", - "label.orespawn.ore_source.aliases": "Block tags", - "label.orespawn.ore_source.placement_rules": "Placement Rules", - "label.orespawn.ore_source.placement_explanation": "Outputs choose the block; placement rules choose frequency, shape, depth and hosts.", - "label.orespawn.ore_source.standard_veins": "Standard veins", - "label.orespawn.ore_source.placement_choice_count": "%s (%s choices)", - "label.orespawn.ore_source.no_placement_rules": "No managed placement rules", - "tooltip.orespawn.ore_source.group_settings": "Edit this group's name, aliases and placement rules.", - "tooltip.orespawn.ore_source.remove_alias": "Remove %s from this group.", - "tooltip.orespawn.ore_source.placement_rules": "Outputs select the ore block; placement rules select frequency, shape, depth and host restrictions.", - "tooltip.orespawn.ore_source.placement_requires_consolidated": "Placement ownership applies only to consolidated Balanced, Single or Custom modes.", - "tooltip.orespawn.ore_source.placement_missing": "The saved placement source is missing; this channel remains disabled.", - "tooltip.orespawn.ore_source.placement_readonly": "Only one active managed rule is available, so this source is read-only.", - "tooltip.orespawn.ore_source.placement_select": "Click to choose between active managed placement sources.", - "tooltip.orespawn.ore_source.external_excluded": "Independent external generators are reported but cannot be selected as placement rules.", - "button.orespawn.ore_source.hide_single": "Hide Singles", - "tooltip.orespawn.ore_source.group_colours": "Green entries have one alias and one output and need no action. Yellow groups have a saved rule. Red groups need attention. Show All includes green entries.", - "button.orespawn.ore_source.reset_all": "Reset All", - "button.orespawn.ore_source.confirm_reset_all": "Confirm Reset", - "tooltip.orespawn.ore_source.reset_all": "Restore built-in material groups and recreate source policies from the currently loaded ores. The change remains pending until the main editor's Done button is used.", - "screen.orespawn.biomes": "Biomes", - "screen.orespawn.biome_palettes": "Biome Palettes", - "screen.orespawn.biome_palette_settings": "Biome Palette Settings", - "button.orespawn.biome.hide_routine": "Hide Routine", - "button.orespawn.biome.replace_new_terrain": "Replace in new terrain with...", - "button.orespawn.biome.replace_with": "Replace in new terrain with %s...", - "button.orespawn.biome.leave_original": "Leave original behaviour", - "button.orespawn.biome.palettes": "Palettes: %s", - "button.orespawn.biome.reset_selected": "Reset Biome", - "button.orespawn.biome.confirm_reset": "Confirm Reset", - "button.orespawn.biome.reset_palette": "Reset Palette", - "button.orespawn.biome.confirm_reset_palette": "Confirm Palette Reset", - "button.orespawn.biome.reset_dimension": "Reset Dimension", - "button.orespawn.biome.confirm_reset_dimension": "Confirm Dimension Reset", - "button.orespawn.biome.reset_all": "Reset All Biomes", - "button.orespawn.biome.confirm_reset_all": "Confirm All-Biome Reset", - "value.orespawn.biome.status.user_replaced": "Replaced in new terrain", - "value.orespawn.biome.status.layered": "Several placement rules", - "value.orespawn.biome.status.disabled": "Placement disabled", - "value.orespawn.biome.status.missing": "Missing biome or provider", - "value.orespawn.biome.status.provider_managed": "Provider-managed", - "value.orespawn.biome.status.unmanaged": "Registered, unmanaged", - "label.orespawn.biome.rule_count": "Placement rules: %s", - "label.orespawn.biome.replaced_by": "New-terrain replacement: %s", - "label.orespawn.biome.palette_owner_order": "Owner: %s; effective order: %s", - "label.orespawn.biome.surface_effective": "This rule supplies the effective surface.", - "label.orespawn.biome.surface_overridden": "A later enabled rule overrides this surface.", - "label.orespawn.biome.placement_rules": "Placement rules", - "label.orespawn.biome.palette_entries": "Placement entries: %s", - "tooltip.orespawn.biome.no_retrogen": "Biome replacements apply only while new terrain is generated. Existing chunks are never rewritten.", - "tooltip.orespawn.biome.override_palette": "Reserved final replacement layer. Edit it through each biome's replacement control.", - "tooltip.orespawn.biome.palette_entries_read_only": "Palette membership is provider/profile-defined. Select a biome in the directory to edit an existing placement rule.", - "option.orespawn.biome.coverage": "Coverage", - "option.orespawn.biome.fallback_weight": "Original-biome weight", - "option.orespawn.biome.include_namespaces": "Included namespaces (comma-separated)", - "option.orespawn.biome.exclude_namespaces": "Excluded namespaces (comma-separated)" -} diff --git a/src/main/resources/assets/orespawn/lang/en_gb.json b/src/main/resources/assets/orespawn/lang/en_gb.json index e495e4a4..40737272 100644 --- a/src/main/resources/assets/orespawn/lang/en_gb.json +++ b/src/main/resources/assets/orespawn/lang/en_gb.json @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "Coverage", "option.orespawn.biome.fallback_weight": "Original-biome weight", "option.orespawn.biome.include_namespaces": "Included namespaces (comma-separated)", - "option.orespawn.biome.exclude_namespaces": "Excluded namespaces (comma-separated)" + "option.orespawn.biome.exclude_namespaces": "Excluded namespaces (comma-separated)", + "commands.orespawn.help": "OreSpawn tools: status verbose; chunk [x z]; survey [radius]; explain [x y z]; retrogen status; jobs; cancel ; clearchunk; undo .", + "commands.orespawn.options": "Options: --dimension , --center , --y , --block . Survey radius: 0–8 (default 1).", + "commands.orespawn.safety": "Clearing changes player-placed terrain too. Use a disposable world. Level 4, Creative/Spectator, a preview and a verified backup are required. Undo cannot reverse entities or time.", + "commands.orespawn.scope": "Surveys inspect loaded chunks only. Reports describe observed blocks, not their historical generator or guaranteed future placement.", + "commands.orespawn.data": "Data: %s", + "commands.orespawn.report": "Report %s: %s", + "commands.orespawn.started": "Job started. %s", + "commands.orespawn.preview_started": "Preparing preview; no blocks will change.", + "commands.orespawn.preview_title": "Preview only — nothing changed.", + "commands.orespawn.preview_location": "%s | Chunk %s, %s | Y %s–%s", + "commands.orespawn.preview_clear_counts": "Clear %s blocks; keep %s.", + "commands.orespawn.preview_undo_counts": "Restore up to %s blocks; keep %s others.", + "commands.orespawn.preview_warning": "Also clears matching player-placed terrain. Use a test world.", + "commands.orespawn.preview_undo_warning": "Undo restores blocks, not entities or elapsed time.", + "commands.orespawn.preview_expiry": "Open chat to choose below. Expires in 2 min.", + "commands.orespawn.confirm_clear": "[Confirm clearing]", + "commands.orespawn.confirm_undo": "[Confirm undo]", + "commands.orespawn.preview_cancel": "[Cancel]", + "commands.orespawn.preview_cancelled": "Preview cancelled. No blocks changed.", + "commands.orespawn.preview_inactive": "This preview is no longer active.", + "commands.orespawn.action_hint": "Click to run: %s", + "commands.orespawn.details": "[Details]", + "commands.orespawn.complete_clear": "Cleared %s blocks. %s %s", + "commands.orespawn.complete_undo": "Restored %s blocks. %s", + "commands.orespawn.undo_preview": "[Undo…]", + "commands.orespawn.job_result": "Job %s — %s: %s", + "commands.orespawn.backups": "Backups remain here across restarts: %s. Use /orespawn undo .", + "commands.orespawn.failed": "OreSpawn could not do that: %s" } diff --git a/src/main/resources/assets/orespawn/lang/en_pt.json b/src/main/resources/assets/orespawn/lang/en_pt.json index e495e4a4..5f9afa02 100644 --- a/src/main/resources/assets/orespawn/lang/en_pt.json +++ b/src/main/resources/assets/orespawn/lang/en_pt.json @@ -115,15 +115,15 @@ "option.orespawn.excluded_biome_ids_short": "Excluded Biomes", "option.orespawn.biome_dictionary_short": "Included Biome Types", "option.orespawn.excluded_biome_dictionary_short": "Excluded Biome Types", - "screen.orespawn.world_settings": "OreSpawn Geology", - "button.orespawn.world_settings": "OreSpawn...", - "button.orespawn.configure_strata": "Configure Rock Strata...", - "button.orespawn.fluid_deposit_details": "Fluid Deposits...", - "button.orespawn.fluid_deposits_count": "Fluid Deposits: %s / %s", - "screen.orespawn.fluid_deposits": "Fluid Deposits", - "screen.orespawn.fluid_deposit": "Fluid Deposit", - "screen.orespawn.fluid_deposit_dimension": "Fluid Deposit Dimension", - "option.orespawn.fluid_deposits": "Fluid Deposits", + "screen.orespawn.world_settings": "OreSpawn's Chart Room", + "button.orespawn.world_settings": "OreSpawn Ahoy...", + "button.orespawn.configure_strata": "Chart Rock Layers...", + "button.orespawn.fluid_deposit_details": "Liquid Caches...", + "button.orespawn.fluid_deposits_count": "Liquid Caches: %s / %s", + "screen.orespawn.fluid_deposits": "Liquid Caches", + "screen.orespawn.fluid_deposit": "Liquid Cache", + "screen.orespawn.fluid_deposit_dimension": "Liquid Cache Waters", + "option.orespawn.fluid_deposits": "Liquid Caches", "option.orespawn.output_fluid": "Output Fluid Block", "option.orespawn.biome_ids": "Biome IDs (comma separated)", "option.orespawn.excluded_biome_ids": "Excluded Biome IDs (comma separated)", @@ -132,61 +132,61 @@ "tooltip.orespawn.fluid_deposits": "ON generates configured covered underground fluid pockets. OFF keeps their settings but does not place them.", "error.orespawn.host_required": "Choose at least one host family, block, or tag.", "error.orespawn.invalid_values": "Check the values and registry IDs.", - "button.orespawn.recommended": "Recommended Defaults", - "button.orespawn.advanced": "Advanced Settings...", - "button.orespawn.help": "Help & Guide", - "button.orespawn.previous": "Previous", - "button.orespawn.next": "Next", - "button.orespawn.materials": "Rocks & Ores...", - "button.orespawn.geomes": "Geomes & Biomes...", - "button.orespawn.formation_details": "Custom Shapes...", - "button.orespawn.cyano_details": "Cyano Settings...", - "button.orespawn.geome_weights": "Geome Weights...", - "button.orespawn.search": "Search", - "button.orespawn.show_all": "Show All", - "button.orespawn.safe_only": "Safe Only", - "button.orespawn.add": "Add", - "button.orespawn.add_block": "Add Block...", - "button.orespawn.reset": "Reset", - "button.orespawn.unassign": "Unassign", - "button.orespawn.remove": "Remove", - "button.orespawn.remove_dimension": "Remove Dimension", - "screen.orespawn.numeric_settings": "Detailed Geology Settings", - "screen.orespawn.materials": "Worldgen Materials", - "screen.orespawn.assign_block": "Assign Block", - "screen.orespawn.choose_block": "Choose Installed Block", - "screen.orespawn.rock_entry": "Rock Settings", - "screen.orespawn.geome_weights": "Geome Weights", - "screen.orespawn.ore_entry": "Ore Settings", - "screen.orespawn.ore_dimension": "Ore Dimension Settings", - "screen.orespawn.geomes": "Geomes & Biome Influences", - "screen.orespawn.geome_entry": "Geome Settings", - "screen.orespawn.advanced": "Advanced Geology Settings", - "screen.orespawn.guide": "OreSpawn Player Guide", - "guide.orespawn.welcome.title": "Welcome to OreSpawn", - "guide.orespawn.welcome.1": "OreSpawn is a world-building engine used by other mods. Installed alone, it leaves terrain and vanilla ores unchanged.", - "guide.orespawn.welcome.2": "Provider mods can supply rocks, ores, fluid deposits, and ready-made settings. Ore-only mods do not have to add rock layers.", - "guide.orespawn.welcome.3": "Recommended Defaults restores the choices supplied by your installed mods and mod pack. It is the safest place to start.", - "guide.orespawn.world.title": "Choose Your Geology", - "guide.orespawn.world.1": "Your choices are copied into this world when it is created. A template loads a complete setup supplied by a mod or mod pack.", - "guide.orespawn.world.2": "Rock layers are optional. Sky makes biome-influenced geological regions called geomes. Cyano (Legacy) uses the classic older layer engine.", - "guide.orespawn.world.3": "Formation Reach controls width. Layer Thickness controls depth. Waviness bends layers, Edge Detail roughens their borders, and Continuity keeps formations together.", - "guide.orespawn.rocks.title": "Rocks and Geomes", - "guide.orespawn.rocks.1": "Sedimentary, metamorphic, and igneous rocks form in different places and at different depths. Geomes decide which families suit each region.", - "guide.orespawn.rocks.2": "Open Rocks & Ores to edit a block. Removing a rock only stops it appearing in new terrain; the block and its recipes stay available for old worlds.", - "guide.orespawn.rocks.3": "Configure Rock Strata starts with stone, granite, diorite, and andesite. Add Block can deliberately include mod rocks or special vanilla blocks.", - "guide.orespawn.ores.title": "Ores", - "guide.orespawn.ores.1": "Manage Vanilla Ores lets OreSpawn replace Minecraft's normal ore features with the rules shown here. Leave it off to keep vanilla placement.", - "guide.orespawn.ores.2": "Attempts per Chunk controls how often an ore tries to generate. Minimum and Maximum Block Budget control the possible size of each deposit.", - "guide.orespawn.ores.3": "Minimum and Maximum Y set depth. Hosts choose which rock families, blocks, or block tags may be replaced; geome weights favour particular regions.", - "guide.orespawn.mods.title": "Using Other Mods", - "guide.orespawn.mods.1": "Blocks and biomes from installed mods appear in the pickers. OreSpawn does not need a hard dependency just to use their registry names.", - "guide.orespawn.mods.2": "Provider mods and mod packs can supply ready-made rocks, ores, biome influences, dimensions, and templates. OreSpawn validates them before generation.", - "guide.orespawn.mods.3": "Full registry IDs, such as minecraft:granite, identify blocks safely. Missing blocks or invalid settings are rejected before a world is generated.", - "guide.orespawn.server.title": "Worlds and Servers", - "guide.orespawn.server.1": "Your choices are saved in serverconfig/orespawn-worldgen.json inside the world. Keep that file when moving the world to a dedicated server.", - "guide.orespawn.server.2": "Changes affect newly generated chunks only. Land you have already explored is never rewritten.", - "guide.orespawn.server.3": "A server needs the same mods used by the profile. For a new server world, a pack author may instead prepare config/orespawn-worldgen.json.", + "button.orespawn.recommended": "Captain's Defaults", + "button.orespawn.advanced": "Fine-Tune the Charts...", + "button.orespawn.help": "Captain's Handbook", + "button.orespawn.previous": "Astern", + "button.orespawn.next": "Ahead", + "button.orespawn.materials": "Rocks & Buried Ores...", + "button.orespawn.geomes": "Chart Geomes & Biomes...", + "button.orespawn.formation_details": "Shape the Layers...", + "button.orespawn.cyano_details": "Rig the Cyano Engine...", + "button.orespawn.geome_weights": "Weigh the Geomes...", + "button.orespawn.search": "Spyglass", + "button.orespawn.show_all": "Show the Lot", + "button.orespawn.safe_only": "Safe Cargo Only", + "button.orespawn.add": "Bring Aboard", + "button.orespawn.add_block": "Bring a Block Aboard...", + "button.orespawn.reset": "Restore the Chart", + "button.orespawn.unassign": "Unclaim", + "button.orespawn.remove": "Strike Off", + "button.orespawn.remove_dimension": "Strike Off Dimension", + "screen.orespawn.numeric_settings": "Geology Chart Details", + "screen.orespawn.materials": "World Materials Ledger", + "screen.orespawn.assign_block": "Give the Block a Job", + "screen.orespawn.choose_block": "Pick a Block from the Hold", + "screen.orespawn.rock_entry": "Rock Chart", + "screen.orespawn.geome_weights": "Weigh the Geomes", + "screen.orespawn.ore_entry": "Ore Chart", + "screen.orespawn.ore_dimension": "Ore Chart by Dimension", + "screen.orespawn.geomes": "Geomes & Biome Charts", + "screen.orespawn.geome_entry": "Geome Chart", + "screen.orespawn.advanced": "Fine-Tune the Geology Charts", + "screen.orespawn.guide": "OreSpawn Captain's Handbook", + "guide.orespawn.welcome.title": "Welcome Aboard OreSpawn", + "guide.orespawn.welcome.1": "OreSpawn helps other mods build yer world. With no providers aboard, it leaves the land and vanilla ores as they were.", + "guide.orespawn.welcome.2": "Provider mods can bring rocks, ores, liquid caches and ready-made orders aboard. An ore-only mod needn't lay any rock layers.", + "guide.orespawn.welcome.3": "Captain's Defaults restores the choices from yer mods and mod pack. Start there if ye haven't charted a course.", + "guide.orespawn.world.title": "Chart Yer Geology", + "guide.orespawn.world.1": "Yer choices are copied into the world when ye make it. A template brings aboard a complete setup from a mod or mod pack.", + "guide.orespawn.world.2": "Rock layers are optional. Sky draws regions called geomes with help from the biomes. Cyano (Legacy) follows the old layer charts.", + "guide.orespawn.world.3": "Formation Reach sets width; Layer Thickness sets depth. Waviness bends the layers, Edge Detail roughens the borders, and Continuity holds the formations together.", + "guide.orespawn.rocks.title": "Rocks Beneath the Keel", + "guide.orespawn.rocks.1": "Sedimentary, metamorphic and igneous rocks belong in different places and at different depths. The geome charts say which families suit each region.", + "guide.orespawn.rocks.2": "Open Rocks & Buried Ores to edit a block. Strike a rock off the chart and it stops appearing in new land; its block and recipes stay aboard for old worlds.", + "guide.orespawn.rocks.3": "Chart Rock Layers starts with stone, granite, diorite and andesite. Bring a Block Aboard can add mod rocks or special vanilla blocks.", + "guide.orespawn.ores.title": "Chart the Buried Ores", + "guide.orespawn.ores.1": "Manage Vanilla Loot lets OreSpawn use these rules in place of Minecraft's usual ore features. Leave it off to keep vanilla placement.", + "guide.orespawn.ores.2": "Attempts per Chunk says how often ye try for ore. Minimum and Maximum Block Budget set the possible size of each deposit.", + "guide.orespawn.ores.3": "Minimum and Maximum Y set depth. Hosts tell ye which rock families, blocks or tags can be replaced; geome weights favour some regions over others.", + "guide.orespawn.mods.title": "Bring Other Mods Aboard", + "guide.orespawn.mods.1": "Blocks and biomes from mods aboard appear in the pickers. OreSpawn needn't depend on a mod just to use its registry names.", + "guide.orespawn.mods.2": "Provider mods and packs can bring ready-made rocks, ores, biome influences, dimensions and templates. OreSpawn checks the cargo before generation.", + "guide.orespawn.mods.3": "Use full registry IDs like minecraft:granite to point to the right block. Missing blocks and bad settings are caught before the world is made.", + "guide.orespawn.server.title": "Keep Yer World and Server Charts", + "guide.orespawn.server.1": "Yer world keeps its orders in serverconfig/orespawn-worldgen.json. Take that file aboard when ye move the world to a dedicated server.", + "guide.orespawn.server.2": "These changes only reach newly charted chunks. Land ye already explored won't be rewritten.", + "guide.orespawn.server.3": "A server needs the same mods aboard as the saved profile. For a new server world, a pack author can prepare config/orespawn-worldgen.json instead.", "tab.orespawn.sedimentary": "Sedimentary", "tab.orespawn.metamorphic": "Metamorphic", "tab.orespawn.igneous": "Igneous", @@ -200,14 +200,14 @@ "tab.orespawn.hosts": "Hosts", "option.orespawn.geology_mode": "Geology", "option.orespawn.template": "Template", - "option.orespawn.manage_vanilla_ores": "Manage Vanilla Ores", - "option.orespawn.search": "Search", + "option.orespawn.manage_vanilla_ores": "Manage Vanilla Loot", + "option.orespawn.search": "Spyglass", "option.orespawn.block_id": "Block registry ID", "option.orespawn.registry_id": "Registry ID", "option.orespawn.dimension": "Dimension ID", "option.orespawn.available_dimension": "Available Dimension", "option.orespawn.mod_filter": "Mod", - "option.orespawn.enabled": "Enabled", + "option.orespawn.enabled": "In Service", "option.orespawn.family": "Rock Family", "option.orespawn.weight": "Selection Weight", "option.orespawn.depth_peak": "Preferred Y", @@ -252,10 +252,10 @@ "option.orespawn.formation_continuity": "Continuity", "value.orespawn.geology_mode.geome": "Sky", "value.orespawn.geology_mode.legacy": "Cyano (Legacy)", - "value.orespawn.template.none": "Pack Defaults", + "value.orespawn.template.none": "Pack's Own Orders", "value.orespawn.intrusive": "Igneous (Intrusive)", "value.orespawn.volcanic": "Igneous (Volcanic)", - "value.orespawn.all_mods": "All Mods", + "value.orespawn.all_mods": "All Mods Aboard", "value.orespawn.dimension.overworld": "Overworld", "value.orespawn.dimension.the_nether": "The Nether", "value.orespawn.dimension.the_end": "The End", @@ -297,20 +297,20 @@ "value.orespawn.ore_pattern.clusters": "Clusters", "value.orespawn.ore_pattern.underfluids": "Under Fluids", "message.orespawn.external_pattern_read_only": "Settings for this registered pattern are read-only here.", - "screen.orespawn.biomes_world_materials": "Biomes & World Materials", - "screen.orespawn.biome_palette": "Biome Palette", - "screen.orespawn.choose_biome": "Choose Installed Biome", - "screen.orespawn.biome_placement": "Biome Settings", - "screen.orespawn.biome_references": "Similar Biomes", - "screen.orespawn.dimension_materials": "%s Materials", + "screen.orespawn.biomes_world_materials": "Biomes & the World's Cargo", + "screen.orespawn.biome_palette": "Biome Chart", + "screen.orespawn.choose_biome": "Pick a Biome Aboard", + "screen.orespawn.biome_placement": "Biome Chart Settings", + "screen.orespawn.biome_references": "Lookalike Biomes", + "screen.orespawn.dimension_materials": "%s Cargo", "button.orespawn.biomes_world_materials": "Biomes & World Materials...", - "button.orespawn.biome_palette_count": "Biomes: %s", - "button.orespawn.dimension_materials": "World Materials...", - "button.orespawn.geome_influences": "Geome Influences...", - "button.orespawn.add_biome": "Add Biome...", + "button.orespawn.biome_palette_count": "Biomes Aboard: %s", + "button.orespawn.dimension_materials": "World Cargo...", + "button.orespawn.geome_influences": "Chart Geome Influences...", + "button.orespawn.add_biome": "Bring a Biome Aboard...", "button.orespawn.similar_biomes": "Similar: %s", "button.orespawn.required_biomes": "Required: %s", - "button.orespawn.clear": "Clear", + "button.orespawn.clear": "Clear the Slate", "button.orespawn.biome_selected": "%s (selected)", "button.orespawn.biome_available": "%s", "option.orespawn.biome_palette": "Biome Palette", @@ -340,28 +340,28 @@ "tab.orespawn.biome_placement": "Placement", "tab.orespawn.biome_surface": "Surface", "tab.orespawn.biome_climate": "Climate", - "guide.orespawn.biomes.title": "Biomes", - "guide.orespawn.biomes.1": "Provider mods can offer new biomes. Augment mixes them with the existing world, while Replace uses only the configured choices where the rule applies.", - "guide.orespawn.biomes.2": "Scope decides which existing biome namespaces can be replaced. Minecraft Only protects every modded biome; Selected Mods changes only namespaces you choose.", - "guide.orespawn.biomes.3": "Region Size controls broad patches. Each biome can use weight, climate limits, similar-biome hints, and optional top, filler, underwater, and ceiling blocks.", - "guide.orespawn.patterns.title": "Ore Shapes and Visibility", - "guide.orespawn.patterns.1": "Compact makes familiar blobs. Veins stretch through rock, Clusters form groups, Clouds spread broadly, and Under Fluids favours blocks beneath liquids.", - "guide.orespawn.patterns.2": "Height Distribution controls where attempts land between Minimum and Maximum Y. Uniform spreads them evenly; triangle choices favour particular depths.", - "guide.orespawn.patterns.3": "Air-Exposure Discard hides some ore touching caves. 0 keeps every exposed attempt and 1 rejects all exposed attempts; values between are chances.", - "guide.orespawn.fluids.title": "Fluid Deposits", - "guide.orespawn.fluids.1": "Fluid Deposits create covered underground pockets of water, lava, oil, or another installed fluid. They are separate from oceans and World Materials.", - "guide.orespawn.fluids.2": "Attempts per Chunk controls rarity. Horizontal and Vertical Radius set deposit size, while Lobes join several rounded pockets into a less regular shape.", - "guide.orespawn.fluids.3": "Solid Cover protects the roof and Solid Shell protects the sides and floor from caves. Hosts and biome rules decide where a deposit is allowed.", - "guide.orespawn.materials.title": "World Materials", - "guide.orespawn.materials.1": "World Materials changes background materials across a whole dimension. Use Fluid Deposits instead when you only want occasional underground pockets.", - "guide.orespawn.materials.2": "Aquifer Fluid changes the normal fluid used below sea level. Deep Aquifer uses a second fluid below the chosen Y level.", - "guide.orespawn.materials.3": "Snow and Ice replace vanilla snow and ordinary ice near the surface. Not set leaves Minecraft's normal material unchanged.", - "button.orespawn.dimension_materials_named": "%s Materials...", - "label.orespawn.dimension_materials.scope": "Applies to every biome in newly generated %s terrain.", - "button.orespawn.mods": "Mods", - "button.orespawn.mod.configure": "Configure", + "guide.orespawn.biomes.title": "Chart the Biomes", + "guide.orespawn.biomes.1": "Provider mods can bring new biomes aboard. Augment mixes them into the existing world; Replace uses only the choices on yer chart where the rule applies.", + "guide.orespawn.biomes.2": "Scope sets which biome namespaces can be swapped. Minecraft Only protects modded biomes; Selected Mods changes only the namespaces ye pick.", + "guide.orespawn.biomes.3": "Region Size sets the width of each patch. Ye can set weights, climate limits, similar biomes and optional top, filler, underwater and ceiling blocks.", + "guide.orespawn.patterns.title": "Shape the Buried Ores", + "guide.orespawn.patterns.1": "Compact makes familiar lumps. Veins stretch through rock, Clusters gather in groups, Clouds scatter wider, and Under Fluids favours blocks below liquids.", + "guide.orespawn.patterns.2": "Height Distribution sets where attempts land between Minimum and Maximum Y. Uniform spreads them evenly; triangle choices favour particular depths on yer chart.", + "guide.orespawn.patterns.3": "Air-Exposure Discard can hide ore that touches a cave. Set it to 0 to keep every exposed attempt, or 1 to reject them all. Values in between are chances.", + "guide.orespawn.fluids.title": "Liquid Caches Below Deck", + "guide.orespawn.fluids.1": "Liquid Caches make covered pockets of water, lava, oil or another fluid aboard. They don't change oceans or the materials in the World Cargo chart.", + "guide.orespawn.fluids.2": "Attempts per Chunk controls how rare the caches are. Horizontal and Vertical Radius set size, while Lobes join rounded pockets into a less regular shape.", + "guide.orespawn.fluids.3": "Solid Cover guards the roof and Solid Shell guards the sides and floor against caves. Host and biome rules tell ye where a cache may form.", + "guide.orespawn.materials.title": "Take Stock of World Cargo", + "guide.orespawn.materials.1": "World Cargo swaps background materials across an entire dimension. Use Liquid Caches if ye only want the odd underground pocket.", + "guide.orespawn.materials.2": "Aquifer Fluid sets the usual fluid below sea level. Deep Aquifer uses another fluid below the Y level ye choose.", + "guide.orespawn.materials.3": "Snow and Ice swap the vanilla materials near the surface. Leave a material unset to keep Minecraft's usual block.", + "button.orespawn.dimension_materials_named": "%s Cargo...", + "label.orespawn.dimension_materials.scope": "Every biome in newly charted %s terrain uses this cargo.", + "button.orespawn.mods": "Mods Aboard", + "button.orespawn.mod.configure": "Set Up", "tooltip.orespawn.main.mods": "View loaded mods integrated with OreSpawn.", - "screen.orespawn.mods": "OreSpawn Mods", + "screen.orespawn.mods": "OreSpawn Mods Aboard", "tooltip.orespawn.mod.configure": "Open %s configuration.", "tooltip.orespawn.mod.unavailable": "%s does not provide an OreSpawn-linked configuration screen.", "label.orespawn.mod.id_version": "%s - Mod version %s", @@ -381,16 +381,16 @@ "status.orespawn.mod.config_only": "Configuration screen only", "error.orespawn.mod.screen_missing": "%s did not create a configuration screen.", "error.orespawn.mod.screen_failed": "Could not open %s configuration (%s).", - "button.orespawn.ore_sources": "Ore Sources...", + "button.orespawn.ore_sources": "Ore Supplies...", "tooltip.orespawn.ore_sources": "Review equivalent ore outputs without multiplying placement frequency.", - "screen.orespawn.ore_sources": "Ore Sources", - "screen.orespawn.ore_source_detail": "Ore Source Policy", - "label.orespawn.ore_source.none": "No equivalent managed ore sources were found.", + "screen.orespawn.ore_sources": "Ore Supplies", + "screen.orespawn.ore_source_detail": "Ore Supply Orders", + "label.orespawn.ore_source.none": "No matching managed ore supplies aboard.", "label.orespawn.ore_source.row": "%s - %s - %s candidates - %s", - "label.orespawn.ore_source.intro": "Choose how equivalent ores generate.", + "label.orespawn.ore_source.intro": "Set the orders for matching ores.", "label.orespawn.ore_source.summary": "%s candidates - %s", - "button.orespawn.ore_source.review": "Review...", - "button.orespawn.ore_source.configure": "Configure...", + "button.orespawn.ore_source.review": "Inspect...", + "button.orespawn.ore_source.configure": "Give Orders...", "label.orespawn.ore_source.material": "Material: %s", "label.orespawn.ore_source.domain": "Dimension/domain: %s", "label.orespawn.ore_source.channels": "Placement channels: %s", @@ -419,17 +419,17 @@ "tooltip.orespawn.ore_source.enrichment": "This entry is enrichment, not an interchangeable ore source.", "tooltip.orespawn.ore_source.missing": "This source is unavailable. Its saved selection will be restored if the owning mod returns.", "error.orespawn.ore_source.weight": "Output weights must be positive numbers.", - "button.orespawn.back": "Back", - "button.orespawn.ore_source.all_groups": "All Groups", - "button.orespawn.ore_source.add_group": "Add Group", - "button.orespawn.ore_source.accept": "Accept", + "button.orespawn.back": "Back to Deck", + "button.orespawn.ore_source.all_groups": "Every Crew", + "button.orespawn.ore_source.add_group": "Form a Crew", + "button.orespawn.ore_source.accept": "Aye", "tooltip.orespawn.ore_source.accept": "Keep the current Keep Original policy unchanged and mark this group as reviewed. It is saved only when the main editor's Done is used.", - "button.orespawn.ore_source.delete_group": "Delete", - "button.orespawn.ore_source.dissolve_group": "Dissolve Group", - "button.orespawn.ore_source.confirm_dissolve": "Confirm Dissolve", - "button.orespawn.ore_source.move": "Move", - "button.orespawn.ore_source.advanced": "Advanced...", - "button.orespawn.ore_source.hide_advanced": "Hide Advanced", + "button.orespawn.ore_source.delete_group": "Strike Off", + "button.orespawn.ore_source.dissolve_group": "Disband Crew", + "button.orespawn.ore_source.confirm_dissolve": "Aye, Disband Crew", + "button.orespawn.ore_source.move": "Move to This Crew", + "button.orespawn.ore_source.advanced": "More Orders...", + "button.orespawn.ore_source.hide_advanced": "Stow Extra Orders", "option.orespawn.ore_source.group_name": "Group name", "option.orespawn.ore_source.alias": "Block tag", "option.orespawn.ore_source.output_mode": "Output: %s", @@ -452,8 +452,8 @@ "error.orespawn.ore_source.alias_owned": "%s already owns this entry. Press Move to reassign it.", "error.orespawn.ore_source.manage_vanilla_first": "Enable Manage Vanilla Ores before moving a native vanilla ore into another group.", "error.orespawn.ore_source.defaults_write": "Could not save material-group defaults.", - "screen.orespawn.ore_source.group_settings": "Ore Source Group Settings", - "label.orespawn.ore_source.groups": "Groups", + "screen.orespawn.ore_source.group_settings": "Ore Crew Orders", + "label.orespawn.ore_source.groups": "Crews", "label.orespawn.ore_source.aliases": "Block tags", "label.orespawn.ore_source.placement_rules": "Placement Rules", "label.orespawn.ore_source.placement_explanation": "Outputs choose the block; placement rules choose frequency, shape, depth and hosts.", @@ -468,27 +468,27 @@ "tooltip.orespawn.ore_source.placement_readonly": "Only one active managed rule is available, so this source is read-only.", "tooltip.orespawn.ore_source.placement_select": "Click to choose between active managed placement sources.", "tooltip.orespawn.ore_source.external_excluded": "Independent external generators are reported but cannot be selected as placement rules.", - "button.orespawn.ore_source.hide_single": "Hide Singles", + "button.orespawn.ore_source.hide_single": "Hide Lone Sources", "tooltip.orespawn.ore_source.group_colours": "Green entries have one alias and one output and need no action. Yellow groups have a saved rule. Red groups need attention. Show All includes green entries.", - "button.orespawn.ore_source.reset_all": "Reset All", - "button.orespawn.ore_source.confirm_reset_all": "Confirm Reset", + "button.orespawn.ore_source.reset_all": "Restore All Orders", + "button.orespawn.ore_source.confirm_reset_all": "Aye, Restore", "tooltip.orespawn.ore_source.reset_all": "Restore built-in material groups and recreate source policies from the currently loaded ores. The change remains pending until the main editor's Done button is used.", - "screen.orespawn.biomes": "Biomes", - "screen.orespawn.biome_palettes": "Biome Palettes", - "screen.orespawn.biome_palette_settings": "Biome Palette Settings", - "button.orespawn.biome.hide_routine": "Hide Routine", - "button.orespawn.biome.replace_new_terrain": "Replace in new terrain with...", - "button.orespawn.biome.replace_with": "Replace in new terrain with %s...", - "button.orespawn.biome.leave_original": "Leave original behaviour", - "button.orespawn.biome.palettes": "Palettes: %s", - "button.orespawn.biome.reset_selected": "Reset Biome", - "button.orespawn.biome.confirm_reset": "Confirm Reset", - "button.orespawn.biome.reset_palette": "Reset Palette", - "button.orespawn.biome.confirm_reset_palette": "Confirm Palette Reset", - "button.orespawn.biome.reset_dimension": "Reset Dimension", - "button.orespawn.biome.confirm_reset_dimension": "Confirm Dimension Reset", - "button.orespawn.biome.reset_all": "Reset All Biomes", - "button.orespawn.biome.confirm_reset_all": "Confirm All-Biome Reset", + "screen.orespawn.biomes": "Biome Charts", + "screen.orespawn.biome_palettes": "Biome Chart Sets", + "screen.orespawn.biome_palette_settings": "Biome Chart Orders", + "button.orespawn.biome.hide_routine": "Hide Ordinary Biomes", + "button.orespawn.biome.replace_new_terrain": "Swap in New Land...", + "button.orespawn.biome.replace_with": "Swap New Land for %s...", + "button.orespawn.biome.leave_original": "Keep the Old Course", + "button.orespawn.biome.palettes": "Chart Sets: %s", + "button.orespawn.biome.reset_selected": "Restore Biome", + "button.orespawn.biome.confirm_reset": "Aye, Restore", + "button.orespawn.biome.reset_palette": "Restore Chart Set", + "button.orespawn.biome.confirm_reset_palette": "Aye, Restore Chart Set", + "button.orespawn.biome.reset_dimension": "Restore Dimension", + "button.orespawn.biome.confirm_reset_dimension": "Aye, Restore Dimension", + "button.orespawn.biome.reset_all": "Restore All Biomes", + "button.orespawn.biome.confirm_reset_all": "Aye, Restore All Biomes", "value.orespawn.biome.status.user_replaced": "Replaced in new terrain", "value.orespawn.biome.status.layered": "Several placement rules", "value.orespawn.biome.status.disabled": "Placement disabled", @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "Coverage", "option.orespawn.biome.fallback_weight": "Original-biome weight", "option.orespawn.biome.include_namespaces": "Included namespaces (comma-separated)", - "option.orespawn.biome.exclude_namespaces": "Excluded namespaces (comma-separated)" + "option.orespawn.biome.exclude_namespaces": "Excluded namespaces (comma-separated)", + "commands.orespawn.help": "OreSpawn tools: status verbose; chunk [x z]; survey [radius]; explain [x y z]; retrogen status; jobs; cancel ; clearchunk; undo .", + "commands.orespawn.options": "Options: --dimension , --center , --y , --block . Survey radius: 0–8 (default 1).", + "commands.orespawn.safety": "Clearing changes player-placed terrain too. Use a disposable world. Level 4, Creative/Spectator, a preview and a verified backup are required. Undo cannot reverse entities or time.", + "commands.orespawn.scope": "Surveys inspect loaded chunks only. Reports describe observed blocks, not their historical generator or guaranteed future placement.", + "commands.orespawn.data": "Data: %s", + "commands.orespawn.report": "Report %s: %s", + "commands.orespawn.started": "Job started. %s", + "commands.orespawn.preview_started": "Preparing preview; no blocks will change.", + "commands.orespawn.preview_title": "Preview only — nothing changed.", + "commands.orespawn.preview_location": "%s | Chunk %s, %s | Y %s–%s", + "commands.orespawn.preview_clear_counts": "Clear %s blocks; keep %s.", + "commands.orespawn.preview_undo_counts": "Restore up to %s blocks; keep %s others.", + "commands.orespawn.preview_warning": "Also clears matching player-placed terrain. Use a test world.", + "commands.orespawn.preview_undo_warning": "Undo restores blocks, not entities or elapsed time.", + "commands.orespawn.preview_expiry": "Open chat to choose below. Expires in 2 min.", + "commands.orespawn.confirm_clear": "[Confirm clearing]", + "commands.orespawn.confirm_undo": "[Confirm undo]", + "commands.orespawn.preview_cancel": "[Cancel]", + "commands.orespawn.preview_cancelled": "Preview cancelled. No blocks changed.", + "commands.orespawn.preview_inactive": "This preview is no longer active.", + "commands.orespawn.action_hint": "Click to run: %s", + "commands.orespawn.details": "[Details]", + "commands.orespawn.complete_clear": "Cleared %s blocks. %s %s", + "commands.orespawn.complete_undo": "Restored %s blocks. %s", + "commands.orespawn.undo_preview": "[Undo…]", + "commands.orespawn.job_result": "Job %s — %s: %s", + "commands.orespawn.backups": "Backups remain here across restarts: %s. Use /orespawn undo .", + "commands.orespawn.failed": "OreSpawn could not do that: %s" } diff --git a/src/main/resources/assets/orespawn/lang/en_us.json b/src/main/resources/assets/orespawn/lang/en_us.json index 7f70e8c4..e2459afd 100644 --- a/src/main/resources/assets/orespawn/lang/en_us.json +++ b/src/main/resources/assets/orespawn/lang/en_us.json @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "Coverage", "option.orespawn.biome.fallback_weight": "Original-biome weight", "option.orespawn.biome.include_namespaces": "Included namespaces (comma-separated)", - "option.orespawn.biome.exclude_namespaces": "Excluded namespaces (comma-separated)" + "option.orespawn.biome.exclude_namespaces": "Excluded namespaces (comma-separated)", + "commands.orespawn.help": "OreSpawn tools: status verbose; chunk [x z]; survey [radius]; explain [x y z]; retrogen status; jobs; cancel ; clearchunk; undo .", + "commands.orespawn.options": "Options: --dimension , --center , --y , --block . Survey radius: 0–8 (default 1).", + "commands.orespawn.safety": "Clearing changes player-placed terrain too. Use a disposable world. Level 4, Creative/Spectator, a preview and a verified backup are required. Undo cannot reverse entities or time.", + "commands.orespawn.scope": "Surveys inspect loaded chunks only. Reports describe observed blocks, not their historical generator or guaranteed future placement.", + "commands.orespawn.data": "Data: %s", + "commands.orespawn.report": "Report %s: %s", + "commands.orespawn.started": "Job started. %s", + "commands.orespawn.preview_started": "Preparing preview; no blocks will change.", + "commands.orespawn.preview_title": "Preview only — nothing changed.", + "commands.orespawn.preview_location": "%s | Chunk %s, %s | Y %s–%s", + "commands.orespawn.preview_clear_counts": "Clear %s blocks; keep %s.", + "commands.orespawn.preview_undo_counts": "Restore up to %s blocks; keep %s others.", + "commands.orespawn.preview_warning": "Also clears matching player-placed terrain. Use a test world.", + "commands.orespawn.preview_undo_warning": "Undo restores blocks, not entities or elapsed time.", + "commands.orespawn.preview_expiry": "Open chat to choose below. Expires in 2 min.", + "commands.orespawn.confirm_clear": "[Confirm clearing]", + "commands.orespawn.confirm_undo": "[Confirm undo]", + "commands.orespawn.preview_cancel": "[Cancel]", + "commands.orespawn.preview_cancelled": "Preview cancelled. No blocks changed.", + "commands.orespawn.preview_inactive": "This preview is no longer active.", + "commands.orespawn.action_hint": "Click to run: %s", + "commands.orespawn.details": "[Details]", + "commands.orespawn.complete_clear": "Cleared %s blocks. %s %s", + "commands.orespawn.complete_undo": "Restored %s blocks. %s", + "commands.orespawn.undo_preview": "[Undo…]", + "commands.orespawn.job_result": "Job %s — %s: %s", + "commands.orespawn.backups": "Backups remain here across restarts: %s. Use /orespawn undo .", + "commands.orespawn.failed": "OreSpawn could not do that: %s" } diff --git a/src/main/resources/assets/orespawn/lang/es_es.json b/src/main/resources/assets/orespawn/lang/es_es.json index 4c297776..90b3e953 100644 --- a/src/main/resources/assets/orespawn/lang/es_es.json +++ b/src/main/resources/assets/orespawn/lang/es_es.json @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "Cobertura", "option.orespawn.biome.fallback_weight": "Peso del bioma original", "option.orespawn.biome.include_namespaces": "Espacios de nombres incluidos (separados por comas)", - "option.orespawn.biome.exclude_namespaces": "Espacios de nombres excluidos (separados por comas)" + "option.orespawn.biome.exclude_namespaces": "Espacios de nombres excluidos (separados por comas)", + "commands.orespawn.help": "Herramientas de OreSpawn: status verbose; chunk [x z]; survey [radio]; explain [x y z]; retrogen status; jobs; cancel ; clearchunk; undo .", + "commands.orespawn.options": "Opciones: --dimension , --center , --y , --block . Radio: 0–8 (predeterminado 1).", + "commands.orespawn.safety": "El despeje también elimina terreno colocado por jugadores. Usa un mundo de prueba. Requiere nivel 4, Creativo/Espectador, vista previa y copia verificada. undo no revierte entidades ni el tiempo.", + "commands.orespawn.scope": "Los sondeos solo leen chunks cargados. Los informes describen bloques observados, no su generador original ni una colocación futura garantizada.", + "commands.orespawn.data": "Datos: %s", + "commands.orespawn.report": "Informe %s: %s", + "commands.orespawn.started": "Trabajo iniciado. %s", + "commands.orespawn.preview_started": "Preparando vista previa; no se cambiará ningún bloque.", + "commands.orespawn.preview_title": "Solo vista previa — no se ha cambiado nada.", + "commands.orespawn.preview_location": "%s | Chunk %s, %s | Altura %s–%s", + "commands.orespawn.preview_clear_counts": "Eliminar %s bloques; conservar %s.", + "commands.orespawn.preview_undo_counts": "Restaurar hasta %s bloques; conservar otros %s.", + "commands.orespawn.preview_warning": "También elimina terreno coincidente colocado por jugadores. Usa un mundo de prueba.", + "commands.orespawn.preview_undo_warning": "Deshacer restaura bloques, no entidades ni el tiempo transcurrido.", + "commands.orespawn.preview_expiry": "Abre el chat y elige abajo. Caduca en 2 min.", + "commands.orespawn.confirm_clear": "[Confirmar limpieza]", + "commands.orespawn.confirm_undo": "[Confirmar restauración]", + "commands.orespawn.preview_cancel": "[Cancelar]", + "commands.orespawn.preview_cancelled": "Vista previa cancelada. No se cambió ningún bloque.", + "commands.orespawn.preview_inactive": "Esta vista previa ya no está activa.", + "commands.orespawn.action_hint": "Haz clic para ejecutar: %s", + "commands.orespawn.details": "[Detalles]", + "commands.orespawn.complete_clear": "Se eliminaron %s bloques. %s %s", + "commands.orespawn.complete_undo": "Se restauraron %s bloques. %s", + "commands.orespawn.undo_preview": "[Deshacer…]", + "commands.orespawn.job_result": "Trabajo %s — %s: %s", + "commands.orespawn.backups": "Las copias se conservan aquí tras reiniciar: %s. Usa /orespawn undo .", + "commands.orespawn.failed": "OreSpawn no pudo realizar la operación: %s" } diff --git a/src/main/resources/assets/orespawn/lang/es_mx.json b/src/main/resources/assets/orespawn/lang/es_mx.json index 4c297776..90b3e953 100644 --- a/src/main/resources/assets/orespawn/lang/es_mx.json +++ b/src/main/resources/assets/orespawn/lang/es_mx.json @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "Cobertura", "option.orespawn.biome.fallback_weight": "Peso del bioma original", "option.orespawn.biome.include_namespaces": "Espacios de nombres incluidos (separados por comas)", - "option.orespawn.biome.exclude_namespaces": "Espacios de nombres excluidos (separados por comas)" + "option.orespawn.biome.exclude_namespaces": "Espacios de nombres excluidos (separados por comas)", + "commands.orespawn.help": "Herramientas de OreSpawn: status verbose; chunk [x z]; survey [radio]; explain [x y z]; retrogen status; jobs; cancel ; clearchunk; undo .", + "commands.orespawn.options": "Opciones: --dimension , --center , --y , --block . Radio: 0–8 (predeterminado 1).", + "commands.orespawn.safety": "El despeje también elimina terreno colocado por jugadores. Usa un mundo de prueba. Requiere nivel 4, Creativo/Espectador, vista previa y copia verificada. undo no revierte entidades ni el tiempo.", + "commands.orespawn.scope": "Los sondeos solo leen chunks cargados. Los informes describen bloques observados, no su generador original ni una colocación futura garantizada.", + "commands.orespawn.data": "Datos: %s", + "commands.orespawn.report": "Informe %s: %s", + "commands.orespawn.started": "Trabajo iniciado. %s", + "commands.orespawn.preview_started": "Preparando vista previa; no se cambiará ningún bloque.", + "commands.orespawn.preview_title": "Solo vista previa — no se ha cambiado nada.", + "commands.orespawn.preview_location": "%s | Chunk %s, %s | Altura %s–%s", + "commands.orespawn.preview_clear_counts": "Eliminar %s bloques; conservar %s.", + "commands.orespawn.preview_undo_counts": "Restaurar hasta %s bloques; conservar otros %s.", + "commands.orespawn.preview_warning": "También elimina terreno coincidente colocado por jugadores. Usa un mundo de prueba.", + "commands.orespawn.preview_undo_warning": "Deshacer restaura bloques, no entidades ni el tiempo transcurrido.", + "commands.orespawn.preview_expiry": "Abre el chat y elige abajo. Caduca en 2 min.", + "commands.orespawn.confirm_clear": "[Confirmar limpieza]", + "commands.orespawn.confirm_undo": "[Confirmar restauración]", + "commands.orespawn.preview_cancel": "[Cancelar]", + "commands.orespawn.preview_cancelled": "Vista previa cancelada. No se cambió ningún bloque.", + "commands.orespawn.preview_inactive": "Esta vista previa ya no está activa.", + "commands.orespawn.action_hint": "Haz clic para ejecutar: %s", + "commands.orespawn.details": "[Detalles]", + "commands.orespawn.complete_clear": "Se eliminaron %s bloques. %s %s", + "commands.orespawn.complete_undo": "Se restauraron %s bloques. %s", + "commands.orespawn.undo_preview": "[Deshacer…]", + "commands.orespawn.job_result": "Trabajo %s — %s: %s", + "commands.orespawn.backups": "Las copias se conservan aquí tras reiniciar: %s. Usa /orespawn undo .", + "commands.orespawn.failed": "OreSpawn no pudo realizar la operación: %s" } diff --git a/src/main/resources/assets/orespawn/lang/fr_ca.json b/src/main/resources/assets/orespawn/lang/fr_ca.json index 08d8bdb9..0dcb13a9 100644 --- a/src/main/resources/assets/orespawn/lang/fr_ca.json +++ b/src/main/resources/assets/orespawn/lang/fr_ca.json @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "Couverture", "option.orespawn.biome.fallback_weight": "Poids du biome d'origine", "option.orespawn.biome.include_namespaces": "Espaces de noms inclus (séparés par des virgules)", - "option.orespawn.biome.exclude_namespaces": "Espaces de noms exclus (séparés par des virgules)" + "option.orespawn.biome.exclude_namespaces": "Espaces de noms exclus (séparés par des virgules)", + "commands.orespawn.help": "Outils OreSpawn : status verbose ; chunk [x z] ; survey [rayon] ; explain [x y z] ; retrogen status ; jobs ; cancel ; clearchunk ; undo .", + "commands.orespawn.options": "Options : --dimension , --center , --y , --block . Rayon : 0–8 (1 par défaut).", + "commands.orespawn.safety": "Le dégagement supprime aussi le terrain placé par les joueurs. Utilisez un monde de test. Niveau 4, Créatif/Spectateur, aperçu et sauvegarde vérifiée requis. undo ne restaure ni les entités ni le temps.", + "commands.orespawn.scope": "Les relevés lisent uniquement les chunks chargés. Les rapports décrivent les blocs observés, pas leur générateur d’origine ni un placement futur garanti.", + "commands.orespawn.data": "Données : %s", + "commands.orespawn.report": "Rapport %s : %s", + "commands.orespawn.started": "Tâche lancée. %s", + "commands.orespawn.preview_started": "Préparation de l’aperçu ; aucun bloc ne sera modifié.", + "commands.orespawn.preview_title": "Aperçu uniquement — rien n’a changé.", + "commands.orespawn.preview_location": "%s | Chunk %s, %s | Altitude %s–%s", + "commands.orespawn.preview_clear_counts": "Retirer %s blocs ; en conserver %s.", + "commands.orespawn.preview_undo_counts": "Restaurer jusqu’à %s blocs ; conserver les %s autres.", + "commands.orespawn.preview_warning": "Retire aussi le terrain correspondant posé par les joueurs. Utilisez un monde de test.", + "commands.orespawn.preview_undo_warning": "L’annulation restaure les blocs, pas les entités ni le temps écoulé.", + "commands.orespawn.preview_expiry": "Ouvrez le chat et choisissez ci-dessous. Valable 2 min.", + "commands.orespawn.confirm_clear": "[Confirmer l’effacement]", + "commands.orespawn.confirm_undo": "[Confirmer la restauration]", + "commands.orespawn.preview_cancel": "[Annuler]", + "commands.orespawn.preview_cancelled": "Aperçu annulé. Aucun bloc n’a été modifié.", + "commands.orespawn.preview_inactive": "Cet aperçu n’est plus actif.", + "commands.orespawn.action_hint": "Cliquer pour exécuter : %s", + "commands.orespawn.details": "[Détails]", + "commands.orespawn.complete_clear": "%s blocs retirés. %s %s", + "commands.orespawn.complete_undo": "%s blocs restaurés. %s", + "commands.orespawn.undo_preview": "[Restaurer…]", + "commands.orespawn.job_result": "Tâche %s — %s : %s", + "commands.orespawn.backups": "Les sauvegardes restent ici après redémarrage : %s. Utilisez /orespawn undo .", + "commands.orespawn.failed": "OreSpawn n’a pas pu effectuer cette opération : %s" } diff --git a/src/main/resources/assets/orespawn/lang/fr_fr.json b/src/main/resources/assets/orespawn/lang/fr_fr.json index 08d8bdb9..0dcb13a9 100644 --- a/src/main/resources/assets/orespawn/lang/fr_fr.json +++ b/src/main/resources/assets/orespawn/lang/fr_fr.json @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "Couverture", "option.orespawn.biome.fallback_weight": "Poids du biome d'origine", "option.orespawn.biome.include_namespaces": "Espaces de noms inclus (séparés par des virgules)", - "option.orespawn.biome.exclude_namespaces": "Espaces de noms exclus (séparés par des virgules)" + "option.orespawn.biome.exclude_namespaces": "Espaces de noms exclus (séparés par des virgules)", + "commands.orespawn.help": "Outils OreSpawn : status verbose ; chunk [x z] ; survey [rayon] ; explain [x y z] ; retrogen status ; jobs ; cancel ; clearchunk ; undo .", + "commands.orespawn.options": "Options : --dimension , --center , --y , --block . Rayon : 0–8 (1 par défaut).", + "commands.orespawn.safety": "Le dégagement supprime aussi le terrain placé par les joueurs. Utilisez un monde de test. Niveau 4, Créatif/Spectateur, aperçu et sauvegarde vérifiée requis. undo ne restaure ni les entités ni le temps.", + "commands.orespawn.scope": "Les relevés lisent uniquement les chunks chargés. Les rapports décrivent les blocs observés, pas leur générateur d’origine ni un placement futur garanti.", + "commands.orespawn.data": "Données : %s", + "commands.orespawn.report": "Rapport %s : %s", + "commands.orespawn.started": "Tâche lancée. %s", + "commands.orespawn.preview_started": "Préparation de l’aperçu ; aucun bloc ne sera modifié.", + "commands.orespawn.preview_title": "Aperçu uniquement — rien n’a changé.", + "commands.orespawn.preview_location": "%s | Chunk %s, %s | Altitude %s–%s", + "commands.orespawn.preview_clear_counts": "Retirer %s blocs ; en conserver %s.", + "commands.orespawn.preview_undo_counts": "Restaurer jusqu’à %s blocs ; conserver les %s autres.", + "commands.orespawn.preview_warning": "Retire aussi le terrain correspondant posé par les joueurs. Utilisez un monde de test.", + "commands.orespawn.preview_undo_warning": "L’annulation restaure les blocs, pas les entités ni le temps écoulé.", + "commands.orespawn.preview_expiry": "Ouvrez le chat et choisissez ci-dessous. Valable 2 min.", + "commands.orespawn.confirm_clear": "[Confirmer l’effacement]", + "commands.orespawn.confirm_undo": "[Confirmer la restauration]", + "commands.orespawn.preview_cancel": "[Annuler]", + "commands.orespawn.preview_cancelled": "Aperçu annulé. Aucun bloc n’a été modifié.", + "commands.orespawn.preview_inactive": "Cet aperçu n’est plus actif.", + "commands.orespawn.action_hint": "Cliquer pour exécuter : %s", + "commands.orespawn.details": "[Détails]", + "commands.orespawn.complete_clear": "%s blocs retirés. %s %s", + "commands.orespawn.complete_undo": "%s blocs restaurés. %s", + "commands.orespawn.undo_preview": "[Restaurer…]", + "commands.orespawn.job_result": "Tâche %s — %s : %s", + "commands.orespawn.backups": "Les sauvegardes restent ici après redémarrage : %s. Utilisez /orespawn undo .", + "commands.orespawn.failed": "OreSpawn n’a pas pu effectuer cette opération : %s" } diff --git a/src/main/resources/assets/orespawn/lang/ja_jp.json b/src/main/resources/assets/orespawn/lang/ja_jp.json index aea08a9e..68fe0556 100644 --- a/src/main/resources/assets/orespawn/lang/ja_jp.json +++ b/src/main/resources/assets/orespawn/lang/ja_jp.json @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "適用範囲", "option.orespawn.biome.fallback_weight": "元のバイオームの重み", "option.orespawn.biome.include_namespaces": "含める名前空間(カンマ区切り)", - "option.orespawn.biome.exclude_namespaces": "除外する名前空間(カンマ区切り)" + "option.orespawn.biome.exclude_namespaces": "除外する名前空間(カンマ区切り)", + "commands.orespawn.help": "OreSpawn の管理コマンド: status verbose、chunk [x z]、survey [半径]、explain <ルール> [x y z]、retrogen status、jobs、cancel 、clearchunk、undo <バックアップ>。", + "commands.orespawn.options": "オプション: --dimension <読み込み済みID>、--center 、--y <最小 最大>、--block 。半径は0~8(既定値1)。", + "commands.orespawn.safety": "除去はプレイヤーが置いた地形にも影響します。テスト用ワールドを使用してください。権限4、クリエイティブ/スペクテイター、プレビュー、検証済みバックアップが必要です。undo はエンティティや時間を戻しません。", + "commands.orespawn.scope": "読み込み済みチャンクのみを調査します。レポートは現在のブロックを示し、生成元や将来の配置を保証するものではありません。", + "commands.orespawn.data": "データ: %s", + "commands.orespawn.report": "レポート %s: %s", + "commands.orespawn.started": "ジョブを開始しました。%s", + "commands.orespawn.preview_started": "プレビューを準備中です。ブロックは変更されません。", + "commands.orespawn.preview_title": "プレビューのみ — まだ何も変更していません。", + "commands.orespawn.preview_location": "%s | チャンク %s, %s | Y %s–%s", + "commands.orespawn.preview_clear_counts": "%s ブロックを除去し、%s ブロックを保持します。", + "commands.orespawn.preview_undo_counts": "最大 %s ブロックを復元し、他の %s ブロックは保持します。", + "commands.orespawn.preview_warning": "条件に合うプレイヤー設置の地形も除去します。テスト用ワールドを使ってください。", + "commands.orespawn.preview_undo_warning": "復元できるのはブロックだけです。エンティティや経過時間は元に戻りません。", + "commands.orespawn.preview_expiry": "チャットを開き、下から選んでください。有効期限は2分です。", + "commands.orespawn.confirm_clear": "[除去を確定]", + "commands.orespawn.confirm_undo": "[復元を確定]", + "commands.orespawn.preview_cancel": "[キャンセル]", + "commands.orespawn.preview_cancelled": "プレビューをキャンセルしました。ブロックは変更していません。", + "commands.orespawn.preview_inactive": "このプレビューはもう有効ではありません。", + "commands.orespawn.action_hint": "クリックして実行: %s", + "commands.orespawn.details": "[詳細]", + "commands.orespawn.complete_clear": "%s ブロックを除去しました。%s %s", + "commands.orespawn.complete_undo": "%s ブロックを復元しました。%s", + "commands.orespawn.undo_preview": "[元に戻す…]", + "commands.orespawn.job_result": "ジョブ %s — %s: %s", + "commands.orespawn.backups": "再起動後もバックアップはここに残ります: %s。/orespawn undo <フォルダーID> で復元します。", + "commands.orespawn.failed": "OreSpawn が操作を実行できませんでした: %s" } diff --git a/src/main/resources/assets/orespawn/lang/ko_kr.json b/src/main/resources/assets/orespawn/lang/ko_kr.json index 921ada3c..badf5657 100644 --- a/src/main/resources/assets/orespawn/lang/ko_kr.json +++ b/src/main/resources/assets/orespawn/lang/ko_kr.json @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "적용 범위", "option.orespawn.biome.fallback_weight": "원래 생물군계 가중치", "option.orespawn.biome.include_namespaces": "포함할 네임스페이스(쉼표로 구분)", - "option.orespawn.biome.exclude_namespaces": "제외할 네임스페이스(쉼표로 구분)" + "option.orespawn.biome.exclude_namespaces": "제외할 네임스페이스(쉼표로 구분)", + "commands.orespawn.help": "OreSpawn 관리 명령: status verbose, chunk [x z], survey [반경], explain <규칙> [x y z], retrogen status, jobs, cancel , clearchunk, undo <백업>.", + "commands.orespawn.options": "옵션: --dimension <불러온 ID>, --center , --y <최소 최대>, --block . 반경: 0–8 (기본 1).", + "commands.orespawn.safety": "제거 작업은 플레이어가 놓은 지형도 바꿉니다. 시험용 세계를 사용하세요. 권한 4, 크리에이티브/관전자, 미리 보기와 검증된 백업이 필요합니다. undo는 개체나 시간을 되돌리지 않습니다.", + "commands.orespawn.scope": "불러온 청크만 조사합니다. 보고서는 관측한 블록을 설명하며 원래 생성기나 향후 배치를 보장하지 않습니다.", + "commands.orespawn.data": "데이터: %s", + "commands.orespawn.report": "보고서 %s: %s", + "commands.orespawn.started": "작업을 시작했습니다. %s", + "commands.orespawn.preview_started": "미리보기를 준비합니다. 블록은 변경되지 않습니다.", + "commands.orespawn.preview_title": "미리보기만 표시합니다 — 아직 변경된 것은 없습니다.", + "commands.orespawn.preview_location": "%s | 청크 %s, %s | Y %s–%s", + "commands.orespawn.preview_clear_counts": "블록 %s개 제거, %s개 유지.", + "commands.orespawn.preview_undo_counts": "최대 %s개 블록을 복원하고 나머지 %s개는 유지합니다.", + "commands.orespawn.preview_warning": "조건에 맞으면 플레이어가 놓은 지형도 제거됩니다. 테스트 월드를 사용하세요.", + "commands.orespawn.preview_undo_warning": "되돌리기는 블록만 복원하며 엔티티나 경과 시간은 되돌리지 않습니다.", + "commands.orespawn.preview_expiry": "채팅을 열고 아래에서 선택하세요. 2분 후 만료됩니다.", + "commands.orespawn.confirm_clear": "[제거 확인]", + "commands.orespawn.confirm_undo": "[복원 확인]", + "commands.orespawn.preview_cancel": "[취소]", + "commands.orespawn.preview_cancelled": "미리보기를 취소했습니다. 변경된 블록은 없습니다.", + "commands.orespawn.preview_inactive": "이 미리보기는 더 이상 유효하지 않습니다.", + "commands.orespawn.action_hint": "클릭하여 실행: %s", + "commands.orespawn.details": "[자세히]", + "commands.orespawn.complete_clear": "블록 %s개를 제거했습니다. %s %s", + "commands.orespawn.complete_undo": "블록 %s개를 복원했습니다. %s", + "commands.orespawn.undo_preview": "[되돌리기…]", + "commands.orespawn.job_result": "작업 %s — %s: %s", + "commands.orespawn.backups": "재시작 후에도 백업은 여기에 남습니다: %s. /orespawn undo <폴더-ID>를 사용하세요.", + "commands.orespawn.failed": "OreSpawn이 작업을 수행하지 못했습니다: %s" } diff --git a/src/main/resources/assets/orespawn/lang/pt_br.json b/src/main/resources/assets/orespawn/lang/pt_br.json index b459efd5..178651bf 100644 --- a/src/main/resources/assets/orespawn/lang/pt_br.json +++ b/src/main/resources/assets/orespawn/lang/pt_br.json @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "Cobertura", "option.orespawn.biome.fallback_weight": "Peso do bioma original", "option.orespawn.biome.include_namespaces": "Namespaces incluídos (separados por vírgulas)", - "option.orespawn.biome.exclude_namespaces": "Namespaces excluídos (separados por vírgulas)" + "option.orespawn.biome.exclude_namespaces": "Namespaces excluídos (separados por vírgulas)", + "commands.orespawn.help": "Ferramentas do OreSpawn: status verbose; chunk [x z]; survey [raio]; explain [x y z]; retrogen status; jobs; cancel ; clearchunk; undo .", + "commands.orespawn.options": "Opções: --dimension , --center , --y , --block . Raio: 0–8 (padrão 1).", + "commands.orespawn.safety": "A limpeza também remove terreno colocado por jogadores. Use um mundo de teste. Exige nível 4, Criativo/Espectador, prévia e backup verificado. undo não reverte entidades nem o tempo.", + "commands.orespawn.scope": "As pesquisas leem apenas chunks carregados. Os relatórios descrevem blocos observados, não seu gerador original nem uma colocação futura garantida.", + "commands.orespawn.data": "Dados: %s", + "commands.orespawn.report": "Relatório %s: %s", + "commands.orespawn.started": "Tarefa iniciada. %s", + "commands.orespawn.preview_started": "Preparando a prévia; nenhum bloco será alterado.", + "commands.orespawn.preview_title": "Somente prévia — nada foi alterado.", + "commands.orespawn.preview_location": "%s | Chunk %s, %s | Altura %s–%s", + "commands.orespawn.preview_clear_counts": "Remover %s blocos; preservar %s.", + "commands.orespawn.preview_undo_counts": "Restaurar até %s blocos; preservar os outros %s.", + "commands.orespawn.preview_warning": "Também remove terreno correspondente colocado por jogadores. Use um mundo de teste.", + "commands.orespawn.preview_undo_warning": "Desfazer restaura blocos, não entidades nem o tempo decorrido.", + "commands.orespawn.preview_expiry": "Abra o chat e escolha abaixo. Expira em 2 min.", + "commands.orespawn.confirm_clear": "[Confirmar limpeza]", + "commands.orespawn.confirm_undo": "[Confirmar restauração]", + "commands.orespawn.preview_cancel": "[Cancelar]", + "commands.orespawn.preview_cancelled": "Prévia cancelada. Nenhum bloco foi alterado.", + "commands.orespawn.preview_inactive": "Esta prévia não está mais ativa.", + "commands.orespawn.action_hint": "Clique para executar: %s", + "commands.orespawn.details": "[Detalhes]", + "commands.orespawn.complete_clear": "%s blocos removidos. %s %s", + "commands.orespawn.complete_undo": "%s blocos restaurados. %s", + "commands.orespawn.undo_preview": "[Desfazer…]", + "commands.orespawn.job_result": "Tarefa %s — %s: %s", + "commands.orespawn.backups": "Os backups permanecem aqui após reiniciar: %s. Use /orespawn undo .", + "commands.orespawn.failed": "O OreSpawn não pôde realizar a operação: %s" } diff --git a/src/main/resources/assets/orespawn/lang/ru_ru.json b/src/main/resources/assets/orespawn/lang/ru_ru.json index 9085d8d0..b09bcca0 100644 --- a/src/main/resources/assets/orespawn/lang/ru_ru.json +++ b/src/main/resources/assets/orespawn/lang/ru_ru.json @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "Покрытие", "option.orespawn.biome.fallback_weight": "Вес исходного биома", "option.orespawn.biome.include_namespaces": "Включённые пространства имён (через запятую)", - "option.orespawn.biome.exclude_namespaces": "Исключённые пространства имён (через запятую)" + "option.orespawn.biome.exclude_namespaces": "Исключённые пространства имён (через запятую)", + "commands.orespawn.help": "Инструменты OreSpawn: status verbose; chunk [x z]; survey [радиус]; explain <правило> [x y z]; retrogen status; jobs; cancel ; clearchunk; undo <копия>.", + "commands.orespawn.options": "Параметры: --dimension <загруженный ID>, --center , --y <мин макс>, --block <мод:блок@метаданные>. Радиус: 0–8 (по умолчанию 1).", + "commands.orespawn.safety": "Очистка удаляет и блоки ландшафта, поставленные игроком. Используйте тестовый мир. Нужны уровень 4, Творчество/Наблюдатель, просмотр и проверенная копия. undo не возвращает сущности и время.", + "commands.orespawn.scope": "Проверяются только загруженные чанки. Отчёт описывает найденные блоки, но не их исходный генератор и не гарантированное будущее размещение.", + "commands.orespawn.data": "Данные: %s", + "commands.orespawn.report": "Отчёт %s: %s", + "commands.orespawn.started": "Задание запущено. %s", + "commands.orespawn.preview_started": "Подготовка предпросмотра; блоки не будут изменены.", + "commands.orespawn.preview_title": "Только предпросмотр — ничего не изменено.", + "commands.orespawn.preview_location": "%s | Чанк %s, %s | Y %s–%s", + "commands.orespawn.preview_clear_counts": "Удалить блоков: %s; сохранить: %s.", + "commands.orespawn.preview_undo_counts": "Восстановить до %s блоков; сохранить остальные %s.", + "commands.orespawn.preview_warning": "Будет удалён и подходящий ландшафт, созданный игроками. Используйте тестовый мир.", + "commands.orespawn.preview_undo_warning": "Отмена восстанавливает блоки, но не сущности и не прошедшее время.", + "commands.orespawn.preview_expiry": "Откройте чат и выберите ниже. Срок действия — 2 мин.", + "commands.orespawn.confirm_clear": "[Подтвердить очистку]", + "commands.orespawn.confirm_undo": "[Подтвердить восстановление]", + "commands.orespawn.preview_cancel": "[Отмена]", + "commands.orespawn.preview_cancelled": "Предпросмотр отменён. Блоки не изменены.", + "commands.orespawn.preview_inactive": "Этот предпросмотр больше не действует.", + "commands.orespawn.action_hint": "Нажмите для выполнения: %s", + "commands.orespawn.details": "[Подробнее]", + "commands.orespawn.complete_clear": "Удалено блоков: %s. %s %s", + "commands.orespawn.complete_undo": "Восстановлено блоков: %s. %s", + "commands.orespawn.undo_preview": "[Восстановить…]", + "commands.orespawn.job_result": "Задание %s — %s: %s", + "commands.orespawn.backups": "Копии сохраняются здесь после перезапуска: %s. Используйте /orespawn undo .", + "commands.orespawn.failed": "OreSpawn не удалось выполнить действие: %s" } diff --git a/src/main/resources/assets/orespawn/lang/zh_cn.json b/src/main/resources/assets/orespawn/lang/zh_cn.json index 52e8838b..30c06028 100644 --- a/src/main/resources/assets/orespawn/lang/zh_cn.json +++ b/src/main/resources/assets/orespawn/lang/zh_cn.json @@ -508,5 +508,33 @@ "option.orespawn.biome.coverage": "覆盖率", "option.orespawn.biome.fallback_weight": "原始生物群系权重", "option.orespawn.biome.include_namespaces": "包含的命名空间(逗号分隔)", - "option.orespawn.biome.exclude_namespaces": "排除的命名空间(逗号分隔)" + "option.orespawn.biome.exclude_namespaces": "排除的命名空间(逗号分隔)", + "commands.orespawn.help": "OreSpawn 管理命令:status verbose;chunk [x z];survey [半径];explain <规则> [x y z];retrogen status;jobs;cancel ;clearchunk;undo <备份>。", + "commands.orespawn.options": "选项:--dimension <已加载ID>、--center 、--y <最小 最大>、--block 。半径为0–8,默认1。", + "commands.orespawn.safety": "清除也会影响玩家放置的地形。请使用测试世界。需要权限4、创造/旁观模式、预览及验证过的备份。undo不能恢复实体或倒退时间。", + "commands.orespawn.scope": "仅调查已加载区块。报告描述实际观察到的方块,并不证明其原始生成器或保证未来生成结果。", + "commands.orespawn.data": "数据:%s", + "commands.orespawn.report": "报告 %s:%s", + "commands.orespawn.started": "任务已启动。%s", + "commands.orespawn.preview_started": "正在准备预览;不会更改任何方块。", + "commands.orespawn.preview_title": "仅预览 — 尚未更改任何内容。", + "commands.orespawn.preview_location": "%s | 区块 %s, %s | Y %s–%s", + "commands.orespawn.preview_clear_counts": "清除 %s 个方块;保留 %s 个。", + "commands.orespawn.preview_undo_counts": "最多恢复 %s 个方块;保留其余 %s 个。", + "commands.orespawn.preview_warning": "符合条件的玩家建造地形也会被清除。请使用测试世界。", + "commands.orespawn.preview_undo_warning": "撤销仅恢复方块,无法恢复实体或已经过去的时间。", + "commands.orespawn.preview_expiry": "打开聊天并在下方选择。2 分钟后失效。", + "commands.orespawn.confirm_clear": "[确认清除]", + "commands.orespawn.confirm_undo": "[确认恢复]", + "commands.orespawn.preview_cancel": "[取消]", + "commands.orespawn.preview_cancelled": "已取消预览。没有更改方块。", + "commands.orespawn.preview_inactive": "此预览已失效。", + "commands.orespawn.action_hint": "点击执行:%s", + "commands.orespawn.details": "[详情]", + "commands.orespawn.complete_clear": "已清除 %s 个方块。%s %s", + "commands.orespawn.complete_undo": "已恢复 %s 个方块。%s", + "commands.orespawn.undo_preview": "[撤销…]", + "commands.orespawn.job_result": "任务 %s — %s:%s", + "commands.orespawn.backups": "重启后备份仍保存在此处:%s。使用 /orespawn undo <备份文件夹ID>。", + "commands.orespawn.failed": "OreSpawn 无法执行此操作:%s" } diff --git a/src/nativeOreIntegrationTest/java/zone/moddev/mc/orespawn/testmod/NativeOreProbeTestMod.java b/src/nativeOreIntegrationTest/java/zone/moddev/mc/orespawn/testmod/NativeOreProbeTestMod.java index 20309c95..d2449e81 100644 --- a/src/nativeOreIntegrationTest/java/zone/moddev/mc/orespawn/testmod/NativeOreProbeTestMod.java +++ b/src/nativeOreIntegrationTest/java/zone/moddev/mc/orespawn/testmod/NativeOreProbeTestMod.java @@ -38,6 +38,7 @@ public final class NativeOreProbeTestMod { private static final String QUARTZ = "minecraft:nether_quartz_ore"; private static final String NETHER = "minecraft:the_nether"; + private static final String IMPORTED_QUARTZ = "orespawn:legacy/minecraft/quartz"; public NativeOreProbeTestMod() { MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::prepare); @@ -47,6 +48,7 @@ public NativeOreProbeTestMod() { private void prepare(FMLServerAboutToStartEvent event) { Path profile = profilePath(event.getServer()); String phase = System.getProperty("nativeoreprobe.phase", "fresh"); + String scenario = System.getProperty("nativeoreprobe.importMode", ""); if ("reload".equals(phase)) return; try { JsonObject root; @@ -83,6 +85,18 @@ private void prepare(FMLServerAboutToStartEvent event) { blocks.add("minecraft:netherrack"); rule.add("host_blocks", blocks); } + if (scenario.startsWith("import-")) { + JsonObject ores = root.getAsJsonObject("ores"); + JsonObject imported = new JsonParser().parse(ores.get(QUARTZ).toString()).getAsJsonObject(); + imported.addProperty("block", QUARTZ); + imported.addProperty("source_mod", "legacy"); + imported.addProperty("native_generation", false); + ores.add(IMPORTED_QUARTZ, imported); + // The default would place quartz outside the imported band if both ran. + rule.addProperty("min_y", 85); + rule.addProperty("max_y", 91); + } + if (scenario.endsWith("-off")) root.addProperty("manage_vanilla_ores", false); Files.createDirectories(profile.getParent()); Files.write(profile, new GsonBuilder().setPrettyPrinting().create().toJson(root) .getBytes(StandardCharsets.UTF_8)); @@ -94,8 +108,9 @@ private void prepare(FMLServerAboutToStartEvent event) { private void audit(FMLServerStartedEvent event) { MinecraftServer server = event.getServer(); String phase = System.getProperty("nativeoreprobe.phase", "fresh"); - if (!NativeOreProbeBridge.controlsQuartz()) { - throw new IllegalStateException("Quartz is not controlled by OreSpawn before generation"); + boolean managementOff = System.getProperty("nativeoreprobe.importMode", "").endsWith("-off"); + if (NativeOreProbeBridge.controlsQuartz() == managementOff) { + throw new IllegalStateException("Quartz control does not match Manage Vanilla Ores"); } if (WorldGeologyProfileManager.activeProfile().oreRetrogenEnabled()) { throw new IllegalStateException("The quartz test must not enable retrogen"); @@ -108,7 +123,7 @@ private void audit(FMLServerStartedEvent event) { if (!"fresh".equals(phase)) { try (InputStream input = Files.newInputStream(marker)) { previous.load(input); } } - Properties current = inspect(world, -8, 24, 28); + Properties current = inspect(world, -8, managementOff ? 0 : 24, managementOff ? 255 : 28); current.setProperty("profile_sha256", hex(digest().digest(Files.readAllBytes(profilePath(server))))); if (!"fresh".equals(phase)) { for (String name : current.stringPropertyNames()) { diff --git a/src/parityIntegrationTest/java/zone/moddev/mc/orespawn/worldgen/BenchmarkProbe.java b/src/parityIntegrationTest/java/zone/moddev/mc/orespawn/worldgen/BenchmarkProbe.java new file mode 100644 index 00000000..02c9cd86 --- /dev/null +++ b/src/parityIntegrationTest/java/zone/moddev/mc/orespawn/worldgen/BenchmarkProbe.java @@ -0,0 +1,102 @@ +package zone.moddev.mc.orespawn.worldgen; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadMXBean; +import java.security.MessageDigest; +import java.util.Locale; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.dimension.DimensionType; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.eventbus.api.EventPriority; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.event.server.FMLServerStartedEvent; + +/** The same fixture runs unchanged against the frozen and candidate player jars. */ +public final class BenchmarkProbe { + BenchmarkProbe() { MinecraftForge.EVENT_BUS.register(this); } + @SubscribeEvent(priority=EventPriority.HIGHEST) + public void worldLoaded(net.minecraftforge.event.world.WorldEvent.Load event) { + if (event.getWorld() instanceof ServerWorld) { ProbeTags.stabilizeCorals(); ProbeTags.stabilizeFossils(); } + } + @SubscribeEvent(priority=EventPriority.LOWEST) + public void run(FMLServerStartedEvent event) { + try { + ServerWorld world = event.getServer().getWorld(DimensionType.OVERWORLD); + ParityProbe.require(world.getSaveHandler().getWorldDirectory().getName().equals("benchmark-parity-world"), "Not a disposable benchmark"); + ProbeTags.stabilizeCorals(); + ThreadMXBean cpu = ManagementFactory.getThreadMXBean(); + ParityProbe.require(cpu.isCurrentThreadCpuTimeSupported(), "No generation-thread CPU clock"); + cpu.setThreadCpuTimeEnabled(true); + if (net.minecraftforge.fml.ModList.get().isLoaded("modernmetals")) + square(world, 6, -20, 2); // The seed/chunk that previously crashed air-exposure checks. + net.minecraft.block.Block substitute = System.getProperty("parity.mode", "").equals("fluidbench") + ? net.minecraftforge.registries.ForgeRegistries.BLOCKS.getValue(new net.minecraft.util.ResourceLocation("parityprobe:water")) : null; + for (int warmup = 0; warmup < 5; warmup++) square(world, -128 - warmup * 64, 128, 5); + JsonArray passes = new JsonArray(); + for (int pass = 0; pass < 5; pass++) { + int cx = -256 - pass * 32, cz = 256; + long compilation = ManagementFactory.getCompilationMXBean().getTotalCompilationTime(); + long processCpu = ((com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getProcessCpuTime(); + long cpuStarted = generationCpu(cpu), started = System.nanoTime(); + square(world, cx, cz, 5); + long nanos = System.nanoTime() - started, cpuNanos = generationCpu(cpu) - cpuStarted; + JsonObject result = new JsonObject(); result.addProperty("pass", pass); + result.addProperty("elapsed_ns", nanos); result.addProperty("generation_thread_cpu_ns", cpuNanos); + result.addProperty("whole_jvm_cpu_ns_diagnostic", ((com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getProcessCpuTime() - processCpu); + result.addProperty("jit_compilation_ms_diagnostic", ManagementFactory.getCompilationMXBean().getTotalCompilationTime() - compilation); + result.addProperty("generated_chunks", 121); result.addProperty("measured_chunks", 81); + MessageDigest blocks = MessageDigest.getInstance("SHA-256"), biomes = MessageDigest.getInstance("SHA-256"); + java.util.Map stateKeys = new java.util.IdentityHashMap<>(); + long structureReferences = 0; + BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); + for (int z = cz - 4; z <= cz + 4; z++) for (int x = cx - 4; x <= cx + 4; x++) { + Chunk chunk = world.getChunk(x, z); + for (it.unimi.dsi.fastutil.longs.LongSet references : chunk.getStructureReferences().values()) + structureReferences += references.size(); + for (int y = 0; y < 256; y++) for (int lz = 0; lz < 16; lz++) for (int lx = 0; lx < 16; lx++) { + net.minecraft.block.BlockState state = chunk.getBlockState(position.setPos(x * 16 + lx, y, z * 16 + lz)); + if (state.getBlock() == substitute) state = net.minecraft.block.Blocks.WATER.getDefaultState(); + blocks.update(stateKeys.computeIfAbsent(state, value -> net.minecraft.command.arguments.BlockStateParser + .toString(value).getBytes(java.nio.charset.StandardCharsets.UTF_8))); blocks.update((byte) 0); + } + for (net.minecraft.world.biome.Biome biome : chunk.getBiomes()) { + biomes.update(biome.getRegistryName().toString().getBytes(java.nio.charset.StandardCharsets.UTF_8)); biomes.update((byte) 0); + } + } + result.addProperty("blocks_sha256", hex(blocks.digest())); result.addProperty("biomes_sha256", hex(biomes.digest())); + result.addProperty("structure_references", structureReferences); + passes.add(result); System.out.println("PARITY_BENCHMARK_PASS " + result); + } + JsonObject report = new JsonObject(); report.add("passes", passes); report.addProperty("passed", true); + report.addProperty("java", System.getProperty("java.version")); report.addProperty("processors", Runtime.getRuntime().availableProcessors()); + report.addProperty("cpu_scope", "Server thread and native Server-Worker world-generation pool, plus WorldGen workers if supplied by an integration; excludes GC, JIT and modloading workers"); + report.addProperty("fixture_stabilization", "Ordered coral tags and seeded native fossils' otherwise unseeded region RNG; identical fixture in both controls and candidates"); + report.addProperty("warmup_chunks", 605); + report.add("profile", WorldGeologyProfileManager.activeProfile().toJson()); + ParityProbe.write(java.nio.file.Paths.get("benchmark.json"), report); + event.getServer().initiateShutdown(false); + } catch (Throwable failure) { failure.printStackTrace(); event.getServer().initiateShutdown(false); } + } + private static void square(ServerWorld world, int cx, int cz, int radius) { + for (int z = cz - radius; z <= cz + radius; z++) for (int x = cx - radius; x <= cx + radius; x++) world.getChunk(x, z); + } + private static String hex(byte[] bytes) { + StringBuilder result = new StringBuilder(); for (byte value : bytes) result.append(String.format(Locale.ROOT, "%02x", value & 255)); return result.toString(); + } + private static long generationCpu(ThreadMXBean clock) { + long total = 0; + for (long id : clock.getAllThreadIds()) { + java.lang.management.ThreadInfo thread = clock.getThreadInfo(id); + if (thread == null) continue; + String name = thread.getThreadName(); + if (name.equals("Server thread") || name.startsWith("Server-Worker-") + || name.startsWith("WorldGen-Worker-") || name.startsWith("WorldGen-Scheduler-")) + total += Math.max(0, clock.getThreadCpuTime(id)); + } + return total; + } +} diff --git a/src/parityIntegrationTest/java/zone/moddev/mc/orespawn/worldgen/GenerationProbe.java b/src/parityIntegrationTest/java/zone/moddev/mc/orespawn/worldgen/GenerationProbe.java new file mode 100644 index 00000000..b0ec9ca2 --- /dev/null +++ b/src/parityIntegrationTest/java/zone/moddev/mc/orespawn/worldgen/GenerationProbe.java @@ -0,0 +1,321 @@ +package zone.moddev.mc.orespawn.worldgen; + +import com.google.gson.JsonObject; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.util.BitSet; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.Map; +import net.minecraft.block.Block; +import net.minecraft.block.FlowingFluidBlock; +import net.minecraft.block.BlockState; +import net.minecraft.block.Blocks; +import net.minecraft.fluid.Fluids; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.dimension.DimensionType; +import net.minecraft.world.gen.OverworldChunkGenerator; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.RegistryEvent; +import net.minecraftforge.eventbus.api.EventPriority; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.event.server.FMLServerAboutToStartEvent; +import net.minecraftforge.fml.event.server.FMLServerStartedEvent; +import net.minecraftforge.fml.event.server.FMLServerStoppingEvent; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import zone.moddev.mc.orespawn.api.*; + +/** Checks native terrain, the sampler and fluid provenance in real generated chunks. */ +final class GenerationProbe { + private final String mode, fluid = System.getProperty("parity.fluid", "native"); + private final Map masks = new java.util.concurrent.ConcurrentHashMap<>(); + private net.minecraft.world.gen.feature.Feature capture; + private Block water, luminous; + private ServerWorld savedWorld; + private int savedCenterX, savedCenterZ; + private JsonObject savedResult; + GenerationProbe(String mode) { + this.mode = mode; + MinecraftForge.EVENT_BUS.register(this); + if (mode.equals("fluids")) { + TestLiquid[] waterFluids = testFluids("water"), luminousFluids = testFluids("luminous_water"); + FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(net.minecraft.fluid.Fluid.class, + (RegistryEvent.Register event) -> event.getRegistry().registerAll( + waterFluids[0], waterFluids[1], luminousFluids[0], luminousFluids[1])); + FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(Block.class, + (RegistryEvent.Register event) -> { + water = new TestWater(0, waterFluids[0]).setRegistryName("parityprobe", "water"); + luminous = new TestWater(8, luminousFluids[0]).setRegistryName("parityprobe", "luminous_water"); + for (TestLiquid liquid : waterFluids) liquid.block = water; + for (TestLiquid liquid : luminousFluids) liquid.block = luminous; + event.getRegistry().registerAll(water, luminous); + }); + } + if (mode.equals("formations")) RockFormationRegistry.register(new ResourceLocation("parityprobe:band"), + json -> context -> new RockFormationColumn() { + public FormationMaterial at(int y) { + return y >= 15 && y <= 40 ? new FormationMaterial(Blocks.POLISHED_GRANITE.getDefaultState(), + GeologyFamily.IGNEOUS_INTRUSIVE) : null; + } + }); + } + + @SubscribeEvent(priority=EventPriority.LOWEST) + public void configure(FMLServerAboutToStartEvent event) { + if (mode.equals("fluids")) ParityProbe.require(water.getDefaultState().getFluidState().getFluid() != Fluids.WATER + && !water.getDefaultState().getFluidState().isTagged(net.minecraft.tags.FluidTags.WATER), + "The acceptance fluid must have its own identity and must not inherit the water tag"); + JsonObject root = WorldGeologyProfileManager.activeProfile().rootCopy(); + root.addProperty("manage_vanilla_ores", false); + if (mode.equals("formations")) { + JsonObject terrain = new JsonObject(); + terrain.add("minecraft:overworld", WorldgenProvider.TerrainDimensionDefinition.builder(new ResourceLocation("minecraft:overworld")) + .hostBlock(new ResourceLocation("minecraft:stone")).hostBlock(new ResourceLocation("minecraft:granite")) + .hostBlock(new ResourceLocation("minecraft:diorite")).hostBlock(new ResourceLocation("minecraft:andesite")).build().toJson()); + root.add("terrain_dimensions", terrain); + JsonObject formations = new JsonObject(), rule = new JsonObject(), materials = new JsonObject(), material = new JsonObject(); + rule.addProperty("type", "parityprobe:band"); rule.addProperty("algorithm_revision", 1); + material.addProperty("block", "minecraft:polished_granite"); material.addProperty("family", "igneous_intrusive"); + materials.add("body", material); rule.add("materials", materials); formations.add("parityprobe:band", rule); + JsonObject quartz = new com.google.gson.JsonParser().parse("{\"type\":\"orespawn:quartz_vein\",\"algorithm_revision\":1,\"chance\":1,\"spacing_chunks\":8,\"radius_min\":26,\"radius_max\":28,\"min_y\":24,\"max_y\":24,\"height\":30,\"priority\":1,\"materials\":{\"vein_quartz\":{\"block\":\"minecraft:quartz_block\"}}}").getAsJsonObject(); + formations.add("parityprobe:quartz", quartz); root.add("rock_formations", formations); + } else { + JsonObject materials = new JsonObject(), rule = new JsonObject(); + rule.addProperty("dimension", "minecraft:overworld"); rule.addProperty("enabled", true); + rule.addProperty("default_fluid", fluid.equals("native") ? "minecraft:water" : "parityprobe:" + fluid); + materials.add("parityprobe:materials", rule); root.add("dimension_materials", materials); + } + WorldGeologyProfileManager.applyBenchmarkProfile(WorldGeologyProfileManager.activeProfile().withRoot(root)); + if (mode.equals("fluids") && !System.getProperty("parity.mode", "").equals("fluidbench")) { + capture = + new net.minecraft.world.gen.feature.Feature(net.minecraft.world.gen.feature.NoFeatureConfig::deserialize) { + @Override public boolean place(net.minecraft.world.IWorld region, net.minecraft.world.gen.ChunkGenerator generator, + java.util.Random random, BlockPos origin, net.minecraft.world.gen.feature.NoFeatureConfig config) { + net.minecraft.world.chunk.IChunk chunk = region.getChunk(origin.getX() >> 4, origin.getZ() >> 4); + masks.put(chunk.getPos().asLong(), AquiferMaterialSubstitution.captureMask(chunk, + ((OverworldChunkGenerator) generator).defaultFluid, generator.getSeaLevel())); + return true; + } + }; + } + } + + @SubscribeEvent(priority=EventPriority.LOWEST) + public void worldLoaded(net.minecraftforge.event.world.WorldEvent.Load event) { + if (!(event.getWorld() instanceof ServerWorld)) return; + ProbeTags.stabilizeCorals(); + ProbeTags.stabilizeFossils(); + if (capture != null) for (net.minecraft.world.biome.Biome biome : net.minecraftforge.registries.ForgeRegistries.BIOMES.getValues()) { + java.util.List> features = biome.getFeatures(net.minecraft.world.gen.GenerationStage.Decoration.RAW_GENERATION); + features.removeIf(feature -> feature.feature == capture); + features.add(0, new net.minecraft.world.gen.feature.ConfiguredFeature<>(capture, new net.minecraft.world.gen.feature.NoFeatureConfig())); + } + } + + @SubscribeEvent(priority=EventPriority.LOWEST) + public void run(FMLServerStartedEvent event) { + if (System.getProperty("parity.mode", "").equals("fluidbench")) return; + try { + ServerWorld world = event.getServer().getWorld(DimensionType.OVERWORLD); + ParityProbe.require(world.getSaveHandler().getWorldDirectory().getName().equals("generation-parity-world"), "Not a disposable world"); + ProbeTags.stabilizeCorals(); ProbeTags.stabilizeFossils(); + OverworldChunkGenerator generator = (OverworldChunkGenerator) world.getChunkProvider().getChunkGenerator(); + if (mode.equals("fluids")) { + ParityProbe.require(fluid.equals("luminous_water") ? generator.defaultFluid.getBlock() == luminous + : generator.defaultFluid.getBlock() == Blocks.WATER, "Wrong aquifer generator path"); + } + // Spawn prepares a wide feature halo in 1.14. Keep exact comparisons outside it. + BlockPos ocean = generator.getBiomeProvider().findBiomePosition(4096, -4096, 2048, + java.util.Arrays.asList(net.minecraft.world.biome.Biomes.OCEAN, net.minecraft.world.biome.Biomes.DEEP_OCEAN), + new java.util.Random(471)); + ParityProbe.require(ocean != null, "No remote ocean test site"); + int centerX = ocean.getX() >> 4, centerZ = ocean.getZ() >> 4; + if (mode.equals("formations")) { + BlockPos dry = generator.getBiomeProvider().findBiomePosition(0, 0, 2048, + java.util.Collections.singletonList(net.minecraft.world.biome.Biomes.PLAINS), new java.util.Random(471)); + ParityProbe.require(dry != null, "No plains test site"); + centerX = dry.getX() >> 4; centerZ = dry.getZ() >> 4; + } + for (int z = centerZ - 5; z <= centerZ + 5; z++) for (int x = centerX - 5; x <= centerX + 5; x++) world.getChunk(x, z); + int loaded = world.getChunkProvider().getLoadedChunkCount(); + java.util.Random rng = world.rand; + java.lang.reflect.Field seed = java.util.Random.class.getDeclaredField("seed"); seed.setAccessible(true); + long beforeRng = ((java.util.concurrent.atomic.AtomicLong) seed.get(rng)).get(); + GeologySampler sampler = mode.equals("formations") ? OreSpawnApi.createSampler(world).get() : null; + long formations = 0, quartz = 0, custom = 0, waterCells = 0, scheduled = 0; + MessageDigest digest = MessageDigest.getInstance("SHA-256"), stable = MessageDigest.getInstance("SHA-256"); + Map keys = new IdentityHashMap<>(); + Map counts = new java.util.TreeMap<>(); + BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); + for (int z = centerZ - 4; z <= centerZ + 4; z++) for (int x = centerX - 4; x <= centerX + 4; x++) { + Chunk chunk = world.getChunk(x, z); + java.util.List updates = world.getPendingFluidTicks().func_223188_a(chunk.getPos(), false, false); + scheduled += updates == null ? 0 : updates.size(); + for (int lz = 0; lz < 16; lz++) for (int lx = 0; lx < 16; lx++) { + GeologyColumn column = sampler == null ? null : sampler.sampleColumn(x * 16 + lx, z * 16 + lz, 64); + int floor = generator.func_222529_a(x * 16 + lx, z * 16 + lz, net.minecraft.world.gen.Heightmap.Type.OCEAN_FLOOR_WG) - 1; + int expected = floor < generator.getSeaLevel() - 1 ? -1 : floor; + ParityProbe.require(NativeDensityTerrain.chunk(generator, x, z).terrainTop(lx, lz) == expected, + "Cached terrain height differs from native density interpolation at " + x + "," + z + ":" + lx + "," + lz); + for (int y = 0; y < 256; y++) { + BlockState state = chunk.getBlockState(position.setPos(x * 16 + lx, y, z * 16 + lz)); + counts.merge(state.getBlock().getRegistryName().toString(), 1L, Long::sum); + if (mode.equals("formations")) { + if (state.getBlock() == Blocks.POLISHED_GRANITE || state.getBlock() == Blocks.QUARTZ_BLOCK) { + ParityProbe.require(column.formationAt(y).isPresent() && column.rockAt(y).equals(state), "Sampler differs from generated formation at " + position); + formations++; if (state.getBlock() == Blocks.QUARTZ_BLOCK) quartz++; + } + if (y >= 15 && y <= 40) ParityProbe.require(!NaturalFormations.nativeStoneVariant(state), "Unreplaced native stone in test formation at " + position); + } else { + if (state.getBlock() == water || state.getBlock() == luminous) { + custom++; + if (state.getBlock() == water && !System.getProperty("parity.phase", "Fresh").equals("Reload")) { + BitSet mask = masks.get(chunk.getPos().asLong()); + ParityProbe.require(y < world.getSeaLevel() && mask != null && mask.get(AquiferMaterialSubstitution.index(lx, y, lz)), "Replaced a later lake/spring or unrecorded cell"); + } + state = Blocks.WATER.getDefaultState(); + } else if (state.getBlock() == Blocks.WATER) waterCells++; + } + final BlockState normalized = state; + digest.update(keys.computeIfAbsent(state, ignored -> net.minecraft.command.arguments.BlockStateParser + .toString(normalized).getBytes(java.nio.charset.StandardCharsets.UTF_8))); digest.update((byte) 0); + BlockState permanent = state.getBlock() == Blocks.BROWN_MUSHROOM || state.getBlock() == Blocks.RED_MUSHROOM + ? Blocks.AIR.getDefaultState() : state; + stable.update(keys.computeIfAbsent(permanent, value -> net.minecraft.command.arguments.BlockStateParser + .toString(value).getBytes(java.nio.charset.StandardCharsets.UTF_8))); stable.update((byte) 0); + } + } + if (mode.equals("fluids")) ParityProbe.require(!AquiferMaterialSubstitution.apply(world, chunk), "Consumed an aquifer mask twice"); + } + ParityProbe.require(loaded == world.getChunkProvider().getLoadedChunkCount(), "Sampler or substitution loaded chunks"); + ParityProbe.require(beforeRng == ((java.util.concurrent.atomic.AtomicLong) seed.get(rng)).get(), "Sampler consumed generation randomness"); + ParityProbe.write(Paths.get("counts-" + System.getProperty("parity.phase", "Fresh") + ".json"), new com.google.gson.Gson().toJsonTree(counts).getAsJsonObject()); + if (mode.equals("formations")) ParityProbe.require(formations > 0 && quartz > 0, "No generated test formations or built-in quartz veins: formations=" + formations + " quartz=" + quartz); + else if (!fluid.equals("native")) ParityProbe.require(custom > 0 && waterCells > 0, "No substituted aquifer or preserved native lake/spring water"); + JsonObject result = new JsonObject(); result.addProperty("passed", true); result.addProperty("formations", formations); + result.addProperty("quartz", quartz); result.addProperty("substituted", custom); result.addProperty("native_water", waterCells); + result.addProperty("pending_fluid_ticks", scheduled); result.addProperty("normalized_blocks_sha256", hex(digest.digest())); + result.addProperty("stable_terrain_sha256", hex(stable.digest())); + result.addProperty("reload_normalizes_only_fragile_mushrooms", true); + result.addProperty("sampler_no_rng_or_chunk_load", true); + result.addProperty("center_x", centerX); result.addProperty("center_z", centerZ); + String phase = System.getProperty("parity.phase", "Fresh"); + if (mode.equals("formations") && phase.equals("Fresh")) + result.addProperty("lake_rim_restored", checkLakeRim(world, generator, centerX + 64, centerZ)); + if (phase.equals("Reload")) { + JsonObject before = new com.google.gson.JsonParser().parse(new String(Files.readAllBytes(Paths.get("generation-Fresh.json")), java.nio.charset.StandardCharsets.UTF_8)).getAsJsonObject(); + ParityProbe.require(before.get("stable_terrain_sha256").equals(result.get("stable_terrain_sha256")), "Reload changed existing terrain beyond ordinary mushroom support updates"); + } + if (mode.equals("fluids")) { + AquiferMaterialSubstitution.clear(); + ParityProbe.require(generator.defaultFluid.getBlock() == Blocks.WATER && AquiferMaterialSubstitution.pendingCount() == 0, "Shutdown failed to restore aquifer state"); + } + ParityProbe.write(Paths.get("generation-" + phase + ".json"), result); + savedWorld = world; savedCenterX = centerX; savedCenterZ = centerZ; savedResult = result; + System.out.println("GENERATION_PARITY_PASS " + result); + } catch (Throwable failure) { failure.printStackTrace(); } + event.getServer().initiateShutdown(false); + } + + private static int checkLakeRim(ServerWorld world, OverworldChunkGenerator generator, + int chunkX, int chunkZ) { + // This sealed, artificial site is outside the generation-hash sample. + for (int z = chunkZ - 1; z <= chunkZ + 1; z++) + for (int x = chunkX - 1; x <= chunkX + 1; x++) world.getChunk(x, z); + BlockPos origin = new BlockPos(chunkX * 16, 30, chunkZ * 16); + Map original = new java.util.LinkedHashMap<>(); + GeologySampler sampler = OreSpawnApi.createSampler(world).get(); + for (int z = -1; z <= 16; z++) for (int x = -1; x <= 16; x++) { + GeologyColumn column = sampler.sampleColumn(origin.getX() + x, origin.getZ() + z, 64); + for (int y = 20; y <= 40; y++) { + BlockPos at = new BlockPos(origin.getX() + x, y, origin.getZ() + z); + BlockState state = column.formationAt(y).get().material().state(); + original.put(at, state); world.setBlockState(at, state, 2); + } + } + net.minecraft.world.gen.feature.LakesConfig config = new net.minecraft.world.gen.feature.LakesConfig(Blocks.LAVA.getDefaultState()); + ParityProbe.require(net.minecraft.world.gen.feature.Feature.LAKE.place( + world, generator, new java.util.Random(610), origin, config), "Native test lake was rejected"); + Map nativeResult = new java.util.LinkedHashMap<>(); + for (BlockPos at : original.keySet()) nativeResult.put(at, world.getBlockState(at)); + for (Map.Entry entry : original.entrySet()) world.setBlockState(entry.getKey(), entry.getValue(), 2); + ParityProbe.require(((net.minecraft.world.gen.feature.Feature) VanillaLakeCompatibility.FEATURE).place( + world, generator, new java.util.Random(610), origin, config), "Wrapped test lake was rejected"); + int restored = 0, lava = 0, air = 0; + for (Map.Entry entry : nativeResult.entrySet()) { + BlockState expected = entry.getValue(); + if (expected.equals(Blocks.STONE.getDefaultState())) { expected = original.get(entry.getKey()); restored++; } + if (expected.getBlock() == Blocks.LAVA) lava++; + if (expected.isAir()) air++; + ParityProbe.require(expected.equals(world.getBlockState(entry.getKey())), + "Lake changed its cavity, lava or formation rim at " + entry.getKey()); + } + ParityProbe.require(restored > 0 && lava > 0 && air > 0, "Lake test did not exercise its rim and cavity"); + return restored; + } + + @SubscribeEvent(priority=EventPriority.LOWEST) + public void stopping(FMLServerStoppingEvent event) throws Exception { + if (savedResult == null) return; + // The server may finish one tick after shutdown is requested. Snapshot after it, + // immediately before the normal save, rather than treating falling plants as retrogen. + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + Map keys = new IdentityHashMap<>(); + BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); + for (int z = savedCenterZ - 4; z <= savedCenterZ + 4; z++) for (int x = savedCenterX - 4; x <= savedCenterX + 4; x++) { + Chunk chunk = savedWorld.getChunk(x, z); + for (int lz = 0; lz < 16; lz++) for (int lx = 0; lx < 16; lx++) for (int y = 0; y < 256; y++) { + BlockState current = chunk.getBlockState(position.setPos(x * 16 + lx, y, z * 16 + lz)); + if (mode.equals("fluids") && (current.getBlock() == water || current.getBlock() == luminous)) current = Blocks.WATER.getDefaultState(); + final BlockState state = current; + digest.update(keys.computeIfAbsent(state, ignored -> net.minecraft.command.arguments.BlockStateParser + .toString(state).getBytes(java.nio.charset.StandardCharsets.UTF_8))); digest.update((byte) 0); + } + } + savedResult.addProperty("saved_blocks_sha256", hex(digest.digest())); + savedResult.addProperty("snapshot_stage", "server_stopping_before_save"); + Files.write(Paths.get("generation-" + System.getProperty("parity.phase", "Fresh") + ".json"), + savedResult.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + private static String hex(byte[] bytes) { + StringBuilder result = new StringBuilder(); for (byte value : bytes) result.append(String.format(java.util.Locale.ROOT, "%02x", value & 255)); return result.toString(); + } + private static final class TestWater extends FlowingFluidBlock { + TestWater(int light, net.minecraft.fluid.FlowingFluid fluid) { super(fluid, Block.Properties.from(Blocks.WATER).lightValue(light)); } + } + + private static TestLiquid[] testFluids(String name) { + TestLiquid still = new TestLiquid(true), flowing = new TestLiquid(false); + for (TestLiquid liquid : new TestLiquid[]{still, flowing}) { liquid.still = still; liquid.flowing = flowing; } + still.setRegistryName(new ResourceLocation("parityprobe", name)); + flowing.setRegistryName(new ResourceLocation("parityprobe", "flowing_" + name)); + for (TestLiquid liquid : new TestLiquid[]{still, flowing}) + for (net.minecraft.fluid.IFluidState state : liquid.getStateContainer().getValidStates()) + net.minecraft.fluid.Fluid.STATE_REGISTRY.add(state); + return new TestLiquid[]{still, flowing}; + } + + /** Water-like flow, but neither a native water identity nor a water-tag member. */ + private static final class TestLiquid extends net.minecraft.fluid.WaterFluid { + private final boolean source; + private TestLiquid still, flowing; + private Block block; + TestLiquid(boolean source) { this.source = source; } + @Override public net.minecraft.fluid.Fluid getStillFluid() { return still; } + @Override public net.minecraft.fluid.Fluid getFlowingFluid() { return flowing; } + @Override protected void fillStateContainer(net.minecraft.state.StateContainer.Builder builder) { + super.fillStateContainer(builder); builder.add(LEVEL_1_8); + } + @Override public int getLevel(net.minecraft.fluid.IFluidState state) { return source ? 8 : state.get(LEVEL_1_8); } + @Override public boolean isSource(net.minecraft.fluid.IFluidState state) { return source; } + @Override public boolean isEquivalentTo(net.minecraft.fluid.Fluid fluid) { return fluid == still || fluid == flowing; } + @Override public BlockState getBlockState(net.minecraft.fluid.IFluidState state) { + return block.getDefaultState().with(FlowingFluidBlock.LEVEL, getLevelFromState(state)); + } + } +} diff --git a/src/parityIntegrationTest/java/zone/moddev/mc/orespawn/worldgen/ParityProbe.java b/src/parityIntegrationTest/java/zone/moddev/mc/orespawn/worldgen/ParityProbe.java new file mode 100644 index 00000000..bc6603dc --- /dev/null +++ b/src/parityIntegrationTest/java/zone/moddev/mc/orespawn/worldgen/ParityProbe.java @@ -0,0 +1,147 @@ +package zone.moddev.mc.orespawn.worldgen; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import net.minecraft.block.Blocks; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.ChunkSection; +import net.minecraft.world.dimension.DimensionType; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.world.ChunkDataEvent; +import net.minecraftforge.eventbus.api.EventPriority; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.fml.event.server.FMLServerAboutToStartEvent; +import net.minecraftforge.fml.event.server.FMLServerStartedEvent; + +/** Runs only in its named disposable world, using real saves and separate server processes. */ +@Mod("parityprobe") +public final class ParityProbe { + private static final String PHASE = System.getProperty("parity.phase", "Fresh"); + private static final int X = -64, Z = 67; + private ServerWorld world; + private Chunk chunk; + private int ticks; + private boolean ready; + public ParityProbe() { + String mode = System.getProperty("parity.mode", "retrogen"); + if (mode.equals("bench")) new BenchmarkProbe(); + else if (mode.equals("fluidbench")) { new GenerationProbe("fluids"); new BenchmarkProbe(); } + else if (mode.equals("formations") || mode.equals("fluids")) new GenerationProbe(mode); + else MinecraftForge.EVENT_BUS.register(this); + } + + @SubscribeEvent(priority=EventPriority.LOWEST) + public void configure(FMLServerAboutToStartEvent event) { + JsonObject root = WorldGeologyProfileManager.activeProfile().rootCopy(); + root.addProperty("manage_vanilla_ores", false); + JsonObject ores = new JsonObject(), ore = new JsonObject(), dimensions = new JsonObject(), rule = new JsonObject(); + ore.addProperty("block", "minecraft:gold_block"); ore.addProperty("enabled", true); ore.addProperty("retrogen", true); + rule.addProperty("enabled", true); rule.addProperty("min_y", 5); rule.addProperty("max_y", 32); + rule.addProperty("frequency", 8); rule.addProperty("quantity", 32); + com.google.gson.JsonArray hosts = new com.google.gson.JsonArray(); + hosts.add("minecraft:stone"); rule.add("host_blocks", hosts); + dimensions.add("minecraft:overworld", rule); ore.add("dimensions", dimensions); ores.add("parityprobe:deposit", ore); + root.add("ores", ores); root.add("ore_source_policies", new JsonObject()); + JsonObject retrogen = new JsonObject(); + retrogen.addProperty("enabled", !PHASE.equals("Off")); + retrogen.addProperty("force", PHASE.equals("Force")); retrogen.addProperty("chunks_per_tick", 16); + retrogen.addProperty("revision", PHASE.equals("Off") ? 999 : newerRevision() ? 124 : 123); + root.add("retrogen", retrogen); + WorldGeologyProfileManager.applyBenchmarkProfile(WorldGeologyProfileManager.activeProfile().withRoot(root)); + } + + private boolean newerRevision() { + return PHASE.equals("Revision") || PHASE.equals("RevisionReload") || PHASE.equals("Force") || PHASE.equals("ForceOff"); + } + + @SubscribeEvent + public void started(FMLServerStartedEvent event) { + try { + world = event.getServer().getWorld(DimensionType.OVERWORLD); + require(world.getSaveHandler().getWorldDirectory().getName().equals("retrogen-parity-world"), "Not a disposable world"); + for (int x = X - 2; x <= X + 2; x++) for (int z = Z - 2; z <= Z + 2; z++) { + world.forceChunk(x, z, true); world.getChunk(x, z); + } + chunk = world.getChunk(X, Z); + net.minecraft.nbt.CompoundNBT rules = world.getGameRules().write(); + rules.putString("randomTickSpeed", "0"); world.getGameRules().read(rules); + if (PHASE.equals("Fresh")) { + for (int y = 5; y <= 32; y++) for (int z = 0; z < 16; z++) for (int x = 0; x < 16; x++) + put(x, y, z, Blocks.STONE.getDefaultState()); + OreRetrogenManager.clear(); OreRetrogenManager.refreshWorldConfig(); + require(OreRetrogenManager.queueLoadedArea(world, chunk.getPos(), 0) == 1, "Explicit initial queue failed"); + } + ready = true; + } catch (Throwable failure) { fail(failure); } + } + + @SubscribeEvent(priority=EventPriority.LOWEST) + public void tick(TickEvent.ServerTickEvent event) { + if (!ready || event.phase != TickEvent.Phase.END || ++ticks < 80) return; + try { + long count = count(); + require(world.getChunkProvider().func_225313_a(X, Z) == chunk, "The fixture's chunk unloaded before its save"); + boolean shouldPlace = PHASE.equals("Fresh") || PHASE.equals("Revision") || PHASE.equals("Force"); + require(shouldPlace ? count > 0 : count == 0, "Mined ore reappeared or requested retrogen did not run: " + PHASE + " count=" + count); + CompoundNBT marker = new CompoundNBT(); + OreRetrogenManager.onChunkSave(new ChunkDataEvent.Save(chunk, marker)); + int revision = marker.getCompound("OreSpawn").getInt("generation_revision"); + require(revision == (newerRevision() ? 124 : 123), "Saved the configured revision instead of completed work: " + revision); + if (shouldPlace) { + // Mine into the same host rock so a repeated pass would demonstrably refill it. + for (int y = 5; y <= 32; y++) for (int z = 0; z < 16; z++) for (int x = 0; x < 16; x++) + if (chunk.getBlockState(new BlockPos(X * 16 + x, y, Z * 16 + z)).getBlock() == Blocks.GOLD_BLOCK) + put(x, y, z, Blocks.STONE.getDefaultState()); + } + for (int save = 0; save < 3; save++) { + chunk.markDirty(); world.getChunkProvider().save(true); + } + JsonObject result = new JsonObject(); result.addProperty("passed", true); result.addProperty("phase", PHASE); + result.addProperty("placed_blocks", count); result.addProperty("saved_revision", revision); + result.addProperty("consecutive_real_saves", 3); result.addProperty("remaining_after_mining", count()); + write(Paths.get("retrogen-" + PHASE + ".json"), result); + ready = false; System.out.println("RETROGEN_PARITY_PASS " + result); world.getServer().initiateShutdown(false); + } catch (Throwable failure) { fail(failure); } + } + + private long count() { + long result = 0; + for (int y = 5; y <= 32; y++) for (int z = 0; z < 16; z++) for (int x = 0; x < 16; x++) + if (chunk.getBlockState(new BlockPos(X * 16 + x, y, Z * 16 + z)).getBlock() == Blocks.GOLD_BLOCK) result++; + return result; + } + + @SubscribeEvent(priority=EventPriority.LOWEST) + public void saveRootOnlyFixture(ChunkDataEvent.Save event) { + if (PHASE.equals("StripLevel") && event.getChunk().getPos().x == X && event.getChunk().getPos().z == Z) { + require(event.getData().getCompound("OreSpawn").getInt("generation_revision") == 123, + "Historical fixture lost its original root marker"); + event.getData().getCompound("Level").remove("OreSpawn"); + } + } + private void put(int x, int y, int z, net.minecraft.block.BlockState state) { + ChunkSection[] sections = chunk.getSections(); + if (sections[y >> 4] == null) sections[y >> 4] = new ChunkSection((y >> 4) << 4); + sections[y >> 4].setBlockState(x, y & 15, z, state); chunk.markDirty(); + } + private void fail(Throwable failure) { + ready = false; failure.printStackTrace(); + try { JsonObject result = new JsonObject(); result.addProperty("failure", failure.toString()); write(Paths.get("retrogen-failed.json"), result); } + catch (Exception outputFailure) { outputFailure.printStackTrace(); } + if (world != null) world.getServer().initiateShutdown(false); + else throw new AssertionError(failure); + } + static void require(boolean condition, String message) { if (!condition) throw new AssertionError(message); } + static void write(Path path, JsonObject value) throws Exception { + Files.write(path, value.toString().getBytes(StandardCharsets.UTF_8), java.nio.file.StandardOpenOption.CREATE_NEW); + } +} diff --git a/src/parityIntegrationTest/java/zone/moddev/mc/orespawn/worldgen/ProbeTags.java b/src/parityIntegrationTest/java/zone/moddev/mc/orespawn/worldgen/ProbeTags.java new file mode 100644 index 00000000..ce6fdf21 --- /dev/null +++ b/src/parityIntegrationTest/java/zone/moddev/mc/orespawn/worldgen/ProbeTags.java @@ -0,0 +1,58 @@ +package zone.moddev.mc.orespawn.worldgen; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.tags.BlockTags; +import net.minecraft.tags.Tag; +import net.minecraft.tags.TagCollection; + +/** Test-only ordering: vanilla chooses coral variants from an identity-hashed set. */ +final class ProbeTags { + private static final net.minecraft.world.gen.feature.Feature FOSSILS = + new net.minecraft.world.gen.feature.Feature(net.minecraft.world.gen.feature.NoFeatureConfig::deserialize) { + public boolean place(net.minecraft.world.IWorld world, net.minecraft.world.gen.ChunkGenerator generator, + java.util.Random random, net.minecraft.util.math.BlockPos origin, net.minecraft.world.gen.feature.NoFeatureConfig config) { + // Vanilla FossilsFeature ignores its seeded feature RNG and uses an unseeded region RNG. + world.getRandom().setSeed(world.getSeed() ^ origin.toLong() ^ 0x6E17C073L); + return net.minecraft.world.gen.feature.Feature.FOSSIL.place(world, generator, random, origin, config); + } + }; + private ProbeTags() { } + static void stabilizeCorals() { + TagCollection tags = BlockTags.getCollection(); + java.util.Map> builders = new java.util.LinkedHashMap<>(); + tags.getTagMap().forEach((id, tag) -> builders.put(id, Tag.Builder.create().add(tag.getAllElements().toArray(new Block[0])))); + for (Tag tag : java.util.Arrays.asList(BlockTags.CORAL_BLOCKS, BlockTags.CORALS, BlockTags.WALL_CORALS)) { + List blocks = new ArrayList<>(tag.getAllElements()); + blocks.sort(Comparator.comparing(block -> block.getRegistryName().toString())); + builders.put(tag.getId(), Tag.Builder.create().ordered(true).add(blocks.toArray(new Block[0]))); + } + tags.registerAll(builders); + BlockTags.setCollection(tags); + } + static void stabilizeFossils() { + for (net.minecraft.world.biome.Biome biome : net.minecraftforge.registries.ForgeRegistries.BIOMES.getValues()) + for (net.minecraft.world.gen.GenerationStage.Decoration stage : net.minecraft.world.gen.GenerationStage.Decoration.values()) { + List> features = biome.getFeatures(stage); + for (int index = 0; index < features.size(); index++) { + net.minecraft.world.gen.feature.ConfiguredFeature feature = features.get(index); + features.set(index, stabilize(feature)); + } + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static net.minecraft.world.gen.feature.ConfiguredFeature stabilize(net.minecraft.world.gen.feature.ConfiguredFeature feature) { + if (feature.feature == net.minecraft.world.gen.feature.Feature.FOSSIL) + return new net.minecraft.world.gen.feature.ConfiguredFeature<>(FOSSILS, new net.minecraft.world.gen.feature.NoFeatureConfig()); + if (feature.config instanceof net.minecraft.world.gen.feature.DecoratedFeatureConfig) { + net.minecraft.world.gen.feature.DecoratedFeatureConfig config = (net.minecraft.world.gen.feature.DecoratedFeatureConfig) feature.config; + net.minecraft.world.gen.feature.ConfiguredFeature child = stabilize(config.feature); + if (child != config.feature) return new net.minecraft.world.gen.feature.ConfiguredFeature((net.minecraft.world.gen.feature.Feature) feature.feature, + new net.minecraft.world.gen.feature.DecoratedFeatureConfig(child, config.decorator)); + } + return feature; + } +} diff --git a/src/parityIntegrationTest/resources/META-INF/mods.toml b/src/parityIntegrationTest/resources/META-INF/mods.toml new file mode 100644 index 00000000..1cf48a3f --- /dev/null +++ b/src/parityIntegrationTest/resources/META-INF/mods.toml @@ -0,0 +1,13 @@ +modLoader="javafml" +loaderVersion="[28,)" +license="Test fixture" +[[mods]] +modId="parityprobe" +version="1" +displayName="OreSpawn parity test fixture" +[[dependencies.parityprobe]] +modId="orespawn" +mandatory=true +versionRange="[4.1,)" +ordering="AFTER" +side="BOTH" diff --git a/src/parityIntegrationTest/resources/pack.mcmeta b/src/parityIntegrationTest/resources/pack.mcmeta new file mode 100644 index 00000000..5e8de804 --- /dev/null +++ b/src/parityIntegrationTest/resources/pack.mcmeta @@ -0,0 +1 @@ +{"pack":{"pack_format":4,"description":"OreSpawn isolated parity tests"}} diff --git a/src/test/java/zone/moddev/mc/orespawn/LocalizationParityTest.java b/src/test/java/zone/moddev/mc/orespawn/LocalizationParityTest.java index d74367fa..e614e4a3 100644 --- a/src/test/java/zone/moddev/mc/orespawn/LocalizationParityTest.java +++ b/src/test/java/zone/moddev/mc/orespawn/LocalizationParityTest.java @@ -26,7 +26,7 @@ class LocalizationParityTest { private static final Path LANG_DIR = Paths.get("src", "main", "resources", "assets", "orespawn", "lang"); private static final Set EXPECTED_LOCALES = ImmutableSet.of( - "de_au.json", "de_de.json", "en_ca.json", "en_en.json", + "de_at.json", "de_de.json", "en_ca.json", "en_gb.json", "en_pt.json", "en_us.json", "es_es.json", "es_mx.json", "fr_ca.json", "fr_fr.json", "ja_jp.json", "ko_kr.json", "pt_br.json", "ru_ru.json", "zh_cn.json"); @@ -37,18 +37,18 @@ class LocalizationParityTest { private static final Map> INTENTIONAL_ENGLISH_VALUES = ImmutableMap.>builder() .put("button.orespawn.world_settings", ImmutableSet.of( - "de_au.json", "de_de.json", "es_es.json", "es_mx.json", "fr_ca.json", + "de_at.json", "de_de.json", "es_es.json", "es_mx.json", "fr_ca.json", "fr_fr.json", "ja_jp.json", "ko_kr.json", "pt_br.json", "ru_ru.json", "zh_cn.json")) .put("button.orespawn.biome_available", ImmutableSet.of( - "de_au.json", "de_de.json", "es_es.json", "es_mx.json", "fr_ca.json", + "de_at.json", "de_de.json", "es_es.json", "es_mx.json", "fr_ca.json", "fr_fr.json", "ja_jp.json", "ko_kr.json", "pt_br.json", "ru_ru.json", "zh_cn.json")) .put("option.orespawn.mod_filter", ImmutableSet.of( - "de_au.json", "de_de.json", "fr_ca.json", "fr_fr.json")) + "de_at.json", "de_de.json", "fr_ca.json", "fr_fr.json")) .put("screen.orespawn.biomes", ImmutableSet.of("fr_ca.json", "fr_fr.json")) .put("tab.orespawn.biomes", ImmutableSet.of("fr_ca.json", "fr_fr.json")) - .put("tab.orespawn.geomes", ImmutableSet.of("de_au.json", "de_de.json")) + .put("tab.orespawn.geomes", ImmutableSet.of("de_at.json", "de_de.json")) .put("tab.orespawn.placement", ImmutableSet.of("fr_ca.json", "fr_fr.json")) .put("tab.orespawn.biome_placement", ImmutableSet.of("fr_ca.json", "fr_fr.json")) .put("tab.orespawn.biome_surface", ImmutableSet.of("fr_ca.json", "fr_fr.json")) @@ -56,19 +56,19 @@ class LocalizationParityTest { .put("value.orespawn.geology_mode.geome", ImmutableSet.of( "es_es.json", "es_mx.json", "fr_ca.json", "fr_fr.json", "ja_jp.json", "ko_kr.json", "pt_br.json", "ru_ru.json", "zh_cn.json")) - .put("value.orespawn.geology_mode.legacy", ImmutableSet.of("de_au.json", "de_de.json")) - .put("value.orespawn.height_distribution.uniform", ImmutableSet.of("de_au.json", "de_de.json")) + .put("value.orespawn.geology_mode.legacy", ImmutableSet.of("de_at.json", "de_de.json")) + .put("value.orespawn.height_distribution.uniform", ImmutableSet.of("de_at.json", "de_de.json")) .put("value.orespawn.height_distribution.triangle", ImmutableSet.of("pt_br.json")) .put("value.orespawn.ore_pattern.default", ImmutableSet.of( - "de_au.json", "de_de.json", "es_es.json", "es_mx.json", "fr_ca.json", + "de_at.json", "de_de.json", "es_es.json", "es_mx.json", "fr_ca.json", "fr_fr.json", "ja_jp.json", "ko_kr.json", "pt_br.json", "ru_ru.json", "zh_cn.json")) .put("value.orespawn.ore_pattern.precision", ImmutableSet.of( - "de_au.json", "de_de.json", "es_es.json", "es_mx.json", "fr_ca.json", + "de_at.json", "de_de.json", "es_es.json", "es_mx.json", "fr_ca.json", "fr_fr.json", "ja_jp.json", "ko_kr.json", "pt_br.json", "ru_ru.json", "zh_cn.json")) .put("value.orespawn.ore_pattern.underfluids", ImmutableSet.of( - "de_au.json", "de_de.json", "es_es.json", "es_mx.json", "fr_ca.json", + "de_at.json", "de_de.json", "es_es.json", "es_mx.json", "fr_ca.json", "fr_fr.json", "ja_jp.json", "ko_kr.json", "pt_br.json", "ru_ru.json", "zh_cn.json")) .build(); @@ -81,11 +81,19 @@ class LocalizationParityTest { "\uad11\ubb3c\ud559", "\u9271\u7269\u5b66", "\u77ff\u7269\u5b66", "\u7926\u7269\u5b78" }; + @Test + void shippedGameLocaleIdsHaveTheirOwnMenuText() throws Exception { + assertEquals("Empfohlene Standardeinstellungen", read(LANG_DIR.resolve("de_at.json")) + .get("button.orespawn.recommended").getAsString()); + assertEquals("Captain's Defaults", read(LANG_DIR.resolve("en_pt.json")) + .get("button.orespawn.recommended").getAsString()); + } + @Test void everyLocaleMatchesEnglishKeysAndFormatting() throws Exception { JsonObject english = read(LANG_DIR.resolve("en_us.json")); Set englishKeys = JsonCopies.keys(english); - assertEquals(510, englishKeys.size(), + assertEquals(538, englishKeys.size(), "The target locale contract changed; review every shipped translation"); Set localeFiles = new HashSet<>(); Set observedIntentionalEnglishValues = new HashSet<>(); diff --git a/src/test/java/zone/moddev/mc/orespawn/api/WorldgenProviderTest.java b/src/test/java/zone/moddev/mc/orespawn/api/WorldgenProviderTest.java index 179dac1a..cc92ef27 100644 --- a/src/test/java/zone/moddev/mc/orespawn/api/WorldgenProviderTest.java +++ b/src/test/java/zone/moddev/mc/orespawn/api/WorldgenProviderTest.java @@ -369,4 +369,59 @@ private static JsonObject profileDefaults() { profile.addProperty("manage_vanilla_ores", true); return profile; } + @Test + void derivesStablePlacementChannelsAndExposesImmutableMaterial() { + WorldgenProvider.OreDimensionDefinition standard = WorldgenProvider.OreDimensionDefinition + .builder(id("minecraft:overworld")).hostBlock(id("minecraft:stone")).build(); + WorldgenProvider.OreDimensionDefinition custom = WorldgenProvider.OreDimensionDefinition + .builder(id("minecraft:overworld")) + .pattern(id("realisticdeposits:stratiform"), new JsonObject()) + .hostBlock(id("minecraft:stone")).build(); + WorldgenProvider.OreDefinition ore = WorldgenProvider.OreDefinition + .builder(id("examplemod:iron"), id("examplemod:iron_ore")) + .material(id("orespawn:iron")).dimension(standard).build(); + + assertEquals(id("orespawn:iron"), ore.material().get()); + assertEquals(id("orespawn:standard"), standard.placementChannel()); + assertEquals(id("realisticdeposits:stratiform"), custom.placementChannel()); + } + + @Test + void serializesBackgroundControllerAndExistingWorldMergePolicy() { + WorldgenProvider.OreDimensionDefinition placement = WorldgenProvider.OreDimensionDefinition + .builder(id("minecraft:overworld")) + .hostBlock(id("minecraft:stone")) + .backgroundGenerationScale(0.25D) + .build(); + WorldgenProvider provider = WorldgenProvider.builder("examplemod", 1) + .mergeNewEntriesIntoExistingWorlds(false) + .ore(id("examplemod:iron_controller"), id("minecraft:iron_ore"), ore -> ore + .retrogen(false).dimension(placement)) + .build(); + + assertFalse(provider.mergeNewEntriesIntoExistingWorlds()); + assertEquals(0.25D, placement.backgroundGenerationScale().getAsDouble()); + JsonObject json = provider.toJson(); + assertFalse(json.get("merge_new_entries_into_existing_worlds").getAsBoolean()); + assertEquals(0.25D, json.getAsJsonObject("ores") + .getAsJsonObject("examplemod:iron_controller") + .getAsJsonObject("dimensions").getAsJsonObject("minecraft:overworld") + .get("background_generation_scale").getAsDouble()); + } + + @Test + void backgroundControllerDefaultsAreNonControllingAndBoundsAreValidated() { + WorldgenProvider.OreDimensionDefinition ordinary = WorldgenProvider.OreDimensionDefinition + .builder(id("minecraft:overworld")).hostBlock(id("minecraft:stone")).build(); + assertFalse(ordinary.backgroundGenerationScale().isPresent()); + assertTrue(WorldgenProvider.builder("examplemod", 1) + .ore(id("examplemod:ordinary"), id("minecraft:iron_ore"), ore -> ore.dimension(ordinary)) + .build().mergeNewEntriesIntoExistingWorlds()); + assertThrows(IllegalStateException.class, () -> WorldgenProvider.OreDimensionDefinition + .builder(id("minecraft:overworld")).hostBlock(id("minecraft:stone")) + .backgroundGenerationScale(-0.01D).build()); + assertThrows(IllegalStateException.class, () -> WorldgenProvider.OreDimensionDefinition + .builder(id("minecraft:overworld")).hostBlock(id("minecraft:stone")) + .backgroundGenerationScale(1.01D).build()); + } } diff --git a/src/test/java/zone/moddev/mc/orespawn/client/OreSourceEditorViewTest.java b/src/test/java/zone/moddev/mc/orespawn/client/OreSourceEditorViewTest.java new file mode 100644 index 00000000..3b4d391b --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/client/OreSourceEditorViewTest.java @@ -0,0 +1,32 @@ +package zone.moddev.mc.orespawn.client; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.junit.jupiter.api.Test; + +class OreSourceEditorViewTest { + @Test + void oldInferredChannelShowsOnceWithoutRewritingTheSavedChoice() { + JsonObject profile = parse("{\"ores\":{\"example:copper\":{\"dimensions\":" + + "{\"minecraft:overworld\":{\"pattern\":\"orespawn:precision\"}}}}}"); + JsonObject saved = parse("{\"domain\":\"minecraft:overworld\"," + + "\"placement_sources\":{\"orespawn:precision\":\"example:copper\"}," + + "\"candidates\":[{\"source_id\":\"example:copper\",\"placement_channel\":\"orespawn:standard\",\"loaded\":true}," + + "{\"source_id\":\"example:copper\",\"placement_channel\":\"orespawn:precision\",\"loaded\":false}]}"); + String before = saved.toString(); + + JsonObject view = OreSourceEditorView.policy(profile, saved); + assertEquals(1, view.getAsJsonArray("candidates").size()); + assertTrue(view.getAsJsonObject("placement_sources").has("orespawn:standard")); + assertFalse(view.getAsJsonObject("placement_sources").has("orespawn:precision")); + assertEquals(before, saved.toString()); + } + + private static JsonObject parse(String json) { + return new JsonParser().parse(json).getAsJsonObject(); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminDataTest.java b/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminDataTest.java new file mode 100644 index 00000000..a28a20f7 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminDataTest.java @@ -0,0 +1,108 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import static org.junit.jupiter.api.Assertions.*; +import com.google.gson.JsonObject; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import net.minecraft.block.Blocks; +import zone.moddev.mc.orespawn.test.Forge28TestBootstrap; + +class AdminDataTest { + @TempDir Path temporary; + @BeforeAll static void bootstrap() { Forge28TestBootstrap.registerVanilla(); } + + @Test void exactStatesRoundTripIncludingLegacyMetadata() { + for (net.minecraft.block.Block block : new net.minecraft.block.Block[]{Blocks.STONE, Blocks.WHITE_WOOL, Blocks.WATER, Blocks.OAK_LEAVES}) + for (net.minecraft.block.BlockState state : block.getStateContainer().getValidStates()) + assertEquals(state, DiagnosticStates.resolve(DiagnosticStates.key(state))); + } + @Test void chunkSamplesMeasureExactStatesWithoutPredictingTheirOrigin() { + java.util.List visits = new java.util.ArrayList<>(); + com.google.gson.JsonArray samples = AdminCommands.columnSamples(position -> { + visits.add(position); + return Blocks.DIORITE.getDefaultState(); + }, -2, -3, 5, 40); + assertEquals(4, samples.size()); + assertEquals(Arrays.asList(5, 21, 37, 40), Arrays.asList(samples.get(0).getAsJsonObject().get("y").getAsInt(), + samples.get(1).getAsJsonObject().get("y").getAsInt(), samples.get(2).getAsJsonObject().get("y").getAsInt(), + samples.get(3).getAsJsonObject().get("y").getAsInt())); + assertEquals(-24, samples.get(0).getAsJsonObject().get("x").getAsInt()); + assertEquals(-40, samples.get(0).getAsJsonObject().get("z").getAsInt()); + assertEquals(DiagnosticStates.key(Blocks.DIORITE.getDefaultState()), samples.get(0).getAsJsonObject().get("state").getAsString()); + assertEquals(4, visits.size()); + assertEquals(new net.minecraft.util.math.BlockPos(-24, 40, -40), visits.get(3)); + } + @Test void missingStatesNeverBecomeAir() { + assertThrows(IllegalArgumentException.class, () -> DiagnosticStates.resolve("missing:ore[]")); + assertThrows(IllegalArgumentException.class, () -> DiagnosticStates.resolve("minecraft:stone[variant=missing,]")); + assertThrows(IllegalArgumentException.class, () -> DiagnosticStates.resolve("minecraft:oak_log[]")); + } + @Test void fingerprintDoesNotDependOnObjectInsertionOrder() { + JsonObject first = new JsonObject(), second = new JsonObject(); + first.addProperty("a", 1); first.addProperty("b", 2); + second.addProperty("b", 2); second.addProperty("a", 1); + assertEquals(DiagnosticFiles.fingerprint(first), DiagnosticFiles.fingerprint(second)); + } + @Test void verifiedBackupsAreNeverOverwrittenAndDetectCorruption() throws Exception { + Path backup = temporary.resolve("backup.json"); + JsonObject payload = new JsonObject(); payload.addProperty("saved", "state"); + DiagnosticFiles.backup(backup, payload); + assertEquals(payload, DiagnosticFiles.readBackup(backup)); + assertThrows(java.io.IOException.class, () -> DiagnosticFiles.backup(backup, payload)); + Files.write(backup, new String(Files.readAllBytes(backup), StandardCharsets.UTF_8).replace("state", "other").getBytes(StandardCharsets.UTF_8)); + assertThrows(java.io.IOException.class, () -> DiagnosticFiles.readBackup(backup)); + } + @Test void reportIdsCannotEscapeTheirDirectory() { + for (String value : Arrays.asList("../world", "a/b", "a\\b", ".", "", "a:b")) + assertThrows(IllegalArgumentException.class, () -> DiagnosticFiles.child(temporary, value)); + } + @Test void observedCountsUseActualYBiomeAndNegativeChunkCoordinates() { + SurveyCounts counts = new SurveyCounts(); + counts.add("ore", "ore", 3, "desert", -1, -2); + counts.add("ore", "ore", 3, "desert", -1, -2); + counts.add("air", "air", 4, "plains", -1, -2); + JsonObject report = counts.json(); + assertEquals(3, report.get("sampled_volume").getAsInt()); + assertEquals(2, report.get("non_air_volume").getAsInt()); + assertEquals(2, report.getAsJsonObject("by_chunk").get("-1,-2\tore").getAsInt()); + assertEquals(2, report.getAsJsonObject("by_y").get("3\tore").getAsInt()); + assertTrue(counts.csv().get("biomes.csv").contains("\"desert\",\"ore\",2")); + } + @Test void cataloguePreservesVanillaOresAndConfiguredDepositsEvenWhenDisabled() { + JsonObject profile = new com.google.gson.JsonParser().parse("{\"fluid_deposits\":{\"test:water\":{\"enabled\":false,\"block\":\"minecraft:water\"}},\"ores\":{\"test:diorite\":{\"block\":\"minecraft:diorite\"}}}").getAsJsonObject(); + DiagnosticCatalog catalog = new DiagnosticCatalog(profile); + assertFalse(catalog.removable(Blocks.DIORITE.getDefaultState(), false)); + assertTrue(catalog.removable(Blocks.STONE.getDefaultState(), false)); + assertFalse(catalog.removable(Blocks.DIAMOND_ORE.getDefaultState(), false)); + assertFalse(catalog.removable(Blocks.WATER.getDefaultState(), false)); + assertFalse(catalog.removable(Blocks.STONE.getDefaultState(), true)); + assertFalse(catalog.removable(Blocks.CHEST.getDefaultState(), false)); + assertFalse(catalog.removable(Blocks.BEDROCK.getDefaultState(), false)); + } + @Test void undoAllowsOnlyExpectedOrAlreadyRestoredCells() { + EditJournal.Cell cell = new EditJournal.Cell(0, "stone", "air"); + assertTrue(EditJournal.canUndo("air", cell)); + assertTrue(EditJournal.canUndo("stone", cell)); + assertFalse(EditJournal.canUndo("player-chest", cell)); + } + @Test void oversizedReportsStopBeforeAddingAnIncompleteCell() { + SurveyCounts counts = new SurveyCounts(4); + counts.add("ore", "ore", 0, "desert", 0, 0); + assertThrows(IllegalStateException.class, () -> counts.add("air", "air", 0, "desert", 0, 0)); + assertEquals(1, counts.volume()); + assertEquals(1, counts.json().getAsJsonObject("blocks").entrySet().size()); + } + @Test void protectionUsesExactFlattenedIdFallbackWithoutEditingTheProfile() { + JsonObject profile = new com.google.gson.JsonParser().parse("{\"ores\":{\"minecraft:diorite\":{},\"test:wool\":{\"block\":\"minecraft:black_wool\"}},\"rocks\":{\"test:wool\":{\"block\":\"minecraft:black_wool\"}}}").getAsJsonObject(); + String before = profile.toString(); + DiagnosticCatalog catalog = new DiagnosticCatalog(profile); + assertFalse(catalog.removable(Blocks.DIORITE.getDefaultState(), false)); + assertFalse(catalog.removable(Blocks.BLACK_WOOL.getDefaultState(), false)); + assertEquals(before, profile.toString()); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminFeedbackTest.java b/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminFeedbackTest.java new file mode 100644 index 00000000..0a7a0d67 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminFeedbackTest.java @@ -0,0 +1,141 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import static org.junit.jupiter.api.Assertions.*; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.entity.Entity; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.StringTextComponent; +import net.minecraft.util.text.TranslationTextComponent; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.util.text.event.ClickEvent; +import net.minecraft.util.text.event.HoverEvent; +import net.minecraft.world.World; +import org.junit.jupiter.api.Test; + +class AdminFeedbackTest { + private static final String JOB = "93612699-1d93-4b04-b988-af46c628edf0"; + private static final String TOKEN = "c1eec0f7-863f-4b6d-8a14-f509422bd1ac"; + + @Test void previewSeparatesLocationCountsWarningAndActionsWithoutShowingIds() { + List lines = preview(false); + assertEquals(6, lines.size()); + assertEquals("commands.orespawn.preview_title", translated(lines.get(0)).getKey()); + Object[] location = translated(lines.get(1)).getFormatArgs(); + assertEquals("value.orespawn.dimension.overworld", translated((ITextComponent) location[0]).getKey()); + assertArrayEquals(new Object[]{-18, 3, 0, 255}, java.util.Arrays.copyOfRange(location, 1, location.length)); + assertEquals("commands.orespawn.preview_clear_counts", translated(lines.get(2)).getKey()); + assertArrayEquals(new Object[]{14468, 51068}, translated(lines.get(2)).getFormatArgs()); + assertEquals("commands.orespawn.preview_warning", translated(lines.get(3)).getKey()); + assertEquals("commands.orespawn.preview_expiry", translated(lines.get(4)).getKey()); + for (ITextComponent line : lines) { + assertFalse(line.getString().contains(JOB)); + assertFalse(line.getString().contains(TOKEN)); + } + } + + @Test void clearActionsCarryTheExactConfirmationCancelAndDetailsCommands() { + List actions = preview(false).get(5).getSiblings(); + assertEquals(5, actions.size()); + assertAction(actions.get(0), "confirm_clear", "/orespawn clearchunk confirm " + TOKEN); + assertAction(actions.get(2), "preview_cancel", "/orespawn clearchunk cancel " + TOKEN); + assertAction(actions.get(4), "details", "/orespawn jobs " + JOB); + assertEquals(TextFormatting.RED, actions.get(0).getStyle().getColor()); + assertTrue(actions.get(0).getStyle().getBold()); + assertTrue(actions.get(0).getStyle().getUnderlined()); + assertEquals(HoverEvent.Action.SHOW_TEXT, actions.get(0).getStyle().getHoverEvent().getAction()); + } + + @Test void undoHasItsOwnWarningAndBackupBoundConfirmation() { + List lines = preview(true); + assertEquals("commands.orespawn.preview_undo_counts", translated(lines.get(2)).getKey()); + assertEquals("commands.orespawn.preview_undo_warning", translated(lines.get(3)).getKey()); + assertAction(lines.get(5).getSiblings().get(0), "confirm_undo", "/orespawn undo backup-id confirm " + TOKEN); + assertAction(lines.get(5).getSiblings().get(2), "preview_cancel", "/orespawn clearchunk cancel " + TOKEN); + } + + @Test void packetRoundTripKeepsClickableActions() { + ITextComponent copy = ITextComponent.Serializer.fromJson(ITextComponent.Serializer.toJson(preview(false).get(5))); + assertNotNull(copy); + assertAction(copy.getSiblings().get(0), "confirm_clear", "/orespawn clearchunk confirm " + TOKEN); + assertAction(copy.getSiblings().get(2), "preview_cancel", "/orespawn clearchunk cancel " + TOKEN); + } + + @Test void consolesStillReceiveACopyableCommandWithoutWorldAccess() { + Sender sender = new Sender(); + AdminFeedback.preview(sender, JOB, TOKEN, false, null, "example:moon", -18, 3, 0, 255, 14468, 51068); + assertEquals(7, sender.messages.size()); + assertEquals("/orespawn clearchunk confirm " + TOKEN, sender.messages.get(6).getString()); + assertEquals("example:moon", ((ITextComponent) translated(sender.messages.get(1)).getFormatArgs()[0]).getString()); + } + + @Test void completionOffersAnUndoPreviewInTheOriginalDimensionNotAnImmediateRestore() { + Sender sender = new Sender(); + AdminFeedback.completed(sender, JOB, 14468, false, "backup-id", "minecraft:the_nether"); + TranslationTextComponent completed = translated(sender.messages.get(0)); + assertEquals("commands.orespawn.complete_clear", completed.getKey()); + assertEquals(14468, completed.getFormatArgs()[0]); + assertAction((ITextComponent) completed.getFormatArgs()[1], "undo_preview", "/orespawn undo backup-id --dimension minecraft:the_nether"); + assertEquals("/orespawn undo backup-id --dimension minecraft:the_nether", sender.messages.get(1).getString()); + } + + @Test void completedUndoDoesNotOfferAnotherUndoOrShowTheBackupId() { + Sender sender = new Sender(); + AdminFeedback.completed(sender, JOB, 14468, true, "backup-id", "minecraft:overworld"); + assertEquals(1, sender.messages.size()); + assertEquals("commands.orespawn.complete_undo", translated(sender.messages.get(0)).getKey()); + assertFalse(sender.messages.get(0).getString().contains("backup-id")); + } + + @Test void routineJobsUseADetailsLinkAndKeepLargeFailureTextBounded() { + Sender sender = new Sender(); + AdminFeedback.started(sender, JOB); + assertAction((ITextComponent) translated(sender.messages.get(0)).getFormatArgs()[0], "details", "/orespawn jobs " + JOB); + AdminFeedback.result(sender, JOB, "failed", String.join("", java.util.Collections.nCopies(40000, "x"))); + TranslationTextComponent result = translated(sender.messages.get(2)); + String message = (String) result.getFormatArgs()[2]; + assertEquals(1024, message.length()); + assertTrue(message.endsWith("...")); + } + + @Test void dismissingAnUnknownPreviewNeedsNoWorldAndCannotBypassPermissions() { + Sender sender = new Sender(); + assertFalse(AdminJobs.cancelPreview(sender, TOKEN)); + assertThrows(IllegalArgumentException.class, () -> AdminJobs.cancelPreview(new Sender() { + @Override public boolean canUseCommand(int level, String command) { return level <= 2; } + }, TOKEN)); + } + + private static List preview(boolean undo) { + return AdminFeedback.previewLines(JOB, TOKEN, undo, "backup-id", "minecraft:overworld", -18, 3, 0, 255, 14468, 51068); + } + + private static TranslationTextComponent translated(ITextComponent component) { + assertTrue(component instanceof TranslationTextComponent); + return (TranslationTextComponent) component; + } + + private static void assertAction(ITextComponent component, String key, String command) { + assertEquals("commands.orespawn." + key, translated(component).getKey()); + assertNotNull(component.getStyle().getClickEvent()); + assertEquals(ClickEvent.Action.RUN_COMMAND, component.getStyle().getClickEvent().getAction()); + assertEquals(command, component.getStyle().getClickEvent().getValue()); + } + + private static class Sender implements AdminSource { + final List messages = new ArrayList<>(); + public String getName() { return "test"; } + public ITextComponent getDisplayName() { return new StringTextComponent("test"); } + public void sendMessage(ITextComponent text) { messages.add(text); } + public boolean canUseCommand(int level, String command) { return true; } + public BlockPos getPosition() { throw new AssertionError("Unexpected world access"); } + public Vec3d getPositionVector() { throw new AssertionError("Unexpected world access"); } + public net.minecraft.world.server.ServerWorld getEntityWorld() { throw new AssertionError("Unexpected world access"); } + public Entity getCommandSenderEntity() { return null; } + public boolean sendCommandFeedback() { return true; } + public MinecraftServer getServer() { throw new AssertionError("Unexpected server access"); } + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminLightingTest.java b/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminLightingTest.java new file mode 100644 index 00000000..ee00987b --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminLightingTest.java @@ -0,0 +1,148 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import static org.junit.jupiter.api.Assertions.*; +import static zone.moddev.mc.orespawn.test.TestObjects.allocate; +import java.lang.reflect.Field; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.event.world.ChunkDataEvent; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class AdminLightingTest { + @AfterEach void clear() { AdminLighting.clear(); } + + @Test void exactChangedCellsSurviveRepeatedSaveAndReload() throws Exception { + ServerWorld world = allocate(ServerWorld.class); + Chunk chunk = chunk(world, -20, 21); + AdminLighting.changed(world, chunk, new BlockPos(-320, 0, 336)); + AdminLighting.changed(world, chunk, new BlockPos(-305, 255, 351)); + CompoundNBT data = save(chunk); + for (int restart = 0; restart < 3; restart++) { + AdminLighting.clear(); + AdminLighting.onLoad(new ChunkDataEvent.Load(chunk, data.contains("Level", 10) ? data.getCompound("Level") : data)); + assertTrue(AdminLighting.isPending(world, chunk)); + data = save(chunk); + assertArrayEquals(new int[]{0, 65535}, data.getCompound("OreSpawnAdminLighting").getIntArray("cells")); + } + pendingFuture(java.util.concurrent.CompletableFuture.completedFuture(null)); + assertTrue(AdminLighting.complete(world, chunk)); + assertFalse(save(chunk).contains("OreSpawnAdminLighting")); + } + + @Test void worldsAndChunksRemainIndependent() throws Exception { + ServerWorld a = allocate(ServerWorld.class), b = allocate(ServerWorld.class); + Chunk first = chunk(a, -1, -1), second = chunk(b, -1, -1), neighbour = chunk(a, -2, -1); + AdminLighting.changed(a, first, new BlockPos(-1, 12, -1)); + assertTrue(AdminLighting.isPending(a, first)); + assertFalse(AdminLighting.isPending(b, second)); + assertFalse(AdminLighting.isPending(a, neighbour)); + assertFalse(save(second).contains("OreSpawnAdminLighting")); + assertFalse(save(neighbour).contains("OreSpawnAdminLighting")); + } + + @Test void absentMalformedAndOutOfRangeMarkersNeverResumeEdits() throws Exception { + ServerWorld world = allocate(ServerWorld.class); + Chunk chunk = chunk(world, 0, 0); + for (int[] cells : new int[][]{new int[0], {-1}, {65536}, {0, 65536}}) { + AdminLighting.changed(world, chunk, new BlockPos(1, 1, 1)); + CompoundNBT data = new CompoundNBT(), marker = new CompoundNBT(); + marker.putInt("format", 1); marker.putIntArray("cells", cells); + data.put("OreSpawnAdminLighting", marker); + AdminLighting.onLoad(new ChunkDataEvent.Load(chunk, data)); + assertFalse(AdminLighting.isPending(world, chunk)); + } + AdminLighting.changed(world, chunk, new BlockPos(1, 1, 1)); + AdminLighting.onLoad(new ChunkDataEvent.Load(chunk, new CompoundNBT())); + assertFalse(AdminLighting.isPending(world, chunk)); + assertEquals(0, AdminLighting.tick(System.nanoTime() + 1000000, 16384)); + } + + @Test void asyncBarrierRetainsItsMarkerUntilTheNativeFutureCompletes() throws Exception { + ServerWorld world = allocate(ServerWorld.class); + Chunk chunk = chunk(world, 0, 0); + AdminLighting.changed(world, chunk, new BlockPos(0, 15, 0)); + java.util.concurrent.CompletableFuture nativeWork = new java.util.concurrent.CompletableFuture<>(); + pendingFuture(nativeWork); + assertFalse(AdminLighting.complete(world, chunk)); + assertTrue(save(chunk).getCompound("OreSpawnAdminLighting").getBoolean("relight_required")); + nativeWork.complete(null); + assertTrue(AdminLighting.complete(world, chunk)); + assertFalse(save(chunk).contains("OreSpawnAdminLighting")); + } + + @Test void anEmptyCellListStillRestoresAnUnfinishedNativeLightBarrier() throws Exception { + ServerWorld world = allocate(ServerWorld.class); + Chunk chunk = chunk(world, 0, 0); + CompoundNBT data = new CompoundNBT(), marker = new CompoundNBT(); + marker.putInt("format", 1); marker.putIntArray("cells", new int[0]); + marker.putBoolean("relight_required", true); data.put("OreSpawnAdminLighting", marker); + AdminLighting.onLoad(new ChunkDataEvent.Load(chunk, data)); + assertTrue(AdminLighting.isPending(world, chunk)); + pendingFuture(java.util.concurrent.CompletableFuture.completedFuture(null)); + assertTrue(AdminLighting.complete(world, chunk)); + } + + private static void pendingFuture(java.util.concurrent.CompletableFuture future) throws Exception { + Field field = AdminLighting.class.getDeclaredField("PENDING"); field.setAccessible(true); + java.util.Map pending = (java.util.Map) field.get(null); + assertEquals(1, pending.size()); + Object entry = pending.values().iterator().next(); + set(entry.getClass(), entry, "light", future); + } + + @Test void failedNativeLightingKeepsTheRecoveryMarker() throws Exception { + ServerWorld world = allocate(ServerWorld.class); + Chunk chunk = chunk(world, 0, 0); + AdminLighting.changed(world, chunk, new BlockPos(0, 15, 0)); + java.util.concurrent.CompletableFuture nativeWork = new java.util.concurrent.CompletableFuture<>(); + nativeWork.completeExceptionally(new IllegalStateException("worker failed")); + pendingFuture(nativeWork); + assertThrows(java.util.concurrent.CompletionException.class, () -> AdminLighting.complete(world, chunk)); + assertTrue(save(chunk).getCompound("OreSpawnAdminLighting").getBoolean("relight_required")); + } + + @Test void anotherEditCannotReuseAnOlderLightBarrier() throws Exception { + ServerWorld world = allocate(ServerWorld.class); + Chunk chunk = chunk(world, 0, 0); + AdminLighting.changed(world, chunk, new BlockPos(0, 15, 0)); + pendingFuture(java.util.concurrent.CompletableFuture.completedFuture(null)); + AdminLighting.changed(world, chunk, new BlockPos(1, 15, 0)); + Field field = AdminLighting.class.getDeclaredField("PENDING"); field.setAccessible(true); + Object pending = ((java.util.Map) field.get(null)).values().iterator().next(); + Field light = pending.getClass().getDeclaredField("light"); light.setAccessible(true); + assertNull(light.get(pending)); + assertArrayEquals(new int[]{3840, 3841}, save(chunk).getCompound("OreSpawnAdminLighting").getIntArray("cells")); + } + + @Test void aHotReloadRetainsCleanupWithoutResumingTheInterruptedEdit() throws Exception { + ServerWorld world = allocate(ServerWorld.class); + Chunk first = chunk(world, -1, 2), reloaded = chunk(world, -1, 2); + AdminLighting.changed(world, first, new BlockPos(-16, 15, 32)); + AdminLighting.recover(world, first); + AdminLighting.onChunkAvailable(new net.minecraftforge.event.world.ChunkEvent.Load(reloaded)); + assertArrayEquals(new int[]{3840}, save(reloaded).getCompound("OreSpawnAdminLighting").getIntArray("cells")); + Field field = AdminLighting.class.getDeclaredField("PENDING"); field.setAccessible(true); + Object pending = ((java.util.Map) field.get(null)).values().iterator().next(); + Field retained = pending.getClass().getDeclaredField("chunk"); retained.setAccessible(true); + assertSame(reloaded, retained.get(pending)); + } + + private static CompoundNBT save(Chunk chunk) { + CompoundNBT data = new CompoundNBT(); + AdminLighting.onSave(new ChunkDataEvent.Save(chunk, data)); + return data; + } + private static Chunk chunk(ServerWorld world, int x, int z) throws Exception { + Chunk chunk = allocate(Chunk.class); + set(Chunk.class, chunk, "world", world); + set(Chunk.class, chunk, "pos", new net.minecraft.util.math.ChunkPos(x, z)); + return chunk; + } + private static void set(Class type, Object target, String name, Object value) throws Exception { + Field field = type.getDeclaredField(name); field.setAccessible(true); field.set(target, value); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminSafetyTest.java b/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminSafetyTest.java new file mode 100644 index 00000000..ae96d50c --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminSafetyTest.java @@ -0,0 +1,134 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import static org.junit.jupiter.api.Assertions.*; +import com.google.gson.JsonObject; +import java.util.Arrays; +import java.util.Collections; +import net.minecraft.entity.Entity; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.StringTextComponent; +import net.minecraft.world.World; +import org.junit.jupiter.api.Test; + +class AdminSafetyTest { + @Test void confirmationExpiresAtExactlyTwoMinutes() { + PreviewLease lease = new PreviewLease("operator", "profile", 100); + assertTrue(lease.accepts("operator", "profile", 100)); + assertTrue(lease.accepts("operator", "profile", 100 + PreviewLease.LIFETIME - 1)); + assertFalse(lease.accepts("operator", "profile", 100 + PreviewLease.LIFETIME)); + assertFalse(lease.accepts("operator", "profile", 99)); + } + @Test void confirmationRequiresOriginalOperatorAndProfile() { + PreviewLease lease = new PreviewLease("alice", "original", 0); + assertFalse(lease.accepts("bob", "original", 1)); + assertFalse(lease.accepts("alice", "edited", 1)); + } + @Test void destructiveCommandsRejectLevelTwoBeforeAccessingAnyWorld() { + for (String[] command : new String[][]{{"clearchunk"}, {"clearchunk", "confirm", "fake"}, {"clearchunk", "cancel", "fake"}, + {"undo", "backup"}, {"undo", "backup", "confirm", "fake"}}) + assertThrows(AdminFailure.class, () -> AdminCommands.handle(null, new Sender(2), command)); + } + @Test void diagnosticCommandsRejectNonOperatorsBeforeAccessingAnyWorld() { + for (String action : Arrays.asList("help", "chunk", "survey", "explain", "jobs", "cancel")) + assertThrows(AdminFailure.class, () -> AdminCommands.handle(null, new Sender(0), new String[]{action})); + } + @Test void ordinaryStatusAndExistingMaintenanceStillUseTheirOriginalHandler() throws Exception { + for (String action : Arrays.asList("status", "reload", "retrogen", "dump-biomes")) + assertFalse(AdminCommands.handle(null, new Sender(0), new String[]{action})); + } + @Test void helpRequiresNoWorldAndUsesTranslatedMessages() throws Exception { + Sender sender = new Sender(2); + assertTrue(AdminCommands.handle(null, sender, new String[]{"help"})); + assertEquals(4, sender.messages); + } + @Test void radiusAndCoordinateLimitsRejectOverflowAndMalformedNumbers() { + for (String value : Arrays.asList("-1", "9", "999999999999999", "oops")) + assertThrows(IllegalArgumentException.class, () -> AdminCommands.integer(value, 0, 8)); + assertEquals(8, AdminCommands.integer("8", 0, 8)); + assertEquals(-2, AdminCommands.integer("-2", -1874999, 1874999)); + } + @Test void journalsRejectDuplicateOutOfChunkAndUnchangedCells() { + JsonObject header = header(); + EditJournal.Cell cell = new EditJournal.Cell(0, "stone", "air"); + assertThrows(IllegalArgumentException.class, () -> new EditJournal(header, Arrays.asList(cell, cell))); + assertThrows(IllegalArgumentException.class, () -> new EditJournal(header, Collections.singletonList(new EditJournal.Cell(65536, "stone", "air")))); + assertThrows(IllegalArgumentException.class, () -> new EditJournal(header, Collections.singletonList(new EditJournal.Cell(0, "air", "air")))); + } + @Test void journalsRoundTripAndDefensivelyCopyTheirHeader() { + JsonObject header = header(); + EditJournal journal = new EditJournal(header, Collections.singletonList(new EditJournal.Cell(123, "stone", "air"))); + header.addProperty("world", "other"); + EditJournal copy = EditJournal.read(journal.json()); + assertEquals("test", copy.header.get("world").getAsString()); + assertEquals(123, copy.cells.get(0).index); + assertEquals("stone", copy.cells.get(0).before); + assertThrows(UnsupportedOperationException.class, () -> copy.cells.clear()); + } + private static JsonObject header() { + JsonObject result = new JsonObject(); + result.addProperty("minecraft_version", "1.14.4"); + for (String key : new String[]{"world", "dimension", "chunk_x", "chunk_z", "profile", "operator", "snapshot"}) result.addProperty(key, "test"); + return result; + } + @Test void anotherMinecraftVersionsCoordinateEncodingCannotBeRestored() { + JsonObject header = header(); header.addProperty("minecraft_version", "1.21.1"); + assertThrows(IllegalArgumentException.class, () -> new EditJournal(header, Collections.singletonList(new EditJournal.Cell(0, "stone", "air")))); + } + + @Test void anOlderPortsJournalCannotPassAsThisTargetsSnapshot() { + for (String version : new String[]{"1.10.2", "1.13.2"}) { + JsonObject header = header(); header.addProperty("minecraft_version", version); + assertThrows(IllegalArgumentException.class, () -> new EditJournal(header, + Collections.singletonList(new EditJournal.Cell(0, "stone", "air")))); + } + } + @Test void fileBacklogIsBoundedAndNeverRunsOverflowWorkOnTheServerThread() throws Exception { + java.util.concurrent.ExecutorService worker = AdminJobs.newFileWorker(); + java.util.concurrent.CountDownLatch started = new java.util.concurrent.CountDownLatch(1); + java.util.concurrent.CountDownLatch release = new java.util.concurrent.CountDownLatch(1); + try { + worker.submit(() -> { started.countDown(); try { release.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); + assertTrue(started.await(2, java.util.concurrent.TimeUnit.SECONDS)); + for (int i = 0; i < 32; i++) worker.submit(() -> { }); + assertThrows(java.util.concurrent.RejectedExecutionException.class, () -> worker.submit(() -> { fail("Overflow must not run inline"); })); + } finally { release.countDown(); worker.shutdownNow(); } + } + @Test void largeJobReportsCannotOverflowMinecraftChatPackets() throws Exception { + java.lang.reflect.Field field = AdminJobs.class.getDeclaredField("HISTORY"); + field.setAccessible(true); + @SuppressWarnings("unchecked") java.util.Map history = (java.util.Map) field.get(null); + String id = "large-chat-regression"; + JsonObject report = new JsonObject(); + StringBuilder large = new StringBuilder(); + for (int i = 0; i < 40000; i++) large.append('地').append('"').append((char) 92); + report.addProperty("message", large.toString()); + history.put(id, report); + try { + Sender sender = new Sender(2); + assertTrue(AdminCommands.handle(null, sender, new String[]{"jobs", id})); + String packet = ITextComponent.Serializer.toJson(sender.lastMessage); + assertTrue(packet.getBytes(java.nio.charset.StandardCharsets.UTF_8).length < 32767, + "Diagnostic feedback must fit a chat packet; the complete report remains on disk"); + assertEquals(large.toString(), history.get(id).get("message").getAsString()); + } finally { history.remove(id); } + } + private static final class Sender implements AdminSource { + final int level; + int messages; + ITextComponent lastMessage; + Sender(int level) { this.level = level; } + public String getName() { return "test"; } + public ITextComponent getDisplayName() { return new StringTextComponent("test"); } + public void sendMessage(ITextComponent text) { messages++; lastMessage = text; } + public boolean canUseCommand(int required, String name) { return level >= required; } + public BlockPos getPosition() { throw new AssertionError("Unexpected world access"); } + public Vec3d getPositionVector() { throw new AssertionError("Unexpected world access"); } + public net.minecraft.world.server.ServerWorld getEntityWorld() { throw new AssertionError("Unexpected world access"); } + public Entity getCommandSenderEntity() { return null; } + public boolean sendCommandFeedback() { return true; } + public MinecraftServer getServer() { return null; } + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/integration/FormationOverrideTest.java b/src/test/java/zone/moddev/mc/orespawn/integration/FormationOverrideTest.java new file mode 100644 index 00000000..f64a03f8 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/integration/FormationOverrideTest.java @@ -0,0 +1,44 @@ +package zone.moddev.mc.orespawn.integration; + +import static org.junit.jupiter.api.Assertions.*; +import com.google.gson.*; +import java.lang.reflect.Field; +import java.util.*; +import org.junit.jupiter.api.Test; +import zone.moddev.mc.orespawn.test.Forge28TestBootstrap; +import zone.moddev.mc.orespawn.util.JsonCopies; + +class FormationOverrideTest { + @SuppressWarnings("unchecked") + @Test void onlyUntouchedPackagedDefaultsAreTuned() throws Exception { + Forge28TestBootstrap.registerVanilla(); + Field resources=WorldgenIntegrationManager.class.getDeclaredField("RESOURCE_PROVIDERS");resources.setAccessible(true); + Field files=WorldgenIntegrationManager.class.getDeclaredField("FILE_PROVIDERS");files.setAccessible(true); + Map packaged=(Map)resources.get(null), external=(Map)files.get(null); + JsonObject stock=new JsonObject();stock.addProperty("chance",.12);stock.addProperty("enabled",true); + JsonObject definitions=new JsonObject();definitions.add("test:body",stock); + JsonObject provider=new JsonObject();provider.add("rock_formations",definitions); + JsonObject tuning=JsonCopies.copy(definitions);tuning.getAsJsonObject("test:body").addProperty("chance",.45); + JsonObject beforeResource=packaged.get("test"), beforeFile=external.remove("test"); + packaged.put("test",provider); + try { + JsonObject target=JsonCopies.copy(provider); + target.getAsJsonObject("rock_formations").getAsJsonObject("test:body").addProperty("source_provider","test"); + WorldgenIntegrationManager.applyStockFormationTuning(target,tuning); + assertEquals(.45,target.getAsJsonObject("rock_formations").getAsJsonObject("test:body").get("chance").getAsDouble()); + for(String edit:Arrays.asList("chance","enabled")) { + target=JsonCopies.copy(provider); + JsonObject rule=target.getAsJsonObject("rock_formations").getAsJsonObject("test:body"); + if(edit.equals("chance"))rule.addProperty(edit,.2);else rule.addProperty(edit,false); + JsonObject authored=JsonCopies.copy(target);WorldgenIntegrationManager.applyStockFormationTuning(target,tuning); + assertEquals(authored,target); + } + target=new JsonObject();WorldgenIntegrationManager.applyStockFormationTuning(target,tuning);assertFalse(target.has("rock_formations")); + external.put("test",provider);target=JsonCopies.copy(provider); + WorldgenIntegrationManager.applyStockFormationTuning(target,tuning);assertEquals(provider,target); + } finally { + if(beforeResource==null)packaged.remove("test");else packaged.put("test",beforeResource); + if(beforeFile==null)external.remove("test");else external.put("test",beforeFile); + } + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/integration/LegacyOreReplacementsTest.java b/src/test/java/zone/moddev/mc/orespawn/integration/LegacyOreReplacementsTest.java new file mode 100644 index 00000000..1ec93821 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/integration/LegacyOreReplacementsTest.java @@ -0,0 +1,202 @@ +package zone.moddev.mc.orespawn.integration; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.Set; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.junit.jupiter.api.Test; +import zone.moddev.mc.orespawn.util.JsonCopies; + +class LegacyOreReplacementsTest { + private static final String PROVIDER = "baseminerals"; + private static final String OLD = "baseminerals:legacy/baseminerals_lithium_ore_0"; + private static final String NATIVE = "baseminerals:legacy/lithium_ore"; + private static final String FALLBACK_POLICY = "orespawn:lithium|orespawn:all_except_nether_end"; + + private final JsonObject profile = parse("{\"ores\":{},\"ore_source_policies\":{}}"); + private final JsonObject ores = profile.getAsJsonObject("ores"); + private final JsonObject policies = profile.getAsJsonObject("ore_source_policies"); + private final JsonObject defaults = new JsonObject(); + private final JsonObject manifest = new JsonObject(); + private final Set known = new LinkedHashSet<>(Arrays.asList(OLD)); + + LegacyOreReplacementsTest() { + ores.add(OLD, parse("{\"block\":\"baseminerals:lithium_ore\",\"enabled\":false," + + "\"source_mod\":\"baseminerals\",\"source_provider\":\"baseminerals\"," + + "\"native_generation\":false,\"outputs\":[{\"block\":\"baseminerals:lithium_ore\"}]," + + "\"dimensions\":{\"minecraft:overworld\":{\"frequency\":1.5}}}")); + defaults.add(NATIVE, parse("{\"block\":\"baseminerals:lithium_ore\",\"enabled\":true," + + "\"dimensions\":{\"minecraft:overworld\":{\"frequency\":4.0}}," + + "\"dimension_selectors\":{\"orespawn:all_except_nether_end\":{\"frequency\":4.0}}}")); + } + + @Test + void forge25ImportCanBeRecognisedBeforeAProviderHasAManifest() { + String imported = "orespawn:legacy/baseminerals/lithium"; + JsonObject converted = ores.remove(OLD).getAsJsonObject(); + converted.addProperty("source_mod", "legacy"); + converted.addProperty("suppress_vanilla", true); + converted.remove("source_provider"); + ores.add(imported, converted); + known.clear(); + + assertTrue(merge().suppressed.contains(NATIVE)); + assertEquals(imported, manifest.getAsJsonObject("legacy_ore_replacements").get(NATIVE).getAsString()); + assertEquals(converted, ores.get(imported)); + } + + @Test + void instanceMergeDoesNotRemoveAnExistingRuleWithoutAWorldBackup() { + addNative(); + LegacyOreReplacements.Result result = LegacyOreReplacements.reconcile(profile, PROVIDER, ores, + defaults, defaults, manifest, known, false); + assertFalse(result.suppressed.contains(NATIVE)); + assertTrue(ores.has(NATIVE)); + } + + @Test + void remembersImportAndPreservesItsScopeAndChoicesOnEveryReload() { + policies.add("existing", parse("{\"mode\":\"consolidated\",\"output_mode\":\"single\",\"outputs\":{\"" + OLD + "\":1}}")); + JsonObject saved = JsonCopies.copy(profile); + assertTrue(merge().suppressed.contains(NATIVE)); + assertEquals(OLD, manifest.getAsJsonObject("legacy_ore_replacements").get(NATIVE).getAsString()); + assertEquals(saved, profile); + assertTrue(LegacyOreReplacements.retains(manifest, OLD, JsonCopies.keys(defaults))); + assertFalse(merge().changed); + // Removing a previously tracked import is not permission to add the native default. + ores.remove(OLD); + assertTrue(merge().suppressed.contains(NATIVE)); + } + + @Test + void dropsOnlyTheUntouchedAddedDefaultAndItsGeneratedFallback() { + addNative(); + policies.add(FALLBACK_POLICY, parse("{\"material\":\"orespawn:lithium\",\"domain\":\"orespawn:all_except_nether_end\"," + + "\"mode\":\"keep_separate\",\"output_mode\":\"custom\",\"status\":\"separate\"," + + "\"review_required\":false,\"outputs\":{\"" + NATIVE + "\":1}," + + "\"placement_sources\":{\"orespawn:standard\":\"" + NATIVE + "\"}}")); + JsonObject original = JsonCopies.copy(ores.getAsJsonObject(OLD)); + assertTrue(merge().changed); + assertFalse(ores.has(NATIVE)); + assertFalse(policies.has(FALLBACK_POLICY)); + assertEquals(original, ores.get(OLD)); + assertFalse(merge().changed); + } + + @Test + void emptyScopeAddedByOreSourceDiscoveryIsNotAUserEdit() { + defaults.getAsJsonObject(NATIVE).remove("dimension_selectors"); + addNative(); + ores.getAsJsonObject(NATIVE).add("dimension_selectors", new JsonObject()); + + assertTrue(merge().suppressed.contains(NATIVE)); + assertFalse(ores.has(NATIVE)); + } + + @Test + void keepsANativeRuleWithAnAddedPlacementScope() { + defaults.getAsJsonObject(NATIVE).remove("dimension_selectors"); + addNative(); + ores.getAsJsonObject(NATIVE).add("dimension_selectors", + parse("{\"orespawn:all_except_nether_end\":{\"frequency\":1}}")); + JsonObject before = JsonCopies.copy(profile); + + assertFalse(merge().suppressed.contains(NATIVE)); + assertEquals(before, profile); + assertTrue(manifest.getAsJsonObject("legacy_ore_review").has(NATIVE)); + } + + @Test + void retainsAnEditedNativeRuleAndAsksForReview() { + addNative(); + ores.getAsJsonObject(NATIVE).addProperty("enabled", false); + JsonObject before = JsonCopies.copy(profile); + assertFalse(merge().suppressed.contains(NATIVE)); + assertEquals(before, profile); + assertTrue(manifest.getAsJsonObject("legacy_ore_review").has(NATIVE)); + assertFalse(merge().changed); + } + + @Test + void retainsAnUntouchedNativeRuleWhenPlayerPolicyUsesIt() { + addNative(); + policies.add("existing", parse("{\"mode\":\"consolidated\",\"output_mode\":\"single\",\"outputs\":{\"" + NATIVE + "\":1}}")); + JsonObject before = JsonCopies.copy(profile); + assertFalse(merge().suppressed.contains(NATIVE)); + assertEquals(before, profile); + assertTrue(manifest.getAsJsonObject("legacy_ore_review").has(NATIVE)); + } + + @Test + void doesNotGuessForMultipleImportsOrMultipleNativeRules() { + String second = OLD.substring(0, OLD.length() - 1) + "1"; + known.add(second); + ores.add(second, JsonCopies.copy(ores.get(OLD))); + addNative(); + assertTrue(merge().suppressed.contains(NATIVE)); + assertTrue(ores.has(NATIVE)); + assertFalse(manifest.has("legacy_ore_replacements")); + assertTrue(manifest.getAsJsonObject("legacy_ore_review").has(NATIVE)); + + ores.remove(second); + defaults.add("baseminerals:other_lithium", JsonCopies.copy(defaults.get(NATIVE))); + assertTrue(merge().suppressed.contains(NATIVE)); + assertTrue(ores.has(NATIVE)); + assertFalse(manifest.has("legacy_ore_replacements")); + } + + @Test + void doesNotMatchAnUntrackedRuleOrAnotherOutputVariant() { + known.clear(); + assertFalse(merge().suppressed.contains(NATIVE)); + known.add(OLD); + defaults.getAsJsonObject(NATIVE).addProperty("metadata", 1); + assertFalse(merge().suppressed.contains(NATIVE)); + ores.getAsJsonObject(OLD).addProperty("source_provider", "anothermod"); + defaults.getAsJsonObject(NATIVE).remove("metadata"); + assertFalse(merge().suppressed.contains(NATIVE)); + assertFalse(manifest.has("legacy_ore_replacements")); + } + + @Test + void recognizesStockDuplicateEvenWhenTheOldConvertedFileIsActive() { + addNative(); + JsonObject active = new JsonObject(); + active.add(OLD, JsonCopies.copy(ores.get(OLD))); + assertTrue(LegacyOreReplacements.reconcile(profile, PROVIDER, ores, defaults, active, manifest, known, true) + .suppressed.contains(NATIVE)); + assertFalse(ores.has(NATIVE)); + } + + @Test + void retainsADefaultChangedByAProviderOverride() { + addNative(); + JsonObject active = JsonCopies.copy(defaults); + active.getAsJsonObject(NATIVE).addProperty("enabled", false); + assertFalse(LegacyOreReplacements.reconcile(profile, PROVIDER, ores, defaults, active, manifest, known, true) + .suppressed.contains(NATIVE)); + assertTrue(ores.has(NATIVE)); + assertTrue(manifest.getAsJsonObject("legacy_ore_review").has(NATIVE)); + } + + private void addNative() { + JsonObject nativeRule = JsonCopies.copy(defaults.getAsJsonObject(NATIVE)); + nativeRule.addProperty("source_provider", PROVIDER); + ores.add(NATIVE, nativeRule); + known.add(NATIVE); + } + + private LegacyOreReplacements.Result merge() { + return LegacyOreReplacements.reconcile(profile, PROVIDER, ores, defaults, defaults, manifest, known, true); + } + + private static JsonObject parse(String source) { + return new JsonParser().parse(source).getAsJsonObject(); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/integration/RetainedProviderOreDefaultsTest.java b/src/test/java/zone/moddev/mc/orespawn/integration/RetainedProviderOreDefaultsTest.java new file mode 100644 index 00000000..8df2edbe --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/integration/RetainedProviderOreDefaultsTest.java @@ -0,0 +1,374 @@ +package zone.moddev.mc.orespawn.integration; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class RetainedProviderOreDefaultsTest { + + private Map providers; + private Map previous; + private JsonObject provider; + private JsonObject profile; + + @BeforeEach + @SuppressWarnings("unchecked") + void installOnlyTheFixtureProvider() throws Exception { + java.lang.reflect.Field field = WorldgenIntegrationManager.class.getDeclaredField("ACTIVE_PROVIDERS"); + field.setAccessible(true); + providers = (Map) field.get(null); + previous = new LinkedHashMap<>(providers); + providers.clear(); + provider = fixture("current-basemetals-ores.json"); + profile = fixture("retained-basemetals-ores.json"); + JsonObject policy = new JsonParser().parse("{\"mode\":\"keep_separate\",\"outputs\":{\"basemetals:tin_ore\":1.0},\n\t\t\t\t \"placement_sources\":{\"orespawn:standard\":\"basemetals:legacy/tin_ore\"}}").getAsJsonObject(); + JsonObject policies = new JsonObject(); + policies.add("orespawn:tin|minecraft:overworld", policy); + profile.add("ore_source_policies", policies); + activate("basemetals", provider); + } + + @AfterEach + void restoreOtherProviderTests() { + if (providers != null && previous != null) { + providers.clear(); + providers.putAll(previous); + } + } + + @ParameterizedTest + @ValueSource(strings = {"coldiron", "adamantine", "starsteel", "tin", "lead", "zinc", "silver", "mercury", "nickel", "platinum"}) + void retainsEachSavedBaseMetalsRuleAndAddsACompleteDisabledAlternative(String material) { + JsonObject before = copy(profile); + JsonObject providerBefore = copy(provider); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + JsonObject alternative = ores(profile).getAsJsonObject("basemetals:ore/" + material); + assertFalse(alternative.get("enabled").getAsBoolean(), material + " must not get a second placement pass"); + JsonObject expected = copy(ores(provider).getAsJsonObject("basemetals:ore/" + material)); + expected.addProperty("enabled", false); + expected.addProperty("source_provider", "basemetals"); + assertEquals(expected, alternative, "The alternative remains complete and editable"); + assertSavedRules(before); + assertEquals(before.get("ore_source_policies"), profile.get("ore_source_policies")); + assertEquals(providerBefore, provider, "Merging must not change packaged provider defaults"); + } + + @Test + void disabledAndZeroFrequencySavedChoicesAreNotReenabled() { + JsonObject saved = ores(profile).getAsJsonObject("basemetals:legacy/coldiron_ore"); + saved.addProperty("enabled", false); + JsonObject placement = saved.getAsJsonObject("dimensions").getAsJsonObject("minecraft:the_nether"); + placement.addProperty("enabled", false); + placement.addProperty("frequency", 0); + JsonObject before = copy(profile); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + assertFalse(ores(profile).getAsJsonObject("basemetals:ore/coldiron").get("enabled").getAsBoolean()); + assertSavedRules(before); + } + + @Test + void aUserMayEnableTheAlternativeAndThatChoiceSurvivesRepeatedMerges() { + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + ores(profile).getAsJsonObject("basemetals:ore/coldiron").addProperty("enabled", true); + JsonObject chosen = copy(profile); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + assertEquals(chosen, profile); + assertTrue(ores(profile).getAsJsonObject("basemetals:ore/coldiron").get("enabled").getAsBoolean()); + } + + @Test + void anExistingExplicitModernRuleIsNeverChanged() { + JsonObject chosen = copy(ores(provider).getAsJsonObject("basemetals:ore/coldiron")); + chosen.getAsJsonObject("dimensions").getAsJsonObject("minecraft:the_nether").addProperty("frequency", 0.125); + ores(profile).add("basemetals:ore/coldiron", copy(chosen)); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + assertEquals(chosen, ores(profile).get("basemetals:ore/coldiron")); + } + + @Test + void anIntentionallyRemovedKnownAlternativeIsNotRecreated() { + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + ores(profile).remove("basemetals:ore/coldiron"); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + assertFalse(ores(profile).has("basemetals:ore/coldiron")); + } + + @Test + void deletingAKnownHistoricalRuleDoesNotEnableItsReplacement() { + ores(profile).remove("basemetals:legacy/coldiron_ore"); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + assertFalse(ores(profile).has("basemetals:legacy/coldiron_ore")); + assertFalse(ores(profile).getAsJsonObject("basemetals:ore/coldiron").get("enabled").getAsBoolean()); + } + + @ParameterizedTest + @ValueSource(ints = {1, 2}) + void unrelatedMatchingRowsDoNotOverrideAKnownHistoricalDeletion(int count) { + ores(profile).remove("basemetals:legacy/coldiron_ore"); + Map custom = new LinkedHashMap<>(); + for (int index = 0; index < count; index++) { + JsonObject row = copy(ores(provider).getAsJsonObject("basemetals:ore/coldiron")); + row.addProperty("source_provider", "anothermod"); + String id = "anothermod:custom/coldiron_" + index; + custom.put(id, copy(row)); + ores(profile).add(id, row); + } + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + assertFalse(ores(profile).getAsJsonObject("basemetals:ore/coldiron").get("enabled").getAsBoolean()); + custom.forEach((id, row) -> assertEquals(row, ores(profile).get(id))); + } + + @Test + void aSecondCurrentDepositDoesNotOverrideAnExplicitHistoricalDeletion() throws Exception { + ores(profile).remove("basemetals:legacy/coldiron_ore"); + ores(provider).add("basemetals:ore/extra_coldiron", copy(ores(provider).get("basemetals:ore/coldiron"))); + activate("basemetals", provider); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + assertFalse(ores(profile).getAsJsonObject("basemetals:ore/coldiron").get("enabled").getAsBoolean()); + assertTrue(ores(profile).getAsJsonObject("basemetals:ore/extra_coldiron").get("enabled").getAsBoolean()); + } + + @Test + void aRuleThatWasNeverKnownStillGetsItsNormalDefault() { + ores(profile).remove("basemetals:legacy/coldiron_ore"); + profile.remove("providers"); + assertCurrentColdIronEnabled(); + } + + @Test + void freshProfilesKeepAllCurrentProviderDefaults() { + profile = new JsonObject(); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + for (Map.Entry entry : ores(provider).entrySet()) { + JsonObject expected = copy(entry.getValue().getAsJsonObject()); + expected.addProperty("source_provider", "basemetals"); + assertEquals(expected, ores(profile).get(entry.getKey())); + } + } + + @Test + void aCustomRuleOrOrphanMarkerAloneDoesNotDeclareALegacyReplacement() { + JsonObject old = ores(profile).remove("basemetals:legacy/coldiron_ore").getAsJsonObject(); + // No historical deletion is recorded in this unrelated-rule fixture. + profile.remove("providers"); + old.addProperty("orphaned_provider", true); + ores(profile).add("basemetals:custom/extra_coldiron", old); + assertCurrentColdIronEnabled(); + } + + @Test + void foreignOwnerProvenanceDoesNotDisableThisProvidersDefaults() { + JsonObject old = ores(profile).remove("basemetals:legacy/coldiron_ore").getAsJsonObject(); + profile.remove("providers"); + old.addProperty("source_provider", "anothermod"); + ores(profile).add("anothermod:legacy/coldiron_ore", old); + assertCurrentColdIronEnabled(); + } + + @Test + void conflictingExplicitOwnerIsNotTreatedAsAnOwnedImport() { + ores(profile).getAsJsonObject("basemetals:legacy/coldiron_ore").addProperty("source_provider", "anothermod"); + assertCurrentColdIronEnabled(); + } + + @Test + void oreSpawnImporterIdsAlsoCarryPositiveOwnerProvenance() { + JsonObject old = ores(profile).remove("basemetals:legacy/coldiron_ore").getAsJsonObject(); + profile.remove("providers"); + old.remove("source_provider"); + ores(profile).add("orespawn:legacy/basemetals/coldiron_ore", old); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + assertFalse(ores(profile).getAsJsonObject("basemetals:ore/coldiron").get("enabled").getAsBoolean()); + } + + @ParameterizedTest + @ValueSource(strings = {"orespawn:legacy/examplemod/diamond", "examplemod:legacy/diamond"}) + void genericImportsAreRecognisedButAnArbitraryProvidersLegacyPrefixIsNot(String savedId) throws Exception { + JsonObject current = copy(ores(provider).getAsJsonObject("basemetals:ore/coldiron")); + current.addProperty("block", "minecraft:diamond_ore"); + current.addProperty("source_mod", "examplemod"); + JsonObject defaults = new JsonObject(); + JsonObject currentOres = new JsonObject(); + currentOres.add("examplemod:ore/diamond", current); + defaults.add("ores", currentOres); + providers.clear(); + activate("examplemod", defaults); + JsonObject saved = copy(current); + JsonObject savedOres = new JsonObject(); + savedOres.add(savedId, saved); + profile = new JsonObject(); + profile.add("ores", savedOres); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + assertEquals(!savedId.startsWith("orespawn:legacy/"), + ores(profile).getAsJsonObject("examplemod:ore/diamond").get("enabled").getAsBoolean()); + assertEquals(saved, ores(profile).get(savedId)); + } + + @ParameterizedTest + @ValueSource(strings = {"legacy", "basemetals", "anothermod"}) + void fallbackOwnershipMustNotConflictWithTheImportedOwner(String fallbackOwner) { + JsonObject old = ores(profile).remove("basemetals:legacy/coldiron_ore").getAsJsonObject(); + profile.remove("providers"); + old.remove("source_provider"); + old.addProperty("source_mod", fallbackOwner); + ores(profile).add("orespawn:legacy/basemetals/coldiron_ore", old); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + assertEquals(fallbackOwner.equals("anothermod"), + ores(profile).getAsJsonObject("basemetals:ore/coldiron").get("enabled").getAsBoolean()); + } + + @Test + void explicitProviderOwnershipTakesPrecedenceOverTheFallbackOwner() { + ores(profile).getAsJsonObject("basemetals:legacy/coldiron_ore").addProperty("source_mod", "anothermod"); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + assertFalse(ores(profile).getAsJsonObject("basemetals:ore/coldiron").get("enabled").getAsBoolean()); + } + + @Test + void separateDimensionAndPlacementChannelDepositsRemainEnabled() { + JsonObject old = ores(profile).getAsJsonObject("basemetals:legacy/coldiron_ore"); + JsonObject placement = old.getAsJsonObject("dimensions").remove("minecraft:the_nether").getAsJsonObject(); + old.getAsJsonObject("dimensions").add("minecraft:the_end", placement); + assertCurrentColdIronEnabled(); + old.getAsJsonObject("dimensions").remove("minecraft:the_end"); + old.getAsJsonObject("dimensions").add("minecraft:the_nether", placement); + placement.addProperty("placement_channel", "anothermod:enrichment"); + assertCurrentColdIronEnabled(); + } + + @Test + void multipleCurrentPlacementsForOneOutputAreNotGuessedAway() throws Exception { + ores(provider).add("basemetals:ore/extra_coldiron", copy(ores(provider).get("basemetals:ore/coldiron"))); + activate("basemetals", provider); + assertCurrentColdIronEnabled(); + assertTrue(ores(profile).getAsJsonObject("basemetals:ore/extra_coldiron").get("enabled").getAsBoolean()); + } + + @Test + void multipleLegacyPlacementsForOneOutputAreNotGuessedAway() { + ores(profile).add("basemetals:legacy/extra_coldiron", copy(ores(profile).get("basemetals:legacy/coldiron_ore"))); + assertCurrentColdIronEnabled(); + } + + @Test + void weightedMixedOutputsAndMetadataVariantsAreNotEquivalent() { + JsonObject old = ores(profile).getAsJsonObject("basemetals:legacy/coldiron_ore"); + JsonArray outputs = old.getAsJsonArray("outputs"); + JsonObject extra = copy(outputs.get(0).getAsJsonObject()); + extra.addProperty("block", "basemetals:tin_ore"); + outputs.add(extra); + assertCurrentColdIronEnabled(); + JsonArray singleton = new JsonArray(); + singleton.add(outputs.get(0)); + old.add("outputs", singleton); + old.addProperty("metadata", 1); + assertCurrentColdIronEnabled(); + } + + @Test + void differentDeepOutputsOrNamespacedPatternChannelsAreNotEquivalent() { + JsonObject old = ores(profile).getAsJsonObject("basemetals:legacy/coldiron_ore"); + old.addProperty("deep_output", "basemetals:tin_ore"); + assertCurrentColdIronEnabled(); + old.remove("deep_output"); + JsonObject placement = old.getAsJsonObject("dimensions").getAsJsonObject("minecraft:the_nether"); + placement.remove("placement_channel"); + placement.add("pattern", new JsonParser().parse("{\"type\":\"anothermod:enrichment\"}")); + assertCurrentColdIronEnabled(); + } + + @Test + void emptyOrMalformedPlacementScopesAreNotEquivalent() { + JsonObject old = ores(profile).getAsJsonObject("basemetals:legacy/coldiron_ore"); + old.add("dimensions", new JsonObject()); + assertCurrentColdIronEnabled(); + } + + private void assertCurrentColdIronEnabled() { + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + assertTrue(ores(profile).getAsJsonObject("basemetals:ore/coldiron").get("enabled").getAsBoolean()); + ores(profile).remove("basemetals:ore/coldiron"); + profile.remove("providers"); + profile.remove("ore_providers"); + } + + private void assertSavedRules(JsonObject before) { + for (Map.Entry entry : ores(before).entrySet()) { + JsonObject expected = copy(entry.getValue().getAsJsonObject()); + JsonObject actual = copy(ores(profile).getAsJsonObject(entry.getKey())); + expected.remove("orphaned_provider"); + actual.remove("orphaned_provider"); + assertEquals(expected, actual, entry.getKey()); + } + } + + private void activate(String owner, JsonObject defaults) throws Exception { + Class type = Class.forName(WorldgenIntegrationManager.class.getName() + "$ProviderDefinition"); + java.lang.reflect.Constructor constructor = type.getDeclaredConstructor(String.class, int.class, JsonObject.class); + constructor.setAccessible(true); + providers.put(owner, constructor.newInstance(owner, 1, defaults)); + } + + @ParameterizedTest + @ValueSource(strings = {"default", "vein", "normal_cloud", "precision", "clusters", "underfluids", "custom"}) + void matchingUsesThisTargetsEffectivePatternChannels(String pattern) throws Exception { + JsonObject current = ores(provider).getAsJsonObject("basemetals:ore/coldiron") + .getAsJsonObject("dimensions").getAsJsonObject("minecraft:the_nether"); + JsonObject saved = ores(profile).getAsJsonObject("basemetals:legacy/coldiron_ore") + .getAsJsonObject("dimensions").getAsJsonObject("minecraft:the_nether"); + saved.remove("placement_channel"); + JsonObject shape = new JsonObject(); + shape.addProperty("type", "orespawn:" + pattern); + saved.add("pattern", shape); + Class policies = Class.forName("zone.moddev.mc.orespawn.worldgen.OreSourcePolicies"); + java.lang.reflect.Method channel = policies.getDeclaredMethod("placementChannel", JsonObject.class); + channel.setAccessible(true); + boolean sameChannel = channel.invoke(null, current).equals(channel.invoke(null, saved)); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + assertEquals(!sameChannel, ores(profile).getAsJsonObject("basemetals:ore/coldiron") + .get("enabled").getAsBoolean(), "A saved explicit or custom channel must not be collapsed"); + } + + @ParameterizedTest + @ValueSource(strings = {"", " "}) + void blankChannelsUseTheTargetsDefaultChannel(String blank) throws Exception { + JsonObject saved = ores(profile).getAsJsonObject("basemetals:legacy/coldiron_ore") + .getAsJsonObject("dimensions").getAsJsonObject("minecraft:the_nether"); + saved.addProperty("placement_channel", blank); + WorldgenIntegrationManager.mergeProviderDefinitions(profile); + assertFalse(ores(profile).getAsJsonObject("basemetals:ore/coldiron").get("enabled").getAsBoolean()); + } + + private static JsonObject copy(JsonObject value) { + return new JsonParser().parse(value.toString()).getAsJsonObject(); + } + + private static JsonElement copy(JsonElement value) { + return new JsonParser().parse(value.toString()); + } + + private static JsonObject ores(JsonObject root) { return root.getAsJsonObject("ores"); } + + private static JsonObject fixture(String name) throws Exception { + try (java.io.InputStream input = RetainedProviderOreDefaultsTest.class.getResourceAsStream("/provider-merge/" + name)) { + assertNotNull(input); + try (InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8)) { + return new JsonParser().parse(reader).getAsJsonObject(); + } + } + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/integration/WorldgenIntegrationManagerTest.java b/src/test/java/zone/moddev/mc/orespawn/integration/WorldgenIntegrationManagerTest.java index 2ac2dddb..2b3cf6e5 100644 --- a/src/test/java/zone/moddev/mc/orespawn/integration/WorldgenIntegrationManagerTest.java +++ b/src/test/java/zone/moddev/mc/orespawn/integration/WorldgenIntegrationManagerTest.java @@ -1,5 +1,8 @@ package zone.moddev.mc.orespawn.integration; +import java.util.LinkedHashMap; +import java.lang.reflect.Field; +import java.lang.reflect.Constructor; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -186,4 +189,53 @@ private static JsonObject biomeProvider(int schema, String fluid) { root.add("dimension_materials", materials); return root; } + @Test + void providerCanDeferNewEntriesForExistingWorldsWithoutChangingNewWorldDefaults() + throws Exception { + JsonObject root = new JsonObject(); + root.addProperty("schema_version", 4); + root.addProperty("provider_modid", "realisticdeposits"); + root.addProperty("provider_revision", 1); + root.addProperty("merge_new_entries_into_existing_worlds", false); + JsonObject ores = new JsonObject(); + ores.add("realisticdeposits:deposit/minecraft/iron_ore", new JsonObject()); + root.add("ores", ores); + + Class definitionType = Class.forName( + "zone.moddev.mc.orespawn.integration.WorldgenIntegrationManager$ProviderDefinition"); + Constructor constructor = definitionType.getDeclaredConstructor( + String.class, int.class, JsonObject.class); + constructor.setAccessible(true); + Object provider = constructor.newInstance("realisticdeposits", 1, root); + Field activeField = WorldgenIntegrationManager.class.getDeclaredField("ACTIVE_PROVIDERS"); + activeField.setAccessible(true); + Map active = (Map) activeField.get(null); + Map saved = new LinkedHashMap(active); + try { + active.clear(); + active.put("realisticdeposits", provider); + JsonObject existingWorld = new JsonObject(); + WorldgenIntegrationManager.mergeSavedProviderDefinitions(existingWorld); + assertFalse(existingWorld.getAsJsonObject("ores") + .has("realisticdeposits:deposit/minecraft/iron_ore")); + + JsonObject newWorld = new JsonObject(); + WorldgenIntegrationManager.mergeProviderDefinitions(newWorld); + assertTrue(newWorld.getAsJsonObject("ores") + .has("realisticdeposits:deposit/minecraft/iron_ore")); + } finally { + active.clear(); + active.putAll(saved); + } + } + + @Test + void absentProvidersDoNotIntroduceAFormationSectionIntoAnOldSave() { + JsonObject root = new JsonObject(); + JsonObject providers = new JsonObject(); + providers.add("not_installed", new JsonObject()); + root.add("providers", providers); + WorldgenIntegrationManager.mergeSavedProviderDefinitions(root); + assertFalse(root.has("rock_formations")); + } } diff --git a/src/test/java/zone/moddev/mc/orespawn/test/EclipseSourceAccessTest.java b/src/test/java/zone/moddev/mc/orespawn/test/EclipseSourceAccessTest.java new file mode 100644 index 00000000..7aede4dd --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/test/EclipseSourceAccessTest.java @@ -0,0 +1,32 @@ +package zone.moddev.mc.orespawn.test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; + +class EclipseSourceAccessTest { + @Test + void sourcesDoNotDependDirectlyOnRestrictedJreClasses() throws Exception { + // javac accepts these references, but Eclipse's Java 8 execution + // environment rejects them. Do not hide that difference in IDE settings. + Pattern restricted = Pattern.compile("(?m)^\\s*import\\s+(?:static\\s+)?sun\\." + + "|\\bsun\\.(?:misc|reflect)\\.[\\w$]+\\s*\\.class\\b"); + List offending = new ArrayList<>(); + try (Stream sources = Files.walk(Paths.get("src"))) { + for (Path path : (Iterable) sources.filter(file -> file.toString().endsWith(".java"))::iterator) { + String text = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + if (restricted.matcher(text).find()) offending.add(path.toString()); + } + } + assertEquals(java.util.Collections.emptyList(), offending, + "Use the test-only allocator rather than importing restricted JRE classes"); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/test/TestObjects.java b/src/test/java/zone/moddev/mc/orespawn/test/TestObjects.java new file mode 100644 index 00000000..0b266ebf --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/test/TestObjects.java @@ -0,0 +1,20 @@ +package zone.moddev.mc.orespawn.test; + +import java.lang.reflect.Field; + +/** Creates empty fixture objects without starting the Minecraft server their constructors need. */ +public final class TestObjects { + private TestObjects() { + } + + public static T allocate(Class type) throws ReflectiveOperationException { + // Keep the internal Java 8 API behind reflection so Eclipse can compile + // these tests with its normal JRE access restrictions still enabled. + Class allocator = Class.forName("sun.misc.Unsafe"); + Field singleton = allocator.getDeclaredField("theUnsafe"); + singleton.setAccessible(true); + Object instance = allocator.getMethod("allocateInstance", Class.class) + .invoke(singleton.get(null), type); + return type.cast(instance); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/test/TestObjectsTest.java b/src/test/java/zone/moddev/mc/orespawn/test/TestObjectsTest.java new file mode 100644 index 00000000..ad627db8 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/test/TestObjectsTest.java @@ -0,0 +1,32 @@ +package zone.moddev.mc.orespawn.test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; + +import org.junit.jupiter.api.Test; + +class TestObjectsTest { + @Test + void allocationDoesNotRunTheConstructorOrFieldInitializers() throws Exception { + Fixture value = TestObjects.allocate(Fixture.class); + assertEquals(0, value.number); + } + + @Test + void eachAllocationCreatesAnIndependentObject() throws Exception { + Fixture first = TestObjects.allocate(Fixture.class); + Fixture second = TestObjects.allocate(Fixture.class); + first.number = 12; + assertNotSame(first, second); + assertEquals(12, first.number); + assertEquals(0, second.number); + } + + private static final class Fixture { + int number = 42; + + private Fixture() { + throw new AssertionError("A test shell must not run this constructor"); + } + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/AquiferMaterialSubstitutionTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/AquiferMaterialSubstitutionTest.java new file mode 100644 index 00000000..af457f18 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/AquiferMaterialSubstitutionTest.java @@ -0,0 +1,190 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.BitSet; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import net.minecraft.block.Blocks; +import net.minecraft.world.chunk.ChunkPrimer; +import net.minecraft.world.gen.ChunkGenerator; +import net.minecraft.world.chunk.ChunkSection; +import zone.moddev.mc.orespawn.test.Forge28TestBootstrap; + +class AquiferMaterialSubstitutionTest { + @BeforeAll + static void bootstrapMinecraftRegistries() { + Forge28TestBootstrap.registerVanilla(); + } + + @Test + void capturesOnlyExactNativeFluidBelowSeaLevel() { + ChunkPrimer primer = new ChunkPrimer(new net.minecraft.util.math.ChunkPos(0, 0), net.minecraft.world.chunk.UpgradeData.EMPTY); + primer.setBlockState(new net.minecraft.util.math.BlockPos(1, 10, 2), Blocks.WATER.getDefaultState(), false); + primer.setBlockState(new net.minecraft.util.math.BlockPos(3, 63, 4), Blocks.WATER.getDefaultState(), false); + primer.setBlockState(new net.minecraft.util.math.BlockPos(5, 64, 6), Blocks.WATER.getDefaultState(), false); + primer.setBlockState(new net.minecraft.util.math.BlockPos(7, 20, 8), Blocks.LAVA.getDefaultState(), false); + + BitSet mask = AquiferMaterialSubstitution.captureMask( + primer, Blocks.WATER.getDefaultState(), 64); + + assertEquals(2, mask.cardinality()); + assertTrue(mask.get(AquiferMaterialSubstitution.index(1, 10, 2))); + assertTrue(mask.get(AquiferMaterialSubstitution.index(3, 63, 4))); + assertFalse(mask.get(AquiferMaterialSubstitution.index(5, 64, 6))); + assertFalse(mask.get(AquiferMaterialSubstitution.index(7, 20, 8))); + } + + @Test + void primerIndexRoundTripsEveryLocalCoordinate() { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y : new int[] { 0, 1, 63, 127, 255 }) { + int index = AquiferMaterialSubstitution.index(x, y, z); + assertEquals(x, AquiferMaterialSubstitution.localX(index)); + assertEquals(y, AquiferMaterialSubstitution.localY(index)); + assertEquals(z, AquiferMaterialSubstitution.localZ(index)); + } + } + } + } + + @ParameterizedTest + @ValueSource(ints = {-1, 0, 1, 17, 63, 256, 300}) + void sectionCaptureMatchesExactChunkReadsAndKeepsBelowSeaMasksCompact(int seaLevel) { + ChunkPrimer primer = new ChunkPrimer(new net.minecraft.util.math.ChunkPos(-3, -9), net.minecraft.world.chunk.UpgradeData.EMPTY); + java.util.Random random = new java.util.Random(417); + net.minecraft.block.BlockState[] states = {Blocks.AIR.getDefaultState(), Blocks.STONE.getDefaultState(), + Blocks.WATER.getDefaultState(), Blocks.WATER.getDefaultState().with(net.minecraft.state.properties.BlockStateProperties.LEVEL_0_15, 1)}; + net.minecraft.util.math.BlockPos.MutableBlockPos cursor = new net.minecraft.util.math.BlockPos.MutableBlockPos(); + for (int y = 0; y < 80; y++) for (int z = 0; z < 16; z++) for (int x = 0; x < 16; x++) + primer.setBlockState(cursor.setPos(x, y, z), states[random.nextInt(states.length)], false); + int maximumY = Math.max(0, Math.min(256, seaLevel)); + BitSet expected = new BitSet(); + for (int y = 0; y < maximumY; y++) for (int z = 0; z < 16; z++) for (int x = 0; x < 16; x++) + if (primer.getBlockState(cursor.setPos(x, y, z)).equals(Blocks.WATER.getDefaultState())) + expected.set(AquiferMaterialSubstitution.index(x, y, z)); + BitSet actual = AquiferMaterialSubstitution.captureMask(primer, Blocks.WATER.getDefaultState(), seaLevel); + assertEquals(expected, actual); + assertTrue(actual.size() <= maximumY * 256); + } + + @Test + void unusualNativeAirStillIncludesAbsentSections() { + BitSet mask = AquiferMaterialSubstitution.captureMask(new ChunkPrimer(new net.minecraft.util.math.ChunkPos(-1, -2), net.minecraft.world.chunk.UpgradeData.EMPTY), Blocks.AIR.getDefaultState(), 32); + assertEquals(32 * 256, mask.cardinality()); + } + + @Test + void customChunkViewsUseTheirOwnBlockReads() { + net.minecraft.world.chunk.IChunk view = (net.minecraft.world.chunk.IChunk) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[]{net.minecraft.world.chunk.IChunk.class}, (proxy, method, arguments) -> { + if (!method.getName().equals("getBlockState")) throw new AssertionError("Unexpected chunk access: " + method); + net.minecraft.util.math.BlockPos position = (net.minecraft.util.math.BlockPos) arguments[0]; + return position.getX() == 1 && position.getY() == 2 && position.getZ() == 3 + ? Blocks.WATER.getDefaultState() : Blocks.AIR.getDefaultState(); + }); + BitSet mask = AquiferMaterialSubstitution.captureMask(view, Blocks.WATER.getDefaultState(), 4); + assertEquals(1, mask.cardinality()); + assertTrue(mask.get(AquiferMaterialSubstitution.index(1, 2, 3))); + } + + @Test + void pendingMasksAreIdentityScopedAndConsumedOnceAtNegativeCoordinates() { + AquiferMaterialSubstitution.PendingMasks masks = + new AquiferMaterialSubstitution.PendingMasks(); + ChunkGenerator overworld = generator(); + ChunkGenerator otherDimension = generator(); + BitSet bits = new BitSet(); + bits.set(AquiferMaterialSubstitution.index(2, 30, 9)); + AquiferMaterialSubstitution.Pending pending = new AquiferMaterialSubstitution.Pending( + Blocks.WATER.getDefaultState(), Blocks.WATER.getDefaultState().with(net.minecraft.state.properties.BlockStateProperties.LEVEL_0_15, 1), bits); + + masks.put(overworld, -12, -34, pending); + assertNull(masks.take(otherDimension, -12, -34)); + assertNotNull(masks.take(overworld, -12, -34)); + assertNull(masks.take(overworld, -12, -34)); + assertEquals(0, masks.size()); + } + + @Test + void pendingMasksCanBeRemovedPerDimensionOrClearedAtShutdown() { + AquiferMaterialSubstitution.PendingMasks masks = + new AquiferMaterialSubstitution.PendingMasks(); + ChunkGenerator overworld = generator(); + ChunkGenerator nether = generator(); + AquiferMaterialSubstitution.Pending pending = new AquiferMaterialSubstitution.Pending( + Blocks.WATER.getDefaultState(), Blocks.WATER.getDefaultState().with(net.minecraft.state.properties.BlockStateProperties.LEVEL_0_15, 1), new BitSet()); + masks.put(overworld, 0, 0, pending); + masks.put(nether, 0, 0, pending); + + masks.remove(overworld); + assertNull(masks.take(overworld, 0, 0)); + assertNotNull(masks.take(nether, 0, 0)); + masks.put(nether, 1, 1, pending); + masks.clear(); + assertEquals(0, masks.size()); + } + + @Test + void lightingCompatibilitySelectsTheSafeFastPath() { + assertTrue(AquiferMaterialSubstitution.lightCompatible( + Blocks.WATER.getDefaultState(), Blocks.WATER.getDefaultState().with(net.minecraft.state.properties.BlockStateProperties.LEVEL_0_15, 1))); + assertFalse(AquiferMaterialSubstitution.lightCompatible( + Blocks.WATER.getDefaultState(), Blocks.LAVA.getDefaultState())); + } + + @Test + void substitutionTouchesOnlyRecordedCellsThatStillContainNativeFluid() { + ChunkSection[] sections = new ChunkSection[16]; + sections[1] = new ChunkSection(16); + sections[1].setBlockState(1, 4, 2, Blocks.WATER.getDefaultState()); + sections[1].setBlockState(3, 5, 4, Blocks.LAVA.getDefaultState()); + sections[1].setBlockState(5, 6, 6, Blocks.WATER.getDefaultState()); + + BitSet bits = new BitSet(); + bits.set(AquiferMaterialSubstitution.index(1, 20, 2)); + bits.set(AquiferMaterialSubstitution.index(3, 21, 4)); + AquiferMaterialSubstitution.Pending pending = new AquiferMaterialSubstitution.Pending( + Blocks.WATER.getDefaultState(), Blocks.WATER.getDefaultState().with(net.minecraft.state.properties.BlockStateProperties.LEVEL_0_15, 1), bits); + + assertEquals(1, AquiferMaterialSubstitution.applyToSections(pending, sections)); + assertEquals(Blocks.WATER.getDefaultState().with(net.minecraft.state.properties.BlockStateProperties.LEVEL_0_15, 1), sections[1].getBlockState(1, 4, 2)); + assertEquals(Blocks.LAVA.getDefaultState(), sections[1].getBlockState(3, 5, 4), + "a recorded cell changed by caves or another pass must be preserved"); + assertEquals(Blocks.WATER.getDefaultState(), sections[1].getBlockState(5, 6, 6), + "a later lake or spring outside the mask must be preserved"); + } + + @Test + void passRunsBeforeLakesAndLeavesGenerationRandomnessAndNotificationsAlone() throws Exception { + String installer = new String(Files.readAllBytes(Paths.get("src/main/java/zone/moddev/mc/orespawn/worldgen/BiomeFeatureInstaller.java")), StandardCharsets.UTF_8); + assertTrue(installer.contains("GenerationStage.Decoration.RAW_GENERATION")); + String substitution = new String(Files.readAllBytes(Paths.get("src/main/java/zone/moddev/mc/orespawn/worldgen/AquiferMaterialSubstitution.java")), StandardCharsets.UTF_8); + assertTrue(substitution.contains("section.setBlockState(x, y & 15, z, pending.selectedFluid)")); + assertFalse(substitution.contains("world.setBlockState")); + assertFalse(substitution.contains("scheduleUpdate")); + assertFalse(substitution.contains("nextInt(")); + assertTrue(substitution.indexOf("generator.defaultFluid = nativeFluid") + < substitution.indexOf("if (lightCompatible(nativeFluid, selected))")); + assertTrue(substitution.contains("entry.getKey().defaultFluid = entry.getValue()")); + assertTrue(substitution.contains("WorldgenBenchmark.isVanillaBaseline()")); + } + + private static ChunkGenerator generator() { + try { return zone.moddev.mc.orespawn.test.TestObjects.allocate(net.minecraft.world.gen.OverworldChunkGenerator.class); } + catch (ReflectiveOperationException failure) { throw new AssertionError(failure); } + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/BackgroundGenerationScaleTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/BackgroundGenerationScaleTest.java new file mode 100644 index 00000000..4b3fc857 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/BackgroundGenerationScaleTest.java @@ -0,0 +1,66 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.IdentityHashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.util.ResourceLocation; + +class BackgroundGenerationScaleTest { + private static final ResourceLocation OVERWORLD = new ResourceLocation("minecraft", "overworld"); + private static final ResourceLocation IRON = new ResourceLocation("minecraft", "iron_ore"); + + @Test + void controllerRuleRemainsUnscaledWhileBackgroundRulesAreScaled() { + assertEquals(8.0D, OreSpawnOreGeneration.scaledManagedFrequency(8.0D, true, 0.25D)); + assertEquals(2.0D, OreSpawnOreGeneration.scaledManagedFrequency(8.0D, false, 0.25D)); + } + + @Test + void declaredMaterialsScaleOnlyTheStandardPlacementChannel() { + ResourceLocation material = new ResourceLocation("orespawn:iron"); + assertEquals(0.15D, OreSpawnOreGeneration.channelBackgroundScale(material, + new ResourceLocation("orespawn:standard"), 0.15D, 0.75D)); + assertEquals(1.0D, OreSpawnOreGeneration.channelBackgroundScale(material, + new ResourceLocation("realisticdeposits:district"), 0.15D, 0.75D)); + assertEquals(0.75D, OreSpawnOreGeneration.channelBackgroundScale(null, + new ResourceLocation("orespawn:standard"), 0.15D, 0.75D)); + } + + @Test + void lowestControllerScaleWinsForTheSamePrimaryResource() { + Map scales = new IdentityHashMap<>(); + Block output = new Block(Block.Properties.create(Material.ROCK)); + OreSpawnOreGeneration.mergeBackgroundScale(scales, output, 0.75D); + OreSpawnOreGeneration.mergeBackgroundScale(scales, output, 0.25D); + OreSpawnOreGeneration.mergeBackgroundScale(scales, output, 0.5D); + assertEquals(0.25D, scales.get(output).doubleValue()); + } + + @Test + void vanillaScaleGateIsStableByWorldDimensionChunkAndResource() { + assertFalse(OreSpawnOreGeneration.passesBackgroundScale( + OVERWORLD, IRON, 42L, -3, 7, 0.0D)); + assertTrue(OreSpawnOreGeneration.passesBackgroundScale( + OVERWORLD, IRON, 42L, -3, 7, 1.0D)); + boolean first = OreSpawnOreGeneration.passesBackgroundScale( + OVERWORLD, IRON, 42L, -3, 7, 0.25D); + assertEquals(first, OreSpawnOreGeneration.passesBackgroundScale( + OVERWORLD, IRON, 42L, -3, 7, 0.25D)); + + int accepted = 0; + for (int chunk = -5000; chunk < 5000; chunk++) { + if (OreSpawnOreGeneration.passesBackgroundScale( + OVERWORLD, IRON, 42L, chunk, -chunk, 0.25D)) accepted++; + } + assertTrue(accepted > 2200 && accepted < 2800, + "quarter-scale gate should retain approximately one quarter of chunks: " + accepted); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/LegacyConfigMigratorTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/LegacyConfigMigratorTest.java index 52eef7b3..76ec7466 100644 --- a/src/test/java/zone/moddev/mc/orespawn/worldgen/LegacyConfigMigratorTest.java +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/LegacyConfigMigratorTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; @@ -22,6 +23,17 @@ class LegacyConfigMigratorTest { @TempDir Path temporary; + @Test + void leavesAnExistingInstanceProfileAlone() throws IOException { + Path legacy = Files.createDirectories(temporary.resolve("orespawn3")).resolve("basemetals.json"); + write(legacy, baseMetalsFixture().toString()); + Path target = temporary.resolve("orespawn-worldgen.json"); + String original = "{\"ores\":{},\"manage_vanilla_ores\":false}"; + write(target, original); + assertNull(LegacyConfigMigrator.migrateIfNeeded(target, new JsonObject())); + assertEquals(original, read(target)); + } + @Test void migratesBaseMetalsOs3FixtureExactly() throws IOException { Path legacyDirectory = Files.createDirectories(temporary.resolve("orespawn3")); diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/MmdOreConflictCatalogTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/MmdOreConflictCatalogTest.java index 4f9e6db7..68c8820b 100644 --- a/src/test/java/zone/moddev/mc/orespawn/worldgen/MmdOreConflictCatalogTest.java +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/MmdOreConflictCatalogTest.java @@ -38,9 +38,9 @@ void unrelatedExternalAndEnrichmentProvidersDoNotTriggerBalancing() { @Test void establishedPrioritiesAndDimensionProvidersRemainDistinct() { - assertEquals(Arrays.asList("mineralogy", "baseminerals", "electricadvantage"), + assertEquals(Arrays.asList("mineralogy", "baseminerals", "baseelectric", "electricadvantage"), MmdOreConflictCatalog.priority("sulfur")); - assertEquals(Arrays.asList("baseminerals", "electricadvantage"), + assertEquals(Arrays.asList("baseminerals", "baseelectric", "electricadvantage"), MmdOreConflictCatalog.priority("lithium")); assertEquals(Collections.emptyList(), MmdOreConflictCatalog.priority("copper")); assertTrue(MmdOreConflictCatalog.netherOnly("nethermetals")); diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeAquaticCompatibilityTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeAquaticCompatibilityTest.java new file mode 100644 index 00000000..41c1d9b0 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeAquaticCompatibilityTest.java @@ -0,0 +1,77 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.*; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.fluid.Fluids; +import net.minecraft.block.Blocks; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IWorld; +import net.minecraft.world.biome.Biome; +import net.minecraft.world.gen.feature.ConfiguredFeature; +import net.minecraft.world.gen.feature.Feature; +import net.minecraft.world.gen.feature.LiquidsConfig; +import net.minecraft.world.gen.feature.NoFeatureConfig; +import net.minecraft.world.gen.placement.IPlacementConfig; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import zone.moddev.mc.orespawn.test.Forge28TestBootstrap; + +class NativeAquaticCompatibilityTest { + @BeforeAll static void bootstrap() { Forge28TestBootstrap.registerVanilla(); } + @Test void fluidOnlyCompatibilityDoesNotChangeSpringsOrUnrelatedFeatures() { + ConfiguredFeature kelp = Biome.createDecoratedFeature(Feature.KELP, new NoFeatureConfig(), net.minecraft.world.gen.placement.Placement.NOPE, IPlacementConfig.NO_PLACEMENT_CONFIG); + ConfiguredFeature spring = Biome.createDecoratedFeature(Feature.SPRING_FEATURE, new LiquidsConfig(Fluids.WATER.getDefaultState()), net.minecraft.world.gen.placement.Placement.NOPE, IPlacementConfig.NO_PLACEMENT_CONFIG); + List> features = new ArrayList<>(java.util.Arrays.asList(kelp, spring)); + assertTrue(VanillaSpringCompatibility.rewriteFeatureList(features, false, true)); + assertSame(NativeAquaticCompatibility.FEATURE, + ((net.minecraft.world.gen.feature.DecoratedFeatureConfig) features.get(0).config).feature.feature); + assertSame(spring, features.get(1)); + assertFalse(VanillaSpringCompatibility.rewriteFeatureList(features, false, true)); + assertSame(Feature.KELP, ((net.minecraft.world.gen.feature.DecoratedFeatureConfig) kelp.config).feature.feature, + "The saved original must remain unchanged"); + } + @Test void onlyKnownNativeAquaticDecoratorsReceiveTheNativeView() { + for (Feature feature : new Feature[]{Feature.LAKE, Feature.SEAGRASS, Feature.KELP, Feature.SEA_PICKLE, + Feature.CORAL_TREE, Feature.CORAL_CLAW, Feature.CORAL_MUSHROOM, Feature.SWAMP_TREE, + Feature.ICEBERG, Feature.BLUE_ICE, Feature.OCEAN_MONUMENT, Feature.OCEAN_RUIN, + Feature.BURIED_TREASURE, Feature.STRONGHOLD, Feature.VILLAGE, Feature.WATERLILY, Feature.REED, + Feature.DISK, Feature.FREEZE_TOP_LAYER}) assertTrue(NativeAquaticCompatibility.accepts(feature)); + for (Feature feature : new Feature[]{Feature.SPRING_FEATURE, Feature.ORE, + StoneReplacer.FEATURE, NativeAquaticCompatibility.FEATURE}) assertFalse(NativeAquaticCompatibility.accepts(feature)); + } + + @Test void nativeReadViewKeepsWritesAndRandomnessOnTheRealWorld() { + BlockPos position = new BlockPos(-17, 40, 31); + java.util.Random random = new java.util.Random(17); + java.util.concurrent.atomic.AtomicReference write = new java.util.concurrent.atomic.AtomicReference<>(); + IWorld world = (IWorld) java.lang.reflect.Proxy.newProxyInstance(IWorld.class.getClassLoader(), + new Class[]{IWorld.class}, (proxy, method, arguments) -> { + switch (method.getName()) { + case "getBlockState": return Blocks.LAVA.getDefaultState(); + case "getRandom": return random; + case "setBlockState": write.set(arguments); return true; + default: throw new AssertionError("Unexpected operation: " + method); + } + }); + NativeAquiferView view = new NativeAquiferView(world, Blocks.WATER.getDefaultState(), Blocks.LAVA.getDefaultState()); + assertSame(Blocks.WATER.getDefaultState(), view.getBlockState(position)); + assertSame(Blocks.WATER.getDefaultState().getFluidState(), view.getFluidState(position)); + assertSame(random, view.getRandom()); + assertTrue(view.setBlockState(position, Blocks.LAVA.getDefaultState(), 2)); + assertSame(position, write.get()[0]); + assertSame(Blocks.LAVA.getDefaultState(), write.get()[1]); + assertEquals(2, write.get()[2]); + } + + @Test void customWorldFluidLookupsAreNotReplacedWithBlockStateDefaults() { + IWorld world = (IWorld) java.lang.reflect.Proxy.newProxyInstance(IWorld.class.getClassLoader(), + new Class[]{IWorld.class}, (proxy, method, arguments) -> { + if (method.getName().equals("getBlockState")) return Blocks.STONE.getDefaultState(); + if (method.getName().equals("getFluidState")) return Fluids.LAVA.getDefaultState(); + throw new AssertionError("Unexpected operation: " + method); + }); + NativeAquiferView view = new NativeAquiferView(world, Blocks.WATER.getDefaultState(), Blocks.LAVA.getDefaultState()); + assertSame(Fluids.LAVA.getDefaultState(), view.getFluidState(new BlockPos(0, 0, 0))); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeBakeDiagnosticsTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeBakeDiagnosticsTest.java new file mode 100644 index 00000000..426dca65 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeBakeDiagnosticsTest.java @@ -0,0 +1,43 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.Logger; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.junit.jupiter.api.Test; +import zone.moddev.mc.orespawn.test.Forge28TestBootstrap; +import zone.moddev.mc.orespawn.test.TestObjects; + +class NativeBakeDiagnosticsTest { + @Test void onlyAnAuthoritativeWorldTagBakeWarnsAboutAnUnresolvedRule() throws Exception { + Forge28TestBootstrap.registerVanilla(); + Logger logger = (Logger) LogManager.getLogger(OreSpawnOreGeneration.class); + Level oldLevel = logger.getLevel(); boolean oldAdditive = logger.isAdditive(); + List levels = new ArrayList<>(); + AbstractAppender sink = new AbstractAppender("tag-readiness-test", null, null, false) { + @Override public void append(LogEvent event) { levels.add(event.getLevel()); } + }; + Field server = WorldGeologyProfileManager.class.getDeclaredField("activeServer"); server.setAccessible(true); + Field pending = WorldGeologyProfileManager.class.getDeclaredField("tagRulesPending"); pending.setAccessible(true); + Object previousServer = server.get(null), previousPending = pending.get(null); + sink.start(); logger.addAppender(sink); logger.setLevel(Level.ALL); logger.setAdditive(false); + try { + Method report = OreSpawnOreGeneration.class.getDeclaredMethod("reportBakeProblem", String.class, Object[].class); + report.setAccessible(true); + server.set(null, TestObjects.allocate(net.minecraft.server.dedicated.DedicatedServer.class)); + pending.set(null, true); report.invoke(null, "Provisional tag lookup", new Object[0]); + pending.set(null, false); report.invoke(null, "Definitively invalid lookup", new Object[0]); + server.set(null, null); report.invoke(null, "Early mod-loading lookup", new Object[0]); + assertEquals(java.util.Arrays.asList(Level.DEBUG, Level.WARN, Level.DEBUG), levels); + } finally { + server.set(null, previousServer); pending.set(null, previousPending); + logger.removeAppender(sink); sink.stop(); logger.setLevel(oldLevel); logger.setAdditive(oldAdditive); + } + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeDensityTerrainTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeDensityTerrainTest.java new file mode 100644 index 00000000..c5bb6793 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeDensityTerrainTest.java @@ -0,0 +1,89 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.*; +import static zone.moddev.mc.orespawn.test.TestObjects.allocate; +import java.lang.reflect.Field; +import net.minecraft.world.biome.provider.BiomeProvider; +import net.minecraft.world.gen.ChunkGenerator; +import net.minecraft.world.gen.OverworldChunkGenerator; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import zone.moddev.mc.orespawn.test.Forge28TestBootstrap; + +class NativeDensityTerrainTest { + @BeforeAll static void bootstrap() { Forge28TestBootstrap.registerVanilla(); } + @AfterEach void clear() { NativeDensityTerrain.clear(); } + + @Test void interpolatesTheNativeVerticalAndHorizontalAxes() throws Exception { + NativeDensityTerrain.Data data = new NativeDensityTerrain.Data(generator(0), 0, 0); + assertEquals(32.0, data.density(0, 0, 0)); + assertEquals(32 - 19 + .1 * 7 / 4 + .2 * 11 / 4, data.density(7, 19, 11), 1e-9); + assertEquals(32 - 255 + .1 * 15 / 4 + .2 * 15 / 4, data.density(15, 255, 15), 1e-9); + } + + @Test void negativeChunkCoordinatesKeepTheirNativeNoiseOrigin() throws Exception { + NativeDensityTerrain.Data data = new NativeDensityTerrain.Data(generator(0), -3, -4); + assertEquals(32 - .1 * 12 - .2 * 16, data.density(0, 0, 0), 1e-9); + assertEquals(27, data.terrainTop(0, 0)); + } + + @Test void fluidMaskRejectsCountryRockAndStopsAtSeaLevel() throws Exception { + NativeDensityTerrain.Data data = new NativeDensityTerrain.Data(generator(63), 0, 0); + assertFalse(data.nativeFluid(0, 5, 0)); + assertTrue(data.nativeFluid(0, 32, 0)); + assertTrue(data.nativeFluid(0, 62, 0)); + assertFalse(data.nativeFluid(0, 63, 0)); + assertFalse(data.nativeFluid(0, -1, 0)); + assertFalse(data.nativeFluid(0, 256, 0)); + } + + @Test void waterCoveredColumnsDoNotBecomeDryFormationSurfaces() throws Exception { + assertEquals(-1, new NativeDensityTerrain.Data(generator(63), 0, 0).terrainTop(0, 0)); + assertEquals(31, new NativeDensityTerrain.Data(generator(0), 0, 0).terrainTop(0, 0)); + } + + @Test void samplesEachDensityCornerOnceAndReusesTheChunk() throws Exception { + Generator generator = generator(0); + NativeDensityTerrain.Data data = NativeDensityTerrain.chunk(generator, -2, 3); + assertEquals(25, generator.calls); + for (int x = 0; x < 16; x++) for (int z = 0; z < 16; z++) data.terrainTop(x, z); + assertSame(data, NativeDensityTerrain.chunk(generator, -2, 3)); + assertEquals(25, generator.calls); + } + + @Test void differentGeneratorsAndProviderChangesCannotShareDensity() throws Exception { + Generator generator = generator(0); + NativeDensityTerrain.Data original = NativeDensityTerrain.chunk(generator, 0, 0); + assertNotSame(original, NativeDensityTerrain.chunk(generator(0), 0, 0)); + Field provider = ChunkGenerator.class.getDeclaredField("biomeProvider"); provider.setAccessible(true); + provider.set(generator, allocate(BiomeOverlaySource.class)); + assertNotSame(original, NativeDensityTerrain.chunk(generator, 0, 0)); + assertEquals(50, generator.calls); + } + + @Test void cacheHasABoundedWorkingSetAndCanBeCleared() throws Exception { + Generator generator = generator(0); + NativeDensityTerrain.Data oldest = NativeDensityTerrain.chunk(generator, 0, 0); + for (int x = 1; x <= 512; x++) NativeDensityTerrain.chunk(generator, x, 0); + assertNotSame(oldest, NativeDensityTerrain.chunk(generator, 0, 0)); + NativeDensityTerrain.clear(); + assertEquals(514 * 25, generator.calls); + NativeDensityTerrain.chunk(generator, 0, 0); + assertEquals(515 * 25, generator.calls); + } + + private static Generator generator(int seaLevel) throws Exception { + Generator generator = allocate(Generator.class); generator.seaLevel = seaLevel; return generator; + } + + private static final class Generator extends OverworldChunkGenerator { + int seaLevel, calls; + private Generator() { super(null, null, null); } + @Override public int getSeaLevel() { return seaLevel; } + @Override protected void func_222548_a(double[] column, int x, int z) { + calls++; + for (int y = 0; y < column.length; y++) column[y] = 32 - y * 8 + x * .1 + z * .2; + } + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeFeatureIdentityTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeFeatureIdentityTest.java new file mode 100644 index 00000000..4355e7a2 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeFeatureIdentityTest.java @@ -0,0 +1,13 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import net.minecraft.util.ResourceLocation; +import org.junit.jupiter.api.Test; +import zone.moddev.mc.orespawn.test.Forge28TestBootstrap; + +class NativeFeatureIdentityTest { + @Test void managedOreFeatureKeepsItsForgeRegistryIdentity() { + Forge28TestBootstrap.registerVanilla(); + assertEquals(new ResourceLocation("orespawn:managed_ores"), OreSpawnOreGeneration.FEATURE.getRegistryName()); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeOreHostTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeOreHostTest.java index a34f5146..68298bc0 100644 --- a/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeOreHostTest.java +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeOreHostTest.java @@ -11,6 +11,7 @@ import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.HashMap; +import java.util.IdentityHashMap; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -21,6 +22,7 @@ import org.junit.jupiter.api.Test; import com.google.gson.JsonObject; +import com.google.gson.JsonElement; import com.google.gson.JsonArray; import com.google.gson.JsonParser; @@ -57,6 +59,19 @@ void restoreTags() { BlockTags.setCollection(previousTags); } + @Test + void plainStoneHostDoesNotAcceptTheFlattenedIgneousBlocks() throws Exception { + Method add = OreSpawnOreGeneration.class.getDeclaredMethod("addBlocks", Map.class, Map.class, JsonElement.class); + add.setAccessible(true); + Map hosts = new IdentityHashMap<>(); + JsonArray blocks = new JsonArray(); + blocks.add("minecraft:stone"); + Map exact = new IdentityHashMap<>(); + add.invoke(null, hosts, exact, blocks); + assertEquals(Collections.singletonMap(Blocks.STONE, 1.0D), hosts); + assertTrue(exact.isEmpty(), "A bare stone ID must not broaden into other flattened rocks"); + } + @Test void forge28ShipsTheDefaultQuartzHost() throws Exception { try (InputStream input = getClass().getResourceAsStream("/data/forge/tags/blocks/netherrack.json")) { diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/NativePortContractsTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativePortContractsTest.java new file mode 100644 index 00000000..1e74aa46 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativePortContractsTest.java @@ -0,0 +1,72 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.*; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import net.minecraft.block.Block; +import net.minecraft.block.BlockState; +import net.minecraft.block.Blocks; +import net.minecraft.world.biome.Biome; +import net.minecraft.world.gen.feature.ConfiguredFeature; +import net.minecraft.world.gen.feature.Feature; +import net.minecraft.world.gen.feature.OreFeatureConfig; +import net.minecraft.world.gen.placement.IPlacementConfig; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import zone.moddev.mc.orespawn.test.Forge28TestBootstrap; +import zone.moddev.mc.orespawn.util.ConfiguredBlockState; + +class NativePortContractsTest { + @BeforeAll static void bootstrap() { Forge28TestBootstrap.registerVanilla(); } + + @Test void retainedLegacyMetadataDoesNotReinterpretFlattenedHostIds() throws Exception { + JsonObject host = new JsonObject(); + host.addProperty("block", "minecraft:stone"); host.addProperty("metadata", 3); + JsonArray hosts = new JsonArray(); hosts.add(host); + Map blocks = new IdentityHashMap<>(); + Map exact = new IdentityHashMap<>(); + Method add = OreSpawnOreGeneration.class.getDeclaredMethod("addBlocks", Map.class, Map.class, com.google.gson.JsonElement.class); + add.setAccessible(true); add.invoke(null, blocks, exact, hosts); + assertEquals(java.util.Collections.singletonMap(Blocks.STONE, 1.0), blocks); + assertTrue(exact.isEmpty(), "Existing 1.13 profiles used flattened IDs, not legacy variants"); + } + + @Test void exactPropertiesUseMinecraftValidationWithoutChangingTheDefinition() { + JsonObject block = new JsonObject(); block.addProperty("block", "minecraft:oak_log"); + JsonObject properties = new JsonObject(); properties.addProperty("axis", "x"); + block.add("properties", properties); + String original = block.toString(); + assertEquals(net.minecraft.util.Direction.Axis.X, + ConfiguredBlockState.read(block).get(net.minecraft.state.properties.BlockStateProperties.AXIS)); + assertEquals(original, block.toString()); + properties.addProperty("axis", "sideways"); + assertThrows(IllegalArgumentException.class, () -> ConfiguredBlockState.read(block)); + } + + @Test void oreGateDoesNotHideNativeStonePatchesFromTerrainReplacement() { + ConfiguredFeature patch = Biome.createDecoratedFeature(Feature.ORE, + new OreFeatureConfig(OreFeatureConfig.FillerBlockType.NATURAL_STONE, Blocks.GRANITE.getDefaultState(), 10), + net.minecraft.world.gen.placement.Placement.NOPE, IPlacementConfig.NO_PLACEMENT_CONFIG); + List> features = new ArrayList<>(); features.add(patch); + assertTrue(VanillaOreFeatureGate.wrapFeatureList(features)); + assertTrue(StoneReplacer.removeVanillaMatchingStoneFeatures(features)); + assertTrue(features.isEmpty()); + } + + @Test void nestedNativeStoneContextsRestoreTheirOuterPass() { + boolean outer = NativeStonePatchContext.enter(true, Blocks.GRANITE); + try { + assertTrue(NativeStonePatchContext.active()); + boolean inner = NativeStonePatchContext.enter(true, Blocks.IRON_ORE); + assertFalse(NativeStonePatchContext.active()); + NativeStonePatchContext.restore(inner); + assertTrue(NativeStonePatchContext.active()); + } finally { NativeStonePatchContext.restore(outer); } + assertFalse(NativeStonePatchContext.active()); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeStructureProtectionTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeStructureProtectionTest.java new file mode 100644 index 00000000..5a0f456c --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeStructureProtectionTest.java @@ -0,0 +1,81 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.*; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.util.math.MutableBoundingBox; +import net.minecraft.world.biome.Biome; +import net.minecraft.world.biome.Biomes; +import net.minecraft.world.chunk.ChunkPrimer; +import net.minecraft.world.chunk.IChunk; +import net.minecraft.world.chunk.UpgradeData; +import net.minecraft.world.gen.ChunkGenerator; +import net.minecraft.world.gen.WorldGenRegion; +import net.minecraft.world.gen.feature.Feature; +import net.minecraft.world.gen.feature.structure.StructureStart; +import net.minecraft.world.gen.feature.template.TemplateManager; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import zone.moddev.mc.orespawn.test.Forge28TestBootstrap; +import zone.moddev.mc.orespawn.test.TestObjects; + +class NativeStructureProtectionTest { + @BeforeAll static void bootstrap() { Forge28TestBootstrap.registerVanilla(); } + + @Test void localStartsAndNeighbourReferencesProtectTheirExactBounds() throws Exception { + WorldGenRegion region = region(); + IChunk center = region.getChunk(-1, -1), neighbour = region.getChunk(0, -1); + MutableBoundingBox local = new MutableBoundingBox(-16, 20, -16, -1, 40, -1); + MutableBoundingBox crossing = new MutableBoundingBox(-8, 30, -8, 10, 50, 10); + center.putStructureStart("Mansion", start(local)); + neighbour.putStructureStart("Mineshaft", start(crossing)); + center.addStructureReference("Mineshaft", ChunkPos.asLong(0, -1)); + List boxes = boxes(region, center); + assertEquals(2, boxes.size()); assertTrue(boxes.contains(local)); assertTrue(boxes.contains(crossing)); + Method protectedAt = NaturalFormations.class.getDeclaredMethod("protectedAt", List.class, int.class, int.class, int.class); + protectedAt.setAccessible(true); + assertEquals(true, protectedAt.invoke(null, boxes, -16, 20, -16)); + assertEquals(true, protectedAt.invoke(null, boxes, 10, 50, 10)); + assertEquals(false, protectedAt.invoke(null, boxes, 11, 50, 10)); + } + + @Test void anUnavailableStartFailsClosedWithoutRequestingAnotherChunk() throws Exception { + WorldGenRegion region = region(); IChunk center = region.getChunk(-1, -1); + center.addStructureReference("Mansion", ChunkPos.asLong(200, -200)); + assertNull(boxes(region, center)); + assertFalse(region.chunkExists(200, -200)); + } + + @Test void aMissingReferencedStartIsNotTreatedAsUnprotectedTerrain() throws Exception { + WorldGenRegion region = region(); IChunk center = region.getChunk(-1, -1); + center.addStructureReference("Mansion", ChunkPos.asLong(0, -1)); + assertNull(boxes(region, center)); + } + + @SuppressWarnings("unchecked") + private static List boxes(WorldGenRegion region, IChunk chunk) throws Exception { + Method method = NaturalFormations.class.getDeclaredMethod("structures", net.minecraft.world.IWorld.class, IChunk.class); + method.setAccessible(true); return (List) method.invoke(null, region, chunk); + } + private static StructureStart start(MutableBoundingBox box) { + return new StructureStart(Feature.WOODLAND_MANSION, -1, -1, Biomes.PLAINS, box, 0, 47) { + @Override public void init(ChunkGenerator generator, TemplateManager templates, int x, int z, Biome biome) { } + @Override public boolean isValid() { return true; } + }; + } + private static WorldGenRegion region() throws Exception { + WorldGenRegion region = TestObjects.allocate(WorldGenRegion.class); + List chunks = new ArrayList<>(); + for (int z = -2; z <= 0; z++) for (int x = -2; x <= 0; x++) + chunks.add(new ChunkPrimer(new ChunkPos(x, z), UpgradeData.EMPTY)); + set(region, "chunkPrimers", chunks); set(region, "field_217380_e", 3); + set(region, "mainChunkX", -1); set(region, "mainChunkZ", -1); + return region; + } + private static void set(Object target, String name, Object value) throws Exception { + Field field = WorldGenRegion.class.getDeclaredField(name); field.setAccessible(true); field.set(target, value); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/NaturalFormationTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/NaturalFormationTest.java new file mode 100644 index 00000000..a3e931cd --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/NaturalFormationTest.java @@ -0,0 +1,145 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.*; +import com.google.gson.*; +import java.util.*; +import net.minecraft.block.BlockState; +import net.minecraft.block.Blocks; +import net.minecraft.util.ResourceLocation; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import zone.moddev.mc.orespawn.api.*; +import zone.moddev.mc.orespawn.test.Forge28TestBootstrap; + +class NaturalFormationTest { + @BeforeAll static void bootstrap() { Forge28TestBootstrap.registerVanilla(); } + static JsonObject rule(String type) { + JsonObject r = new JsonObject(); + r.addProperty("type", "orespawn:" + type); r.addProperty("algorithm_revision", 1); + r.addProperty("salt", 71); r.addProperty("chance", 1); r.addProperty("spacing_chunks", 16); + r.addProperty("radius_min", 18); r.addProperty("radius_max", 28); + r.addProperty("min_y", 32); r.addProperty("max_y", 32); r.addProperty("height", 40); + JsonObject m = new JsonObject(); + String[] roles = {"syenite", "nepheline_syenite", "carbonatite", "granite", "skarn", "greisen", + "serpentinite", "pipe", "vein_quartz", "ferricrete", "lateritic_clay", "saprolitic_rock"}; + for (int i = 0; i < roles.length; i++) { + String[] variants = {"granite", "polished_granite", "diorite", + "polished_diorite", "andesite", "polished_andesite"}; + JsonObject material = new JsonObject(); + material.addProperty("block", "minecraft:" + variants[i % variants.length]); + material.addProperty("family", "igneous_intrusive"); + m.add(roles[i], material); + } + r.add("materials", m); return r; + } + static GeologyColumn base(int x, int z) { + return new GeologyColumn() { + public ResourceLocation dimension() { return new ResourceLocation("minecraft:overworld"); } + public ResourceLocation biome() { return new ResourceLocation("minecraft:jungle"); } + public ResourceLocation geome() { return new ResourceLocation("orespawn:stable_craton"); } + public int blockX() { return x; } public int blockZ() { return z; } public int surfaceY() { return 100; } + public BlockState rockAt(int y) { return Blocks.STONE.getDefaultState(); } + public Optional familyAt(int y) { return Optional.of(GeologyFamily.IGNEOUS_INTRUSIVE); } + }; + } + @Test void deterministicAcrossNegativeRegionsAndReverseColumnOrder() { + BuiltinRockFormation f = new BuiltinRockFormation("alkaline_complex", rule("alkaline_complex")); + List forward = new ArrayList<>(), reverse = new ArrayList<>(); + for (int x = -512; x < 512; x += 8) for (int z = -256; z < 256; z += 8) + forward.add(sample(f, x, z)); + for (int x = 504; x >= -512; x -= 8) for (int z = 248; z >= -256; z -= 8) + reverse.add(sample(f, x, z)); + Collections.reverse(reverse); assertEquals(forward, reverse); + assertTrue(forward.stream().anyMatch(s -> !s.equals("none"))); + } + private static String sample(BuiltinRockFormation f, int x, int z) { + RockFormationColumn column = f.prepare(new RockFormationContext(719, base(x,z), 1, 1, () -> 100)); + if (column == null) return "none"; + StringBuilder s = new StringBuilder(); + for (int y = 4; y < 100; y++) { + FormationMaterial m = column.at(y); + if (m != null) { assertTrue(y >= 5 && y <= 92); s.append(y).append(':').append(m.state()).append(';'); } + } + return s.length() == 0 ? "none" : s.toString(); + } + @Test void unknownRevisionMissingOutputsAndOversizedBodiesFailClosed() { + JsonObject r = rule("barren_pipe"); r.addProperty("algorithm_revision", 2); + assertThrows(IllegalArgumentException.class, () -> new BuiltinRockFormation("barren_pipe", r)); + r.addProperty("algorithm_revision", 1); r.getAsJsonObject("materials").remove("pipe"); + assertThrows(IllegalArgumentException.class, () -> new BuiltinRockFormation("barren_pipe", r)); + r.getAsJsonObject("materials").add("pipe", r.getAsJsonObject("materials").get("granite")); + r.addProperty("radius_max", 64); + assertThrows(IllegalArgumentException.class, () -> new BuiltinRockFormation("barren_pipe", r)); + } + @Test void providerBuilderCopiesDefinitionsAndEnablesSchemaSixOnlyWhenNeeded() { + JsonObject r = rule("quartz_vein"); + WorldgenProvider provider = WorldgenProvider.builder("test", 1).rockFormation(new ResourceLocation("test:veins"), + new ResourceLocation("orespawn:quartz_vein"), r).build(); + r.addProperty("algorithm_revision", 99); + assertEquals(6, provider.toJson().get("schema_version").getAsInt()); + assertEquals(1, provider.toJson().getAsJsonObject("rock_formations").getAsJsonObject("test:veins") + .get("algorithm_revision").getAsInt()); + } + @Test void oldProfilesAndUnprofiledUpgradesDoNotInheritNewFormations() { + JsonObject defaults = new JsonObject(); + JsonObject forms = new JsonObject(); forms.add("test:veins", rule("quartz_vein")); + defaults.add("rock_formations", forms); + WorldGeologyProfile fresh = WorldGeologyProfile.fromGlobalConfig(defaults, + zone.moddev.mc.orespawn.OreSpawnConfig.GeologyMode.GEOME, false); + assertTrue(fresh.toJson().has("rock_formations")); + for (int schema : new int[]{1,2,3,6,7}) { + JsonObject old = new JsonObject(); old.addProperty("schema_version", schema); + assertFalse(WorldGeologyProfile.fromJson(old,fresh).toJson().has("rock_formations")); + } + assertFalse(WorldGeologyProfileManager.initializeNewWorldPolicies(fresh,true).toJson().has("rock_formations")); + assertEquals(forms, WorldGeologyProfile.fromJson(fresh.toJson(),fresh).toJson().get("rock_formations")); + } + @Test void missingFormationExtensionsRemainDormantWithoutLosingTheirSettings() { + JsonObject profile = new JsonObject(), formations = new JsonObject(); + JsonObject definition = rule("barren_pipe"); + definition.addProperty("type", "not_installed:pipe"); + formations.add("not_installed:pipe", definition); + profile.add("rock_formations", formations); + JsonObject before = zone.moddev.mc.orespawn.util.JsonCopies.copy(profile); + try { + assertDoesNotThrow(() -> NaturalFormations.install(profile)); + assertFalse(NaturalFormations.hasConfiguredFormations()); + assertEquals(before, profile); + } finally { NaturalFormations.install(new JsonObject()); } + } + @Test void weatheringNeedsWarmWetClimateAndANaturalGraniteParent() { + JsonObject definition = rule("weathering_profile"); + BuiltinRockFormation formation = new BuiltinRockFormation("weathering_profile", definition); + int[] site = null; + for (int x = -256; x < 256 && site == null; x += 4) for (int z = -256; z < 256; z += 4) { + RockFormationColumn column = weatherColumn(formation, x, z, 1, 1, Blocks.GRANITE.getDefaultState()); + if (column != null && column.at(95) != null) { site = new int[]{x,z}; break; } + } + assertNotNull(site); + RockFormationColumn wet = weatherColumn(formation, site[0], site[1], 1, 1, Blocks.GRANITE.getDefaultState()); + assertNotNull(wet.at(85)); assertNotNull(wet.at(91)); assertNotNull(wet.at(95)); + assertNotEquals(wet.at(85).state(), wet.at(91).state()); + assertNotEquals(wet.at(91).state(), wet.at(95).state()); + assertNull(wet.at(84)); assertNull(wet.at(98)); + for (BlockState unsuitable : new BlockState[]{Blocks.STONE.getDefaultState(), + Blocks.POLISHED_GRANITE.getDefaultState(), Blocks.INFESTED_STONE.getDefaultState(), Blocks.CLAY.getDefaultState()}) { + RockFormationColumn column = weatherColumn(formation, site[0], site[1], 1, 1, unsuitable); + assertNull(column.at(95)); + } + assertNull(weatherColumn(formation, site[0], site[1], .5F, 1, Blocks.GRANITE.getDefaultState()).at(95)); + assertNull(weatherColumn(formation, site[0], site[1], 1, .2F, Blocks.GRANITE.getDefaultState()).at(95)); + } + static RockFormationColumn weatherColumn(BuiltinRockFormation formation, int x, int z, + float temperature, float rain, BlockState parent) { + GeologyColumn original = base(x,z); + GeologyColumn column = new GeologyColumn() { + public ResourceLocation dimension(){return original.dimension();} + public ResourceLocation biome(){return original.biome();} + public ResourceLocation geome(){return original.geome();} + public int blockX(){return x;} public int blockZ(){return z;} public int surfaceY(){return 100;} + public BlockState rockAt(int y){return parent;} + public Optional familyAt(int y){return Optional.empty();} + }; + return formation.prepare(new RockFormationContext(713,column,temperature,rain,()->100)); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/OreAirRegionBoundaryTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/OreAirRegionBoundaryTest.java new file mode 100644 index 00000000..79b3da69 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/OreAirRegionBoundaryTest.java @@ -0,0 +1,174 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertSame; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import net.minecraft.block.Blocks; +import net.minecraft.block.BlockState; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IWorld; +import net.minecraft.world.chunk.ChunkPrimer; +import net.minecraft.world.gen.WorldGenRegion; +import zone.moddev.mc.orespawn.test.Forge28TestBootstrap; +import zone.moddev.mc.orespawn.test.TestObjects; + +class OreAirRegionBoundaryTest { + + @BeforeAll + static void bootstrap() { + Forge28TestBootstrap.registerVanilla(); + } + + @ParameterizedTest + @CsvSource({ + "3, -22, 47, 24", "3, -22, 0, 24", + "3, -22, 24, 47", "3, -22, 24, 0", + "-3, -3, 47, 24", "-3, -3, 0, 24", + "-3, -3, 24, 47", "-3, -3, 24, 0" + }) + void exposureChecksDoNotReadBeyondAnyRegionEdge(int minChunkX, int minChunkZ, + int offsetX, int offsetZ) throws Exception { + WorldGenRegion region = region(minChunkX, minChunkZ); + Object context = context(region); + int x = (minChunkX << 4) + offsetX; + int z = (minChunkZ << 4) + offsetZ; + int[][] neighbours = {{x + 1, 64, z}, {x - 1, 64, z}, + {x, 65, z}, {x, 63, z}, {x, 64, z + 1}, {x, 64, z - 1}}; + for (int[] position : neighbours) { + if (region.chunkExists(position[0] >> 4, position[2] >> 4)) { + region.getChunk(position[0] >> 4, position[2] >> 4).setBlockState( + new BlockPos(position[0], position[1], position[2]), + Blocks.STONE.getDefaultState(), false); + } + } + + // An unavailable neighbour is not air and must never request another chunk. + assertFalse(invoke(context, "isAdjacentToAir", x, 64, z)); + + int inwardX = x + (offsetX == 0 ? 1 : offsetX == 47 ? -1 : 0); + int inwardZ = z + (offsetZ == 0 ? 1 : offsetZ == 47 ? -1 : 0); + region.getChunk(inwardX >> 4, inwardZ >> 4).setBlockState( + new BlockPos(inwardX, 64, inwardZ), Blocks.AIR.getDefaultState(), false); + assertTrue(invoke(context, "isAdjacentToAir", x, 64, z), + "Available air must still trigger the exposure rule at a region edge"); + } + + @Test + void verticalLimitsAndAvailableAirKeepTheirExistingMeaning() throws Exception { + Object context = context(region(-1, -1)); + assertFalse(invoke(context, "isAir", 0, -1, 0)); + assertFalse(invoke(context, "isAir", 0, 256, 0)); + assertTrue(invoke(context, "isAir", 0, 0, 0)); + assertTrue(invoke(context, "isAir", 0, 255, 0)); + } + + @Test + void nativeCurrentChunkReadsUseTheHeldChunkIncludingNegativeCoordinates() throws Exception { + WorldGenRegion region = region(-3, -3); + Object context = context(region); + ChunkPrimer held = new ChunkPrimer(new net.minecraft.util.math.ChunkPos(-2, -2), net.minecraft.world.chunk.UpgradeData.EMPTY); + BlockPos position = new BlockPos(-17, 64, -17); + held.setBlockState(position, Blocks.GOLD_ORE.getDefaultState(), false); + set(context, context.getClass(), "chunk", held); + set(context, context.getClass(), "chunkX", -2); + set(context, context.getClass(), "chunkZ", -2); + set(context, context.getClass(), "nativeChunkReads", true); + assertSame(Blocks.GOLD_ORE.getDefaultState(), stateAt(context, position)); + + BlockPos neighbour = new BlockPos(-16, 64, -17); + region.getChunk(-1, -2).setBlockState(neighbour, Blocks.IRON_ORE.getDefaultState(), false); + assertSame(Blocks.IRON_ORE.getDefaultState(), stateAt(context, neighbour)); + } + + @Test + void customWorldReadViewsAreNotBypassed() throws Exception { + Object context = context(region(0, 0)); + BlockPos position = new BlockPos(1, 64, 1); + IWorld view = (IWorld) java.lang.reflect.Proxy.newProxyInstance(IWorld.class.getClassLoader(), + new Class[] {IWorld.class}, (proxy, method, arguments) -> { + if (method.getName().equals("getBlockState") && position.equals(arguments[0])) + return Blocks.GOLD_ORE.getDefaultState(); + throw new AssertionError("Unexpected world read: " + method); + }); + set(context, context.getClass(), "world", view); + set(context, context.getClass(), "chunk", new ChunkPrimer(new net.minecraft.util.math.ChunkPos(0, 0), net.minecraft.world.chunk.UpgradeData.EMPTY)); + assertSame(Blocks.GOLD_ORE.getDefaultState(), stateAt(context, position)); + } + + @Test + void chunkOnlyRetrogenReadsStillUseTheChunk() throws Exception { + Object context = context(region(0, 0)); + ChunkPrimer held = new ChunkPrimer(new net.minecraft.util.math.ChunkPos(0, 0), net.minecraft.world.chunk.UpgradeData.EMPTY); + BlockPos position = new BlockPos(1, 64, 1); + held.setBlockState(position, Blocks.IRON_ORE.getDefaultState(), false); + set(context, context.getClass(), "world", null); + set(context, context.getClass(), "chunk", held); + assertSame(Blocks.IRON_ORE.getDefaultState(), stateAt(context, position)); + } + + @Test + void nativeFluidReadViewDoesNotChangeTheBackingRegion() throws Exception { + WorldGenRegion world = region(-3, -3); + BlockPos position = new BlockPos(-17, 40, -17); + world.getChunk(-2, -2).setBlockState(position, Blocks.LAVA.getDefaultState(), false); + NativeAquiferView view = new NativeAquiferView(world, Blocks.WATER.getDefaultState(), Blocks.LAVA.getDefaultState()); + assertSame(Blocks.WATER.getDefaultState(), view.getBlockState(position)); + assertSame(Blocks.WATER.getDefaultState().getFluidState(), view.getFluidState(position)); + assertSame(Blocks.LAVA.getDefaultState(), world.getBlockState(position)); + assertSame(Blocks.AIR.getDefaultState().getFluidState(), view.getFluidState(position.up())); + } + + private static BlockState stateAt(Object context, BlockPos position) throws Exception { + Method method = context.getClass().getDeclaredMethod("stateAt", BlockPos.class); + method.setAccessible(true); + return (BlockState) method.invoke(context, position); + } + + private static Object context(WorldGenRegion region) throws Exception { + Class type = Class.forName(OreSpawnOreGeneration.class.getName() + "$PatternContext"); + Constructor constructor = type.getDeclaredConstructor(BlockPos.MutableBlockPos.class); + constructor.setAccessible(true); + Object context = constructor.newInstance(new BlockPos.MutableBlockPos()); + set(context, type, "world", region); + return context; + } + + private static boolean invoke(Object context, String name, int x, int y, int z) throws Exception { + Method method = context.getClass().getDeclaredMethod(name, int.class, int.class, int.class); + method.setAccessible(true); + return (boolean) method.invoke(context, x, y, z); + } + + private static WorldGenRegion region(int minChunkX, int minChunkZ) throws Exception { + // Exercise Minecraft's actual bounds and block reads without starting a server. + // Its constructor requires a live World; these reads need only this chunk array. + WorldGenRegion region = TestObjects.allocate(WorldGenRegion.class); + ChunkPrimer[] chunks = new ChunkPrimer[9]; + for (int z = 0; z < 3; z++) { + for (int x = 0; x < 3; x++) { + chunks[x + z * 3] = new ChunkPrimer(new net.minecraft.util.math.ChunkPos(minChunkX + x, minChunkZ + z), net.minecraft.world.chunk.UpgradeData.EMPTY); + } + } + set(region, WorldGenRegion.class, "chunkPrimers", java.util.Arrays.asList(chunks)); + set(region, WorldGenRegion.class, "field_217380_e", 3); + set(region, WorldGenRegion.class, "mainChunkX", minChunkX + 1); + set(region, WorldGenRegion.class, "mainChunkZ", minChunkZ + 1); + return region; + } + + private static void set(Object target, Class type, String name, Object value) throws Exception { + Field field = type.getDeclaredField(name); + field.setAccessible(true); + field.set(target, value); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/OreRetrogenManagerTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/OreRetrogenManagerTest.java new file mode 100644 index 00000000..bf309e04 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/OreRetrogenManagerTest.java @@ -0,0 +1,327 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.*; +import static zone.moddev.mc.orespawn.test.TestObjects.allocate; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.World; +import net.minecraft.world.dimension.OverworldDimension; +import net.minecraft.world.dimension.DimensionType; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.event.world.ChunkDataEvent; +import net.minecraftforge.event.TickEvent; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import zone.moddev.mc.orespawn.test.Forge28TestBootstrap; + +class OreRetrogenManagerTest { + private ServerWorld level; + private Chunk chunk; + + @BeforeAll + static void bootstrap() { Forge28TestBootstrap.registerVanilla(); } + + @BeforeEach + void start() throws Exception { + OreRetrogenManager.clear(); + level = world(0); + chunk = chunk(level, -20, 21); + settings(true, false, false, 777); + } + + @AfterEach + void stop() { OreRetrogenManager.clear(); } + + @Test + void nativeLoadMarkersSurviveRepeatedSavesAndRestartsEvenWhenDisabled() throws Exception { + CompoundNBT disk = marker(777); + for (int restart = 0; restart < 5; restart++) { + OreRetrogenManager.clear(); + settings(restart % 2 == 0, false, false, 777); + level = world(0); chunk = chunk(level, -20, 21); + load(chunk, disk); + assertEquals(0, OreRetrogenManager.queuedCount()); + for (int save = 0; save < 3; save++) { + disk = save(chunk); + assertEquals(777, revision(disk)); + } + } + } + + @Test + void completionSurvivesRepeatedSavesAndProcessRestarts() throws Exception { + CompoundNBT disk = marker(777); + for (int restart = 0; restart < 5; restart++) { + OreRetrogenManager.clear(); + settings(true, false, false, 777); + load(chunk, disk); + assertEquals(0, OreRetrogenManager.queuedCount()); + for (int save = 0; save < 3; save++) { + disk = save(chunk); + assertEquals(777, revision(disk), "A normal save must retain completed work"); + } + } + } + + @Test + void disabledRetrogenStillPreservesTheSavedMarker() throws Exception { + settings(false, false, false, 888); + load(chunk, marker(777)); + assertEquals(777, revision(save(chunk))); + assertEquals(0, OreRetrogenManager.queuedCount()); + } + + @Test + void disableSaveRestartAndReenableDoesNotRepeatCompletedWork() throws Exception { + settings(false, false, false, 777); + load(chunk, marker(777)); + CompoundNBT disk = save(chunk); + OreRetrogenManager.clear(); + settings(true, false, false, 777); + load(chunk, disk); + assertEquals(0, OreRetrogenManager.queuedCount()); + } + + @Test + void changingSettingsDoesNotStampAnUnprocessedRevision() throws Exception { + load(chunk, marker(777)); + settings(true, false, false, 888); + assertEquals(777, revision(save(chunk))); + } + + @Test + void anExplicitNewRevisionQueuesWithoutPretendingItHasFinished() throws Exception { + settings(true, false, false, 888); + load(chunk, marker(777)); + assertEquals(1, OreRetrogenManager.queuedCount()); + assertEquals(777, revision(save(chunk))); + } + + @Test + void forceStillQueuesMarkedChunksButDoesNotEraseTheirMarker() throws Exception { + settings(true, true, false, 777); + load(chunk, marker(777)); + load(chunk, marker(777)); + assertEquals(1, OreRetrogenManager.queuedCount()); + assertEquals(777, revision(save(chunk))); + } + + @Test + void anAbsentMarkerIsNotCompletionAtRevisionZero() throws Exception { + settings(true, false, false, 0); + load(chunk, new CompoundNBT()); + assertEquals(1, OreRetrogenManager.queuedCount()); + assertFalse(save(chunk).contains("OreSpawn")); + } + + @Test + void aStringMarkerIsNotCompletionAtRevisionZero() throws Exception { + settings(true, false, false, 0); + CompoundNBT disk = new CompoundNBT(); + CompoundNBT root = new CompoundNBT(); + root.putString("generation_revision", "0"); + disk.put("OreSpawn", root); + load(chunk, disk); + assertEquals(1, OreRetrogenManager.queuedCount()); + } + + @Test + void negativeMarkersAreNotTreatedAsCompletedWork() { + load(chunk, marker(-1)); + assertEquals(1, OreRetrogenManager.queuedCount()); + assertFalse(save(chunk).contains("OreSpawn")); + } + + @Test + void negativeCoordinatesDoNotShareCompletion() throws Exception { + load(chunk, marker(777)); + Chunk other = chunk(level, 21, -20); + load(other, new CompoundNBT()); + assertEquals(1, OreRetrogenManager.queuedCount()); + assertFalse(save(other).contains("OreSpawn")); + assertEquals(777, revision(save(chunk))); + } + + @Test + void differentDimensionsDoNotShareCompletion() throws Exception { + load(chunk, marker(777)); + Chunk other = chunk(world(-1), -20, 21); + load(other, new CompoundNBT()); + assertFalse(save(other).contains("OreSpawn")); + assertEquals(777, revision(save(chunk))); + } + + @Test + void separateWorldsWithTheSameDimensionDoNotShareCompletion() throws Exception { + load(chunk, marker(777)); + Chunk other = chunk(world(0), -20, 21); + assertFalse(save(other).contains("OreSpawn")); + assertEquals(777, revision(save(chunk))); + } + + @Test + void reloadingTheSameChunkInOneSessionKeepsItsMarker() throws Exception { + load(chunk, marker(777)); + CompoundNBT disk = save(chunk); + Chunk reloaded = chunk(level, -20, 21); + load(reloaded, disk); + assertEquals(0, OreRetrogenManager.queuedCount()); + assertEquals(777, revision(save(reloaded))); + } + + @Test + void shutdownClearsAllRememberedCompletion() { + load(chunk, marker(777)); + OreRetrogenManager.clear(); + assertFalse(save(chunk).contains("OreSpawn")); + assertEquals(0, OreRetrogenManager.queuedCount()); + } + + @Test + void bedrockOnlyRetrogenAlsoRetainsCompletion() throws Exception { + settings(false, false, true, 777); + load(chunk, marker(777)); + assertEquals(0, OreRetrogenManager.queuedCount()); + assertEquals(777, revision(save(chunk))); + } + + @Test + void turningOffQueuedWorkDoesNotMarkItComplete() throws Exception { + load(chunk, new CompoundNBT()); + settings(false, false, false, 888); + OreRetrogenManager.onServerTick(new TickEvent.ServerTickEvent(TickEvent.Phase.END)); + assertEquals(0, OreRetrogenManager.queuedCount()); + assertFalse(save(chunk).contains("OreSpawn")); + } + + @Test + void freshlyGeneratedChunksKeepTheRevisionTheyActuallyCompleted() throws Exception { + markGenerated(level, chunk.getPos()); + settings(true, false, false, 888); + assertEquals(777, revision(save(chunk))); + } + + @Test + void freshGenerationDoesNotMarkAnotherWorldAtTheSameCoordinates() throws Exception { + markGenerated(level, chunk.getPos()); + assertFalse(save(chunk(world(0), -20, 21)).contains("OreSpawn")); + assertEquals(777, revision(save(chunk))); + } + + @Test + void anUnmarkedReloadDoesNotInheritOldSessionBookkeeping() { + load(chunk, marker(777)); + load(chunk, new CompoundNBT()); + assertEquals(1, OreRetrogenManager.queuedCount()); + assertFalse(save(chunk).contains("OreSpawn")); + } + + @Test + void savingKeepsOtherFieldsAlreadyInTheEventData() { + load(chunk, marker(777)); + CompoundNBT disk = marker(1); + disk.getCompound("OreSpawn").putString("note", "keep this"); + OreRetrogenManager.onChunkSave(new ChunkDataEvent.Save(chunk, disk)); + assertEquals(777, revision(disk)); + assertEquals("keep this", disk.getCompound("OreSpawn").getString("note")); + } + + @Test + void loadingDoesNotMutateTheSavedNbt() { + CompoundNBT disk = marker(777); + CompoundNBT original = disk.copy(); + load(chunk, disk); + assertEquals(original, disk); + } + + @Test + void theLargestRevisionRoundTripsWithoutOverflow() throws Exception { + settings(true, false, false, Integer.MAX_VALUE); + load(chunk, marker(Integer.MAX_VALUE)); + assertEquals(0, OreRetrogenManager.queuedCount()); + assertEquals(Integer.MAX_VALUE, revision(save(chunk))); + } + + private static void load(Chunk chunk, CompoundNBT data) { + OreRetrogenManager.onChunkLoad(new ChunkDataEvent.Load(chunk, data.contains("Level", 10) ? data.getCompound("Level") : data, + net.minecraft.world.chunk.ChunkStatus.Type.LEVELCHUNK)); + } + + @Test void protoChunkDataDoesNotRestoreOrQueueAFullChunkMarker() { + OreRetrogenManager.onChunkLoad(new ChunkDataEvent.Load(chunk, marker(777), + net.minecraft.world.chunk.ChunkStatus.Type.PROTOCHUNK)); + assertEquals(0, OreRetrogenManager.queuedCount()); + assertFalse(save(chunk).contains("OreSpawn")); + } + + private static CompoundNBT save(Chunk chunk) { + CompoundNBT data = new CompoundNBT(); + OreRetrogenManager.onChunkSave(new ChunkDataEvent.Save(chunk, data)); + return data; + } + + private static CompoundNBT marker(int revision) { + CompoundNBT data = new CompoundNBT(); + CompoundNBT root = new CompoundNBT(); + root.putInt("generation_revision", revision); + data.put("OreSpawn", root); + return data; + } + + private static int revision(CompoundNBT data) { + assertTrue(data.getCompound("OreSpawn").contains("generation_revision", 3)); + return data.getCompound("OreSpawn").getInt("generation_revision"); + } + + private static void settings(boolean ore, boolean force, boolean bedrock, int revision) throws Exception { + Class type = Class.forName(OreRetrogenManager.class.getName() + "$Settings"); + Constructor constructor = type.getDeclaredConstructor(boolean.class, boolean.class, boolean.class, int.class, int.class); + constructor.setAccessible(true); + Field field = OreRetrogenManager.class.getDeclaredField("settings"); + field.setAccessible(true); + field.set(null, constructor.newInstance(ore, force, bedrock, 1, revision)); + } + + // These handlers only need chunk identity; no live server or save is opened. + private static ServerWorld world(int dimension) throws Exception { + ServerWorld level = allocate(ServerWorld.class); + set(World.class, level, "dimension", new OverworldDimension(level, + dimension == -1 ? DimensionType.THE_NETHER : DimensionType.OVERWORLD)); + return level; + } + + private static Chunk chunk(ServerWorld level, int x, int z) { + try { + Chunk chunk = allocate(Chunk.class); + set(Chunk.class, chunk, "world", level); + set(Chunk.class, chunk, "pos", new ChunkPos(x, z)); + return chunk; + } catch (Exception ex) { throw new AssertionError(ex); } + } + + private static void markGenerated(ServerWorld world, ChunkPos position) throws Exception { + try { + java.lang.reflect.Method method = OreRetrogenManager.class.getDeclaredMethod( + "markGenerated", ServerWorld.class, ChunkPos.class); + method.setAccessible(true); + method.invoke(null, world, position); + } catch (NoSuchMethodException oldSignature) { + java.lang.reflect.Method method = OreRetrogenManager.class.getDeclaredMethod( + "markGenerated", net.minecraft.util.ResourceLocation.class, ChunkPos.class); + method.setAccessible(true); + method.invoke(null, WorldIds.dimension(world), position); + } + } + + private static void set(Class owner, Object target, String name, Object value) throws Exception { + Field field = owner.getDeclaredField(name); + field.setAccessible(true); + field.set(target, value); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/OreSourcePoliciesTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/OreSourcePoliciesTest.java index 44d62954..82671fe8 100644 --- a/src/test/java/zone/moddev/mc/orespawn/worldgen/OreSourcePoliciesTest.java +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/OreSourcePoliciesTest.java @@ -9,6 +9,7 @@ import org.junit.jupiter.api.Test; import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import net.minecraft.util.ResourceLocation; @@ -16,6 +17,47 @@ class OreSourcePoliciesTest { private static final ResourceLocation SULFUR = id("orespawn:sulfur"); private static final ResourceLocation OVERWORLD = id("minecraft:overworld"); + @Test + void importedBuiltInPatternsShareTheStandardChannelButExplicitChannelsStaySeparate() { + JsonObject rule = new JsonParser().parse("{\"pattern\":{\"type\":\"orespawn:precision\"}}").getAsJsonObject(); + assertEquals(OreSourcePolicies.STANDARD, OreSourcePolicies.placementChannel(rule)); + rule.addProperty("placement_channel", "orespawn:precision"); + assertEquals(id("orespawn:precision"), OreSourcePolicies.placementChannel(rule)); + rule.remove("placement_channel"); + rule.addProperty("pattern", "example:precision"); + assertEquals(id("example:precision"), OreSourcePolicies.placementChannel(rule)); + } + + @Test + void retainedChannelMustMatchItsOwnPatternWithoutChangingTheProfile() { + JsonObject profile = new JsonParser().parse("{\"ores\":{\"example:ore\":{\"dimensions\":{" + + "\"minecraft:overworld\":{\"pattern\":{\"type\":\"orespawn:precision\"}}}}}}").getAsJsonObject(); + String before = profile.toString(); + assertTrue(OreSourcePolicies.legacyChannelSelection(profile, id("example:ore"), OVERWORLD, + id("orespawn:precision"), OreSourcePolicies.STANDARD)); + assertFalse(OreSourcePolicies.legacyChannelSelection(profile, id("example:ore"), OVERWORLD, + id("orespawn:clusters"), OreSourcePolicies.STANDARD)); + assertEquals(before, profile.toString()); + profile.getAsJsonObject("ores").getAsJsonObject("example:ore").getAsJsonObject("dimensions") + .getAsJsonObject("minecraft:overworld").addProperty("placement_channel", "orespawn:standard"); + assertFalse(OreSourcePolicies.legacyChannelSelection(profile, id("example:ore"), OVERWORLD, + id("orespawn:precision"), OreSourcePolicies.STANDARD)); + } + + @Test + void baseElectricIsRecognisedWithoutChangingAnExistingWorldsPolicy() { + OreSourcePolicies.Group shared = group(); + shared.add(candidate("mineralogy:sulfur", "mineralogy", "mineralogy:sulfur_ore", + "forge:ores/sulfur", true, true, false, false)); + shared.add(candidate("baseelectric:sulfur", "baseelectric", "baseelectric:sulfur_ore", + "forge:ores/sulfur", true, true, false, false)); + JsonObject fresh = OreSourcePolicies.createPolicy(shared, false); + assertEquals("consolidated", fresh.get("mode").getAsString()); + assertEquals("mineralogy:sulfur", fresh.getAsJsonObject("placement_sources") + .get("orespawn:standard").getAsString()); + assertSeparate(OreSourcePolicies.createPolicy(shared, true)); + } + @Test void newWorldBalancesOnlyTwoLoadedOrdinaryOwnersWithAnExactSharedTag() { OreSourcePolicies.Group one = group(); diff --git a/src/test/resources/provider-merge/README.md b/src/test/resources/provider-merge/README.md new file mode 100644 index 00000000..c9e71ce7 --- /dev/null +++ b/src/test/resources/provider-merge/README.md @@ -0,0 +1,16 @@ +# Retained Provider Merge Fixtures + +These are structured JSON extracts, not generated worlds. They retain the ten +affected Base Metals rules and their original placement values. + +- `retained-basemetals-ores.json`: selected rules and the Base Metals manifest + from the released base* 1.10 fixture retained by the 1.12 upgrade tests. + Complete source-profile SHA-256: + `AF4A6124287D5B40F81BCC05A3B013B5C94F903A221F3C7B48FB6B0842E72197`. +- `current-basemetals-ores.json`: the corresponding rules from Base Metals' + 26.1.2 provider declaration. Complete source-declaration SHA-256: + `3963718AA0464BDB240DA5521C65EA1479AC46D34B0FF8EAD2675013C93B05D0`. + +The regression tests call the real provider merge, temporarily installing +only this provider and restoring its prior state afterwards. No Base Metals +classes, jars, or live world folders are needed to run them. diff --git a/src/test/resources/provider-merge/current-basemetals-ores.json b/src/test/resources/provider-merge/current-basemetals-ores.json new file mode 100644 index 00000000..227c590f --- /dev/null +++ b/src/test/resources/provider-merge/current-basemetals-ores.json @@ -0,0 +1,325 @@ +{ + "schema_version": 3, + "provider_modid": "basemetals", + "provider_revision": 1, + "ores": { + "basemetals:ore/coldiron": { + "block": "basemetals:coldiron_ore", + "enabled": true, + "source_mod": "basemetals", + "retrogen": false, + "dimensions": { + "minecraft:the_nether": { + "enabled": true, + "min_y": 0, + "max_y": 127, + "frequency": 5, + "min_quantity": 4, + "max_quantity": 11, + "pattern": "vein", + "height_distribution": "uniform", + "discard_chance_on_air_exposure": 0, + "spread": 8, + "vertical_spread": 4, + "node_size": 4, + "length": 16, + "host_blocks": [ + "minecraft:netherrack" + ], + "host_tags": [ + "forge:netherrack" + ] + } + } + }, + "basemetals:ore/adamantine": { + "block": "basemetals:adamantine_ore", + "enabled": true, + "source_mod": "basemetals", + "retrogen": false, + "dimensions": { + "minecraft:the_nether": { + "enabled": true, + "min_y": 0, + "max_y": 127, + "frequency": 2, + "min_quantity": 4, + "max_quantity": 11, + "pattern": "vein", + "height_distribution": "uniform", + "discard_chance_on_air_exposure": 0, + "spread": 8, + "vertical_spread": 4, + "node_size": 4, + "length": 16, + "host_blocks": [ + "minecraft:netherrack" + ], + "host_tags": [ + "forge:netherrack" + ] + } + } + }, + "basemetals:ore/starsteel": { + "block": "basemetals:starsteel_ore", + "enabled": true, + "source_mod": "basemetals", + "retrogen": false, + "dimensions": { + "minecraft:the_end": { + "enabled": true, + "min_y": 0, + "max_y": 254, + "frequency": 5, + "min_quantity": 4, + "max_quantity": 11, + "pattern": "vein", + "height_distribution": "uniform", + "discard_chance_on_air_exposure": 0, + "spread": 8, + "vertical_spread": 4, + "node_size": 4, + "length": 16, + "host_blocks": [ + "minecraft:end_stone" + ], + "host_tags": [ + "forge:end_stones" + ] + } + } + }, + "basemetals:ore/tin": { + "block": "basemetals:tin_ore", + "enabled": true, + "source_mod": "basemetals", + "retrogen": false, + "dimension_selectors": { + "orespawn:all_except_nether_end": { + "enabled": true, + "min_y": -64, + "max_y": 128, + "frequency": 10, + "min_quantity": 4, + "max_quantity": 11, + "pattern": "vein", + "height_distribution": "triangle", + "discard_chance_on_air_exposure": 0, + "spread": 8, + "vertical_spread": 4, + "node_size": 4, + "length": 16, + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [ + "minecraft:stone_ore_replaceables", + "minecraft:deepslate_ore_replaceables" + ] + } + } + }, + "basemetals:ore/lead": { + "block": "basemetals:lead_ore", + "enabled": true, + "source_mod": "basemetals", + "retrogen": false, + "dimension_selectors": { + "orespawn:all_except_nether_end": { + "enabled": true, + "min_y": -64, + "max_y": 64, + "frequency": 5, + "min_quantity": 4, + "max_quantity": 11, + "pattern": "vein", + "height_distribution": "triangle", + "discard_chance_on_air_exposure": 0, + "spread": 8, + "vertical_spread": 4, + "node_size": 4, + "length": 16, + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [ + "minecraft:stone_ore_replaceables", + "minecraft:deepslate_ore_replaceables" + ] + } + } + }, + "basemetals:ore/zinc": { + "block": "basemetals:zinc_ore", + "enabled": true, + "source_mod": "basemetals", + "retrogen": false, + "dimension_selectors": { + "orespawn:all_except_nether_end": { + "enabled": true, + "min_y": -64, + "max_y": 96, + "frequency": 5, + "min_quantity": 4, + "max_quantity": 11, + "pattern": "vein", + "height_distribution": "triangle", + "discard_chance_on_air_exposure": 0, + "spread": 8, + "vertical_spread": 4, + "node_size": 4, + "length": 16, + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [ + "minecraft:stone_ore_replaceables", + "minecraft:deepslate_ore_replaceables" + ] + } + } + }, + "basemetals:ore/silver": { + "block": "basemetals:silver_ore", + "enabled": true, + "source_mod": "basemetals", + "retrogen": false, + "dimension_selectors": { + "orespawn:all_except_nether_end": { + "enabled": true, + "min_y": -64, + "max_y": 32, + "frequency": 4, + "min_quantity": 4, + "max_quantity": 11, + "pattern": "vein", + "height_distribution": "bottom_triangle", + "discard_chance_on_air_exposure": 0, + "spread": 8, + "vertical_spread": 4, + "node_size": 4, + "length": 16, + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [ + "minecraft:stone_ore_replaceables", + "minecraft:deepslate_ore_replaceables" + ] + } + } + }, + "basemetals:ore/mercury": { + "block": "basemetals:mercury_ore", + "enabled": true, + "source_mod": "basemetals", + "retrogen": false, + "dimension_selectors": { + "orespawn:all_except_nether_end": { + "enabled": true, + "min_y": -64, + "max_y": 32, + "frequency": 3, + "min_quantity": 4, + "max_quantity": 11, + "pattern": "vein", + "height_distribution": "bottom_triangle", + "discard_chance_on_air_exposure": 0, + "spread": 8, + "vertical_spread": 4, + "node_size": 4, + "length": 16, + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [ + "minecraft:stone_ore_replaceables", + "minecraft:deepslate_ore_replaceables" + ] + } + } + }, + "basemetals:ore/nickel": { + "block": "basemetals:nickel_ore", + "enabled": true, + "source_mod": "basemetals", + "retrogen": false, + "dimension_selectors": { + "orespawn:all_except_nether_end": { + "enabled": true, + "min_y": -32, + "max_y": 96, + "frequency": 1, + "min_quantity": 4, + "max_quantity": 11, + "pattern": "vein", + "height_distribution": "triangle", + "discard_chance_on_air_exposure": 0, + "spread": 8, + "vertical_spread": 4, + "node_size": 4, + "length": 16, + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [ + "minecraft:stone_ore_replaceables", + "minecraft:deepslate_ore_replaceables" + ] + } + } + }, + "basemetals:ore/platinum": { + "block": "basemetals:platinum_ore", + "enabled": true, + "source_mod": "basemetals", + "retrogen": false, + "dimension_selectors": { + "orespawn:all_except_nether_end": { + "enabled": true, + "min_y": -64, + "max_y": 16, + "frequency": 0.125, + "min_quantity": 4, + "max_quantity": 11, + "pattern": "vein", + "height_distribution": "bottom_triangle", + "discard_chance_on_air_exposure": 0, + "spread": 8, + "vertical_spread": 4, + "node_size": 4, + "length": 16, + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [ + "minecraft:stone_ore_replaceables", + "minecraft:deepslate_ore_replaceables" + ] + } + } + } + } +} diff --git a/src/test/resources/provider-merge/retained-basemetals-ores.json b/src/test/resources/provider-merge/retained-basemetals-ores.json new file mode 100644 index 00000000..9c35adff --- /dev/null +++ b/src/test/resources/provider-merge/retained-basemetals-ores.json @@ -0,0 +1,551 @@ +{ + "schema_version": 7, + "ores": { + "basemetals:legacy/coldiron_ore": { + "block": "basemetals:coldiron_ore", + "dimension_selectors": {}, + "dimensions": { + "minecraft:the_nether": { + "biome_dictionary": [], + "biome_ids": [], + "discard_chance_on_air_exposure": 0, + "enabled": true, + "excluded_biome_dictionary": [], + "excluded_biome_ids": [], + "frequency": 5, + "geomes": {}, + "height_distribution": "uniform", + "host_blocks": [ + "minecraft:stone", + "minecraft:netherrack", + "minecraft:end_stone" + ], + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [], + "max_quantity": 11, + "max_y": 127, + "min_quantity": 4, + "min_y": 0, + "node_size": 4, + "pattern": "default", + "placement_channel": "orespawn:standard", + "spread": 8, + "vertical_spread": 4 + } + }, + "enabled": true, + "material": "orespawn:coldiron", + "native_generation": false, + "outputs": [ + { + "block": "basemetals:coldiron_ore", + "max_y": 2048, + "min_y": -2048, + "weight": 100 + } + ], + "retrogen": false, + "source_provider": "basemetals", + "suppress_vanilla": false + }, + "basemetals:legacy/adamantine_ore": { + "block": "basemetals:adamantine_ore", + "dimension_selectors": {}, + "dimensions": { + "minecraft:the_nether": { + "biome_dictionary": [], + "biome_ids": [], + "discard_chance_on_air_exposure": 0, + "enabled": true, + "excluded_biome_dictionary": [], + "excluded_biome_ids": [], + "frequency": 2, + "geomes": {}, + "height_distribution": "uniform", + "host_blocks": [ + "minecraft:stone", + "minecraft:netherrack", + "minecraft:end_stone" + ], + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [], + "max_quantity": 11, + "max_y": 127, + "min_quantity": 4, + "min_y": 0, + "node_size": 4, + "pattern": "default", + "placement_channel": "orespawn:standard", + "spread": 8, + "vertical_spread": 4 + } + }, + "enabled": true, + "material": "orespawn:adamantine", + "native_generation": false, + "outputs": [ + { + "block": "basemetals:adamantine_ore", + "max_y": 2048, + "min_y": -2048, + "weight": 100 + } + ], + "retrogen": false, + "source_provider": "basemetals", + "suppress_vanilla": false + }, + "basemetals:legacy/starsteel_ore": { + "block": "basemetals:starsteel_ore", + "dimension_selectors": {}, + "dimensions": { + "minecraft:the_end": { + "biome_dictionary": [], + "biome_ids": [], + "discard_chance_on_air_exposure": 0, + "enabled": true, + "excluded_biome_dictionary": [], + "excluded_biome_ids": [], + "frequency": 5, + "geomes": {}, + "height_distribution": "uniform", + "host_blocks": [ + "minecraft:stone", + "minecraft:netherrack", + "minecraft:end_stone" + ], + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [], + "max_quantity": 11, + "max_y": 254, + "min_quantity": 4, + "min_y": 0, + "node_size": 4, + "pattern": "default", + "placement_channel": "orespawn:standard", + "spread": 8, + "vertical_spread": 4 + } + }, + "enabled": true, + "material": "orespawn:starsteel", + "native_generation": false, + "outputs": [ + { + "block": "basemetals:starsteel_ore", + "max_y": 2048, + "min_y": -2048, + "weight": 100 + } + ], + "retrogen": false, + "source_provider": "basemetals", + "suppress_vanilla": false + }, + "basemetals:legacy/tin_ore": { + "block": "basemetals:tin_ore", + "dimension_selectors": { + "orespawn:all_except_nether_end": { + "biome_dictionary": [], + "biome_ids": [], + "discard_chance_on_air_exposure": 0, + "enabled": true, + "excluded_biome_dictionary": [], + "excluded_biome_ids": [], + "frequency": 10, + "geomes": {}, + "height_distribution": "uniform", + "host_blocks": [ + "minecraft:stone", + "minecraft:netherrack", + "minecraft:end_stone" + ], + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [], + "max_quantity": 11, + "max_y": 127, + "min_quantity": 4, + "min_y": 0, + "node_size": 4, + "pattern": "default", + "placement_channel": "orespawn:standard", + "spread": 8, + "vertical_spread": 4 + } + }, + "dimensions": {}, + "enabled": true, + "material": "orespawn:tin", + "native_generation": false, + "outputs": [ + { + "block": "basemetals:tin_ore", + "max_y": 2048, + "min_y": -2048, + "weight": 100 + } + ], + "retrogen": false, + "source_provider": "basemetals", + "suppress_vanilla": false + }, + "basemetals:legacy/lead_ore": { + "block": "basemetals:lead_ore", + "dimension_selectors": { + "orespawn:all_except_nether_end": { + "biome_dictionary": [], + "biome_ids": [], + "discard_chance_on_air_exposure": 0, + "enabled": true, + "excluded_biome_dictionary": [], + "excluded_biome_ids": [], + "frequency": 5, + "geomes": {}, + "height_distribution": "uniform", + "host_blocks": [ + "minecraft:stone", + "minecraft:netherrack", + "minecraft:end_stone" + ], + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [], + "max_quantity": 11, + "max_y": 63, + "min_quantity": 4, + "min_y": 0, + "node_size": 4, + "pattern": "default", + "placement_channel": "orespawn:standard", + "spread": 8, + "vertical_spread": 4 + } + }, + "dimensions": {}, + "enabled": true, + "material": "orespawn:lead", + "native_generation": false, + "outputs": [ + { + "block": "basemetals:lead_ore", + "max_y": 2048, + "min_y": -2048, + "weight": 100 + } + ], + "retrogen": false, + "source_provider": "basemetals", + "suppress_vanilla": false + }, + "basemetals:legacy/zinc_ore": { + "block": "basemetals:zinc_ore", + "dimension_selectors": { + "orespawn:all_except_nether_end": { + "biome_dictionary": [], + "biome_ids": [], + "discard_chance_on_air_exposure": 0, + "enabled": true, + "excluded_biome_dictionary": [], + "excluded_biome_ids": [], + "frequency": 5, + "geomes": {}, + "height_distribution": "uniform", + "host_blocks": [ + "minecraft:stone", + "minecraft:netherrack", + "minecraft:end_stone" + ], + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [], + "max_quantity": 11, + "max_y": 95, + "min_quantity": 4, + "min_y": 0, + "node_size": 4, + "pattern": "default", + "placement_channel": "orespawn:standard", + "spread": 8, + "vertical_spread": 4 + } + }, + "dimensions": {}, + "enabled": true, + "material": "orespawn:zinc", + "native_generation": false, + "outputs": [ + { + "block": "basemetals:zinc_ore", + "max_y": 2048, + "min_y": -2048, + "weight": 100 + } + ], + "retrogen": false, + "source_provider": "basemetals", + "suppress_vanilla": false + }, + "basemetals:legacy/silver_ore": { + "block": "basemetals:silver_ore", + "dimension_selectors": { + "orespawn:all_except_nether_end": { + "biome_dictionary": [], + "biome_ids": [], + "discard_chance_on_air_exposure": 0, + "enabled": true, + "excluded_biome_dictionary": [], + "excluded_biome_ids": [], + "frequency": 4, + "geomes": {}, + "height_distribution": "uniform", + "host_blocks": [ + "minecraft:stone", + "minecraft:netherrack", + "minecraft:end_stone" + ], + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [], + "max_quantity": 11, + "max_y": 31, + "min_quantity": 4, + "min_y": 0, + "node_size": 4, + "pattern": "default", + "placement_channel": "orespawn:standard", + "spread": 8, + "vertical_spread": 4 + } + }, + "dimensions": {}, + "enabled": true, + "material": "orespawn:silver", + "native_generation": false, + "outputs": [ + { + "block": "basemetals:silver_ore", + "max_y": 2048, + "min_y": -2048, + "weight": 100 + } + ], + "retrogen": false, + "source_provider": "basemetals", + "suppress_vanilla": false + }, + "basemetals:legacy/mercury_ore": { + "block": "basemetals:mercury_ore", + "dimension_selectors": { + "orespawn:all_except_nether_end": { + "biome_dictionary": [], + "biome_ids": [], + "discard_chance_on_air_exposure": 0, + "enabled": true, + "excluded_biome_dictionary": [], + "excluded_biome_ids": [], + "frequency": 3, + "geomes": {}, + "height_distribution": "uniform", + "host_blocks": [ + "minecraft:stone", + "minecraft:netherrack", + "minecraft:end_stone" + ], + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [], + "max_quantity": 11, + "max_y": 31, + "min_quantity": 4, + "min_y": 0, + "node_size": 4, + "pattern": "default", + "placement_channel": "orespawn:standard", + "spread": 8, + "vertical_spread": 4 + } + }, + "dimensions": {}, + "enabled": true, + "material": "orespawn:mercury", + "native_generation": false, + "outputs": [ + { + "block": "basemetals:mercury_ore", + "max_y": 2048, + "min_y": -2048, + "weight": 100 + } + ], + "retrogen": false, + "source_provider": "basemetals", + "suppress_vanilla": false + }, + "basemetals:legacy/nickel_ore": { + "block": "basemetals:nickel_ore", + "dimension_selectors": { + "orespawn:all_except_nether_end": { + "biome_dictionary": [], + "biome_ids": [], + "discard_chance_on_air_exposure": 0, + "enabled": true, + "excluded_biome_dictionary": [], + "excluded_biome_ids": [], + "frequency": 1, + "geomes": {}, + "height_distribution": "uniform", + "host_blocks": [ + "minecraft:stone", + "minecraft:netherrack", + "minecraft:end_stone" + ], + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [], + "max_quantity": 11, + "max_y": 95, + "min_quantity": 4, + "min_y": 32, + "node_size": 4, + "pattern": "default", + "placement_channel": "orespawn:standard", + "spread": 8, + "vertical_spread": 4 + } + }, + "dimensions": {}, + "enabled": true, + "material": "orespawn:nickel", + "native_generation": false, + "outputs": [ + { + "block": "basemetals:nickel_ore", + "max_y": 2048, + "min_y": -2048, + "weight": 100 + } + ], + "retrogen": false, + "source_provider": "basemetals", + "suppress_vanilla": false + }, + "basemetals:legacy/platinum_ore": { + "block": "basemetals:platinum_ore", + "dimension_selectors": { + "orespawn:all_except_nether_end": { + "biome_dictionary": [], + "biome_ids": [], + "discard_chance_on_air_exposure": 0, + "enabled": true, + "excluded_biome_dictionary": [], + "excluded_biome_ids": [], + "frequency": 0.125, + "geomes": {}, + "height_distribution": "uniform", + "host_blocks": [ + "minecraft:stone", + "minecraft:netherrack", + "minecraft:end_stone" + ], + "host_families": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ], + "host_tags": [], + "max_quantity": 11, + "max_y": 31, + "min_quantity": 4, + "min_y": 1, + "node_size": 4, + "pattern": "default", + "placement_channel": "orespawn:standard", + "spread": 8, + "vertical_spread": 4 + } + }, + "dimensions": {}, + "enabled": true, + "material": "orespawn:platinum", + "native_generation": false, + "outputs": [ + { + "block": "basemetals:platinum_ore", + "max_y": 2048, + "min_y": -2048, + "weight": 100 + } + ], + "retrogen": false, + "source_provider": "basemetals", + "suppress_vanilla": false + } + }, + "providers": { + "basemetals": { + "known_biome_palettes": [], + "known_biome_rules": [], + "known_dimension_materials": [], + "known_fluid_deposits": [], + "known_geomes": [], + "known_ores": [ + "basemetals:legacy/adamantine_ore", + "basemetals:legacy/coldiron_ore", + "basemetals:legacy/copper_ore", + "basemetals:legacy/lead_ore", + "basemetals:legacy/mercury_ore", + "basemetals:legacy/nickel_ore", + "basemetals:legacy/platinum_ore", + "basemetals:legacy/silver_ore", + "basemetals:legacy/starsteel_ore", + "basemetals:legacy/tin_ore", + "basemetals:legacy/zinc_ore" + ], + "known_rocks": [], + "known_templates": [], + "known_terrain_dimensions": [], + "provider_revision": 1 + } + } +}