diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e64d8113..cf5ff153 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.6.110021.jar - build/libs/OreSpawn-4.1.6.110021-sources.jar - build/libs/OreSpawn-4.1.6.110021-javadoc.jar + build/libs/OreSpawn-4.1.7.110021.jar + build/libs/OreSpawn-4.1.7.110021-sources.jar + build/libs/OreSpawn-4.1.7.110021-javadoc.jar build/release/SHA256SUMS CHANGELOG.txt diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 489a0829..6f3497ef 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,3 +1,32 @@ +Version 4.1.7.110021 + +* Keep completed retrogen marked through later saves and restarts, even while + retrogen is off. Do not mark chunks with a revision they have not processed. + +* Add loaded-chunk ore surveys, JSON/CSV reports, chunk details and rule + explanations. Keep read-only diagnostics independent of generation settings. +* Restore terrain clearing with permission checks, a preview, a verified + backup and checked undo. Keep ores, fluid deposits and unknown blocks safe. + Show short previews with clickable confirmation, cancellation and undo links. + +* 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. + +* Add provider/profile declarations and compiled natural rock formations. + Use the same deterministic, chunk-local geometry for early terrain placement + and geology prediction, with read-only formation and parent-material queries. +* Preserve caves, fluids, structures, other ores and existing chunks. Existing + worlds without formation definitions keep that absence in later terrain too. +* Let realism templates tune untouched packaged formations while preserving + authored, disabled, removed and authoritative external definitions. +* Keep native granite/diorite/andesite patches from cutting the expanded + formation rocks differently according to chunk population order, without + changing normal metal-ore hosts or older profiles. +* Preserve natural formation rock in vanilla lava-lake rims regardless of + neighbouring chunk order. Keep native lake shapes, fluid cavities and random + draws unchanged in normal, Amplified, Large Biomes and Customized worlds; + leave older profiles and custom generators alone. + Version 4.1.6.110021 * Fix duplicate ore generation when an OreSpawn 1 world is moved without its diff --git a/README.md b/README.md index 4e3071ab..f34d3109 100644 --- a/README.md +++ b/README.md @@ -10,13 +10,17 @@ It gives mods and modpacks one place to configure ores, deposit shapes, optional rock strata and geomes, provider-owned underground fluid deposits, biome palettes and world materials, flat bedrock, and bounded ore retrogen. -This branch builds target-qualified version `4.1.6.110021`: the OreSpawn 4.1.6 +This branch builds local candidate `4.1.7.110021`: the OreSpawn 4.1.7 feature set for Minecraft 1.10.2 and Forge. It adds stable generation identity, non-loading geology sampling, per-resource background control, existing-world provider merge policy, an Ore Sources arbiter for equivalent provider ores and a biome directory with exact new-terrain replacement overrides, plus a client -world-settings extension point for add-ons such as Realistic Deposits -while retaining API major 1. See the +world-settings extension point for add-ons such as Realistic Deposits. +Natural rock formations now share their compiled geometry between early +terrain placement and read-only geology prediction, including formation and +parent-material provenance. Missing formation sections in saved worlds remain +empty; this is not retrogen or a wholesale 4.2 backport. API major 1 is retained. +See the [versioning policy](docs/VERSIONS.md) for the encoding and release convention. Its deprecated compatibility layer imports OreSpawn 1 and OreSpawn 3 @@ -27,6 +31,10 @@ metadata block states, exclusive legacy height ceilings, and the historical Metals. OreSpawn never schedules both an original legacy generator and its OS4 translation. +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. @@ -208,3 +216,10 @@ Public developer and AI integration guidance lives in `docs/` and is included in the built jar. OreSpawn is licensed under LGPL-2.1. + +## Admin and distribution tools + +Use `/orespawn help` for loaded-chunk surveys, rule explanations and chunk +diagnostics. Guarded `/orespawn clearchunk` previews one chunk before changing +it and keeps a verified backup for checked undo. Open chat to review the preview +and choose Confirm clearing or Cancel. See [the admin guide](docs/ADMIN_TOOLS.md). diff --git a/build.gradle b/build.gradle index 2e3c6606..4778912a 100644 --- a/build.gradle +++ b/build.gradle @@ -59,6 +59,9 @@ tasks.withType(JavaCompile).configureEach { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 options.encoding = 'UTF-8' + // javac 8 can emit different anonymous-class constant pools after a partial + // incremental compile. Compile the complete source set for stable jar bytes. + options.incremental = false options.compilerArgs.addAll(['-Xmaxerrs', '1000']) } @@ -189,8 +192,8 @@ tasks.register('verifyDocumentationParity') { dependsOn tasks.named('processResources') doLast { List tracked = trackedDocumentationFiles() - if (tracked.size() != 20) { - throw new GradleException("Expected 20 tracked documentation files, found ${tracked.size()}") + if (tracked.size() != 22) { + throw new GradleException("Expected 22 tracked documentation files, found ${tracked.size()}") } tracked.each { File source -> String relative = documentationRelativePath(source) diff --git a/docs/ADMIN_TOOLS.md b/docs/ADMIN_TOOLS.md new file mode 100644 index 00000000..4f05fbd8 --- /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:stone@3 +/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 Ore +Dictionary 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 chunk is marked for native relighting instead of claiming completion. + +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/CONFIGURATION.md b/docs/CONFIGURATION.md index fd9e4a7e..59e73482 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -384,6 +384,14 @@ or `host_tags` entry. Optional `biome_ids`, `excluded_biome_ids`, Only ore rules with `retrogen:true` participate. Terrain strata are never retro-generated. +Completed revisions survive chunk saves and server restarts, including time +spent with retrogen disabled. Changing settings alone does not mark a new +revision as complete. A different revision, `force:true`, or the manual +retrogen command can deliberately run another pass. Keep force off for normal +use. This repair cannot identify or remove extra ores placed by older builds, +or reconstruct completion markers those builds already lost; back up your save +before enabling retrogen. + `flat_bedrock.enabled` and `flat_bedrock.retrogen` are off by default. `layers` is 1-5 and `dimensions` is an array of full dimension IDs. diff --git a/docs/MIGRATION.md b/docs/MIGRATION.md index 878b9df2..8fd73946 100644 --- a/docs/MIGRATION.md +++ b/docs/MIGRATION.md @@ -1,5 +1,41 @@ # Migration +## 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. + ## OreSpawn 1 And OreSpawn 3 Compatibility On Minecraft 1.10.2 This branch ships deprecated compatibility bridges for existing OreSpawn 1 and diff --git a/docs/PLAYER_GUIDE.md b/docs/PLAYER_GUIDE.md index a065b905..2cffbadd 100644 --- a/docs/PLAYER_GUIDE.md +++ b/docs/PLAYER_GUIDE.md @@ -180,5 +180,9 @@ For a dedicated server, copy the whole world including that file and install the same mods. Alternatively, place a prepared global profile at `config/orespawn-worldgen.json` before creating a new server world. +For measured ore counts, chunk details and guarded terrain clearing, see +[Admin tools](ADMIN_TOOLS.md). Surveys read loaded chunks only; clearing and +undo need explicit permission, a preview and a verified backup. + The server console commands `/orespawn status`, `/orespawn reload`, and `/orespawn dump-biomes` help pack authors diagnose active providers and IDs. diff --git a/docs/README.md b/docs/README.md index aafc1673..58405395 100644 --- a/docs/README.md +++ b/docs/README.md @@ -14,6 +14,8 @@ API and provider references for the details. - [Configuration field reference](CONFIGURATION.md) - [Provider JSON files](PROVIDERS.md) - [Java API and custom patterns](API.md) +- [Natural rock formations](ROCK_FORMATIONS.md) +- [Admin commands, ore surveys and guarded clearing](ADMIN_TOOLS.md) - [Ore patterns and runtime tools](FEATURES.md) - [Templates](TEMPLATES.md) - [Biomes and world materials](BIOMES.md) diff --git a/docs/ROCK_FORMATIONS.md b/docs/ROCK_FORMATIONS.md new file mode 100644 index 00000000..3f64bb6a --- /dev/null +++ b/docs/ROCK_FORMATIONS.md @@ -0,0 +1,58 @@ +# Natural rock formations (local 1.10.2 candidate) + +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. OreSpawn clears it on each ore event, +at the end of the ore pass and at world reset; nested passes restore their outer +context. 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. +`Original Strata` retains Mineralogy's modest defaults rather than applying the +Realistic Deposits tuning. Disabling physical terrain or choosing Cyano suppresses +the formation pass. The exact vanilla Overworld generator supports normal, +Amplified, Large Biomes and Customized worlds, with the same lava-lake +protection in each. Custom generators, including subclasses of the vanilla +generator, fail closed for prediction, placement and 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 is intentional for vein fill and regolith, not a random 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. + +This contract is local and unreleased. Add-ons must use checksum-bound local +candidate dependencies until an engine release is separately authorised. diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 69fa71a8..b2b5287c 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`. +## Checking ore distribution + +Use `/orespawn survey 1` in a loaded test area, then `/orespawn jobs ` +to find the JSON/CSV reports. Compare coverage and height ranges before +comparing ore counts. `/orespawn explain [x y z]` explains current +eligibility without changing settings or rolling a generation attempt. +See [Admin tools](ADMIN_TOOLS.md) for permissions, limitations and safe clearing. diff --git a/docs/schemas/orespawn-provider.schema.json b/docs/schemas/orespawn-provider.schema.json index 41739283..26630666 100644 --- a/docs/schemas/orespawn-provider.schema.json +++ b/docs/schemas/orespawn-provider.schema.json @@ -2,44 +2,141 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://mcmoddev.com/orespawn/schemas/orespawn-provider.schema.json", "type": "object", - "required": ["schema_version", "provider_modid", "provider_revision"], + "required": [ + "schema_version", + "provider_modid", + "provider_revision" + ], "properties": { - "schema_version": { "enum": [1, 2, 3, 4, 5] }, - "provider_modid": { "type": "string", "pattern": "^[a-z][a-z0-9_.-]+$" }, - "provider_revision": { "type": "integer", "minimum": 1 }, - "merge_new_entries_into_existing_worlds": { "type": "boolean" }, - "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" } }, - "geomes": { "type": "object", "additionalProperties": { "$ref": "profile-common.schema.json#/$defs/geome" } }, - "biome_rules": { "type": "object", "additionalProperties": { "$ref": "profile-common.schema.json#/$defs/weights" } }, - "terrain_dimensions": { "type": "object", "additionalProperties": { "$ref": "profile-common.schema.json#/$defs/terrainDimension" } }, - "biome_palettes": { "type": "object", "additionalProperties": { "$ref": "profile-common.schema.json#/$defs/biomePalette" } }, - "dimension_materials": { "type": "object", "additionalProperties": { "$ref": "profile-common.schema.json#/$defs/dimensionMaterials" } }, - "profile_defaults": { "type": "object" }, + "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" + }, + "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" + } + }, + "geomes": { + "type": "object", + "additionalProperties": { + "$ref": "profile-common.schema.json#/$defs/geome" + } + }, + "biome_rules": { + "type": "object", + "additionalProperties": { + "$ref": "profile-common.schema.json#/$defs/weights" + } + }, + "terrain_dimensions": { + "type": "object", + "additionalProperties": { + "$ref": "profile-common.schema.json#/$defs/terrainDimension" + } + }, + "biome_palettes": { + "type": "object", + "additionalProperties": { + "$ref": "profile-common.schema.json#/$defs/biomePalette" + } + }, + "dimension_materials": { + "type": "object", + "additionalProperties": { + "$ref": "profile-common.schema.json#/$defs/dimensionMaterials" + } + }, + "profile_defaults": { + "type": "object" + }, "templates": { "type": "object", "additionalProperties": { "type": "object", - "required": ["profile"], + "required": [ + "profile" + ], "properties": { - "name_key": { "type": "string" }, - "description_key": { "type": "string" }, - "required_mods": { "type": "array", "uniqueItems": true, "items": { "type": "string" } }, - "auto_select": { "type": "boolean" }, - "auto_select_priority": { "type": "integer" }, - "profile": { "type": "object" } + "name_key": { + "type": "string" + }, + "description_key": { + "type": "string" + }, + "required_mods": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string" + } + }, + "auto_select": { + "type": "boolean" + }, + "auto_select_priority": { + "type": "integer" + }, + "profile": { + "type": "object" + } } } + }, + "rock_formations": { + "type": "object", + "additionalProperties": { + "$ref": "profile-common.schema.json#/$defs/rockFormation" + } } }, "allOf": [ { - "if": { "properties": { "schema_version": { "const": 1 } } }, + "if": { + "properties": { + "schema_version": { + "const": 1 + } + } + }, "then": { - "required": ["ores"], + "required": [ + "ores" + ], "properties": { - "ores": { "minProperties": 1 }, + "ores": { + "minProperties": 1 + }, "rocks": false, "geomes": false, "biome_rules": false, @@ -48,34 +145,169 @@ "biome_palettes": false, "dimension_materials": false, "templates": false, - "profile_defaults": false - } - } - }, - { - "if": { "properties": { "schema_version": { "enum": [1, 2] } } }, - "then": { "properties": { "fluid_deposits": false } } - }, - { - "if": { "properties": { "schema_version": { "enum": [1, 2, 3] } } }, - "then": { - "properties": { - "biome_palettes": false, - "dimension_materials": false - } - } - } + "profile_defaults": false, + "rock_formations": false + } + } + }, + { + "if": { + "properties": { + "schema_version": { + "enum": [ + 1, + 2 + ] + } + } + }, + "then": { + "properties": { + "fluid_deposits": false + } + } + }, + { + "if": { + "properties": { + "schema_version": { + "enum": [ + 1, + 2, + 3 + ] + } + } + }, + "then": { + "properties": { + "biome_palettes": false, + "dimension_materials": false + } + } + }, + { + "if": { + "properties": { + "schema_version": { + "enum": [ + 1, + 2, + 3, + 4, + 5 + ] + } + } + }, + "then": { + "properties": { + "rock_formations": false + } + } + } ], "anyOf": [ - { "required": ["rocks"], "properties": { "rocks": { "minProperties": 1 } } }, - { "required": ["ores"], "properties": { "ores": { "minProperties": 1 } } }, - { "required": ["geomes"], "properties": { "geomes": { "minProperties": 1 } } }, - { "required": ["biome_rules"], "properties": { "biome_rules": { "minProperties": 1 } } }, - { "required": ["terrain_dimensions"], "properties": { "terrain_dimensions": { "minProperties": 1 } } }, - { "required": ["fluid_deposits"], "properties": { "fluid_deposits": { "minProperties": 1 } } }, - { "required": ["biome_palettes"], "properties": { "biome_palettes": { "minProperties": 1 } } }, - { "required": ["dimension_materials"], "properties": { "dimension_materials": { "minProperties": 1 } } }, - { "required": ["templates"], "properties": { "templates": { "minProperties": 1 } } } + { + "required": [ + "rocks" + ], + "properties": { + "rocks": { + "minProperties": 1 + } + } + }, + { + "required": [ + "ores" + ], + "properties": { + "ores": { + "minProperties": 1 + } + } + }, + { + "required": [ + "geomes" + ], + "properties": { + "geomes": { + "minProperties": 1 + } + } + }, + { + "required": [ + "biome_rules" + ], + "properties": { + "biome_rules": { + "minProperties": 1 + } + } + }, + { + "required": [ + "terrain_dimensions" + ], + "properties": { + "terrain_dimensions": { + "minProperties": 1 + } + } + }, + { + "required": [ + "fluid_deposits" + ], + "properties": { + "fluid_deposits": { + "minProperties": 1 + } + } + }, + { + "required": [ + "biome_palettes" + ], + "properties": { + "biome_palettes": { + "minProperties": 1 + } + } + }, + { + "required": [ + "dimension_materials" + ], + "properties": { + "dimension_materials": { + "minProperties": 1 + } + } + }, + { + "required": [ + "templates" + ], + "properties": { + "templates": { + "minProperties": 1 + } + } + }, + { + "required": [ + "rock_formations" + ], + "properties": { + "rock_formations": { + "minProperties": 1 + } + } + } ], "additionalProperties": false } diff --git a/docs/schemas/profile-common.schema.json b/docs/schemas/profile-common.schema.json index 9584dad2..2df770e2 100644 --- a/docs/schemas/profile-common.schema.json +++ b/docs/schemas/profile-common.schema.json @@ -2,407 +2,1360 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://mcmoddev.com/orespawn/schemas/profile-common.schema.json", "type": "object", - "required": ["formations", "rocks", "geomes", "biomes", "terrain_dimensions", "biome_palettes", "dimension_materials", "ores", "ore_material_groups", "ore_source_policies", "fluid_deposits"], + "required": [ + "formations", + "rocks", + "geomes", + "biomes", + "terrain_dimensions", + "biome_palettes", + "dimension_materials", + "ores", + "ore_material_groups", + "ore_source_policies", + "fluid_deposits" + ], "properties": { - "geology_mode": { "enum": ["geome", "legacy"] }, - "place_fluid_deposits": { "type": "boolean" }, - "manage_vanilla_ores": { "type": "boolean" }, - "suppress_all_ore_features": { "type": "boolean" }, - "default_template": { "$ref": "#/$defs/optionalRegistryId" }, - "selected_template": { "$ref": "#/$defs/registryId" }, - "formations": { "$ref": "#/$defs/formations" }, - "rocks": { "type": "object", "additionalProperties": { "$ref": "#/$defs/rock" } }, - "geomes": { "type": "object", "minProperties": 1, "additionalProperties": { "$ref": "#/$defs/geome" } }, - "biomes": { "type": "object", "additionalProperties": { "$ref": "#/$defs/weights" } }, - "biome_dictionary": { "type": "object", "additionalProperties": { "$ref": "#/$defs/weights" } }, - "terrain_dimensions": { "type": "object", "additionalProperties": { "$ref": "#/$defs/terrainDimension" } }, - "biome_palettes": { "type": "object", "additionalProperties": { "$ref": "#/$defs/biomePalette" } }, - "dimension_materials": { "type": "object", "additionalProperties": { "$ref": "#/$defs/dimensionMaterials" } }, - "ores": { "type": "object", "additionalProperties": { "$ref": "#/$defs/ore" } }, - "ore_material_groups": { "type": "object", "propertyNames": { "pattern": "^[a-z0-9_.-]+:[a-z0-9_./-]+$" }, "additionalProperties": { "$ref": "#/$defs/oreMaterialGroup" } }, - "ore_source_policies": { "type": "object", "additionalProperties": { "$ref": "#/$defs/oreSourcePolicy" } }, - "fluid_deposits": { "type": "object", "additionalProperties": { "$ref": "#/$defs/fluidDeposit" } }, - "worldgen_aliases": { "type": "object", "additionalProperties": { "$ref": "#/$defs/registryId" } }, - "providers": { "type": "object" }, - "ore_providers": { "type": "object" } - ,"retrogen": { "$ref": "#/$defs/retrogen" } - ,"flat_bedrock": { "$ref": "#/$defs/flatBedrock" } + "geology_mode": { + "enum": [ + "geome", + "legacy" + ] + }, + "place_fluid_deposits": { + "type": "boolean" + }, + "manage_vanilla_ores": { + "type": "boolean" + }, + "suppress_all_ore_features": { + "type": "boolean" + }, + "default_template": { + "$ref": "#/$defs/optionalRegistryId" + }, + "selected_template": { + "$ref": "#/$defs/registryId" + }, + "formations": { + "$ref": "#/$defs/formations" + }, + "rocks": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/rock" + } + }, + "geomes": { + "type": "object", + "minProperties": 1, + "additionalProperties": { + "$ref": "#/$defs/geome" + } + }, + "biomes": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/weights" + } + }, + "biome_dictionary": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/weights" + } + }, + "terrain_dimensions": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/terrainDimension" + } + }, + "biome_palettes": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/biomePalette" + } + }, + "dimension_materials": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/dimensionMaterials" + } + }, + "ores": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/ore" + } + }, + "ore_material_groups": { + "type": "object", + "propertyNames": { + "pattern": "^[a-z0-9_.-]+:[a-z0-9_./-]+$" + }, + "additionalProperties": { + "$ref": "#/$defs/oreMaterialGroup" + } + }, + "ore_source_policies": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/oreSourcePolicy" + } + }, + "fluid_deposits": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/fluidDeposit" + } + }, + "worldgen_aliases": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/registryId" + } + }, + "providers": { + "type": "object" + }, + "ore_providers": { + "type": "object" + }, + "retrogen": { + "$ref": "#/$defs/retrogen" + }, + "flat_bedrock": { + "$ref": "#/$defs/flatBedrock" + }, + "rock_formations": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/rockFormation" + } + } }, "additionalProperties": true, "$defs": { - "registryId": { "type": "string", "pattern": "^[a-z0-9_.-]+:[a-z0-9_./-]+$" }, - "optionalRegistryId": { "type": "string", "pattern": "^(|[a-z0-9_.-]+:[a-z0-9_./-]+)$" }, - "registryIds": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/registryId" } }, - "family": { "enum": ["sedimentary", "metamorphic", "igneous_intrusive", "igneous_volcanic"] }, - "preset": { "enum": ["tiny", "small", "average", "large", "huge", "custom"] }, - "weights": { "type": "object", "additionalProperties": { "type": "number", "minimum": 0 } }, - "metadata": { "type": "integer", "minimum": 0, "maximum": 15 }, + "registryId": { + "type": "string", + "pattern": "^[a-z0-9_.-]+:[a-z0-9_./-]+$" + }, + "optionalRegistryId": { + "type": "string", + "pattern": "^(|[a-z0-9_.-]+:[a-z0-9_./-]+)$" + }, + "registryIds": { + "type": "array", + "uniqueItems": true, + "items": { + "$ref": "#/$defs/registryId" + } + }, + "family": { + "enum": [ + "sedimentary", + "metamorphic", + "igneous_intrusive", + "igneous_volcanic" + ] + }, + "preset": { + "enum": [ + "tiny", + "small", + "average", + "large", + "huge", + "custom" + ] + }, + "weights": { + "type": "object", + "additionalProperties": { + "type": "number", + "minimum": 0 + } + }, + "metadata": { + "type": "integer", + "minimum": 0, + "maximum": 15 + }, "weightedBlock": { "type": "object", - "required": ["block"], + "required": [ + "block" + ], "properties": { - "block": { "$ref": "#/$defs/registryId" }, - "metadata": { "$ref": "#/$defs/metadata" }, - "weight": { "type": "number", "minimum": 0, "maximum": 1 } + "block": { + "$ref": "#/$defs/registryId" + }, + "metadata": { + "$ref": "#/$defs/metadata" + }, + "weight": { + "type": "number", + "minimum": 0, + "maximum": 1 + } } }, "weightedTag": { "type": "object", - "required": ["tag"], + "required": [ + "tag" + ], "properties": { - "tag": { "$ref": "#/$defs/registryId" }, - "weight": { "type": "number", "minimum": 0, "maximum": 1 } + "tag": { + "$ref": "#/$defs/registryId" + }, + "weight": { + "type": "number", + "minimum": 0, + "maximum": 1 + } } }, "hostBlocks": { "type": "array", - "items": { "anyOf": [ - { "$ref": "#/$defs/registryId" }, - { "$ref": "#/$defs/weightedBlock" } - ] } + "items": { + "anyOf": [ + { + "$ref": "#/$defs/registryId" + }, + { + "$ref": "#/$defs/weightedBlock" + } + ] + } }, "hostTags": { "type": "array", - "items": { "anyOf": [ - { "$ref": "#/$defs/registryId" }, - { "$ref": "#/$defs/weightedTag" } - ] } + "items": { + "anyOf": [ + { + "$ref": "#/$defs/registryId" + }, + { + "$ref": "#/$defs/weightedTag" + } + ] + } }, "formations": { "type": "object", - "required": ["algorithm", "horizontal_size", "vertical_thickness", "waviness", "edge_irregularity", "formation_continuity", "custom"], + "required": [ + "algorithm", + "horizontal_size", + "vertical_thickness", + "waviness", + "edge_irregularity", + "formation_continuity", + "custom" + ], "properties": { - "algorithm": { "enum": ["stable_layers", "sky_v1"] }, - "horizontal_size": { "$ref": "#/$defs/preset" }, - "vertical_thickness": { "$ref": "#/$defs/preset" }, - "waviness": { "$ref": "#/$defs/preset" }, - "edge_irregularity": { "$ref": "#/$defs/preset" }, - "formation_continuity": { "$ref": "#/$defs/preset" }, - "custom": { "type": "object", "additionalProperties": { "type": "number" } } + "algorithm": { + "enum": [ + "stable_layers", + "sky_v1" + ] + }, + "horizontal_size": { + "$ref": "#/$defs/preset" + }, + "vertical_thickness": { + "$ref": "#/$defs/preset" + }, + "waviness": { + "$ref": "#/$defs/preset" + }, + "edge_irregularity": { + "$ref": "#/$defs/preset" + }, + "formation_continuity": { + "$ref": "#/$defs/preset" + }, + "custom": { + "type": "object", + "additionalProperties": { + "type": "number" + } + } } }, "rock": { "type": "object", - "required": ["enabled", "family", "depth_peak", "depth_spread", "min_y", "max_y", "weight", "ore_replaceable"], + "required": [ + "enabled", + "family", + "depth_peak", + "depth_spread", + "min_y", + "max_y", + "weight", + "ore_replaceable" + ], "properties": { - "block": { "$ref": "#/$defs/registryId" }, - "metadata": { "$ref": "#/$defs/metadata" }, - "enabled": { "type": "boolean" }, - "family": { "$ref": "#/$defs/family" }, - "depth_peak": { "type": "integer", "minimum": -2048, "maximum": 2048 }, - "depth_spread": { "type": "integer", "minimum": 1 }, - "min_y": { "type": "integer", "minimum": -2048, "maximum": 2048 }, - "max_y": { "type": "integer", "minimum": -2048, "maximum": 2048 }, - "weight": { "type": "number", "minimum": 0 }, - "ore_replaceable": { "type": "boolean" }, - "geomes": { "$ref": "#/$defs/weights" }, - "dimensions": { "$ref": "#/$defs/registryIds" } + "block": { + "$ref": "#/$defs/registryId" + }, + "metadata": { + "$ref": "#/$defs/metadata" + }, + "enabled": { + "type": "boolean" + }, + "family": { + "$ref": "#/$defs/family" + }, + "depth_peak": { + "type": "integer", + "minimum": -2048, + "maximum": 2048 + }, + "depth_spread": { + "type": "integer", + "minimum": 1 + }, + "min_y": { + "type": "integer", + "minimum": -2048, + "maximum": 2048 + }, + "max_y": { + "type": "integer", + "minimum": -2048, + "maximum": 2048 + }, + "weight": { + "type": "number", + "minimum": 0 + }, + "ore_replaceable": { + "type": "boolean" + }, + "geomes": { + "$ref": "#/$defs/weights" + }, + "dimensions": { + "$ref": "#/$defs/registryIds" + } }, "additionalProperties": true }, "geome": { "type": "object", - "required": ["base", "families"], + "required": [ + "base", + "families" + ], "properties": { - "base": { "type": "number", "minimum": 0 }, - "families": { "type": "object", "additionalProperties": { "type": "number", "minimum": 0 } } + "base": { + "type": "number", + "minimum": 0 + }, + "families": { + "type": "object", + "additionalProperties": { + "type": "number", + "minimum": 0 + } + } }, "additionalProperties": true }, "terrainDimension": { "type": "object", - "required": ["enabled", "host_blocks", "host_tags"], + "required": [ + "enabled", + "host_blocks", + "host_tags" + ], "properties": { - "enabled": { "type": "boolean" }, - "biome_ids": { "$ref": "#/$defs/registryIds" }, - "biome_namespaces": { "type": "array", "uniqueItems": true, "items": { "type": "string", "pattern": "^[a-z][a-z0-9_.-]+$" } }, - "host_blocks": { "$ref": "#/$defs/hostBlocks" }, - "host_tags": { "$ref": "#/$defs/hostTags" } + "enabled": { + "type": "boolean" + }, + "biome_ids": { + "$ref": "#/$defs/registryIds" + }, + "biome_namespaces": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^[a-z][a-z0-9_.-]+$" + } + }, + "host_blocks": { + "$ref": "#/$defs/hostBlocks" + }, + "host_tags": { + "$ref": "#/$defs/hostTags" + } } }, "oreDimension": { "type": "object", - "required": ["enabled", "min_y", "max_y", "frequency"], + "required": [ + "enabled", + "min_y", + "max_y", + "frequency" + ], "properties": { - "enabled": { "type": "boolean" }, - "min_y": { "type": "integer", "minimum": -2048, "maximum": 2048 }, - "max_y": { "type": "integer", "minimum": -2048, "maximum": 2048 }, - "frequency": { "type": "number", "minimum": 0, "maximum": 64 }, - "quantity": { "type": "integer", "minimum": 1, "maximum": 64 }, - "min_quantity": { "type": "integer", "minimum": 1, "maximum": 64 }, - "max_quantity": { "type": "integer", "minimum": 1, "maximum": 64 }, - "pattern": { "anyOf": [ - { "enum": ["default", "vein", "normal_cloud", "precision", "clusters", "underfluids", "cluster", "cloud"] }, - { - "type": "object", - "required": ["type", "settings"], - "properties": { - "type": { "$ref": "#/$defs/registryId" }, - "settings": { "type": "object" } + "enabled": { + "type": "boolean" + }, + "min_y": { + "type": "integer", + "minimum": -2048, + "maximum": 2048 + }, + "max_y": { + "type": "integer", + "minimum": -2048, + "maximum": 2048 + }, + "frequency": { + "type": "number", + "minimum": 0, + "maximum": 64 + }, + "quantity": { + "type": "integer", + "minimum": 1, + "maximum": 64 + }, + "min_quantity": { + "type": "integer", + "minimum": 1, + "maximum": 64 + }, + "max_quantity": { + "type": "integer", + "minimum": 1, + "maximum": 64 + }, + "pattern": { + "anyOf": [ + { + "enum": [ + "default", + "vein", + "normal_cloud", + "precision", + "clusters", + "underfluids", + "cluster", + "cloud" + ] + }, + { + "type": "object", + "required": [ + "type", + "settings" + ], + "properties": { + "type": { + "$ref": "#/$defs/registryId" + }, + "settings": { + "type": "object" + } + } } - } - ] }, + ] + }, "height_distribution": { - "enum": ["uniform", "triangle", "bottom_triangle", "uniform_bottom_triangle"] + "enum": [ + "uniform", + "triangle", + "bottom_triangle", + "uniform_bottom_triangle" + ] }, "discard_chance_on_air_exposure": { "type": "number", - "minimum": 0.0, - "maximum": 1.0 + "minimum": 0, + "maximum": 1 }, "background_generation_scale": { "type": "number", - "minimum": 0.0, - "maximum": 1.0 - }, - "placement_channel": { "$ref": "#/$defs/registryId" }, - "spread": { "type": "integer", "minimum": 0, "maximum": 64 }, - "vertical_spread": { "type": "integer", "minimum": 0, "maximum": 64 }, - "node_size": { "type": "integer", "minimum": 1, "maximum": 32 }, - "length": { "type": "integer", "minimum": 1, "maximum": 64 }, - "fluid": { "$ref": "#/$defs/registryId" }, - "host_families": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/family" } }, - "host_blocks": { "$ref": "#/$defs/hostBlocks" }, - "host_tags": { "$ref": "#/$defs/hostTags" }, - "geomes": { "$ref": "#/$defs/weights" }, - "biome_ids": { "$ref": "#/$defs/registryIds" }, - "excluded_biome_ids": { "$ref": "#/$defs/registryIds" }, - "biome_dictionary": { "type": "array", "items": { "type": "string" } }, - "excluded_biome_dictionary": { "type": "array", "items": { "type": "string" } } + "minimum": 0, + "maximum": 1 + }, + "placement_channel": { + "$ref": "#/$defs/registryId" + }, + "spread": { + "type": "integer", + "minimum": 0, + "maximum": 64 + }, + "vertical_spread": { + "type": "integer", + "minimum": 0, + "maximum": 64 + }, + "node_size": { + "type": "integer", + "minimum": 1, + "maximum": 32 + }, + "length": { + "type": "integer", + "minimum": 1, + "maximum": 64 + }, + "fluid": { + "$ref": "#/$defs/registryId" + }, + "host_families": { + "type": "array", + "uniqueItems": true, + "items": { + "$ref": "#/$defs/family" + } + }, + "host_blocks": { + "$ref": "#/$defs/hostBlocks" + }, + "host_tags": { + "$ref": "#/$defs/hostTags" + }, + "geomes": { + "$ref": "#/$defs/weights" + }, + "biome_ids": { + "$ref": "#/$defs/registryIds" + }, + "excluded_biome_ids": { + "$ref": "#/$defs/registryIds" + }, + "biome_dictionary": { + "type": "array", + "items": { + "type": "string" + } + }, + "excluded_biome_dictionary": { + "type": "array", + "items": { + "type": "string" + } + } }, "allOf": [ - { "anyOf": [ - { "required": ["quantity"] }, - { "required": ["min_quantity", "max_quantity"] } - ] }, - { "anyOf": [ - { "required": ["host_families"] }, - { "required": ["host_blocks"] }, - { "required": ["host_tags"] } - ] } + { + "anyOf": [ + { + "required": [ + "quantity" + ] + }, + { + "required": [ + "min_quantity", + "max_quantity" + ] + } + ] + }, + { + "anyOf": [ + { + "required": [ + "host_families" + ] + }, + { + "required": [ + "host_blocks" + ] + }, + { + "required": [ + "host_tags" + ] + } + ] + } ], "dependentRequired": { - "min_quantity": ["max_quantity"], - "max_quantity": ["min_quantity"] + "min_quantity": [ + "max_quantity" + ], + "max_quantity": [ + "min_quantity" + ] }, "additionalProperties": true }, "ore": { "type": "object", - "required": ["enabled"], + "required": [ + "enabled" + ], "properties": { - "block": { "$ref": "#/$defs/registryId" }, - "material": { "$ref": "#/$defs/registryId" }, - "metadata": { "$ref": "#/$defs/metadata" }, - "enabled": { "type": "boolean" }, - "source_mod": { "type": "string" }, - "native_generation": { "type": "boolean" }, - "suppress_vanilla": { "type": "boolean" }, - "retrogen": { "type": "boolean" }, + "block": { + "$ref": "#/$defs/registryId" + }, + "material": { + "$ref": "#/$defs/registryId" + }, + "metadata": { + "$ref": "#/$defs/metadata" + }, + "enabled": { + "type": "boolean" + }, + "source_mod": { + "type": "string" + }, + "native_generation": { + "type": "boolean" + }, + "suppress_vanilla": { + "type": "boolean" + }, + "retrogen": { + "type": "boolean" + }, "outputs": { "type": "array", "items": { "type": "object", - "required": ["block", "weight"], + "required": [ + "block", + "weight" + ], "properties": { - "block": { "$ref": "#/$defs/registryId" }, - "metadata": { "$ref": "#/$defs/metadata" }, - "weight": { "type": "number", "minimum": 0 }, - "min_y": { "type": "integer" }, - "max_y": { "type": "integer" } + "block": { + "$ref": "#/$defs/registryId" + }, + "metadata": { + "$ref": "#/$defs/metadata" + }, + "weight": { + "type": "number", + "minimum": 0 + }, + "min_y": { + "type": "integer" + }, + "max_y": { + "type": "integer" + } } } }, - "deep_output": { "$ref": "#/$defs/registryId" }, - "deep_output_metadata": { "$ref": "#/$defs/metadata" }, - "deep_output_max_y": { "type": "integer" }, - "dimensions": { "type": "object", "minProperties": 1, "additionalProperties": { "$ref": "#/$defs/oreDimension" } }, + "deep_output": { + "$ref": "#/$defs/registryId" + }, + "deep_output_metadata": { + "$ref": "#/$defs/metadata" + }, + "deep_output_max_y": { + "type": "integer" + }, + "dimensions": { + "type": "object", + "minProperties": 1, + "additionalProperties": { + "$ref": "#/$defs/oreDimension" + } + }, "dimension_selectors": { "type": "object", "minProperties": 1, "properties": { - "orespawn:all_except_nether_end": { "$ref": "#/$defs/oreDimension" } + "orespawn:all_except_nether_end": { + "$ref": "#/$defs/oreDimension" + } }, "additionalProperties": false } }, "anyOf": [ - { "required": ["dimensions"] }, - { "required": ["dimension_selectors"] } + { + "required": [ + "dimensions" + ] + }, + { + "required": [ + "dimension_selectors" + ] + } ], "additionalProperties": true }, "oreSourceCandidate": { "type": "object", - "required": ["source_id", "owner", "registry_id", "material", "domain", "placement_channel", "loaded", "external"], + "required": [ + "source_id", + "owner", + "registry_id", + "material", + "domain", + "placement_channel", + "loaded", + "external" + ], "properties": { - "source_id": { "type": "string", "minLength": 1 }, - "owner": { "type": "string", "minLength": 1 }, - "owner_name": { "type": "string" }, - "owner_version": { "type": "string" }, - "registry_id": { "$ref": "#/$defs/registryId" }, - "metadata": { "$ref": "#/$defs/metadata" }, - "material": { "$ref": "#/$defs/registryId" }, - "domain": { "$ref": "#/$defs/registryId" }, - "placement_channel": { "$ref": "#/$defs/registryId" }, - "ore_dictionary": { "type": "array", "uniqueItems": true, "items": { "type": "string", "minLength": 1 } }, - "loaded": { "type": "boolean" }, - "placement_active": { "type": "boolean" }, - "external": { "type": "boolean" }, - "enrichment": { "type": "boolean" }, - "review_required": { "type": "boolean" }, - "material_declared": { "type": "boolean" } + "source_id": { + "type": "string", + "minLength": 1 + }, + "owner": { + "type": "string", + "minLength": 1 + }, + "owner_name": { + "type": "string" + }, + "owner_version": { + "type": "string" + }, + "registry_id": { + "$ref": "#/$defs/registryId" + }, + "metadata": { + "$ref": "#/$defs/metadata" + }, + "material": { + "$ref": "#/$defs/registryId" + }, + "domain": { + "$ref": "#/$defs/registryId" + }, + "placement_channel": { + "$ref": "#/$defs/registryId" + }, + "ore_dictionary": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "minLength": 1 + } + }, + "loaded": { + "type": "boolean" + }, + "placement_active": { + "type": "boolean" + }, + "external": { + "type": "boolean" + }, + "enrichment": { + "type": "boolean" + }, + "review_required": { + "type": "boolean" + }, + "material_declared": { + "type": "boolean" + } }, "additionalProperties": false }, "oreSourcePolicy": { "type": "object", - "required": ["material", "domain", "mode", "output_mode", "outputs", "placement_sources", "candidates"], + "required": [ + "material", + "domain", + "mode", + "output_mode", + "outputs", + "placement_sources", + "candidates" + ], "properties": { - "material": { "$ref": "#/$defs/registryId" }, - "domain": { "$ref": "#/$defs/registryId" }, - "mode": { "enum": ["consolidated", "keep_separate"] }, - "output_mode": { "enum": ["balanced", "single", "custom"] }, - "outputs": { "type": "object", "additionalProperties": { "type": "number", "exclusiveMinimum": 0 } }, - "placement_sources": { "type": "object", "propertyNames": { "pattern": "^[a-z0-9_.-]+:[a-z0-9_./-]+$" }, "additionalProperties": { "type": "string", "minLength": 1 } }, - "candidates": { "type": "array", "items": { "$ref": "#/$defs/oreSourceCandidate" } }, - "review_required": { "type": "boolean" }, - "status": { "enum": ["consolidated", "separate", "review_required", "missing_source", "external_generation"] }, - "dormant": { "type": "boolean" } + "material": { + "$ref": "#/$defs/registryId" + }, + "domain": { + "$ref": "#/$defs/registryId" + }, + "mode": { + "enum": [ + "consolidated", + "keep_separate" + ] + }, + "output_mode": { + "enum": [ + "balanced", + "single", + "custom" + ] + }, + "outputs": { + "type": "object", + "additionalProperties": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "placement_sources": { + "type": "object", + "propertyNames": { + "pattern": "^[a-z0-9_.-]+:[a-z0-9_./-]+$" + }, + "additionalProperties": { + "type": "string", + "minLength": 1 + } + }, + "candidates": { + "type": "array", + "items": { + "$ref": "#/$defs/oreSourceCandidate" + } + }, + "review_required": { + "type": "boolean" + }, + "status": { + "enum": [ + "consolidated", + "separate", + "review_required", + "missing_source", + "external_generation" + ] + }, + "dormant": { + "type": "boolean" + } }, "additionalProperties": false }, "oreMaterialGroup": { "type": "object", - "required": ["display_name", "ore_dictionary_entries"], + "required": [ + "display_name", + "ore_dictionary_entries" + ], "properties": { - "display_name": { "type": "string", "minLength": 1, "maxLength": 64 }, - "ore_dictionary_entries": { "type": "array", "uniqueItems": true, "items": { "type": "string", "pattern": "^ore[A-Z][A-Za-z0-9_]*$", "maxLength": 128 } } + "display_name": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "ore_dictionary_entries": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^ore[A-Z][A-Za-z0-9_]*$", + "maxLength": 128 + } + } }, "additionalProperties": false }, "fluidDepositDimension": { - "type": "object", - "required": ["enabled", "min_y", "max_y", "frequency", "min_radius", "max_radius", "min_vertical_radius", "max_vertical_radius", "max_lobes", "min_solid_cover"], - "properties": { - "enabled": { "type": "boolean" }, - "min_y": { "type": "integer" }, "max_y": { "type": "integer" }, - "frequency": { "type": "number", "minimum": 0, "maximum": 64 }, - "min_radius": { "type": "integer", "minimum": 1, "maximum": 64 }, "max_radius": { "type": "integer", "minimum": 1, "maximum": 64 }, - "min_vertical_radius": { "type": "integer", "minimum": 1, "maximum": 64 }, "max_vertical_radius": { "type": "integer", "minimum": 1, "maximum": 64 }, - "max_lobes": { "type": "integer", "minimum": 1, "maximum": 16 }, "min_solid_cover": { "type": "integer", "minimum": 0, "maximum": 64 }, - "min_solid_shell": { "type": "integer", "minimum": 0, "maximum": 64, "default": 1 }, - "host_families": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/family" } }, - "host_blocks": { "$ref": "#/$defs/hostBlocks" }, - "host_tags": { "$ref": "#/$defs/hostTags" }, - "geomes": { "$ref": "#/$defs/weights" }, - "biome_ids": { "$ref": "#/$defs/registryIds" }, - "excluded_biome_ids": { "$ref": "#/$defs/registryIds" }, - "biome_dictionary": { "type": "array", "items": { "type": "string", "minLength": 1 } }, - "excluded_biome_dictionary": { "type": "array", "items": { "type": "string", "minLength": 1 } } - }, - "anyOf": [ - { "required": ["host_families"] }, - { "required": ["host_blocks"] }, - { "required": ["host_tags"] } - ], - "additionalProperties": true - }, - "fluidDeposit": { - "type": "object", - "required": ["enabled", "block", "dimensions"], - "properties": { - "enabled": { "type": "boolean" }, - "block": { "$ref": "#/$defs/registryId" }, - "metadata": { "$ref": "#/$defs/metadata" }, - "dimensions": { "type": "object", "minProperties": 1, "additionalProperties": { "$ref": "#/$defs/fluidDepositDimension" } } - }, - "additionalProperties": true - }, + "type": "object", + "required": [ + "enabled", + "min_y", + "max_y", + "frequency", + "min_radius", + "max_radius", + "min_vertical_radius", + "max_vertical_radius", + "max_lobes", + "min_solid_cover" + ], + "properties": { + "enabled": { + "type": "boolean" + }, + "min_y": { + "type": "integer" + }, + "max_y": { + "type": "integer" + }, + "frequency": { + "type": "number", + "minimum": 0, + "maximum": 64 + }, + "min_radius": { + "type": "integer", + "minimum": 1, + "maximum": 64 + }, + "max_radius": { + "type": "integer", + "minimum": 1, + "maximum": 64 + }, + "min_vertical_radius": { + "type": "integer", + "minimum": 1, + "maximum": 64 + }, + "max_vertical_radius": { + "type": "integer", + "minimum": 1, + "maximum": 64 + }, + "max_lobes": { + "type": "integer", + "minimum": 1, + "maximum": 16 + }, + "min_solid_cover": { + "type": "integer", + "minimum": 0, + "maximum": 64 + }, + "min_solid_shell": { + "type": "integer", + "minimum": 0, + "maximum": 64, + "default": 1 + }, + "host_families": { + "type": "array", + "uniqueItems": true, + "items": { + "$ref": "#/$defs/family" + } + }, + "host_blocks": { + "$ref": "#/$defs/hostBlocks" + }, + "host_tags": { + "$ref": "#/$defs/hostTags" + }, + "geomes": { + "$ref": "#/$defs/weights" + }, + "biome_ids": { + "$ref": "#/$defs/registryIds" + }, + "excluded_biome_ids": { + "$ref": "#/$defs/registryIds" + }, + "biome_dictionary": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "excluded_biome_dictionary": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "anyOf": [ + { + "required": [ + "host_families" + ] + }, + { + "required": [ + "host_blocks" + ] + }, + { + "required": [ + "host_tags" + ] + } + ], + "additionalProperties": true + }, + "fluidDeposit": { + "type": "object", + "required": [ + "enabled", + "block", + "dimensions" + ], + "properties": { + "enabled": { + "type": "boolean" + }, + "block": { + "$ref": "#/$defs/registryId" + }, + "metadata": { + "$ref": "#/$defs/metadata" + }, + "dimensions": { + "type": "object", + "minProperties": 1, + "additionalProperties": { + "$ref": "#/$defs/fluidDepositDimension" + } + } + }, + "additionalProperties": true + }, "retrogen": { "type": "object", "properties": { - "enabled": { "type": "boolean" }, - "force": { "type": "boolean" }, - "revision": { "type": "integer", "minimum": 0 }, - "chunks_per_tick": { "type": "integer", "minimum": 1, "maximum": 16 } + "enabled": { + "type": "boolean" + }, + "force": { + "type": "boolean" + }, + "revision": { + "type": "integer", + "minimum": 0 + }, + "chunks_per_tick": { + "type": "integer", + "minimum": 1, + "maximum": 16 + } } }, "biomeSurface": { "type": "object", "properties": { - "top_block": { "$ref": "#/$defs/registryId" }, - "top_block_metadata": { "$ref": "#/$defs/metadata" }, - "filler_block": { "$ref": "#/$defs/registryId" }, - "filler_block_metadata": { "$ref": "#/$defs/metadata" }, - "underwater_block": { "$ref": "#/$defs/registryId" }, - "underwater_block_metadata": { "$ref": "#/$defs/metadata" }, - "ceiling_block": { "$ref": "#/$defs/registryId" }, - "ceiling_block_metadata": { "$ref": "#/$defs/metadata" }, - "filler_depth": { "type": "integer", "minimum": 0, "maximum": 16 } + "top_block": { + "$ref": "#/$defs/registryId" + }, + "top_block_metadata": { + "$ref": "#/$defs/metadata" + }, + "filler_block": { + "$ref": "#/$defs/registryId" + }, + "filler_block_metadata": { + "$ref": "#/$defs/metadata" + }, + "underwater_block": { + "$ref": "#/$defs/registryId" + }, + "underwater_block_metadata": { + "$ref": "#/$defs/metadata" + }, + "ceiling_block": { + "$ref": "#/$defs/registryId" + }, + "ceiling_block_metadata": { + "$ref": "#/$defs/metadata" + }, + "filler_depth": { + "type": "integer", + "minimum": 0, + "maximum": 16 + } }, "additionalProperties": true }, "biomePlacement": { "type": "object", "properties": { - "enabled": { "type": "boolean" }, - "weight": { "type": "number", "minimum": 0 }, - "similar_biomes": { "$ref": "#/$defs/registryIds" }, - "required_similar_biomes": { "$ref": "#/$defs/registryIds" }, - "min_temperature": { "type": "number", "minimum": -2, "maximum": 2 }, - "max_temperature": { "type": "number", "minimum": -2, "maximum": 2 }, - "min_downfall": { "type": "number", "minimum": 0, "maximum": 1 }, - "max_downfall": { "type": "number", "minimum": 0, "maximum": 1 }, - "surface": { "$ref": "#/$defs/biomeSurface" } + "enabled": { + "type": "boolean" + }, + "weight": { + "type": "number", + "minimum": 0 + }, + "similar_biomes": { + "$ref": "#/$defs/registryIds" + }, + "required_similar_biomes": { + "$ref": "#/$defs/registryIds" + }, + "min_temperature": { + "type": "number", + "minimum": -2, + "maximum": 2 + }, + "max_temperature": { + "type": "number", + "minimum": -2, + "maximum": 2 + }, + "min_downfall": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "max_downfall": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "surface": { + "$ref": "#/$defs/biomeSurface" + } }, "additionalProperties": true }, "biomePalette": { "type": "object", - "required": ["dimension", "enabled", "mode", "scope", "region_size", "coverage", "fallback_weight", "biomes"], + "required": [ + "dimension", + "enabled", + "mode", + "scope", + "region_size", + "coverage", + "fallback_weight", + "biomes" + ], "properties": { - "dimension": { "$ref": "#/$defs/registryId" }, - "enabled": { "type": "boolean" }, - "mode": { "enum": ["augment", "replace"] }, - "scope": { "enum": ["all", "minecraft_only", "selected_namespaces"] }, - "region_size": { "enum": ["tiny", "small", "average", "large", "huge"] }, - "coverage": { "type": "number", "minimum": 0, "maximum": 1 }, - "fallback_weight": { "type": "number", "minimum": 0 }, - "include_namespaces": { "type": "array", "uniqueItems": true, "items": { "type": "string", "pattern": "^[a-z][a-z0-9_.-]+$" } }, - "exclude_namespaces": { "type": "array", "uniqueItems": true, "items": { "type": "string", "pattern": "^[a-z][a-z0-9_.-]+$" } }, - "biomes": { "type": "object", "minProperties": 1, "additionalProperties": { "$ref": "#/$defs/biomePlacement" } } + "dimension": { + "$ref": "#/$defs/registryId" + }, + "enabled": { + "type": "boolean" + }, + "mode": { + "enum": [ + "augment", + "replace" + ] + }, + "scope": { + "enum": [ + "all", + "minecraft_only", + "selected_namespaces" + ] + }, + "region_size": { + "enum": [ + "tiny", + "small", + "average", + "large", + "huge" + ] + }, + "coverage": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "fallback_weight": { + "type": "number", + "minimum": 0 + }, + "include_namespaces": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^[a-z][a-z0-9_.-]+$" + } + }, + "exclude_namespaces": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^[a-z][a-z0-9_.-]+$" + } + }, + "biomes": { + "type": "object", + "minProperties": 1, + "additionalProperties": { + "$ref": "#/$defs/biomePlacement" + } + } }, "additionalProperties": true }, "dimensionMaterials": { "type": "object", - "required": ["dimension", "enabled"], + "required": [ + "dimension", + "enabled" + ], "properties": { - "dimension": { "$ref": "#/$defs/registryId" }, - "enabled": { "type": "boolean" }, - "default_fluid": { "$ref": "#/$defs/registryId" }, - "deep_aquifer_fluid": { "$ref": "#/$defs/registryId" }, - "deep_aquifer_max_y": { "type": "integer", "minimum": -2048, "maximum": 2048 }, - "snow_block": { "$ref": "#/$defs/registryId" }, - "ice_block": { "$ref": "#/$defs/registryId" } + "dimension": { + "$ref": "#/$defs/registryId" + }, + "enabled": { + "type": "boolean" + }, + "default_fluid": { + "$ref": "#/$defs/registryId" + }, + "deep_aquifer_fluid": { + "$ref": "#/$defs/registryId" + }, + "deep_aquifer_max_y": { + "type": "integer", + "minimum": -2048, + "maximum": 2048 + }, + "snow_block": { + "$ref": "#/$defs/registryId" + }, + "ice_block": { + "$ref": "#/$defs/registryId" + } }, "anyOf": [ - { "properties": { "enabled": { "const": false } }, "required": ["enabled"] }, - { "required": ["default_fluid"] }, - { "required": ["deep_aquifer_fluid"] }, - { "required": ["snow_block"] }, - { "required": ["ice_block"] } + { + "properties": { + "enabled": { + "const": false + } + }, + "required": [ + "enabled" + ] + }, + { + "required": [ + "default_fluid" + ] + }, + { + "required": [ + "deep_aquifer_fluid" + ] + }, + { + "required": [ + "snow_block" + ] + }, + { + "required": [ + "ice_block" + ] + } ], "additionalProperties": true }, "flatBedrock": { "type": "object", "properties": { - "enabled": { "type": "boolean" }, - "retrogen": { "type": "boolean" }, - "layers": { "type": "integer", "minimum": 1, "maximum": 5 }, - "dimensions": { "$ref": "#/$defs/registryIds" } + "enabled": { + "type": "boolean" + }, + "retrogen": { + "type": "boolean" + }, + "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" + }, + "metadata": { + "$ref": "#/$defs/metadata" + }, + "family": { + "$ref": "#/$defs/family" + } + } + } + } } } } diff --git a/gradle.properties b/gradle.properties index 58fe7950..97836617 100644 --- a/gradle.properties +++ b/gradle.properties @@ -30,7 +30,7 @@ mod_vendor=Minecraft Mod Development mod_license=LGPL-2.1 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_version=4.1.6.110021 +mod_version=4.1.7.110021 mod_group=zone.moddev.mc.orespawn mod_authors=SkyBlade1978, dshadowwolf, the MMD Team mod_description=Configurable, provider-driven terrain, ore, and deposit generation. diff --git a/gradle/ide/eclipse.gradle b/gradle/ide/eclipse.gradle index 51f50f01..806fbda2 100644 --- a/gradle/ide/eclipse.gradle +++ b/gradle/ide/eclipse.gradle @@ -157,8 +157,8 @@ tasks.register('verifyEclipseProductionClasspath') { } File eclipseResources = file('bin/main') List trackedDocs = trackedDocumentationFiles() - if (trackedDocs.size() != 20) { - throw new GradleException("Expected 20 tracked documentation files, found ${trackedDocs.size()}") + if (trackedDocs.size() != 22) { + throw new GradleException("Expected 22 tracked documentation files, found ${trackedDocs.size()}") } trackedDocs.each { File source -> String relative = documentationRelativePath(source) diff --git a/gradle/release/artifacts.gradle b/gradle/release/artifacts.gradle index 9f61621d..32f2946a 100644 --- a/gradle/release/artifacts.gradle +++ b/gradle/release/artifacts.gradle @@ -77,7 +77,7 @@ tasks.register('verifyReleaseConfiguration') { description = 'Validates the target-qualified release, API, schemas, reports, and publishing identity.' doLast { - if (project.mod_version != '4.1.6.110021' + if (project.mod_version != '4.1.7.110021' || project.mod_group != expectedMavenGroup) { throw new GradleException("Unexpected OreSpawn release version: ${project.mod_version}") } @@ -106,8 +106,8 @@ tasks.register('verifyReleaseConfiguration') { 'src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyOs3ProfileMigration.java', 'README.md', 'CHANGELOG.txt' ].each { path -> - if (!file(path).getText('UTF-8').contains('4.1.6.110021')) { - throw new GradleException("Authoritative release location does not contain 4.1.6.110021: ${path}") + if (!file(path).getText('UTF-8').contains('4.1.7.110021')) { + throw new GradleException("Authoritative release location does not contain 4.1.7.110021: ${path}") } } if (!file('docs/API.md').getText('UTF-8').contains('orespawn@[4.0.6,5.0.0)')) { @@ -124,8 +124,8 @@ tasks.register('verifyReleaseConfiguration') { throw new GradleException('Global/world schema versions must remain 8/7') } def providerSchema = new JsonSlurper().parse(file('docs/schemas/orespawn-provider.schema.json')) - if (!(providerSchema.properties.schema_version.enum as List).containsAll([4, 5])) { - throw new GradleException('Provider schema must support schema versions 4 and 5') + if (!(providerSchema.properties.schema_version.enum as List).containsAll([4, 5, 6])) { + throw new GradleException('Provider schema must support schema versions 4, 5 and 6') } } } @@ -204,8 +204,8 @@ tasks.register('verifyReleaseArtifacts') { } } List trackedDocs = trackedDocumentationFiles() - if (trackedDocs.size() != 20) { - throw new GradleException("Expected 20 tracked documentation files, found ${trackedDocs.size()}") + if (trackedDocs.size() != 22) { + throw new GradleException("Expected 22 tracked documentation files, found ${trackedDocs.size()}") } trackedDocs.each { File source -> String relative = documentationRelativePath(source) diff --git a/src/main/java/com/mcmoddev/orespawn/compat/LegacyOs3Bridge.java b/src/main/java/com/mcmoddev/orespawn/compat/LegacyOs3Bridge.java index 29c0d244..8c830df1 100644 --- a/src/main/java/com/mcmoddev/orespawn/compat/LegacyOs3Bridge.java +++ b/src/main/java/com/mcmoddev/orespawn/compat/LegacyOs3Bridge.java @@ -1029,7 +1029,7 @@ private static void writeHumanUpgradeReport(Path destination) throws IOException } } List lines = new ArrayList<>(); - lines.add("OreSpawn 4.1.6.110021 Upgrade Report"); + lines.add("OreSpawn 4.1.7.110021 Upgrade Report"); lines.add("================================"); lines.add(""); lines.add("RESULT: Legacy OreSpawn configuration was consumed and translated for OS4."); diff --git a/src/main/java/cyano/orespawn/OreSpawn.java b/src/main/java/cyano/orespawn/OreSpawn.java index 69af7ac5..9948f4de 100644 --- a/src/main/java/cyano/orespawn/OreSpawn.java +++ b/src/main/java/cyano/orespawn/OreSpawn.java @@ -19,7 +19,7 @@ public class OreSpawn { public static OreSpawn INSTANCE; public static final String MODID = "orespawn"; public static final String NAME = "OreSpawn"; - public static final String VERSION = "4.1.6.110021"; + public static final String VERSION = "4.1.7.110021"; public static final List oreSpawnConfigFiles = new ArrayList<>(); public static final List additionalStoneBlocks = new ArrayList<>(); public static boolean disableVanillaOreGen; diff --git a/src/main/java/zone/moddev/mc/orespawn/OreSpawn.java b/src/main/java/zone/moddev/mc/orespawn/OreSpawn.java index e9a0f50b..050c2823 100644 --- a/src/main/java/zone/moddev/mc/orespawn/OreSpawn.java +++ b/src/main/java/zone/moddev/mc/orespawn/OreSpawn.java @@ -52,7 +52,7 @@ public class OreSpawn { public static final String MODID = "orespawn"; public static final String NAME = "OreSpawn"; - public static final String VERSION = "4.1.6.110021"; + public static final String VERSION = "4.1.7.110021"; private static final Logger LOGGER = LogManager.getLogger(); @@ -136,6 +136,7 @@ public void serverStarting(FMLServerStartingEvent event) { @EventHandler public void serverStopped(FMLServerStoppedEvent event) { + zone.moddev.mc.orespawn.commands.admin.AdminJobs.shutdown(); WorldGeologyProfileManager.onServerStopped(event); OreSpawnWorldGenerator.INSTANCE.clear(); } @@ -220,6 +221,9 @@ private static final class RuntimeEvents { @SubscribeEvent public void worldLoad(WorldEvent.Load event) { WorldGeologyProfileManager.onWorldLoad(event); } + @SubscribeEvent public void diagnosticWorldUnload(WorldEvent.Unload event) { + zone.moddev.mc.orespawn.commands.admin.AdminJobs.unload(event.getWorld()); + } @SubscribeEvent public void chunkLoad(ChunkEvent.Load event) { WorldMaterialWeather.onChunkLoad(event); } @@ -234,6 +238,10 @@ private static final class RuntimeEvents { } @SubscribeEvent public void serverTick(TickEvent.ServerTickEvent event) { OreRetrogenManager.onServerTick(event); + if (event.phase == TickEvent.Phase.END) { + zone.moddev.mc.orespawn.commands.admin.AdminJobs.pollExports(); + zone.moddev.mc.orespawn.commands.admin.AdminJobs.tick(); + } } } 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..abd6aac0 --- /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.state.IBlockState; +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 IBlockState state; + private final Optional family; + public FormationMaterial(IBlockState state, GeologyFamily family) { + this.state = java.util.Objects.requireNonNull(state); + this.family = Optional.ofNullable(family); + } + public IBlockState 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..a76bbbd2 --- /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.state.IBlockState; + +/** 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 IBlockState parent; + private final FormationMaterial material; + public FormationSample(ResourceLocation id, int revision, IBlockState 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 IBlockState 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 d17b4b3d..d9b61e4f 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(); IBlockState rockAt(int y); Optional familyAt(int y); + /** Natural formation provenance, excluding later ore, mine and marker writes. */ + 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 3c452b5d..46fe8772 100644 --- a/src/main/java/zone/moddev/mc/orespawn/api/OreSpawnApi.java +++ b/src/main/java/zone/moddev/mc/orespawn/api/OreSpawnApi.java @@ -21,6 +21,15 @@ public final class OreSpawnApi { private OreSpawnApi() { } + /** + * True only during a vanilla granite/diorite/andesite patch pass in a world + * with active natural formations. Natural formation blocks may decline that + * decorative replacement while remaining normal hosts for metal ores. + */ + public static boolean isNativeStonePatchPass() { + return zone.moddev.mc.orespawn.worldgen.NativeStonePatchContext.active(); + } + /** * Enqueues a provider before OreSpawn freezes discovery. Call this during * the provider mod's Forge initialization phase. 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 47579873..ac5432f3 100644 --- a/src/main/java/zone/moddev/mc/orespawn/api/OreSpawnGeologySampler.java +++ b/src/main/java/zone/moddev/mc/orespawn/api/OreSpawnGeologySampler.java @@ -65,7 +65,8 @@ public GeologyColumn sampleColumn(int blockX, int blockZ, int surfaceY) { 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..7a3b6f0c --- /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.state.IBlockState 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..63206a98 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/api/RockFormationRegistry.java @@ -0,0 +1,24 @@ +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); + } +} 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 6d7d5aa4..11e9337f 100644 --- a/src/main/java/zone/moddev/mc/orespawn/api/WorldgenProvider.java +++ b/src/main/java/zone/moddev/mc/orespawn/api/WorldgenProvider.java @@ -62,7 +62,7 @@ public boolean mergeNewEntriesIntoExistingWorlds() { return mergeNewEntriesIntoExistingWorlds; } - /** Returns a defensive JSON representation matching provider schema 5. */ + /** Returns defensive provider JSON; formation contributors use schema 6. */ public JsonObject toJson() { return JsonCopies.copy(definition); } @@ -84,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); @@ -223,7 +233,7 @@ 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"); @@ -236,8 +246,9 @@ public WorldgenProvider build() { 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", @@ -251,6 +262,11 @@ public WorldgenProvider build() { root.add("biome_palettes", object(biomePalettes)); root.add("dimension_materials", object(dimensionMaterials)); root.add("templates", object(templates)); + 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); } @@ -1351,6 +1367,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) { @@ -1360,6 +1377,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); } @@ -1381,6 +1399,7 @@ public JsonObject toJson() { 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; } @@ -1392,6 +1411,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"); @@ -1399,6 +1419,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; } 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 fd5d3d3f..674602f4 100644 --- a/src/main/java/zone/moddev/mc/orespawn/commands/OreSpawnCommands.java +++ b/src/main/java/zone/moddev/mc/orespawn/commands/OreSpawnCommands.java @@ -32,18 +32,35 @@ private OreSpawnCommands() { public static void register(FMLServerStartingEvent event) { event.registerServerCommand(new RootCommand()); + for (String alias : new String[]{"clearchunk", "clearchunks"}) { + if (!event.getServer().getCommandManager().getCommands().containsKey(alias)) event.registerServerCommand(new ClearAlias(alias)); + } + } + + private static final class ClearAlias extends CommandBase { + private final String name; + ClearAlias(String name) { this.name = name; } + @Override public String getName() { return name; } + @Override public String getUsage(ICommandSender sender) { return "/orespawn clearchunk [confirm token]"; } + @Override public int getRequiredPermissionLevel() { return 4; } + @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { + String[] delegated = new String[args.length + 1]; delegated[0] = "clearchunk"; + System.arraycopy(args, 0, delegated, 1, args.length); + zone.moddev.mc.orespawn.commands.admin.AdminCommands.handle(server, sender, delegated); + } } private static final class RootCommand extends CommandBase { @Override public String getName() { return "orespawn"; } @Override public String getUsage(ICommandSender sender) { - return "/orespawn "; + return "/orespawn help"; } @Override public int getRequiredPermissionLevel() { return 0; } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { + if (zone.moddev.mc.orespawn.commands.admin.AdminCommands.handle(server, sender, args)) return; String action = args.length == 0 ? "status" : args[0]; if ("status".equals(action)) { status(sender); @@ -62,6 +79,24 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args } } + @Override public List getTabCompletions(MinecraftServer server, ICommandSender sender, + String[] args, net.minecraft.util.math.BlockPos target) { + if (args.length == 1) { + List names = new ArrayList<>(); + for (String name : zone.moddev.mc.orespawn.commands.admin.AdminCommands.ACTIONS) + if ("status".equals(name) || sender.canUseCommand("clearchunk".equals(name) || "undo".equals(name) ? 4 : 2, "orespawn")) names.add(name); + return getListOfStringsMatchingLastWord(args, names); + } + if (!sender.canUseCommand(2, "orespawn")) return Collections.emptyList(); + if (args.length == 2 && "explain".equals(args[0])) { + List rules = new ArrayList<>(); + com.google.gson.JsonObject root = WorldGeologyProfileManager.activeProfile().toJson(); + if (root.has("ores")) root.getAsJsonObject("ores").entrySet().forEach(e -> rules.add(e.getKey())); + return getListOfStringsMatchingLastWord(args, rules); + } + return getListOfStringsMatchingLastWord(args, "--dimension", "--center", "--y", "--block", "preview", "confirm", "cancel", "status", "verbose", "backups"); + } + private static void requireAdmin(ICommandSender sender) throws CommandException { if (!sender.canUseCommand(2, "orespawn")) throw new CommandException("commands.generic.permission"); } 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..d3e692e5 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminCommands.java @@ -0,0 +1,233 @@ +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.command.CommandException; +import net.minecraft.command.ICommandSender; +import net.minecraft.entity.player.EntityPlayerMP; +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.TextComponentTranslation; +import net.minecraft.world.WorldServer; +import net.minecraft.world.biome.Biome; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.common.DimensionManager; +import net.minecraftforge.fml.common.registry.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, ICommandSender sender, String[] args) throws CommandException { + 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 CommandException("commands.generic.permission"); + if (("clearchunk".equals(action) || "undo".equals(action)) && !sender.canUseCommand(4, "orespawn")) + throw new CommandException("commands.generic.permission"); + try { + if ("help".equals(action)) { + for (String key : new String[]{"help", "options", "safety", "scope"}) sender.sendMessage(new TextComponentTranslation("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 TextComponentTranslation("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 TextComponentTranslation("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 TextComponentTranslation("commands.orespawn.preview_started")); + } + return true; + } catch (RuntimeException e) { throw new CommandException("commands.orespawn.failed", e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()); } + } + + private static void started(ICommandSender sender, String id) { AdminFeedback.started(sender, id); } + + private static void data(ICommandSender 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 TextComponentTranslation("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()) { + net.minecraftforge.fml.common.ModContainer mod = net.minecraftforge.fml.common.Loader.instance().getIndexedModList().get(provider); + versions.addProperty(provider, mod == null ? "provider ID is not a loaded mod ID" : mod.getVersion()); + } + 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 = selected.world.getChunkProvider().getLoadedChunk(selected.cx, selected.cz); + JsonObject data = new JsonObject(); + data.addProperty("dimension", WorldIds.dimension(selected.world).toString()); + data.addProperty("dimension_id", selected.world.provider.getDimension()); + 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.isTerrainPopulated()); data.addProperty("light_populated", chunk.isLightPopulated()); + 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 = chunk.getHeightValue(i & 15, i >>> 4); low = Math.min(low, height); high = Math.max(high, height); + Biome biome = Biome.getBiome(chunk.getBiomeArray()[i] & 255); + 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 = Biome.getBiome(chunk.getBiomeArray()[136] & 255); + 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; + } + + static final class Selection { + WorldServer world; + BlockPos block; + int cx, cz, minY, maxY; + String filter = ""; + final List words = new ArrayList<>(); + Selection(ICommandSender sender, String[] args) { + world = sender instanceof EntityPlayerMP ? (WorldServer) sender.getEntityWorld() : DimensionManager.getWorld(0); + boolean center = false; + for (int i = 0; i < args.length; i++) { + String value = args[i]; + if ("--dimension".equals(value)) { + String id = args[++i]; WorldServer found = null; + for (WorldServer loaded : DimensionManager.getWorlds()) if (String.valueOf(loaded.provider.getDimension()).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 instanceof EntityPlayerMP && 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()) { + String[] parts = filter.split("@", -1); + if (parts.length > 2 || !ForgeRegistries.BLOCKS.containsKey(new ResourceLocation(parts[0]))) throw new IllegalArgumentException("Unknown block filter"); + if (parts.length == 2) integer(parts[1], 0, 15); + } + } + 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/AdminFeedback.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminFeedback.java new file mode 100644 index 00000000..22f9f02d --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminFeedback.java @@ -0,0 +1,94 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import java.util.ArrayList; +import java.util.List; +import net.minecraft.command.ICommandSender; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.util.text.TextComponentTranslation; +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 TextComponentTranslation("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 TextComponentTranslation("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 TextComponentTranslation("commands.orespawn.preview_title"); + title.getStyle().setColor(TextFormatting.YELLOW).setBold(true); + lines.add(title); + lines.add(new TextComponentTranslation("commands.orespawn.preview_location", dimensionLabel(dimension), cx, cz, minY, maxY)); + lines.add(new TextComponentTranslation("commands.orespawn." + (undo ? "preview_undo_counts" : "preview_clear_counts"), changes, preserved)); + ITextComponent warning = new TextComponentTranslation("commands.orespawn." + (undo ? "preview_undo_warning" : "preview_warning")); + warning.getStyle().setColor(TextFormatting.YELLOW); + lines.add(warning); + ITextComponent expiry = new TextComponentTranslation("commands.orespawn.preview_expiry"); + expiry.getStyle().setColor(TextFormatting.GRAY); + lines.add(expiry); + ITextComponent buttons = new TextComponentString(""); + 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(ICommandSender 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(ICommandSender sender, String id) { + sender.sendMessage(new TextComponentTranslation("commands.orespawn.started", details(id))); + consoleCommand(sender, "/orespawn jobs " + id); + } + + static void completed(ICommandSender sender, String id, int edited, boolean undo, String backupId, String dimension) { + if (undo) sender.sendMessage(new TextComponentTranslation("commands.orespawn.complete_undo", edited, details(id))); + else { + String command = "/orespawn undo " + backupId + " --dimension " + dimension; + sender.sendMessage(new TextComponentTranslation("commands.orespawn.complete_clear", edited, + action("undo_preview", command, TextFormatting.AQUA), details(id))); + consoleCommand(sender, command); + } + } + + static void result(ICommandSender sender, String id, String status, String message) { + String shortMessage = message.length() > 1024 ? message.substring(0, 1021) + "..." : message; + sender.sendMessage(new TextComponentTranslation("commands.orespawn.job_result", details(id), status, shortMessage)); + consoleCommand(sender, "/orespawn jobs " + id); + } + + private static void consoleCommand(ICommandSender sender, String command) { + // Server consoles cannot click chat, so they still need a copyable command. + if (!(sender.getCommandSenderEntity() instanceof EntityPlayer)) sender.sendMessage(new TextComponentString(command)); + } + + private static ITextComponent dimensionLabel(String dimension) { + if ("minecraft:overworld".equals(dimension) || "minecraft:the_nether".equals(dimension) || "minecraft:the_end".equals(dimension)) + return new TextComponentTranslation("value.orespawn.dimension." + dimension.substring("minecraft:".length())); + return new TextComponentString(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..1bfc715e --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/AdminJobs.java @@ -0,0 +1,533 @@ +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.state.IBlockState; +import net.minecraft.command.ICommandSender; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Blocks; +import net.minecraft.network.play.server.SPacketChunkData; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.util.text.TextComponentTranslation; +import net.minecraft.world.WorldServer; +import net.minecraft.world.biome.Biome; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.storage.ExtendedBlockStorage; +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(ICommandSender sender) { + return sender.getCommandSenderEntity() == null ? "console:" + sender.getName() + : sender.getCommandSenderEntity().getUniqueID().toString(); + } + + public static Path root(WorldServer world) { + return world.getMinecraftServer().worldServerForDimension(0).getSaveHandler().getWorldDirectory() + .toPath().toAbsolutePath().normalize().resolve("orespawn/diagnostics"); + } + + private static String worldKey(WorldServer world) { + return DiagnosticFiles.hash((root(world).toString() + ":" + world.getSeed()).getBytes(StandardCharsets.UTF_8)); + } + + public static String start(ICommandSender sender, WorldServer 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(ICommandSender sender, WorldServer 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(ICommandSender 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(ICommandSender 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(ICommandSender 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(ICommandSender sender, WorldServer world, int cx, int cz) { + if (!sender.canUseCommand(4, "orespawn")) throw new IllegalArgumentException("Permission level 4 is required"); + if (sender instanceof EntityPlayerMP && !((EntityPlayerMP) sender).isSpectator() + && !((EntityPlayerMP) sender).isCreative()) throw new IllegalArgumentException("Use Creative or Spectator mode"); + for (net.minecraft.entity.player.EntityPlayer player : world.playerEntities) + if ((player.getPosition().getX() >> 4) == cx && (player.getPosition().getZ() >> 4) == cz + && !player.isSpectator() && !player.capabilities.isCreativeMode) + 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(ICommandSender sender, WorldServer 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 TextComponentTranslation("commands.orespawn.report", id, directory.toString())); + return id; + } + + public static void listBackups(ICommandSender sender, WorldServer world) { + Path directory = root(world).resolve("backups"); + sender.sendMessage(new TextComponentTranslation("commands.orespawn.backups", directory.toString())); + } + + public static void cancel(ICommandSender 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() { + if (active == null) return; + Job job = active; + long deadline = System.nanoTime() + TICK_NANOS; + int visits = 0; + 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 WorldServer)) 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 WorldServer 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 ICommandSender sender; + final WorldServer world; + final long started = System.currentTimeMillis(); + final String profile; + final String filter; + 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, initialLightPopulated; + Chunk chunk; + MessageDigest digest; + EditJournal journal; + Future future; + + Job(ICommandSender sender, WorldServer 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.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(IBlockState 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 && world.getChunkProvider().getLoadedChunk(cx, cz) == chunk; } + + boolean step() throws Exception { + if (world.getMinecraftServer() != 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 (!world.checkLight(pos(journal.cells.get(lightCursor++).index))) throw new IOException("Lighting area unloaded; cleanup remains pending"); + return true; + } + lightingComplete = true; + chunk.setLightPopulated(initialLightPopulated); chunk.setChunkModified(); + finish(terminalStatus, terminalMessage == null ? "Changed " + edited + " cells; backup " + backupId : terminalMessage); return false; + } + if (scanningUndo) { + if (chunk == null) chunk = world.getChunkProvider().getLoadedChunk(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); + IBlockState 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.chunkXPos; cz = at.chunkZPos; + if (chunk == null) { + chunk = world.getChunkProvider().getLoadedChunk(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); + IBlockState 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 = Biome.getBiome(chunk.getBiomeArray()[((cursor >>> 4) & 15) * 16 + (cursor & 15)] & 255); + 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(IBlockState state) { + if (filter.isEmpty()) return true; + String[] parts = filter.split("@", -1); + if (!String.valueOf(net.minecraftforge.fml.common.registry.ForgeRegistries.BLOCKS.getKey(state.getBlock())).equals(parts[0])) return false; + return parts.length == 1 || state.getBlock().getMetaFromState(state) == Integer.parseInt(parts[1]); + } + + 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", "1.10.2"); + 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 = world.getChunkProvider().getLoadedChunk(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), false)) + 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; } + chunk.generateSkylightMap(); chunk.setChunkModified(); phase = "light"; return true; + } + EditJournal.Cell cell = journal.cells.get(editCursor++); + BlockPos pos = pos(cell.index); + IBlockState 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; + IBlockState replacement = resolved.computeIfAbsent(destination, DiagnosticStates::resolve); + ExtendedBlockStorage[] sections = chunk.getBlockStorageArray(); + int section = cell.index >>> 12; + if (sections[section] == null) sections[section] = new ExtendedBlockStorage(section << 4, !world.provider.hasNoSky()); + sections[section].set(pos.getX() & 15, pos.getY() & 15, pos.getZ() & 15, replacement); + if (!changed) initialLightPopulated = chunk.isLightPopulated(); + // Persist this before a possible unload, not only when cleanup detects it. + chunk.setLightPopulated(false); + changed = true; edited++; chunk.setChunkModified(); + 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; + chunk.generateSkylightMap(); chunk.setChunkModified(); + 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; + 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) { chunk.generateSkylightMap(); chunk.setLightPopulated(false); } + chunk.setChunkModified(); + List watchers = new ArrayList<>(); + for (net.minecraft.entity.player.EntityPlayer player : world.playerEntities) + if (player instanceof EntityPlayerMP && world.getPlayerChunkMap().isPlayerWatchingChunk((EntityPlayerMP) player, cx, cz)) + watchers.add((EntityPlayerMP) player); + if (!watchers.isEmpty()) { + SPacketChunkData packet = new SPacketChunkData(chunk, 65535); + watchers.forEach(player -> player.connection.sendPacket(packet)); + } + } + } + } + + 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/DiagnosticCatalog.java b/src/main/java/zone/moddev/mc/orespawn/commands/admin/DiagnosticCatalog.java new file mode 100644 index 00000000..60cce26c --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/DiagnosticCatalog.java @@ -0,0 +1,134 @@ +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.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.common.registry.ForgeRegistries; +import net.minecraftforge.oredict.OreDictionary; +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.LIT_REDSTONE_ORE, Blocks.QUARTZ_ORE}) ores.addAll(block.getBlockState().getValidStates()); + for (Block block : new Block[] {Blocks.STONE, Blocks.DIRT, Blocks.GRASS, Blocks.SAND, + Blocks.GRAVEL, Blocks.SANDSTONE, Blocks.RED_SANDSTONE, Blocks.NETHERRACK, + Blocks.END_STONE, Blocks.CLAY, Blocks.HARDENED_CLAY, Blocks.STAINED_HARDENED_CLAY, + Blocks.MYCELIUM, Blocks.SNOW, Blocks.SNOW_LAYER}) terrain.add(block); + backgroundFluids.add(Blocks.WATER); backgroundFluids.add(Blocks.FLOWING_WATER); + backgroundFluids.add(Blocks.LAVA); backgroundFluids.add(Blocks.FLOWING_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.FLOWING_WATER)) { + deposits.add(Blocks.WATER); deposits.add(Blocks.FLOWING_WATER); + } + if (deposits.contains(Blocks.LAVA) || deposits.contains(Blocks.FLOWING_LAVA)) { + deposits.add(Blocks.LAVA); deposits.add(Blocks.FLOWING_LAVA); + } + for (String name : OreDictionary.getOreNames()) { + if (!name.startsWith("ore") || name.length() <= 3) continue; + for (ItemStack stack : OreDictionary.getOres(name, false)) { + Block block = Block.getBlockFromItem(stack.getItem()); + if (block == Blocks.AIR) continue; + if (stack.getMetadata() == OreDictionary.WILDCARD_VALUE) ores.addAll(block.getBlockState().getValidStates()); + else try { ores.add(block.getStateFromMeta(stack.getMetadata())); } catch (RuntimeException ignored) { } + } + } + } + + public String category(IBlockState state) { + if (ores.contains(state)) return "ore"; + if (deposits.contains(state.getBlock())) return "fluid_deposit"; + if (state.getBlock() == Blocks.AIR) return "air"; + if (terrain.contains(state.getBlock()) || rocks.contains(state) || backgroundFluids.contains(state.getBlock())) return "terrain"; + return "unclassified"; + } + + public boolean removable(IBlockState 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; + target.add(block.getStateFromMeta(Math.max(0, Math.min(15, value)))); + } 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..5465d58a --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/commands/admin/DiagnosticStates.java @@ -0,0 +1,54 @@ +package zone.moddev.mc.orespawn.commands.admin; + +import java.util.Map; +import java.util.TreeMap; +import net.minecraft.block.Block; +import net.minecraft.block.properties.IProperty; +import net.minecraft.block.state.IBlockState; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.common.registry.ForgeRegistries; + +/** Registry names and properties remain meaningful when numeric IDs change. */ +public final class DiagnosticStates { + private DiagnosticStates() { } + + public static String key(IBlockState 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.getProperties().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 IBlockState 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); + IBlockState 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.getBlockState().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 IBlockState withProperty(IBlockState state, IProperty property, String value) { + com.google.common.base.Optional parsed = property.parseValue(value); + if (!parsed.isPresent()) throw new IllegalArgumentException("Invalid property value"); + return state.withProperty(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..2407be43 --- /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") || !"1.10.2".equals(header.get("minecraft_version").getAsString())) + throw new IllegalArgumentException("This journal is not a Minecraft 1.10.2 block snapshot"); + 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.10 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 2d4ea7a3..862550ea 100644 --- a/src/main/java/zone/moddev/mc/orespawn/documentation/DocumentationExporter.java +++ b/src/main/java/zone/moddev/mc/orespawn/documentation/DocumentationExporter.java @@ -28,6 +28,8 @@ public final class DocumentationExporter { "TEMPLATES.md", "DIMENSIONS.md", "BIOMES.md", + "ROCK_FORMATIONS.md", + "ADMIN_TOOLS.md", "MIGRATION.md", "TROUBLESHOOTING.md", "examples/examplemod-orespawn.json", 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..4843ff79 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/integration/RetainedProviderOreDefaults.java @@ -0,0 +1,184 @@ +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 type) { + // Imports name built-in patterns in full, but they still place ordinary veins. + // Only these known patterns share a channel; custom patterns stay independent. + if ("orespawn".equals(type.getResourceDomain())) { + switch (type.getResourcePath()) { + case "default": + case "vein": + case "normal_cloud": + case "precision": + case "clusters": + case "underfluids": + return STANDARD; + default: + break; + } + } + + return type; + } + + 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 07d83bb2..ba9eff11 100644 --- a/src/main/java/zone/moddev/mc/orespawn/integration/WorldgenIntegrationManager.java +++ b/src/main/java/zone/moddev/mc/orespawn/integration/WorldgenIntegrationManager.java @@ -60,7 +60,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<>(); @@ -274,6 +274,8 @@ private static boolean mergeProviderDefinitions(JsonObject target, boolean exist changed = true; } for (String sectionName : MERGED_SECTIONS) { + // Formations are a new-world substrate contract, never a provider migration. + if (existingWorld && "rock_formations".equals(sectionName)) continue; String targetName = "biome_rules".equals(sectionName) ? "biomes" : sectionName; JsonObject targetSection = object(target, targetName); JsonObject providerSection = provider.section(sectionName); @@ -291,6 +293,14 @@ private static boolean mergeProviderDefinitions(JsonObject target, boolean exist 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); } @@ -379,12 +389,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()).getResourceDomain(); + 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); @@ -552,7 +584,7 @@ private static JsonObject installedProviderRoot(String providerId) { 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 != 2 && schema != 3 && schema != 4 && schema != 5 && schema != 6) { throw new JsonSyntaxException("unsupported schema_version"); } if (!providerId.equals(string(root, "provider_modid", ""))) { @@ -569,7 +601,7 @@ static void validateProvider(String providerId, JsonObject root) { if (schema == 1) { for (String section : new String[] { "rocks", "geomes", "biome_rules", "terrain_dimensions", "fluid_deposits", "biome_palettes", - "dimension_materials", "templates", "profile_defaults" }) { + "dimension_materials", "templates", "profile_defaults", "rock_formations" }) { if (root.has(section)) { throw new JsonSyntaxException("provider schema 1 is ore-only; found " + section); } @@ -586,6 +618,7 @@ static void validateProvider(String providerId, JsonObject root) { } int entries = 0; + if (schema < 6 && root.has("rock_formations")) throw new JsonSyntaxException("rock_formations requires provider schema 6"); for (String section : MERGED_SECTIONS) { JsonObject values = optionalObject(root, section); entries += values.entrySet().size(); @@ -614,6 +647,19 @@ 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(formation.get("type").getAsString()); + if (integer(formation, "algorithm_revision", 0) < 1) + throw new JsonSyntaxException("Formation requires algorithm_revision: " + entry.getKey()); + for (Entry material : requiredObject(formation, "materials").entrySet()) { + JsonObject m = material.getValue().getAsJsonObject(); + Block output = block(string(m, "block", "")); + if (output == null || output == Blocks.AIR || output == Blocks.BEDROCK) + throw new JsonSyntaxException("Unknown formation output " + material.getKey()); + validateMetadata(m, "metadata", entry.getKey()); + if (m.has("family")) RockFamily.fromConfigName(m.get("family").getAsString()); + } } } } @@ -1033,7 +1079,8 @@ private static void readTemplates(ProviderDefinition provider) { + id.getResourcePath() + ".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))); } } @@ -1245,9 +1292,15 @@ 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) { + this(id,nameKey,descriptionKey,profile,available,autoSelect,autoSelectPriority,false); + } + TemplateDefinition(ResourceLocation id, String nameKey, String descriptionKey, + JsonObject profile, boolean available, boolean autoSelect, int autoSelectPriority, + boolean preserveFormationOverrides) { this.id = id; this.nameKey = nameKey; this.descriptionKey = descriptionKey; @@ -1255,6 +1308,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/worldgen/BakedGeomeConfig.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/BakedGeomeConfig.java index b67a535b..84399bc2 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/BakedGeomeConfig.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/BakedGeomeConfig.java @@ -84,6 +84,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); @@ -229,12 +236,15 @@ RockFamily familyOf(IBlockState state) { } public IBlockState[] 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 (IBlockState state : rockStates) { + for (IBlockState state : available) { RockFamily family = rockFamilies.get(state.getBlock()); if (family != null && (mask & (1 << family.ordinal())) != 0) { count++; @@ -242,7 +252,7 @@ public IBlockState[] statesForFamily(RockFamily... families) { } IBlockState[] result = new IBlockState[count]; int index = 0; - for (IBlockState state : rockStates) { + for (IBlockState state : available) { RockFamily family = rockFamilies.get(state.getBlock()); if (family != null && (mask & (1 << family.ordinal())) != 0) { result[index++] = state; @@ -255,6 +265,8 @@ void addRockBlocks(Set target) { for (IBlockState 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() { 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..62afcd39 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/BuiltinRockFormation.java @@ -0,0 +1,149 @@ +package zone.moddev.mc.orespawn.worldgen; + +import com.google.gson.*; +import java.util.*; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.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 (!Block.REGISTRY.containsKey(id)) throw new IllegalArgumentException("Missing formation material: " + id); + Block block = Block.REGISTRY.getObject(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(block.getStateFromMeta(integer(m, "metadata", 0)), 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 (Block.REGISTRY.containsKey(key)) into.add(Block.REGISTRY.getObject(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 IBlockState weatherParent = type == 5 ? c.base().rockAt(surface - 18) : null; + final boolean weatherable = type == 5 && (weatherParents.contains(weatherParent.getBlock()) + || weatherParent.equals(Blocks.STONE.getStateFromMeta(1))); + return new RockFormationColumn() { + @Override public FormationMaterial at(int y) { + if (y < 5 || y > surface - 3) return null; + IBlockState 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 IBlockState 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/GeomeConfig.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/GeomeConfig.java index 1bb7f283..01e20add 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/GeomeConfig.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/GeomeConfig.java @@ -123,12 +123,14 @@ private static BakedGeomeConfig bakeGlobal(boolean chooseOreSourceDefaults) { 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/LegacyMineralogyProfileMigration.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyMineralogyProfileMigration.java index 4befc702..f51474cf 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyMineralogyProfileMigration.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyMineralogyProfileMigration.java @@ -125,7 +125,7 @@ private static void writeUpgradeReport(Path worldRoot, Path configDirectory, } List lines = new ArrayList<>(); - lines.add("OreSpawn 4.1.6.110021 Upgrade Report"); + lines.add("OreSpawn 4.1.7.110021 Upgrade Report"); lines.add("================================"); lines.add(""); lines.add("RESULT: Existing Mineralogy " + mineralogyVersion diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyOs3ProfileMigration.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyOs3ProfileMigration.java index 985b3550..502d74a3 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyOs3ProfileMigration.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/LegacyOs3ProfileMigration.java @@ -65,7 +65,7 @@ private static void writeInitialUpgradeReport(Path configDirectory, boolean forceRetrogen, boolean flatBedrock, boolean retrogenBedrock, int bedrockLayers) throws IOException { String newline = System.lineSeparator(); - String text = "OreSpawn 4.1.6.110021 Upgrade Report" + newline + String text = "OreSpawn 4.1.7.110021 Upgrade Report" + newline + "================================" + newline + newline + "RESULT: Legacy OreSpawn settings were imported into the OS4 profile." + newline + "- Manage vanilla ores: " + manageVanilla + newline 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..a0c2bd5a --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/NativeStonePatchContext.java @@ -0,0 +1,26 @@ +package zone.moddev.mc.orespawn.worldgen; + +import net.minecraftforge.event.terraingen.OreGenEvent.GenerateMinable.EventType; +import java.util.ArrayDeque; +import java.util.Deque; + +/** Server-thread context for vanilla's non-metal stone-patch passes only. */ +public final class NativeStonePatchContext { + private static final ThreadLocal ACTIVE = new ThreadLocal<>(); + private static final ThreadLocal> FRAMES = ThreadLocal.withInitial(ArrayDeque::new); + private NativeStonePatchContext() { } + + static void select(boolean formationsEnabled, EventType type) { + if (formationsEnabled && (type == EventType.GRANITE || type == EventType.DIORITE || type == EventType.ANDESITE)) + ACTIVE.set(Boolean.TRUE); + else reset(); + } + public static boolean active() { return Boolean.TRUE.equals(ACTIVE.get()); } + static void reset() { ACTIVE.set(Boolean.FALSE); } + static void begin() { FRAMES.get().push(active()); reset(); } + static void end() { + Deque frames = FRAMES.get(); + ACTIVE.set(frames.isEmpty() ? Boolean.FALSE : frames.pop()); + } + static void clear() { ACTIVE.remove(); FRAMES.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..f782bdb8 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/NaturalFormations.java @@ -0,0 +1,158 @@ +package zone.moddev.mc.orespawn.worldgen; + +import java.util.*; +import com.google.gson.*; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.WorldServer; +import net.minecraft.world.biome.Biome; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.gen.structure.MapGenStructureData; +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 List rules = Collections.emptyList(); + private static 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; + CompiledRockFormation compiler = RockFormationRegistry.compile(new ResourceLocation(def.get("type").getAsString()), + 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 = Block.REGISTRY.getObject(new ResourceLocation(m.get("block").getAsString())); + FormationMaterial material = new FormationMaterial(block.getStateFromMeta(BuiltinRockFormation.integer(m, "metadata", 0)), + 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; + SURFACES.clear(); + } + public static Collection materials() { return materials.values(); } + static boolean enabledForPlacement(net.minecraft.world.World world) { + return !rules.isEmpty() && world instanceof WorldServer + && NaturalTerrainSurface.nativeGenerator((WorldServer) world) != null + && zone.moddev.mc.orespawn.OreSpawnConfig.placeOreSpawnRock() + && WorldGeologyProfileManager.activeProfile().geologyMode() + == zone.moddev.mc.orespawn.OreSpawnConfig.GeologyMode.GEOME; + } + static FormationMaterial material(IBlockState state) { return materials.get(state); } + public static GeologyColumn wrap(WorldServer 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.getTemperature(), biome.getRainfall(), () -> 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(WorldServer world, Chunk chunk, BakedTerrainDimension terrain) { + if (!enabledForPlacement(world)) return; + GeologySampler sampler = OreSpawnApi.createSampler(world).get(); + List boxes = structures(world, chunk.xPosition, chunk.zPosition); + 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.xPosition * 16 + dx, z = chunk.zPosition * 16 + dz; + GeologyColumn column = sampler.sampleColumn(x, z, chunk.getHeightValue(dx, dz) - 1); + if (!(column instanceof Column)) continue; + GeologyColumn country = column; + while (country instanceof Column) country = ((Column) country).base; + for (int y = 5; y < chunk.getHeightValue(dx, dz); y++) { + IBlockState target = column.rockAt(y), parent = country.rockAt(y); + if (target.equals(parent) || protectedAt(boxes, x, y, z)) continue; + pos.setPos(x, y, z); + IBlockState current = chunk.getBlockState(pos); + // Native stone patches may have spilled across this boundary + // before this chunk's early pass. They are country rock, not a + // protected metal ore; the same planned substrate wins either way. + if ((!current.equals(parent) && !nativeStoneVariant(current)) + || chunk.getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK) != null) continue; + chunk.setBlockState(pos, target); + changed = true; + } + } + if (changed) ChunkAccessCompat.markChanged(chunk); + } + static boolean nativeStoneVariant(IBlockState state) { + if (state.getBlock() != net.minecraft.init.Blocks.STONE) return false; + int metadata = net.minecraft.init.Blocks.STONE.getMetaFromState(state); + return metadata == 0 || metadata == 1 || metadata == 3 || metadata == 5; + } + private static List structures(WorldServer world, int cx, int cz) { + List result = new ArrayList<>(); + for (String name : new String[]{"Mineshaft", "Village", "Stronghold", "Temple", "Monument"}) { + MapGenStructureData data = (MapGenStructureData) world.getMapStorage().getOrLoadData(MapGenStructureData.class, name); + if (data == null) continue; + NBTTagCompound root = data.getTagCompound(); + for (String key : root.getKeySet()) { + int[] b = root.getCompoundTag(key).getIntArray("BB"); + if (b.length == 6 && b[0] <= cx * 16 + 15 && b[3] >= cx * 16 && b[2] <= cz * 16 + 15 && b[5] >= cz * 16) result.add(b); + } + } + return result; + } + private static boolean protectedAt(List boxes, int x, int y, int z) { + for (int[] b : boxes) if (x >= b[0] && x <= b[3] && y >= b[1] && y <= b[4] && z >= b[2] && z <= b[5]) 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 IBlockState 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); + IBlockState 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..c4e71b9b --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/NaturalTerrainSurface.java @@ -0,0 +1,54 @@ +package zone.moddev.mc.orespawn.worldgen; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.lang.ref.WeakReference; +import net.minecraft.block.state.IBlockState; +import net.minecraft.block.material.Material; +import net.minecraft.world.WorldServer; +import net.minecraft.world.chunk.ChunkPrimer; +import net.minecraft.world.gen.ChunkProviderOverworld; + +/** Bounded height cache; never calls provideChunk or generates a neighbouring world chunk. */ +final class NaturalTerrainSurface { + private final WeakReference world; + private final Map cache = new LinkedHashMap(128, .75F, true) { + @Override protected boolean removeEldestEntry(Map.Entry e) { return size() > 512; } + }; + NaturalTerrainSurface(WorldServer world) { this.world = new WeakReference<>(world); } + + static ChunkProviderOverworld nativeGenerator(WorldServer world) { + net.minecraft.world.chunk.IChunkGenerator generator = world.getChunkProvider().chunkGenerator; + // Amplified, Large Biomes and Customized use this same implementation. + // Subclasses may change population order or lake geometry, so exclude them. + return generator != null && generator.getClass() == ChunkProviderOverworld.class + ? (ChunkProviderOverworld) generator : null; + } + + synchronized int at(int x, int z) { + WorldServer world = this.world.get(); + if (world == null) return -1; + ChunkProviderOverworld generator = nativeGenerator(world); + if (generator == null) return -1; + int cx = x >> 4, cz = z >> 4; + long key = ((long) cx << 32) ^ (cz & 0xffffffffL); + short[] heights = cache.get(key); + if (heights == null) { + heights = new short[256]; + ChunkPrimer primer = new ChunkPrimer(); + generator.setBlocksInChunk(cx, cz, primer); + for (int dx = 0; dx < 16; dx++) for (int dz = 0; dz < 16; dz++) { + int top = -1; + for (int y = 255; y >= 0; y--) { + IBlockState state = primer.getBlockState(dx, y, dz); + if (state.getMaterial() == Material.AIR) continue; + top = state.getMaterial().isLiquid() ? -1 : y; + break; + } + heights[dz * 16 + dx] = (short) top; + } + cache.put(key, heights); + } + return heights[(z & 15) * 16 + (x & 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 f8c998d4..6f93374b 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/OreRetrogenManager.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/OreRetrogenManager.java @@ -1,16 +1,16 @@ 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.NBTTagCompound; -import net.minecraft.util.ResourceLocation; import net.minecraft.world.WorldServer; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.chunk.Chunk; -import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.event.world.ChunkDataEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; /** Bounded, marker-based ore and flat-bedrock retrogen with no reflected internals. */ public final class OreRetrogenManager { @@ -18,7 +18,8 @@ public final class OreRetrogenManager { 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() { @@ -33,23 +34,30 @@ public static void refreshWorldConfig() { public static void onChunkLoad(ChunkDataEvent.Load event) { Settings current = settings; - if ((!current.oreEnabled && !current.bedrockEnabled) - || !(event.getWorld() instanceof WorldServer) + if (!(event.getWorld() instanceof WorldServer) || !(event.getChunk() instanceof Chunk)) return; WorldServer level = (WorldServer) event.getWorld(); Chunk chunk = (Chunk) event.getChunk(); + ChunkKey key = new ChunkKey(level, chunkKey(ChunkAccessCompat.position(chunk))); NBTTagCompound marker = event.getData().getCompoundTag(ROOT_TAG); - if (!current.force && marker.getInteger(REVISION_TAG) == current.revision) return; - enqueue(level, chunk); + Integer revision = marker.hasKey(REVISION_TAG, 3) && marker.getInteger(REVISION_TAG) >= 0 + ? marker.getInteger(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 WorldServer)) return; WorldServer level = (WorldServer) event.getWorld(); - ChunkKey key = new ChunkKey(WorldIds.dimension(level), chunkKey(ChunkAccessCompat.position(event.getChunk()))); - if (!COMPLETE.contains(key)) return; + ChunkKey key = new ChunkKey(level, chunkKey(ChunkAccessCompat.position(event.getChunk()))); + Integer revision = COMPLETE.get(key); + if (revision == null) return; NBTTagCompound marker = event.getData().getCompoundTag(ROOT_TAG); - marker.setInteger(REVISION_TAG, settings.revision); + marker.setInteger(REVISION_TAG, revision); event.getData().setTag(ROOT_TAG, marker); } @@ -58,28 +66,37 @@ 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); - ChunkPos queuedPos = ChunkAccessCompat.position(queued.chunk); - if (queued.level.getChunkProvider().getLoadedChunk(queuedPos.chunkXPos, - queuedPos.chunkZPos) != 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 = ChunkAccessCompat.position(queued.chunk); + if (queued.level.getChunkProvider().getLoadedChunk( + queuedPos.chunkXPos, queuedPos.chunkZPos) != 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, chunkKey(chunk))); + static void markGenerated(WorldServer level, ChunkPos chunk) { + ChunkKey key = new ChunkKey(level, chunkKey(chunk)); + COMPLETE.put(key, settings.revision); + GENERATED_THIS_SESSION.add(key); } public static int queueLoadedArea(WorldServer level, ChunkPos center, int radius) { int count = 0; for (int x = center.chunkXPos - radius; x <= center.chunkXPos + radius; x++) { for (int z = center.chunkZPos - radius; z <= center.chunkZPos + radius; z++) { - Chunk loaded = level.getChunkProvider().getLoadedChunk(x, z); - if (loaded != null && enqueue(level, loaded)) count++; + Chunk chunk = level.getChunkProvider().getLoadedChunk(x, z); + if (chunk != null && enqueue(level, chunk, true)) count++; } } return count; @@ -89,17 +106,36 @@ 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(WorldServer 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(WorldServer level, Chunk chunk) { - ChunkKey key = new ChunkKey(WorldIds.dimension(level), chunkKey(ChunkAccessCompat.position(chunk))); + private static boolean enqueue(WorldServer level, Chunk chunk, boolean explicit) { + ChunkKey key = new ChunkKey(level, chunkKey(ChunkAccessCompat.position(chunk))); if (!QUEUED.add(key)) return false; - QUEUE.add(new QueuedChunk(level, chunk, key)); + QUEUE.add(new QueuedChunk(level, chunk, key, explicit)); return true; } @@ -107,6 +143,7 @@ private static long chunkKey(ChunkPos pos) { return ((long) pos.chunkXPos & 0xFFFFFFFFL) | (((long) pos.chunkZPos & 0xFFFFFFFFL) << 32); } + private static final class Settings { static final Settings DISABLED = new Settings(false, false, false, 1, 0); final boolean oreEnabled; @@ -128,26 +165,28 @@ private static final class QueuedChunk { final WorldServer level; final Chunk chunk; final ChunkKey key; - QueuedChunk(WorldServer level, Chunk chunk, ChunkKey key) { + final boolean explicit; + QueuedChunk(WorldServer 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 WorldServer level; final long position; - ChunkKey(ResourceLocation dimension, long position) { - this.dimension = dimension; + ChunkKey(WorldServer 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/OreSpawnOreGeneration.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSpawnOreGeneration.java index d12544da..43e76b1e 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSpawnOreGeneration.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSpawnOreGeneration.java @@ -76,6 +76,93 @@ public final class OreSpawnOreGeneration { private OreSpawnOreGeneration() { } + /** Reads the same baked placement budget used by generation without rolling an attempt. */ + public static JsonObject diagnosticRule(WorldServer level, BlockPos position, ResourceLocation ruleId) { + Chunk chunk = level.getChunkProvider().getLoadedChunk(position.getX() >> 4, position.getZ() >> 4); + 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 = Biome.getBiome(chunk.getBiomeArray()[8 * 16 + 8] & 255); + ResourceLocation biomeId = biome == null ? null : WorldIds.biome(biome); + IBlockState 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.xPosition << 4) + 8, (chunk.zPosition << 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", zone.moddev.mc.orespawn.commands.admin.DiagnosticStates.key(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() { refreshWorldConfig(); } @@ -152,7 +239,7 @@ boolean generate(World world, Chunk chunk, Random random) { WorldServer level = world instanceof WorldServer ? (WorldServer) world : null; boolean changed = generateChunk(level, world, chunk, biome, biomeId, dimension, world.getSeed(), random, ores, false, scratch); - OreRetrogenManager.markGenerated(dimension, ChunkAccessCompat.position(chunk)); + if (level != null) OreRetrogenManager.markGenerated(level, ChunkAccessCompat.position(chunk)); return changed; } diff --git a/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSpawnWorldGenerator.java b/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSpawnWorldGenerator.java index 26384b65..112c8ad1 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSpawnWorldGenerator.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/OreSpawnWorldGenerator.java @@ -16,6 +16,7 @@ import net.minecraftforge.event.terraingen.DecorateBiomeEvent; import net.minecraftforge.event.terraingen.ChunkGeneratorEvent; import net.minecraftforge.event.terraingen.OreGenEvent; +import net.minecraftforge.event.terraingen.PopulateChunkEvent; import net.minecraftforge.fml.common.IWorldGenerator; import net.minecraftforge.fml.common.eventhandler.Event; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; @@ -49,6 +50,12 @@ public void beforeBiomeDecoration(DecorateBiomeEvent.Pre event) { generateEarly(event.getWorld(), pos.chunkXPos, pos.chunkZPos, event.getRand()); } + @SubscribeEvent(priority = EventPriority.LOWEST) + public void preserveNaturalLakeLining(PopulateChunkEvent.Populate event) { + if (WorldgenBenchmark.isVanillaBaseline()) return; + VanillaLakeCompatibility.replaceLavaLake(event); + } + @SubscribeEvent(priority = EventPriority.LOWEST) public void replaceVanillaSprings(DecorateBiomeEvent.Decorate event) { if (WorldgenBenchmark.isVanillaBaseline()) return; @@ -58,6 +65,7 @@ public void replaceVanillaSprings(DecorateBiomeEvent.Decorate event) { @SubscribeEvent public void beforeVanillaOres(OreGenEvent.Pre event) { if (WorldgenBenchmark.isVanillaBaseline()) return; + NativeStonePatchContext.begin(); ChunkPos pos = new ChunkPos(event.getPos()); generateOres(event.getWorld(), pos.chunkXPos, pos.chunkZPos, event.getRand()); } @@ -66,6 +74,8 @@ public void beforeVanillaOres(OreGenEvent.Pre event) { public void filterVanillaOre(OreGenEvent.GenerateMinable event) { if (WorldgenBenchmark.isVanillaBaseline()) return; ResourceLocation dimension = WorldIds.dimension(event.getWorld()); + NativeStonePatchContext.select(NaturalFormations.enabledForPlacement(event.getWorld()) + && GeomeConfig.terrainDimension(dimension) != null, event.getType()); Block output = vanillaOutput(event.getType()); if (WorldGeologyProfileManager.activeProfile().suppressAllOreFeatures()) { event.setResult(Event.Result.DENY); @@ -82,6 +92,11 @@ public void filterVanillaOre(OreGenEvent.GenerateMinable event) { } } + @SubscribeEvent(priority = EventPriority.LOWEST) + public void afterVanillaOres(OreGenEvent.Post event) { + NativeStonePatchContext.end(); + } + @SubscribeEvent(priority = EventPriority.LOWEST) public void afterBiomeDecoration(DecorateBiomeEvent.Post event) { if (WorldgenBenchmark.isVanillaBaseline()) return; @@ -115,6 +130,7 @@ private void generateEarly(World world, int chunkX, int chunkZ, Random random) { } private void generateOres(World world, int chunkX, int chunkZ, Random random) { + generateEarly(world, chunkX, chunkZ, random); ChunkKey key = new ChunkKey(WorldIds.dimension(world), chunkX, chunkZ); if (!oreComplete.add(key)) return; Chunk chunk = world.getChunkProvider().provideChunk(chunkX, chunkZ); @@ -122,6 +138,8 @@ private void generateOres(World world, int chunkX, int chunkZ, Random random) { } public void clear() { + VanillaLakeCompatibility.clear(); + NativeStonePatchContext.clear(); VanillaMesaGoldCompatibility.clear(); AquiferMaterialSubstitution.clear(); earlyComplete.clear(); 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 4d2660f2..3f4a72cc 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/StoneReplacer.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/StoneReplacer.java @@ -45,6 +45,8 @@ boolean generate(World world, Chunk chunk, Random random) { geology.legacy.replaceStoneInChunk(world, chunk, terrain); } else { geology.sky.replaceStoneInChunk(world, chunk, terrain); + if (world instanceof net.minecraft.world.WorldServer) + NaturalFormations.apply((net.minecraft.world.WorldServer) 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..dc113708 --- /dev/null +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/VanillaLakeCompatibility.java @@ -0,0 +1,105 @@ +package zone.moddev.mc.orespawn.worldgen; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Random; +import java.util.WeakHashMap; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraft.world.WorldServer; +import net.minecraft.world.gen.ChunkProviderOverworld; +import net.minecraft.world.gen.ChunkProviderSettings; +import net.minecraft.world.gen.feature.WorldGenLakes; +import net.minecraftforge.event.terraingen.PopulateChunkEvent; +import net.minecraftforge.fml.common.eventhandler.Event; +import net.minecraftforge.fml.common.ObfuscationReflectionHelper; +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; + +/** Keeps native lava-lake lining from erasing an already placed formation. */ +final class VanillaLakeCompatibility { + private static final Map SETTINGS = new WeakHashMap<>(); + private static final WorldGenLakes LAVA = new WorldGenLakes(Blocks.LAVA); + + private VanillaLakeCompatibility() { } + + static synchronized void configure(WorldServer world) { + SETTINGS.remove(world); + ChunkProviderOverworld generator = NaturalTerrainSurface.nativeGenerator(world); + if (generator == null) return; + // Resolve the native generator's actual settings once, not in a + // per-block loop. Keep other mods' edits to that settings object. + ChunkProviderSettings settings = ObfuscationReflectionHelper.getPrivateValue( + ChunkProviderOverworld.class, generator, + "field_186000_s", "settings"); + if (settings != null) SETTINGS.put(world, settings); + } + + static void replaceLavaLake(PopulateChunkEvent.Populate event) { + if (event.getType() != PopulateChunkEvent.Populate.EventType.LAVA + || event.getResult() == Event.Result.DENY + || !(event.getWorld() instanceof WorldServer) + || !NaturalFormations.enabledForPlacement(event.getWorld()) + || GeomeConfig.terrainDimension(WorldIds.dimension(event.getWorld())) == null) return; + ChunkProviderSettings settings; + synchronized (VanillaLakeCompatibility.class) { settings = SETTINGS.get(event.getWorld()); } + if (settings == null || settings.lavaLakeChance < 8) return; + World world = event.getWorld(); + BlockPos origin = new BlockPos(event.getChunkX() * 16, 0, event.getChunkZ() * 16); + BlockPos position = choosePosition(event.getRand(), origin, world.getSeaLevel(), settings.lavaLakeChance); + if (position != null) generate(world, event.getRand(), position, LAVA, + OreSpawnApi.createSampler((WorldServer) world).get()); + event.setResult(Event.Result.DENY); + } + + /** Exactly the native post-event coordinate draws and sea-level branch. */ + static BlockPos choosePosition(Random random, BlockPos origin, int seaLevel, int chance) { + int x = random.nextInt(16) + 8; + int y = random.nextInt(random.nextInt(248) + 8); + int z = random.nextInt(16) + 8; + return y < seaLevel || random.nextInt(chance / 8) == 0 ? origin.add(x, y, z) : null; + } + + static boolean generate(World world, Random random, BlockPos position, WorldGenLakes lake, + GeologySampler sampler) { + BlockPos origin = position.add(-8, 0, -8); + while (origin.getY() > 5 && world.isAirBlock(origin)) origin = origin.down(); + if (origin.getY() <= 4) return lake.generate(world, random, position); + origin = origin.down(4); + Map original = new LinkedHashMap<>(); + // Native WorldGenLakes reads/writes only this bounded 16x8x16 box. + // Snapshot loaded cells only; never cause neighbouring chunk loads. + 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 (!world.isBlockLoaded(at, false)) continue; + IBlockState state = world.getBlockState(at); + if (NaturalFormations.material(state) == null || world.getTileEntity(at) != null) continue; + if (column == null) column = sampler.sampleColumn(at.getX(), at.getZ(), 64); + Optional formation = column.formationAt(at.getY()); + // A material such as granite is also ordinary strata. Only an + // exact winning formation here is eligible, never all granite. + if (formation.isPresent() && formation.get().material().state().equals(state)) + original.put(at, state); + } + } + boolean generated = lake.generate(world, random, position); + for (Map.Entry entry : original.entrySet()) { + BlockPos at = entry.getKey(); + // The native solid rim writes exactly plain stone. Keep actual + // cavity air, lava, water, other ores and tile entities untouched. + if (world.getBlockState(at).equals(Blocks.STONE.getDefaultState()) + && world.getTileEntity(at) == null) + world.setBlockState(at, entry.getValue(), 2); + } + return generated; + } + + static synchronized void clear() { SETTINGS.clear(); } +} 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 50ed7954..8ce3807d 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/WorldGeologyProfile.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/WorldGeologyProfile.java @@ -107,6 +107,7 @@ public static WorldGeologyProfile fromJson(JsonObject json, WorldGeologyProfile // Schema 1 contained only mode, oil and formations. Overlay those fields on // the currently effective pack profile so the resulting profile is complete. 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 bec6f1e0..441ede00 100644 --- a/src/main/java/zone/moddev/mc/orespawn/worldgen/WorldGeologyProfileManager.java +++ b/src/main/java/zone/moddev/mc/orespawn/worldgen/WorldGeologyProfileManager.java @@ -181,7 +181,10 @@ static WorldGeologyProfile initializeNewWorldPolicies(WorldGeologyProfile profil // A generated world without an OS4 profile is an upgrade. Its installed-pack // fallback may already contain fresh-world consolidation defaults, which must // not alter the world's historical ore frequency implicitly. - if (generatedWorld) initialized.remove(OreSourcePolicies.SECTION); + if (generatedWorld) { + initialized.remove(OreSourcePolicies.SECTION); + initialized.remove(NaturalFormations.SECTION); + } OreSourcePolicies.initialize(initialized, generatedWorld); return profile.withRoot(initialized); } @@ -200,6 +203,7 @@ public static void onServerStopped(FMLServerStoppedEvent event) { public static void onWorldLoad(WorldEvent.Load event) { if (!(event.getWorld() instanceof WorldServer)) return; + VanillaLakeCompatibility.configure((WorldServer) event.getWorld()); WorldGeologyProfile profile = activeProfile; if (profile != null) { BiomeWorldgenManager.apply((WorldServer) event.getWorld(), profile); diff --git a/src/main/resources/assets/orespawn/lang/de_AU.lang b/src/main/resources/assets/orespawn/lang/de_AU.lang index ddf85f92..54557d25 100644 --- a/src/main/resources/assets/orespawn/lang/de_AU.lang +++ b/src/main/resources/assets/orespawn/lang/de_AU.lang @@ -508,3 +508,32 @@ 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) +# Admin and distribution tools +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.lang b/src/main/resources/assets/orespawn/lang/de_DE.lang index ddf85f92..54557d25 100644 --- a/src/main/resources/assets/orespawn/lang/de_DE.lang +++ b/src/main/resources/assets/orespawn/lang/de_DE.lang @@ -508,3 +508,32 @@ 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) +# Admin and distribution tools +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.lang b/src/main/resources/assets/orespawn/lang/en_CA.lang index d4da74c0..26fd62d2 100644 --- a/src/main/resources/assets/orespawn/lang/en_CA.lang +++ b/src/main/resources/assets/orespawn/lang/en_CA.lang @@ -508,3 +508,32 @@ 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) +# Admin and distribution tools +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.lang b/src/main/resources/assets/orespawn/lang/en_EN.lang index d4da74c0..26fd62d2 100644 --- a/src/main/resources/assets/orespawn/lang/en_EN.lang +++ b/src/main/resources/assets/orespawn/lang/en_EN.lang @@ -508,3 +508,32 @@ 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) +# Admin and distribution tools +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_GB.lang b/src/main/resources/assets/orespawn/lang/en_GB.lang index d4da74c0..26fd62d2 100644 --- a/src/main/resources/assets/orespawn/lang/en_GB.lang +++ b/src/main/resources/assets/orespawn/lang/en_GB.lang @@ -508,3 +508,32 @@ 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) +# Admin and distribution tools +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.lang b/src/main/resources/assets/orespawn/lang/en_PT.lang index d4da74c0..26fd62d2 100644 --- a/src/main/resources/assets/orespawn/lang/en_PT.lang +++ b/src/main/resources/assets/orespawn/lang/en_PT.lang @@ -508,3 +508,32 @@ 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) +# Admin and distribution tools +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.lang b/src/main/resources/assets/orespawn/lang/en_US.lang index ea25544d..4848d542 100644 --- a/src/main/resources/assets/orespawn/lang/en_US.lang +++ b/src/main/resources/assets/orespawn/lang/en_US.lang @@ -508,3 +508,32 @@ 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) +# Admin and distribution tools +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.lang b/src/main/resources/assets/orespawn/lang/es_ES.lang index 1954b63f..c2e5efb4 100644 --- a/src/main/resources/assets/orespawn/lang/es_ES.lang +++ b/src/main/resources/assets/orespawn/lang/es_ES.lang @@ -508,3 +508,32 @@ 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) +# Admin and distribution tools +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.lang b/src/main/resources/assets/orespawn/lang/es_MX.lang index 1954b63f..c2e5efb4 100644 --- a/src/main/resources/assets/orespawn/lang/es_MX.lang +++ b/src/main/resources/assets/orespawn/lang/es_MX.lang @@ -508,3 +508,32 @@ 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) +# Admin and distribution tools +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.lang b/src/main/resources/assets/orespawn/lang/fr_CA.lang index 72a6cb4d..5a08c325 100644 --- a/src/main/resources/assets/orespawn/lang/fr_CA.lang +++ b/src/main/resources/assets/orespawn/lang/fr_CA.lang @@ -508,3 +508,32 @@ 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) +# Admin and distribution tools +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.lang b/src/main/resources/assets/orespawn/lang/fr_FR.lang index 72a6cb4d..5a08c325 100644 --- a/src/main/resources/assets/orespawn/lang/fr_FR.lang +++ b/src/main/resources/assets/orespawn/lang/fr_FR.lang @@ -508,3 +508,32 @@ 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) +# Admin and distribution tools +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.lang b/src/main/resources/assets/orespawn/lang/ja_JP.lang index 1e5ac494..c5d13112 100644 --- a/src/main/resources/assets/orespawn/lang/ja_JP.lang +++ b/src/main/resources/assets/orespawn/lang/ja_JP.lang @@ -508,3 +508,32 @@ option.orespawn.biome.coverage=適用範囲 option.orespawn.biome.fallback_weight=元のバイオームの重み option.orespawn.biome.include_namespaces=含める名前空間(カンマ区切り) option.orespawn.biome.exclude_namespaces=除外する名前空間(カンマ区切り) +# Admin and distribution tools +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.lang b/src/main/resources/assets/orespawn/lang/ko_KR.lang index 21b43106..1abdc4b2 100644 --- a/src/main/resources/assets/orespawn/lang/ko_KR.lang +++ b/src/main/resources/assets/orespawn/lang/ko_KR.lang @@ -508,3 +508,32 @@ option.orespawn.biome.coverage=적용 범위 option.orespawn.biome.fallback_weight=원래 생물군계 가중치 option.orespawn.biome.include_namespaces=포함할 네임스페이스(쉼표로 구분) option.orespawn.biome.exclude_namespaces=제외할 네임스페이스(쉼표로 구분) +# Admin and distribution tools +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.lang b/src/main/resources/assets/orespawn/lang/pt_BR.lang index 5ae787d8..9987a2db 100644 --- a/src/main/resources/assets/orespawn/lang/pt_BR.lang +++ b/src/main/resources/assets/orespawn/lang/pt_BR.lang @@ -508,3 +508,32 @@ 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) +# Admin and distribution tools +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.lang b/src/main/resources/assets/orespawn/lang/ru_RU.lang index 0cb3aaae..d24cfdd1 100644 --- a/src/main/resources/assets/orespawn/lang/ru_RU.lang +++ b/src/main/resources/assets/orespawn/lang/ru_RU.lang @@ -508,3 +508,32 @@ option.orespawn.biome.coverage=Покрытие option.orespawn.biome.fallback_weight=Вес исходного биома option.orespawn.biome.include_namespaces=Включённые пространства имён (через запятую) option.orespawn.biome.exclude_namespaces=Исключённые пространства имён (через запятую) +# Admin and distribution tools +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.lang b/src/main/resources/assets/orespawn/lang/zh_CN.lang index 83b2c1aa..253f9302 100644 --- a/src/main/resources/assets/orespawn/lang/zh_CN.lang +++ b/src/main/resources/assets/orespawn/lang/zh_CN.lang @@ -508,3 +508,32 @@ option.orespawn.biome.coverage=覆盖率 option.orespawn.biome.fallback_weight=原始生物群系权重 option.orespawn.biome.include_namespaces=包含的命名空间(逗号分隔) option.orespawn.biome.exclude_namespaces=排除的命名空间(逗号分隔) +# Admin and distribution tools +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/test/java/zone/moddev/mc/orespawn/LocalizationParityTest.java b/src/test/java/zone/moddev/mc/orespawn/LocalizationParityTest.java index 1a85f3ea..747c1e9f 100644 --- a/src/test/java/zone/moddev/mc/orespawn/LocalizationParityTest.java +++ b/src/test/java/zone/moddev/mc/orespawn/LocalizationParityTest.java @@ -87,7 +87,7 @@ class LocalizationParityTest { void everyLocaleMatchesEnglishKeysAndFormatting() throws Exception { JsonObject english = read(LANG_DIR.resolve("en_US.lang")); 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/commands/admin/AdminDataTest.java b/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminDataTest.java new file mode 100644 index 00000000..8db83373 --- /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.init.Blocks; +import zone.moddev.mc.orespawn.test.Forge12TestBootstrap; + +class AdminDataTest { + @TempDir Path temporary; + @BeforeAll static void bootstrap() { Forge12TestBootstrap.registerVanilla(); } + + @Test void exactStatesRoundTripIncludingLegacyMetadata() { + for (net.minecraft.block.Block block : new net.minecraft.block.Block[]{Blocks.STONE, Blocks.WOOL, Blocks.WATER, Blocks.LEAVES}) + for (net.minecraft.block.state.IBlockState state : block.getBlockState().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.STONE.getStateFromMeta(3); + }, -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.STONE.getStateFromMeta(3)), 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:stone[]")); + } + @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:stone\":{\"block\":\"minecraft:stone\",\"metadata\":3}}}").getAsJsonObject(); + DiagnosticCatalog catalog = new DiagnosticCatalog(profile); + assertFalse(catalog.removable(Blocks.STONE.getStateFromMeta(3), false)); + assertTrue(catalog.removable(Blocks.STONE.getStateFromMeta(0), false)); + assertFalse(catalog.removable(Blocks.DIAMOND_ORE.getDefaultState(), false)); + assertFalse(catalog.removable(Blocks.FLOWING_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 protectionUsesTheGeneratorsExactIdFallbackAndMetadataClampWithoutEditingTheProfile() { + JsonObject profile = new com.google.gson.JsonParser().parse("{\"ores\":{\"minecraft:stone\":{\"metadata\":3},\"test:wool\":{\"block\":\"minecraft:wool\",\"metadata\":999}},\"rocks\":{\"test:wool\":{\"block\":\"minecraft:wool\",\"metadata\":15}}}").getAsJsonObject(); + String before = profile.toString(); + DiagnosticCatalog catalog = new DiagnosticCatalog(profile); + assertFalse(catalog.removable(Blocks.STONE.getStateFromMeta(3), false)); + assertFalse(catalog.removable(Blocks.WOOL.getStateFromMeta(15), 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..b5b26fc1 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminFeedbackTest.java @@ -0,0 +1,144 @@ +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.command.CommandResultStats; +import net.minecraft.command.ICommandSender; +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.TextComponentString; +import net.minecraft.util.text.TextComponentTranslation; +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.getUnformattedText().contains(JOB)); + assertFalse(line.getUnformattedText().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.jsonToComponent(ITextComponent.Serializer.componentToJson(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).getUnformattedText()); + assertEquals("example:moon", ((ITextComponent) translated(sender.messages.get(1)).getFormatArgs()[0]).getUnformattedText()); + } + + @Test void completionOffersAnUndoPreviewInTheOriginalDimensionNotAnImmediateRestore() { + Sender sender = new Sender(); + AdminFeedback.completed(sender, JOB, 14468, false, "backup-id", "minecraft:the_nether"); + TextComponentTranslation 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).getUnformattedText()); + } + + @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).getUnformattedText().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"))); + TextComponentTranslation 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 TextComponentTranslation translated(ITextComponent component) { + assertTrue(component instanceof TextComponentTranslation); + return (TextComponentTranslation) 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 ICommandSender { + final List messages = new ArrayList<>(); + public String getName() { return "test"; } + public ITextComponent getDisplayName() { return new TextComponentString("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 World getEntityWorld() { throw new AssertionError("Unexpected world access"); } + public Entity getCommandSenderEntity() { return null; } + public boolean sendCommandFeedback() { return true; } + public void setCommandStat(CommandResultStats.Type type, int value) { } + public MinecraftServer getServer() { throw new AssertionError("Unexpected server access"); } + } +} 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..2a540ce8 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/commands/admin/AdminSafetyTest.java @@ -0,0 +1,130 @@ +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.command.CommandException; +import net.minecraft.command.CommandResultStats; +import net.minecraft.command.ICommandSender; +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.TextComponentString; +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(CommandException.class, () -> AdminCommands.handle(null, new Sender(2), command)); + } + @Test void diagnosticCommandsRejectNonOperatorsBeforeAccessingAnyWorld() { + for (String action : Arrays.asList("help", "chunk", "survey", "explain", "jobs", "cancel")) + assertThrows(CommandException.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.10.2"); + 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 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.componentToJson(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 ICommandSender { + final int level; + int messages; + ITextComponent lastMessage; + Sender(int level) { this.level = level; } + public String getName() { return "test"; } + public ITextComponent getDisplayName() { return new TextComponentString("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 World getEntityWorld() { throw new AssertionError("Unexpected world access"); } + public Entity getCommandSenderEntity() { return null; } + public boolean sendCommandFeedback() { return true; } + public void setCommandStat(CommandResultStats.Type type, int value) { } + public MinecraftServer getServer() { return null; } + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/documentation/DocumentationExporterTest.java b/src/test/java/zone/moddev/mc/orespawn/documentation/DocumentationExporterTest.java index 659de75f..1405524f 100644 --- a/src/test/java/zone/moddev/mc/orespawn/documentation/DocumentationExporterTest.java +++ b/src/test/java/zone/moddev/mc/orespawn/documentation/DocumentationExporterTest.java @@ -28,7 +28,7 @@ void exportsCompleteGuideAndDoesNotOverwriteExistingFiles() throws Exception { .sorted() .collect(Collectors.toList()); } - assertEquals(20, tracked.size()); + assertEquals(22, tracked.size()); assertEquals(tracked.size(), firstExport); for (Path source : tracked) { Path relative = Paths.get("docs").relativize(source); 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..2a42fc6f --- /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.Forge12TestBootstrap; +import zone.moddev.mc.orespawn.util.JsonCopies; + +class FormationOverrideTest { + @SuppressWarnings("unchecked") + @Test void onlyUntouchedPackagedDefaultsAreTuned() throws Exception { + Forge12TestBootstrap.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/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/test/EclipseSourceAccessTest.java b/src/test/java/zone/moddev/mc/orespawn/test/EclipseSourceAccessTest.java new file mode 100644 index 00000000..ca0d72f8 --- /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 checks reject them. + // Keep the fixtures portable instead of weakening the IDE's checks. + 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 reflection for test fixtures rather than importing restricted JRE classes"); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/FormationTerrainCompatibilityTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/FormationTerrainCompatibilityTest.java new file mode 100644 index 00000000..6fa24c39 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/FormationTerrainCompatibilityTest.java @@ -0,0 +1,121 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.*; + +import java.lang.reflect.Field; +import java.lang.reflect.Proxy; +import java.util.Map; +import net.minecraft.world.WorldServer; +import net.minecraft.world.WorldSettings; +import net.minecraft.world.WorldType; +import net.minecraft.world.GameType; +import net.minecraft.world.chunk.IChunkGenerator; +import net.minecraft.world.gen.ChunkProviderOverworld; +import net.minecraft.world.gen.ChunkProviderServer; +import net.minecraft.world.gen.ChunkProviderSettings; +import net.minecraft.world.storage.WorldInfo; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import zone.moddev.mc.orespawn.test.Forge12TestBootstrap; + +class FormationTerrainCompatibilityTest { + @BeforeAll static void bootstrap() { Forge12TestBootstrap.registerVanilla(); } + @AfterEach void clear() { VanillaLakeCompatibility.clear(); } + + @Test void nativeWorldTypesReceiveTheSameLakeProtection() throws Exception { + for (WorldType type : new WorldType[]{WorldType.DEFAULT, WorldType.AMPLIFIED, + WorldType.LARGE_BIOMES, WorldType.CUSTOMIZED}) { + ChunkProviderSettings settings = allocate(ChunkProviderSettings.class); + ChunkProviderOverworld generator = allocate(ChunkProviderOverworld.class); + set(ChunkProviderOverworld.class, generator, "settings", settings); + TestWorld world = world(type, generator); + VanillaLakeCompatibility.configure(world); + assertSame(settings, registeredSettings().get(world), "Missing protection for " + type); + } + } + + @Test void customSubclassesAreNotTreatedAsTheNativeGenerator() throws Exception { + TestWorld world = world(WorldType.DEFAULT, allocate(CustomGenerator.class)); + VanillaLakeCompatibility.configure(world); + assertFalse(registeredSettings().containsKey(world)); + assertEquals(-1, new NaturalTerrainSurface(world).at(-950, 1033)); + } + + @Test void unrelatedGeneratorsAreRejectedWithoutSamplingThem() throws Exception { + IChunkGenerator generator = (IChunkGenerator) Proxy.newProxyInstance( + IChunkGenerator.class.getClassLoader(), new Class[]{IChunkGenerator.class}, + (proxy, method, args) -> { throw new AssertionError("Unsupported generator was sampled"); }); + TestWorld world = world(WorldType.AMPLIFIED, generator); + VanillaLakeCompatibility.configure(world); + assertFalse(registeredSettings().containsKey(world)); + assertEquals(-1, new NaturalTerrainSurface(world).at(-1, -1)); + } + + @Test void replacingTheGeneratorDropsItsOldLakeSettings() throws Exception { + ChunkProviderOverworld generator = allocate(ChunkProviderOverworld.class); + set(ChunkProviderOverworld.class, generator, "settings", allocate(ChunkProviderSettings.class)); + TestWorld world = world(WorldType.DEFAULT, generator); + VanillaLakeCompatibility.configure(world); + assertTrue(registeredSettings().containsKey(world)); + set(ChunkProviderServer.class, world.chunks, "chunkGenerator", allocate(CustomGenerator.class)); + VanillaLakeCompatibility.configure(world); + assertFalse(registeredSettings().containsKey(world)); + } + + @Test void shutdownDropsAllWorldSpecificLakeSettings() throws Exception { + java.util.List worlds = new java.util.ArrayList<>(); + for (WorldType type : new WorldType[]{WorldType.DEFAULT, WorldType.AMPLIFIED}) { + ChunkProviderOverworld generator = allocate(ChunkProviderOverworld.class); + set(ChunkProviderOverworld.class, generator, "settings", allocate(ChunkProviderSettings.class)); + TestWorld world = world(type, generator); + worlds.add(world); + VanillaLakeCompatibility.configure(world); + } + assertEquals(worlds.size(), registeredSettings().size()); + VanillaLakeCompatibility.clear(); + assertTrue(registeredSettings().isEmpty()); + } + + private static TestWorld world(WorldType type, IChunkGenerator generator) throws Exception { + TestWorld world = allocate(TestWorld.class); + world.chunks = allocate(ChunkProviderServer.class); + set(ChunkProviderServer.class, world.chunks, "chunkGenerator", generator); + world.info = new WorldInfo(new WorldSettings(17, GameType.SURVIVAL, true, false, type), "test"); + return world; + } + + @SuppressWarnings("unchecked") + private static Map registeredSettings() throws Exception { + Field field = VanillaLakeCompatibility.class.getDeclaredField("SETTINGS"); + field.setAccessible(true); + return (Map) field.get(null); + } + + 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); + } + + private static T allocate(Class type) throws Exception { + Class unsafeType = Class.forName("sun.misc.Unsafe"); + Field field = unsafeType.getDeclaredField("theUnsafe"); + field.setAccessible(true); + return type.cast(unsafeType.getMethod("allocateInstance", Class.class).invoke(field.get(null), type)); + } + + // These fixtures never construct a save or a native generator. Only the + // eligibility/settings seams are used; actual generation is tested packaged. + private static final class TestWorld extends WorldServer { + ChunkProviderServer chunks; + WorldInfo info; + private TestWorld() { super(null, null, null, 0, null); } + @Override public ChunkProviderServer getChunkProvider() { return chunks; } + @Override public WorldInfo getWorldInfo() { return info; } + } + + private static final class CustomGenerator extends ChunkProviderOverworld { + private CustomGenerator() { super(null, 0, false, ""); } + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeStonePatchContextTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeStonePatchContextTest.java new file mode 100644 index 00000000..dd08bc26 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/NativeStonePatchContextTest.java @@ -0,0 +1,52 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.*; +import net.minecraftforge.event.terraingen.OreGenEvent.GenerateMinable.EventType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import zone.moddev.mc.orespawn.api.OreSpawnApi; + +class NativeStonePatchContextTest { + @AfterEach void reset() { NativeStonePatchContext.clear(); } + @Test void onlyThreeNativeStonePatchesAreMarked() { + for (EventType type : EventType.values()) { + NativeStonePatchContext.select(true, type); + assertEquals(type == EventType.GRANITE || type == EventType.DIORITE || type == EventType.ANDESITE, + OreSpawnApi.isNativeStonePatchPass(), type.toString()); + } + } + @Test void absentFormationsAndPostResetRetainOrdinaryReplacement() { + NativeStonePatchContext.select(false, EventType.GRANITE); + assertFalse(OreSpawnApi.isNativeStonePatchPass()); + NativeStonePatchContext.select(true, EventType.GRANITE); + assertTrue(OreSpawnApi.isNativeStonePatchPass()); + NativeStonePatchContext.reset(); + assertFalse(OreSpawnApi.isNativeStonePatchPass()); + } + @Test void passContextDoesNotLeakAcrossThreads() throws Exception { + NativeStonePatchContext.select(true, EventType.ANDESITE); + final boolean[] observed = {true}; + Thread other = new Thread(() -> observed[0] = OreSpawnApi.isNativeStonePatchPass()); + other.start(); other.join(); + assertFalse(observed[0]); + assertTrue(OreSpawnApi.isNativeStonePatchPass()); + } + @Test void nestedOrePassRestoresOuterNativePatchAndWorldClearDropsFrames() { + NativeStonePatchContext.select(true, EventType.GRANITE); + NativeStonePatchContext.begin(); + assertFalse(OreSpawnApi.isNativeStonePatchPass()); + NativeStonePatchContext.select(true, EventType.IRON); + NativeStonePatchContext.end(); + assertTrue(OreSpawnApi.isNativeStonePatchPass()); + NativeStonePatchContext.begin(); + NativeStonePatchContext.clear(); + NativeStonePatchContext.end(); + assertFalse(OreSpawnApi.isNativeStonePatchPass()); + } + @Test void releasedTerrainCacheOwnerCannotLoadAnyChunk() throws Exception { + NaturalTerrainSurface surface = new NaturalTerrainSurface(null); + java.lang.reflect.Field owner = NaturalTerrainSurface.class.getDeclaredField("world"); + assertEquals(java.lang.ref.WeakReference.class, owner.getType()); + assertEquals(-1, surface.at(-1,-1)); + } +} 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..92429bb6 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/NaturalFormationTest.java @@ -0,0 +1,129 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.*; +import com.google.gson.*; +import java.util.*; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.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.Forge12TestBootstrap; + +class NaturalFormationTest { + @BeforeAll static void bootstrap() { Forge12TestBootstrap.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++) { + JsonObject material = new JsonObject(); material.addProperty("block", "minecraft:stone"); + material.addProperty("metadata", i % 6 + 1); 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 IBlockState 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 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.STONE.getStateFromMeta(1)); + 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.STONE.getStateFromMeta(1)); + 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 (IBlockState unsuitable : new IBlockState[]{Blocks.STONE.getDefaultState(), + Blocks.STONE.getStateFromMeta(2), Blocks.MONSTER_EGG.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.STONE.getStateFromMeta(1)).at(95)); + assertNull(weatherColumn(formation, site[0], site[1], 1, .2F, Blocks.STONE.getStateFromMeta(1)).at(95)); + } + static RockFormationColumn weatherColumn(BuiltinRockFormation formation, int x, int z, + float temperature, float rain, IBlockState 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 IBlockState 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/OreRetrogenManagerTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/OreRetrogenManagerTest.java new file mode 100644 index 00000000..0086e8e3 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/OreRetrogenManagerTest.java @@ -0,0 +1,290 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.*; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.WorldServer; +import net.minecraft.world.World; +import net.minecraft.world.WorldProviderSurface; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.event.world.ChunkDataEvent; +import net.minecraftforge.fml.common.gameevent.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.Forge12TestBootstrap; + +class OreRetrogenManagerTest { + private WorldServer level; + private Chunk chunk; + + @BeforeAll + static void bootstrap() { Forge12TestBootstrap.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 completionSurvivesRepeatedSavesAndProcessRestarts() throws Exception { + NBTTagCompound 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)); + NBTTagCompound 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 NBTTagCompound()); + assertEquals(1, OreRetrogenManager.queuedCount()); + assertFalse(save(chunk).hasKey("OreSpawn")); + } + + @Test + void aStringMarkerIsNotCompletionAtRevisionZero() throws Exception { + settings(true, false, false, 0); + NBTTagCompound disk = new NBTTagCompound(); + NBTTagCompound root = new NBTTagCompound(); + root.setString("generation_revision", "0"); + disk.setTag("OreSpawn", root); + load(chunk, disk); + assertEquals(1, OreRetrogenManager.queuedCount()); + } + + @Test + void negativeMarkersAreNotTreatedAsCompletedWork() { + load(chunk, marker(-1)); + assertEquals(1, OreRetrogenManager.queuedCount()); + assertFalse(save(chunk).hasKey("OreSpawn")); + } + + @Test + void negativeCoordinatesDoNotShareCompletion() throws Exception { + load(chunk, marker(777)); + Chunk other = chunk(level, 21, -20); + load(other, new NBTTagCompound()); + assertEquals(1, OreRetrogenManager.queuedCount()); + assertFalse(save(other).hasKey("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 NBTTagCompound()); + assertFalse(save(other).hasKey("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).hasKey("OreSpawn")); + assertEquals(777, revision(save(chunk))); + } + + @Test + void reloadingTheSameChunkInOneSessionKeepsItsMarker() throws Exception { + load(chunk, marker(777)); + NBTTagCompound 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).hasKey("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 NBTTagCompound()); + settings(false, false, false, 888); + OreRetrogenManager.onServerTick(new TickEvent.ServerTickEvent(TickEvent.Phase.END)); + assertEquals(0, OreRetrogenManager.queuedCount()); + assertFalse(save(chunk).hasKey("OreSpawn")); + } + + @Test + void freshlyGeneratedChunksKeepTheRevisionTheyActuallyCompleted() throws Exception { + OreRetrogenManager.markGenerated(level, ChunkAccessCompat.position(chunk)); + settings(true, false, false, 888); + assertEquals(777, revision(save(chunk))); + } + + @Test + void freshGenerationDoesNotMarkAnotherWorldAtTheSameCoordinates() throws Exception { + OreRetrogenManager.markGenerated(level, ChunkAccessCompat.position(chunk)); + assertFalse(save(chunk(world(0), -20, 21)).hasKey("OreSpawn")); + assertEquals(777, revision(save(chunk))); + } + + @Test + void anUnmarkedReloadDoesNotInheritOldSessionBookkeeping() { + load(chunk, marker(777)); + load(chunk, new NBTTagCompound()); + assertEquals(1, OreRetrogenManager.queuedCount()); + assertFalse(save(chunk).hasKey("OreSpawn")); + } + + @Test + void savingKeepsOtherFieldsAlreadyInTheEventData() { + load(chunk, marker(777)); + NBTTagCompound disk = marker(1); + disk.getCompoundTag("OreSpawn").setString("note", "keep this"); + OreRetrogenManager.onChunkSave(new ChunkDataEvent.Save(chunk, disk)); + assertEquals(777, revision(disk)); + assertEquals("keep this", disk.getCompoundTag("OreSpawn").getString("note")); + } + + @Test + void loadingDoesNotMutateTheSavedNbt() { + NBTTagCompound disk = marker(777); + NBTTagCompound 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, NBTTagCompound data) { + OreRetrogenManager.onChunkLoad(new ChunkDataEvent.Load(chunk, data)); + } + + private static NBTTagCompound save(Chunk chunk) { + NBTTagCompound data = new NBTTagCompound(); + OreRetrogenManager.onChunkSave(new ChunkDataEvent.Save(chunk, data)); + return data; + } + + private static NBTTagCompound marker(int revision) { + NBTTagCompound data = new NBTTagCompound(); + NBTTagCompound root = new NBTTagCompound(); + root.setInteger("generation_revision", revision); + data.setTag("OreSpawn", root); + return data; + } + + private static int revision(NBTTagCompound data) { + assertTrue(data.getCompoundTag("OreSpawn").hasKey("generation_revision", 3)); + return data.getCompoundTag("OreSpawn").getInteger("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 WorldServer world(int dimension) throws Exception { + WorldServer level = allocate(WorldServer.class); + set(World.class, level, "provider", new WorldProviderSurface()); + level.provider.setDimension(dimension); + return level; + } + + private static Chunk chunk(WorldServer level, int x, int z) { + return new Chunk(level, x, z); + } + + 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); + } + + private static T allocate(Class type) throws Exception { + // Runtime lookup keeps this test fixture compatible with Eclipse's Java 8 checks. + Class allocator = Class.forName("sun.misc.Unsafe"); + Field field = allocator.getDeclaredField("theUnsafe"); + field.setAccessible(true); + return type.cast(allocator.getMethod("allocateInstance", Class.class).invoke(field.get(null), type)); + } +} diff --git a/src/test/java/zone/moddev/mc/orespawn/worldgen/VanillaLakeCompatibilityTest.java b/src/test/java/zone/moddev/mc/orespawn/worldgen/VanillaLakeCompatibilityTest.java new file mode 100644 index 00000000..65041bd3 --- /dev/null +++ b/src/test/java/zone/moddev/mc/orespawn/worldgen/VanillaLakeCompatibilityTest.java @@ -0,0 +1,146 @@ +package zone.moddev.mc.orespawn.worldgen; + +import static org.junit.jupiter.api.Assertions.*; +import com.google.gson.*; +import java.util.*; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraft.world.gen.feature.WorldGenLakes; +import net.minecraft.world.chunk.IChunkProvider; +import net.minecraft.tileentity.TileEntity; +import org.junit.jupiter.api.*; +import zone.moddev.mc.orespawn.test.Forge12TestBootstrap; +import zone.moddev.mc.orespawn.api.*; +import net.minecraft.util.ResourceLocation; + +class VanillaLakeCompatibilityTest { + @BeforeAll static void bootstrap() { Forge12TestBootstrap.registerVanilla(); } + @BeforeEach void formation() { + JsonObject rule = NaturalFormationTest.rule("barren_pipe"); + JsonObject material = new JsonObject(); material.addProperty("block", "minecraft:diamond_block"); + JsonObject materials = new JsonObject(); materials.add("pipe", material); rule.add("materials", materials); + JsonObject rules = new JsonObject(); rules.add("test:pipe", rule); + JsonObject profile = new JsonObject(); profile.add("rock_formations", rules); + NaturalFormations.install(profile); + } + @AfterEach void clear() { NaturalFormations.install(new JsonObject()); VanillaLakeCompatibility.clear(); } + + private StateWorld world(Map cells) { + try { + // No real save/provider/chunk is constructed by this isolated state map. + Class type=Class.forName("sun.misc.Unsafe"); + java.lang.reflect.Field field=type.getDeclaredField("theUnsafe");field.setAccessible(true); + StateWorld world=(StateWorld)type.getMethod("allocateInstance",Class.class).invoke(field.get(null),StateWorld.class); + world.cells=cells;world.unloaded=new HashSet<>();world.read=new HashSet<>(); + return world; + } catch (ReflectiveOperationException failure) { throw new AssertionError(failure); } + } + + private static final class StateWorld extends World { + Map cells;Set unloaded,read;BlockPos tileAt; + private StateWorld(){super(null,null,null,null,false);} + protected IChunkProvider createChunkProvider(){return null;} + protected boolean isChunkLoaded(int x,int z,boolean empty){return true;} + public boolean isBlockLoaded(BlockPos pos,boolean empty){return !unloaded.contains(pos);} + public boolean isAirBlock(BlockPos pos){return getBlockState(pos).getBlock()==Blocks.AIR;} + public IBlockState getBlockState(BlockPos pos){read.add(pos.toImmutable());return cells.getOrDefault(pos,Blocks.STONE.getDefaultState());} + public TileEntity getTileEntity(BlockPos pos){read.add(pos.toImmutable());return pos.equals(tileAt)?new TileEntity(){}:null;} + public boolean setBlockState(BlockPos pos,IBlockState state,int flags){assertEquals(2,flags);cells.put(pos.toImmutable(),state);return true;} + } + + private boolean generate(World world,Random random,BlockPos position,WorldGenLakes lake) { + return VanillaLakeCompatibility.generate(world,random,position,lake,sampler(Blocks.DIAMOND_BLOCK.getDefaultState())); + } + + private GeologySampler sampler(IBlockState material) { + return (x,z,surface) -> new GeologyColumn() { + GeologyColumn base=NaturalFormationTest.base(x,z); + public ResourceLocation dimension(){return base.dimension();} + public ResourceLocation biome(){return base.biome();} + public ResourceLocation geome(){return base.geome();} + public int blockX(){return x;}public int blockZ(){return z;}public int surfaceY(){return surface;} + public IBlockState rockAt(int y){return material==null?Blocks.STONE.getDefaultState():material;} + public Optional familyAt(int y){return Optional.empty();} + public Optional formationAt(int y){ + return material==null?Optional.empty():Optional.of(new FormationSample(new ResourceLocation("test:pipe"),1, + Blocks.STONE.getDefaultState(),new FormationMaterial(material,null))); + } + }; + } + + @Test void lakeBeforeAndAfterFormationRetainTheSameSubstrate() { + BlockPos at = new BlockPos(-281, 44, -667), lakeAt = new BlockPos(-280, 48, -664); + for (boolean formationFirst : new boolean[]{false,true}) { + Map cells = new HashMap<>(); World world = world(cells); + if (formationFirst) cells.put(at, Blocks.DIAMOND_BLOCK.getDefaultState()); + WorldGenLakes lake = new WorldGenLakes(Blocks.LAVA) { + public boolean generate(World w, Random r, BlockPos p) { + w.setBlockState(at, Blocks.STONE.getDefaultState(), 2); return true; + } + }; + assertTrue(generate(world,new Random(7),lakeAt,lake)); + if (!formationFirst) cells.put(at,Blocks.DIAMOND_BLOCK.getDefaultState()); + assertEquals(Blocks.DIAMOND_BLOCK.getDefaultState(), cells.get(at)); + } + } + + @Test void cavityFluidsOresAndTileEntitiesAreNotRestored() { + BlockPos at = new BlockPos(3,44,3), lakeAt = new BlockPos(8,48,8); + for (IBlockState output : new IBlockState[]{Blocks.AIR.getDefaultState(),Blocks.LAVA.getDefaultState(), + Blocks.WATER.getDefaultState(),Blocks.IRON_ORE.getDefaultState()}) { + Map cells = new HashMap<>();cells.put(at,Blocks.DIAMOND_BLOCK.getDefaultState()); + World world = world(cells); + generate(world,new Random(9),lakeAt,new WorldGenLakes(Blocks.LAVA) { + public boolean generate(World w,Random r,BlockPos p){w.setBlockState(at,output,2);return true;} + }); + assertEquals(output,cells.get(at)); + } + Map cells = new HashMap<>();cells.put(at,Blocks.DIAMOND_BLOCK.getDefaultState()); + StateWorld world = world(cells);world.tileAt=at; + generate(world,new Random(9),lakeAt,new WorldGenLakes(Blocks.LAVA) { + public boolean generate(World w,Random r,BlockPos p){w.setBlockState(at,Blocks.STONE.getDefaultState(),2);return true;} + }); + assertEquals(Blocks.STONE.getDefaultState(),cells.get(at)); + } + + @Test void ordinaryRocksAreNotProtectedAndUnloadedCellsAreNotRead() { + BlockPos at = new BlockPos(3,44,3), unloaded = new BlockPos(4,44,3); + Map cells = new HashMap<>();cells.put(at,Blocks.GOLD_BLOCK.getDefaultState()); + StateWorld world = world(cells);world.unloaded.add(unloaded); + generate(world,new Random(9),new BlockPos(8,48,8),new WorldGenLakes(Blocks.LAVA) { + public boolean generate(World w,Random r,BlockPos p){w.setBlockState(at,Blocks.STONE.getDefaultState(),2);return true;} + }); + assertEquals(Blocks.STONE.getDefaultState(),cells.get(at)); + assertFalse(world.read.contains(unloaded)); + } + + @Test void coordinateAndLakeRandomStreamsMatchVanillaExactly() { + for (long seed=0;seed<200;seed++) { + Random expected=new Random(seed),actual=new Random(seed); + int x=expected.nextInt(16)+8,y=expected.nextInt(expected.nextInt(248)+8),z=expected.nextInt(16)+8; + boolean selected=y<63||expected.nextInt(80/8)==0; + BlockPos origin=new BlockPos(-320,0,-688); + assertEquals(selected?origin.add(x,y,z):null,VanillaLakeCompatibility.choosePosition(actual,origin,63,80)); + assertEquals(expected.nextLong(),actual.nextLong()); + } + Random expected=new Random(51),actual=new Random(51); + expected.nextLong();expected.nextInt(73); + generate(world(new HashMap<>()),actual,new BlockPos(8,48,8),new WorldGenLakes(Blocks.LAVA) { + public boolean generate(World w,Random r,BlockPos p){r.nextLong();r.nextInt(73);return false;} + }); + assertEquals(expected.nextLong(),actual.nextLong()); + } + + @Test void declaredMaterialOutsideItsFormationOrWithDifferentProvenanceIsNotProtected() { + BlockPos at=new BlockPos(3,44,3); + for (IBlockState expected : new IBlockState[]{null,Blocks.GOLD_BLOCK.getDefaultState()}) { + Map cells=new HashMap<>();cells.put(at,Blocks.DIAMOND_BLOCK.getDefaultState()); + VanillaLakeCompatibility.generate(world(cells),new Random(17),new BlockPos(8,48,8),new WorldGenLakes(Blocks.LAVA) { + public boolean generate(World w,Random r,BlockPos p){w.setBlockState(at,Blocks.STONE.getDefaultState(),2);return true;} + },sampler(expected)); + assertEquals(Blocks.STONE.getDefaultState(),cells.get(at)); + } + } +} 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 + } + } +}