From c982974f2b13ca56a2cbb1a727ca4e0d95141053 Mon Sep 17 00:00:00 2001 From: JohnBraham Date: Fri, 27 Nov 2026 11:18:12 +0000 Subject: [PATCH 1/9] Port realistic weather to Minecraft 1.11.2 --- README.md | 8 +- build.gradle | 14 +- docs/API.md | 9 +- docs/BIOME_COMPATIBILITY.md | 129 +++++---- docs/BUILDING.md | 246 +++++------------- docs/CONFIGURATION.md | 8 +- docs/FARMING.md | 28 +- docs/PACK_SUPPORT.md | 12 +- docs/PORTING_1_11_2.md | 95 +++++++ docs/PROJECT_DESCRIPTION.md | 98 +++++++ gradle.properties | 8 +- gradle/eclipse-runs.gradle | 65 ++--- scripts/Prepare-RuntimeFixture.py | 42 +++ scripts/Run-CrashQualification.py | 37 +-- scripts/Run-PackChecks.py | 14 +- scripts/Run-PlantChecks.py | 15 +- scripts/Run-RuntimeChecks.py | 89 +++++++ scripts/Run-ThermometerChecks.py | 8 +- scripts/Run-WeatherEndurance.py | 4 +- .../game/PlantGrowthProbe.java | 23 +- .../verify/BiomeCompatibilityProbe.java | 2 +- .../verify/ClientProbe.java | 2 +- .../verify/TemperatureZoneProbe.java | 4 +- .../verify/ThermometerProbe.java | 20 +- .../verify/WeatherProbe.java | 14 +- .../verify/crash/CrashQualificationProbe.java | 4 +- .../verify/pack/PackSupportProbe.java | 20 +- .../verify/pack/TanChecks.java | 14 +- .../mc/skysrealisticweather/WeatherMod.java | 4 +- .../admin/WeatherCommand.java | 2 +- .../admin/WeatherController.java | 14 +- .../client/ClimateHud.java | 4 +- .../client/ClimateModeScreen.java | 12 +- .../client/DistantPrecipitationRenderer.java | 2 +- .../client/PresetEditorScreen.java | 12 +- .../client/ThermometerHud.java | 6 +- .../client/WeatherAdminScreen.java | 30 +-- .../client/WeatherConfigScreen.java | 28 +- .../client/WeatherGuiFactory.java | 14 +- .../climate/BiomeClimateMap.java | 2 +- .../compat/ForestryClimate.java | 19 ++ .../compat/Integrations.java | 8 +- .../compat/JeiClimatePlugin.java | 12 +- .../compat/ToughAsNailsBridge.java | 10 +- .../compat/WailaProvider.java | 2 +- .../core/PlantTransformer.java | 24 +- .../core/WeatherLoadingPlugin.java | 2 +- .../core/WeatherTransformer.java | 30 +-- .../game/BiomeClimates.java | 8 +- .../skysrealisticweather/game/OtgWeather.java | 16 +- .../skysrealisticweather/game/PlantItems.java | 4 +- .../skysrealisticweather/game/RtgWeather.java | 15 -- .../game/SurfaceTracker.java | 10 +- .../game/TemperatureZones.java | 4 +- .../game/WeatherState.java | 2 +- .../instrument/Thermometer.java | 12 +- .../network/TemperaturePreferenceMessage.java | 2 +- .../lang/{en_US.lang => en_us.lang} | 0 .../core/GenerationHooksTest.java | 39 +++ 59 files changed, 804 insertions(+), 577 deletions(-) create mode 100644 docs/PORTING_1_11_2.md create mode 100644 docs/PROJECT_DESCRIPTION.md create mode 100644 scripts/Prepare-RuntimeFixture.py create mode 100644 scripts/Run-RuntimeChecks.py create mode 100644 src/main/java/zone/moddev/mc/skysrealisticweather/compat/ForestryClimate.java delete mode 100644 src/main/java/zone/moddev/mc/skysrealisticweather/game/RtgWeather.java rename src/main/resources/assets/skysrealisticweather/lang/{en_US.lang => en_us.lang} (100%) create mode 100644 src/test/java/zone/moddev/mc/skysrealisticweather/core/GenerationHooksTest.java diff --git a/README.md b/README.md index 2363ce3..7be8f6f 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ assumptions](docs/TESTING_ASSUMPTIONS.md). Natural plant growth also follows local temperature. Cool-weather crops, warm crops and fruit use editable profiles; fertiliser keeps its native behaviour. -Optional integrations cover HarvestCraft, AgriCraft, Mystical Agriculture and +Optional integrations cover HarvestCraft, Mystical Agriculture and Forestry. Hover seeds, saplings and crops to see preferred temperatures and whether the current local temperature suits them. Celsius is the default; choose Fahrenheit through **Config → Display / units**. See @@ -58,9 +58,13 @@ body temperature and survival systems. JEI, Hwyla and The One Probe provide crop climate information. Operator validation and JSON reports help diagnose pack rules. See [modpack support](docs/PACK_SUPPORT.md). +This is the local **1.11.2 port**, version **0.1.21.111021**. See the +[port status and integration matrix](docs/PORTING_1_11_2.md) for tested builds +and remaining acceptance checks. + ## Install -Use Minecraft **1.10.2**, Forge **12.18.3.2511** and **Java 8**. Put the main jar +Use Minecraft **1.11.2**, Forge **13.20.1.2588** and **Java 8**. Put the main jar in the `mods` folder on both the client and the server. The mod works in single-player, LAN and dedicated-server worlds. It has no required content mods. diff --git a/build.gradle b/build.gradle index 9be7d46..a516454 100644 --- a/build.gradle +++ b/build.gradle @@ -68,13 +68,13 @@ repositories { } dependencies { - compileOnly 'curse.maven:crafttweaker-239197:2433444' - compileOnly('maven.modrinth:ge1sOdFH:9sk3Ji4h') { transitive = false } - compileOnly 'curse.maven:jei-238222:2428966' - compileOnly 'curse.maven:hwyla-253449:2433252' + compileOnly 'curse.maven:crafttweaker-239197:2838724' + compileOnly('maven.modrinth:ge1sOdFH:rVR7XpTd') { transitive = false } + compileOnly 'curse.maven:jei-238222:2461378' + compileOnly 'curse.maven:hwyla-253449:2496989' compileOnly 'curse.maven:the-one-probe-245211:2496984' - compileOnly 'curse.maven:realistic-terrain-generation-237989:2550453' - compileOnly 'curse.maven:open-terrain-generator-265894:2439892' + compileOnly 'curse.maven:forestry-59751:2542509' + compileOnly 'curse.maven:open-terrain-generator-265894:2530369' implementation minecraft.dependency("net.minecraftforge:forge:${minecraft_version}-${forge_version}") constraints { implementation('org.lwjgl.lwjgl:lwjgl:2.9.4-nightly-20150209') { @@ -86,7 +86,7 @@ dependencies { testRuntimeOnly 'org.junit.platform:junit-platform-launcher:1.10.2' } -def mergedOutput = layout.buildDirectory.dir('forge10-development/main') +def mergedOutput = layout.buildDirectory.dir('forge11-development/main') def syncDevelopmentOutput = tasks.register('syncDevelopmentOutput', Sync) { dependsOn tasks.named('classes') from sourceSets.main.output diff --git a/docs/API.md b/docs/API.md index 2074065..0496582 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1,5 +1,8 @@ # Weather API, version 8 +This guide targets Minecraft 1.11.2. Recompile consumers against the matching +API and Forge jars; the matching API number does not imply cross-Minecraft binary compatibility. + Use `zone.moddev.mc.skysrealisticweather.api`. The `-api.jar` in `build/libs` is the compile-only artifact. Use the main mod jar at runtime. Declare Forge loading order after `skysrealisticweather`. @@ -8,7 +11,7 @@ before loading a separate integration class that references the API. ```groovy dependencies { - compileOnly files('libs/SkysRealisticWeather-0.1.21.110021-api.jar') + compileOnly files('libs/SkysRealisticWeather-0.1.21.111021-api.jar') } ``` @@ -144,7 +147,7 @@ Only the `api` package is a supported integration surface. Register selectors during initialization or post-initialization, on both physical sides. Registration freezes at load completion and accepts one profile per selector. Server configuration takes priority. A selector may include block state -properties, or an AgriCraft plant ID. Unregistered, unmapped plants remain native. +properties. Unregistered, unmapped plants remain native. ```java WeatherApi.registerPlantGrowthProfile("example:tomato", @@ -169,7 +172,7 @@ again to a growth path already covered by this mod. Plant registration is separate from biome registration. During world generation use the supplied-biome climate queries and `PlantGrowthProfile.multiplier` if a custom generator needs a suitability decision before a plant exists. The runtime -plant query requires an existing plant, including its state or AgriCraft seed. +plant query requires an existing plant, including its state. See [farming](FARMING.md) for the native hook and fertiliser contracts. Player-facing displays may use Celsius or Fahrenheit. All API temperature values diff --git a/docs/BIOME_COMPATIBILITY.md b/docs/BIOME_COMPATIBILITY.md index cc6a628..99368e2 100644 --- a/docs/BIOME_COMPATIBILITY.md +++ b/docs/BIOME_COMPATIBILITY.md @@ -1,67 +1,62 @@ -# Overworld biome compatibility on Minecraft 1.10.2 - -Sky's Realistic Weather reads the local biome for temperature and precipitation. -The world generator determines whether a newly populated chunk also receives -seasonal surface cover. This matters for modpacks that use the same biome -library with a different world type. - -The following checks used Sky's Realistic Weather 0.1.7.110021 on dedicated -Forge 12.18.3.2511 with Java 8. The selection covers popular Overworld biome -projects, biome configuration tools and replacement generators with over -one million project-wide downloads on CurseForge. The table reports a winter -and a summer sample in the named biome for each setup. - -| Mod and tested build | World type and biome | Exposed weather from the API | Snow on fresh winter terrain | -| --- | --- | --- | --- | -| [Biomes O' Plenty 5.0.0.2290](https://www.curseforge.com/minecraft/mc-mods/biomes-o-plenty/files/2452877) | Biomes O' Plenty, Meadow | Winter snow, summer rain | 190 columns | -| [AbyssalCraft 1.9.4.11](https://www.curseforge.com/minecraft/mc-mods/abyssalcraft/files/2596856) | Default, Darklands Plains | Winter snow, summer rain | 212 columns | -| [Thaumcraft 6.0.BETA8](https://www.curseforge.com/minecraft/mc-mods/thaumcraft/files/2546413) | Default, Magical Forest | Winter snow, summer rain | 251 columns | -| [Vampirism 1.2.5](https://www.curseforge.com/minecraft/mc-mods/vampirism-become-a-vampire/files/2555238) | Default, Vampire Forest | Winter snow, summer rain | 220 columns | -| [GeographiCraft 0.8.9](https://www.curseforge.com/minecraft/mc-mods/climate-control-geographicraft/files/2486027) | Default with its biome layout, Plains | Winter snow, summer rain | 236 columns | -| [BiomeTweaker 2.3.239](https://www.curseforge.com/minecraft/mc-mods/biometweaker/files/2402226) | Default, Plains with a scripted humidity of 0.3125 | Winter snow, summer rain. Both climate queries reported the edited humidity. | 196 columns | -| [Realistic Terrain Generation 4.1.3.0](https://www.curseforge.com/minecraft/mc-mods/realistic-terrain-generation/files/2550453) | RTG, Plains | Winter snow, summer rain | 189 columns | -| RTG 4.1.3.0 + Biomes O' Plenty 5.0.0.2290 + GeographiCraft 0.8.9 | RTG, Biomes O' Plenty Meadow | Winter snow, summer rain | 176 columns | -| [Biome Bundle 5.1](https://www.curseforge.com/minecraft/mc-mods/biome-bundle/files/2430752) with [Open Terrain Generator v21](https://www.curseforge.com/minecraft/mc-mods/open-terrain-generator/files/2439892) | OTG, TemperatePlainsMeadowM | Winter snow, summer rain | 173 columns | -| [The Lost Cities 1.0.2](https://www.curseforge.com/minecraft/mc-mods/the-lost-cities/files/2497880) | Lost Cities, Plains | Winter snow, summer rain | 210 columns | - -Each count is from a 16 × 16 population area and includes only the target -biome. All summer samples contained zero snow columns. RTG waits for neighboring -chunks before decorating. Its measurements include the target chunk's Forge -ICE pass. RTG's snow-layers setting and surface eligibility rules still apply. -RTG and The Lost Cities honor Forge ICE event denial. - -Biomes O' Plenty Glacier also kept its native snow and ice in a warm-season -population fixture. During a winter front, a supplied Outback biome stayed -dry, and the lowland Tropical Rainforest received rain with a seasonal -temperature scale of 0.35. Its native temperature fell with elevation. - -OTG uses the virtual biome and surface height it selected during its frost -pass. When that biome would ordinarily be warm, seasonal weather can add a -single thawable snow layer or freeze an exposed water source if the preset -uses ordinary ice. OTG retains its native frost routine and materials on -naturally cold surfaces that remain cold. Protected biomes always use native -frost. Both the virtual and the saved registry ID, when present, are checked -against the configured protection list. - -OTG can choose a virtual biome for terrain generation and save a different -biome ID in the chunk. In the tested meadow, the supplied-biome climate query -read TemperatePlainsMeadowM, which had no Forge registry name. After generation -the loaded query read `minecraft:plains`, the biome OTG had saved. Integrations -that need the virtual biome's temperature should use the supplied-biome API -during generation and allow for a null `ClimateSample.biomeId`. [Weather API](API.md) - -The published listings for Oh The Biomes You'll Go did not provide a 1.10.2 -artifact for this check. The author's historical notes mention developing -with 1.10.2. [CurseForge files](https://www.curseforge.com/minecraft/mc-mods/oh-the-biomes-youll-go/files/all) -and [author's MCreator listing](https://mcreator.net/modification/21622/oh-biomes-youll-go-5-new-update?page=13) - -## Test conditions - -Each setup used a disposable world with seed 123948. The test forced a -frontal precipitation event at Burlington seasonal strength 2 on winter -day 45, then summer day 45. It queried the generator's chosen biome before -loading a chunk, generated the area synchronously, counted snow before a -weather tick could touch it, and sampled exposed weather on the server. -The Glacier test supplied controlled water and snow-supporting columns during -the Biomes O' Plenty frost pass. Client rendering, other dimensions and the -frequency of naturally scheduled storms were outside these checks. +# Overworld biome and generator compatibility on Minecraft 1.11.2 + +Sky's Realistic Weather reads the selected local biome for temperature and +precipitation. Generator integration additionally applies seasonal snow and ice +while terrain is populated. Runtime climate support alone does not establish +support for a generator's surface pass. + +The pinned builds are listed in [the port matrix](PORTING_1_11_2.md). Disposable +Forge 13.20.1.2588 fixtures test Biomes O' Plenty 6.2.0.2319, AbyssalCraft +1.9.4.11-FINAL, Vampirism 1.2.9, GeographiCraft 0.8.9, BiomeTweaker 3.1.304, +OTG v9 with Biome Bundle v5.1, and The Lost Cities 1.0.2 with CompatLayer 0.3.1. + +Each controlled generation test uses Burlington at strength 2, winter day 45, +then summer day 45, with a forced frontal precipitation event and seed 123948. +The probe queries the generator's biome, generates fresh terrain and counts +cover immediately, before normal weather ticks can alter it. This tests the +native generation path without relying on a later snow tick. Actual candidate +hashes, weather readings and counts are retained in the port's verification +folder; 1.10.2 counts and performance figures are not reused. + + +| Profile | Snow columns in fresh winter terrain | Snow columns in fresh summer terrain | +| --- | ---: | ---: | +| Biomes O' Plenty | 218 | 0 | +| AbyssalCraft | 212 | 0 | +| Vampirism | 256 | 0 | +| GeographiCraft | 236 | 0 | +| BiomeTweaker | 196 | 0 | +| The Lost Cities | 210 | 0 | +| OTG + Biome Bundle | 173 | 0 | + +Counts refer to the target biome within a 16 × 16 population area, not the +whole world. Client visuals and whole-chunk performance are separate checks. + +## Native exceptions and ownership + +Protected polar and glacier biomes keep their native frost routine. Seasonal +cover outside those exceptions is tracked so warming can remove only deposits +the mod owns. Forge ICE denial and the public seasonal-surface event remain +available to veto placement. Disabling seasonal world generation retains the +generator's native behaviour; it does not regenerate existing chunks. + +## Open Terrain Generator + +The v9 adapter uses the virtual biome and height selected by OTG's frost pass. +Warm native surfaces may receive one thawable snow layer or freeze an exposed +water source when ordinary ice is configured. Naturally cold surfaces retain +OTG's native materials and frost behaviour. Both virtual and saved registry IDs +are checked against the protection list. + +OTG can generate with a virtual biome and store another biome ID in the chunk. +The tested TemperatePlainsMeadowM has no registry ID while the saved biome is +`minecraft:plains`. During generation, consumers should use the supplied-biome +API and allow `ClimateSample.biomeId` to be null. Loaded queries use the biome +actually saved in the chunk. See [the weather API](API.md). + +## Unavailable version targets + +RTG and Thaumcraft have no 1.11.2 artifacts in their project file listings; their +1.10.2 integration does not establish support here. Oh The Biomes You'll Go has +no verified original artifact in this qualification set. The port's launch +profiles contain only pinned, version-appropriate jars. diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 14df4d9..940666d 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -2,11 +2,11 @@ Run Gradle from this checkout with Java 17 and configure a Java 8 toolchain for Minecraft. The wrapper uses Gradle 9.6.1 and the sibling ForgeGradle -toolchain with stable 29 mappings. +toolchain with stable 32-1.11 mappings. -Gradle downloads the RTG 4.1.3.0 and Open Terrain Generator v21 jars from -CurseMaven to compile the optional integrations. The main jar runs on plain Forge -and does not bundle either mod. +Gradle resolves pinned 1.11.2 integrations for compilation and separate optional +Eclipse profiles. Original third-party jars are never bundled. The supported +builds and port qualification are listed in [port status](PORTING_1_11_2.md). ```text gradlew check build writeReleaseChecksum prepareRuntimeProbe @@ -17,6 +17,7 @@ The main jar, compile-only API jar, sources, Javadocs and main jar checksum are Use the main jar for a normal Minecraft installation. The mapped jar in `build/libs-dev` is for the development classpath. +Use the outer `SkysRealisticWeather111` folder as the Eclipse workspace. Import the nested checkout in Eclipse with Buildship and use the generated `runClient` or `runServer` launch profile with Java 8 and a disposable game directory. Use **Gradle → Refresh Gradle Project** in Eclipse after dependency @@ -37,25 +38,21 @@ development runtime. Its first run needs access to CurseMaven. | Eclipse launch | Additional mods | | --- | --- | | `runClientBoP` | Biomes O' Plenty | -| `runClientRTG` | Realistic Terrain Generation | | `runClientOTG` | Open Terrain Generator | | `runClientBiomeBundle` | Open Terrain Generator and Biome Bundle | | `runClientLostCities` | The Lost Cities and CompatLayer | -| `runClientRTGBoPGeo` | RTG, Biomes O' Plenty and GeographiCraft | | `runClientGeographiCraft` | GeographiCraft | | `runClientBiomeTweaker` | BiomeTweaker | | `runClientAbyssalCraft` | AbyssalCraft | -| `runClientThaumcraft` | Thaumcraft and Baubles | | `runClientVampirism` | Vampirism | -| `runClientHarvestCraft` | Pam's HarvestCraft 1.10.2j | -| `runClientAgriCraft` | AgriCraft a21 and InfinityLib 0.11.0 | -| `runClientMysticalAgriculture` | Mystical Agriculture 1.5.10 | -| `runClientForestry` | Forestry 5.2.17.388 | -| `runClientBaseMetals` | Base Metals 2.5.1.110021 and OreSpawn 4.1.6.110021 | -| `runClientFarming` | All four farming mods and InfinityLib | +| `runClientHarvestCraft` | Pam's HarvestCraft 1.11.2h | +| `runClientMysticalAgriculture` | Mystical Agriculture 1.5.9 | +| `runClientForestry` | Forestry 5.3.4.257 | +| `runClientBaseMetals` | Base Metals 2.5.2.111021 and OreSpawn 4.1.7.111021 | +| `runClientFarming` | HarvestCraft, Mystical Agriculture and Forestry | Choose the matching world type when creating a test world for Biomes O' -Plenty, RTG, OTG or The Lost Cities. Use the Biome Bundle preset in the OTG +Plenty, OTG or The Lost Cities. Use the Biome Bundle preset in the OTG world creation screen for `runClientBiomeBundle`. The runtime probe jars in `build/verification/probe` belong in disposable @@ -63,182 +60,71 @@ test profiles. They exercise native Forge lifecycle, hooks, save/reload, configuration and client synchronization. The main jar contains only the mod's production classes and resources. -For accelerated climate checks on Windows, build `prepareRuntimeProbe`, then run: +## Disposable runtime fixture -```text -python scripts/Run-WeatherEndurance.py -python scripts/Analyze-WeatherEndurance.py build/verification/weather-endurance/ -``` - -This uses the existing disposable dedicated Forge fixture under -`build/verification/worldgen-performance/whole-chunk-v1/1-vanilla`. It starts -one Java 8 server at a time, hidden, at below-normal priority, pinned to one -logical CPU with a 1 GiB heap limit. It opens no client and uses no desktop -input. The default sweep samples every 100 Minecraft ticks for 20 years per -preset on three seeds, plus five years at strength 0 and 2. The native-weather -stage runs 2,190 Minecraft days in every preset and Per Biome Climate, -discarding the first 365 days for warm-up and scoring five 365-day blocks. Eight sites include lowlands, Y=200, coast, mountain, -jungle, desert, Cold Taiga and native Arctic terrain. Surface columns use a -seeded geometric weather-selection cadence of 1/4096 per tick, with 09:00 -majority cover observations, runtime reconstruction and a process save/reload. -A 30-day synthetic real-weather replay checks the feed-to-timer control path. - -Use `--years`, `--seeds`, `--native-days`, `--phase`, `--output`, `--jar` and -`--extra-mod` to choose durations, independent seeds, stages, a fresh evidence -directory, a candidate jar and optional compatibility jars. Existing -stage logs are preserved. Receipts record artifact hashes, exit status, CPU -time and peak working set; CSV files retain seasonal frequencies, event types, -start hours, temperatures, spell lengths, estimated rainfall thresholds and -daily biome/deposit readings. Use the analyzer's `--sweep-only` option for -an independent-seed sweep without the native stages. The default jar follows -`mod_version` in `gradle.properties`. - -Use `--sample-step`, `--sweep-climates`, `--extreme-years`, `--native-climates` -and `--warmup-days` for resolution checks and focused runtime cases. The analyzer -supports `--native-only` for runtime/reload-only evidence. `prepareRuntimeProbe` -records compiled source and jar hashes; the runner rejects stale probes or -source changes and changing candidate jars between stages. It also snapshots -packaged climate tables and acceptance objectives. - -The native stage advances the production weather handlers and Minecraft's -weather timers directly. It does not simulate entity AI, random block ticks, -client rendering or a full modpack's world-generation workload. The analyzer -checks broad climate relationships; its pass is not a claim of calibrated -meteorological accuracy. Review frequency and temperature findings alongside -the checks. The initial report is in -`build/verification/weather-endurance/RESULT.md`. -The subsequent realism fixes and independent-seed checks are recorded in -`build/verification/weather-realism/RESULT.md`. - -The revised climate balance, corrected observations, independent seeds and -old-candidate comparison are recorded in -`build/verification/climate-balance/RESULT.md`. - -## Packaged farming checks +Prepare the probes and original integration jars, then point the fixture helper +at an already installed Forge 13.20.1.2588 server engine (with its libraries): ```text -python scripts/Run-PlantChecks.py --profile combined --phase contracts --output build/verification/plant-growth/ -python scripts/Run-PlantChecks.py --profile combined --phase reload --output build/verification/plant-growth/ -python scripts/Run-PlantChecks.py --profile combined --phase endurance --output build/verification/plant-growth/ -python scripts/Run-PlantChecks.py --profile combined --phase performance --output build/verification/plant-growth/ +gradlew preparePackProbe prepareCrashProbe preparePublishedIntegrationMods +python scripts/Prepare-RuntimeFixture.py --engine-dir ``` -Other profiles are `vanilla`, `harvestcraft`, `agricraft`, `mystical` and -`forestry`. The runner expects original released jars under -`build/verification/plant-growth-review`, and uses the same disposable Forge -fixture and resource limits as the weather checks. It rejects unbuilt source, -changed candidates and existing stage logs, and records original jar hashes. -The endurance phase defaults to five 365-day Minecraft years on three seeds -in every preset. It selects actual native plant updates at a seeded geometric -cadence of 3/4096 per game tick, with controlled light and hydrated soil. Rates -are checked against independently measured native growth and the configured -suitability curve. This isolates temperature from irrigation and light effects. -The performance phase measures native block update cost with the policy enabled -and its event listener removed for the native baseline, then translates it to the expected native random-tick cadence -for 1,000 and 10,000 crops. It does not measure whole-server tick time. - -## Packaged thermometer checks +The helper copies only the verified engine jars and creates fresh test settings. +It copies no saves, modpacks or player worlds. Runtime checks use Java 8, a hidden +process, below-normal priority, one logical CPU and a 1 GiB heap. Evidence stays +under ignored `build/verification`; failed receipts are preserved. ```text -python scripts/Run-ThermometerChecks.py --profile vanilla --output build/verification/thermometer/ -python scripts/Run-ThermometerChecks.py --profile vanilla --phase reload --output build/verification/thermometer/ -python scripts/Run-ThermometerChecks.py --profile basemetals --output build/verification/thermometer/ -python scripts/Run-ThermometerChecks.py --profile basemetals --phase reload --output build/verification/thermometer/ +python scripts/Run-PlantChecks.py --profile combined --output build/verification/plants/ +python scripts/Run-PlantChecks.py --profile combined --phase reload --output build/verification/plants/ +python scripts/Run-PackChecks.py --profile full --output build/verification/packs/ +python scripts/Run-PackChecks.py --profile full --phase reload --output build/verification/packs/ +python scripts/Run-ThermometerChecks.py --profile basemetals --output build/verification/thermometer/ +python scripts/Run-ThermometerChecks.py --check temperature-zones --output build/verification/heat/ +python scripts/Run-ThermometerChecks.py --check temperature-zones --phase reload --output build/verification/heat/ +python scripts/Run-CrashQualification.py --case edge --output build/verification/crash/ +python scripts/Run-CrashQualification.py --case stress --output build/verification/crash/ ``` -Build `prepareRuntimeProbe` first. The runner uses the disposable Forge fixture -and hidden, below-normal-priority, single-CPU server limits described above. -The Base Metals profile expects the original pinned `base-metals-240967-9280029.jar` -and `mmd-orespawn-245586-9518063.jar` under -`build/verification/thermometer/providers/`. It records their hashes and checks -that the originals and test copies are unchanged. Recipes, ordinary-player -placement and readings, both hands, support loss, metadata, unit preferences, -native-temperature fallback and physical save/reload are exercised. Test-only -ore-dictionary fixtures demonstrate late registration without adding mercury -to the distributed mod. These server checks do not render the client HUD. - -## Precipitation boundaries - -`PrecipitationRendererTest` transforms the real mapped vanilla renderer and -verifies its bytecode stack, the precipitation-pass gate, both rain/snow opacity -hooks and the existing local fog/particle hooks. A disposable dedicated server -with the packaged probe and `-Dskyweather.probe=precipitation` tests the shared -column policy against native biome data. It checks snow/rain beside clear -climates, packet reconstruction, moving cell gaps, intensity scaling, forced -blizzard temperature limits, live/passive fallback and unloaded terrain. -Headless tests verify policy and bytecode; they do not establish rendered visual -acceptance. See `build/verification/precipitation-boundaries/RESULT.md` for the -local candidate and receipts. - -## Distant precipitation - -Add `-Dskyweather.distant=true` to the packaged precipitation probe for a -loaded flat-world landscape with adjacent jungle and Arctic biomes. It checks -curtains beyond 128 blocks, mixed rain/snow, distance/quality limits, disabled -and clear paths and absent terrain. It writes `distant-weather/columns.csv` -and sampling timing percentiles after warm-up. - -`verify.DistantRenderProbe` is a standalone mapped Java 8 probe. Its arguments -are the exported columns CSV, a Minecraft jar containing vanilla textures, -and a fresh output directory. Add the mapped main/probe jars and normal -Minecraft runtime libraries to the classpath and set `java.library.path` to -the LWJGL natives folder. It creates an offscreen Pbuffer, exercises the -production drawing method, writes previews and measures two resolutions and -three distance bounds. It opens no game window. Timings include view culling, -vertex submission and synchronized drawing, with an empty-pass baseline. -They do not measure Minecraft's terrain, entities or complete frame time. -The retained local runners and artifact-bound receipts are in -`build/verification/distant-weather/`. - -## Local temperature zones - -The packaged probe's `-Dskyweather.probe=temperature-zones` mode checks native -zone registration, replacement/removal, dimensions, crops, thermometers, -thread/bounds rules, furnace operation, burnout, breakage and query timings -with 2,000 unrelated zones. Use `-Dzones.reload=true` in a second process on -the same disposable world to verify runtime-only child registration and native -furnace recovery. Unit tests cover inclusive bounds, chunk/section indexing, -deterministic priorities, chunk snapshot encoding/clearing and C/F editing. -The retained runner, compiled API-only consumer, source hashes and results are -under `build/verification/temperature-zones/`. These checks do not replace a -live multiplayer UI/transport qualification. - -## Crash and saved-world qualification - -Build `prepareCrashProbe` to produce the separate, optional-dependency -`weather-qualification-probe.jar`. It can run the same native scenario with -or without the main weather jar. Keep both probes out of a playable profile. +Plant profiles are `vanilla`, `harvestcraft`, `mystical`, `forestry` and `combined`. +Pack profiles also include individual optional bridges and `--disabled` coverage. +Receipts bind the candidate, probes, source and unchanged original provider jars. +The 1.10.2 Sylvester pack is not a 1.11.2 test fixture; this port's crash runner +accepts synthetic edge and stress worlds only. + +## Accelerated years and native generation ```text -python scripts/Run-CrashQualification.py --case edge --output build/verification/crash-qualification/ -python scripts/Run-CrashQualification.py --case stress --variant control --output build/verification/crash-qualification/ -python scripts/Run-CrashQualification.py --case stress --output build/verification/crash-qualification/ -python scripts/Run-CrashQualification.py --case sylvester --variant control --ticks 6000 --output build/verification/crash-qualification/ -python scripts/Run-CrashQualification.py --case sylvester --ticks 6000 --output build/verification/crash-qualification/ -python scripts/Run-CrashQualification.py --case sylvester --phase reload --ticks 6000 --output build/verification/crash-qualification/ +python scripts/Run-WeatherEndurance.py --years 2 --seeds 81173 29119 --native-days 730 --warmup-days 365 --extreme-years 1 --output build/verification/weather/ +python scripts/Analyze-WeatherEndurance.py build/verification/weather/ +python scripts/Run-PlantChecks.py --profile combined --phase endurance --years 2 --output build/verification/plants/ +python scripts/Run-RuntimeChecks.py --mode population --world-type CUSTOMIZED --fixed-biome 1 --universal --option skyweather.population=winter --expect "SKY_WEATHER_CHECK POPULATION_WINTER PASS" --output build/verification/generation/ ``` -The edge case injects a non-finite biome temperature and verifies that crop -queries become unavailable, native growth continues, and valid readings recover. -The stress case ticks valid vanilla, HarvestCraft and Mystical Agriculture plant -states across four season dates and resolves item metadata/NBT variants with the -combined farming stack. Existing packaged farming contracts exercise AgriCraft -tiles, Forestry, fertiliser and hook compatibility separately. - -The Sylvester case requires a previously verified, independent snapshot under -`build/verification/crash-qualification/input-sylvester`, plus exported saved -crop points and target chunks. It never launches the original profile. Preserve -the source manifest and verify both source and snapshot after qualification. -This runner is specific to the retained local fixture, not a world-copy tool. -It excludes duplicate older jars and client-only OptiFine; pins Forge 2511 in -both control and weather runs; redirects copied backup settings into the copy; -and disables Forge's automatic deletion of erroring entities in copied configs. - -Saved-world tests execute actual server ticks, native crop callbacks, chunk -rotation, tile serialization and physical save/reload. Each tick also advances -the weather calendar by one day; calendar years do not represent years of full -server physics. Tests run hidden, below normal priority on one CPU, with a 3 GiB -heap for Sylvester and 1 GiB for synthetic cases. Receipts bind the jars and -record failures without replacing them. These checks cannot establish live -client, OptiFine, renderer, multiplayer or every modpack interaction coverage. -See `build/verification/crash-qualification/RESULT.md` for the qualified candidate. +`--universal` selects Burlington for a controlled generator comparison; omitting +it keeps the normal Per Biome Climate default. `--fixed-biome` writes the native +customized-world fixed-biome setting. `--mod` adds an original pinned integration +jar, for example `--mod BoP`. Use `--world-type BIOMESOP` for that generator; +Biome Bundle needs `--world-type OTG --level-name "Biome Bundle"`, plus its two +mods. `--option` passes additional named probe settings. Use a new output for a +new candidate or scenario; `--stage reload` reuses a matching passing world. + +The short example is a pilot; the retained balance thresholds were designed for +longer samples. Use `--years 20 --native-days 2190 --warmup-days 365 +--extreme-years 5` for full qualification, and preserve unsuccessful pilot results. + +Climate checks advance production weather handlers and native weather timers. +They isolate seasonal behaviour rather than simulating full-server physics. +Farming endurance uses seeded natural crop callbacks with valid light and soil. +Neither establishes real meteorological accuracy or full-server performance. + +## Acceptance scope + +Unit tests verify native renderer and Overworld generation bytecode as well as +climate, network and API contracts. Packaged servers cover native hooks, crops, +commands, temperature zones, crafting and save/reload. The distant-render probe +can draw through an offscreen LWJGL Pbuffer without a game window. These checks +do not replace manual client visuals, live multiplayer testing or testing a +particular modpack. Old 1.10.2 timing and gameplay receipts do not qualify this +version. See [current port evidence and limitations](PORTING_1_11_2.md). diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 2172b26..82c504a 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -69,7 +69,7 @@ profile. Changing general gameplay options keeps the preset selected. The `biome_climates` section maps biome registry IDs to climate preset IDs. Startup adds missing entries for registered vanilla and mod biomes. The starter mappings cover vanilla, Biomes O' Plenty and known Overworld biomes from -Thaumcraft, AbyssalCraft and Vampirism. Other registered biomes use Forge tags, +AbyssalCraft and Vampirism. Other registered biomes use Forge tags, temperature, rainfall and descriptive biome names to choose a default. GeographiCraft and BiomeTweaker edits are read before these defaults are generated. Existing mapping entries take precedence. @@ -165,8 +165,8 @@ mod, existing snow and ice behave as standard Minecraft blocks. ### Snow and ice on new chunks -The standard Overworld, Biomes O' Plenty, RTG, The Lost Cities and Open Terrain -Generator v21 use local weather during their snow and ice pass. A cold storm can +The standard Overworld, Biomes O' Plenty, The Lost Cities and Open Terrain +Generator v9 use local weather during their snow and ice pass. A cold storm can leave a fresh snow layer on newly explored grassland. Cold, clear weather can freeze exposed water, and naturally cold surfaces can retain a dusting between storms. Warm weather skips the seasonal surface deposits. The mod @@ -197,7 +197,7 @@ using seasonal snow and thaw during normal play. Superflat and generators without a seasonal integration use their own population rules. For results with other Overworld generators and biome mods, see the -[Minecraft 1.10.2 biome compatibility checks](BIOME_COMPATIBILITY.md). +[Minecraft 1.11.2 biome compatibility checks](BIOME_COMPATIBILITY.md). The presets use Minecraft temperature and weather multipliers. Regional profiles take their seasonal patterns from published climate normals and diff --git a/docs/FARMING.md b/docs/FARMING.md index 3a2e36e..3f568be 100644 --- a/docs/FARMING.md +++ b/docs/FARMING.md @@ -22,14 +22,14 @@ positions retain precedence. | Vanilla crops, stems, cocoa, reeds, cactus and plants using Forge's crop event | Natural growth suitability through the Forge event; respect another mod's explicit ALLOW or DENY. | | Vanilla and compatible saplings | Forge sapling event, with state-specific tree profiles. | | Pam's HarvestCraft field crops and fruit | Natural growth rolls, including fruit logs. Saplings use the Forge sapling event. | -| AgriCraft | The seeded, immature natural crop-stick callback. Seed identity selects the profile. Mature plants, cross-crop processing, genetics and direct growth/fertiliser calls retain native behaviour. | | Mystical Agriculture | Resource crops are exempt by default. An explicit mapping can opt them into a temperature profile. | -| Forestry | Ambient temperature and a seasonal humidity proxy reach Forestry's climate manager, including consumers such as bees. Its controlled climate positions retain their own temperature and humidity. Ordinary mapped crops also recognise a Forestry controlled temperature at their position. | +| Forestry | Ambient temperature and a seasonal humidity proxy reach Forestry's climate manager, including consumers such as bees, through Forestry 5.3's ambient climate-info fallback. Its controlled climate positions retain their own temperature and humidity. Ordinary mapped crops also recognise a Forestry controlled temperature at their position. | -The pinned Minecraft 1.10.2 targets are HarvestCraft **1.10.2j**, AgriCraft -**2.0.0-0.11.0-a21** with InfinityLib **0.11.0**, Mystical Agriculture -**1.5.10**, and Forestry **5.2.17.388**. Other releases need their own -compatibility check. +The pinned Minecraft 1.11.2 targets are HarvestCraft **1.11.2h**, Mystical +Agriculture **1.5.9**, and Forestry **5.3.4.257**. AgriCraft has no published +1.11.2 build in its project file listing and is not a supported integration +on this port. Legacy config keys remain readable for pack migration. Other +releases need their own compatibility check. The optional adapters use narrow runtime hooks inside this mod. Downloaded third-party jars and sources are not edited or bundled. A hook whose expected @@ -75,19 +75,11 @@ The `mappings` list contains overrides, for example: minecraft:wheat=cool minecraft:sapling[type=spruce]=cool harvestcraft:pamtomatocrop=warm -agricraft:tomato_plant=warm mysticalagriculture:inferium_crop=exempt ``` -AgriCraft selectors use `agricraft:` from its plant definitions, rather -than the shared crop-stick block ID. A block selector can provide a fallback. -State selectors are more specific than a plain block ID within the same source. -Config overrides API registrations, which override the bundled mappings. The -last equally specific matching row wins. Unknown plants keep native growth. -Invalid rows remain in the config for correction; unresolved profiles keep -native growth. Magical seed namespaces remain exempt unless a rule explicitly -selects another profile. The bundled plant list is in -`assets/skysrealisticweather/plant_growth.json` inside the mod jar. +The legacy `agricraft` switch and selectors remain readable for configuration +migration; they do not represent a supported 1.11.2 dependency. `/skyweather crop` inspects the plant under an operator's crosshair; `/skyweather crop x y z` inspects a loaded position. It reports the resolved @@ -117,9 +109,7 @@ that it is unavailable. Missing temperature data leaves native growth in effect; climate rules resume when a valid reading returns. Vanilla and supported farming seeds, sapling variants, HarvestCraft produce, -Mystical Agriculture crops/essences and AgriCraft's NBT seed identities are -recognised. Tagged AgriCraft seeds label their crop-stick growth rules; ordinary -planting outside crop sticks uses the underlying plant's own rules. Crafted foods do not acquire crop tooltips. When several plants +Mystical Agriculture crops and essences are recognised. Crafted foods do not acquire crop tooltips. When several plants produce the same item and have different climate rules, the tooltip directs you to their seeds rather than picking one. Native plantable items from other mods can use the existing profile mappings; unrelated custom item encodings may need diff --git a/docs/PACK_SUPPORT.md b/docs/PACK_SUPPORT.md index 2e97c2a..ccae517 100644 --- a/docs/PACK_SUPPORT.md +++ b/docs/PACK_SUPPORT.md @@ -1,4 +1,4 @@ -# Modpack support (Minecraft 1.10.2) +# Modpack support (Minecraft 1.11.2) All integrations are optional. Install their original jars alongside Sky's Realistic Weather; none are bundled. The `integrations` config category can @@ -9,7 +9,7 @@ cover CraftTweaker, ToughAsNails, JEI, Hwyla, TheOneProbe and PackSupport ## CraftTweaker 3 -Target: CraftTweaker 1.10.2 **3.0.26** (legacy `MineTweaker3`). Example: +Target: CraftTweaker 1.11.2 **3.1.0-legacy** (`crafttweaker`). Example: ```zenscript import mods.skysrealisticweather.Climate; @@ -33,7 +33,7 @@ changed definitions are held pending its next restart. Weather, existing crop rules and connected clients keep the active snapshot. `/skyweather validate` reports pending changes. An unchanged reload does not require a restart. -CraftTweaker 3.0.26 runs its initial scripts **after spawn terrain preparation**. +CraftTweaker 3 runs its initial scripts **after spawn terrain preparation**. Script biome mappings apply before gameplay and to subsequently generated chunks. Put mappings needed for initial spawn generation in `biome_climates` in Sky's config. Existing terrain is never regenerated. @@ -79,7 +79,7 @@ on an existing world. The default calendar remains 365 Minecraft days. ## Tough As Nails -Target: **Tough As Nails 1.9.4-1.1.1** on Minecraft 1.10.2. When present, the +Target: **Tough As Nails 1.11.2-2.1.0.65** on Minecraft 1.11.2. When present, the bridge uses Sky's effective local temperature, including registered heated zones and burning furnaces, as TAN's ambient target. TAN retains its body temperature, response timer, clothing, wetness, proximity and other modifiers, @@ -97,7 +97,7 @@ native TAN behaviour. An incompatible bridge disables itself and logs why. ## Farming information -JEI **3.14.7.420** adds a **Climate requirements** category for recognised plant +JEI **4.5.1.296** adds a **Climate requirements** category for recognised plant items once a world is available. It shows preferred temperatures, current local suitability and typical phase-midpoint temperatures at the player's position. Phase estimates exclude weather episodes and local heating; native @@ -105,7 +105,7 @@ soil/light requirements still apply. Moving, changing season or heating an area changes the displayed live reading. The item catalogue is indexed once per joined world, rather than scanned every frame. -Hwyla **1.8.17-B31** and The One Probe **1.4.19** show the same current crop +Hwyla **1.8.22-B37** and The One Probe **1.4.19** show the same current crop requirements and growth status when looking at a plant. Rules and climate data come from the server; each player sees Celsius or Fahrenheit according to their existing preference. An unavailable temperature never becomes a false diff --git a/docs/PORTING_1_11_2.md b/docs/PORTING_1_11_2.md new file mode 100644 index 0000000..9f263b2 --- /dev/null +++ b/docs/PORTING_1_11_2.md @@ -0,0 +1,95 @@ +# Minecraft 1.11.2 port + +This checkout targets **Minecraft 1.11.2**, **Forge 13.20.1.2588**, Java 8, +and stable **32-1.11** mappings. The local candidate is **0.1.21.111021**, +with **API 8**, **config 8** and **world settings schema 1**. It starts from +the merged 1.10.2 implementation at `a4c6f7930c06cd97c2a503deecc6f92137c167f3`. + +The 365-Minecraft-day calendar and Per Biome Climate remain the defaults. +Seasonal surface ownership, native Arctic exceptions, natural crop growth, +mercury thermometers, tapered local heaters and child temperature zones retain +their existing contracts. Config schema compatibility does not make whole +Minecraft saves or third-party mod jars interchangeable between versions. +Use a backup and a version-appropriate test pack for migration. + +## Version-specific changes + +- Forge dependency and optional mod IDs match their 1.11.2 registrations. +- Items use the 1.11 empty-stack and count contracts. Thermometer placement, + hand use, creative-tab entries and block callbacks use the new signatures. +- The config GUI supports the Forge 1.11 factory methods; language assets use + the lowercase resource name expected by this version. +- The OTG v9 bridge uses its new package and loaded-terrain material access. + It retains OTG's virtual biome, protected native cover and native materials. +- Forestry 5.3's ambient climate-info fallback receives local temperature and + seasonal humidity. Controlled climate rooms return through Forestry's own path. +- Tough As Nails uses `SeasonsOption` and its configurable temperature-scale + midpoint; its body temperature, response timer and other modifiers remain native. +- JEI uses the 4.x ingredient registry and category contract. + +## Integration builds + +All jars are optional and unmodified. These are the pinned **1.11.2** targets; +version-specific qualification is recorded below. A server load check cannot +establish client visual acceptance. + +| Integration | Minecraft version | Pinned build | Coverage | +| --- | --- | --- | --- | +| [Pam's HarvestCraft](https://www.curseforge.com/minecraft/mc-mods/pams-harvestcraft/files/2410937) | 1.11.2 | 1.11.2h | Native growth, fruit/logs/saplings, produce tooltips and fertiliser | +| [Mystical Agriculture](https://www.curseforge.com/minecraft/mc-mods/mystical-agriculture/files/2487658) | 1.11.2 | 1.5.9 | Default exemptions, opt-in growth rules and item identities | +| [Forestry](https://www.curseforge.com/minecraft/mc-mods/forestry/files/2542509) | 1.11.2 | 5.3.4.257 | Ambient climate info, humidity and controlled-room precedence | +| [CraftTweaker](https://www.curseforge.com/minecraft/mc-mods/crafttweaker/files/2838724) | 1.11.2 | 3.1.0-legacy, file 2838724 | Startup/reload rules, scripts, synchronized snapshots | +| [Tough As Nails](https://modrinth.com/mod/tough-as-nails/version/rVR7XpTd) | 1.11.2 | 2.1.0.65 | Ambient correction, heated zones and restored seasonal ownership | +| [JEI](https://www.curseforge.com/minecraft/mc-mods/jei/files/2461378) | 1.11.2 | 4.5.1.296 | API compilation and dedicated-server optional-side loading; client UI acceptance pending | +| [Hwyla](https://www.curseforge.com/minecraft/mc-mods/hwyla/files/2496989) | 1.11.2 | 1.8.22-B37 | Registered provider, server data and ordinary-crop climate presentation | +| [The One Probe](https://www.curseforge.com/minecraft/mc-mods/the-one-probe/files/2496984) | 1.11.2 | 1.4.19 with CompatLayer 0.3.1 | Provider registration and crop climate presentation | +| [Biomes O' Plenty](https://www.curseforge.com/minecraft/mc-mods/biomes-o-plenty/files/2536549) | 1.11.2 | 6.2.0.2319 | Climate mapping and native seasonal population | +| [AbyssalCraft](https://www.curseforge.com/minecraft/mc-mods/abyssalcraft/files/2596860) | 1.11.2 | 1.9.4.11-FINAL | Overworld climate mapping and seasonal population | +| [Vampirism](https://www.curseforge.com/minecraft/mc-mods/vampirism-become-a-vampire/files/2555244) | 1.11.2 | 1.2.9 | Overworld climate mapping and seasonal population | +| [GeographiCraft](https://www.curseforge.com/minecraft/mc-mods/climate-control-geographicraft/files/2486027) | 1.11.2 | 0.8.9 | Generated biome layout and seasonal population | +| [BiomeTweaker](https://www.curseforge.com/minecraft/mc-mods/biometweaker/files/2478061) | 1.11.2 | 3.1.304 | Native biome configuration and seasonal population | +| [Open Terrain Generator](https://www.curseforge.com/minecraft/mc-mods/open-terrain-generator/files/2530369) | 1.11.2 | v9, file 2530369 | Optional frost bridge, tested with Biome Bundle | +| [Biome Bundle](https://www.curseforge.com/minecraft/mc-mods/biome-bundle/files/2431190) | 1.11.2 | v5.1, file 2431190 | Virtual-biome winter/summer population | +| [The Lost Cities](https://www.curseforge.com/minecraft/mc-mods/the-lost-cities/files/2497880) | 1.11.2 | 1.0.2 with CompatLayer 0.3.1 | Native seasonal population | +| [Base Metals](https://www.curseforge.com/minecraft/mc-mods/base-metals/files/9541705) | 1.11.2 | 2.5.2.111021 with OreSpawn 4.1.7.111021 | Actual ore-dictionary mercury recipe, placement and reload | + +RTG, Thaumcraft and AgriCraft have no 1.11.2 artifacts in their project file +listings. Their 1.10.2 support does not carry over; this port supplies no launch +profiles or support claim for them. Legacy AgriCraft config fields remain +readable. Oh The Biomes You'll Go has no verified original 1.11.2 artifact in +this port's qualification set. + +## Verification and acceptance + +The local build passes **56 unit tests**, including native renderer and generation +bytecode verification. The combined farming suite passes **571,769 contracts** +and process reload; two-year farming simulations cover all 28 presets on two +independent seeds. Core, individual and combined optional bridge profiles pass, +as do disabled bridges, mercury crafting, heaters, temperature zones, invalid +climate fallback, a plant/item stress matrix and native save/reload. + +Seven biome/generator profiles pass winter/summer generation checks. Separate +fixtures verify Arctic and glacier native cover, Cold Taiga seasonal behaviour, +Forge ICE denial, clear weather, seasonal ownership and thaw after reload. +Three Java API examples compile against the matching 1.11.2 API. Distant weather +passes native sampling and six offscreen rendering configurations. + +The longer weather run uses 20-year sweeps on two independent seeds, five-year +strength extremes and six native years per climate (one warm-up, five scored). +It completes without crashes and passes **335 of 336 balance checks**. British +Isles (`oxford`) averages **35.025 snow dates/year** against a design band of +18–35: one extra snow date across 40 simulated years. This small upper-band +finding is retained, and no climate values or acceptance thresholds were changed +for the port. The shorter pilot's three low-band findings are also preserved; +they do not recur in the longer sample. Statistical qualification is therefore +not reported as an unqualified pass. + +Local checks and their candidate hashes are retained under +`build/verification/port-1.11.2`. See `RESULT.md` there for final receipts, +including preserved unsuccessful port attempts. [Build instructions](BUILDING.md) +explain how to repeat the checks with fresh disposable worlds. + +The port is local and unpublished. Manual client gameplay, visual acceptance, +live two-client multiplayer and a new whole-chunk performance baseline remain +separate acceptance work. Published 1.10.2 timings and the 1.10.2 Sylvester pack +are not used to claim 1.11.2 coverage. No player world is launched by these tests. diff --git a/docs/PROJECT_DESCRIPTION.md b/docs/PROJECT_DESCRIPTION.md new file mode 100644 index 0000000..bce9abc --- /dev/null +++ b/docs/PROJECT_DESCRIPTION.md @@ -0,0 +1,98 @@ +# Sky’s Realistic Weather + +Spring rain, summer thunderstorms, autumn mist and the first snow on the hills—Sky’s Realistic Weather gives your Minecraft world a changing climate, with seasons that affect exploring, farming and the landscape around you. + +Weather responds to **biome, altitude, season and time of day**. The same storm might bring rain to a valley and snow to the mountains above it, while tropical forests and deserts follow their own weather patterns. + +## Seasons that suit your world + +The default year lasts **365 Minecraft days**, with shorter cycles available if you prefer seasons to move more quickly. Season lengths, strength, temperatures and weather patterns are configurable. + +Choose how your world’s climate works: + +- **Per Biome Climate — the default.** Each biome receives an appropriate climate, allowing temperate forests, tropical regions, deserts and frozen landscapes to behave differently. +- **Universal Climate.** Choose one climate as the basis for the world, with local biome and elevation adjustments. +- **Real World Climate.** Use weather data for a configured real-world location, with a seasonal fallback when data is unavailable. + +The editable preset library includes Mediterranean, British Isles, Central European, tropical monsoon, continental, desert, subarctic and alpine climates. Fantasy options include **Winter Wonderland, Storm Coast, Mistwood, Thunderlands, Eternal Spring and Two Winters**. + +Presets can be edited, duplicated or added through the configuration screen, so you can build a climate that suits your world or modpack. + +## More than rain or sunshine + +Different climates bring different combinations of passing showers, prolonged rain, thunderstorms, hail, fog, snow squalls, blizzards and dust storms. Cold snaps and heatwaves can change conditions between the usual seasonal transitions. + +Rain and snow remain visible across biome boundaries, helping storms feel like part of the surrounding landscape. + +Seasonal snow and ice can appear as new terrain generates, then gradually thaw as conditions warm. Special handling preserves the native snow and ice generation of polar and glacier biomes. + +## Farming with the seasons + +Local temperature affects natural plant growth. Suitable conditions allow normal growth; less suitable temperatures slow it, and extreme cold or heat can pause it. Plants remain intact, while their usual soil, water, light and fertiliser requirements continue to apply. + +Seed, sapling and crop tooltips show preferred temperatures and whether the current local conditions suit them. Readouts support **Celsius or Fahrenheit**, including the temperature HUD and inspection tools. + +A craftable **thermometer** provides a temperature reading without operator permissions. Hold it in either hand for a small graphical HUD, or place it in the world. Its glass-and-mercury recipe accepts mercury ingots from **Base Metals** or another mod supplying the appropriate ore-dictionary ingredient. + +Burning furnaces, fire, lava and ordinary torches provide configurable local warmth that fades with distance. Overlapping heaters use the strongest contribution. Heating currently uses a simple radius model; walls and glass do not provide insulation. + +## Mod integrations + +All integrations are optional. The table lists the Minecraft versions each integration currently supports; install compatible releases of the mods you want to use. As ports become available, their supported integrations will be added here. + +| Mod | Minecraft versions | Integration | +| --- | --- | --- | +| **Pam’s HarvestCraft** | 1.10.2, 1.11.2 | Temperature-sensitive natural growth for supported crops and fruit, including fruit logs and saplings. | +| **AgriCraft** | 1.10.2 | Climate suitability for natural crop-stick growth, using the planted seed’s identity while preserving genetics and cross-crop behaviour. | +| **Forestry** | 1.10.2, 1.11.2 | Local temperature and seasonal humidity information for Forestry climate consumers. Forestry’s own controlled climates retain precedence. | +| **Mystical Agriculture** | 1.10.2, 1.11.2 | Magical resource crops remain exempt by default, with configurable mappings available to bring them into the climate system. | +| **Tough As Nails** | 1.10.2, 1.11.2 | Uses Sky’s local temperature as the environmental basis for its temperature system, while retaining body-temperature responses, clothing, wetness, thirst and other survival mechanics. | +| **JEI** | 1.10.2, 1.11.2 | A Climate Requirements category showing recognised plants’ preferred temperatures and current local suitability. | +| **Hwyla** | 1.10.2, 1.11.2 | Crop temperature requirements and growth status when looking at supported plants. | +| **The One Probe** | 1.10.2, 1.11.2 | Crop temperature requirements and growth status when looking at supported plants. | +| **CraftTweaker** | 1.10.2, 1.11.2 | Scripts can customise crop temperatures, exempt plants, map biomes to climates and query local conditions. | +| **Biomes O’ Plenty** | 1.10.2, 1.11.2 | Biome climate mappings that give its supported biomes appropriate seasonal weather. | +| **Thaumcraft** | 1.10.2 | Climate mappings for supported Overworld biomes. | +| **AbyssalCraft** | 1.10.2, 1.11.2 | Climate mappings for supported Overworld biomes. | +| **Vampirism** | 1.10.2, 1.11.2 | Climate mappings for supported Overworld biomes. | +| **GeographiCraft** | 1.10.2, 1.11.2 | Biome changes are respected when choosing climate defaults. | +| **BiomeTweaker** | 1.10.2, 1.11.2 | Biome changes are respected when choosing climate defaults. | +| **Realistic Terrain Generation** | 1.10.2 | Seasonal snow and ice generation in RTG worlds. | +| **Open Terrain Generator** | 1.10.2, 1.11.2 | Seasonal snow and ice generation in supported OTG terrain. | +| **Biome Bundle** | 1.10.2, 1.11.2 | Seasonal snow and ice generation when used with Open Terrain Generator. | +| **The Lost Cities** | 1.10.2, 1.11.2 | Seasonal snow and ice generation in Lost Cities worlds. | +| **Base Metals** | 1.10.2, 1.11.2 | Supplies mercury for the thermometer recipe. Other mods providing the appropriate mercury ingredient can also be used. | + +The 1.11.2 entries describe the local port and its pinned integration builds; +that version is not published yet. JEI client UI acceptance is still pending. +See the [version support guide](https://github.com/MinecraftModDevelopmentMods/SkysRealisticWeather/wiki/Version-Support) for current qualification and download status. + +## Tools for players and pack makers + +The configuration screen brings together climate modes, presets, seasons, farming rules, display preferences and local heating. + +Operators can use the **Weather Controller** or `/skyweather gui` to preview conditions, change settings and advance through seasons. Settings can be saved per world, while commands such as `/skyweather climate`, `/skyweather crop` and `/skyweather validate` help inspect local conditions and diagnose pack rules. + +For other mod developers, the public Java API exposes runtime and world-generation climate information, plant-growth queries and temperature-zone registration. A companion mod can use it to manage heated rooms, greenhouses or other controlled spaces. + +[Find API documentation for your Minecraft version in the source repository](https://github.com/MinecraftModDevelopmentMods/SkysRealisticWeather). + +## Optional real-world weather and external requests + +**Real-world weather is opt-in.** The default Per Biome Climate mode and Universal Climate mode work offline and do not make weather-service requests. + +When Real World Climate is enabled, the world host contacts **Open-Meteo** over HTTPS when the feed starts, then approximately every **15 real-world minutes** while the world is running. On a dedicated server, the server makes these requests; in single-player, they come from your computer. + +Requests include the **configured latitude and longitude** and ask for temperature and weather-condition data. The mod does not automatically detect your location or include player names, UUIDs, world seeds or save files in those requests. Open-Meteo can see the connecting host’s public IP address and may retain request logs under its [terms and privacy policy](https://open-meteo.com/en/terms). + +The feed uses weather-model data, which the mod translates into Minecraft conditions. Biomes and elevation still influence local effects, and seasons continue to follow Minecraft time. If the service is unavailable, a recent reading can remain in use before the configured seasonal fallback takes over. + +Weather data is provided by [Open-Meteo.com](https://open-meteo.com/en/docs) under **CC BY 4.0**, adapted into Minecraft weather. Its public free API is intended for non-commercial use; the provider’s terms and usage limits apply. + +## Installation + +Choose a download that matches your Minecraft version and mod loader. Check the selected file’s download page for its Minecraft, loader and Java requirements. + +Install the main mod on both the client and server for multiplayer. Optional integrations are downloaded separately. A mercury-supplying mod is needed to craft the thermometer. + +[Source code and documentation](https://github.com/MinecraftModDevelopmentMods/SkysRealisticWeather) diff --git a/gradle.properties b/gradle.properties index 6260fd5..c3a137b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,11 +4,11 @@ org.gradle.configuration-cache=false org.gradle.caching=true net.minecraftforge.gradle.merge-source-sets=false -minecraft_version=1.10.2 -forge_version=12.18.3.2511 -mapping_version=29-1.10.2 +minecraft_version=1.11.2 +forge_version=13.20.1.2588 +mapping_version=32-1.11 mod_id=skysrealisticweather mod_name=Sky's Realistic Weather -mod_version=0.1.21.110021 +mod_version=0.1.21.111021 mod_group=zone.moddev.mc.skysrealisticweather mod_description=Four seasons, local climate and optional real-world weather for the Overworld. diff --git a/gradle/eclipse-runs.gradle b/gradle/eclipse-runs.gradle index f81be51..f505079 100644 --- a/gradle/eclipse-runs.gradle +++ b/gradle/eclipse-runs.gradle @@ -2,65 +2,70 @@ import groovy.xml.XmlParser import groovy.xml.XmlUtil def modCoordinates = [ - BoP : 'biomes-o-plenty-220318:2452877', - RTG : 'realistic-terrain-generation-237989:2550453', - OTG : 'open-terrain-generator-265894:2439892', - BiomeBundle : 'biome-bundle-241542:2430752', + BoP : 'biomes-o-plenty-220318:2536549', + OTG : 'open-terrain-generator-265894:2530369', + BiomeBundle : 'biome-bundle-241542:2431190', LostCities : 'the-lost-cities-269024:2497880', - CompatLayer : 'compatlayer-253729:2532012', + CompatLayer : 'compatlayer-253729:2532013', GeographiCraft: 'climate-control-geographicraft-76544:2486027', - BiomeTweaker : 'biometweaker-228895:2402226', - AbyssalCraft : 'abyssalcraft-53686:2596856', - Thaumcraft : 'thaumcraft-223628:2546413', - Baubles : 'baubles-227083:2518666', - Vampirism : 'vampirism-become-a-vampire-233029:2555238', - HarvestCraft : 'pams-harvestcraft-221857:2428363', - AgriCraft : 'agricraft-225635:2495110', - InfinityLib : 'infinitylib-251396:2451336', - MysticalAgriculture: 'mystical-agriculture-246640:2530121', - Forestry : 'forestry-59751:2476716', - BaseMetals : 'base-metals-240967:9280029', - OreSpawn : 'mmd-orespawn-245586:9518063', - CraftTweaker : 'crafttweaker-239197:2433444', - ToughAsNails : 'maven.modrinth:ge1sOdFH:9sk3Ji4h', - JEI : 'jei-238222:2428966', - Hwyla : 'hwyla-253449:2433252', + BiomeTweaker : 'biometweaker-228895:2478061', + AbyssalCraft : 'abyssalcraft-53686:2596860', + Vampirism : 'vampirism-become-a-vampire-233029:2555244', + HarvestCraft : 'pams-harvestcraft-221857:2410937', + MysticalAgriculture: 'mystical-agriculture-246640:2487658', + Forestry : 'forestry-59751:2542509', + BaseMetals : 'base-metals-240967:9541705', + OreSpawn : 'mmd-orespawn-245586:9639128', + CraftTweaker : 'crafttweaker-239197:2838724', + ToughAsNails : 'maven.modrinth:ge1sOdFH:rVR7XpTd', + JEI : 'jei-238222:2461378', + Hwyla : 'hwyla-253449:2496989', TheOneProbe : 'the-one-probe-245211:2496984' ] def compatibilityProfiles = [ BoP : ['BoP'], - RTG : ['RTG'], OTG : ['OTG'], BiomeBundle : ['OTG', 'BiomeBundle'], LostCities : ['LostCities', 'CompatLayer'], - RTGBoPGeo : ['RTG', 'BoP', 'GeographiCraft'], GeographiCraft: ['GeographiCraft'], BiomeTweaker : ['BiomeTweaker'], AbyssalCraft : ['AbyssalCraft'], - Thaumcraft : ['Thaumcraft', 'Baubles'], Vampirism : ['Vampirism'], HarvestCraft : ['HarvestCraft'], - AgriCraft : ['InfinityLib', 'AgriCraft'], MysticalAgriculture: ['MysticalAgriculture'], Forestry : ['Forestry'], BaseMetals : ['OreSpawn', 'BaseMetals'], - Farming : ['HarvestCraft', 'InfinityLib', 'AgriCraft', 'MysticalAgriculture', 'Forestry'], + Farming : ['HarvestCraft', 'MysticalAgriculture', 'Forestry'], CraftTweaker : ['CraftTweaker'], ToughAsNails : ['ToughAsNails'], JEI : ['JEI'], Hwyla : ['Hwyla'], TheOneProbe : ['CompatLayer', 'TheOneProbe'], - PackSupport : ['CraftTweaker', 'ToughAsNails', 'JEI', 'Hwyla', 'CompatLayer', 'TheOneProbe', 'HarvestCraft', 'InfinityLib', 'AgriCraft', 'MysticalAgriculture', 'Forestry'] + PackSupport : ['CraftTweaker', 'ToughAsNails', 'JEI', 'Hwyla', 'CompatLayer', 'TheOneProbe', 'HarvestCraft', 'MysticalAgriculture', 'Forestry'] ] def publishedMods = modCoordinates.collectEntries { name, coordinates -> [(name): configurations.detachedConfiguration(dependencies.create(coordinates.startsWith('maven.modrinth:') ? coordinates : "curse.maven:${coordinates}"))] } +// Unmodified author jars for disposable packaged-server checks (never ship these). +tasks.register('preparePublishedIntegrationMods') { + group = 'verification' + inputs.files(publishedMods.values()) + outputs.dir(layout.buildDirectory.dir('compatibility-mods/published')) + doLast { + publishedMods.each { name, published -> + copy { + from published + into layout.buildDirectory.dir('compatibility-mods/published') + rename { "${name}.jar" } + } + } + } +} + def dependenciesByMod = [ BiomeBundle: ['OTG'], - AgriCraft : ['InfinityLib'], BaseMetals : ['OreSpawn'], LostCities : ['CompatLayer'], - Thaumcraft : ['Baubles'], TheOneProbe: ['CompatLayer'] ] def developmentMods = publishedMods.collectEntries { name, published -> @@ -81,7 +86,7 @@ def developmentMods = publishedMods.collectEntries { name, published -> // Remapped class bytes no longer match the published jar signatures. exclude 'META-INF/*.SF', 'META-INF/*.RSA', 'META-INF/*.DSA', 'META-INF/*.EC', 'META-INF/SIG-*' filesMatching('META-INF/*_at.cfg') { - // Forge 1.10 parses the owner and member as separate tokens. + // Forge 1.11 parses the owner and member as separate tokens. filter { String line -> line.replaceFirst(/^(\s*\S+\s+[\w\/$]+)\.(?=\S)/, '$1 ') } } } diff --git a/scripts/Prepare-RuntimeFixture.py b/scripts/Prepare-RuntimeFixture.py new file mode 100644 index 0000000..6b68ab0 --- /dev/null +++ b/scripts/Prepare-RuntimeFixture.py @@ -0,0 +1,42 @@ +"""Prepare a clean 1.11.2 test fixture from an installed Forge server, without copying worlds.""" +from pathlib import Path +import argparse, hashlib, json, shutil, subprocess + +project = Path(__file__).resolve().parents[1] +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('--engine-dir', type=Path, required=True) +args = parser.parse_args() +engine = args.engine_dir.resolve() +fixture = project/'build/verification/runtime-fixture' +forge = 'forge-1.11.2-13.20.1.2588-universal.jar' +assert hashlib.sha1((engine/forge).read_bytes()).hexdigest() == 'acd5d24c3f58590b6a9da6e0e2aa14bd6dcc5166', 'Unexpected Forge server' +assert (engine/'libraries').is_dir(), 'Install Forge server libraries first' +fixture.mkdir(parents=True, exist_ok=True) +for name in [forge, 'minecraft_server.1.11.2.jar']: + destination = fixture/name + if destination.exists(): + assert destination.read_bytes() == (engine/name).read_bytes(), 'Fixture engine changed' + else: + shutil.copy2(engine/name, destination) +if not (fixture/'libraries').exists(): + quoted = lambda path: "'"+str(path).replace("'", "''")+"'" + subprocess.run(['powershell', '-NoProfile', '-Command', + 'New-Item -ItemType Junction -Path '+quoted(fixture/'libraries')+' -Target '+quoted(engine/'libraries')+' | Out-Null'], check=True) +(fixture/'eula.txt').write_text('eula=true\n') +for name in ['ops.json', 'whitelist.json', 'banned-ips.json', 'banned-players.json']: + (fixture/name).write_text('[]\n') +(fixture/'server.properties').write_text('''level-name=world +level-type=DEFAULT +level-seed=123948 +server-ip=127.0.0.1 +server-port=0 +online-mode=false +enable-rcon=false +enable-query=false +view-distance=3 +max-tick-time=-1 +snooper-enabled=false +spawn-npcs=false +generate-structures=false +''') +print(fixture) diff --git a/scripts/Run-CrashQualification.py b/scripts/Run-CrashQualification.py index 863f714..798e5b8 100644 --- a/scripts/Run-CrashQualification.py +++ b/scripts/Run-CrashQualification.py @@ -1,18 +1,16 @@ -"""Crash-focused, disposable full-world or synthetic Forge qualification; never launches the source.""" +"""Crash-focused qualification using disposable synthetic 1.11.2 worlds.""" from pathlib import Path import argparse,ctypes,hashlib,json,os,re,shutil,subprocess,time from ctypes import wintypes project=Path(__file__).resolve().parents[1] p=argparse.ArgumentParser(description=__doc__) -p.add_argument('--case',choices=['edge','stress','sylvester'],required=True) +p.add_argument('--case',choices=['edge','stress'],required=True) p.add_argument('--variant',choices=['control','weather'],default='weather') p.add_argument('--phase',choices=['initial','reload'],default='initial') p.add_argument('--ticks',type=int,default=6000) p.add_argument('--output',type=Path,required=True) args=p.parse_args();output=args.output.resolve() -proof=project/'build/verification/crash-qualification';snapshot=proof/'input-sylvester' -for protected in [Path('D:/MinecraftMineralogy/1 Sylvester').resolve(),snapshot.resolve()]: - if output==protected or protected in output.parents:raise ValueError('Never write qualification output into the protected source or snapshot') +assert output.is_relative_to((project/'build/verification').resolve()), 'Use disposable verification output within this checkout' if args.phase=='initial' and (output/'server').exists():raise FileExistsError('Preserving an existing runtime; choose fresh output') output.mkdir(parents=True,exist_ok=True) version=re.search(r'^mod_version=(.+)$',(project/'gradle.properties').read_text(encoding='utf-8'),re.M).group(1) @@ -29,41 +27,30 @@ def digest(path): for previous in output.glob('*.json'): old=json.loads(previous.read_text(encoding='utf-8'));assert old['case']==args.case and old['variant']==args.variant and old['probe_sha256']==digest(probe) and (args.variant=='control' or old['candidate_sha256']==digest(main)),'Candidate/profile changed; use a fresh output' if args.phase=='reload':assert json.loads((output/'initial.json').read_text(encoding='utf-8'))['passed'],'Reload needs passing initial run' -server=output/'server';fixture=project/'build/verification/worldgen-performance/whole-chunk-v1/1-vanilla' +server=output/'server';fixture=project/'build/verification/runtime-fixture' forge=next(fixture.glob('forge-*-universal.jar')).name -excluded={'OreSpawn-4.0.8.110021.jar':'duplicate older OreSpawn; saved world records 4.0.16','ironagefurniture+1.10.2+v0.2.0.5.jar':'duplicate older furniture; saved world records 0.3.0','OptiFine_1.10.2_HD_U_E7.jar':'client-only renderer; no dedicated-server coverage'} if not server.exists(): server.mkdir();(server/'mods').mkdir() - if args.case=='sylvester': - shutil.copytree(snapshot/'world',server/'world');shutil.copytree(snapshot/'config',server/'config') - for source in (snapshot/'mods').rglob('*.jar'): - if source.name in excluded:continue - target=server/'mods'/source.relative_to(snapshot/'mods');target.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(source,target) - for name in ['biomessetting.txt','harvestcraft.cfg']: - if(snapshot/name).exists():shutil.copy2(snapshot/name,server/name) - backup=server/'config/aroma1997/AromaBackup.cfg';text=backup.read_text(encoding='utf-8');text=re.sub(r'S:location=.*','S:location=backups',text);text=text.replace('B:onStartup=true','B:onStartup=false');text=re.sub(r'I:delay=\d+','I:delay=0',text);backup.write_text(text,encoding='utf-8') - else: - for name in ["Pam's HarvestCraft 1.10.2j.jar",'agricraft-2.0.0-0.11.0-a21.jar','infinitylib-0.11.0.jar','mysticalagriculture-1.10.2-1.5.10.jar','forestry_1.10.2-5.2.17.388.jar']: - shutil.copy2(project/'build/verification/plant-growth-review'/name,server/'mods'/name) - for name in [forge,'minecraft_server.1.10.2.jar','eula.txt','ops.json','whitelist.json','banned-ips.json','banned-players.json']:shutil.copy2(fixture/name,server/name) + for name in ['HarvestCraft.jar','MysticalAgriculture.jar','Forestry.jar']: + shutil.copy2(project/'build/compatibility-mods/published'/name,server/'mods'/name) + for name in [forge,'minecraft_server.1.11.2.jar','eula.txt','ops.json','whitelist.json','banned-ips.json','banned-players.json']:shutil.copy2(fixture/name,server/name) quoted=lambda s:"'"+str(s).replace("'","''")+"'" subprocess.run(['powershell','-NoProfile','-Command','New-Item -ItemType Junction -Path '+quoted(server/'libraries')+' -Target '+quoted((fixture/'libraries').resolve())+' | Out-Null'],check=True) - props=(snapshot/'server.properties' if args.case=='sylvester' else fixture/'server.properties').read_text(encoding='utf-8') + props=(fixture/'server.properties').read_text(encoding='utf-8') changes={'level-name':'world','server-ip':'127.0.0.1','server-port':'0','online-mode':'false','enable-rcon':'false','enable-query':'false','view-distance':'4','max-tick-time':'-1','snooper-enabled':'false'} - if args.case!='sylvester':changes.update({'level-type':'FLAT','generate-structures':'false','spawn-npcs':'false'}) + changes.update({'level-type':'FLAT','generate-structures':'false','spawn-npcs':'false'}) for key,value in changes.items(): pattern=r'^'+re.escape(key)+'=.*' props=re.sub(pattern,key+'='+value,props,flags=re.M) if re.search(pattern,props,re.M) else props+'\n'+key+'='+value (server/'server.properties').write_text(props,encoding='utf-8') - for name in ['target-chunks.tsv','crop-points.tsv']:shutil.copy2(proof/name,server/name) for path in (server/'config').rglob('forge.cfg'): text=path.read_text(encoding='utf-8');text=text.replace('B:removeErroringEntities=true','B:removeErroringEntities=false').replace('B:removeErroringTileEntities=true','B:removeErroringTileEntities=false');path.write_text(text,encoding='utf-8') if args.variant=='weather':shutil.copy2(main,server/'mods'/main.name) shutil.copy2(probe,server/'mods'/probe.name) third_party={str(path.relative_to(server/'mods')):digest(path) for path in (server/'mods').rglob('*.jar') if path.name not in [main.name,probe.name]} -phase='soak' if args.case=='sylvester' else args.case +phase=args.case java=Path.home()/'.gradle/jdks/temurin-8-amd64-windows.2/bin/java.exe' -command=[str(java),'-Xms256m','-Xmx3g' if args.case=='sylvester' else '-Xmx1g','-XX:+UseSerialGC','-XX:ActiveProcessorCount=1','-XX:CICompilerCount=2','-Dcrash.probe=true','-Dcrash.phase='+phase,'-Dcrash.ticks='+str(args.ticks),'-jar',forge,'nogui'] +command=[str(java),'-Xms256m','-Xmx1g','-XX:+UseSerialGC','-XX:ActiveProcessorCount=1','-XX:CICompilerCount=2','-Dcrash.probe=true','-Dcrash.phase='+phase,'-Dcrash.ticks='+str(args.ticks),'-jar',forge,'nogui'] kernel=ctypes.WinDLL('kernel32',use_last_error=True);kernel.SetProcessAffinityMask.argtypes=[wintypes.HANDLE,ctypes.c_size_t];kernel.SetProcessAffinityMask.restype=wintypes.BOOL start=time.monotonic();timed_out=False with logpath.open('wb') as log: @@ -74,7 +61,7 @@ def digest(path): except subprocess.TimeoutExpired:timed_out=True;process.terminate();process.wait() text=logpath.read_text(encoding='utf-8',errors='replace');unchanged=all(digest(server/'mods'/name)==value for name,value in third_party.items()) passed=not timed_out and process.returncode==0 and 'QUALIFY_PASS' in text and 'QUALIFY_FAIL' not in text and unchanged -result={'passed':passed,'case':args.case,'variant':args.variant,'phase':args.phase,'seconds':round(time.monotonic()-start,2),'exit_code':process.returncode,'timed_out':timed_out,'candidate_sha256':digest(main),'probe_sha256':digest(probe),'candidate_loaded':args.variant=='weather','third_party_sha256':third_party,'third_party_unchanged':unchanged,'excluded_source_jars':excluded if args.case=='sylvester' else {},'command':command,'pid':process.pid} +result={'passed':passed,'case':args.case,'variant':args.variant,'phase':args.phase,'seconds':round(time.monotonic()-start,2),'exit_code':process.returncode,'timed_out':timed_out,'candidate_sha256':digest(main),'probe_sha256':digest(probe),'candidate_loaded':args.variant=='weather','third_party_sha256':third_party,'third_party_unchanged':unchanged,'command':command,'pid':process.pid} (output/(args.phase+'.json')).write_text(json.dumps(result,indent=2),encoding='utf-8') for line in text.splitlines(): if 'QUALIFY_' in line:print(line,flush=True) diff --git a/scripts/Run-PackChecks.py b/scripts/Run-PackChecks.py index dce1c64..464ee8f 100644 --- a/scripts/Run-PackChecks.py +++ b/scripts/Run-PackChecks.py @@ -28,10 +28,10 @@ directory.mkdir();(directory/'mods').mkdir();(directory/'scripts').mkdir() if args.disabled: (directory/'config').mkdir();(directory/'config/skysrealisticweather.cfg').write_text('integrations {\n'+''.join(' B:'+key+'=false\n' for key in ['crafttweaker','toughasnails','jei','waila','theoneprobe'])+'}\n') -fixture=project/'build/verification/worldgen-performance/whole-chunk-v1/1-vanilla' +fixture=project/'build/verification/runtime-fixture' forge=next(fixture.glob('forge-*-universal.jar')).name if args.phase=='contracts': - for name in [forge,'minecraft_server.1.10.2.jar','eula.txt','ops.json','whitelist.json','banned-ips.json','banned-players.json']:shutil.copy2(fixture/name,directory/name) + for name in [forge,'minecraft_server.1.11.2.jar','eula.txt','ops.json','whitelist.json','banned-ips.json','banned-players.json']:shutil.copy2(fixture/name,directory/name) quoted=lambda path:"'"+str(path).replace("'","''")+"'" subprocess.run(['powershell','-NoProfile','-Command','New-Item -ItemType Junction -Path '+quoted(directory/'libraries')+' -Target '+quoted((fixture/'libraries').resolve())+' | Out-Null'],check=True) props=(fixture/'server.properties').read_text() @@ -39,13 +39,13 @@ pattern=r'^'+re.escape(key)+'=.*';props=re.sub(pattern,key+'='+value,props,flags=re.M) if re.search(pattern,props,re.M) else props+'\n'+key+'='+value (directory/'server.properties').write_text(props) (directory/'scripts/weather.zs').write_text('import mods.skysrealisticweather.Climate;\nClimate.exemptCrop("minecraft:wheat");\nClimate.mapBiome("minecraft:plains","TROPICAL_MONSOON");\n',encoding='utf-8') -dependencies={'crafttweaker':['CraftTweaker-1.10.2-3.0.26.jar'],'tan':['ToughAsNails-1.9.4-1.1.1.jar'], - 'jei':['jei_1.10.2-3.14.7.420.jar'],'hwyla':['Hwyla-1.8.17-B31_1.10.2.jar'],'top':['compatlayer-253729-2532012.jar','theoneprobe-1.1x-1.4.19.jar'],'core':[]} +dependencies={'crafttweaker':['CraftTweaker.jar'],'tan':['ToughAsNails.jar'], + 'jei':['JEI.jar'],'hwyla':['Hwyla.jar'],'top':['CompatLayer.jar','TheOneProbe.jar'],'core':[]} dependencies['combined']=sum([dependencies[key] for key in ['crafttweaker','tan','jei','hwyla','top']],[]) -dependencies['full']=dependencies['combined']+["Pam's HarvestCraft 1.10.2j.jar",'agricraft-2.0.0-0.11.0-a21.jar','infinitylib-0.11.0.jar','mysticalagriculture-1.10.2-1.5.10.jar','forestry_1.10.2-5.2.17.388.jar'] +dependencies['full']=dependencies['combined']+["HarvestCraft.jar",'MysticalAgriculture.jar','Forestry.jar'] for name in dependencies[args.profile]: - source=project/'build/verification/pack-support-review'/name - if not source.exists():source=project/'build/verification/plant-growth-review'/name + source=project/'build/compatibility-mods/published'/name + if not source.exists():source=project/'build/compatibility-mods/published'/name shutil.copy2(source,directory/'mods'/name) for jar in [main,probe]:shutil.copy2(jar,directory/'mods'/jar.name) thirdparty={name:digest(directory/'mods'/name) for name in dependencies[args.profile]} diff --git a/scripts/Run-PlantChecks.py b/scripts/Run-PlantChecks.py index 41df436..6aa8782 100644 --- a/scripts/Run-PlantChecks.py +++ b/scripts/Run-PlantChecks.py @@ -15,7 +15,7 @@ project = Path(__file__).resolve().parents[1] parser = argparse.ArgumentParser(description=__doc__) -parser.add_argument('--profile', choices=['vanilla','harvestcraft','agricraft','mystical','forestry','combined'], default='vanilla') +parser.add_argument('--profile', choices=['vanilla','harvestcraft','mystical','forestry','combined'], default='vanilla') parser.add_argument('--phase', choices=['contracts','reload','endurance','performance'], default='contracts') parser.add_argument('--years', type=int, default=5) parser.add_argument('--seeds', type=int, nargs='+', default=[123948,70289,91173]) @@ -26,13 +26,12 @@ args.jar = project/('build/libs/SkysRealisticWeather-'+version+'.jar') output = args.output.resolve() output.mkdir(parents=True, exist_ok=True) -review = project/'build/verification/plant-growth-review' -profiles = dict(harvestcraft=["Pam's HarvestCraft 1.10.2j.jar"], - agricraft=['agricraft-2.0.0-0.11.0-a21.jar','infinitylib-0.11.0.jar'], - mystical=['mysticalagriculture-1.10.2-1.5.10.jar'], forestry=['forestry_1.10.2-5.2.17.388.jar'], vanilla=[]) -profiles['combined'] = sum([profiles[k] for k in ['harvestcraft','agricraft','mystical','forestry']], []) +review = project/'build/compatibility-mods/published' +profiles = dict(harvestcraft=["HarvestCraft.jar"], + mystical=['MysticalAgriculture.jar'], forestry=['Forestry.jar'], vanilla=[]) +profiles['combined'] = sum([profiles[k] for k in ['harvestcraft','mystical','forestry']], []) extra_mods = [review/name for name in profiles[args.profile]] -fixture = project/'build/verification/worldgen-performance/whole-chunk-v1/1-vanilla' +fixture = project/'build/verification/runtime-fixture' probe = project/'build/verification/probe/skyweather-probe.jar' java = Path.home()/'.gradle/jdks/temurin-8-amd64-windows.2/bin/java.exe' forge = next(fixture.glob('forge-*-universal.jar')).name @@ -58,7 +57,7 @@ def digest(path): def prepare(directory): (directory/'mods').mkdir(parents=True, exist_ok=True) - for name in [forge, 'minecraft_server.1.10.2.jar', 'eula.txt', 'ops.json', + for name in [forge, 'minecraft_server.1.11.2.jar', 'eula.txt', 'ops.json', 'whitelist.json', 'banned-ips.json', 'banned-players.json']: if not (directory/name).exists(): shutil.copy2(fixture/name, directory/name) diff --git a/scripts/Run-RuntimeChecks.py b/scripts/Run-RuntimeChecks.py new file mode 100644 index 0000000..ff051fa --- /dev/null +++ b/scripts/Run-RuntimeChecks.py @@ -0,0 +1,89 @@ +"""Run a packaged weather probe in a disposable, hidden, single-CPU Forge server.""" +from pathlib import Path +import argparse, ctypes, hashlib, json, os, shutil, subprocess, time +from ctypes import wintypes + +project = Path(__file__).resolve().parents[1] +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('--mode', required=True) +parser.add_argument('--expect', required=True, help='Required success marker in the server log') +parser.add_argument('--mod', action='append', default=[], help='Published integration name, e.g. BoP') +parser.add_argument('--option', action='append', default=[], help='Additional Java system property key=value') +parser.add_argument('--world-type', default='FLAT') +parser.add_argument('--fixed-biome', type=int, help='Actual vanilla biome registry id, not the Customized GUI index') +parser.add_argument('--level-name', default='world') +parser.add_argument('--universal', action='store_true', help='Use the Burlington climate for controlled generator tests') +parser.add_argument('--output', type=Path, required=True) +parser.add_argument('--stage', default='initial') +args = parser.parse_args() +output = args.output.resolve() +assert output.is_relative_to((project/'build/verification').resolve()), 'Use disposable verification output' +assert args.stage.isidentifier(), 'Use a simple stage name' +output.mkdir(parents=True, exist_ok=True) +logpath = output/(args.stage+'.log') +assert not logpath.exists(), 'Preserve previous evidence' +digest = lambda path: hashlib.sha256(path.read_bytes()).hexdigest() +receipt = json.loads((project/'build/verification/probe/probe-build.json').read_text()) +for name, expected in receipt['source_sha256'].items(): + assert digest(project/name) == expected, 'Unbuilt source: '+name +main = next(path for path in (project/'build/libs').glob('*.jar') if digest(path) == receipt['main_sha256']) +probe = project/'build/verification/probe/skyweather-probe.jar' +assert digest(probe) == receipt['probe_sha256'], 'Rebuild probe' +directory = output/'server' +fixture = project/'build/verification/runtime-fixture' +forge = 'forge-1.11.2-13.20.1.2588-universal.jar' +if not directory.exists(): + directory.mkdir(); (directory/'mods').mkdir() + for name in [forge, 'minecraft_server.1.11.2.jar', 'eula.txt', 'ops.json', 'whitelist.json', 'banned-ips.json', 'banned-players.json']: + shutil.copy2(fixture/name, directory/name) + quoted = lambda path: "'"+str(path).replace("'", "''")+"'" + subprocess.run(['powershell', '-NoProfile', '-Command', + 'New-Item -ItemType Junction -Path '+quoted(directory/'libraries')+' -Target '+quoted(fixture/'libraries')+' | Out-Null'], check=True) + props = (fixture/'server.properties').read_text().replace('level-type=DEFAULT', 'level-type='+args.world_type) + props = props.replace('level-name=world', 'level-name='+args.level_name) + if args.fixed_biome is not None: + assert args.world_type.upper() == 'CUSTOMIZED' and args.fixed_biome not in [8, 9] + # Customized's persisted selection omits the Nether and End entries. + selection = args.fixed_biome-2 if args.fixed_biome >= 10 else args.fixed_biome + props += '\ngenerator-settings='+json.dumps(dict(fixedBiome=selection))+'\n' + (directory/'server.properties').write_text(props) + if args.universal: + (directory/'config').mkdir() + (directory/'config/skysrealisticweather.cfg').write_text('~CONFIG_VERSION: 8\ngeneral {\n S:climateMode=UNIVERSAL\n S:activePreset=burlington\n}\n') +else: + previous = json.loads((output/'initial.json').read_text()) + assert previous['passed'] and previous['main_sha256'] == digest(main) and previous['probe_sha256'] == digest(probe), 'Reload requires the same passing candidate' +for path in [main, probe]: + shutil.copy2(path, directory/'mods'/path.name) +originals = {} +for name in args.mod: + assert name.isidentifier(), 'Use a pinned integration name' + source = project/'build/compatibility-mods/published'/(name+'.jar') + shutil.copy2(source, directory/'mods'/source.name) + originals[source.name] = digest(source) +java = Path.home()/'.gradle/jdks/temurin-8-amd64-windows.2/bin/java.exe' +command = [str(java), '-Xms128m', '-Xmx1g', '-XX:+UseSerialGC', '-XX:ActiveProcessorCount=1', '-XX:CICompilerCount=2', + '-Dskyweather.probe='+args.mode, *['-D'+value for value in args.option], '-jar', forge, 'nogui'] +kernel = ctypes.WinDLL('kernel32', use_last_error=True) +kernel.SetProcessAffinityMask.argtypes = [wintypes.HANDLE, ctypes.c_size_t] +kernel.SetProcessAffinityMask.restype = wintypes.BOOL +start = time.monotonic() +with logpath.open('wb') as log: + process = subprocess.Popen(command, cwd=directory, stdout=log, stderr=subprocess.STDOUT, + creationflags=subprocess.CREATE_NO_WINDOW|subprocess.BELOW_NORMAL_PRIORITY_CLASS) + assert kernel.SetProcessAffinityMask(int(process._handle), 1< plants) throws Exception { IProperty property = age(state); IBlockState mature = state.withProperty(property, (Comparable) Collections.max(property.getAllowedValues())); net.minecraft.item.Item product = block.getItemDropped(mature, new Random(0), 0); - if (product != null) { + if (product != null && product != Items.AIR) { net.minecraft.item.ItemStack stack = new net.minecraft.item.ItemStack(product, 1, block.damageDropped(mature)); require(PlantItems.resolve(stack, world, pos).stream().anyMatch(p -> p.id.equals(block.getRegistryName().toString())), "harvest identity " + block.getRegistryName()); require(tooltip(stack).contains("Here:"), "harvest tooltip " + block.getRegistryName()); resolved++; } net.minecraft.item.Item seed = block.getItemDropped(state, new Random(0), 0); - if (seed != null) { + if (seed != null && seed != Items.AIR) { net.minecraft.item.ItemStack stack = new net.minecraft.item.ItemStack(seed, 1, block.damageDropped(state)); require(PlantItems.resolve(stack, world, pos).stream().anyMatch(p -> p.id.equals(block.getRegistryName().toString())), "seed identity " + block.getRegistryName()); } @@ -291,7 +295,7 @@ private void mappingContracts() throws Exception { BlockPos unloaded = new BlockPos(900008, 81, 900008); require(!world.isBlockLoaded(unloaded, false) && !WeatherApi.getPlantGrowth(world, unloaded).isPresent() && !world.isBlockLoaded(unloaded, false), "plant API never loads terrain"); - require(!WeatherApi.getPlantGrowth(world.getMinecraftServer().worldServerForDimension(-1), pos).isPresent(), "unsupported dimension query"); + require(!WeatherApi.getPlantGrowth(world.getMinecraftServer().getWorld(-1), pos).isPresent(), "unsupported dimension query"); Map registration = Collections.singletonMap("minecraft:wheat", PlantGrowthProfile.EXEMPT); FarmingSettings override = new FarmingSettings(true, true, true, true, true, FarmingSettings.defaultProfiles(), new String[0], registration); frame(-0.3F, override); require(WeatherApi.getPlantGrowth(world, pos).get().naturalGrowthMultiplier == 1, "API overrides bundled"); @@ -419,30 +423,31 @@ private void agricraft() throws Exception { private void forestry() throws Exception { pad(pos, Blocks.WHEAT.getDefaultState()); frame(1.0F, startup.farming); Object manager = Class.forName("forestry.api.core.ForestryAPI").getField("climateManager").get(null); - require(Math.abs(((Number) invoke(manager, "getTemperature", world, pos)).floatValue() - WeatherApi.getTemperature(world, pos).getAsDouble()) < 0.0001, "Forestry ambient temperature bridge"); - require(Math.abs(((Number) invoke(manager, "getHumidity", world, pos)).floatValue() - 0.5F) < 0.0001, "Forestry ambient humidity proxy"); + require(Math.abs(((Number) invoke(invoke(manager, "getInfo", world, pos), "getTemperature")).floatValue() - WeatherApi.getTemperature(world, pos).getAsDouble()) < 0.0001, "Forestry ambient temperature bridge"); + require(Math.abs(((Number) invoke(invoke(manager, "getInfo", world, pos), "getHumidity")).floatValue() - 0.5F) < 0.0001, "Forestry ambient humidity proxy"); Class positionType = Class.forName("forestry.api.climate.IClimatePosition"); Class regionType = Class.forName("forestry.api.climate.IClimateRegion"); Object position = Proxy.newProxyInstance(positionType.getClassLoader(), new Class[] {positionType}, (proxy, method, args) -> { switch (method.getName()) { case "getTemperature": return 0.8F; case "getHumidity": return 0.73F; + case "getInfo": return invoke(manager, "createInfo", 0.8F, 0.73F); case "equals": return proxy == args[0]; case "hashCode": return System.identityHashCode(proxy); default: return null; } }); Object region = Proxy.newProxyInstance(regionType.getClassLoader(), new Class[] {regionType}, (proxy, method, args) -> { - switch (method.getName()) { case "getWorld": return world; case "getPositions": return Collections.singletonMap(pos, position); + switch (method.getName()) { case "getWorld": return world; case "getPosition": return pos.equals(args[0]) ? position : null; case "getPositions": return Collections.singletonMap(pos, position); case "getSources": return Collections.emptyList(); case "equals": return proxy == args[0]; case "hashCode": return System.identityHashCode(proxy); default: return null; } }); invoke(manager, "addRegion", region); frame(-0.3F, startup.farming); - require(((Number) invoke(manager, "getTemperature", world, pos)).floatValue() == 0.8F, "Forestry controlled temperature retained"); - require(((Number) invoke(manager, "getHumidity", world, pos)).floatValue() == 0.73F, "Forestry controlled humidity retained"); + require(((Number) invoke(invoke(manager, "getInfo", world, pos), "getTemperature")).floatValue() == 0.8F, "Forestry controlled temperature retained"); + require(((Number) invoke(invoke(manager, "getInfo", world, pos), "getHumidity")).floatValue() == 0.73F, "Forestry controlled humidity retained"); PlantGrowthSample sample = WeatherApi.getPlantGrowth(world, pos).get(); require(sample.controlledClimate && sample.naturalGrowthMultiplier == 1, "ordinary crops recognise controlled climate"); require(tooltip(new net.minecraft.item.ItemStack(Items.WHEAT_SEEDS)).contains("controlled climate") && tooltip(new net.minecraft.item.ItemStack(Items.WHEAT_SEEDS)).contains("Suitable; normal"), "tooltip uses Forestry controlled temperature"); invoke(manager, "removeRegion", region); frame(1.0F, startup.farming.withEnabled(false)); - require(((Number) invoke(manager, "getTemperature", world, pos)).floatValue() == Biomes.PLAINS.getTemperature(), "Forestry native fallback with master disabled"); + require(((Number) invoke(invoke(manager, "getInfo", world, pos), "getTemperature")).floatValue() == Biomes.PLAINS.getTemperature(), "Forestry native fallback with master disabled"); System.out.println("PLANT_FORESTRY PASS"); } diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/BiomeCompatibilityProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/BiomeCompatibilityProbe.java index 03ac0f3..1ac5aa3 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/BiomeCompatibilityProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/BiomeCompatibilityProbe.java @@ -83,7 +83,7 @@ public void tick(TickEvent.WorldTickEvent event) { if (event.world != world || event.phase != TickEvent.Phase.END) return; ticks++; if (ticks == 120) { - if (Loader.isModLoaded("BiomesOPlenty")) verifyBopClimates(); + if (Loader.isModLoaded("biomesoplenty")) verifyBopClimates(); sample(true); command("skyweather season set summer 45"); } else if (ticks == 160) { diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java index 4791e9f..e1d05d5 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java @@ -234,7 +234,7 @@ private void admin(Minecraft game) throws ReflectiveOperationException { private static void verifyCreativeEntry(boolean operator) { net.minecraft.block.Block block = WeatherController.BLOCK; Item item = Item.getItemFromBlock(block); - List entries = new ArrayList<>(); + net.minecraft.util.NonNullList entries = net.minecraft.util.NonNullList.create(); CreativeTabs tab = block.getCreativeTabToDisplayOn(); item.getSubItems(item, tab, entries); WeatherProbe.require(entries.size() == (operator ? 1 : 0), "controller is listed only for creative operators"); diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/TemperatureZoneProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/TemperatureZoneProbe.java index 50a0dc7..ab040d7 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/TemperatureZoneProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/TemperatureZoneProbe.java @@ -56,7 +56,7 @@ private static void contracts(WorldServer world)throws Exception { WeatherApi.removeTemperatureZone(world,high.id);require(WeatherApi.getLocalTemperature(world,CROP).getAsDouble()==room.temperature,"removing winner restores lower zone"); AtomicReference wrongThread=new AtomicReference<>();Thread worker=new Thread(()->{try{WeatherApi.putTemperatureZone(world,room);}catch(Throwable e){wrongThread.set(e);}}); worker.start();worker.join();require(wrongThread.get() instanceof IllegalStateException,"off-thread mutations rejected"); - WorldServer nether=world.getMinecraftServer().worldServerForDimension(-1);nether.getChunkFromBlockCoords(CROP); + WorldServer nether=world.getMinecraftServer().getWorld(-1);nether.getChunkFromBlockCoords(CROP); require(WeatherApi.getTemperatureSample(nether,CROP).get().source==TemperatureSample.Source.AMBIENT,"dimension isolation"); WeatherApi.putTemperatureZone(nether,room);require(WeatherApi.getLocalTemperature(nether,CROP).getAsDouble()==room.temperature,"zones usable outside seasonal dimensions"); WeatherApi.removeTemperatureZone(nether,ROOM); @@ -92,7 +92,7 @@ private static void contracts(WorldServer world)throws Exception { require(Math.abs(WeatherApi.getLocalTemperature(world,CROP).getAsDouble()-tropical-nearBonus)<.00001,"furnace also adds warmth to hot ambient"); Arrays.fill(biomes,(byte)Biome.getIdForBiome(Biomes.ICE_PLAINS)); TileEntityFurnace furnace=(TileEntityFurnace)world.getTileEntity(FURNACE); - furnace.setInventorySlotContents(1,null);furnace.setField(0,1);advance(world);furnace.update(); + furnace.setInventorySlotContents(1,ItemStack.EMPTY);furnace.setField(0,1);advance(world);furnace.update(); require(WeatherApi.getTemperatureSample(world,CROP).get().source==TemperatureSample.Source.AMBIENT,"burnout removes heat"); start(world);world.setBlockToAir(FURNACE); require(WeatherApi.getTemperatureSample(world,CROP).get().source==TemperatureSample.Source.AMBIENT,"broken furnace cannot leave ghost heat"); diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ThermometerProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ThermometerProbe.java index c6ccb39..ddf3c1e 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ThermometerProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ThermometerProbe.java @@ -47,7 +47,7 @@ private static ItemStack craft(WorldServer world, ItemStack glass, ItemStack met grid.setInventorySlotContents(1, glass.copy()); grid.setInventorySlotContents(4, glass.copy()); grid.setInventorySlotContents(7, metal.copy()); return CraftingManager.getInstance().findMatchingRecipe(grid, world); } - private static boolean thermometer(ItemStack stack) { return stack != null && stack.getItem() == Item.getItemFromBlock(Thermometer.BLOCK) && stack.stackSize == 1; } + private static boolean thermometer(ItemStack stack) { return stack != null && stack.getItem() == Item.getItemFromBlock(Thermometer.BLOCK) && stack.getCount() == 1; } private static void contracts(WorldServer world) throws Exception { Block block = Thermometer.BLOCK; // Use the vanilla owner for inherited-method reobfuscation in this separate probe jar. Item item = Item.getItemFromBlock(Thermometer.BLOCK); @@ -74,17 +74,17 @@ private static void contracts(WorldServer world) throws Exception { require(Thermometer.heldBy(player), "main hand enables instrument HUD"); player.setHeldItem(EnumHand.MAIN_HAND, new ItemStack(item, 0)); require(!Thermometer.heldBy(player), "consumed stack does not enable instrument HUD"); - player.setHeldItem(EnumHand.MAIN_HAND, null); player.setHeldItem(EnumHand.OFF_HAND, new ItemStack(item)); + player.setHeldItem(EnumHand.MAIN_HAND, ItemStack.EMPTY); player.setHeldItem(EnumHand.OFF_HAND, new ItemStack(item)); require(Thermometer.heldBy(player), "offhand enables instrument HUD"); - player.setHeldItem(EnumHand.OFF_HAND, null); player.inventory.setInventorySlotContents(3, new ItemStack(item)); + player.setHeldItem(EnumHand.OFF_HAND, ItemStack.EMPTY); player.inventory.setInventorySlotContents(3, new ItemStack(item)); require(!Thermometer.heldBy(player), "inventory alone does not enable instrument HUD"); world.setBlockState(FLOOR.down(), Blocks.STONE.getDefaultState(), 2); world.setBlockToAir(FLOOR); ItemStack held = new ItemStack(item, 2); player.setHeldItem(EnumHand.MAIN_HAND, held); - require(item.onItemUse(held, player, world, FLOOR.down(), EnumHand.MAIN_HAND, EnumFacing.UP, .5F, 1, .5F) == EnumActionResult.SUCCESS, + require(item.onItemUse(player, world, FLOOR.down(), EnumHand.MAIN_HAND, EnumFacing.UP, .5F, 1, .5F) == EnumActionResult.SUCCESS, "non-operator places standing thermometer"); - require(held.stackSize == 1 && world.getBlockState(FLOOR).getBlock() == Thermometer.BLOCK && !world.getBlockState(FLOOR).getValue(Thermometer.WALL), "standing item consumed and correct state"); + require(held.getCount() == 1 && world.getBlockState(FLOOR).getBlock() == Thermometer.BLOCK && !world.getBlockState(FLOOR).getValue(Thermometer.WALL), "standing item consumed and correct state"); world.setBlockState(WALL.south(), Blocks.STONE.getDefaultState(), 2); world.setBlockToAir(WALL); - require(item.onItemUse(held, player, world, WALL.south(), EnumHand.MAIN_HAND, EnumFacing.NORTH, .5F, .5F, 0) == EnumActionResult.SUCCESS, + require(item.onItemUse(player, world, WALL.south(), EnumHand.MAIN_HAND, EnumFacing.NORTH, .5F, .5F, 0) == EnumActionResult.SUCCESS, "non-operator places wall thermometer"); require(world.getBlockState(WALL).getValue(Thermometer.WALL) && world.getBlockState(WALL).getValue(BlockHorizontal.FACING) == EnumFacing.NORTH, "wall mount faces outward"); require(!block.canPlaceBlockOnSide(world, WALL, EnumFacing.DOWN), "no ceiling placement"); @@ -98,11 +98,11 @@ private static void contracts(WorldServer world) throws Exception { for (TemperatureDisplay.Unit unit : TemperatureDisplay.Unit.values()) { new TemperaturePreferenceMessage(unit).apply(player); messages.clear(); IBlockState state = world.getBlockState(FLOOR); - require(block.onBlockActivated(world, FLOOR, state, player, EnumHand.MAIN_HAND, null, EnumFacing.NORTH, .5F, .5F, 0), "non-operator reads placed thermometer"); + require(block.onBlockActivated(world, FLOOR, state, player, EnumHand.MAIN_HAND, EnumFacing.NORTH, .5F, .5F, 0), "non-operator reads placed thermometer"); require(messages.size() == 1 && messages.get(0).contains(unit.symbol), "placed reading follows user units"); messages.clear(); - ItemStack hand = new ItemStack(item); - require(item.onItemRightClick(hand, world, player, EnumHand.OFF_HAND).getType() == EnumActionResult.SUCCESS && hand.stackSize == 1, "hand use does not consume item"); + ItemStack hand = new ItemStack(item); player.setHeldItem(EnumHand.OFF_HAND, hand); + require(item.onItemRightClick(world, player, EnumHand.OFF_HAND).getType() == EnumActionResult.SUCCESS && hand.getCount() == 1, "hand use does not consume item"); require(messages.size() == 1 && messages.get(0).contains(unit.symbol), "hand reading follows user units"); } List drops = block.getDrops(world, FLOOR, world.getBlockState(FLOOR), 0); @@ -115,7 +115,7 @@ private static void contracts(WorldServer world) throws Exception { BlockPos far = new BlockPos(800008, 81, 800008); require(!world.isBlockLoaded(far, false) && !Thermometer.temperature(world, far).isPresent() && !world.isBlockLoaded(far, false), "measurement never loads terrain"); require(Math.abs(Thermometer.gauge(.15F) - .4F) < .00001 && Thermometer.gauge(-5) == 0 && Thermometer.gauge(5) == 1, "HUD gauge endpoints and freezing point"); - WorldServer nether = world.getMinecraftServer().worldServerForDimension(-1); nether.getChunkFromBlockCoords(FLOOR); + WorldServer nether = world.getMinecraftServer().getWorld(-1); nether.getChunkFromBlockCoords(FLOOR); require(!WeatherApi.getTemperature(nether, FLOOR).isPresent() && Thermometer.temperature(nether, FLOOR).getAsDouble() == nether.getBiome(FLOOR).getFloatTemperature(FLOOR), "native biome fallback outside weather dimensions"); new File("thermometer").mkdirs(); Files.write(new File("thermometer/saved.txt").toPath(), "standing and north wall".getBytes(StandardCharsets.UTF_8)); diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java index f85acd4..6b91278 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java @@ -81,7 +81,7 @@ public void init(FMLInitializationEvent event) { @Mod.EventHandler public void started(FMLServerStartedEvent event) { MinecraftServer server = net.minecraftforge.fml.common.FMLCommonHandler.instance().getMinecraftServerInstance(); - world = server.worldServerForDimension(0); + world = server.getWorld(0); require(HookStatus.available(), "required weather hooks loaded"); switch (MODE) { case "temperature-zones": TemperatureZoneProbe.run(world); break; @@ -227,7 +227,7 @@ private void write() { require(weather(CHECK.east(16)).precipitation == LocalWeather.Precipitation.NONE, "desert stays dry"); time(MID_WINTER, 0); require(!WeatherApi.getWeather(world, new BlockPos(180000, 70, 180000)).isPresent(), "unloaded query"); - require(!WeatherApi.getSeason(world.getMinecraftServer().worldServerForDimension(-1)).isPresent(), "Nether scope"); + require(!WeatherApi.getSeason(world.getMinecraftServer().getWorld(-1)).isPresent(), "Nether scope"); succeed("WRITE"); } @@ -376,7 +376,7 @@ private void libraryTick() { require(command("skyweather climate ~ ~ ~") == 1, "relative climate diagnostic succeeds"); require(command("skyweather climate 180000 70 180000") == 0 && world.getChunkProvider().getLoadedChunk(11250, 11250) == null, "diagnostic does not generate terrain"); - require(WeatherApi.getClimate(world.getMinecraftServer().worldServerForDimension(-1), covered, Biomes.PLAINS) + require(WeatherApi.getClimate(world.getMinecraftServer().getWorld(-1), covered, Biomes.PLAINS) .isPresent() == false, "Nether has no seasonal climate frame"); require(apiEpisodeStarts == 1 && apiEpisodeEnds == 0, "storm start event fires once"); command("skyweather weather clear 4"); @@ -463,17 +463,19 @@ private void adminNetworkTick() { BlockPos foot = new BlockPos(3, 70, 6); world.setBlockState(foot, Blocks.STONE.getDefaultState()); Item item = Item.getItemFromBlock(WeatherController.BLOCK); - require(item.onItemUse(new ItemStack(item), guest, world, foot, EnumHand.MAIN_HAND, + guest.setHeldItem(EnumHand.MAIN_HAND, new ItemStack(item)); + require(item.onItemUse(guest, world, foot, EnumHand.MAIN_HAND, EnumFacing.UP, 0.5F, 1, 0.5F) == EnumActionResult.FAIL && world.isAirBlock(foot.up()), "guest creative placement is denied on the server"); - require(item.onItemUse(new ItemStack(item), operator, world, foot, EnumHand.MAIN_HAND, + operator.setHeldItem(EnumHand.MAIN_HAND, new ItemStack(item)); + require(item.onItemUse(operator, world, foot, EnumHand.MAIN_HAND, EnumFacing.UP, 0.5F, 1, 0.5F) == EnumActionResult.SUCCESS && world.getBlockState(foot.up()).getBlock() == WeatherController.BLOCK, "operator places the registered controller"); net.minecraft.block.Block placed = world.getBlockState(foot.up()).getBlock(); for (EntityPlayerMP player : new EntityPlayerMP[] {guest, operator}) { placed.onBlockActivated(world, foot.up(), world.getBlockState(foot.up()), player, - EnumHand.MAIN_HAND, null, EnumFacing.UP, 0.5F, 1, 0.5F); + EnumHand.MAIN_HAND, EnumFacing.UP, 0.5F, 1, 0.5F); } } ServerWeather weather = ServerWeather.INSTANCE; diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/crash/CrashQualificationProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/crash/CrashQualificationProbe.java index 0dabf57..5519464 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/crash/CrashQualificationProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/crash/CrashQualificationProbe.java @@ -37,7 +37,7 @@ public final class CrashQualificationProbe { @Mod.EventHandler public void started(FMLServerStartedEvent event) { if(!Boolean.getBoolean("crash.probe"))return; MinecraftServer server=FMLCommonHandler.instance().getMinecraftServerInstance(); - WorldServer world=server.worldServerForDimension(0);long start=System.nanoTime(); + WorldServer world=server.getWorld(0);long start=System.nanoTime(); List tickets=new ArrayList<>(); try { String phase=System.getProperty("crash.phase","soak"); @@ -59,7 +59,7 @@ public final class CrashQualificationProbe { if(tick%200==0){ for(ChunkPos pos:activeChunks)ForgeChunkManager.unforceChunk(ticket,pos);activeChunks.clear(); for(int index=0;indexvalue.equals("disabled")||value.equals("absent")),"optional bridges disabled independently of installed mods"); require(ScriptRules.crops().isEmpty()&&ScriptRules.biomes().isEmpty(),"disabled script bridge leaves native rules"); } - if(!disabled&&Loader.isModLoaded("Waila"))Class.forName("zone.moddev.mc.skysrealisticweather.verify.pack.WailaChecks").getMethod("run",WorldServer.class).invoke(null,world); + if(!disabled&&Loader.isModLoaded("waila"))Class.forName("zone.moddev.mc.skysrealisticweather.verify.pack.WailaChecks").getMethod("run",WorldServer.class).invoke(null,world); if(!disabled&&Loader.isModLoaded("theoneprobe"))Class.forName("zone.moddev.mc.skysrealisticweather.verify.pack.TopChecks").getMethod("run",WorldServer.class).invoke(null,world); - if(!disabled&&Loader.isModLoaded("ToughAsNails"))Class.forName("zone.moddev.mc.skysrealisticweather.verify.pack.TanChecks").getMethod("run",WorldServer.class).invoke(null,world); - if(!disabled&&Loader.isModLoaded("MineTweaker3")) { + if(!disabled&&Loader.isModLoaded("toughasnails"))Class.forName("zone.moddev.mc.skysrealisticweather.verify.pack.TanChecks").getMethod("run",WorldServer.class).invoke(null,world); + if(!disabled&&Loader.isModLoaded("crafttweaker")) { require(!ScriptRules.crops().isEmpty(),"startup scripts captured before gameplay"); require(ServerWeather.INSTANCE.settings().farming.resolve("minecraft:wheat",Blocks.WHEAT.getDefaultState()).profile.exempt!=reload,"active script crop policy"); require(ServerWeather.INSTANCE.settings().biomes.preset(Biomes.PLAINS).id.equals("tropical_monsoon"),"scripts override generated biome config"); diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/pack/TanChecks.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/pack/TanChecks.java index 80f2f24..b057841 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/pack/TanChecks.java +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/pack/TanChecks.java @@ -22,13 +22,13 @@ public final class TanChecks { public static void run(WorldServer world) { require(Integrations.status().get("toughasnails").equals("active"),"TAN adapter initialized"); - require(!SyncedConfig.getBooleanValue(GameplayOption.ENABLE_SEASONS),"Sky owns TAN seasonal effects"); + require(!SyncedConfig.getBooleanValue(SeasonsOption.ENABLE_SEASONS),"Sky owns TAN seasonal effects"); EntityPlayerMP player=FakePlayerFactory.get(world,new GameProfile(UUID.fromString("1cfdf478-0b96-48bf-a8e4-f627f824c592"),"ClimateChecks")); BlockPos pos=new BlockPos(8,81,8);player.setPosition(pos.getX(),pos.getY(),pos.getZ()); for(BlockPos p:new BlockPos[]{pos,pos.north(10),pos.south(10),pos.east(10),pos.west(10)})world.getChunkFromBlockCoords(p); ITemperature data=TemperatureHelper.getTemperatureData(player); require(data!=null,"native TAN capability attached"); - int body=TemperatureHandler.TEMPERATURE_SCALE_MIDPOINT; + int body=TemperatureScale.getScaleMidpoint(); data.setTemperature(new Temperature(body));data.setChangeTime(37);data.applyModifier("other:heat",2,5,500); ResourceLocation zone=new ResourceLocation("packchecks","tan"); WeatherApi.putTemperatureZone(world,TemperatureZone.celsius(zone,pos.add(-1,-1,-1),pos.add(1,1,1),-35)); @@ -44,12 +44,12 @@ public static void run(WorldServer world) { require(data.getExternalModifiers().get(ToughAsNailsBridge.MODIFIER).getRate()==0,"ambient bridge adds no response-rate modifier"); WeatherApi.removeTemperatureZone(world,zone); net.minecraft.world.World previousWorld=player.world; - player.world=world.getMinecraftServer().worldServerForDimension(-1);ToughAsNailsBridge.update(player); + player.world=world.getMinecraftServer().getWorld(-1);ToughAsNailsBridge.update(player); require(!data.hasModifier(ToughAsNailsBridge.MODIFIER)&&data.hasModifier("other:heat"),"unsupported dimensions remove only Sky's ambient correction"); player.world=previousWorld;ToughAsNailsBridge.update(player); require(data.hasModifier(ToughAsNailsBridge.MODIFIER),"returning to supported world restores correction"); int previousSeason=SeasonHandler.getSeasonSavedData(world).seasonCycleTicks; - SeasonHandler.getSeasonSavedData(world).seasonCycleTicks=SeasonTime.TOTAL_CYCLE_TICKS-1000; + SeasonHandler.getSeasonSavedData(world).seasonCycleTicks=SeasonTime.ZERO.getCycleDuration()-1000; world.setBlockState(pos.down(),Blocks.FARMLAND.getDefaultState(),2);world.setBlockState(pos,Blocks.WHEAT.getDefaultState(),2); for(int i=0;i<100;i++)Blocks.WHEAT.updateTick(world,pos,world.getBlockState(pos),world.rand); require(world.getBlockState(pos).getBlock()==Blocks.WHEAT,"TAN winter does not destroy crops under Sky seasons"); @@ -58,9 +58,9 @@ public static void run(WorldServer world) { WeatherState.server(new WeatherState.Frame(world,frame.settings.withOptions(true,true,true,true,true),null)); Integrations.weatherChanged.accept(world);ToughAsNailsBridge.update(player); require(!data.hasModifier(ToughAsNailsBridge.MODIFIER)&&data.hasModifier("other:heat"),"passive mode removes only Sky modifier"); - require(SyncedConfig.getBooleanValue(GameplayOption.ENABLE_SEASONS)==Boolean.parseBoolean( - SyncedConfig.optionsToSync.get(GameplayOption.ENABLE_SEASONS.getOptionName()).defaultValue),"native TAN seasons restored"); + require(SyncedConfig.getBooleanValue(SeasonsOption.ENABLE_SEASONS)==Boolean.parseBoolean( + SyncedConfig.optionsToSync.get(SeasonsOption.ENABLE_SEASONS.getOptionName()).defaultValue),"native TAN seasons restored"); WeatherState.server(frame);Integrations.weatherChanged.accept(world); - require(!SyncedConfig.getBooleanValue(GameplayOption.ENABLE_SEASONS),"season ownership resumes when Sky resumes"); + require(!SyncedConfig.getBooleanValue(SeasonsOption.ENABLE_SEASONS),"season ownership resumes when Sky resumes"); } } diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/WeatherMod.java b/src/main/java/zone/moddev/mc/skysrealisticweather/WeatherMod.java index cf60abb..210af4b 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/WeatherMod.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/WeatherMod.java @@ -20,8 +20,8 @@ import zone.moddev.mc.skysrealisticweather.network.WeatherAdminMessage; @Mod(modid = BuildInfo.ID, name = BuildInfo.NAME, version = BuildInfo.VERSION, - acceptedMinecraftVersions = "[1.10.2]", acceptableRemoteVersions = "[" + BuildInfo.VERSION + "]", - dependencies = "required-after:Forge@[12.18.3.2511,);after:MineTweaker3;after:ToughAsNails;after:Waila;after:theoneprobe;after:JEI", + acceptedMinecraftVersions = "[1.11.2]", acceptableRemoteVersions = "[" + BuildInfo.VERSION + "]", + dependencies = "required-after:forge@[13.20.1.2588,);after:crafttweaker;after:toughasnails;after:waila;after:theoneprobe;after:jei", guiFactory = "zone.moddev.mc.skysrealisticweather.client.WeatherGuiFactory") public final class WeatherMod { public static final SimpleNetworkWrapper NETWORK = NetworkRegistry.INSTANCE.newSimpleChannel(BuildInfo.ID); diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/admin/WeatherCommand.java b/src/main/java/zone/moddev/mc/skysrealisticweather/admin/WeatherCommand.java index 7f12cd5..c3729a5 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/admin/WeatherCommand.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/admin/WeatherCommand.java @@ -307,7 +307,7 @@ else if (args.length == 1 && sender.getCommandSenderEntity() instanceof net.mine net.minecraft.util.math.Vec3d eye = new net.minecraft.util.math.Vec3d(player.posX, player.posY + player.getEyeHeight(), player.posZ); net.minecraft.util.math.Vec3d look = player.getLook(1); net.minecraft.util.math.RayTraceResult hit = weather.world().rayTraceBlocks(eye, - eye.addVector(look.xCoord * 6, look.yCoord * 6, look.zCoord * 6), false, false, true); + eye.addVector(look.x * 6, look.y * 6, look.z * 6), false, false, true); if (hit == null || hit.getBlockPos() == null) throw new CommandException("Look at a plant or supply coordinates."); position = hit.getBlockPos(); } else throw new WrongUsageException("/skyweather crop "); diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/admin/WeatherController.java b/src/main/java/zone/moddev/mc/skysrealisticweather/admin/WeatherController.java index 301dc1e..362938a 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/admin/WeatherController.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/admin/WeatherController.java @@ -1,6 +1,6 @@ package zone.moddev.mc.skysrealisticweather.admin; -import java.util.List; +import net.minecraft.util.NonNullList; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.SoundType; @@ -27,8 +27,8 @@ public final class WeatherController extends Block { public static final WeatherController BLOCK = new WeatherController(); private static final CreativeTabs ADMIN = new CreativeTabs("skysweatheradmin") { @Override - public Item getTabIconItem() { - return Item.getItemFromBlock(BLOCK); + public ItemStack getTabIconItem() { + return new ItemStack(BLOCK); } }; @@ -48,13 +48,13 @@ public static void register() { } @Override - public void getSubBlocks(Item item, CreativeTabs tab, List items) { + public void getSubBlocks(Item item, CreativeTabs tab, NonNullList items) { if (WeatherMod.proxy.showAdminItem()) super.getSubBlocks(item, tab, items); } @Override public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, - ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { + EnumFacing side, float hitX, float hitY, float hitZ) { if (hand == EnumHand.MAIN_HAND && !world.isRemote && player instanceof EntityPlayerMP) { WeatherCommand.open((EntityPlayerMP) player); } @@ -72,14 +72,14 @@ private static final class ControllerItem extends ItemBlock { } @Override - public EnumActionResult onItemUse(ItemStack stack, EntityPlayer player, World world, BlockPos pos, + public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { if (!WeatherCommand.permitted(player) || !WeatherState.supports(world)) { if (!world.isRemote) player.sendMessage(new TextComponentString( "Only operators can place the Weather Controller in the Overworld.")); return EnumActionResult.FAIL; } - return super.onItemUse(stack, player, world, pos, hand, facing, hitX, hitY, hitZ); + return super.onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); } } } diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/client/ClimateHud.java b/src/main/java/zone/moddev/mc/skysrealisticweather/client/ClimateHud.java index fd4a72c..cd7ddfb 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/client/ClimateHud.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/client/ClimateHud.java @@ -47,9 +47,9 @@ public void render(RenderGameOverlayEvent.Text event) { event.getRight().add("Sky's Climate"); for (String line : ClimateReadout.details(climate, local, WeatherApi.getWeatherEpisode(game.world, position).orElse(null))) { int width = Math.max(0, event.getResolution().getScaledWidth() / 2 - 8); - event.getRight().add(game.fontRendererObj.trimStringToWidth(line, width)); + event.getRight().add(game.fontRenderer.trimStringToWidth(line, width)); } - event.getRight().add(game.fontRendererObj.trimStringToWidth(ClimateReadout.temperature(temperature,WeatherConfiguration.temperatureUnit()), + event.getRight().add(game.fontRenderer.trimStringToWidth(ClimateReadout.temperature(temperature,WeatherConfiguration.temperatureUnit()), Math.max(0,event.getResolution().getScaledWidth()/2-8))); } else { event.getRight().add(ClimateReadout.compact(climate,new LocalWeather(local.precipitation,local.source,temperature.temperature, diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/client/ClimateModeScreen.java b/src/main/java/zone/moddev/mc/skysrealisticweather/client/ClimateModeScreen.java index d831246..d699b0b 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/client/ClimateModeScreen.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/client/ClimateModeScreen.java @@ -63,7 +63,7 @@ protected void keyTyped(char character, int key) { @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { drawDefaultBackground(); - drawCenteredString(fontRendererObj, BuildInfo.NAME, width / 2, 12, 0xFFFFFF); + drawCenteredString(fontRenderer, BuildInfo.NAME, width / 2, 12, 0xFFFFFF); String help; switch (WeatherConfiguration.mode()) { case PER_BIOME: help = "Each biome uses its mapped climate. Configure biome mappings, the shared calendar and effects."; break; @@ -71,11 +71,11 @@ public void drawScreen(int mouseX, int mouseY, float partialTicks) { default: help = "Use one selected climate preset throughout the Overworld, with local biome and altitude adjustments."; break; } int y = 122; - for (String line : fontRendererObj.listFormattedStringToWidth(help, Math.min(400, width - 24))) { - drawCenteredString(fontRendererObj, line, width / 2, y, 0xD6E5F3); + for (String line : fontRenderer.listFormattedStringToWidth(help, Math.min(400, width - 24))) { + drawCenteredString(fontRenderer, line, width / 2, y, 0xD6E5F3); y += 10; } - drawCenteredString(fontRendererObj, "Saved changes apply after restarting Minecraft.", width / 2, height - 92, 0xBBBBBB); + drawCenteredString(fontRenderer, "Saved changes apply after restarting Minecraft.", width / 2, height - 92, 0xBBBBBB); super.drawScreen(mouseX, mouseY, partialTicks); } @@ -116,8 +116,8 @@ protected void keyTyped(char character, int key) { @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { drawDefaultBackground(); - drawCenteredString(fontRendererObj, "Real World Climate", width / 2, 20, 0xFFFFFF); - drawCenteredString(fontRendererObj, "Uses Open-Meteo weather data for the selected location.", width / 2, 36, 0xD6E5F3); + drawCenteredString(fontRenderer, "Real World Climate", width / 2, 20, 0xFFFFFF); + drawCenteredString(fontRenderer, "Uses Open-Meteo weather data for the selected location.", width / 2, 36, 0xD6E5F3); super.drawScreen(mouseX, mouseY, partialTicks); } } diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/client/DistantPrecipitationRenderer.java b/src/main/java/zone/moddev/mc/skysrealisticweather/client/DistantPrecipitationRenderer.java index 394b6ee..c8dbfa1 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/client/DistantPrecipitationRenderer.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/client/DistantPrecipitationRenderer.java @@ -39,7 +39,7 @@ public void render(RenderWorldLastEvent event) { int requested = WeatherConfiguration.distantWeatherDistance(); if (game.world == null || camera == null || requested == 0 || frame == null || !frame.active() || game.world.provider.getWeatherRenderer() != null || frame.currentEpisode() == null - && frame.scheduled || game.world.provider.hasNoSky()) { + && frame.scheduled || !game.world.provider.hasSkyLight()) { field.clear(); world = null; return; } float strength = frame.regionalSchedule() ? 1 : game.world.getRainStrength(event.getPartialTicks()); diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/client/PresetEditorScreen.java b/src/main/java/zone/moddev/mc/skysrealisticweather/client/PresetEditorScreen.java index ad7b0fe..a900d43 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/client/PresetEditorScreen.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/client/PresetEditorScreen.java @@ -62,8 +62,8 @@ private void buildControls() { for (int index = 0; index < draft.length; index++) { String label = index == 0 ? "Overview" : draft[index][0].trim(); if (label.isEmpty()) label = Preset.defaultPhaseLabel(SEASONS[index - 1]); - if (fontRendererObj.getStringWidth(label) > tab - 9) { - label = fontRendererObj.trimStringToWidth(label, tab - 9 - fontRendererObj.getStringWidth("...")) + "..."; + if (fontRenderer.getStringWidth(label) > tab - 9) { + label = fontRenderer.trimStringToWidth(label, tab - 9 - fontRenderer.getStringWidth("...")) + "..."; } GuiButton button = new GuiButton(index, start + index * tab, 29, tab - 2, 20, label); button.enabled = index != page; @@ -72,7 +72,7 @@ private void buildControls() { int[] limits = page == 0 ? OVERVIEW_LIMITS : PHASE_LIMITS; int fieldWidth = Math.min(width / 2, 270); for (int index = 0; index < draft[page].length; index++) { - GuiTextField field = new GuiTextField(index, fontRendererObj, width / 2, 59 + index * 21, fieldWidth - 10, 16); + GuiTextField field = new GuiTextField(index, fontRenderer, width / 2, 59 + index * 21, fieldWidth - 10, 16); field.setMaxStringLength(limits[index]); field.setText(draft[page][index]); inputs.add(field); @@ -176,14 +176,14 @@ protected void keyTyped(char character, int key) { @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { drawDefaultBackground(); - drawCenteredString(fontRendererObj, editing ? "Edit Weather Preset" : "New Weather Preset", width / 2, 12, 0xFFFFFF); + drawCenteredString(fontRenderer, editing ? "Edit Weather Preset" : "New Weather Preset", width / 2, 12, 0xFFFFFF); String[] labels = page == 0 ? OVERVIEW_FIELDS : PHASE_FIELDS; for (int index = 0; index < inputs.size(); index++) { String label = labels[index] + (page != 0 && index == 2 ? " (" + unit.symbol + ")" : ""); - drawString(fontRendererObj, label, width / 2 - fontRendererObj.getStringWidth(label) - 10, 63 + index * 21, 0xD6E5F3); + drawString(fontRenderer, label, width / 2 - fontRenderer.getStringWidth(label) - 10, 63 + index * 21, 0xD6E5F3); inputs.get(index).drawTextBox(); } - if (error != null) drawCenteredString(fontRendererObj, error, width / 2, height - 39, 0xFFAAAA); + if (error != null) drawCenteredString(fontRenderer, error, width / 2, height - 39, 0xFFAAAA); super.drawScreen(mouseX, mouseY, partialTicks); } } diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/client/ThermometerHud.java b/src/main/java/zone/moddev/mc/skysrealisticweather/client/ThermometerHud.java index 4737556..ff69dac 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/client/ThermometerHud.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/client/ThermometerHud.java @@ -39,9 +39,9 @@ public void render(RenderGameOverlayEvent.Post event) { Gui.drawRect(x + 8, y + 28 - level, x + 12, y + 28, 0xFFD5E4ED); } for (int mark = 0; mark <= 4; mark++) Gui.drawRect(x + 14, y + 6 + mark * 5, x + 17, y + 7 + mark * 5, 0xFFA9BBC7); - game.fontRendererObj.drawStringWithShadow(I18n.format("hud.skysrealisticweather.temperature"), x + 21, y + 4, 0xC9D8E2); - game.fontRendererObj.drawStringWithShadow(reading.isPresent() ? TemperatureDisplay.format((float) reading.getAsDouble()) : "--", x + 21, y + 16, 0xFFFFFF); - game.fontRendererObj.drawStringWithShadow(I18n.format(held ? "hud.skysrealisticweather.here" : "hud.skysrealisticweather.placed"), x + 21, y + 27, 0x91A5B4); + game.fontRenderer.drawStringWithShadow(I18n.format("hud.skysrealisticweather.temperature"), x + 21, y + 4, 0xC9D8E2); + game.fontRenderer.drawStringWithShadow(reading.isPresent() ? TemperatureDisplay.format((float) reading.getAsDouble()) : "--", x + 21, y + 16, 0xFFFFFF); + game.fontRenderer.drawStringWithShadow(I18n.format(held ? "hud.skysrealisticweather.here" : "hud.skysrealisticweather.placed"), x + 21, y + 27, 0x91A5B4); GlStateManager.color(1, 1, 1, 1); } @SubscribeEvent diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/client/WeatherAdminScreen.java b/src/main/java/zone/moddev/mc/skysrealisticweather/client/WeatherAdminScreen.java index 78a1223..1a770ec 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/client/WeatherAdminScreen.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/client/WeatherAdminScreen.java @@ -276,7 +276,7 @@ private String value(String key) { } private void field(String key, int x, int y, int width, String initial) { - GuiTextField field = new GuiTextField(fields.size(), fontRendererObj, x, y, width, 16); + GuiTextField field = new GuiTextField(fields.size(), fontRenderer, x, y, width, 16); field.setMaxStringLength(16); field.setText(draft.getOrDefault(key, initial)); fields.put(key, field); @@ -345,39 +345,39 @@ public boolean doesGuiPauseGame() { public void drawScreen(int mouseX, int mouseY, float partialTicks) { drawRect(8, 7, 8 + panelWidth, 238, 0xED15202D); drawRect(8, 7, 8 + panelWidth, 9, 0xFF6DAAC7); - drawString(fontRendererObj, "Weather Controller", 16, 14, 0xFFFFFF); - drawString(fontRendererObj, fit(worldStatus(), panelWidth - 16), 16, 27, 0xC1DEEB); + drawString(fontRenderer, "Weather Controller", 16, 14, 0xFFFFFF); + drawString(fontRenderer, fit(worldStatus(), panelWidth - 16), 16, 27, 0xC1DEEB); int cell = (panelWidth - 16) / 4; switch (page) { case WEATHER: int right = 21 + (panelWidth - 24) * 56 / 100; - drawString(fontRendererObj, "Seconds", right, 93, 0xC1DEEB); - drawString(fontRendererObj, "Intensity (0.01-1)", right, 124, 0xC1DEEB); + drawString(fontRenderer, "Seconds", right, 93, 0xC1DEEB); + drawString(fontRenderer, "Intensity (0.01-1)", right, 124, 0xC1DEEB); break; case CALENDAR: - drawString(fontRendererObj, "Jump to a phase on day", 16, 98, 0xC1DEEB); + drawString(fontRenderer, "Jump to a phase on day", 16, 98, 0xC1DEEB); break; case CLIMATE: String preset = snapshot.presets.getOrDefault(snapshot.preset, "Custom"); - drawString(fontRendererObj, fit(preset, cell * 2 - 6), 16, 71, 0xC1DEEB); - drawString(fontRendererObj, "Strength", 16, 98, 0xC1DEEB); + drawString(fontRenderer, fit(preset, cell * 2 - 6), 16, 71, 0xC1DEEB); + drawString(fontRenderer, "Strength", 16, 98, 0xC1DEEB); int column = (panelWidth - 16) / PHASE_FIELDS.length; for (int index = 0; index < PHASE_FIELDS.length; index++) { - drawString(fontRendererObj, fit(index == 1 ? "Δ" + zone.moddev.mc.skysrealisticweather.climate.WeatherConfiguration.temperatureUnit().symbol : PHASE_FIELDS[index], column - 3), 16 + index * column, 137, 0xC1DEEB); + drawString(fontRenderer, fit(index == 1 ? "Δ" + zone.moddev.mc.skysrealisticweather.climate.WeatherConfiguration.temperatureUnit().symbol : PHASE_FIELDS[index], column - 3), 16 + index * column, 137, 0xC1DEEB); } break; case EFFECTS: - drawString(fontRendererObj, "Changes apply to the whole Overworld.", 16, 148, 0xC1DEEB); + drawString(fontRenderer, "Changes apply to the whole Overworld.", 16, 148, 0xC1DEEB); break; default: break; } String visibleFeedback = fit(feedback, panelWidth - 16); - drawString(fontRendererObj, visibleFeedback, 16, 204, error ? 0xFFAAAA : 0xBDDDA8); + drawString(fontRenderer, visibleFeedback, 16, 204, error ? 0xFFAAAA : 0xBDDDA8); fields.values().forEach(GuiTextField::drawTextBox); super.drawScreen(mouseX, mouseY, partialTicks); if (!visibleFeedback.equals(feedback) && mouseX >= 16 && mouseX <= panelWidth && mouseY >= 204 && mouseY < 213) { - drawHoveringText(fontRendererObj.listFormattedStringToWidth(feedback, panelWidth - 16), mouseX, mouseY); + drawHoveringText(fontRenderer.listFormattedStringToWidth(feedback, panelWidth - 16), mouseX, mouseY); } } @@ -399,8 +399,8 @@ private String worldStatus() { } private String fit(String value, int pixels) { - if (fontRendererObj.getStringWidth(value) <= pixels) return value; - if (pixels < fontRendererObj.getStringWidth("...")) return ""; - return fontRendererObj.trimStringToWidth(value, pixels - fontRendererObj.getStringWidth("...")) + "..."; + if (fontRenderer.getStringWidth(value) <= pixels) return value; + if (pixels < fontRenderer.getStringWidth("...")) return ""; + return fontRenderer.trimStringToWidth(value, pixels - fontRenderer.getStringWidth("...")) + "..."; } } diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/client/WeatherConfigScreen.java b/src/main/java/zone/moddev/mc/skysrealisticweather/client/WeatherConfigScreen.java index bff341f..5259748 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/client/WeatherConfigScreen.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/client/WeatherConfigScreen.java @@ -158,11 +158,11 @@ else if (key == Keyboard.KEY_UP || key == Keyboard.KEY_DOWN) { public void drawScreen(int mouseX, int mouseY, float partialTicks) { drawDefaultBackground(); presetList.drawScreen(mouseX, mouseY, partialTicks); - drawCenteredString(fontRendererObj, managing ? "Manage Weather Presets" : BuildInfo.NAME, + drawCenteredString(fontRenderer, managing ? "Manage Weather Presets" : BuildInfo.NAME, width / 2, 12, 0xFFFFFF); Preset active = WeatherConfiguration.preset(WeatherConfiguration.activePreset()); String current = active == null ? "Custom" : active.label; - drawCenteredString(fontRendererObj, fit("Active " + current, width - 24), + drawCenteredString(fontRenderer, fit("Active " + current, width - 24), width / 2, 29, 0xD6E5F3); drawPreview(); super.drawScreen(mouseX, mouseY, partialTicks); @@ -173,21 +173,21 @@ private void drawPreview() { int center = width / 2; int top = presetList.bottom + 7; if (preview != null) { - drawCenteredString(fontRendererObj, fit(preview.label + " | " + preview.profile.daysInYear() + drawCenteredString(fontRenderer, fit(preview.label + " | " + preview.profile.daysInYear() + " Minecraft days", width - 24), center, top, 0xFFFFFF); - List lines = fontRendererObj.listFormattedStringToWidth(preview.description, width - 28); + List lines = fontRenderer.listFormattedStringToWidth(preview.description, width - 28); for (int index = 0; index < Math.min(lines.size(), 2); index++) { String line = lines.get(index); if (index == 1 && lines.size() > 2) line = fit(line + "...", width - 28); - drawCenteredString(fontRendererObj, line, center, top + 13 + index * 10, 0xD6E5F3); + drawCenteredString(fontRenderer, line, center, top + 13 + index * 10, 0xD6E5F3); } drawPhasePair(preview, Season.SPRING, Season.SUMMER, top + 37); drawPhasePair(preview, Season.AUTUMN, Season.WINTER, top + 48); } else { String text = presetList.rows.isEmpty() ? "Create a preset in Manage Presets." : "Select a preset to preview it."; - drawCenteredString(fontRendererObj, text, center, top + 18, 0xD6E5F3); + drawCenteredString(fontRenderer, text, center, top + 18, 0xD6E5F3); } - drawCenteredString(fontRendererObj, "Changes take effect after restarting Minecraft.", + drawCenteredString(fontRenderer, "Changes take effect after restarting Minecraft.", center, height - 38, 0xBBBBBB); } @@ -196,13 +196,13 @@ private void drawPhasePair(Preset preset, Season first, Season second, int y) { for (Season season : new Season[] {first, second}) { String phase = preset.phaseLabel(season) + " (" + preset.profile.period(season.ordinal()).days + " days)"; int center = width / 2 + (season == first ? -column / 2 : column / 2); - drawCenteredString(fontRendererObj, fit(phase, column - 4), center, y, 0xD6E5F3); + drawCenteredString(fontRenderer, fit(phase, column - 4), center, y, 0xD6E5F3); } } private String fit(String text, int pixels) { - if (fontRendererObj.getStringWidth(text) <= pixels) return text; - return fontRendererObj.trimStringToWidth(text, pixels - fontRendererObj.getStringWidth("...")) + "..."; + if (fontRenderer.getStringWidth(text) <= pixels) return text; + return fontRenderer.trimStringToWidth(text, pixels - fontRenderer.getStringWidth("...")) + "..."; } private final class PresetList extends GuiSlot { @@ -256,13 +256,13 @@ protected void drawBackground() { protected void drawSlot(int index, int x, int y, int slotHeight, int mouseX, int mouseY) { Row row = rows.get(index); if (row.preset == null) { - drawString(fontRendererObj, row.label, x + 4, y + 4, 0x9DC4E1); + drawString(fontRenderer, row.label, x + 4, y + 4, 0x9DC4E1); return; } boolean active = row.preset.id.equals(WeatherConfiguration.activePreset()); - int reserve = active ? fontRendererObj.getStringWidth("Active") + 18 : 12; - drawString(fontRendererObj, fit(row.label, getListWidth() - reserve), x + 9, y + 4, 0xFFFFFF); - if (active) drawString(fontRendererObj, "Active", x + getListWidth() - reserve + 8, y + 4, 0xB7DB98); + int reserve = active ? fontRenderer.getStringWidth("Active") + 18 : 12; + drawString(fontRenderer, fit(row.label, getListWidth() - reserve), x + 9, y + 4, 0xFFFFFF); + if (active) drawString(fontRenderer, "Active", x + getListWidth() - reserve + 8, y + 4, 0xB7DB98); } void moveSelection(int direction) { diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/client/WeatherGuiFactory.java b/src/main/java/zone/moddev/mc/skysrealisticweather/client/WeatherGuiFactory.java index e26789d..3543587 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/client/WeatherGuiFactory.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/client/WeatherGuiFactory.java @@ -18,19 +18,23 @@ public void initialize(Minecraft minecraft) { } @Override - public Class mainConfigGuiClass() { - return ClimateModeScreen.class; + public GuiScreen createConfigGui(GuiScreen parent) { + return new ClimateModeScreen(parent); } + @Override + public Class mainConfigGuiClass() { return ClimateModeScreen.class; } + @Override public Set runtimeGuiCategories() { return Collections.emptySet(); } @Override - public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) { - return null; - } + public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) { return null; } + + @Override + public boolean hasConfigGui() { return true; } @SubscribeEvent public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) { diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/climate/BiomeClimateMap.java b/src/main/java/zone/moddev/mc/skysrealisticweather/climate/BiomeClimateMap.java index e0d035c..04f55e2 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/climate/BiomeClimateMap.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/climate/BiomeClimateMap.java @@ -68,7 +68,7 @@ public static String classify(Biome biome) { } private static boolean is(Biome biome, BiomeDictionary.Type type) { - return BiomeDictionary.isBiomeOfType(biome, type); + return BiomeDictionary.hasType(biome, type); } public static BiomeClimateMap defaults() { diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/compat/ForestryClimate.java b/src/main/java/zone/moddev/mc/skysrealisticweather/compat/ForestryClimate.java new file mode 100644 index 0000000..2c32366 --- /dev/null +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/compat/ForestryClimate.java @@ -0,0 +1,19 @@ +package zone.moddev.mc.skysrealisticweather.compat; + +import forestry.api.climate.IClimateInfo; +import forestry.api.core.ForestryAPI; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import zone.moddev.mc.skysrealisticweather.game.PlantGrowthHooks; + +/** Called only on Forestry 5.3's ambient fallback; managed rooms return before this hook. */ +public final class ForestryClimate { + private ForestryClimate() { } + + public static IClimateInfo ambient(IClimateInfo nativeInfo, World world, BlockPos pos) { + float temperature = PlantGrowthHooks.forestryTemperature(nativeInfo.getTemperature(), world, pos); + float humidity = PlantGrowthHooks.forestryHumidity(nativeInfo.getHumidity(), world, pos); + return temperature == nativeInfo.getTemperature() && humidity == nativeInfo.getHumidity() ? nativeInfo + : ForestryAPI.climateManager.createInfo(temperature, humidity); + } +} diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/compat/Integrations.java b/src/main/java/zone/moddev/mc/skysrealisticweather/compat/Integrations.java index 763ff66..f4d74e2 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/compat/Integrations.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/compat/Integrations.java @@ -11,11 +11,11 @@ public final class Integrations { public static Runnable worldClosed = () -> { }; private Integrations() { } public static void init() { - load("crafttweaker", "MineTweaker3", "CraftTweakerBridge"); - load("toughasnails", "ToughAsNails", "ToughAsNailsBridge"); - load("waila", "Waila", "WailaProvider"); + load("crafttweaker", "crafttweaker", "CraftTweakerBridge"); + load("toughasnails", "toughasnails", "ToughAsNailsBridge"); + load("waila", "waila", "WailaProvider"); load("theoneprobe", "theoneprobe", "TopProvider"); - STATUS.put("jei",!Loader.isModLoaded("JEI")?"absent":WeatherConfiguration.integration("jei")?"available on clients":"disabled"); + STATUS.put("jei",!Loader.isModLoaded("jei")?"absent":WeatherConfiguration.integration("jei")?"available on clients":"disabled"); } public static void load(String key, String mod, String entry) { if (!Loader.isModLoaded(mod)) { STATUS.put(key, "absent"); return; } diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/compat/JeiClimatePlugin.java b/src/main/java/zone/moddev/mc/skysrealisticweather/compat/JeiClimatePlugin.java index 12efa42..33e6b3b 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/compat/JeiClimatePlugin.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/compat/JeiClimatePlugin.java @@ -28,7 +28,7 @@ public final class JeiClimatePlugin extends BlankModPlugin { @Override public void register(IModRegistry registry) { if(!WeatherConfiguration.integration("jei"))return; - catalogue=new ArrayList<>(registry.getItemRegistry().getItemList()); + catalogue=new ArrayList<>(registry.getIngredientRegistry().getIngredients(ItemStack.class)); registry.addRecipeCategories(new Category(registry.getJeiHelpers().getGuiHelper())); registry.addRecipeHandlers(new Handler()); MinecraftForge.EVENT_BUS.register(this); @@ -43,7 +43,7 @@ public final class JeiClimatePlugin extends BlankModPlugin { recipes.clear();indexedWorld=game.world; if(indexedWorld==null)return; for(ItemStack stack:catalogue) { - if(stack==null||stack.getItem()==null)continue; + if(stack==null||stack.isEmpty())continue; for(PlantItems.Plant plant:PlantItems.resolve(stack,indexedWorld,game.player.getPosition())) { Entry entry=new Entry(stack.copy(),plant);recipes.add(entry);runtime.getRecipeRegistry().addRecipe(entry); } @@ -52,7 +52,6 @@ public final class JeiClimatePlugin extends BlankModPlugin { public static final class Entry extends BlankRecipeWrapper { final ItemStack stack;final PlantItems.Plant plant; Entry(ItemStack stack,PlantItems.Plant plant){this.stack=stack;this.plant=plant;} - @Override public List getOutputs(){return Collections.singletonList(stack);} @Override public void getIngredients(IIngredients ingredients){ingredients.setOutput(ItemStack.class,stack);} public List description(Minecraft game) { if(game.world==null||game.player==null)return Collections.singletonList("Local climate unavailable"); @@ -61,7 +60,7 @@ public List description(Minecraft game) { return lines; } @Override public void drawInfo(Minecraft game,int width,int height,int mouseX,int mouseY) { - game.fontRendererObj.drawString(game.fontRendererObj.trimStringToWidth(stack.getDisplayName(),WIDTH-25),24,5,0x404040); + game.fontRenderer.drawString(game.fontRenderer.trimStringToWidth(stack.getDisplayName(),WIDTH-25),24,5,0x404040); int y=25; for(String line:description(game)) { if(line.contains("AgriCraft crop-stick growth"))continue; @@ -70,9 +69,9 @@ public List description(Minecraft game) { .replace("Typical local seasonal conditions:","Typical seasons:").replace("natural growth","growth"); int colour=line.contains(TextFormatting.RED.toString())?0xA52B2B:line.contains(TextFormatting.GREEN.toString())?0x286B32: line.contains(TextFormatting.YELLOW.toString())?0x846000:0x404040; - for(String part:game.fontRendererObj.listFormattedStringToWidth(TextFormatting.getTextWithoutFormattingCodes(line),WIDTH)) { + for(String part:game.fontRenderer.listFormattedStringToWidth(TextFormatting.getTextWithoutFormattingCodes(line),WIDTH)) { if(y>HEIGHT-10)return; - game.fontRendererObj.drawString(part,0,y,colour);y+=10; + game.fontRenderer.drawString(part,0,y,colour);y+=10; } } } @@ -90,6 +89,7 @@ private static final class Category implements IRecipeCategory { Category(IGuiHelper gui){background=gui.createBlankDrawable(WIDTH,HEIGHT);} public String getUid(){return CATEGORY;} public String getTitle(){return "Climate requirements";} + public String getModName(){return "Sky's Realistic Weather";} public IDrawable getBackground(){return background;} public IDrawable getIcon(){return null;} public void drawExtras(Minecraft game){ } diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/compat/ToughAsNailsBridge.java b/src/main/java/zone/moddev/mc/skysrealisticweather/compat/ToughAsNailsBridge.java index 7d66121..62e4881 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/compat/ToughAsNailsBridge.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/compat/ToughAsNailsBridge.java @@ -51,7 +51,7 @@ private static void changed(WorldServer candidate) { if(!active(candidate)){close();return;} world=candidate; if(seasonOption==null) { - SyncedConfig.SyncedConfigEntry option=SyncedConfig.optionsToSync.get(GameplayOption.ENABLE_SEASONS.getOptionName()); + SyncedConfig.SyncedConfigEntry option=SyncedConfig.optionsToSync.get(SeasonsOption.ENABLE_SEASONS.getOptionName()); if(option==null)throw new IllegalStateException("TAN seasons option is unavailable"); seasonOption=option;previousSeasons=option.value;option.value="false"; synchronize(); @@ -60,7 +60,7 @@ private static void changed(WorldServer candidate) { } private static void synchronize() { NBTTagCompound values=new NBTTagCompound(); - values.setString(GameplayOption.ENABLE_SEASONS.getOptionName(),seasonOption.value); + values.setString(SeasonsOption.ENABLE_SEASONS.getOptionName(),seasonOption.value); PacketHandler.instance.sendToAll(new MessageSyncConfigs(values)); } public static void close() { @@ -95,7 +95,7 @@ public static void update(EntityPlayer player) { Optional local=WeatherApi.getTemperatureSample(player.world,pos); ITemperature data=TemperatureHelper.getTemperatureData(player); if(!local.isPresent()||data==null){remove(player);return;} - Temperature baseline=new Temperature(TemperatureHandler.TEMPERATURE_SCALE_MIDPOINT); + Temperature baseline=new Temperature(TemperatureScale.getScaleMidpoint()); baseline=BIOME.modifyTarget(player.world,player,baseline); baseline=ALTITUDE.modifyTarget(player.world,player,baseline); baseline=TIME.modifyTarget(player.world,player,baseline); @@ -103,7 +103,7 @@ public static void update(EntityPlayer player) { baseline=SEASON.modifyTarget(player.world,player,baseline); int target=ambientTarget(local.get().temperature); int correction=target-baseline.getRawValue(); - // TAN 1.1.1 refreshes an existing modifier's expiry but retains its old amount/rate. + // TAN refreshes an existing modifier's expiry but retains its old amount/rate. TemperatureModifier.ExternalModifier own=data.getExternalModifiers().get(MODIFIER); if(own!=null&&(own.getAmount()!=correction||own.getRate()!=0))remove(player); data.applyModifier(MODIFIER,correction,0,40); @@ -112,7 +112,7 @@ public static void update(EntityPlayer player) { public static int ambientTarget(float minecraftTemperature) { if(!Float.isFinite(minecraftTemperature))throw new IllegalArgumentException("Invalid ambient temperature"); float normalized=Math.max(0,Math.min(1.35F,minecraftTemperature))/1.35F; - return TemperatureHandler.TEMPERATURE_SCALE_MIDPOINT+Math.round((normalized*2-1)*BiomeModifier.MAX_TEMP_OFFSET); + return TemperatureScale.getScaleMidpoint()+Math.round((normalized*2-1)*BiomeModifier.MAX_TEMP_OFFSET); } private static void remove(EntityPlayer player) { ITemperature data=TemperatureHelper.getTemperatureData(player); diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/compat/WailaProvider.java b/src/main/java/zone/moddev/mc/skysrealisticweather/compat/WailaProvider.java index d0961b0..f31af91 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/compat/WailaProvider.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/compat/WailaProvider.java @@ -14,7 +14,7 @@ import zone.moddev.mc.skysrealisticweather.game.CropPresentation; public final class WailaProvider implements IWailaDataProvider { - public static void register(){FMLInterModComms.sendMessage("Waila","register",WailaProvider.class.getName()+".register");} + public static void register(){FMLInterModComms.sendMessage("waila","register",WailaProvider.class.getName()+".register");} public static void register(IWailaRegistrar registrar) { WailaProvider provider=new WailaProvider();registrar.registerBodyProvider(provider,Block.class);registrar.registerNBTProvider(provider,Block.class); Integrations.ready("waila"); diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/core/PlantTransformer.java b/src/main/java/zone/moddev/mc/skysrealisticweather/core/PlantTransformer.java index 12cfc2c..a613a5e 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/core/PlantTransformer.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/core/PlantTransformer.java @@ -108,25 +108,23 @@ private static void agricraft(ClassNode node) { } private static void forestry(ClassNode node) { + String info = "Lforestry/api/climate/IClimateInfo;"; int changes = 0; for (MethodNode method : node.methods) { - boolean temperature = method.name.equals("getTemperature"), humidity = method.name.equals("getHumidity"); - if ((!temperature && !humidity) || !method.desc.equals("(" + WORLD + POS + ")F")) continue; - int calls = 0; - for (AbstractInsnNode i : method.instructions.toArray()) if (i instanceof MethodInsnNode) { - MethodInsnNode call = (MethodInsnNode) i; - if (!call.owner.equals("net/minecraft/world/biome/Biome") || !call.desc.equals("()F")) continue; - if (!(temperature ? call.name.equals("getTemperature") || call.name.equals("func_185353_n") - : call.name.equals("getRainfall") || call.name.equals("func_76727_i"))) continue; + if (!method.name.equals("getInfo") || !method.desc.equals("(" + WORLD + POS + ")" + info)) continue; + for (AbstractInsnNode instruction : method.instructions.toArray()) { + if (!(instruction instanceof MethodInsnNode)) continue; + MethodInsnNode call = (MethodInsnNode) instruction; + if (call.getOpcode() != INVOKESTATIC || !call.owner.equals("forestry/core/climate/BiomeClimateInfo") + || !call.name.equals("getInfo") || !call.desc.equals("(Lnet/minecraft/world/biome/Biome;)Lforestry/core/climate/BiomeClimateInfo;")) continue; InsnList bridge = new InsnList(); bridge.add(new VarInsnNode(ALOAD, 1)); bridge.add(new VarInsnNode(ALOAD, 2)); - bridge.add(new MethodInsnNode(INVOKESTATIC, HOOKS, temperature ? "forestryTemperature" : "forestryHumidity", "(F" + WORLD + POS + ")F", false)); + bridge.add(new MethodInsnNode(INVOKESTATIC, "zone/moddev/mc/skysrealisticweather/compat/ForestryClimate", + "ambient", "(" + info + WORLD + POS + ")" + info, false)); method.instructions.insert(call, bridge); - calls++; + changes++; } - if (calls != 1) throw new IllegalArgumentException("Forestry ambient fallback differs"); - changes++; } - if (changes != 2) throw new IllegalArgumentException("Forestry climate signatures differ"); + if (changes != 1) throw new IllegalArgumentException("Forestry ambient climate fallback differs"); } } diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/core/WeatherLoadingPlugin.java b/src/main/java/zone/moddev/mc/skysrealisticweather/core/WeatherLoadingPlugin.java index f5febe1..a5a8e3a 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/core/WeatherLoadingPlugin.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/core/WeatherLoadingPlugin.java @@ -4,7 +4,7 @@ import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin; @IFMLLoadingPlugin.Name("SkyRealisticWeather") -@IFMLLoadingPlugin.MCVersion("1.10.2") +@IFMLLoadingPlugin.MCVersion("1.11.2") @IFMLLoadingPlugin.SortingIndex(1001) @IFMLLoadingPlugin.TransformerExclusions({"zone.moddev.mc.skysrealisticweather.core"}) public final class WeatherLoadingPlugin implements IFMLLoadingPlugin { diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/core/WeatherTransformer.java b/src/main/java/zone/moddev/mc/skysrealisticweather/core/WeatherTransformer.java index 97f03d5..8e6d1f3 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/core/WeatherTransformer.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/core/WeatherTransformer.java @@ -30,9 +30,8 @@ public final class WeatherTransformer implements IClassTransformer, Opcodes { private static final String BLOCK = "Lnet/minecraft/block/Block;"; private static final String OVERWORLD_GENERATOR = "net.minecraft.world.gen.ChunkProviderOverworld"; private static final String BOP_GENERATOR = "biomesoplenty.common.world.ChunkProviderGenerateBOP"; - private static final String RTG_GENERATOR = "rtg.world.gen.ChunkProviderRTG"; private static final String LOST_GENERATOR = "mcjty.lostcities.dimensions.world.LostCityChunkGenerator"; - private static final String OTG_FROST = "com.khorn.terraincontrol.generator.FrozenSurfaceHelper"; + private static final String OTG_FROST = "com.pg85.otg.generator.FrozenSurfaceHelper"; private static final String PROPERTY_ENUM = "net.minecraft.block.properties.PropertyEnum"; private static final String SECTION_STATES = "net.minecraft.world.chunk.BlockStateContainer"; @@ -57,7 +56,6 @@ public byte[] transform(String name, String target, byte[] bytes) { case "net.minecraft.client.renderer.EntityRenderer": patchRenderer(node); break; case OVERWORLD_GENERATOR: case BOP_GENERATOR: - case RTG_GENERATOR: case LOST_GENERATOR: patchGeneration(node, target); break; case OTG_FROST: patchOtgFrost(node); break; default: return bytes; @@ -174,13 +172,12 @@ private static boolean cachePropertyNameHash(ClassNode type) { } private static boolean isGenerator(String name) { - return OVERWORLD_GENERATOR.equals(name) || BOP_GENERATOR.equals(name) || RTG_GENERATOR.equals(name) + return OVERWORLD_GENERATOR.equals(name) || BOP_GENERATOR.equals(name) || LOST_GENERATOR.equals(name) || OTG_FROST.equals(name); } private static void patchGeneration(ClassNode type, String target) { - MethodNode populate = RTG_GENERATOR.equals(target) ? method(type, "doPopulate", "doPopulate", "(II)V") - : method(type, "populate", "func_185931_b", "(II)V"); + MethodNode populate = method(type, "populate", "func_185931_b", "(II)V"); if (LOST_GENERATOR.equals(target)) { redirect(populate, "canBlockFreeze", "func_175670_e", "(" + POS + "Z)Z", HOOKS, "generationFreeze", "(" + WORLD + POS + "Z)Z", -1, 1); @@ -188,29 +185,14 @@ private static void patchGeneration(ClassNode type, String target) { redirect(populate, "canBlockFreezeWater", "func_175675_v", "(" + POS + ")Z", HOOKS, "generationFreeze", "(" + WORLD + POS + ")Z", -1, 1); } - if (RTG_GENERATOR.equals(target)) { - int count = 0; - for (AbstractInsnNode insn : populate.instructions.toArray()) { - if (!matches(insn, "canSnowAt", "canSnowAt", "(" + POS + "Z)Z")) continue; - if (!"rtg/api/util/WorldUtil".equals(((MethodInsnNode) insn).owner)) continue; - populate.instructions.insertBefore(insn, new VarInsnNode(ALOAD, 0)); - populate.instructions.insertBefore(insn, new FieldInsnNode(GETFIELD, type.name, "worldObj", WORLD)); - populate.instructions.set(insn, hook("zone/moddev/mc/skysrealisticweather/game/RtgWeather", "snow", - "(Lrtg/api/util/WorldUtil;" + POS + "Z" + WORLD + ")Z")); - count++; - } - expect(count, 1, "RTG snow eligibility"); - expect((int) type.fields.stream().filter(f -> f.name.equals("worldObj") && f.desc.equals(WORLD)).count(), 1, "RTG world"); - } else { - redirect(populate, "canSnowAt", "func_175708_f", "(" + POS + "Z)Z", HOOKS, - "generationSnow", "(" + WORLD + POS + "Z)Z", -1, 1); - } + redirect(populate, "canSnowAt", "func_175708_f", "(" + POS + "Z)Z", HOOKS, + "generationSnow", "(" + WORLD + POS + "Z)Z", -1, 1); redirect(populate, "setBlockState", "func_180501_a", "(" + POS + STATE + "I)Z", HOOKS, "placeGeneratedDeposit", "(" + WORLD + POS + STATE + "I)Z", -1, 2); } private static void patchOtgFrost(ClassNode type) { - String otg = "com/khorn/terraincontrol/"; + String otg = "com/pg85/otg/"; String localWorld = "L" + otg + "LocalWorld;"; expect((int) type.fields.stream().filter(f -> f.name.equals("world") && f.desc.equals(localWorld)).count(), 1, "OTG world"); MethodNode column = method(type, "freezeColumn", "freezeColumn", "(II)V"); diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/game/BiomeClimates.java b/src/main/java/zone/moddev/mc/skysrealisticweather/game/BiomeClimates.java index e18c95f..5c609a3 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/game/BiomeClimates.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/game/BiomeClimates.java @@ -28,7 +28,7 @@ public static synchronized void freeze() { Map byBiome = new HashMap<>(); for (Biome biome : Biome.REGISTRY) { BiomeClimate climate = definitions.get(biome.getRegistryName()); - if (climate == null && BiomeDictionary.isBiomeOfType(biome, BiomeDictionary.Type.JUNGLE)) { + if (climate == null && BiomeDictionary.hasType(biome, BiomeDictionary.Type.JUNGLE)) { climate = new BiomeClimate(0, 0.35F, BiomeClimate.PrecipitationRule.BIOME_DEFAULT); } if (climate != null) byBiome.put(biome, climate); @@ -56,8 +56,8 @@ public static boolean allowsPrecipitation(Biome biome, boolean includesDryBiomes default: break; } return biome.canRain() || biome.getEnableSnow() - || includesDryBiomes && (BiomeDictionary.isBiomeOfType(biome, BiomeDictionary.Type.DRY) - || BiomeDictionary.isBiomeOfType(biome, BiomeDictionary.Type.SAVANNA) - || BiomeDictionary.isBiomeOfType(biome, BiomeDictionary.Type.MESA)); + || includesDryBiomes && (BiomeDictionary.hasType(biome, BiomeDictionary.Type.DRY) + || BiomeDictionary.hasType(biome, BiomeDictionary.Type.SAVANNA) + || BiomeDictionary.hasType(biome, BiomeDictionary.Type.MESA)); } } diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/game/OtgWeather.java b/src/main/java/zone/moddev/mc/skysrealisticweather/game/OtgWeather.java index 20a4cb4..948077e 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/game/OtgWeather.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/game/OtgWeather.java @@ -1,18 +1,18 @@ package zone.moddev.mc.skysrealisticweather.game; -import com.khorn.terraincontrol.LocalBiome; -import com.khorn.terraincontrol.LocalMaterialData; -import com.khorn.terraincontrol.LocalWorld; -import com.khorn.terraincontrol.forge.ForgeBiome; -import com.khorn.terraincontrol.forge.ForgeWorld; -import com.khorn.terraincontrol.util.minecraftTypes.DefaultMaterial; +import com.pg85.otg.LocalBiome; +import com.pg85.otg.LocalMaterialData; +import com.pg85.otg.LocalWorld; +import com.pg85.otg.forge.ForgeBiome; +import com.pg85.otg.forge.ForgeWorld; +import com.pg85.otg.util.minecraftTypes.DefaultMaterial; 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.biome.Biome; -/** Called at OTG v21's existing surface height and virtual biome lookup. */ +/** Called at OTG v9's existing surface height and virtual biome lookup. */ public final class OtgWeather { private OtgWeather() { } @@ -35,7 +35,7 @@ public static float frostColumn(LocalBiome selected, int x, int y, int z, LocalW if (temperature >= WeatherState.SNOW_LINE || !world.getWorldBorder().contains(surface) || !world.canSeeSky(surface)) { return nativeTemperature; } - LocalMaterialData support = terrain.getMaterial(x, y - 1, z); + LocalMaterialData support = terrain.getMaterial(x, y - 1, z, false); BlockPos water = surface.down(); if (support.isLiquid()) { if (selected.getBiomeConfig().iceBlock.isMaterial(DefaultMaterial.ICE) diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/game/PlantItems.java b/src/main/java/zone/moddev/mc/skysrealisticweather/game/PlantItems.java index e37b375..14f3810 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/game/PlantItems.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/game/PlantItems.java @@ -30,7 +30,7 @@ public static final class Plant { } public static List resolve(ItemStack stack, World world, BlockPos pos) { - if (stack == null || stack.getItem() == null || stack.stackSize <= 0) return Collections.emptyList(); + if (stack == null || stack.isEmpty()) return Collections.emptyList(); Item item = stack.getItem(); try { if (net.minecraftforge.fml.common.Loader.isModLoaded("agricraft") && @@ -103,7 +103,7 @@ private static void buildProduce() { produce = index; } private static void add(Map>> index, Item item, int meta, Plant plant) { - if (item != null) index.computeIfAbsent(item, ignored -> new HashMap<>()).computeIfAbsent(meta, ignored -> new ArrayList<>()).add(plant); + if (item != null && item != Items.AIR) index.computeIfAbsent(item, ignored -> new HashMap<>()).computeIfAbsent(meta, ignored -> new ArrayList<>()).add(plant); } private static void warn(Class type, Throwable problem) { if (warned.add(type)) LogManager.getLogger("Sky's Realistic Weather").warn("Cannot resolve plant tooltip for {}", type.getName(), problem); diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/game/RtgWeather.java b/src/main/java/zone/moddev/mc/skysrealisticweather/game/RtgWeather.java deleted file mode 100644 index ba42ab6..0000000 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/game/RtgWeather.java +++ /dev/null @@ -1,15 +0,0 @@ -package zone.moddev.mc.skysrealisticweather.game; - -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import rtg.api.util.WorldUtil; - -/** Called only from RTG's Forge ICE pass, after RTG checks its snow-layers setting. */ -public final class RtgWeather { - private RtgWeather() { - } - - public static boolean snow(WorldUtil rtg, BlockPos position, boolean checkLight, World world) { - return WeatherHooks.generationSnow(world, position, checkLight, (w, p, light) -> rtg.canSnowAt(p, light)); - } -} diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/game/SurfaceTracker.java b/src/main/java/zone/moddev/mc/skysrealisticweather/game/SurfaceTracker.java index 7964a15..0aec18e 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/game/SurfaceTracker.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/game/SurfaceTracker.java @@ -51,7 +51,7 @@ boolean place(WorldServer world, BlockPos position, IBlockState proposed, int fl synchronized (this) { deposits.computeIfAbsent(chunk, unused -> new Int2ObjectOpenHashMap<>()).put(localIndex(position), deposit); } - chunk.setChunkModified(); + chunk.markDirty(); } return true; } @@ -89,7 +89,7 @@ public synchronized void changed(Chunk chunk, BlockPos position) { Int2ObjectOpenHashMap entries = deposits.get(chunk); if (entries != null && entries.remove(localIndex(position)) != null) { if (entries.isEmpty()) deposits.remove(chunk); - chunk.setChunkModified(); + chunk.markDirty(); } } @@ -105,7 +105,7 @@ public synchronized void load(ChunkDataEvent.Load event) { if (!row.hasKey("position", 4) || !row.hasKey("deposit", 1)) continue; BlockPos position = BlockPos.fromLong(row.getLong("position")); int type = row.getByte("deposit"); - if (position.getX() >> 4 != chunk.xPosition || position.getZ() >> 4 != chunk.zPosition + if (position.getX() >> 4 != chunk.x || position.getZ() >> 4 != chunk.z || position.getY() < 0 || position.getY() >= 256 || type < 0 || type >= Deposit.ALL.length) continue; Deposit deposit = Deposit.ALL[type]; if (chunk.getBlockState(position) == deposit.placed()) entries.put(localIndex(position), deposit); @@ -121,8 +121,8 @@ public synchronized void save(ChunkDataEvent.Save event) { NBTTagList list = new NBTTagList(); for (Int2ObjectMap.Entry entry : entries.int2ObjectEntrySet()) { int index = entry.getIntKey(); - BlockPos position = new BlockPos((chunk.xPosition << 4) + (index & 15), index >> 8, - (chunk.zPosition << 4) + (index >> 4 & 15)); + BlockPos position = new BlockPos((chunk.x << 4) + (index & 15), index >> 8, + (chunk.z << 4) + (index >> 4 & 15)); NBTTagCompound row = new NBTTagCompound(); row.setLong("position", position.toLong()); row.setByte("deposit", (byte) entry.getValue().ordinal()); diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/game/TemperatureZones.java b/src/main/java/zone/moddev/mc/skysrealisticweather/game/TemperatureZones.java index 9e7bded..8a80c08 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/game/TemperatureZones.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/game/TemperatureZones.java @@ -133,11 +133,11 @@ public static void furnaceTick(TileEntityFurnace furnace) { } @SubscribeEvent public void watch(ChunkWatchEvent.Watch event) { World world=event.getPlayer().world;State state=state(world,true);ChunkPos p=event.getChunk(); - WeatherMod.NETWORK.sendTo(new TemperatureZoneMessage(world.provider.getDimension(),p.chunkXPos,p.chunkZPos,state.enabled,state.index.snapshot(p.chunkXPos,p.chunkZPos)),event.getPlayer()); + WeatherMod.NETWORK.sendTo(new TemperatureZoneMessage(world.provider.getDimension(),p.x,p.z,state.enabled,state.index.snapshot(p.x,p.z)),event.getPlayer()); } @SubscribeEvent public void unwatch(ChunkWatchEvent.UnWatch event) { World world=event.getPlayer().world;State state=state(world,false);ChunkPos p=event.getChunk(); - WeatherMod.NETWORK.sendTo(new TemperatureZoneMessage(world.provider.getDimension(),p.chunkXPos,p.chunkZPos,state==null?WeatherConfiguration.heatingEnabled():state.enabled,Collections.emptyList()),event.getPlayer()); + WeatherMod.NETWORK.sendTo(new TemperatureZoneMessage(world.provider.getDimension(),p.x,p.z,state==null?WeatherConfiguration.heatingEnabled():state.enabled,Collections.emptyList()),event.getPlayer()); } public static void receive(World world,TemperatureZoneMessage message) { if(!world.isRemote||world.provider.getDimension()!=message.dimension)return; diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/game/WeatherState.java b/src/main/java/zone/moddev/mc/skysrealisticweather/game/WeatherState.java index 37ba1ec..c1d745e 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/game/WeatherState.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/game/WeatherState.java @@ -27,7 +27,7 @@ private WeatherState() { public static boolean supports(World world) { return world != null && world.provider.getDimension() == 0 && world.provider.isSurfaceWorld() - && !world.provider.hasNoSky() && world.getWorldType() != WorldType.DEBUG_WORLD; + && world.provider.hasSkyLight() && world.getWorldType() != WorldType.DEBUG_ALL_BLOCK_STATES; } public static Frame frame(World world) { diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/instrument/Thermometer.java b/src/main/java/zone/moddev/mc/skysrealisticweather/instrument/Thermometer.java index 919954d..5bf9e63 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/instrument/Thermometer.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/instrument/Thermometer.java @@ -39,7 +39,7 @@ public static void register() { public static boolean heldBy(EntityLivingBase entity) { return entity != null && (isThermometer(entity.getHeldItemMainhand()) || isThermometer(entity.getHeldItemOffhand())); } - private static boolean isThermometer(ItemStack stack) { return stack != null && stack.stackSize > 0 && stack.getItem() == Item.getItemFromBlock(BLOCK); } + private static boolean isThermometer(ItemStack stack) { return stack != null && !stack.isEmpty() && stack.getItem() == Item.getItemFromBlock(BLOCK); } public static OptionalDouble temperature(World world, BlockPos pos) { if (world == null || !world.isBlockLoaded(pos, false)) return OptionalDouble.empty(); OptionalDouble weather = WeatherApi.getLocalTemperature(world, pos); @@ -56,7 +56,7 @@ private static void read(World world, BlockPos pos, EntityPlayer player) { if (value.isPresent()) player.sendMessage(new TextComponentString("Temperature: " + TemperatureDisplay.forSender(player).format((float) value.getAsDouble()))); } @Override public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, - ItemStack held, EnumFacing side, float x, float y, float z) { + EnumFacing side, float x, float y, float z) { read(world, pos, player); return true; } private static boolean support(World world, BlockPos pos, EnumFacing towardSupport) { @@ -76,7 +76,7 @@ private static boolean support(World world, BlockPos pos, EnumFacing towardSuppo return getDefaultState().withProperty(WALL, side.getAxis().isHorizontal()) .withProperty(FACING, side.getAxis().isHorizontal() ? side : placer.getHorizontalFacing().getOpposite()); } - @Override public void neighborChanged(IBlockState state, World world, BlockPos pos, Block neighbor) { + @Override public void neighborChanged(IBlockState state, World world, BlockPos pos, Block neighbor, BlockPos fromPos) { EnumFacing direction = state.getValue(WALL) ? state.getValue(FACING).getOpposite() : EnumFacing.DOWN; if (!support(world, pos, direction)) { dropBlockAsItem(world, pos, state, 0); world.setBlockToAir(pos); } } @@ -88,7 +88,7 @@ private static boolean support(World world, BlockPos pos, EnumFacing towardSuppo @Override public boolean isFullCube(IBlockState state) { return false; } @net.minecraftforge.fml.relauncher.SideOnly(net.minecraftforge.fml.relauncher.Side.CLIENT) @Override public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.CUTOUT; } - @Override public AxisAlignedBB getCollisionBoundingBox(IBlockState state, World world, BlockPos pos) { return NULL_AABB; } + @Override public AxisAlignedBB getCollisionBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) { return NULL_AABB; } @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) { EnumFacing facing = state.getValue(FACING); if (!state.getValue(WALL)) return facing.getAxis() == EnumFacing.Axis.Z @@ -102,9 +102,9 @@ private static boolean support(World world, BlockPos pos, EnumFacing towardSuppo } private static final class ThermometerItem extends ItemBlock { ThermometerItem() { super(BLOCK); } - @Override public ActionResult onItemRightClick(ItemStack stack, World world, EntityPlayer player, EnumHand hand) { + @Override public ActionResult onItemRightClick(World world, EntityPlayer player, EnumHand hand) { read(world, zone.moddev.mc.skysrealisticweather.game.ClimateReadout.eyes(player), player); - return new ActionResult<>(EnumActionResult.SUCCESS, stack); + return new ActionResult<>(EnumActionResult.SUCCESS, player.getHeldItem(hand)); } } } diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/network/TemperaturePreferenceMessage.java b/src/main/java/zone/moddev/mc/skysrealisticweather/network/TemperaturePreferenceMessage.java index 17c3674..0eb50e3 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/network/TemperaturePreferenceMessage.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/network/TemperaturePreferenceMessage.java @@ -23,7 +23,7 @@ public void apply(EntityPlayerMP player) { } public static final class Handler implements IMessageHandler { @Override public IMessage onMessage(TemperaturePreferenceMessage message, MessageContext context) { - EntityPlayerMP player = context.getServerHandler().playerEntity; + EntityPlayerMP player = context.getServerHandler().player; player.getServerWorld().addScheduledTask(() -> message.apply(player)); return null; } diff --git a/src/main/resources/assets/skysrealisticweather/lang/en_US.lang b/src/main/resources/assets/skysrealisticweather/lang/en_us.lang similarity index 100% rename from src/main/resources/assets/skysrealisticweather/lang/en_US.lang rename to src/main/resources/assets/skysrealisticweather/lang/en_us.lang diff --git a/src/test/java/zone/moddev/mc/skysrealisticweather/core/GenerationHooksTest.java b/src/test/java/zone/moddev/mc/skysrealisticweather/core/GenerationHooksTest.java new file mode 100644 index 0000000..1abb5de --- /dev/null +++ b/src/test/java/zone/moddev/mc/skysrealisticweather/core/GenerationHooksTest.java @@ -0,0 +1,39 @@ +package zone.moddev.mc.skysrealisticweather.core; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import org.junit.jupiter.api.Test; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.tree.*; +import org.objectweb.asm.tree.analysis.Analyzer; +import org.objectweb.asm.tree.analysis.BasicVerifier; +import static org.junit.jupiter.api.Assertions.*; + +final class GenerationHooksTest { + @Test + void nativeOverworldPopulationUsesSeasonalSnowIceAndOwnership() throws Exception { + String target = "net.minecraft.world.gen.ChunkProviderOverworld"; + byte[] original; + try (InputStream stream = getClass().getResourceAsStream("/"+target.replace('.', '/')+".class")) { + assertNotNull(stream); + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] buffer = new byte[8192]; int count; + while ((count = stream.read(buffer)) >= 0) bytes.write(buffer, 0, count); + original = bytes.toByteArray(); + } + byte[] patched = new WeatherTransformer().transform(null, target, original); + ClassNode type = new ClassNode(); new ClassReader(patched).accept(type, 0); + MethodNode population = type.methods.stream().filter(m -> m.name.equals("populate")).findFirst().get(); + int freeze = 0, snow = 0, deposits = 0; + for (AbstractInsnNode instruction : population.instructions.toArray()) { + if (!(instruction instanceof MethodInsnNode)) continue; + MethodInsnNode call = (MethodInsnNode) instruction; + if (!call.owner.equals("zone/moddev/mc/skysrealisticweather/game/WeatherHooks")) continue; + if (call.name.equals("generationFreeze")) freeze++; + if (call.name.equals("generationSnow")) snow++; + if (call.name.equals("placeGeneratedDeposit")) deposits++; + } + assertEquals(1, freeze); assertEquals(1, snow); assertEquals(2, deposits); + new Analyzer<>(new BasicVerifier()).analyze(type.name, population); + } +} From 6d12d81d2b6b5443f32478f0a1ef376a4e047eaf Mon Sep 17 00:00:00 2001 From: JohnBraham Date: Fri, 27 Nov 2026 14:01:32 +0000 Subject: [PATCH 2/9] Qualify 1.11.2 multiplayer and seasonal terrain generation --- README.md | 4 +- build.gradle | 24 + docs/BIOME_COMPATIBILITY.md | 12 +- docs/BUILDING.md | 78 ++- docs/FARMING.md | 4 + docs/PERFORMANCE_1_11_2.md | 145 ++++++ docs/PORTING_1_11_2.md | 46 +- scripts/Analyze-GenerationPerformance.py | 46 ++ scripts/Calibrate-GenerationBaseline.py | 50 ++ scripts/Run-GenerationPerformance.py | 149 ++++++ scripts/Run-MultiplayerChecks.py | 78 +++ scripts/Run-RuntimeChecks.py | 4 +- scripts/verification_clients.py | 60 +++ .../game/PlantGrowthProbe.java | 30 ++ .../verify/ClientProbe.java | 5 + .../verify/TemperatureClientProbe.java | 74 +++ .../verify/TemperatureNetworkProbe.java | 103 ++++ .../verify/WeatherProbe.java | 1 + .../verify/control/ControlClient.java | 29 ++ .../verify/control/ControlProbe.java | 65 +++ .../verify/performance/DepositVeto.java | 20 + .../performance/OtgPopulationCounter.java | 21 + .../performance/WorldgenPerformanceProbe.java | 448 ++++++++++++++++++ .../core/WeatherTransformer.java | 12 + .../game/PlantGrowthHooks.java | 16 + .../core/GenerationHooksTest.java | 18 + 26 files changed, 1523 insertions(+), 19 deletions(-) create mode 100644 docs/PERFORMANCE_1_11_2.md create mode 100644 scripts/Analyze-GenerationPerformance.py create mode 100644 scripts/Calibrate-GenerationBaseline.py create mode 100644 scripts/Run-GenerationPerformance.py create mode 100644 scripts/Run-MultiplayerChecks.py create mode 100644 scripts/verification_clients.py create mode 100644 src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/TemperatureClientProbe.java create mode 100644 src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/TemperatureNetworkProbe.java create mode 100644 src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/control/ControlClient.java create mode 100644 src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/control/ControlProbe.java create mode 100644 src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/performance/DepositVeto.java create mode 100644 src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/performance/OtgPopulationCounter.java create mode 100644 src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/performance/WorldgenPerformanceProbe.java diff --git a/README.md b/README.md index 7be8f6f..4b1a46a 100644 --- a/README.md +++ b/README.md @@ -24,10 +24,12 @@ Storm Coast and Two Winters. The standard year lasts 365 Minecraft days. Day/night temperature changes and independent cold spells make weather transitions more noticeable. The British Isles preset represents northern British lowlands, with snowier uplands. See the [climate balance and test -assumptions](docs/TESTING_ASSUMPTIONS.md). +assumptions](docs/TESTING_ASSUMPTIONS.md). The local 1.11.2 candidate also has +[two-client multiplayer and whole-chunk performance results](docs/PERFORMANCE_1_11_2.md). Natural plant growth also follows local temperature. Cool-weather crops, warm crops and fruit use editable profiles; fertiliser keeps its native behaviour. +Terrain providers can still generate their normal forests and parks in winter. Optional integrations cover HarvestCraft, Mystical Agriculture and Forestry. Hover seeds, saplings and crops to see preferred temperatures and whether the current local temperature suits them. Celsius is the default; diff --git a/build.gradle b/build.gradle index a516454..9fe5a15 100644 --- a/build.gradle +++ b/build.gradle @@ -240,3 +240,27 @@ tasks.register('prepareRuntimeProbe') { receipt.get().asFile.setText(groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(result)), 'UTF-8') } } + + +def performanceProbe = tasks.register('runtimePerformanceProbe', Jar) { + archiveFileName = 'weather-performance-probe-mapped.jar' + destinationDirectory = layout.buildDirectory.dir('verification/probe') + from(sourceSets.integrationTest.output) { include 'zone/moddev/mc/skysrealisticweather/verify/performance/**' } +} +def packagedPerformanceProbe = renamer.classes(performanceProbe) { + map.from minecraft.dependency.toSrgFile + output = layout.buildDirectory.file('verification/probe/weather-performance-probe.jar') +} +tasks.register('preparePerformanceProbe') { dependsOn packagedPerformanceProbe, tasks.named('prepareRuntimeProbe') } + + +def controlProbe = tasks.register('runtimeControlProbe', Jar) { + archiveFileName = 'weather-control-probe-mapped.jar' + destinationDirectory = layout.buildDirectory.dir('verification/probe') + from(sourceSets.integrationTest.output) { include 'zone/moddev/mc/skysrealisticweather/verify/control/**' } +} +def packagedControlProbe = renamer.classes(controlProbe) { + map.from minecraft.dependency.toSrgFile + output = layout.buildDirectory.file('verification/probe/weather-control-probe.jar') +} +tasks.register('prepareControlProbe') { dependsOn packagedControlProbe, tasks.named('prepareRuntimeProbe') } diff --git a/docs/BIOME_COMPATIBILITY.md b/docs/BIOME_COMPATIBILITY.md index 99368e2..73e85d8 100644 --- a/docs/BIOME_COMPATIBILITY.md +++ b/docs/BIOME_COMPATIBILITY.md @@ -21,7 +21,7 @@ folder; 1.10.2 counts and performance figures are not reused. | Profile | Snow columns in fresh winter terrain | Snow columns in fresh summer terrain | | --- | ---: | ---: | -| Biomes O' Plenty | 218 | 0 | +| Biomes O' Plenty | 229 | 0 | | AbyssalCraft | 212 | 0 | | Vampirism | 256 | 0 | | GeographiCraft | 236 | 0 | @@ -31,6 +31,16 @@ folder; 1.10.2 counts and performance figures are not reused. Counts refer to the target biome within a 16 × 16 population area, not the whole world. Client visuals and whole-chunk performance are separate checks. +BOP's native decoration can vary across fresh JVMs, so its exact cover count +can also vary. The table records the corrected candidate's fresh recheck. +The repeated with/without-weather timings, terrain fingerprints and explicit +comparison limits are in [multiplayer and performance results](PERFORMANCE_1_11_2.md). + +Terrain providers retain native tree generation during their population +callback, including Lost Cities' forced sapling growth for parks. Subsequent +natural growth uses local temperature as usual. Seasonal cover may influence +later neighbouring decoration; it does not change the generator's base biome +selection or pre-population height map in the tested comparisons. ## Native exceptions and ownership diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 940666d..2380f3a 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -119,12 +119,88 @@ They isolate seasonal behaviour rather than simulating full-server physics. Farming endurance uses seeded natural crop callbacks with valid light and soil. Neither establishes real meteorological accuracy or full-server performance. +## Multiplayer and generation performance + +```text +gradlew prepareRuntimeProbe prepareControlProbe preparePerformanceProbe +python scripts/Run-MultiplayerChecks.py --case calendar --output build/verification/multiplayer-performance-1112/ +python scripts/Run-MultiplayerChecks.py --case biome --output build/verification/multiplayer-performance-1112/ +python scripts/Run-MultiplayerChecks.py --case admin --output build/verification/multiplayer-performance-1112/ +python scripts/Run-MultiplayerChecks.py --case thermal --output build/verification/multiplayer-performance-1112/ +python scripts/Run-MultiplayerChecks.py --case control --output build/verification/multiplayer-performance-1112/ +python scripts/Run-MultiplayerChecks.py --case control --control-weather --output build/verification/multiplayer-performance-1112/ +python scripts/Run-GenerationPerformance.py --rounds 3 --bop-calibration build/verification/.json --output build/verification/multiplayer-performance-1112/ +``` + +The Windows multiplayer runner opens two real packaged clients on a separate +desktop and never switches input to it. Clients are muted, capped at 10 FPS and +share one logical CPU; the dedicated server uses another. All processes run at +BelowNormal priority and use fresh disposable worlds. The client runtime must +contain the pinned Forge installation, Minecraft assets and Windows natives. +`WEATHER_CLIENT_RUNTIME` and `WEATHER_SERVER_RUNTIME` can override the installed +runtime locations in `scripts/verification_clients.py`. + +Create the BOP calibration receipt with the controls below before running the +four-provider generation comparison. + +The calendar fixture has a deterministic test-only winter storm; normal presets +are unchanged. Biome and thermal cases keep Per Biome Climate. The thermal case +uses ordinary network traffic to test personal display units, instruments, crop +suitability, heat changes, watched chunks and reconnects. The two control variants +use the same test jar, weather, world and two-player workload. After 120 warm-up +ticks with both players present, they record 600 complete server-tick intervals. +Repeat in opposite order to compare CPU time and tick duration. + +Generation uses vanilla terrain, Biomes O' Plenty, Biome Bundle/OTG and Lost +Cities/CompatLayer, one server at a time on one logical CPU. Every process warms +576 chunk requests before timing separate 784-request winter and summer regions. +Three matched repeats counterbalance mod presence and seasonal order. Both +variants use the same seed and rain; the weather variant uses fresh Per Biome +Climate defaults. The world's auxiliary RNG is seeded before each region. +Population coverage and named-state fingerprints are checked outside timing, +normalizing seasonal snow layers and source-water ice. Lightweight biome and +height-map snapshots are captured before population, identically in both variants. +Measurements exclude chunk saving and are not client FPS or a full modpack benchmark. Preserve +every failed receipt and use fresh output directories for repeats. + +Biomes O' Plenty's weighted decorators can vary between fresh JVMs even without +weather. Establish that limitation with two identical controls before allowing +decoration variation in its comparisons; base biome and height-map equality +remains mandatory. Every other provider still requires full normalized block +equality. Keep the calibration receipt and original controls with the results. + +```text +python scripts/Run-GenerationPerformance.py --terrain bop --variant vanilla --rounds 1 --output build/verification/ +python scripts/Run-GenerationPerformance.py --terrain bop --variant vanilla --rounds 1 --output build/verification/ +python scripts/Calibrate-GenerationBaseline.py build/verification//bop-1-vanilla/result.json build/verification//bop-1-vanilla/result.json --output build/verification/.json +python scripts/Run-GenerationPerformance.py --bop-calibration build/verification/.json --output build/verification/ +python scripts/Run-GenerationPerformance.py --terrain vanilla --climate-mode UNIVERSAL --fixed-biome 1 --output build/verification/ +``` + +The last case uses fixed Plains terrain and Burlington's winter to ensure dense +snow/ice placement is measured in addition to the default climate regions. +Physical cover can affect later neighbouring decoration, so this stress case +may fail full post-population equality even though base terrain matches. To +isolate the cause, repeat one pair with `--veto-deposits --rounds 1`. It must +restore complete normalized block equality while actually vetoing deposits. +Then record the diagnostic and pass it only to the same cold-stress workload: + +```text +python scripts/Calibrate-GenerationBaseline.py --cover-veto build/verification/ --output build/verification/.json +python scripts/Run-GenerationPerformance.py --terrain vanilla --climate-mode UNIVERSAL --fixed-biome 1 --cover-diagnostic build/verification/.json --output build/verification/ +python scripts/Analyze-GenerationPerformance.py build/verification/ --output build/verification/.json +``` + +The resulting cold comparison still requires matching base biomes and height +maps and exact summer blocks. Its winter timings include the real population +effects of snow and ice; they are not an equal-decoration microbenchmark. + ## Acceptance scope Unit tests verify native renderer and Overworld generation bytecode as well as climate, network and API contracts. Packaged servers cover native hooks, crops, commands, temperature zones, crafting and save/reload. The distant-render probe can draw through an offscreen LWJGL Pbuffer without a game window. These checks -do not replace manual client visuals, live multiplayer testing or testing a +do not replace manual client gameplay, visual acceptance or testing a particular modpack. Old 1.10.2 timing and gameplay receipts do not qualify this version. See [current port evidence and limitations](PORTING_1_11_2.md). diff --git a/docs/FARMING.md b/docs/FARMING.md index 3f568be..8139112 100644 --- a/docs/FARMING.md +++ b/docs/FARMING.md @@ -9,6 +9,10 @@ still apply. Bonemeal and direct fertiliser keep their native behaviour and eligibility. Machines that invoke the ordinary natural-growth path follow the climate rules. +Terrain generation keeps native plant and tree generation, including generators +that grow saplings to create parks or forests. These generated trees can appear +in winter; later natural growth follows the local climate as usual. + Registered [temperature zones](TEMPERATURE_ZONES.md) and burning vanilla furnace zones can override that temperature. The same effective temperature reaches crop tooltips, thermometers and the compact HUD. F3 and `/skyweather climate` diff --git a/docs/PERFORMANCE_1_11_2.md b/docs/PERFORMANCE_1_11_2.md new file mode 100644 index 0000000..294d303 --- /dev/null +++ b/docs/PERFORMANCE_1_11_2.md @@ -0,0 +1,145 @@ +# Minecraft 1.11.2 multiplayer and generation checks + +The local **0.1.21.111021** candidate passed the two-client scenarios and the +repeated generation comparisons on 27 November 2026. There was no sustained +server-thread CPU penalty in the default-climate sample beyond Biomes O' +Plenty's small winter increase. BOP's winter elapsed time increased more than +its CPU time, so this is not a claim of zero overhead. + +These results apply to Forge **13.20.1.2588** and the pinned builds below. The +candidate remains local and unpublished; manual gameplay and JEI client +acceptance remain separate. See [port status](PORTING_1_11_2.md) and +[reproduction instructions](BUILDING.md). + +## Whole-chunk generation + +Each entry is the median of three matched with/without-weather comparisons. +Percentages are calculated within each pair before taking the median. Negative +values mean less measured time in this sample, not a promised speed improvement. + +| Terrain provider | Winter CPU change | Summer CPU change | Winter elapsed change | Summer elapsed change | +| --- | ---: | ---: | ---: | ---: | +| Vanilla terrain, Forge only | -2.22% | -0.75% | +0.01% | -4.68% | +| Biomes O' Plenty 6.2.0.2319 | +0.26% | -2.11% | +7.44% | -2.33% | +| OTG v9 + Biome Bundle v5.1 | -0.67% | 0.00% | +1.74% | -4.41% | +| The Lost Cities 1.0.2 + CompatLayer 0.3.1 | -3.61% | -3.78% | -1.71% | -3.26% | + +The individual paired CPU changes ranged from -7.04% to +4.72% across the +default-climate cases. BOP winter pairs ranged from -0.28% to +1.41% CPU. +Its independently calculated median elapsed cost was **8.61 to 9.21 ms per +chunk request**; the median per-run 95th percentile was **26.92 to 28.71 ms**. +These small samples on a computer still available for other work cannot +establish a statistically significant speedup or a universal upper bound. + +The comparison measures the complete native chunk request, including terrain, +population and weather integration. Each fresh JVM warms 576 requests, then +times 784 winter and 784 summer requests in separate regions. Mod presence and +seasonal order are counterbalanced across three rounds. This gives 24 JVMs and +37,632 measured requests for the default **Per Biome Climate** comparison. +Both variants use seed 123948, rain, identical provider jars and a seeded +auxiliary world RNG. The weather variant uses a fresh default climate library. +The production weather frame is advanced and its date checked before timing. +Population coverage is asserted, including OTG's own population callback. + +Server-thread CPU time is less sensitive to other desktop activity than elapsed +time; both are retained. The host was Windows 11 on a Ryzen 9 9900X. Each server +ran alone at BelowNormal priority on one logical CPU, with Java 8, Serial GC +and a 1.5 GiB maximum heap. Fingerprints and cover counts run outside timing; +matching biome/height-map snapshots add the same small cost to both variants. +Chunk saving is excluded. These are not FPS, disk throughput, arbitrary-seed or +full-modpack measurements. RTG has no verified 1.11.2 target in this set. + +The chosen vanilla and Lost Cities regions remained warm enough to produce no +seasonal cover in the timed default-climate sample. BOP's winter median was +84,231 snowy columns and 5,276 ice columns; OTG/Biome Bundle produced 61 and +2,292 respectively. The additional vanilla case below tests dense cold cover; +it does not establish every provider's worst-case winter cost. + +## Snow-heavy stress case + +A further six JVMs repeat the vanilla comparison with fixed Plains terrain and +Universal Burlington climate at normal strength. Each winter run produces +**94,572 snowy columns and 16,931 ice columns**; summer produces neither. This +adds 9,408 measured requests, for **47,040 in the two final campaigns**. + +Winter's median paired CPU change is **-7.89%**, and elapsed change **-0.48%**; +summer's changes are **-11.29%** and **-9.61%**. This end-to-end workload includes +the downstream effects of actual snow and ice on neighbouring decoration. +It must not be interpreted as an equal-decoration microbenchmark or evidence +that adding weather always makes generation faster. + +## Terrain correctness and the bug found + +The tests found that Lost Cities grows park trees through native sapling +callbacks during population. Climate growth rules could stop those trees, +leave saplings behind and change subsequent random-number consumption. The +earlier failing comparison showed roughly 15–19% extra CPU cost. + +The corrected build wraps the terrain provider's population callback in an +exception-safe, nested world scope. Natural-growth gates allow native generator +growth inside that scope and resume climate checks afterwards. A regression +test failed before the fix and passes now, including nested calls and exception +cleanup. No third-party jar was changed. + +Base biomes and pre-population height maps match in every final pair. Full +named-block-state comparisons, normalizing seasonal snow layers and source-water +ice, match for vanilla, OTG/Biome Bundle and Lost Cities in the default campaign. +Two explicit limits are recorded: + +- BOP's weighted decorations vary between fresh JVMs even without weather. + Two identical weather-free controls reproduced that variation with identical + base terrain. Its timing comparison therefore requires matching base biomes + and height maps, but does not claim identical trees and plants. +- Dense winter cover can affect later neighbouring population. The cold stress + case initially failed full normalized block equality. A diagnostic using the + public surface event vetoed 250,080 placements across warm-up and timed phases + and restored complete equality. The final stress comparison requires the same + base terrain and exact summer blocks, while explicitly recording winter cover + feedback. The original failure remains retained. + +Arctic, BOP glacier and Cold Taiga fixtures pass on the corrected candidate. +All seven biome/generator compatibility profiles also pass fresh winter/summer +checks. Native protected-cover rules were not changed. + +## Two-client multiplayer + +Two actual packaged Forge clients connected to a dedicated server and passed: + +- A 365-day calendar, season/storm changes, manual weather precedence and sleep. +- Server biome-to-climate mapping and each client's local weather response. +- Creative operator versus guest permissions, controller placement and live GUI + changes, including discarding edits. +- Personal Celsius/Fahrenheit displays, late-join temperature zones, crop + suitability tooltips, held and placed thermometers, torch/furnace falloff, + extinguishing/removing heaters, distant watched chunks, unloading and reconnects. + +A matched two-player control pair measured 600 complete server ticks after +120 warm-up ticks. Mean elapsed tick time was **0.755 ms without weather** and +**0.786 ms with it**, an increase of **0.031 ms**. The 95th percentile was +**1.874 to 2.329 ms**, against Minecraft's 50 ms tick budget. This is one short +pair in a quiet flat world, not a loaded-server capacity test. Windows CPU +timer granularity makes its small CPU difference unsuitable for a speed claim. + +Clients used a separate, non-input Windows desktop that was never switched to, +muted audio, a 10 FPS cap and one shared logical CPU. No computer-control session +or foreground game window was needed. All worlds were fresh disposable fixtures; +no player world was copied or launched. All test clients and servers were stopped. + +## Candidate and retained evidence + +The final build passes **57 unit tests**, **571,778 combined farming checks** +and process reload. Only `WeatherTransformer` and `PlantGrowthHooks` changed +in the release jar after the initial port qualification. Climate tuning, +renderer, public API, recipes and heating implementation are unchanged. + +Main jar SHA-256: + +```text +3b937e2d6da0d8802d165e3f564223a765e735c9984f3153d97a071d32db3779 +``` + +Local raw logs, CSVs, source snapshots, calibration diagnostics, failed attempts +and artifact-bound receipts stay under the ignored +`build/verification/multiplayer-performance-1112` directory. Its `RESULT.md` +indexes the evidence. Test output, disposable worlds and probe jars are not +release contents or tracked repository files. diff --git a/docs/PORTING_1_11_2.md b/docs/PORTING_1_11_2.md index 9f263b2..a11267d 100644 --- a/docs/PORTING_1_11_2.md +++ b/docs/PORTING_1_11_2.md @@ -61,35 +61,51 @@ this port's qualification set. ## Verification and acceptance -The local build passes **56 unit tests**, including native renderer and generation -bytecode verification. The combined farming suite passes **571,769 contracts** -and process reload; two-year farming simulations cover all 28 presets on two -independent seeds. Core, individual and combined optional bridge profiles pass, -as do disabled bridges, mercury crafting, heaters, temperature zones, invalid +The corrected local build passes **57 unit tests**, including native renderer +and generation bytecode verification. The combined farming suite passes +**571,778 contracts** and process reload. The initial port's two-year farming +simulations cover all 28 presets on two independent seeds. Core, individual and +combined optional bridge profiles pass, as do disabled bridges, mercury +crafting, heaters, temperature zones, invalid climate fallback, a plant/item stress matrix and native save/reload. -Seven biome/generator profiles pass winter/summer generation checks. Separate -fixtures verify Arctic and glacier native cover, Cold Taiga seasonal behaviour, +Seven biome/generator profiles pass fresh winter/summer generation checks on the +corrected candidate. Separate fixtures recheck Arctic and glacier native cover +and Cold Taiga seasonal behaviour. Initial port fixtures also verify Forge ICE denial, clear weather, seasonal ownership and thaw after reload. Three Java API examples compile against the matching 1.11.2 API. Distant weather passes native sampling and six offscreen rendering configurations. -The longer weather run uses 20-year sweeps on two independent seeds, five-year -strength extremes and six native years per climate (one warm-up, five scored). +The initial port's longer weather run uses 20-year sweeps on two independent +seeds, five-year strength extremes and six native years per climate (one warm-up, +five scored). It completes without crashes and passes **335 of 336 balance checks**. British Isles (`oxford`) averages **35.025 snow dates/year** against a design band of 18–35: one extra snow date across 40 simulated years. This small upper-band finding is retained, and no climate values or acceptance thresholds were changed for the port. The shorter pilot's three low-band findings are also preserved; they do not recur in the longer sample. Statistical qualification is therefore -not reported as an unqualified pass. +not reported as an unqualified pass. The climate engine and tuning are unchanged +by the subsequent population-scope correction; this long sample was not rerun. + +Two real packaged clients now pass season/storm/sleep, server biome mapping, +admin permissions and UI, personal display units, thermometers, crop tooltips, +temperature-zone synchronization, heaters, chunk watching and reconnect checks. +Three paired whole-chunk repeats compare with and without weather for vanilla, +Biomes O' Plenty, OTG/Biome Bundle and Lost Cities; a further six JVMs exercise +dense winter snow and ice. See [multiplayer and performance results](PERFORMANCE_1_11_2.md) +for timings, the Lost Cities park-tree fix, BOP's native decoration variability +and the isolated downstream effects of winter cover. Local checks and their candidate hashes are retained under -`build/verification/port-1.11.2`. See `RESULT.md` there for final receipts, -including preserved unsuccessful port attempts. [Build instructions](BUILDING.md) +`build/verification/port-1.11.2` for initial qualification and +`build/verification/multiplayer-performance-1112` for the corrected candidate. +See `RESULT.md` and artifact-bound receipts in each, including preserved +unsuccessful attempts. [Build instructions](BUILDING.md) explain how to repeat the checks with fresh disposable worlds. -The port is local and unpublished. Manual client gameplay, visual acceptance, -live two-client multiplayer and a new whole-chunk performance baseline remain -separate acceptance work. Published 1.10.2 timings and the 1.10.2 Sylvester pack +The port is local and unpublished. Manual client gameplay and visual acceptance, +including JEI's client category, remain separate acceptance work. Automated +two-client multiplayer and the new whole-chunk baseline are complete for the +documented scenarios. Published 1.10.2 timings and the 1.10.2 Sylvester pack are not used to claim 1.11.2 coverage. No player world is launched by these tests. diff --git a/scripts/Analyze-GenerationPerformance.py b/scripts/Analyze-GenerationPerformance.py new file mode 100644 index 0000000..57ebc47 --- /dev/null +++ b/scripts/Analyze-GenerationPerformance.py @@ -0,0 +1,46 @@ +"""Summarize completed matched runs without treating timing noise as a speed guarantee.""" +from pathlib import Path +import argparse,json,statistics + +parser=argparse.ArgumentParser(description=__doc__) +parser.add_argument('results',type=Path,help='Campaign directory containing results.json') +parser.add_argument('--output',type=Path,required=True) +args=parser.parse_args() +data=json.loads((args.results/'results.json').read_text()) +assert data['passed'] and data['manifest']['variant'] is None,'A complete on/off campaign is required' +assert all(r['passed'] for r in data['runs']) +summary=[] +for terrain in sorted({r['terrain'] for r in data['runs']}): + for phase in ['winter','summer']: + pairs=[] + for number in range(1,data['manifest']['rounds']+1): + runs={r['profile']:r for r in data['runs'] if r['terrain']==terrain and r['round']==number} + assert set(runs)=={'vanilla','on'} + a,b=[next(row for row in runs[p]['rows'] if row['phase']==phase) for p in ['vanilla','on']] + assert a['requests']==b['requests'] + n=int(a['requests']);off=float(a['cpu_ms'])/n;on=float(b['cpu_ms'])/n + wall_off=float(a['wall_ms'])/n;wall_on=float(b['wall_ms'])/n + pairs.append(dict(round=number,baseline_cpu_ms_per_request=off,weather_cpu_ms_per_request=on, + change_percent=100*(on-off)/off,change_ms_per_request=on-off, + baseline_wall_ms_per_request=wall_off,weather_wall_ms_per_request=wall_on, + wall_change_percent=100*(wall_on-wall_off)/wall_off, + baseline_p95_ms=float(a['request_p95_ms']),weather_p95_ms=float(b['request_p95_ms']), + weather_snow_columns=int(b['snow_columns']),weather_ice_columns=int(b['ice_columns']))) + median=lambda key:statistics.median(r[key] for r in pairs) + summary.append(dict(terrain=terrain,phase=phase,rounds=len(pairs), + baseline_cpu_ms_per_request=median('baseline_cpu_ms_per_request'),weather_cpu_ms_per_request=median('weather_cpu_ms_per_request'), + median_paired_change_percent=median('change_percent'),median_paired_change_ms=median('change_ms_per_request'), + median_paired_wall_change_percent=median('wall_change_percent'), + paired_change_range_percent=[min(r['change_percent'] for r in pairs),max(r['change_percent'] for r in pairs)], + baseline_wall_ms_per_request=median('baseline_wall_ms_per_request'),weather_wall_ms_per_request=median('weather_wall_ms_per_request'), + baseline_request_p95_ms=median('baseline_p95_ms'),weather_request_p95_ms=median('weather_p95_ms'), + median_snow_columns=median('weather_snow_columns'),median_ice_columns=median('weather_ice_columns'),pairs=pairs)) +output=args.output.resolve() +assert not output.exists(),'Preserve earlier analysis' +output.parent.mkdir(parents=True,exist_ok=True) +output.write_text(json.dumps(dict(manifest=data['manifest'],summary=summary,parity_checks=data['parity_checks']),indent=2)) +print('| Terrain | Season | Baseline CPU ms/chunk | Weather CPU ms/chunk | Paired change | Pair range |') +print('| --- | --- | ---: | ---: | ---: | ---: |') +for r in summary: + low,high=r['paired_change_range_percent'] + print(f"| {r['terrain']} | {r['phase']} | {r['baseline_cpu_ms_per_request']:.3f} | {r['weather_cpu_ms_per_request']:.3f} | {r['median_paired_change_percent']:+.2f}% | {low:+.2f}% to {high:+.2f}% |") diff --git a/scripts/Calibrate-GenerationBaseline.py b/scripts/Calibrate-GenerationBaseline.py new file mode 100644 index 0000000..c767c80 --- /dev/null +++ b/scripts/Calibrate-GenerationBaseline.py @@ -0,0 +1,50 @@ +"""Record decoration variability only after two identical weather-free BOP replays prove it.""" +from pathlib import Path +import argparse,hashlib,json + +root=Path(__file__).resolve().parents[1] +parser=argparse.ArgumentParser(description=__doc__) +parser.add_argument('baseline_a',type=Path,nargs='?',help='First bop-1-vanilla/result.json') +parser.add_argument('baseline_b',type=Path,nargs='?',help='Independent repeat with identical arguments') +parser.add_argument('--cover-veto',type=Path,help='Completed fixed-Plains universal-climate veto campaign') +parser.add_argument('--output',type=Path,required=True) +args=parser.parse_args() +digest=lambda p:hashlib.sha256(p.read_bytes()).hexdigest() +if args.cover_veto: + path=(args.cover_veto/'results.json').resolve();data=json.loads(path.read_text());m=data['manifest'] + assert path.is_relative_to(root/'build/verification') and data['passed'] and m['veto_deposits'] + assert m['config']=='UNIVERSAL' and m['fixed_biome']==1 and m['rounds']==1 and len(data['runs'])==2 + a,b=data['runs'];assert a['profile']=='vanilla' and b['profile']=='on' and b['vetoed_deposits']>0 + assert a['terrain']==b['terrain']=='vanilla' and a['terrain_parity']==b['terrain_parity'] + assert a['base_terrain_parity']==b['base_terrain_parity'] + receipt=dict(passed=True,main_sha256=m['main_sha256'],probe_sha256=m['probe_sha256'],terrain='vanilla', + climate_mode='UNIVERSAL',fixed_biome=1,seed=m['seed'],size=m['size'],warmup=m['warmup'], + vetoed_deposits=b['vetoed_deposits'],receipt_sha256={str(path.relative_to(root)):digest(path)}, + explanation='Cold climate queries preserve exact normalized block parity when seasonal surface placement is vetoed. ' + 'Physical winter cover can affect subsequent neighbouring decoration; base and summer parity remain mandatory.') + output=args.output.resolve();assert output.is_relative_to(root/'build/verification') and not output.exists() + output.parent.mkdir(parents=True,exist_ok=True);output.write_text(json.dumps(receipt,indent=2));print(output) + raise SystemExit(0) +assert args.baseline_a and args.baseline_b,'Supply two native BOP controls or a --cover-veto campaign' +paths=[args.baseline_a.resolve(),args.baseline_b.resolve()] +a,b=[json.loads(p.read_text()) for p in paths] +assert all(p.is_relative_to(root/'build/verification') for p in paths) +assert a['passed'] and b['passed'] and a['profile']==b['profile']=='vanilla' +assert a['terrain']==b['terrain']=='bop' and a['artifacts']==b['artifacts'] +assert a['command']==b['command'],'Calibration requires identical JVM and workload arguments' +assert not any(n.startswith('SkysRealisticWeather-') for n in a['artifacts']) +assert a['base_terrain_parity']==b['base_terrain_parity'],'Base biomes and height maps differ' +assert a['terrain_parity']!=b['terrain_parity'],'Native decoration variability was not demonstrated' +assert a['artifacts']['BoP.jar']==digest(root/'build/compatibility-mods/published/BoP.jar') +assert a['artifacts']['weather-performance-probe.jar']==digest(root/'build/verification/probe/weather-performance-probe.jar') +receipt=dict(passed=True,probe_sha256=a['artifacts']['weather-performance-probe.jar'],bop_sha256=a['artifacts']['BoP.jar'], + receipt_sha256={str(p.relative_to(root)):digest(p) for p in paths}, + base_biomes_and_heightmaps_equal=True,normalized_blocks_equal=False, + phase_equal={phase:a['terrain_parity'][phase]==b['terrain_parity'][phase] for phase in ['winter','summer']}, + explanation='Identical weather-free JVMs reproduce base biomes and height maps but differ after population. ' + 'The pinned BOP weighted generator uses an object-keyed HashMap; decoration equality is not a cross-JVM invariant.') +output=args.output.resolve() +assert output.is_relative_to(root/'build/verification') and not output.exists() +output.parent.mkdir(parents=True,exist_ok=True) +output.write_text(json.dumps(receipt,indent=2)) +print(output) diff --git a/scripts/Run-GenerationPerformance.py b/scripts/Run-GenerationPerformance.py new file mode 100644 index 0000000..26c0947 --- /dev/null +++ b/scripts/Run-GenerationPerformance.py @@ -0,0 +1,149 @@ +"""Compare whole native chunk generation in fresh, single-CPU packaged servers.""" +from pathlib import Path +import argparse, csv, ctypes, hashlib, io, json, os, re, shutil, socket, subprocess, time +from ctypes import wintypes + +root = Path(__file__).resolve().parents[1] +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('--output', type=Path, required=True) +parser.add_argument('--rounds', type=int, default=3) +parser.add_argument('--variant',choices=['vanilla','on'],help='A single-profile calibration, not an on/off comparison') +parser.add_argument('--size', type=int, default=28) +parser.add_argument('--warmup', type=int, default=24) +parser.add_argument('--climate-mode', choices=['PER_BIOME','UNIVERSAL'], default='PER_BIOME') +parser.add_argument('--fixed-biome', type=int, help='Controlled vanilla-only biome registry ID') +parser.add_argument('--cover-diagnostic',type=Path,help='Validated cold-cover isolation receipt') +parser.add_argument('--veto-deposits',action='store_true',help='Diagnostic only: cancel seasonal surface placements') +parser.add_argument('--bop-calibration',type=Path,help='Verified native baseline variability receipt') +parser.add_argument('--terrain', nargs='+', choices=['vanilla', 'bop', 'bundle', 'lost'], default=['vanilla', 'bop', 'bundle', 'lost']) +args = parser.parse_args() +assert args.rounds >= 1 and args.size >= 8 and args.warmup >= 8 +assert args.fixed_biome is None or args.terrain == ['vanilla'] and args.fixed_biome not in [8,9] +output = args.output.resolve() +assert output.is_relative_to(root/'build/verification') +output.mkdir(parents=True, exist_ok=False) +fixture = root/'build/verification/runtime-fixture' +build_receipt = json.loads((root/'build/verification/probe/probe-build.json').read_text()) +main = next(p for p in (root/'build/libs').glob('*.jar') if hashlib.sha256(p.read_bytes()).hexdigest() == build_receipt['main_sha256']) +probe = root/'build/verification/probe/weather-performance-probe.jar' +forge = 'forge-1.11.2-13.20.1.2588-universal.jar' +java = Path.home()/'.gradle/jdks/temurin-8-amd64-windows.2/bin/java.exe' +digest = lambda p: hashlib.sha256(p.read_bytes()).hexdigest() +cover_diagnostic=None +if args.cover_diagnostic: + cover_diagnostic=json.loads(args.cover_diagnostic.read_text()) + assert cover_diagnostic['passed'] and cover_diagnostic['main_sha256']==digest(main) and cover_diagnostic['probe_sha256']==digest(probe) + assert args.terrain==['vanilla'] and args.climate_mode=='UNIVERSAL' and args.fixed_biome==1 and not args.veto_deposits + assert args.size==cover_diagnostic['size'] and args.warmup==cover_diagnostic['warmup'] + for name,expected_hash in cover_diagnostic['receipt_sha256'].items():assert digest(root/name)==expected_hash +bop_calibration = None +if args.bop_calibration: + bop_calibration=json.loads(args.bop_calibration.read_text()) + assert bop_calibration['passed'] and bop_calibration['probe_sha256']==digest(probe) + assert bop_calibration['bop_sha256']==digest(root/'build/compatibility-mods/published/BoP.jar') + for name,expected_hash in bop_calibration['receipt_sha256'].items():assert digest(root/name)==expected_hash +cpu = min(20, (os.cpu_count() or 1)-1) +kernel = ctypes.WinDLL('kernel32', use_last_error=True) +kernel.SetProcessAffinityMask.argtypes = [wintypes.HANDLE, ctypes.c_size_t] +kernel.SetProcessAffinityMask.restype = wintypes.BOOL +profiles = dict(vanilla=('DEFAULT', '', []), bop=('BIOMESOP', 'biomesoplenty', ['BoP']), + bundle=('OTG', 'openterraingenerator', ['OTG', 'BiomeBundle']), + lost=('lostcities', 'lostcities', ['LostCities', 'CompatLayer'])) +fields = 'round terrain profile phase requests loaded populated wall_ms cpu_ms gc_count gc_ms request_p50_ms request_p95_ms request_p99_ms group16_p95_ms ice_p50_ms ice_p95_ms snow_columns ice_columns cover_fingerprint'.split() +manifest = dict(main_sha256=digest(main), probe_sha256=digest(probe), forge_sha256=digest(fixture/forge), + seed=123948, size=args.size, warmup=args.warmup, cpu=cpu, priority='BelowNormal', + heap='1536m', rounds=args.rounds, variant=args.variant,veto_deposits=args.veto_deposits, config=args.climate_mode, fixed_biome=args.fixed_biome, + method='one JVM at a time; counterbalanced on/off and seasonal order; server-thread CPU and wall timings') +manifest['cover_diagnostic_sha256']=digest(args.cover_diagnostic) if args.cover_diagnostic else None +manifest['bop_calibration_sha256']=digest(args.bop_calibration) if args.bop_calibration else None +inputs = output/'inputs'; inputs.mkdir() +for path in [Path(__file__), *list((root/'src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/performance').glob('*.java')), root/'build/verification/probe/probe-build.json']: + shutil.copy2(path, inputs/path.name) +if args.bop_calibration:shutil.copy2(args.bop_calibration,inputs/'bop-baseline-calibration.json') +if args.cover_diagnostic:shutil.copy2(args.cover_diagnostic,inputs/'cold-cover-diagnostic.json') +manifest['inputs_sha256'] = {p.name:digest(p) for p in inputs.iterdir()} +(output/'manifest.json').write_text(json.dumps(manifest, indent=2)) +all_rows = [] +receipts = [] +parity_checks=[] +complete = False +try: + for round_number in range(1, args.rounds+1): + for terrain_index, terrain in enumerate(args.terrain): + world_type, expected, mods = profiles[terrain] + if args.fixed_biome is not None:world_type='CUSTOMIZED' + variants = [args.variant] if args.variant else (['vanilla', 'on'] if (round_number+terrain_index)%2 else ['on', 'vanilla']) + for variant in variants: + directory = output/f'{terrain}-{round_number}-{variant}' + (directory/'mods').mkdir(parents=True) + for name in [forge, 'minecraft_server.1.11.2.jar', 'eula.txt', 'ops.json', 'banned-ips.json', 'banned-players.json', 'whitelist.json']: + shutil.copy2(fixture/name, directory/name) + quoted = lambda p: "'"+str(p).replace("'", "''")+"'" + subprocess.run(['powershell', '-NoProfile', '-Command', 'New-Item -ItemType Junction -Path '+quoted(directory/'libraries')+' -Target '+quoted((fixture/'libraries').resolve())+' | Out-Null'], check=True, creationflags=subprocess.CREATE_NO_WINDOW) + with socket.socket() as sock: + sock.bind(('127.0.0.1', 0)); port = sock.getsockname()[1] + level = 'Biome Bundle' if terrain == 'bundle' else 'world' + (directory/'server.properties').write_text(f'level-name={level}\nlevel-type={world_type}\nlevel-seed=123948\nserver-ip=127.0.0.1\nserver-port={port}\nonline-mode=false\nmax-tick-time=-1\nview-distance=3\nspawn-npcs=false\nspawn-monsters=false\nspawn-animals=false\ndifficulty=0\nenable-rcon=false\nsnooper-enabled=false\n') + if args.fixed_biome is not None: + selection=args.fixed_biome-2 if args.fixed_biome>=10 else args.fixed_biome + with (directory/'server.properties').open('a') as props:props.write('generator-settings='+json.dumps(dict(fixedBiome=selection))+'\n') + if variant=='on' and args.climate_mode=='UNIVERSAL': + (directory/'config').mkdir() + (directory/'config/skysrealisticweather.cfg').write_text('general {\n S:climateMode=UNIVERSAL\n S:activePreset=burlington\n}\n') + artifacts = [probe] + ([main] if variant == 'on' else []) + [root/'build/compatibility-mods/published'/(name+'.jar') for name in mods] + hashes = {p.name:digest(p) for p in artifacts} + assert digest(main) == manifest['main_sha256'] and digest(probe) == manifest['probe_sha256'] + for path in artifacts: + shutil.copy2(path, directory/'mods'/path.name) + command = [str(java), '-Xms128m', '-Xmx1536m', '-XX:+UseSerialGC', '-XX:ActiveProcessorCount=1', '-XX:CICompilerCount=2', + '-Dfile.encoding=UTF-8', '-Dperf.profile='+variant, '-Dperf.terrain='+terrain, + '-Dperf.worldType='+world_type, '-Dperf.expectedMod='+expected, '-Dperf.round='+str(round_number), + '-Dperf.reverse='+str(round_number%2 == 0).lower(), '-Dperf.fourBit=true', + '-Dperf.vetoDeposits='+str(args.veto_deposits).lower(),'-Dperf.size='+str(args.size), '-Dperf.warmup='+str(args.warmup), '-jar', forge, 'nogui'] + start = time.monotonic(); error = None + with (directory/'server.log').open('wb') as log: + process = subprocess.Popen(command, cwd=directory, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + creationflags=subprocess.CREATE_NO_WINDOW|subprocess.BELOW_NORMAL_PRIORITY_CLASS) + assert kernel.SetProcessAffinityMask(int(process._handle), 1<0 and int(cold['ice_columns'])>0,'Cold stress must exercise both deposits' + parity_checks.append(dict(terrain=terrain,round=round_number,biomes_and_heightmaps_equal=base_equal, + normalized_blocks_equal=full_equal,documented_native_decoration_variation=native_variation,isolated_winter_cover_feedback=cover_feedback)) + assert base_equal, 'Base terrain parity mismatch: '+terrain + if native_variation:print('NATIVE_BOP_DECORATION_VARIATION: baseline calibration applies; base biomes and height maps match',flush=True) + elif cover_feedback:print('ISOLATED_WINTER_COVER_FEEDBACK: veto diagnostic restores full parity; base and summer parity match',flush=True) + else:assert full_equal, 'Terrain parity mismatch: '+terrain + complete = True +finally: + with (output/'measurements.csv').open('w', newline='') as file: + writer = csv.DictWriter(file, fieldnames=fields); writer.writeheader(); writer.writerows(all_rows) + (output/'results.json').write_text(json.dumps(dict(manifest=manifest, runs=receipts, parity_checks=parity_checks,passed=complete), indent=2)) diff --git a/scripts/Run-MultiplayerChecks.py b/scripts/Run-MultiplayerChecks.py new file mode 100644 index 0000000..efb5ba2 --- /dev/null +++ b/scripts/Run-MultiplayerChecks.py @@ -0,0 +1,78 @@ +"""Run two packaged clients and a disposable server with no desktop focus changes.""" +from pathlib import Path +import ctypes as C,hashlib,json,os,shutil,socket,subprocess,time,argparse,uuid +from ctypes import wintypes as W +from verification_clients import Client,client_command,k,u +root=Path(__file__).resolve().parents[1];proof=root/'build/verification/multiplayer-performance-1112';h=lambda p:hashlib.sha256(p.read_bytes()).hexdigest() +p=argparse.ArgumentParser();p.add_argument('--case',choices=['calendar','biome','admin','thermal','control'],required=True);p.add_argument('--control-weather',action='store_true');p.add_argument('--output',type=Path,required=True);a=p.parse_args();out=a.output.resolve();assert out.is_relative_to(proof);out.mkdir(parents=True,exist_ok=False) +server=out/'server';(server/'mods').mkdir(parents=True);(server/'config').mkdir();fixture=root/'build/verification/runtime-fixture';forge='forge-1.11.2-13.20.1.2588-universal.jar' +with socket.socket() as sock:sock.bind(('127.0.0.1',0));port=sock.getsockname()[1] +for name in [forge,'minecraft_server.1.11.2.jar','eula.txt','ops.json','banned-ips.json','banned-players.json','whitelist.json']:shutil.copy2(fixture/name,server/name) +quote=lambda p:"'"+str(p).replace("'","''")+"'" +subprocess.run(['powershell','-NoProfile','-Command','New-Item -ItemType Junction -Path '+quote(server/'libraries')+' -Target '+quote((fixture/'libraries').resolve())+' | Out-Null'],check=True,creationflags=subprocess.CREATE_NO_WINDOW) +(server/'server.properties').write_text(f'level-name=world\nlevel-type=FLAT\nlevel-seed=123948\nserver-ip=127.0.0.1\nserver-port={port}\nonline-mode=false\nmax-tick-time=-1\nview-distance=3\nspawn-npcs=false\nspawn-monsters=false\nspawn-animals=false\ndifficulty=0\nenable-rcon=false\nsnooper-enabled=false\ngenerate-structures=false\nallow-flight=true\ngamemode='+('1' if a.case=='admin' else '0')+'\n') +if a.case=='thermal': + # Keep both watched-chunk test sites on solid ground at the same altitude. + with (server/'server.properties').open('a') as properties:properties.write('generator-settings=3;minecraft:bedrock,79*minecraft:dirt,minecraft:grass;1;\n') +offline=lambda name:str(uuid.UUID(bytes=hashlib.md5(('OfflinePlayer:'+name).encode()).digest(),version=3)) +(server/'ops.json').write_text(json.dumps([dict(uuid=offline('WeatherTester1'),name='WeatherTester1',level=4,bypassesPlayerLimit=True)])) +config='general {\n S:climateMode='+('PER_BIOME' if a.case in ['biome','thermal'] else 'UNIVERSAL')+'\n S:activePreset=burlington\n}\nbiome_climates {\n S:"minecraft:jungle"=tropical_monsoon\n}\n' +if a.case=='calendar': + # A complete test-only preset: let the production loader seed every other default. + preset=next(v for v in json.loads((root/'src/main/resources/assets/skysrealisticweather/presets.json').read_text()) if v['id']=='burlington') + config+='presets {\n burlington {\n S:name=Network fixture\n S:description=Deterministic network storm\n S:group=user\n D:strength=1\n S:weatherEvents <\n WINTER_STORM,0,0,0,100,0,0,8000,8000,0.8,0.8\n >\n' + for name,values in zip(['spring','summer','autumn','winter'],preset['periods']): + config+=name+' {\n'+''.join((' I:' if key=='days' else ' D:')+key+'='+str(value)+'\n' for key,value in zip(['days','temperature','wetness','thunder','fog'],values))+'}\n' + config+='}\n}\n' +(server/'config/skysrealisticweather.cfg').write_text(config) +build_receipt=json.loads((root/'build/verification/probe/probe-build.json').read_text());main=next(p for p in (root/'build/libs').glob('*.jar') if h(p)==build_receipt['main_sha256']);probe=root/('build/verification/probe/weather-control-probe.jar' if a.case=='control' else 'build/verification/probe/skyweather-probe.jar');artifacts=[probe] if a.case=='control' and not a.control_weather else [main,probe] +artifact_hashes={p.name:h(p) for p in artifacts} +inputs=out/'inputs';inputs.mkdir() +for path in [Path(__file__),root/'scripts/verification_clients.py',root/'build/verification/probe/probe-build.json']:shutil.copy2(path,inputs/path.name) +for jar in artifacts:shutil.copy2(jar,server/'mods'/jar.name) +mode={'calendar':'network','biome':'biome-network','admin':'admin-network','thermal':'thermal-network','control':'control'}[a.case] +java=Path.home()/'.gradle/jdks/temurin-8-amd64-windows.2/bin/java.exe';cmd=[str(java),'-Xms128m','-Xmx1g','-XX:+UseSerialGC','-XX:ActiveProcessorCount=1','-XX:CICompilerCount=2','-Dskyweather.probe='+mode,'-Dskyweather.control='+str(a.case=='control').lower(),'-Dskyweather.controlWeather='+str(a.control_weather).lower(),'-Dskyweather.preset=burlington','-Dfile.encoding=UTF-8','-jar',forge,'nogui'] +clients=[];process=None;desktop=None;start=time.monotonic();passed=False;error=None +try: + with (server/'server.log').open('wb') as log: + process=subprocess.Popen(cmd,cwd=server,stdin=subprocess.PIPE,stdout=log,stderr=subprocess.STDOUT,creationflags=subprocess.CREATE_NO_WINDOW|subprocess.BELOW_NORMAL_PRIORITY_CLASS);assert k.SetProcessAffinityMask(int(process._handle),1<deadline:raise RuntimeError('Server startup failed') + time.sleep(.25) + desktop_name='WeatherNetwork'+str(os.getpid());desktop=u.CreateDesktopW(desktop_name,None,None,0,0x10000000,None);assert desktop,C.WinError(C.get_last_error()) + for index in [1,2]: + target=out/f'client-{index}';(target/'mods').mkdir(parents=True) + for jar in artifacts:shutil.copy2(jar,target/'mods'/jar.name) + (target/'options.txt').write_text('renderDistance:3\npauseOnLostFocus:false\nenableVsync:false\nmaxFps:10\nclouds:false\nsoundCategory_master:0.0\nsoundCategory_music:0.0\n') + props=['skyweather.port='+str(port),'skyweather.control='+str(a.case=='control').lower(),'file.encoding=UTF-8'] + if a.case=='biome':props+=['skyweather.biomeNetwork=true'] + if a.case=='admin':props+=['skyweather.adminProbe=true'] + if a.case=='thermal':props+=['skyweather.heatNetwork=true'] + c=Client(client_command(target,'WeatherTester'+str(index),props),target,'WinSta0\\'+desktop_name,min(19,(os.cpu_count()or 1)-1));clients.append((target,c));print('client',index,c.pid,'on hidden desktop',flush=True) + deadline=time.monotonic()+260 + expected={'calendar':'CLIENT_NETWORK PASS','admin':'CLIENT_ADMIN PASS','biome':'BIOME_NETWORK PASS','thermal':'THERMAL_CLIENT PASS','control':'CONTROL_CLIENT PASS'}[a.case] + while True: + logs=[(d/'client.log').read_text(encoding='utf8',errors='replace') for d,c in clients];serverlog=(server/'server.log').read_text(encoding='utf8',errors='replace') + if all(expected in s for s in logs):break + if time.monotonic()>deadline or any(c.poll() is not None and expected not in s for s,(d,c) in zip(logs,clients)):raise RuntimeError('Client validation failed or timed out') + if process.poll() is not None or 'Encountered an unexpected exception' in serverlog: raise RuntimeError('Server crashed; see retained server.log') + if 'SKY_WEATHER_CHECK failed' in serverlog or any('SKY_WEATHER_CHECK failed' in s for s in logs):raise RuntimeError('Probe assertion failed') + time.sleep(.25) + if a.case!='biome': + want={'calendar':'NETWORK_AND_SLEEP PASS','admin':'ADMIN_NETWORK PASS','thermal':'THERMAL_NETWORK PASS','control':'CONTROL_SERVER PASS'}[a.case] + while want not in (server/'server.log').read_text(encoding='utf8',errors='replace'): + if time.monotonic()>deadline or process.poll() is not None:raise RuntimeError('Server confirmation missing') + time.sleep(.25) + passed=True +except Exception as e:error=repr(e);print(error,flush=True) +finally: + for d,c in clients:c.close() + if process and process.poll() is None: + try:process.stdin.write(b'stop\n');process.stdin.flush();process.wait(timeout=25) + except Exception:process.terminate();process.wait() + if desktop:u.CloseDesktop(desktop) + result=dict(passed=passed,error=error,case=a.case,weather_in_control=a.control_weather,seconds=round(time.monotonic()-start,2),main_sha256=h(main),probe_sha256=artifact_hashes[probe.name],client_processes=[c.pid for d,c in clients],server_pid=None if process is None else process.pid,desktop='non-input desktop; never switched',muted=True,fps=10,server_cpu=20,client_cpu=19,priority='BelowNormal',artifacts=artifact_hashes,generated_config_sha256=h(server/'config/skysrealisticweather.cfg')) + (out/'result.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) +assert passed,'Retained '+str(out) diff --git a/scripts/Run-RuntimeChecks.py b/scripts/Run-RuntimeChecks.py index ff051fa..25cedcc 100644 --- a/scripts/Run-RuntimeChecks.py +++ b/scripts/Run-RuntimeChecks.py @@ -49,7 +49,9 @@ (directory/'server.properties').write_text(props) if args.universal: (directory/'config').mkdir() - (directory/'config/skysrealisticweather.cfg').write_text('~CONFIG_VERSION: 8\ngeneral {\n S:climateMode=UNIVERSAL\n S:activePreset=burlington\n}\n') + # A partial current-schema file would mean an intentionally empty preset library. + # Leave it unversioned so the loader seeds the complete default catalog. + (directory/'config/skysrealisticweather.cfg').write_text('general {\n S:climateMode=UNIVERSAL\n S:activePreset=burlington\n}\n') else: previous = json.loads((output/'initial.json').read_text()) assert previous['passed'] and previous['main_sha256'] == digest(main) and previous['probe_sha256'] == digest(probe), 'Reload requires the same passing candidate' diff --git a/scripts/verification_clients.py b/scripts/verification_clients.py new file mode 100644 index 0000000..c937a62 --- /dev/null +++ b/scripts/verification_clients.py @@ -0,0 +1,60 @@ +"""Launch muted packaged clients on a separate Windows desktop without switching input.""" +from pathlib import Path +import ctypes as C +from ctypes import wintypes as W +import msvcrt,subprocess,os,time,json,zipfile,argparse,hashlib,uuid,shutil +root=Path(__file__).resolve().parents[1] +proof=root/'build/verification/multiplayer-performance-1112' +k=C.WinDLL('kernel32',use_last_error=True);u=C.WinDLL('user32',use_last_error=True) +class STARTUPINFO(C.Structure): + _fields_=[('cb',W.DWORD),('lpReserved',W.LPWSTR),('lpDesktop',W.LPWSTR),('lpTitle',W.LPWSTR),*[(n,W.DWORD) for n in ['dwX','dwY','dwXSize','dwYSize','dwXCountChars','dwYCountChars','dwFillAttribute','dwFlags']],('wShowWindow',W.WORD),('cbReserved2',W.WORD),('lpReserved2',C.POINTER(W.BYTE)),('hStdInput',W.HANDLE),('hStdOutput',W.HANDLE),('hStdError',W.HANDLE)] +class PROCESSINFO(C.Structure):_fields_=[('hProcess',W.HANDLE),('hThread',W.HANDLE),('pid',W.DWORD),('tid',W.DWORD)] +u.CreateDesktopW.argtypes=[W.LPCWSTR,W.LPCWSTR,C.c_void_p,W.DWORD,W.DWORD,C.c_void_p];u.CreateDesktopW.restype=W.HANDLE +u.CloseDesktop.argtypes=[W.HANDLE];u.CloseDesktop.restype=W.BOOL +k.CreateProcessW.argtypes=[W.LPCWSTR,W.LPWSTR,C.c_void_p,C.c_void_p,W.BOOL,W.DWORD,C.c_void_p,W.LPCWSTR,C.POINTER(STARTUPINFO),C.POINTER(PROCESSINFO)];k.CreateProcessW.restype=W.BOOL +k.SetHandleInformation.argtypes=[W.HANDLE,W.DWORD,W.DWORD];k.SetProcessAffinityMask.argtypes=[W.HANDLE,C.c_size_t];k.SetProcessAffinityMask.restype=W.BOOL +k.ResumeThread.argtypes=[W.HANDLE];k.ResumeThread.restype=W.DWORD +k.GetExitCodeProcess.argtypes=[W.HANDLE,C.POINTER(W.DWORD)];k.GetExitCodeProcess.restype=W.BOOL +k.WaitForSingleObject.argtypes=[W.HANDLE,W.DWORD];k.WaitForSingleObject.restype=W.DWORD +k.TerminateProcess.argtypes=[W.HANDLE,W.UINT];k.CloseHandle.argtypes=[W.HANDLE] +class Client: + def __init__(self,command,directory,desktop,cpu): + self.log=(directory/'client.log').open('wb');self.null=open(os.devnull,'rb');si=STARTUPINFO();si.cb=C.sizeof(si);si.lpDesktop=desktop;si.dwFlags=0x100|0x80 + si.hStdInput=msvcrt.get_osfhandle(self.null.fileno());si.hStdOutput=si.hStdError=msvcrt.get_osfhandle(self.log.fileno()) + for h in [si.hStdInput,si.hStdOutput]:assert k.SetHandleInformation(h,1,1) + self.info=PROCESSINFO();cmd=C.create_unicode_buffer(subprocess.list2cmdline(command)) + assert k.CreateProcessW(str(command[0]),cmd,None,None,True,0x08000000|0x4000|4,None,str(directory),C.byref(si),C.byref(self.info)),C.WinError(C.get_last_error()) + self.pid=self.info.pid + try: + assert k.SetProcessAffinityMask(self.info.hProcess,1< s.equals("attached")), "all present adapters attached " + PlantHookStatus.states()); @@ -379,6 +380,35 @@ private void saplingFertilizer() { } } + private void populationScope() { + IBlockState sapling=Blocks.SAPLING.getDefaultState().withProperty(BlockSapling.TYPE,BlockPlanks.EnumType.ACACIA); + pad(pos,sapling);frame(-0.3F,startup.farming); + require(!net.minecraftforge.event.terraingen.TerrainGen.saplingGrowTree(world,new Random(1),pos),"natural cold tree remains gated"); + net.minecraft.world.chunk.IChunkGenerator inner=populationGenerator(() -> { + require(net.minecraftforge.event.terraingen.TerrainGen.saplingGrowTree(world,new Random(1),pos),"nested population keeps native trees"); + throw new IllegalStateException("population fixture"); + }); + net.minecraft.world.chunk.IChunkGenerator outer=populationGenerator(() -> { + require(PlantGrowthHooks.allow(world,pos,new Random(1)),"population bypasses farming gate"); + try{PlantGrowthHooks.populateChunk(inner,0,0,world.getChunkFromBlockCoords(pos));} + catch(IllegalStateException expected){require(expected.getMessage().equals("population fixture"),"native generator exception preserved");} + require(net.minecraftforge.event.terraingen.TerrainGen.saplingGrowTree(world,new Random(1),pos),"outer population scope restored after nested failure"); + }); + PlantGrowthHooks.populateChunk(outer,0,0,world.getChunkFromBlockCoords(pos)); + require(!net.minecraftforge.event.terraingen.TerrainGen.saplingGrowTree(world,new Random(1),pos),"natural gate restored after population"); + try{PlantGrowthHooks.populateChunk(inner,0,0,world.getChunkFromBlockCoords(pos));} + catch(IllegalStateException expected){require(expected.getMessage().equals("population fixture"),"top-level population exception preserved");} + require(!PlantGrowthHooks.allow(world,pos,new Random(1)),"population scope cleared after failure"); + } + + private static net.minecraft.world.chunk.IChunkGenerator populationGenerator(Runnable callback) { + return (net.minecraft.world.chunk.IChunkGenerator)Proxy.newProxyInstance(net.minecraft.world.chunk.IChunkGenerator.class.getClassLoader(), + new Class[]{net.minecraft.world.chunk.IChunkGenerator.class},(proxy,method,args) -> { + if(method.getName().equals("populate")||method.getName().equals("func_185931_b")){callback.run();return null;} + throw new UnsupportedOperationException(method.getName()); + }); + } + private static Object invoke(Object target, String name, Object... args) throws Exception { for (Method method : target.getClass().getMethods()) if (method.getName().equals(name) && method.getParameterCount() == args.length) { method.setAccessible(true); return method.invoke(target, args); diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java index e1d05d5..45b7f21 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java @@ -54,6 +54,7 @@ public final class ClientProbe extends WeatherProbe.SideProbe { private String climatePicture; private int modeUiStage; private GuiScreen modeRoot; + private TemperatureClientProbe thermal; @Override public void register() { @@ -64,6 +65,10 @@ public void register() { public void tick(TickEvent.ClientTickEvent event) throws ReflectiveOperationException { if (event.phase != TickEvent.Phase.END) return; Minecraft game = Minecraft.getMinecraft(); + if (Boolean.getBoolean("skyweather.heatNetwork")) { + if(thermal==null)thermal=new TemperatureClientProbe(); + thermal.tick(game);return; + } if (Boolean.getBoolean("skyweather.biomeNetwork")) { biomeNetwork(game); return; diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/TemperatureClientProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/TemperatureClientProbe.java new file mode 100644 index 0000000..dc37367 --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/TemperatureClientProbe.java @@ -0,0 +1,74 @@ +package zone.moddev.mc.skysrealisticweather.verify; + +import java.util.*; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiMainMenu; +import net.minecraft.client.multiplayer.GuiConnecting; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.*; +import net.minecraft.util.math.*; +import net.minecraftforge.client.event.ClientChatReceivedEvent; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.entity.player.ItemTooltipEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import zone.moddev.mc.skysrealisticweather.WeatherMod; +import zone.moddev.mc.skysrealisticweather.api.*; +import zone.moddev.mc.skysrealisticweather.climate.WeatherConfiguration; +import zone.moddev.mc.skysrealisticweather.game.TemperatureDisplay; +import zone.moddev.mc.skysrealisticweather.instrument.Thermometer; +import zone.moddev.mc.skysrealisticweather.network.TemperaturePreferenceMessage; + +public final class TemperatureClientProbe { + private int stage=-1,ack=-1,ready,attempts,reconnects; + private String reading="";private boolean connecting,complete,clicked; + TemperatureClientProbe(){MinecraftForge.EVENT_BUS.register(this);} + @SubscribeEvent public void chat(ClientChatReceivedEvent event) { + String text=event.getMessage().getUnformattedText(); + if(text.startsWith("WEATHER_THERMAL_STAGE:")) { + int next=Integer.parseInt(text.substring(text.indexOf(':')+1)); + if(next!=stage){stage=next;ready=0;clicked=false;reading="";} + } else if(text.startsWith("Temperature:"))reading=text; + else if(text.equals("WEATHER_THERMAL_COMPLETE"))complete=true; + } + void tick(Minecraft game) { + if(++attempts%100==0)System.out.println("THERMAL_STATE stage="+stage+" ready="+ready+" screen="+(game.currentScreen==null?"none":game.currentScreen.getClass().getSimpleName())+" pos="+(game.player==null?"none":game.player.getPosition())); + if(complete){System.out.println("THERMAL_CLIENT PASS "+game.getSession().getUsername()+" reconnects="+reconnects);game.shutdown();return;} + if(game.world==null) { + if(game.currentScreen instanceof GuiMainMenu || game.currentScreen instanceof net.minecraft.client.gui.GuiDisconnected) { + if(!connecting){connecting=true;reconnects++;game.displayGuiScreen(new GuiConnecting(new GuiMainMenu(),game,"127.0.0.1",Integer.getInteger("skyweather.port")));} + } + return; + } + connecting=false;if(game.player==null||stage<0||stage==ack||game.currentScreen!=null)return; + boolean guest=game.player.getName().endsWith("2");TemperatureDisplay.Unit unit=guest?TemperatureDisplay.Unit.FAHRENHEIT:TemperatureDisplay.Unit.CELSIUS; + if(++ready==1){WeatherConfiguration.file().getCategory(WeatherConfiguration.CLIENT).get("temperatureUnit").set(unit.name());WeatherMod.NETWORK.sendToServer(new TemperaturePreferenceMessage(unit));} + if(ready<20)return; + BlockPos pos=game.player.getPosition();Optional sample=WeatherApi.getTemperatureSample(game.world,pos); + if(!sample.isPresent())return;TemperatureSample value=sample.get(); + if(ready%100==0)System.out.println("THERMAL_WAIT stage="+stage+" pos="+pos+" source="+value.source+" value="+value.temperature+" ambient="+value.ambientTemperature+" reading="+reading); + TemperatureSample.Source expected=stage==0||stage==1||stage==9||stage==7&&!guest?TemperatureSample.Source.ZONE: + stage==3||stage==5?TemperatureSample.Source.TORCH:stage==4?TemperatureSample.Source.FURNACE:TemperatureSample.Source.AMBIENT; + if(value.source!=expected)return; + if(expected==TemperatureSample.Source.ZONE) { + float target=stage==0?25:stage==1?-15:17; + if(Math.abs(TemperatureDisplay.Unit.CELSIUS.temperature(value.temperature)-target)>.01)return; + } + if(expected==TemperatureSample.Source.TORCH && Math.abs(TemperatureDisplay.Unit.CELSIUS.adjustment(value.temperature-value.ambientTemperature)-3)>.02)return; + if(expected==TemperatureSample.Source.FURNACE && Math.abs(TemperatureDisplay.Unit.CELSIUS.adjustment(value.temperature-value.ambientTemperature)-16)>.02)return; + WeatherProbe.require(Thermometer.heldBy(game.player),"ordinary player holds instrument"); + WeatherProbe.require(Math.abs(Thermometer.temperature(game.world,pos).getAsDouble()-value.temperature)<.00001,"thermometer matches synchronized local sample"); + if(stage==1) { + Optional crop=WeatherApi.getPlantGrowth(game.world,new BlockPos(8,81,9));if(!crop.isPresent()||crop.get().naturalGrowthMultiplier!=0)return; + List lines=new ArrayList<>();MinecraftForge.EVENT_BUS.post(new ItemTooltipEvent(new ItemStack(Items.WHEAT_SEEDS),game.player,lines,false)); + WeatherProbe.require(lines.toString().contains(unit.symbol)&&lines.toString().toLowerCase(Locale.ROOT).contains("paused"),"crop tooltip uses cold policy and personal display units"); + if(!clicked){clicked=true;game.playerController.processRightClickBlock(game.player,game.world,new BlockPos(7,81,8),EnumFacing.UP,new Vec3d(7.5,81.5,8.5),EnumHand.MAIN_HAND);return;} + if(!reading.contains(guest?"5.0 °F":"-15.0 °C"))return; + } + if(stage==7 && (guest?pos.getX()>20:pos.getX()<160))return; + if(stage==8 && (!guest && game.world.isBlockLoaded(new BlockPos(168,81,168),false)))return; + if(stage==9 && guest && reconnects<2)return; + System.out.println("THERMAL_CLIENT_STAGE PASS "+game.player.getName()+" stage="+stage+" source="+value.source+" reading="+unit.format(value.temperature)); + game.player.sendChatMessage("/weatherprobeack "+stage);ack=stage; + } +} diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/TemperatureNetworkProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/TemperatureNetworkProbe.java new file mode 100644 index 0000000..7f93502 --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/TemperatureNetworkProbe.java @@ -0,0 +1,103 @@ +package zone.moddev.mc.skysrealisticweather.verify; + +import java.util.*; +import net.minecraft.command.*; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.*; +import net.minecraft.item.ItemStack; +import net.minecraft.server.MinecraftServer; +import net.minecraft.tileentity.TileEntityFurnace; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.world.WorldServer; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; +import zone.moddev.mc.skysrealisticweather.api.*; +import zone.moddev.mc.skysrealisticweather.game.TemperatureDisplay; +import zone.moddev.mc.skysrealisticweather.instrument.Thermometer; + +/** Coordinates assertions in two real clients using ordinary chat commands as acknowledgements. */ +public final class TemperatureNetworkProbe { + private final WorldServer world; + private final Set acknowledgements = new HashSet<>(); + private final ResourceLocation room = new ResourceLocation("networkprobe:room"), remote = new ResourceLocation("networkprobe:remote"); + private final BlockPos origin = new BlockPos(8,81,8), torch = origin.east(), furnace = origin.east(2); + private int stage=-1, elapsed, total; + TemperatureNetworkProbe(WorldServer world) { + this.world=world; MinecraftForge.EVENT_BUS.register(this); + ((CommandHandler)world.getMinecraftServer().getCommandManager()).registerCommand(new CommandBase() { + public String getName(){return "weatherprobeack";} + public String getUsage(ICommandSender sender){return "weatherprobeack ";} + public int getRequiredPermissionLevel(){return 0;} + @Override public boolean checkPermission(MinecraftServer server,ICommandSender sender) { + return sender instanceof EntityPlayerMP && (sender.getName().equals("WeatherTester1")||sender.getName().equals("WeatherTester2")); + } + public void execute(MinecraftServer server,ICommandSender sender,String[] args)throws CommandException { + System.out.println("THERMAL_ACK sender="+sender.getName()+" stage="+stage+" args="+Arrays.toString(args)); + if(sender instanceof EntityPlayerMP && args.length==1 && parseInt(args[0],0,10)==stage) + acknowledgements.add(sender.getName()); + } + }); + world.getGameRules().setOrCreateGameRule("doDaylightCycle","false"); world.setWorldTime(134L*24000+6000); + for(int x=5;x<=12;x++)for(int z=5;z<=11;z++) { + BlockPos p=new BlockPos(x,80,z); world.setBlockToAir(p.up()); world.setBlockState(p,Blocks.GRASS.getDefaultState(),3); + } + BlockPos crop=origin.south();world.setBlockState(crop.down(),Blocks.FARMLAND.getDefaultState(),3);world.setBlockState(crop,Blocks.WHEAT.getDefaultState(),3); + world.setBlockState(origin.west(),((net.minecraft.block.Block)Thermometer.BLOCK).getDefaultState(),3); + put(room,origin,25); + System.out.println("THERMAL_SERVER_READY"); + } + private void put(ResourceLocation id,BlockPos center,float celsius) { + WeatherApi.putTemperatureZone(world,TemperatureZone.celsius(id,center.add(-3,-2,-3),center.add(3,2,3),celsius)); + } + private EntityPlayerMP player(int n){return world.getMinecraftServer().getPlayerList().getPlayerByUsername("WeatherTester"+n);} + private void announce(EntityPlayerMP p){p.sendMessage(new TextComponentString("WEATHER_THERMAL_STAGE:"+stage));} + @SubscribeEvent public void tick(TickEvent.WorldTickEvent event) { + if(event.world!=world||event.phase!=TickEvent.Phase.END)return; + if(++total>5000)throw new IllegalStateException("THERMAL_NETWORK timeout stage="+stage+" ack="+acknowledgements); + if(stage<0) { + if(player(1)==null||player(2)==null)return; + for(int n=1;n<=2;n++) { + EntityPlayerMP p=player(n);p.connection.setPlayerLocation(8.25,81,8.25,0,0); + p.inventory.setInventorySlotContents(0,new ItemStack(Thermometer.BLOCK));p.inventoryContainer.detectAndSendChanges(); + } + advance();return; + } + if(++elapsed%20==0)for(int n=1;n<=2;n++)if(player(n)!=null)announce(player(n)); + if(acknowledgements.size()!=2)return; + if(stage==0 || stage==9)for(int n=1;n<=2;n++) + WeatherProbe.require(TemperatureDisplay.forSender(player(n))==(n==1?TemperatureDisplay.Unit.CELSIUS:TemperatureDisplay.Unit.FAHRENHEIT),"independent server unit preferences"); + System.out.println("THERMAL_SERVER_STAGE PASS "+stage+" players="+acknowledgements); + if(stage==10) { + WeatherApi.removeTemperatureZone(world,room);WeatherApi.removeTemperatureZone(world,remote); + for(int n=1;n<=2;n++)player(n).sendMessage(new TextComponentString("WEATHER_THERMAL_COMPLETE")); + System.out.println("SKY_WEATHER_CHECK THERMAL_NETWORK PASS"); + world.getMinecraftServer().initiateShutdown(); stage=11;return; + } + advance(); + } + private void advance() { + stage++;elapsed=0;acknowledgements.clear(); + switch(stage) { + case 1:put(room,origin,-15);break; + case 2:WeatherApi.removeTemperatureZone(world,room);break; + case 3:world.setBlockState(torch,Blocks.TORCH.getDefaultState(),3);break; + case 4: + world.setBlockState(furnace,Blocks.LIT_FURNACE.getDefaultState(),3); + TileEntityFurnace tile=(TileEntityFurnace)world.getTileEntity(furnace); + tile.setInventorySlotContents(0,new ItemStack(Blocks.IRON_ORE,64));tile.setInventorySlotContents(1,new ItemStack(Items.COAL,64));tile.setField(0,1200);break; + case 5: + TileEntityFurnace cold=(TileEntityFurnace)world.getTileEntity(furnace); + cold.setInventorySlotContents(0,ItemStack.EMPTY);cold.setInventorySlotContents(1,ItemStack.EMPTY);cold.setField(0,0);break; + case 6:world.setBlockToAir(torch);world.setBlockToAir(furnace);break; + case 7:put(remote,new BlockPos(168,81,168),17);player(1).connection.setPlayerLocation(168.25,81,168.25,0,0);break; + case 8:player(1).connection.setPlayerLocation(8.25,81,8.25,0,0);break; + case 9:put(room,origin,17);player(2).connection.disconnect("Thermal reconnect check");break; + case 10:WeatherApi.removeTemperatureZone(world,room);WeatherApi.removeTemperatureZone(world,remote);break; + default:break; + } + for(int n=1;n<=2;n++)if(player(n)!=null)announce(player(n)); + } +} diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java index 6b91278..edc5648 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java @@ -85,6 +85,7 @@ public void started(FMLServerStartedEvent event) { require(HookStatus.available(), "required weather hooks loaded"); switch (MODE) { case "temperature-zones": TemperatureZoneProbe.run(world); break; + case "thermal-network": new TemperatureNetworkProbe(world); break; case "precipitation": PrecipitationProbe.run(world); break; case "thermometer": ThermometerProbe.run(world); break; case "plants": diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/control/ControlClient.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/control/ControlClient.java new file mode 100644 index 0000000..627f8e8 --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/control/ControlClient.java @@ -0,0 +1,29 @@ +package zone.moddev.mc.skysrealisticweather.verify.control; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiMainMenu; +import net.minecraft.client.multiplayer.GuiConnecting; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; +import net.minecraftforge.client.event.ClientChatReceivedEvent; +public final class ControlClient extends ControlProbe.CommonSide { + private boolean connected,bothSeen,complete;private int ticks; + @Override public void register(){MinecraftForge.EVENT_BUS.register(this);} + @SubscribeEvent public void chat(ClientChatReceivedEvent event) { + if(event.getMessage().getUnformattedText().equals("CONTROL_MEASURE_COMPLETE"))complete=true; + } + @SubscribeEvent public void tick(TickEvent.ClientTickEvent event){ + if(event.phase!=TickEvent.Phase.END)return;Minecraft mc=Minecraft.getMinecraft(); + if(mc.world==null){ + if(!connected&&mc.currentScreen instanceof GuiMainMenu){connected=true;mc.displayGuiScreen(new GuiConnecting(mc.currentScreen,mc,"127.0.0.1",Integer.getInteger("skyweather.port")));} + return; + } + if(mc.player==null)return; + bothSeen|=mc.getConnection().getPlayerInfoMap().size()==2; + if(!bothSeen)return; + if(++ticks<100)return; + if(mc.world.getWorldTime()!=134L*24000+6000||!mc.world.isRaining()||mc.world.getRainStrength(1)<.9F)throw new IllegalStateException("CONTROL_CLIENT incorrect server weather/date"); + if(!complete)return; + System.out.println("CONTROL_CLIENT PASS "+mc.player.getName()+" time="+mc.world.getWorldTime()+" rain="+mc.world.getRainStrength(1));mc.shutdown(); + } +} diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/control/ControlProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/control/ControlProbe.java new file mode 100644 index 0000000..955a9d2 --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/control/ControlProbe.java @@ -0,0 +1,65 @@ +package zone.moddev.mc.skysrealisticweather.verify.control; +import net.minecraft.world.WorldServer; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.*; +import net.minecraftforge.fml.common.event.*; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; +import net.minecraftforge.fml.common.eventhandler.EventPriority; +import net.minecraft.util.text.TextComponentString; +import java.lang.management.*; +import java.util.*; +@Mod(modid="weathercontrolprobe", name="Multiplayer Control Probe", version="1") +public final class ControlProbe { + @SidedProxy(clientSide="zone.moddev.mc.skysrealisticweather.verify.control.ControlClient",serverSide="zone.moddev.mc.skysrealisticweather.verify.control.ControlProbe$CommonSide") + public static CommonSide proxy; + private WorldServer world; private int ticks, samples; + private long cpuStart,wallStart,windowCpuStart; + private final long[] cpuTimes=new long[600],wallTimes=new long[600]; + private final ThreadMXBean timer=ManagementFactory.getThreadMXBean(); + @Mod.EventHandler public void init(FMLInitializationEvent event) { + if(!Boolean.getBoolean("skyweather.control")) return; + MinecraftForge.EVENT_BUS.register(this); proxy.register(); + } + @Mod.EventHandler public void started(FMLServerStartedEvent event) { + if(!Boolean.getBoolean("skyweather.control")) return; + if(Loader.isModLoaded("skysrealisticweather")!=Boolean.getBoolean("skyweather.controlWeather")) + throw new IllegalStateException("Wrong multiplayer comparison profile"); + world=FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(0); + world.getGameRules().setOrCreateGameRule("doDaylightCycle","false"); + world.getGameRules().setOrCreateGameRule("doWeatherCycle","false"); + world.setWorldTime(134L*24000+6000); world.getWorldInfo().setRaining(true); + world.getMinecraftServer().getCommandManager().executeCommand(world.getMinecraftServer(),"weather rain 6000"); + world.getWorldInfo().setRainTime(120000); + for(int i=0;i<100;i++)world.updateWeatherBody(); + timer.setThreadCpuTimeEnabled(true); + System.out.println("CONTROL_SERVER_READY"); + } + @SubscribeEvent public void tick(TickEvent.WorldTickEvent event) { + if(world==null||event.world!=world||event.phase!=TickEvent.Phase.END||world.playerEntities.size()!=2)return; + ticks++; + } + @SubscribeEvent(priority=EventPriority.HIGHEST) public void begin(TickEvent.ServerTickEvent event) { + if(event.phase==TickEvent.Phase.START && world!=null && world.playerEntities.size()==2 && ticks>=120 && samples<600) { + cpuStart=timer.getCurrentThreadCpuTime();wallStart=System.nanoTime(); + if(samples==0)windowCpuStart=cpuStart; + } + } + @SubscribeEvent(priority=EventPriority.LOWEST) public void end(TickEvent.ServerTickEvent event) { + if(event.phase!=TickEvent.Phase.END || cpuStart==0)return; + cpuTimes[samples]=timer.getCurrentThreadCpuTime()-cpuStart; + wallTimes[samples++]=System.nanoTime()-wallStart;cpuStart=0; + if(samples!=600)return; + double windowCpu=(timer.getCurrentThreadCpuTime()-windowCpuStart)/600e6; + double cpu=Arrays.stream(cpuTimes).average().getAsDouble()/1e6; + double wall=Arrays.stream(wallTimes).average().getAsDouble()/1e6; + Arrays.sort(wallTimes); + // Windows thread CPU counters are coarse; compare the entire window, not individual tick deltas. + System.out.printf(Locale.ROOT,"MULTIPLAYER_PERF_RESULT weather=%s samples=%d cpu_window_mean_ms=%.5f cpu_inner_mean_ms=%.5f wall_mean_ms=%.5f wall_p95_ms=%.5f wall_p99_ms=%.5f%n", + Loader.isModLoaded("skysrealisticweather"),samples,windowCpu,cpu,wall,wallTimes[569]/1e6,wallTimes[593]/1e6); + System.out.println("CONTROL_SERVER PASS players=2 time="+world.getWorldTime()+" rain="+world.isRaining()); + for(net.minecraft.entity.player.EntityPlayer player:world.playerEntities) + player.sendMessage(new TextComponentString("CONTROL_MEASURE_COMPLETE")); + } + public static class CommonSide { public void register() {} } +} diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/performance/DepositVeto.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/performance/DepositVeto.java new file mode 100644 index 0000000..dc90948 --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/performance/DepositVeto.java @@ -0,0 +1,20 @@ +package zone.moddev.mc.skysrealisticweather.verify.performance; + +import net.minecraft.world.WorldServer; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import zone.moddev.mc.skysrealisticweather.api.SeasonalSurfaceEvent; + +/** Diagnostic only: isolate climate queries from the physical effect of generated cover. */ +public final class DepositVeto { + private final WorldServer world; + private static int count; + private DepositVeto(WorldServer world){this.world=world;} + public static void attach(WorldServer world){MinecraftForge.EVENT_BUS.register(new DepositVeto(world));} + public static int count(){return count;} + @SubscribeEvent public void surface(SeasonalSurfaceEvent event) { + if(event.world==world && (event.action==SeasonalSurfaceEvent.Action.ACCUMULATE_SNOW||event.action==SeasonalSurfaceEvent.Action.FREEZE_WATER)) { + event.setCanceled(true);count++; + } + } +} diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/performance/OtgPopulationCounter.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/performance/OtgPopulationCounter.java new file mode 100644 index 0000000..80c61a3 --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/performance/OtgPopulationCounter.java @@ -0,0 +1,21 @@ +package zone.moddev.mc.skysrealisticweather.verify.performance; + +import com.pg85.otg.LocalWorld; +import com.pg85.otg.OTG; +import com.pg85.otg.events.EventHandler; +import com.pg85.otg.events.EventPriority; +import com.pg85.otg.forge.ForgeWorld; +import java.util.Random; +import net.minecraft.world.WorldServer; + +public final class OtgPopulationCounter extends EventHandler { + private final WorldgenPerformanceProbe probe; + private OtgPopulationCounter(WorldgenPerformanceProbe probe) { this.probe = probe; } + static void attach(WorldgenPerformanceProbe probe) { + OTG.registerEventHandler(new OtgPopulationCounter(probe), EventPriority.MONITOR); + } + @Override + public void onPopulateEnd(LocalWorld world, Random random, boolean village, int x, int z) { + probe.otgDecorated((WorldServer) ((ForgeWorld) world).getWorld(), x, z); + } +} diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/performance/WorldgenPerformanceProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/performance/WorldgenPerformanceProbe.java new file mode 100644 index 0000000..987dc9b --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/performance/WorldgenPerformanceProbe.java @@ -0,0 +1,448 @@ +package zone.moddev.mc.skysrealisticweather.verify.performance; + +import java.lang.management.GarbageCollectorMXBean; +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadMXBean; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import net.minecraft.block.Block; +import net.minecraft.block.BlockStone; +import net.minecraft.block.properties.PropertyEnum; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.storage.ExtendedBlockStorage; +import net.minecraft.init.Blocks; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.world.WorldServer; +import net.minecraft.world.biome.Biome; +import net.minecraft.world.gen.ChunkProviderServer; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.terraingen.PopulateChunkEvent; +import net.minecraftforge.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.event.FMLInitializationEvent; +import net.minecraftforge.fml.common.event.FMLServerStartedEvent; +import net.minecraftforge.fml.common.eventhandler.EventPriority; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; + +@Mod(modid = "worldgenperf", name = "Worldgen Performance Probe", version = "1") +public final class WorldgenPerformanceProbe { + private static final long DAY = 24000L; + private static final int SIZE = Integer.getInteger("perf.size", 28); + private static final int WARM_SIZE = Integer.getInteger("perf.warmup", 24); + private static final String PROFILE = System.getProperty("perf.profile"); + private static final String ROUND = System.getProperty("perf.round"); + private static final String TERRAIN = System.getProperty("perf.terrain"); + private static final boolean ALLOCATION = Boolean.getBoolean("perf.allocation"); + private static final boolean INTERLEAVE = Boolean.getBoolean("perf.interleave"); + private final ThreadMXBean threads = ManagementFactory.getThreadMXBean(); + private final Map frostStart = new HashMap<>(); + private List frostTimes; + private int populationCount; + private final HashSet decorated = new HashSet<>(); + private static final int SLICE_ROWS = Integer.getInteger("perf.rows", 2); + private WorldServer world; + private int ticks; + private boolean captureBase; + private final Map baseHeights=new HashMap<>(); + private final Map baseBiomes=new HashMap<>(); + + @SubscribeEvent(priority=EventPriority.HIGHEST) + public void loaded(net.minecraftforge.event.world.ChunkEvent.Load event) { + if(!captureBase||event.getWorld()!=world)return; + Chunk chunk=event.getChunk();long key=ChunkPos.asLong(chunk.x,chunk.z); + baseHeights.put(key,chunk.getHeightMap().clone());baseBiomes.put(key,chunk.getBiomeArray().clone()); + } + + @Mod.EventHandler + public void init(FMLInitializationEvent event) { + if (PROFILE == null) return; + MinecraftForge.EVENT_BUS.register(this); + MinecraftForge.TERRAIN_GEN_BUS.register(this); + } + + @Mod.EventHandler + public void start(FMLServerStartedEvent event) { + if (PROFILE == null) return; + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + world = server.getWorld(0); + world.getGameRules().setOrCreateGameRule("doDaylightCycle", "false"); + world.setWorldTime(320 * DAY + 6000); + boolean expected = !"vanilla".equals(PROFILE); + if(expected&&Boolean.getBoolean("perf.vetoDeposits"))DepositVeto.attach(world); + require(Loader.isModLoaded("skysrealisticweather") == expected, "wrong mod profile"); + require(world.getWorldType().getName().equalsIgnoreCase(System.getProperty("perf.worldType")), "wrong world type"); + if (!System.getProperty("perf.expectedMod", "").isEmpty()) require(Loader.isModLoaded(System.getProperty("perf.expectedMod")), "generator mod missing"); + if ("bundle".equals(TERRAIN)) { + require(Loader.isModLoaded("biomebundle") && world.getWorldInfo().getWorldName().equals("Biome Bundle"), "wrong OTG preset"); + OtgPopulationCounter.attach(this); + } + require(server.getCommandManager().executeCommand(server, "weather rain 6000") == 1, "weather set"); + require(threads.isCurrentThreadCpuTimeSupported(), "server thread CPU timer available"); + threads.setThreadCpuTimeEnabled(true); + if (ALLOCATION) { + com.sun.management.ThreadMXBean hotspot = (com.sun.management.ThreadMXBean) threads; + require(hotspot.isThreadAllocatedMemorySupported(), "server thread allocation counter available"); + hotspot.setThreadAllocatedMemoryEnabled(true); + } + } + + @SubscribeEvent(priority = EventPriority.HIGHEST) + public void frostStart(PopulateChunkEvent.Populate event) { + if (frostTimes != null && event.getWorld() == world + && event.getType() == PopulateChunkEvent.Populate.EventType.ICE) { + frostStart.put(ChunkPos.asLong(event.getChunkX(), event.getChunkZ()), System.nanoTime()); + if (!"bundle".equals(TERRAIN)) decorated.add(ChunkPos.asLong(event.getChunkX(), event.getChunkZ())); + } + } + + void otgDecorated(WorldServer eventWorld, int x, int z) { + if (eventWorld == world && frostTimes != null) decorated.add(ChunkPos.asLong(x,z)); + } + + @SubscribeEvent(priority = EventPriority.LOWEST) + public void populationEnd(PopulateChunkEvent.Post event) { + if (frostTimes == null || event.getWorld() != world) return; + long end = System.nanoTime(); + populationCount++; + Long start = frostStart.remove(ChunkPos.asLong(event.getChunkX(), event.getChunkZ())); + if (start != null) frostTimes.add(end - start); + } + + @SubscribeEvent + public void tick(TickEvent.WorldTickEvent event) { + if (world == null || event.world != world || event.phase != TickEvent.Phase.END || ++ticks != 32) return; + require(world.isRaining(), "forced rain reached steady state"); + if (!"vanilla".equals(PROFILE)) verifySetting(world); + world.disableLevelSaving = true; + ChunkProviderServer provider = world.getChunkProvider(); + // Warm the same code using a separate region before either timed batch. + world.rand.setSeed(123948L ^ 0x5741524DL); + generate(provider, 740, -540, WARM_SIZE, null); + if (Boolean.getBoolean("perf.reverse")) { + benchmark("summer", -360, 550, 134); + benchmark("winter", 320, 320, 320); + } else { + benchmark("winter", 320, 320, 320); + benchmark("summer", -360, 550, 134); + } + verifyPropertyHash(); + fingerprint("winter", 320, 320); + fingerprint("summer", -360, 550); + System.out.println("WORLDGEN_PERF PASS"); + world.getMinecraftServer().initiateShutdown(); + } + + private void benchmark(String phase, int x, int z, long day) { + world.setWorldTime(day * DAY + 6000); + // A frame captures its date: advance the production controller before each timed phase. + if (!"vanilla".equals(PROFILE)) { + require(world.getMinecraftServer().getCommandManager().executeCommand(world.getMinecraftServer(), + "skyweather weather frontal_precipitation 1800") == 1, "controlled precipitation"); + } + world.getWorldInfo().setWorldTotalTime(world.getTotalWorldTime() + 80); + if (!"vanilla".equals(PROFILE)) { + try { + Class type = Class.forName("zone.moddev.mc.skysrealisticweather.game.ServerWeather"); + type.getMethod("startTick", TickEvent.WorldTickEvent.class).invoke(type.getField("INSTANCE").get(null), + new TickEvent.WorldTickEvent(net.minecraftforge.fml.relauncher.Side.SERVER, TickEvent.Phase.START, world)); + Class state = Class.forName("zone.moddev.mc.skysrealisticweather.game.WeatherState"); + Object frame = state.getMethod("frame", net.minecraft.world.World.class).invoke(null, world); + java.lang.reflect.Field time = frame.getClass().getDeclaredField("time"); time.setAccessible(true); + require(time.getLong(frame) == world.getWorldTime(), "fresh phase snapshot"); + } catch (ReflectiveOperationException invalid) { throw new IllegalStateException(invalid); } + } + world.getWorldInfo().setRaining(true); world.getWorldInfo().setRainTime(120000); + world.getWorldInfo().setThundering(false); world.getWorldInfo().setThunderTime(120000); + for (int i=0;i<100;i++) world.updateWeatherBody(); + require(world.isRaining(), "both batches use the same rain state"); + // Some biome decorators use World.rand rather than the generator's seeded chunk RNG. + world.rand.setSeed(123948L ^ day * 0x9E3779B97F4A7C15L); + ChunkProviderServer provider = world.getChunkProvider(); + for (int dz = 0; dz < SIZE; dz++) { + for (int dx = 0; dx < SIZE; dx++) { + require(provider.getLoadedChunk(x + dx, z + dz) == null, "target is fresh"); + } + } + long[] timings = new long[SIZE * SIZE]; + long[] groups = new long[(timings.length + 15) / 16]; + populationCount = 0; + decorated.clear(); + frostStart.clear(); + frostTimes = new ArrayList<>(timings.length); + int before = provider.getLoadedChunkCount(); + long gcCount = gc(false); + long gcTime = gc(true); + long allocatedBytes = allocated(); + long cpu = threads.getCurrentThreadCpuTime(); + baseHeights.clear();baseBiomes.clear();captureBase=true; + long start = System.nanoTime(); + long elapsed; + if (INTERLEAVE) { + elapsed = 0; + cpu = 0; + for (int row = 0; row < SIZE; row += SLICE_ROWS) { + String slice = phase + "-" + row; + awaitTurn(slice); + long sliceCpu = threads.getCurrentThreadCpuTime(); + long sliceStart = System.nanoTime(); + for (int dz = row; dz < Math.min(row + SLICE_ROWS, SIZE); dz++) { + for (int dx = 0; dx < SIZE; dx++) { + long request = System.nanoTime(); + provider.provideChunk(x + dx, z + dz); + timings[dz * SIZE + dx] = System.nanoTime() - request; + } + } + long wall = System.nanoTime() - sliceStart; + long thread = threads.getCurrentThreadCpuTime() - sliceCpu; + elapsed += wall; + cpu += thread; + System.out.printf(Locale.ROOT, "SLICE %s,%s,%d,%.4f,%.4f%n", PROFILE, phase, row, ms(wall), ms(thread)); + signal(slice + ".done"); + } + awaitTurn(phase + "-cover"); + } else { + generate(provider, x, z, SIZE, timings); + elapsed = System.nanoTime() - start; + cpu = threads.getCurrentThreadCpuTime() - cpu; + } + allocatedBytes = allocated() - allocatedBytes; + captureBase=false; + gcCount = gc(false) - gcCount; + gcTime = gc(true) - gcTime; + List frost = frostTimes; + frostTimes = null; + for (int dz = 2; dz < SIZE-2; dz++) for (int dx=2; dx0,"base height maps are initialized"); + System.out.println("BASE_TERRAIN_PARITY "+PROFILE+" "+phase+" "+hex(baseDigest.digest())+" heights="+low+".."+high); + System.out.printf(Locale.ROOT, "WORLDGEN_PERF_RESULT %s,%s,%s,%s,%d,%d,%d,%.3f,%.3f,%d,%d,%.4f,%.4f,%.4f,%.4f,%.4f,%.4f,%d,%d,%016x%n", + ROUND, TERRAIN, PROFILE, phase, timings.length, provider.getLoadedChunkCount() - before, decorated.size(), + ms(elapsed), ms(cpu), gcCount, gcTime, p(timings, .5), p(timings, .95), p(timings, .99), + p(groups, .95), p(ice, .5), p(ice, .95), cover[0], cover[1], cover[2]); + if (ALLOCATION) System.out.printf(Locale.ROOT, "WORLDGEN_PERF_ALLOCATION %s,%s,%d,%d%n", + PROFILE, phase, timings.length, allocatedBytes); + } + + private long allocated() { + return ALLOCATION ? ((com.sun.management.ThreadMXBean) threads).getThreadAllocatedBytes(Thread.currentThread().getId()) : 0; + } + + private static void generate(ChunkProviderServer provider, int x, int z, int size, long[] timings) { + int index = 0; + for (int dz = 0; dz < size; dz++) { + for (int dx = 0; dx < size; dx++) { + if (timings == null) { + provider.provideChunk(x + dx, z + dz); + } else { + long start = System.nanoTime(); + provider.provideChunk(x + dx, z + dz); + timings[index++] = System.nanoTime() - start; + } + } + } + } + + private static void awaitTurn(String slice) { + signal(slice + ".ready"); + Path gate = Paths.get(slice + ".go"); + long deadline = System.nanoTime() + 600_000_000_000L; + try { + while (!Files.exists(gate)) { + if (System.nanoTime() > deadline) throw new IllegalStateException("Timed out waiting for " + gate); + Thread.sleep(5); + } + } catch (InterruptedException exception) { + throw new IllegalStateException(exception); + } + } + + private static void signal(String marker) { + try { + Files.createFile(Paths.get(marker)); + } catch (java.io.IOException exception) { + throw new IllegalStateException(exception); + } + } + + private static void verifyPropertyHash() { + PropertyEnum first = BlockStone.VARIANT; + PropertyEnum equal = PropertyEnum.create(first.getName(), BlockStone.EnumType.class, first.getAllowedValues()); + Map names = new HashMap<>(); + for (BlockStone.EnumType kind : first.getAllowedValues()) names.put(kind.getName(), kind); + int base = 31 * BlockStone.EnumType.class.hashCode() + first.getName().hashCode(); + int expected = 31 * (31 * base + first.getAllowedValues().hashCode()) + names.hashCode(); + require(first.equals(equal) && first.hashCode() == expected && equal.hashCode() == expected, "original enum hash and equality"); + boolean installed = Arrays.stream(PropertyEnum.class.getDeclaredFields()) + .anyMatch(field -> field.getName().equals("skysrealisticweather$nameTableHash")); + require(installed == !"vanilla".equals(PROFILE), "expected hash optimization in packaged runtime"); + if (Boolean.getBoolean("perf.fourBit")) verifySectionPalette(); + } + + private static void verifySectionPalette() { + net.minecraft.world.chunk.BlockStateContainer palette = new net.minecraft.world.chunk.BlockStateContainer(); + try { + boolean specialized = false; + for (java.lang.reflect.Field field : palette.getClass().getDeclaredFields()) { + if (field.getType() != net.minecraft.util.BitArray.class) continue; + field.setAccessible(true); + specialized = field.get(palette).getClass().getName().endsWith(".FourBitSectionStorage"); + } + require(specialized == !"vanilla".equals(PROFILE), "expected four-bit storage in packaged runtime"); + } catch (ReflectiveOperationException exception) { + throw new AssertionError(exception); + } + List states = new ArrayList<>(); + for (Block block : Block.REGISTRY) { + for (net.minecraft.block.state.IBlockState state : block.getBlockState().getValidStates()) { + int id = Block.BLOCK_STATE_IDS.get(state); + if (id >= 0 && Block.BLOCK_STATE_IDS.getByValue(id) == state) states.add(state); + } + if (states.size() >= 300) break; + } + for (int i = 0; i < states.size(); i++) palette.set(i & 15, i >> 8, (i >> 4) & 15, states.get(i)); + for (int i = 0; i < states.size(); i++) require(palette.get(i & 15, i >> 8, (i >> 4) & 15) == states.get(i), "palette resize at " + i); + } + + private void fingerprint(String phase, int startX, int startZ) { + // Registry numbers can move when another mod registers blocks. Compare named states. + java.util.SortedMap named = new java.util.TreeMap<>(); + for (Block block : Block.REGISTRY) { + if (block.getRegistryName().getResourceDomain().equals("skysrealisticweather")) continue; + for (net.minecraft.block.state.IBlockState state : block.getBlockState().getValidStates()) named.put(state.toString(),state); + } + java.util.IdentityHashMap ids = new java.util.IdentityHashMap<>(); + List table = new ArrayList<>(); int next = 0; + for (Map.Entry row : named.entrySet()) { + ids.put(row.getValue(),next);table.add(next++ + "\t" + Block.getStateId(row.getValue()) + "\t" + row.getKey()); + } + java.util.SortedMap biomes = new java.util.TreeMap<>(); + for (Biome biome : Biome.REGISTRY) biomes.put(biome.getRegistryName().toString(),biome); + int[] biomeIds = new int[256]; List biomeTable = new ArrayList<>();next=0; + for (Map.Entry row : biomes.entrySet()) { + int raw=Biome.getIdForBiome(row.getValue());biomeIds[raw]=next;biomeTable.add(next++ + "\t" + raw + "\t" + row.getKey()); + } + MessageDigest digest = sha256(); byte[] states = new byte[16384], biomeBytes = new byte[1024]; + List chunks = new ArrayList<>(); long[] counts = new long[ids.size()]; + for (int z=0;z>8,(i>>4)&15); + // Seasonal cover changes are intentional. Both source-water forms share a name here. + if(state.getBlock()==Blocks.SNOW_LAYER)state=Blocks.AIR.getDefaultState(); + else if(state.getBlock()==Blocks.ICE || state.getBlock()==Blocks.FLOWING_WATER && state.getValue(net.minecraft.block.BlockLiquid.LEVEL)==0)state=Blocks.WATER.getDefaultState(); + Integer id=ids.get(state);if(id==null)throw new IllegalStateException("unexpected generated state "+state);counts[id]++;putInt(states,i*4,id); + } + digest.update(states);local.update(states); + } + chunks.add((startX+x)+"\t"+(startZ+z)+"\t"+hex(local.digest())); + } + List histogram = new ArrayList<>();next=0; + for(String key:named.keySet()) {if(counts[next]!=0)histogram.add(counts[next]+"\t"+key);next++;} + try { + Files.write(Paths.get("canonical-states.tsv"),table,java.nio.charset.StandardCharsets.UTF_8); + Files.write(Paths.get("canonical-biomes.tsv"),biomeTable,java.nio.charset.StandardCharsets.UTF_8); + Files.write(Paths.get(phase+"-chunks.tsv"),chunks,java.nio.charset.StandardCharsets.UTF_8); + Files.write(Paths.get(phase+"-states.tsv"),histogram,java.nio.charset.StandardCharsets.UTF_8); + } catch(java.io.IOException invalid) {throw new IllegalStateException(invalid);} + System.out.println("TERRAIN_PARITY " + PROFILE + " " + phase + " " + hex(digest.digest())); + } + + private static MessageDigest sha256() { + try {return MessageDigest.getInstance("SHA-256");}catch(NoSuchAlgorithmException invalid){throw new AssertionError(invalid);} + } + private static void putInt(byte[] target,int offset,int value) { + target[offset]=(byte)value;target[offset+1]=(byte)(value>>8);target[offset+2]=(byte)(value>>16);target[offset+3]=(byte)(value>>24); + } + private static String hex(byte[] value) { + char[] chars=new char[value.length*2];String digits="0123456789abcdef"; + for(int i=0;i>4)&15);chars[i*2+1]=digits.charAt(value[i]&15);}return new String(chars); + } + + private long[] cover(int x, int z) { + int snow = 0; + int ice = 0; + long fingerprint = 0xcbf29ce484222325L; + BlockPos.MutableBlockPos column = new BlockPos.MutableBlockPos(); + // Count the exactly populated 16-column offsets, outside the measured interval. + for (int dz = 2 * 16 + 8; dz < (SIZE - 2) * 16 + 8; dz++) { + for (int dx = 2 * 16 + 8; dx < (SIZE - 2) * 16 + 8; dx++) { + BlockPos height = world.getPrecipitationHeight(column.setPos(x * 16 + dx, 0, z * 16 + dz)); + BlockPos below = height.down(); + int snowY = world.getBlockState(height).getBlock() == Blocks.SNOW_LAYER ? height.getY() + : world.getBlockState(below).getBlock() == Blocks.SNOW_LAYER ? below.getY() : -1; + int iceY = world.getBlockState(below).getBlock() == Blocks.ICE ? below.getY() + : world.getBlockState(below.down()).getBlock() == Blocks.ICE ? below.getY() - 1 : -1; + if (snowY >= 0) snow++; + if (iceY >= 0) ice++; + fingerprint = (fingerprint ^ (snowY + 1L) ^ (iceY + 1L) << 9) * 0x100000001b3L; + } + } + return new long[]{snow, ice, fingerprint}; + } + + private static long gc(boolean time) { + long sum = 0; + for (GarbageCollectorMXBean collector : ManagementFactory.getGarbageCollectorMXBeans()) { + sum += Math.max(0, time ? collector.getCollectionTime() : collector.getCollectionCount()); + } + return sum; + } + + private static double p(long[] sorted, double quantile) { + return sorted.length == 0 ? Double.NaN : ms(sorted[(int) Math.ceil(sorted.length * quantile) - 1]); + } + + private static double ms(long ns) { + return ns / 1_000_000.0; + } + + private static void require(boolean condition, String description) { + if (!condition) throw new IllegalStateException("WORLDGEN_PERF FAILED: " + description); + } + + private static void verifySetting(WorldServer world) { + try { + Class state = Class.forName("zone.moddev.mc.skysrealisticweather.game.WeatherState"); + Object frame = state.getMethod("frame", net.minecraft.world.World.class).invoke(null, world); + Object settings = frame.getClass().getField("settings").get(frame); + require((Boolean) settings.getClass().getMethod("seasonalWorldgen").invoke(settings) == "on".equals(PROFILE), "generation switch"); + require((Boolean) frame.getClass().getMethod("active").invoke(frame), "active weather"); + } catch (ReflectiveOperationException e) { throw new IllegalStateException(e); } + } +} diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/core/WeatherTransformer.java b/src/main/java/zone/moddev/mc/skysrealisticweather/core/WeatherTransformer.java index 8e6d1f3..399dfb1 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/core/WeatherTransformer.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/core/WeatherTransformer.java @@ -276,6 +276,18 @@ private static void patchServer(ClassNode type) { } private static void patchChunk(ClassNode type) { + int populations=0; + for(MethodNode method:type.methods)for(AbstractInsnNode instruction:method.instructions.toArray()) { + if(!(instruction instanceof MethodInsnNode)||instruction.getOpcode()!=INVOKEINTERFACE)continue; + MethodInsnNode call=(MethodInsnNode)instruction; + if(!FMLDeobfuscatingRemapper.INSTANCE.map(call.owner).equals("net/minecraft/world/chunk/IChunkGenerator") + ||!matches(call.owner,call.name,call.desc,"populate","func_185931_b","(II)V"))continue; + method.instructions.insertBefore(call,new VarInsnNode(ALOAD,0)); + method.instructions.set(call,hook("zone/moddev/mc/skysrealisticweather/game/PlantGrowthHooks","populateChunk", + "(Lnet/minecraft/world/chunk/IChunkGenerator;II"+CHUNK+")V")); + populations++; + } + expect(populations,1,"population farming scope"); MethodNode set = method(type, "setBlockState", "func_177436_a", "(" + POS + STATE + ")" + STATE); int exits = 0; for (AbstractInsnNode instruction : set.instructions.toArray()) { diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/game/PlantGrowthHooks.java b/src/main/java/zone/moddev/mc/skysrealisticweather/game/PlantGrowthHooks.java index 95c407b..320892e 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/game/PlantGrowthHooks.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/game/PlantGrowthHooks.java @@ -26,6 +26,7 @@ public final class PlantGrowthHooks { public static final PlantGrowthHooks INSTANCE = new PlantGrowthHooks(); private static final Map, Map> METHODS = new ConcurrentHashMap<>(); private static final ThreadLocal FERTILIZING = ThreadLocal.withInitial(() -> false); + private static final ThreadLocal> POPULATING = new ThreadLocal<>(); private static final Map, Method> SAPLING_FERTILIZERS = new ConcurrentHashMap<>(); private static Field forestryManager; private static Method forestryPosition, forestryTemperature; @@ -59,6 +60,7 @@ public void crop(BlockEvent.CropGrowEvent.Pre event) { @SubscribeEvent(priority = EventPriority.LOWEST) public void tree(SaplingGrowTreeEvent event) { + if (populating(event.getWorld())) return; if (!event.getWorld().isBlockLoaded(event.getPos(), false)) return; net.minecraft.block.Block block = event.getWorld().getBlockState(event.getPos()).getBlock(); if (block instanceof net.minecraft.block.BlockSapling && PlantHookStatus.fallback("net.minecraft.block.BlockSapling") @@ -92,6 +94,7 @@ public static int naturalRoll(Random random, int bound, World world, BlockPos po } public static boolean allow(World world, BlockPos pos, Random random) { + if (populating(world)) return true; WeatherState.Frame frame = WeatherState.frame(world); if (world.isRemote || frame == null || !frame.active() || !frame.settings.farming.enabled || !world.isBlockLoaded(pos, false)) return true; PlantGrowthSample sample = sample(world, pos); @@ -100,6 +103,19 @@ public static boolean allow(World world, BlockPos pos, Random random) { return multiplier >= 1 || multiplier > 0 && random.nextFloat() < multiplier; } + /** Preserve native generation callbacks, including parks that explicitly grow saplings. */ + public static void populateChunk(net.minecraft.world.chunk.IChunkGenerator generator,int x,int z,net.minecraft.world.chunk.Chunk chunk) { + Deque worlds=POPULATING.get(); + if(worlds==null){worlds=new ArrayDeque<>();POPULATING.set(worlds);} + worlds.push(chunk.getWorld()); + try {generator.populate(x,z);} + finally {worlds.pop();if(worlds.isEmpty())POPULATING.remove();} + } + + private static boolean populating(World world) { + Deque worlds=POPULATING.get();return worlds!=null&&worlds.contains(world); + } + public static PlantGrowthSample sample(World world, BlockPos pos) { WeatherState.Frame frame = WeatherState.frame(world); if (frame == null || !world.isBlockLoaded(pos, false)) return null; diff --git a/src/test/java/zone/moddev/mc/skysrealisticweather/core/GenerationHooksTest.java b/src/test/java/zone/moddev/mc/skysrealisticweather/core/GenerationHooksTest.java index 1abb5de..3127729 100644 --- a/src/test/java/zone/moddev/mc/skysrealisticweather/core/GenerationHooksTest.java +++ b/src/test/java/zone/moddev/mc/skysrealisticweather/core/GenerationHooksTest.java @@ -10,6 +10,24 @@ import static org.junit.jupiter.api.Assertions.*; final class GenerationHooksTest { + @Test + void nativeChunkPopulationScopesFarmingHooks() throws Exception { + String target="net.minecraft.world.chunk.Chunk"; + byte[] original; + try(InputStream stream=getClass().getResourceAsStream("/"+target.replace('.','/')+".class")) { + assertNotNull(stream);ByteArrayOutputStream bytes=new ByteArrayOutputStream();byte[] buffer=new byte[8192];int count; + while((count=stream.read(buffer))>=0)bytes.write(buffer,0,count);original=bytes.toByteArray(); + } + ClassNode type=new ClassNode();new ClassReader(new WeatherTransformer().transform(null,target,original)).accept(type,0); + int wrappers=0; + for(MethodNode method:type.methods)for(AbstractInsnNode instruction:method.instructions.toArray())if(instruction instanceof MethodInsnNode) { + MethodInsnNode call=(MethodInsnNode)instruction; + if(call.owner.equals("zone/moddev/mc/skysrealisticweather/game/PlantGrowthHooks")&&call.name.equals("populateChunk")) { + wrappers++;new Analyzer<>(new BasicVerifier()).analyze(type.name,method); + } + } + assertEquals(1,wrappers,"natural farming gates must not intercept a generator's sapling callbacks"); + } @Test void nativeOverworldPopulationUsesSeasonalSnowIceAndOwnership() throws Exception { String target = "net.minecraft.world.gen.ChunkProviderOverworld"; From 6160f2f4728aa015a691622637b02c28f7db8b85 Mon Sep 17 00:00:00 2001 From: JohnBraham Date: Fri, 27 Nov 2026 14:37:53 +0000 Subject: [PATCH 3/9] Fit JEI climate pages and qualify the 1.11.2 client --- docs/BUILDING.md | 28 +++ docs/JEI_CLIENT_1_11_2.md | 89 ++++++++++ docs/PACK_SUPPORT.md | 3 + docs/PERFORMANCE_1_11_2.md | 6 +- docs/PORTING_1_11_2.md | 12 +- docs/PROJECT_DESCRIPTION.md | 2 +- scripts/Run-JeiClientChecks.py | 71 ++++++++ scripts/verification_clients.py | 3 +- .../verify/ClientProbe.java | 5 + .../verify/WeatherProbe.java | 1 + .../verify/jei/JeiClientProbe.java | 164 ++++++++++++++++++ .../verify/jei/JeiServerProbe.java | 51 ++++++ .../compat/JeiClimatePlugin.java | 20 ++- 13 files changed, 441 insertions(+), 14 deletions(-) create mode 100644 docs/JEI_CLIENT_1_11_2.md create mode 100644 scripts/Run-JeiClientChecks.py create mode 100644 src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/jei/JeiClientProbe.java create mode 100644 src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/jei/JeiServerProbe.java diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 2380f3a..1319220 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -139,6 +139,7 @@ BelowNormal priority and use fresh disposable worlds. The client runtime must contain the pinned Forge installation, Minecraft assets and Windows natives. `WEATHER_CLIENT_RUNTIME` and `WEATHER_SERVER_RUNTIME` can override the installed runtime locations in `scripts/verification_clients.py`. +`WEATHER_CLIENT_ASSETS` can select a separate complete Minecraft assets folder. Create the BOP calibration receipt with the controls below before running the four-provider generation comparison. @@ -195,6 +196,33 @@ The resulting cold comparison still requires matching base biomes and height maps and exact summer blocks. Its winter timings include the real population effects of snow and ice; they are not an equal-decoration microbenchmark. +## JEI client checks + +```text +gradlew check build writeReleaseChecksum prepareRuntimeProbe +python scripts/Run-JeiClientChecks.py --profile vanilla --output build/verification/jei-client-1112/ +python scripts/Run-JeiClientChecks.py --profile combined --output build/verification/jei-client-1112/ +python scripts/Run-JeiClientChecks.py --profile disabled --output build/verification/jei-client-1112/ +``` + +Each profile uses one packaged JEI 4.5.1.296 client and a fresh dedicated server. +The client is muted, capped at 10 FPS, BelowNormal and on a non-input Windows +desktop. Its ordinary guest player opens native JEI recipe screens, checks +server crop overrides and changing local temperatures, then disconnects/rejoins. +Screenshots cover 800 x 480 and 1280 x 720 at GUI scale 2. The combined profile +adds the pinned HarvestCraft, Mystical Agriculture and Forestry jars. The +disabled profile checks that ordinary JEI remains usable without the climate +category. + +The runner reads complete launcher assets from `%APPDATA%/.minecraft/assets` +by default. Pass `--assets ` or set +`WEATHER_CLIENT_ASSETS` to use another location. It verifies the original 1.11 +asset index and every indexed object before launch, without modifying them. +An incomplete runtime can leave Minecraft's current language unavailable and +crash JEI before a world opens. Client checks therefore require actual assets, +including language and pack metadata, even when sound is muted. +See [JEI client results](JEI_CLIENT_1_11_2.md) for the tested layouts and fix. + ## Acceptance scope Unit tests verify native renderer and Overworld generation bytecode as well as diff --git a/docs/JEI_CLIENT_1_11_2.md b/docs/JEI_CLIENT_1_11_2.md new file mode 100644 index 0000000..35fcc25 --- /dev/null +++ b/docs/JEI_CLIENT_1_11_2.md @@ -0,0 +1,89 @@ +# Minecraft 1.11.2 JEI client checks + +Packaged JEI **4.5.1.296** client checks and screenshot review passed on +27 November 2026, using Forge **13.20.1.2588** and the local **0.1.21.111021** +candidate. The checks found and corrected a recipe-panel layout problem. +Code and binaries remain local and unpublished. + +| Profile | Climate entries | Result | +| --- | ---: | --- | +| Weather + JEI + vanilla content | 44 | Pass | +| Also HarvestCraft 1.11.2h, Mystical Agriculture 1.5.9 and Forestry 5.3.4.257 | 386 | Pass | +| JEI installed, weather integration disabled | 0 | Native JEI remains usable | + +Each profile uses an ordinary guest player on a fresh dedicated server with no +operators. The server overrides wheat's profile; its preferred range appears as +**10.0–25.6 °C** or **50.0–78.0 °F** in JEI, rather than using the client's +default wheat rule. A synchronized API temperature zone changes between +**20 °C**, **-15 °C** and **45 °C**, exercising suitable, too-cold and too-hot +readouts and recovery. + +## Client coverage + +- Seed and harvested-produce lookups discover the climate category through + JEI's native recipe registry and focus API. +- Actual JEI recipe screens render the seed, preferred range, growth limits, + current suitability and all four local seasonal estimates. +- Celsius and Fahrenheit switch independently of server rules. Heated-zone + values update the live reading; seasonal estimates still exclude heating. +- The compact summary fits inside JEI's real header, borders and recipe area at + **800 x 480** and **1280 x 720**, both at GUI scale 2. +- Hovering over **?** opens the complete native tooltip, including the local + temperature source. Ordinary body text does not trigger an obscuring tooltip. +- HarvestCraft items are indexed alongside vanilla plants. Mystical Agriculture + crops retain their default climate exemptions. The combined catalogue has + 200 HarvestCraft and 138 Mystical Agriculture entries. An extended combined + check also opens and renders HarvestCraft's Blackberry Seed and Mystical + Agriculture's Inferium Seeds pages, confirming their ordinary and exempt + readouts respectively. +- Disconnecting removes climate recipes and makes retained entries report + unavailable climate safely. Rejoining rebuilds the catalogue without duplicate + entries and restores the server rule and live temperature. +- With the JEI bridge disabled, its climate category stays absent while ordinary + bread recipes open normally, including after reconnecting. + +## Layout correction + +The original 212 x 160 recipe background exceeded JEI 4's compact 196 x 166 +window, whose dimensions also include its header and borders. Screenshots showed +text outside the panel and overlapping the header. The wrapper also opened its +full tooltip over most of the summary whenever the pointer crossed ordinary text. + +The background now uses 172 x 124, with shorter summary wording and a dedicated +**?** marker for full details. The preferred range, live status, four seasonal +estimates and their weather/heating qualification remain visible. A new native +client regression fails against the previous build and passes after the fix; +it checks the actual JEI panel bounds and tooltip hit area. + +## Candidate and evidence + +Main jar SHA-256: + +```text +ef4b2095af5199ac6e58d71822b68807285ad3b55c57518b644fc8060c2e1686 +``` + +The build and all **57 unit tests** pass. Only `JeiClimatePlugin` and its three +nested class files differ from the multiplayer/performance candidate. All other +release entries are byte-identical, including weather, farming, world generation, +networking and heating. The [earlier generation and multiplayer report](PERFORMANCE_1_11_2.md) +keeps its original candidate hash; those workloads were not rerun for this +client-only layout correction. No third-party jar was changed. + +Raw logs, screenshots, artifact/source hashes and unsuccessful attempts are +retained under ignored `build/verification/jei-client-1112`. Its `RESULT.md` +and `qualified-receipts.json` index the evidence. An early launch used incomplete +Minecraft assets and failed in JEI's language lookup; another fixture used the +wrong crop-config section. Both remain recorded. The runner now verifies the +original asset index and all 1,196 referenced asset objects before launch. + +Tests ran one profile at a time. The client used a separate non-input Windows +desktop, muted sound, a 10 FPS cap and BelowNormal priority; the server and +client each used one logical CPU. No desktop switch or computer-control session +was needed. All worlds were disposable; no player world was copied or launched. +All test clients and servers have stopped. +See [reproduction instructions](BUILDING.md#jei-client-checks). + +This completes the documented JEI client checks for the pinned builds and tested +English layouts. General manual gameplay and visual acceptance remain separate +from these targeted checks. diff --git a/docs/PACK_SUPPORT.md b/docs/PACK_SUPPORT.md index ccae517..e7a6cd1 100644 --- a/docs/PACK_SUPPORT.md +++ b/docs/PACK_SUPPORT.md @@ -104,6 +104,9 @@ position. Phase estimates exclude weather episodes and local heating; native soil/light requirements still apply. Moving, changing season or heating an area changes the displayed live reading. The item catalogue is indexed once per joined world, rather than scanned every frame. +The compact recipe panel includes a **?** marker: hover over it for full +details, including the local temperature source. The summary stays readable +while the pointer is over its ordinary text. Hwyla **1.8.22-B37** and The One Probe **1.4.19** show the same current crop requirements and growth status when looking at a plant. Rules and climate data diff --git a/docs/PERFORMANCE_1_11_2.md b/docs/PERFORMANCE_1_11_2.md index 294d303..bf182f5 100644 --- a/docs/PERFORMANCE_1_11_2.md +++ b/docs/PERFORMANCE_1_11_2.md @@ -7,8 +7,10 @@ Plenty's small winter increase. BOP's winter elapsed time increased more than its CPU time, so this is not a claim of zero overhead. These results apply to Forge **13.20.1.2588** and the pinned builds below. The -candidate remains local and unpublished; manual gameplay and JEI client -acceptance remain separate. See [port status](PORTING_1_11_2.md) and +candidate remains local and unpublished; general manual gameplay remains separate. +Subsequent [JEI client qualification](JEI_CLIENT_1_11_2.md) changed only JEI class +files and has its own updated jar hash. Timings here retain the original tested +candidate. See [port status](PORTING_1_11_2.md) and [reproduction instructions](BUILDING.md). ## Whole-chunk generation diff --git a/docs/PORTING_1_11_2.md b/docs/PORTING_1_11_2.md index a11267d..7cac507 100644 --- a/docs/PORTING_1_11_2.md +++ b/docs/PORTING_1_11_2.md @@ -40,7 +40,7 @@ establish client visual acceptance. | [Forestry](https://www.curseforge.com/minecraft/mc-mods/forestry/files/2542509) | 1.11.2 | 5.3.4.257 | Ambient climate info, humidity and controlled-room precedence | | [CraftTweaker](https://www.curseforge.com/minecraft/mc-mods/crafttweaker/files/2838724) | 1.11.2 | 3.1.0-legacy, file 2838724 | Startup/reload rules, scripts, synchronized snapshots | | [Tough As Nails](https://modrinth.com/mod/tough-as-nails/version/rVR7XpTd) | 1.11.2 | 2.1.0.65 | Ambient correction, heated zones and restored seasonal ownership | -| [JEI](https://www.curseforge.com/minecraft/mc-mods/jei/files/2461378) | 1.11.2 | 4.5.1.296 | API compilation and dedicated-server optional-side loading; client UI acceptance pending | +| [JEI](https://www.curseforge.com/minecraft/mc-mods/jei/files/2461378) | 1.11.2 | 4.5.1.296 | Native client category, live units/suitability, optional plants, disabled bridge and reconnect checks; dedicated-server loading | | [Hwyla](https://www.curseforge.com/minecraft/mc-mods/hwyla/files/2496989) | 1.11.2 | 1.8.22-B37 | Registered provider, server data and ordinary-crop climate presentation | | [The One Probe](https://www.curseforge.com/minecraft/mc-mods/the-one-probe/files/2496984) | 1.11.2 | 1.4.19 with CompatLayer 0.3.1 | Provider registration and crop climate presentation | | [Biomes O' Plenty](https://www.curseforge.com/minecraft/mc-mods/biomes-o-plenty/files/2536549) | 1.11.2 | 6.2.0.2319 | Climate mapping and native seasonal population | @@ -97,6 +97,12 @@ dense winter snow and ice. See [multiplayer and performance results](PERFORMANCE for timings, the Lost Cities park-tree fix, BOP's native decoration variability and the isolated downstream effects of winter cover. +[JEI client checks and screenshot review](JEI_CLIENT_1_11_2.md) are also complete +for the pinned build. They corrected a compact recipe-panel overflow and moved +full details to a dedicated hover marker. Only JEI integration class files +changed after multiplayer/performance qualification; the client report records +the updated jar hash separately from the earlier server qualification. + Local checks and their candidate hashes are retained under `build/verification/port-1.11.2` for initial qualification and `build/verification/multiplayer-performance-1112` for the corrected candidate. @@ -104,8 +110,8 @@ See `RESULT.md` and artifact-bound receipts in each, including preserved unsuccessful attempts. [Build instructions](BUILDING.md) explain how to repeat the checks with fresh disposable worlds. -The port is local and unpublished. Manual client gameplay and visual acceptance, -including JEI's client category, remain separate acceptance work. Automated +The port is local and unpublished. General manual client gameplay and visual +acceptance remain separate work. Targeted JEI client checks, automated two-client multiplayer and the new whole-chunk baseline are complete for the documented scenarios. Published 1.10.2 timings and the 1.10.2 Sylvester pack are not used to claim 1.11.2 coverage. No player world is launched by these tests. diff --git a/docs/PROJECT_DESCRIPTION.md b/docs/PROJECT_DESCRIPTION.md index bce9abc..2a4ef9f 100644 --- a/docs/PROJECT_DESCRIPTION.md +++ b/docs/PROJECT_DESCRIPTION.md @@ -64,7 +64,7 @@ All integrations are optional. The table lists the Minecraft versions each integ | **Base Metals** | 1.10.2, 1.11.2 | Supplies mercury for the thermometer recipe. Other mods providing the appropriate mercury ingredient can also be used. | The 1.11.2 entries describe the local port and its pinned integration builds; -that version is not published yet. JEI client UI acceptance is still pending. +that version is not published yet. Its packaged JEI client checks are complete. See the [version support guide](https://github.com/MinecraftModDevelopmentMods/SkysRealisticWeather/wiki/Version-Support) for current qualification and download status. ## Tools for players and pack makers diff --git a/scripts/Run-JeiClientChecks.py b/scripts/Run-JeiClientChecks.py new file mode 100644 index 0000000..f46c2c7 --- /dev/null +++ b/scripts/Run-JeiClientChecks.py @@ -0,0 +1,71 @@ +"""Check the real JEI client UI on a non-input desktop, using disposable worlds.""" +from pathlib import Path +import argparse,ctypes,hashlib,json,os,shutil,socket,subprocess,time +from verification_clients import Client,client_command,k,u + +root=Path(__file__).resolve().parents[1];digest=lambda p:hashlib.sha256(p.read_bytes()).hexdigest() +parser=argparse.ArgumentParser(description=__doc__) +parser.add_argument('--profile',choices=['vanilla','combined','disabled'],required=True) +parser.add_argument('--output',type=Path,required=True) +parser.add_argument('--assets',type=Path,default=Path(os.environ.get('WEATHER_CLIENT_ASSETS',str(Path(os.environ['APPDATA'])/'.minecraft/assets'))),help='Complete launcher assets; read only') +args=parser.parse_args();output=args.output.resolve();assert output.is_relative_to(root/'build/verification');output.mkdir(parents=True,exist_ok=False) +assets=args.assets.resolve();index=assets/'indexes/1.11.json' +assert hashlib.sha1(index.read_bytes()).hexdigest()=='c64959fe73672e9b053b157f57b6aba318d0b3b5','Need the original complete 1.11 assets' +objects=json.loads(index.read_text())['objects'] +for item in objects.values(): + f=assets/'objects'/item['hash'][:2]/item['hash'];assert f.is_file() and hashlib.sha1(f.read_bytes()).hexdigest()==item['hash'],'Missing or invalid asset: '+str(f) +os.environ['WEATHER_CLIENT_ASSETS']=str(assets) +build=json.loads((root/'build/verification/probe/probe-build.json').read_text()) +for name,h in build['source_sha256'].items():assert digest(root/name)==h,'Rebuild source: '+name +main=next(f for f in (root/'build/libs').glob('*.jar') if digest(f)==build['main_sha256']) +probe=root/'build/verification/probe/skyweather-probe.jar' +mods=[main,probe,root/'build/compatibility-mods/published/JEI.jar'] +if args.profile=='combined':mods += [root/'build/compatibility-mods/published'/name for name in ['HarvestCraft.jar','MysticalAgriculture.jar','Forestry.jar']] +hashes={f.name:digest(f) for f in mods};server=output/'server';client=output/'client' +fixture=root/'build/verification/runtime-fixture';forge='forge-1.11.2-13.20.1.2588-universal.jar' +for directory in [server,client]: + (directory/'mods').mkdir(parents=True);(directory/'config').mkdir() + for f in mods:shutil.copy2(f,directory/'mods'/f.name) + if args.profile=='disabled':(directory/'config/skysrealisticweather.cfg').write_text('integrations {\n B:jei=false\n}\n') +for name in [forge,'minecraft_server.1.11.2.jar','eula.txt','whitelist.json','banned-ips.json','banned-players.json']:shutil.copy2(fixture/name,server/name) +(server/'ops.json').write_text('[]') +quote=lambda p:"'"+str(p).replace("'","''")+"'" +subprocess.run(['powershell','-NoProfile','-Command','New-Item -ItemType Junction -Path '+quote(server/'libraries')+' -Target '+quote((fixture/'libraries').resolve())+' | Out-Null'],check=True,creationflags=subprocess.CREATE_NO_WINDOW) +with socket.socket() as sock:sock.bind(('127.0.0.1',0));port=sock.getsockname()[1] +(server/'server.properties').write_text(f'level-type=FLAT\nlevel-name=world\nlevel-seed=123948\nserver-ip=127.0.0.1\nserver-port={port}\nonline-mode=false\nmax-tick-time=-1\nview-distance=3\nspawn-npcs=false\nspawn-monsters=false\nspawn-animals=false\ndifficulty=0\ngenerate-structures=false\nallow-flight=true\nsnooper-enabled=false\ngenerator-settings=3;minecraft:bedrock,79*minecraft:dirt,minecraft:grass;1;\n') +config=server/'config/skysrealisticweather.cfg' +with config.open('a') as f:f.write('plant_growth {\n S:mappings <\n minecraft:wheat=temperate\n >\n}\n') +(client/'options.txt').write_text('renderDistance:3\nguiScale:2\npauseOnLostFocus:false\nenableVsync:false\nmaxFps:10\nclouds:false\nsoundCategory_master:0.0\nsoundCategory_music:0.0\n') +inputs=output/'inputs';inputs.mkdir() +for f in [Path(__file__),root/'scripts/verification_clients.py',root/'build/verification/probe/probe-build.json',*list((root/'src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/jei').glob('*.java'))]:shutil.copy2(f,inputs/f.name) +java=Path.home()/'.gradle/jdks/temurin-8-amd64-windows.2/bin/java.exe' +command=[str(java),'-Xms128m','-Xmx1g','-XX:+UseSerialGC','-XX:ActiveProcessorCount=1','-XX:CICompilerCount=2','-Dskyweather.probe=jei-client','-jar',forge,'nogui'] +process=None;c=None;desktop=None;passed=False;error=None;start=time.monotonic() +try: + with (server/'server.log').open('wb') as log: + process=subprocess.Popen(command,cwd=server,stdin=subprocess.PIPE,stdout=log,stderr=subprocess.STDOUT,creationflags=subprocess.CREATE_NO_WINDOW|subprocess.BELOW_NORMAL_PRIORITY_CLASS) + assert k.SetProcessAffinityMask(int(process._handle),1<deadline:raise RuntimeError('Server startup failed; see retained log') + time.sleep(.25) + name='WeatherJei'+str(os.getpid());desktop=u.CreateDesktopW(name,None,None,0,0x10000000,None);assert desktop,ctypes.WinError(ctypes.get_last_error()) + c=Client(client_command(client,'JeiTester',['skyweather.jeiClient=true','skyweather.port='+str(port),'jeiprobe.disabled='+str(args.profile=='disabled').lower(),'file.encoding=UTF-8']),client,'WinSta0\\'+name,min(19,(os.cpu_count()or 1)-1)) + print('JEI client',c.pid,'hidden, muted, 10 FPS',flush=True);deadline=time.monotonic()+420 + while True: + clientlog=(client/'client.log').read_text(encoding='utf8',errors='replace');serverlog=(server/'server.log').read_text(encoding='utf8',errors='replace') + if 'JEI_CLIENT PASS' in clientlog and 'JEI_SERVER PASS' in serverlog:passed=True;break + if c.poll() is not None or process.poll() is not None or time.monotonic()>deadline or 'JEI_CLIENT_FAIL' in clientlog:raise RuntimeError('JEI check failed or timed out; see retained logs') + time.sleep(.25) +except Exception as e:error=repr(e);print(error,flush=True) +finally: + if c:c.close() + if process and process.poll() is None: + try:process.stdin.write(b'stop\n');process.stdin.flush();process.wait(timeout=25) + except Exception:process.terminate();process.wait() + if desktop:u.CloseDesktop(desktop) + unchanged=all(digest(d/'mods'/f.name)==hashes[f.name] for d in [server,client] for f in mods) + passed=passed and unchanged + result=dict(passed=passed,error=error,profile=args.profile,main_sha256=digest(main),probe_sha256=digest(probe),artifacts=hashes,original_jars_unchanged=unchanged,assets_index_sha1=hashlib.sha1(index.read_bytes()).hexdigest(),verified_asset_objects=len(objects),seconds=round(time.monotonic()-start,2),server_pid=None if process is None else process.pid,client_pid=None if c is None else c.pid,priority='BelowNormal',server_cpu=20,client_cpu=19,fps=10,muted=True,desktop='non-input; never switched',inputs_sha256={f.name:digest(f) for f in inputs.iterdir()}) + (output/'result.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) +assert passed,'Retained failed JEI attempt: '+str(output) diff --git a/scripts/verification_clients.py b/scripts/verification_clients.py index c937a62..5622d0b 100644 --- a/scripts/verification_clients.py +++ b/scripts/verification_clients.py @@ -39,6 +39,7 @@ def close(self): k.CloseHandle(self.info.hProcess);self.log.close();self.null.close() def client_command(directory,name,options): cache=Path(os.environ.get('WEATHER_CLIENT_RUNTIME','D:/MinecraftMineralogy/packaged-runtime-cache/forge-1.11.2-13.20.1.2588-client'));engine=Path(os.environ.get('WEATHER_SERVER_RUNTIME','D:/MinecraftMineralogy/packaged-runtime-cache/forge-1.11.2-13.20.1.2588')) + assets=Path(os.environ.get('WEATHER_CLIENT_ASSETS',str(cache/'assets'))) with zipfile.ZipFile(engine/'forge-1.11.2-13.20.1.2588-installer.jar') as z:forge=json.loads(z.read('install_profile.json'))['versionInfo'] mc=json.loads((cache/'versions/1.11.2/1.11.2.json').read_text());cp=[cache/'versions/1.11.2/1.11.2.jar',engine/'forge-1.11.2-13.20.1.2588-universal.jar'];seen=set() def library(path): @@ -57,4 +58,4 @@ def library(path): if key in seen:continue seen.add(key);cp.append(library(f'{group.replace(".","/")}/{artifact}/{version}/{artifact}-{version}.jar')) java=Path.home()/'.gradle/jdks/temurin-8-amd64-windows.2/bin/java.exe' - return [str(java),'-Xms128m','-Xmx768m','-XX:+UseSerialGC','-XX:ActiveProcessorCount=1','-XX:CICompilerCount=2','-Dfml.ignoreInvalidMinecraftCertificates=true','-Djava.library.path='+str(cache/'natives'),*['-D'+v for v in options],'-cp',os.pathsep.join(map(str,cp)),'net.minecraft.launchwrapper.Launch','--tweakClass','net.minecraftforge.fml.common.launcher.FMLTweaker','--username',name,'--uuid',uuid.uuid3(uuid.NAMESPACE_DNS,name).hex,'--accessToken','0','--userType','legacy','--version','1.11.2','--gameDir',str(directory),'--assetsDir',str(cache/'assets'),'--assetIndex',mc['assetIndex']['id'],'--width','800','--height','480'] + return [str(java),'-Xms128m','-Xmx768m','-XX:+UseSerialGC','-XX:ActiveProcessorCount=1','-XX:CICompilerCount=2','-Dfml.ignoreInvalidMinecraftCertificates=true','-Djava.library.path='+str(cache/'natives'),*['-D'+v for v in options],'-cp',os.pathsep.join(map(str,cp)),'net.minecraft.launchwrapper.Launch','--tweakClass','net.minecraftforge.fml.common.launcher.FMLTweaker','--username',name,'--uuid',uuid.uuid3(uuid.NAMESPACE_DNS,name).hex,'--accessToken','0','--userType','legacy','--version','1.11.2','--gameDir',str(directory),'--assetsDir',str(assets),'--assetIndex',mc['assetIndex']['id'],'--width','800','--height','480'] diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java index 45b7f21..3543b5c 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java @@ -55,6 +55,7 @@ public final class ClientProbe extends WeatherProbe.SideProbe { private int modeUiStage; private GuiScreen modeRoot; private TemperatureClientProbe thermal; + private zone.moddev.mc.skysrealisticweather.verify.jei.JeiClientProbe jei; @Override public void register() { @@ -65,6 +66,10 @@ public void register() { public void tick(TickEvent.ClientTickEvent event) throws ReflectiveOperationException { if (event.phase != TickEvent.Phase.END) return; Minecraft game = Minecraft.getMinecraft(); + if (Boolean.getBoolean("skyweather.jeiClient")) { + if(jei==null)jei=new zone.moddev.mc.skysrealisticweather.verify.jei.JeiClientProbe(); + jei.tick(game);return; + } if (Boolean.getBoolean("skyweather.heatNetwork")) { if(thermal==null)thermal=new TemperatureClientProbe(); thermal.tick(game);return; diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java index edc5648..76c25a1 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java @@ -86,6 +86,7 @@ public void started(FMLServerStartedEvent event) { switch (MODE) { case "temperature-zones": TemperatureZoneProbe.run(world); break; case "thermal-network": new TemperatureNetworkProbe(world); break; + case "jei-client": new zone.moddev.mc.skysrealisticweather.verify.jei.JeiServerProbe(world); break; case "precipitation": PrecipitationProbe.run(world); break; case "thermometer": ThermometerProbe.run(world); break; case "plants": diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/jei/JeiClientProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/jei/JeiClientProbe.java new file mode 100644 index 0000000..f460797 --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/jei/JeiClientProbe.java @@ -0,0 +1,164 @@ +package zone.moddev.mc.skysrealisticweather.verify.jei; + +import java.io.File; +import java.lang.reflect.Field; +import java.util.*; +import mezz.jei.api.*; +import mezz.jei.api.gui.IRecipeLayoutDrawable; +import mezz.jei.api.recipe.*; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.*; +import net.minecraft.client.multiplayer.GuiConnecting; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ScreenShotHelper; +import net.minecraft.util.text.TextFormatting; +import net.minecraftforge.client.event.*; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; +import net.minecraftforge.fml.relauncher.*; +import zone.moddev.mc.skysrealisticweather.api.*; +import zone.moddev.mc.skysrealisticweather.climate.WeatherConfiguration; +import zone.moddev.mc.skysrealisticweather.compat.JeiClimatePlugin; +import zone.moddev.mc.skysrealisticweather.game.*; + +@JEIPlugin @SideOnly(Side.CLIENT) +public final class JeiClientProbe extends BlankModPlugin { + private static IJeiRuntime runtime; + private final boolean enabled=!Boolean.getBoolean("jeiprobe.disabled"); + private int stage=-1,ack=-1,ready,joins,draws,checks,catalogueSize; + private boolean registered,connecting,reconnect,complete,picture; + private IJeiRuntime oldRuntime; + private JeiClimatePlugin.Entry entry; + private ItemStack pamSeed,magicalSeed; + private String shot; + @Override public void onRuntimeAvailable(IJeiRuntime value){runtime=value;} + private void require(boolean condition,String message){checks++;if(!condition)throw new IllegalStateException("JEI_CLIENT_FAIL "+message);} + @SubscribeEvent public void chat(ClientChatReceivedEvent e) { + String s=e.getMessage().getUnformattedText(); + if(s.startsWith("JEI_STAGE:")){stage=Integer.parseInt(s.substring(10));ready=0;draws=0;} + else if(s.equals("JEI_RECONNECT"))reconnect=true; + else if(s.equals("JEI_COMPLETE"))complete=true; + } + public void tick(Minecraft game)throws ReflectiveOperationException { + if(!registered){registered=true;MinecraftForge.EVENT_BUS.register(this);} + if(complete){System.out.println("JEI_CLIENT PASS checks="+checks+" catalogue="+catalogueSize+" joins="+joins);game.shutdown();return;} + if(reconnect) { + reconnect=false;oldRuntime=runtime;game.world.sendQuittingDisconnectingPacket();game.loadWorld(null);game.displayGuiScreen(new GuiMainMenu());connecting=false;ready=0;return; + } + if(game.world==null) { + if(game.currentScreen instanceof GuiMainMenu||game.currentScreen instanceof net.minecraft.client.gui.GuiDisconnected) { + if(++ready<20)return; + if(oldRuntime!=null&&enabled) { + IRecipeCategory c=category(oldRuntime);require(c==null||oldRuntime.getRecipeRegistry().getRecipeWrappers(c).isEmpty(),"logout clears climate recipes"); + require(entry.description(game).equals(Collections.singletonList("Local climate unavailable")),"old entry safely handles no world"); + } + if(!connecting){connecting=true;joins++;game.displayGuiScreen(new GuiConnecting(new GuiMainMenu(),game,"127.0.0.1",Integer.getInteger("skyweather.port")));} + } + return; + } + if(game.player==null||runtime==null||WeatherState.frame(game.world)==null||stage<0||stage==ack)return; + connecting=false; + if(++ready==1)WeatherConfiguration.file().getCategory(WeatherConfiguration.CLIENT).get("temperatureUnit").set(stage==1||stage==3?"FAHRENHEIT":"CELSIUS"); + TemperatureSample local=WeatherApi.getTemperatureSample(game.world,game.player.getPosition()).orElse(null); + if(ready<25||local==null||local.source!=TemperatureSample.Source.ZONE)return; + float c=stage==1?-15:stage==2?45:20; + if(Math.abs(TemperatureDisplay.Unit.CELSIUS.temperature(local.temperature)-c)>.01)return; + IRecipeCategory category=category(runtime); + if(!enabled) { + require(category==null,"disabled weather bridge registers no climate category"); + if(draws==0){runtime.getRecipesGui().show(runtime.getRecipeRegistry().createFocus(IFocus.Mode.OUTPUT,new ItemStack(Items.BREAD)));draws=1;return;} + if(draws<5){draws++;return;} + require(game.currentScreen instanceof mezz.jei.gui.recipes.RecipesGui,"native JEI remains usable when bridge disabled"); + capture(game,"disabled-"+stage);finish(game);return; + } + if(category==null)return; + if(picture){picture=false;finish(game);return;} + if(draws>0)return; + IRecipeRegistry registry=runtime.getRecipeRegistry(); + List entries=registry.getRecipeWrappers(category);if(entries.isEmpty())return; + if(stage==0)catalogueSize=entries.size(); + if(stage==4){require(joins==2,"real client reconnect completed");require(entries.size()==catalogueSize,"rejoin rebuilds catalogue without duplicates");} + IFocus focus=registry.createFocus(IFocus.Mode.OUTPUT,new ItemStack(Items.WHEAT_SEEDS)); + List wheat=registry.getRecipeWrappers(category,focus);require(!wheat.isEmpty(),"seed recipe lookup discovers climate category");entry=wheat.get(0); + String text=TextFormatting.getTextWithoutFormattingCodes(String.join("\n",entry.description(game))); + System.out.println("JEI_DESCRIPTION stage="+stage+" entries="+entries.size()+"\n"+text); + String unit=WeatherConfiguration.temperatureUnit().symbol; + require(text.contains("Preferred temperature:")&&text.contains("Growth limits:")&&text.contains(unit),"requirements use selected display units"); + require(text.contains("Preferred temperature: "+(stage==1||stage==3?"50.0 °F to 78.0 °F":"10.0 °C to 25.6 °C")),"server crop override reaches JEI rather than client defaults"); + require(text.contains("Temperature source: zone")&&text.contains(WeatherConfiguration.temperatureUnit().format(local.temperature)),"live temperature uses server zone"); + require(text.contains("Spring:")&&text.contains("Summer:")&&text.contains("Autumn:")&&text.contains("Winter:")&&text.contains("Estimates exclude weather and heating."),"all seasonal estimates and qualification present"); + if(stage==1)require(text.contains("Too cold; natural growth paused")&&text.contains("5.0 °F"),"cold Fahrenheit status"); + if(stage==2)require(text.contains("Too hot; natural growth paused")&&text.contains("45.0 °C"),"hot Celsius status"); + if(stage==0||stage==3||stage==4)require(text.contains("Suitable; normal natural growth"),"warm suitability recovers"); + IRecipeLayoutDrawable layout=registry.createRecipeLayoutDrawable(category,entry,focus); + require(layout!=null&&!layout.getItemStacks().getGuiIngredients().get(0).isInput(),"native layout exposes output seed"); + require(entry.getTooltipStrings(50,40).isEmpty(),"body does not obscure the summary with a full tooltip"); + require(entry.getTooltipStrings(category.getBackground().getWidth()-5,5).equals(entry.description(game)),"information marker retains full details"); + require(!registry.getRecipeWrappers(category,registry.createFocus(IFocus.Mode.OUTPUT,new ItemStack(Items.WHEAT))).isEmpty(),"produce lookup discovers climate entry"); + if(stage==0&&Loader.isModLoaded("harvestcraft")) { + int pam=0,magic=0;boolean exempt=false; + for(JeiClimatePlugin.Entry e:entries) { + mezz.jei.ingredients.Ingredients ingredients=new mezz.jei.ingredients.Ingredients();e.getIngredients(ingredients); + for(List group:ingredients.getOutputs(ItemStack.class))for(ItemStack stack:group) { + String id=stack.getItem().getRegistryName().getResourceDomain(); + if(id.equals("harvestcraft")) { + pam++;if(pamSeed==null&&stack.getItem().getRegistryName().getResourcePath().contains("seed") + &&e.description(game).toString().contains("Preferred temperature:"))pamSeed=stack.copy(); + } + if(id.equals("mysticalagriculture")) { + magic++;if(e.description(game).toString().contains("No climate temperature limit (exempt)")) { + exempt=true;if(magicalSeed==null&&stack.getItem().getRegistryName().getResourcePath().contains("seeds"))magicalSeed=stack.copy(); + } + } + } + } + require(pam>50&&magic>0&&exempt&&pamSeed!=null&&magicalSeed!=null,"HarvestCraft entries and exempt magical crops are indexed"); + System.out.println("JEI_OPTIONAL_ITEMS pam="+pam+" magical="+magic); + } + ItemStack shown=stage==2&&pamSeed!=null?pamSeed:stage==3&&magicalSeed!=null?magicalSeed:new ItemStack(Items.WHEAT_SEEDS); + focus=registry.createFocus(IFocus.Mode.OUTPUT,shown); + entry=(JeiClimatePlugin.Entry)registry.getRecipeWrappers(category,focus).get(0); + if(stage==2&&pamSeed!=null)require(entry.description(game).toString().contains("Preferred temperature:"),"actual HarvestCraft page retains crop requirements"); + if(stage==3&&magicalSeed!=null)require(entry.description(game).toString().contains("No climate temperature limit (exempt)") + &&!entry.description(game).toString().contains("Preferred temperature:"),"actual magical seed page shows exemption"); + System.out.println("JEI_DISPLAY stage="+stage+" item="+shown.getItem().getRegistryName()+" details="+entry.description(game)); + if(stage==2){game.gameSettings.guiScale=2;game.resize(1280,720);} + runtime.getRecipesGui().show(focus); + GuiScreen screen=game.currentScreen;require(screen instanceof mezz.jei.gui.recipes.RecipesGui,"actual JEI recipe screen opens"); + Object logic=field(screen,"logic");logic.getClass().getMethod("setRecipeCategory",IRecipeCategory.class).invoke(logic,category); + shot="stage-"+stage;draws=1; + } + private IRecipeCategory category(IJeiRuntime r){return r.getRecipeRegistry().getRecipeCategories().stream().filter(c->c.getUid().equals(JeiClimatePlugin.CATEGORY)).findFirst().orElse(null);} + private static Object field(Object o,String name)throws ReflectiveOperationException{Field f=o.getClass().getDeclaredField(name);f.setAccessible(true);return f.get(o);} + @SubscribeEvent public void drawn(GuiScreenEvent.DrawScreenEvent.Post e)throws ReflectiveOperationException { + if(!enabled||draws==0||shot==null)return; + GuiScreen screen=e.getGui();if(!(screen instanceof mezz.jei.gui.recipes.RecipesGui))return; + List layouts=(List)field(screen,"recipeLayouts"); + require(!layouts.isEmpty(),"native GUI has a visible recipe layout"); + for(mezz.jei.gui.recipes.RecipeLayout l:layouts) { + require(l.getRecipeCategory().getUid().equals(JeiClimatePlugin.CATEGORY),"climate category is selected"); + mezz.jei.gui.recipes.RecipesGui gui=(mezz.jei.gui.recipes.RecipesGui)screen; + int w=l.getRecipeCategory().getBackground().getWidth(),h=l.getRecipeCategory().getBackground().getHeight(); + require(l.getPosX()>=gui.getGuiLeft()+6&&l.getPosX()+w<=gui.getGuiLeft()+gui.getXSize()-6,"recipe fits inside JEI's actual panel"); + require(l.getPosY()>=gui.getGuiTop()+(Integer)field(gui,"headerHeight")&&l.getPosY()+h<=gui.getGuiTop()+gui.getYSize()-5,"recipe clears JEI's header and bottom border"); + require(l.getPosX()+w<=screen.width&&l.getPosY()+h<=screen.height,"recipe panel fits scaled screen"); + } + draws++; + } + @SubscribeEvent public void rendered(TickEvent.RenderTickEvent e)throws ReflectiveOperationException { + if(e.phase!=TickEvent.Phase.END||shot==null||draws<5)return; + Minecraft game=Minecraft.getMinecraft();capture(game,shot); + if(stage==1) { + List layouts=(List)field(game.currentScreen,"recipeLayouts"); + mezz.jei.gui.recipes.RecipeLayout layout=layouts.get(0); + layout.drawOverlays(game,layout.getPosX()+layout.getRecipeCategory().getBackground().getWidth()-5,layout.getPosY()+5); + capture(game,shot+"-tooltip"); + } + shot=null;picture=true; + } + private void capture(Minecraft game,String name){ScreenShotHelper.saveScreenshot(new File("."),"jei-"+name+".png",game.displayWidth,game.displayHeight,game.getFramebuffer());} + private void finish(Minecraft game){System.out.println("JEI_CLIENT_STAGE PASS "+stage);game.displayGuiScreen(null);game.player.sendChatMessage("/jeiprobeack "+stage);ack=stage;} +} diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/jei/JeiServerProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/jei/JeiServerProbe.java new file mode 100644 index 0000000..d3014ec --- /dev/null +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/jei/JeiServerProbe.java @@ -0,0 +1,51 @@ +package zone.moddev.mc.skysrealisticweather.verify.jei; + +import net.minecraft.command.*; +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.text.TextComponentString; +import net.minecraft.world.WorldServer; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; +import zone.moddev.mc.skysrealisticweather.api.*; + +/** Ordinary guest client, controlled temperatures, and an actual disconnect/rejoin. */ +public final class JeiServerProbe { + private final WorldServer world; + private final ResourceLocation zone=new ResourceLocation("jeiprobe:room"); + private EntityPlayerMP joined; + private int stage,elapsed; + private boolean reconnect,complete; + public JeiServerProbe(WorldServer world) { + this.world=world;MinecraftForge.EVENT_BUS.register(this); + world.getGameRules().setOrCreateGameRule("doDaylightCycle","false");world.setWorldTime(134L*24000+6000); + put(20); + ((CommandHandler)world.getMinecraftServer().getCommandManager()).registerCommand(new CommandBase() { + public String getName(){return "jeiprobeack";} + public String getUsage(ICommandSender s){return "jeiprobeack ";} + public int getRequiredPermissionLevel(){return 0;} + @Override public boolean checkPermission(MinecraftServer s,ICommandSender p){return p instanceof EntityPlayerMP&&p.getName().equals("JeiTester");} + public void execute(MinecraftServer server,ICommandSender sender,String[] args)throws CommandException { + if(args.length!=1||parseInt(args[0],0,4)!=stage)return; + System.out.println("JEI_SERVER_STAGE PASS "+stage); + if(stage==3){reconnect=true;sender.sendMessage(new TextComponentString("JEI_RECONNECT"));return;} + if(stage==4){complete=true;sender.sendMessage(new TextComponentString("JEI_COMPLETE"));System.out.println("JEI_SERVER PASS");return;} + stage++;put(stage==1?-15:stage==2?45:20);announce((EntityPlayerMP)sender); + } + }); + System.out.println("JEI_SERVER_READY"); + } + private void put(float c){WeatherApi.putTemperatureZone(world,TemperatureZone.celsius(zone,new BlockPos(5,79,5),new BlockPos(11,84,11),c));} + private void announce(EntityPlayerMP p){p.sendMessage(new TextComponentString("JEI_STAGE:"+stage));} + @SubscribeEvent public void tick(TickEvent.WorldTickEvent e) { + if(e.world!=world||e.phase!=TickEvent.Phase.END||complete)return; + if(++elapsed>8000)throw new IllegalStateException("JEI server timeout at "+stage); + EntityPlayerMP p=world.getMinecraftServer().getPlayerList().getPlayerByUsername("JeiTester"); + if(p==null||p==joined)return; + if(reconnect)stage=4; + joined=p;p.connection.setPlayerLocation(8.25,81,8.25,0,0);announce(p); + } +} diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/compat/JeiClimatePlugin.java b/src/main/java/zone/moddev/mc/skysrealisticweather/compat/JeiClimatePlugin.java index 33e6b3b..8f22e35 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/compat/JeiClimatePlugin.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/compat/JeiClimatePlugin.java @@ -20,7 +20,8 @@ @SideOnly(Side.CLIENT) public final class JeiClimatePlugin extends BlankModPlugin { public static final String CATEGORY="skysrealisticweather.climate"; - private static final int WIDTH=212,HEIGHT=160; + // JEI 4's compact recipe window is 196 x 166, including its header and borders. + private static final int WIDTH=172,HEIGHT=124; private IJeiRuntime runtime; private List catalogue=Collections.emptyList(); private final List recipes=new ArrayList<>(); @@ -60,13 +61,16 @@ public List description(Minecraft game) { return lines; } @Override public void drawInfo(Minecraft game,int width,int height,int mouseX,int mouseY) { - game.fontRenderer.drawString(game.fontRenderer.trimStringToWidth(stack.getDisplayName(),WIDTH-25),24,5,0x404040); - int y=25; + game.fontRenderer.drawString(game.fontRenderer.trimStringToWidth(stack.getDisplayName(),WIDTH-38),24,5,0x404040); + game.fontRenderer.drawString("?",WIDTH-8,5,0x357C9D); + int y=24; for(String line:description(game)) { - if(line.contains("AgriCraft crop-stick growth"))continue; + if(line.contains("AgriCraft crop-stick growth")||line.startsWith("Typical local seasonal conditions:") + ||TextFormatting.getTextWithoutFormattingCodes(line).startsWith("Temperature source:"))continue; line=line.replace("Preferred temperature:","Preferred:").replace("Growth limits:","Limits:") - .replace("Temperature check only; soil, light and native conditions still apply","Native soil/light rules still apply.") - .replace("Typical local seasonal conditions:","Typical seasons:").replace("natural growth","growth"); + .replace("Temperature check only; soil, light and native conditions still apply","Native soil/light rules apply.") + .replace("Estimates exclude weather and heating.","Estimates omit weather/heating.") + .replace(" (controlled climate)","").replace("natural growth","growth"); int colour=line.contains(TextFormatting.RED.toString())?0xA52B2B:line.contains(TextFormatting.GREEN.toString())?0x286B32: line.contains(TextFormatting.YELLOW.toString())?0x846000:0x404040; for(String part:game.fontRenderer.listFormattedStringToWidth(TextFormatting.getTextWithoutFormattingCodes(line),WIDTH)) { @@ -75,7 +79,9 @@ public List description(Minecraft game) { } } } - @Override public List getTooltipStrings(int mouseX,int mouseY){return description(Minecraft.getMinecraft());} + @Override public List getTooltipStrings(int mouseX,int mouseY){ + return mouseX>=WIDTH-12&&mouseX=0&&mouseY<16?description(Minecraft.getMinecraft()):Collections.emptyList(); + } } private static final class Handler implements IRecipeHandler { public Class getRecipeClass(){return Entry.class;} From 25b4e3a8e352ec2406ddedd21942bbd1e51659f3 Mon Sep 17 00:00:00 2001 From: JohnBraham Date: Fri, 27 Nov 2026 14:58:43 +0000 Subject: [PATCH 4/9] Declare optional integrations and prepare CurseForge relations --- docs/BUILDING.md | 11 ++++ docs/PORTING_1_11_2.md | 3 ++ docs/PUBLISHING.md | 54 +++++++++++++++++++ publishing/curseforge-relations.json | 21 ++++++++ .../verify/WeatherProbe.java | 24 +++++++++ .../mc/skysrealisticweather/WeatherMod.java | 2 +- src/main/resources/mcmod.info | 25 ++++++++- 7 files changed, 138 insertions(+), 2 deletions(-) create mode 100644 docs/PUBLISHING.md create mode 100644 publishing/curseforge-relations.json diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 1319220..98a22a3 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -225,6 +225,17 @@ See [JEI client results](JEI_CLIENT_1_11_2.md) for the tested layouts and fix. ## Acceptance scope +Dependency metadata can be checked without a client: + +```text +python scripts/Run-RuntimeChecks.py --mode metadata --expect "SKY_WEATHER_CHECK METADATA PASS" --output build/verification/metadata/ +``` + +Add `--mod ` for each pinned jar to verify installed dependencies +load before weather. The check compares Forge's bound metadata with the actual +jar and confirms only Forge is mandatory. See [publishing](PUBLISHING.md) for +the separate CurseForge relationships. + Unit tests verify native renderer and Overworld generation bytecode as well as climate, network and API contracts. Packaged servers cover native hooks, crops, commands, temperature zones, crafting and save/reload. The distant-render probe diff --git a/docs/PORTING_1_11_2.md b/docs/PORTING_1_11_2.md index 7cac507..b859a01 100644 --- a/docs/PORTING_1_11_2.md +++ b/docs/PORTING_1_11_2.md @@ -26,6 +26,9 @@ Use a backup and a version-appropriate test pack for migration. - Tough As Nails uses `SeasonsOption` and its configurable temperature-scale midpoint; its body temperature, response timer and other modifiers remain native. - JEI uses the 4.x ingredient registry and category contract. +- `mcmod.info` declares the 17 version-appropriate integrations as optional + dependencies; only Forge is required. Matching CurseForge relation data is + prepared separately; see [dependency metadata and publishing](PUBLISHING.md). ## Integration builds diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md new file mode 100644 index 0000000..d474b9e --- /dev/null +++ b/docs/PUBLISHING.md @@ -0,0 +1,54 @@ +# Dependency metadata and CurseForge relations + +The 1.11.2 jar declares its 17 supported integrations as optional dependencies +in `mcmod.info`. Forge is the only required dependency. `useMetadata` and +`useDependencyInformation` enable those declarations; installed integration mods +load before Sky's Realistic Weather, while missing integrations do not prevent +startup. The annotation keeps the minimum Forge requirement as a fallback. +Supported builds are listed in [port status](PORTING_1_11_2.md). + +Forge mod IDs and CurseForge projects are different identifiers. For example, +Hwyla uses the Forge ID `waila` but the CurseForge slug `hwyla`. These identities +must be mapped explicitly when preparing publication. + +CurseForge documents relationships under **Related Projects** on a file upload, +or as project-level **Default Relations**. Jar metadata alone is not a documented +replacement for those settings. See [CurseForge's file and relationship guide](https://support.curseforge.com/support/solutions/articles/9000197242-file-project-types-and-additional-fields). + +The matching upload relation object is tracked at +[publishing/curseforge-relations.json](../publishing/curseforge-relations.json). +Every entry uses `optionalDependency`. In an upload API metadata document, use +the entire object as the value of `relations`, for example: + +```python +metadata["relations"] = json.loads(Path("publishing/curseforge-relations.json").read_text()) +``` + +The repository currently has no automatic CurseForge uploader, so this file is +prepared input, not an active publication step. A manual website upload must +select the matching projects as **Optional Dependency** under Related Projects. +Uploading the jar or placing this JSON beside it does not submit those relations. + +Keep relations specific to the Minecraft version being uploaded. This list +excludes RTG, Thaumcraft, AgriCraft and BYG because this port has no qualified +1.11.2 targets for them. CompatLayer and OreSpawn are dependencies of other mods, +rather than direct integrations to advertise here. Base Metals remains optional; +any mod providing ore-dictionary mercury can supply the thermometer ingredient. + +Avoid project-wide defaults for integrations that are supported only on some +Minecraft versions. Before another port is published, update its own metadata, +relation list and integration-version matrix together. + +## Verification + +The build and 57 unit tests pass. Fresh native server starts verify the bound +metadata with integrations absent, with farming/bridge mods, with biome mods, +and with OTG/Biome Bundle, Lost Cities and Base Metals installed. Only +`mcmod.info` and `WeatherMod.class` differ from the JEI-qualified jar; gameplay, +client, API and hook class files are byte-identical. Earlier gameplay and +performance reports retain their original tested artifact hashes. + +Exact artifacts and receipts are retained under ignored +`build/verification/dependency-metadata-1112`. Its original flat-world attempt +is retained as failed: OTG rejected that world configuration. The successful +generator fixture uses the proper OTG world type and Biome Bundle world name. diff --git a/publishing/curseforge-relations.json b/publishing/curseforge-relations.json new file mode 100644 index 0000000..582be84 --- /dev/null +++ b/publishing/curseforge-relations.json @@ -0,0 +1,21 @@ +{ + "projects": [ + { "slug": "pams-harvestcraft", "type": "optionalDependency" }, + { "slug": "mystical-agriculture", "type": "optionalDependency" }, + { "slug": "forestry", "type": "optionalDependency" }, + { "slug": "crafttweaker", "type": "optionalDependency" }, + { "slug": "tough-as-nails", "type": "optionalDependency" }, + { "slug": "jei", "type": "optionalDependency" }, + { "slug": "hwyla", "type": "optionalDependency" }, + { "slug": "the-one-probe", "type": "optionalDependency" }, + { "slug": "biomes-o-plenty", "type": "optionalDependency" }, + { "slug": "abyssalcraft", "type": "optionalDependency" }, + { "slug": "vampirism-become-a-vampire", "type": "optionalDependency" }, + { "slug": "climate-control-geographicraft", "type": "optionalDependency" }, + { "slug": "biometweaker", "type": "optionalDependency" }, + { "slug": "open-terrain-generator", "type": "optionalDependency" }, + { "slug": "biome-bundle", "type": "optionalDependency" }, + { "slug": "the-lost-cities", "type": "optionalDependency" }, + { "slug": "base-metals", "type": "optionalDependency" } + ] +} diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java index 76c25a1..6e15e64 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java @@ -84,6 +84,7 @@ public void started(FMLServerStartedEvent event) { world = server.getWorld(0); require(HookStatus.available(), "required weather hooks loaded"); switch (MODE) { + case "metadata": metadata(server); break; case "temperature-zones": TemperatureZoneProbe.run(world); break; case "thermal-network": new TemperatureNetworkProbe(world); break; case "jei-client": new zone.moddev.mc.skysrealisticweather.verify.jei.JeiServerProbe(world); break; @@ -139,6 +140,29 @@ public void started(FMLServerStartedEvent event) { } } + private void metadata(MinecraftServer server) { + net.minecraftforge.fml.common.Loader loader=net.minecraftforge.fml.common.Loader.instance(); + net.minecraftforge.fml.common.ModContainer mod=loader.getIndexedModList().get("skysrealisticweather"); + net.minecraftforge.fml.common.ModMetadata bound=mod.getMetadata(); + try(java.util.zip.ZipFile jar=new java.util.zip.ZipFile(mod.getSource()); + java.io.InputStream input=jar.getInputStream(jar.getEntry("mcmod.info"))) { + com.google.gson.JsonObject declared=new com.google.gson.JsonParser().parse(new java.io.InputStreamReader(input,java.nio.charset.StandardCharsets.UTF_8)) + .getAsJsonArray().get(0).getAsJsonObject(); + java.util.Set expected=new java.util.HashSet<>(),actual=new java.util.HashSet<>(); + for(com.google.gson.JsonElement e:declared.getAsJsonArray("dependencies"))expected.add(e.getAsString().split("@",2)[0]); + for(net.minecraftforge.fml.common.versioning.ArtifactVersion v:bound.dependencies)actual.add(v.getLabel()); + require(bound.useDependencyInformation&&expected.equals(actual),"Forge uses declared optional dependency metadata"); + require(bound.requiredMods.size()==1&&bound.requiredMods.iterator().next().getLabel().equals("forge"),"only Forge is mandatory"); + java.util.List sorted=loader.getActiveModList(); + for(net.minecraftforge.fml.common.versioning.ArtifactVersion v:bound.dependencies) { + net.minecraftforge.fml.common.ModContainer dependency=loader.getIndexedModList().get(v.getLabel()); + if(dependency!=null)require(sorted.indexOf(dependency) Date: Fri, 27 Nov 2026 15:10:15 +0000 Subject: [PATCH 5/9] Use public management APIs and restore annotation dependencies --- docs/BUILDING.md | 11 ------- docs/PORTING_1_11_2.md | 6 ++-- docs/PUBLISHING.md | 24 ++++----------- .../verify/WeatherProbe.java | 24 --------------- .../performance/WorldgenPerformanceProbe.java | 30 ++++++++++++++++--- .../mc/skysrealisticweather/WeatherMod.java | 2 +- src/main/resources/mcmod.info | 25 +--------------- 7 files changed, 36 insertions(+), 86 deletions(-) diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 98a22a3..1319220 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -225,17 +225,6 @@ See [JEI client results](JEI_CLIENT_1_11_2.md) for the tested layouts and fix. ## Acceptance scope -Dependency metadata can be checked without a client: - -```text -python scripts/Run-RuntimeChecks.py --mode metadata --expect "SKY_WEATHER_CHECK METADATA PASS" --output build/verification/metadata/ -``` - -Add `--mod ` for each pinned jar to verify installed dependencies -load before weather. The check compares Forge's bound metadata with the actual -jar and confirms only Forge is mandatory. See [publishing](PUBLISHING.md) for -the separate CurseForge relationships. - Unit tests verify native renderer and Overworld generation bytecode as well as climate, network and API contracts. Packaged servers cover native hooks, crops, commands, temperature zones, crafting and save/reload. The distant-render probe diff --git a/docs/PORTING_1_11_2.md b/docs/PORTING_1_11_2.md index b859a01..fb8dd2a 100644 --- a/docs/PORTING_1_11_2.md +++ b/docs/PORTING_1_11_2.md @@ -26,9 +26,9 @@ Use a backup and a version-appropriate test pack for migration. - Tough As Nails uses `SeasonsOption` and its configurable temperature-scale midpoint; its body temperature, response timer and other modifiers remain native. - JEI uses the 4.x ingredient registry and category contract. -- `mcmod.info` declares the 17 version-appropriate integrations as optional - dependencies; only Forge is required. Matching CurseForge relation data is - prepared separately; see [dependency metadata and publishing](PUBLISHING.md). +- Forge keeps its existing annotation-based requirements and optional load + ordering. CurseForge relation data is prepared separately; see + [dependency metadata and publishing](PUBLISHING.md). ## Integration builds diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md index d474b9e..fbf4f2e 100644 --- a/docs/PUBLISHING.md +++ b/docs/PUBLISHING.md @@ -1,10 +1,10 @@ # Dependency metadata and CurseForge relations -The 1.11.2 jar declares its 17 supported integrations as optional dependencies -in `mcmod.info`. Forge is the only required dependency. `useMetadata` and -`useDependencyInformation` enable those declarations; installed integration mods -load before Sky's Realistic Weather, while missing integrations do not prevent -startup. The annotation keeps the minimum Forge requirement as a fallback. +`mcmod.info` contains descriptive mod information. Forge's requirements and +existing optional load ordering remain in the `@Mod` annotation; Forge is the +only required dependency. Optional integrations can be absent without preventing +startup. The separate CurseForge relation list covers the 17 supported +integrations for this version. Supported builds are listed in [port status](PORTING_1_11_2.md). Forge mod IDs and CurseForge projects are different identifiers. For example, @@ -38,17 +38,3 @@ any mod providing ore-dictionary mercury can supply the thermometer ingredient. Avoid project-wide defaults for integrations that are supported only on some Minecraft versions. Before another port is published, update its own metadata, relation list and integration-version matrix together. - -## Verification - -The build and 57 unit tests pass. Fresh native server starts verify the bound -metadata with integrations absent, with farming/bridge mods, with biome mods, -and with OTG/Biome Bundle, Lost Cities and Base Metals installed. Only -`mcmod.info` and `WeatherMod.class` differ from the JEI-qualified jar; gameplay, -client, API and hook class files are byte-identical. Earlier gameplay and -performance reports retain their original tested artifact hashes. - -Exact artifacts and receipts are retained under ignored -`build/verification/dependency-metadata-1112`. Its original flat-world attempt -is retained as failed: OTG rejected that world configuration. The successful -generator fixture uses the proper OTG world type and Biome Bundle world name. diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java index 6e15e64..76c25a1 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/WeatherProbe.java @@ -84,7 +84,6 @@ public void started(FMLServerStartedEvent event) { world = server.getWorld(0); require(HookStatus.available(), "required weather hooks loaded"); switch (MODE) { - case "metadata": metadata(server); break; case "temperature-zones": TemperatureZoneProbe.run(world); break; case "thermal-network": new TemperatureNetworkProbe(world); break; case "jei-client": new zone.moddev.mc.skysrealisticweather.verify.jei.JeiServerProbe(world); break; @@ -140,29 +139,6 @@ public void started(FMLServerStartedEvent event) { } } - private void metadata(MinecraftServer server) { - net.minecraftforge.fml.common.Loader loader=net.minecraftforge.fml.common.Loader.instance(); - net.minecraftforge.fml.common.ModContainer mod=loader.getIndexedModList().get("skysrealisticweather"); - net.minecraftforge.fml.common.ModMetadata bound=mod.getMetadata(); - try(java.util.zip.ZipFile jar=new java.util.zip.ZipFile(mod.getSource()); - java.io.InputStream input=jar.getInputStream(jar.getEntry("mcmod.info"))) { - com.google.gson.JsonObject declared=new com.google.gson.JsonParser().parse(new java.io.InputStreamReader(input,java.nio.charset.StandardCharsets.UTF_8)) - .getAsJsonArray().get(0).getAsJsonObject(); - java.util.Set expected=new java.util.HashSet<>(),actual=new java.util.HashSet<>(); - for(com.google.gson.JsonElement e:declared.getAsJsonArray("dependencies"))expected.add(e.getAsString().split("@",2)[0]); - for(net.minecraftforge.fml.common.versioning.ArtifactVersion v:bound.dependencies)actual.add(v.getLabel()); - require(bound.useDependencyInformation&&expected.equals(actual),"Forge uses declared optional dependency metadata"); - require(bound.requiredMods.size()==1&&bound.requiredMods.iterator().next().getLabel().equals("forge"),"only Forge is mandatory"); - java.util.List sorted=loader.getActiveModList(); - for(net.minecraftforge.fml.common.versioning.ArtifactVersion v:bound.dependencies) { - net.minecraftforge.fml.common.ModContainer dependency=loader.getIndexedModList().get(v.getLabel()); - if(dependency!=null)require(sorted.indexOf(dependency) frostStart = new HashMap<>(); private List frostTimes; private int populationCount; @@ -94,9 +100,7 @@ public void start(FMLServerStartedEvent event) { require(threads.isCurrentThreadCpuTimeSupported(), "server thread CPU timer available"); threads.setThreadCpuTimeEnabled(true); if (ALLOCATION) { - com.sun.management.ThreadMXBean hotspot = (com.sun.management.ThreadMXBean) threads; - require(hotspot.isThreadAllocatedMemorySupported(), "server thread allocation counter available"); - hotspot.setThreadAllocatedMemoryEnabled(true); + enableAllocationCounter(); } } @@ -255,7 +259,25 @@ private void benchmark(String phase, int x, int z, long day) { } private long allocated() { - return ALLOCATION ? ((com.sun.management.ThreadMXBean) threads).getThreadAllocatedBytes(Thread.currentThread().getId()) : 0; + if (!ALLOCATION) return 0; + try { + return (Long) allocationServer.invoke(allocationBean, "getThreadAllocatedBytes", + new Object[] {Thread.currentThread().getId()}, new String[] {"long"}); + } catch (JMException failure) { + throw new IllegalStateException("Cannot read the server thread allocation counter", failure); + } + } + + private void enableAllocationCounter() { + try { + allocationServer = ManagementFactory.getPlatformMBeanServer(); + allocationBean = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME); + require(Boolean.TRUE.equals(allocationServer.getAttribute(allocationBean, "ThreadAllocatedMemorySupported")), + "server thread allocation counter available"); + allocationServer.setAttribute(allocationBean, new Attribute("ThreadAllocatedMemoryEnabled", true)); + } catch (JMException failure) { + throw new IllegalStateException("Cannot enable the server thread allocation counter", failure); + } } private static void generate(ChunkProviderServer provider, int x, int z, int size, long[] timings) { diff --git a/src/main/java/zone/moddev/mc/skysrealisticweather/WeatherMod.java b/src/main/java/zone/moddev/mc/skysrealisticweather/WeatherMod.java index 663f973..210af4b 100644 --- a/src/main/java/zone/moddev/mc/skysrealisticweather/WeatherMod.java +++ b/src/main/java/zone/moddev/mc/skysrealisticweather/WeatherMod.java @@ -21,7 +21,7 @@ @Mod(modid = BuildInfo.ID, name = BuildInfo.NAME, version = BuildInfo.VERSION, acceptedMinecraftVersions = "[1.11.2]", acceptableRemoteVersions = "[" + BuildInfo.VERSION + "]", - useMetadata = true, dependencies = "required-after:forge@[13.20.1.2588,)", + dependencies = "required-after:forge@[13.20.1.2588,);after:crafttweaker;after:toughasnails;after:waila;after:theoneprobe;after:jei", guiFactory = "zone.moddev.mc.skysrealisticweather.client.WeatherGuiFactory") public final class WeatherMod { public static final SimpleNetworkWrapper NETWORK = NetworkRegistry.INSTANCE.newSimpleChannel(BuildInfo.ID); diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info index 4f6a83f..18afacc 100644 --- a/src/main/resources/mcmod.info +++ b/src/main/resources/mcmod.info @@ -5,29 +5,6 @@ "description": "${description}", "version": "${version}", "mcversion": "${mcversion}", - "authorList": ["SkyBlade1978"], - "useDependencyInformation": true, - "requiredMods": ["forge@[13.20.1.2588,)"], - "dependencies": [ - "forge@[13.20.1.2588,)", - "harvestcraft", - "mysticalagriculture", - "forestry", - "crafttweaker", - "toughasnails", - "jei", - "waila", - "theoneprobe", - "biomesoplenty", - "abyssalcraft", - "vampirism", - "geographicraft", - "biometweaker", - "openterraingenerator", - "biomebundle", - "lostcities", - "basemetals" - ], - "dependants": [] + "authorList": ["SkyBlade1978"] } ] From aeaf650a7bd5b97eb8bb19804e54a955f74b213c Mon Sep 17 00:00:00 2001 From: JohnBraham Date: Fri, 27 Nov 2026 16:27:00 +0000 Subject: [PATCH 6/9] Correct resource format for 1.11.2 language loading --- docs/BUILDING.md | 5 +++ docs/PORTING_1_11_2.md | 5 +-- .../verify/ClientProbe.java | 33 +++++++++++++++++++ src/main/resources/pack.mcmeta | 2 +- 4 files changed, 42 insertions(+), 3 deletions(-) diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 1319220..2839f2d 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -29,6 +29,11 @@ The development client opens at 1280 × 720 by default. To use another size, set `overrideWidth` and `overrideHeight` in `options.txt` in the development game folder. +Resources use pack format 3 and lowercase language filenames for Minecraft +1.11.2. `gradlew prepareEclipseResources` refreshes `bin/main` after resource +changes. Restart the client after changing `pack.mcmeta`; Forge selects its +legacy or current resource wrapper when the client starts. + `runClient` and `runServer` use Sky's Realistic Weather and Forge. For a compatibility session, choose one of the generated Eclipse launches below. Each uses its own folder under `run-compat/` for mods, configs and saves. diff --git a/docs/PORTING_1_11_2.md b/docs/PORTING_1_11_2.md index fb8dd2a..788356f 100644 --- a/docs/PORTING_1_11_2.md +++ b/docs/PORTING_1_11_2.md @@ -17,8 +17,9 @@ Use a backup and a version-appropriate test pack for migration. - Forge dependency and optional mod IDs match their 1.11.2 registrations. - Items use the 1.11 empty-stack and count contracts. Thermometer placement, hand use, creative-tab entries and block callbacks use the new signatures. -- The config GUI supports the Forge 1.11 factory methods; language assets use - the lowercase resource name expected by this version. +- The config GUI supports the Forge 1.11 factory methods; resource pack format 3 + enables this version's lowercase language-file names. Item, admin-tab and HUD + translations are checked in a packaged client and the Eclipse resource folder. - The OTG v9 bridge uses its new package and loaded-terrain material access. It retains OTG's virtual biome, protected native cover and native materials. - Forestry 5.3's ambient climate-info fallback receives local temperature and diff --git a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java index 3543b5c..df7c7d8 100644 --- a/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java +++ b/src/integrationTest/java/zone/moddev/mc/skysrealisticweather/verify/ClientProbe.java @@ -255,6 +255,16 @@ private static void click(GuiScreen screen, int x, int y) throws ReflectiveOpera } private void verifyConfig(Minecraft game) throws ReflectiveOperationException { + String thermometer = new ItemStack(zone.moddev.mc.skysrealisticweather.instrument.Thermometer.BLOCK).getDisplayName(); + String controller = new ItemStack(WeatherController.BLOCK).getDisplayName(); + System.out.println("LOCALIZATION_NAMES thermometer=" + thermometer + " controller=" + controller); + WeatherProbe.require(thermometer.equals("Thermometer") && controller.equals("Weather Controller"), "registered item names are translated"); + String tab = net.minecraft.client.resources.I18n.format(((net.minecraft.block.Block) WeatherController.BLOCK).getCreativeTabToDisplayOn().getTranslatedTabLabel()); + WeatherProbe.require(tab.equals("Sky's Weather Admin"), "admin tab is translated"); + WeatherProbe.require(net.minecraft.client.resources.I18n.format("hud.skysrealisticweather.temperature").equals("Temperature"), "client HUD translation is loaded"); + String folder = System.getProperty("skyweather.languageFolder"); + if (folder != null) verifyFolderLanguage(new File(folder)); + System.out.println("SKY_WEATHER_CHECK LOCALIZATION PASS"); GuiScreen parent = new GuiModList(game.currentScreen); Class factory = FMLClientHandler.instance() .getGuiFactoryFor(Loader.instance().getIndexedModList().get("skysrealisticweather")).mainConfigGuiClass(); @@ -371,6 +381,29 @@ private void verifyConfig(Minecraft game) throws ReflectiveOperationException { pendingPicture = true; } + private static void verifyFolderLanguage(final File folder) { + net.minecraftforge.fml.common.ModMetadata metadata = Loader.instance().getIndexedModList().get("skysrealisticweather").getMetadata(); + net.minecraftforge.fml.common.DummyModContainer container = new net.minecraftforge.fml.common.DummyModContainer(metadata) { + @Override public File getSource() { return folder; } + }; + net.minecraft.client.resources.IResourcePack pack = new net.minecraftforge.fml.client.FMLFolderResourcePack(container); + net.minecraft.client.resources.data.MetadataSerializer serializer = new net.minecraft.client.resources.data.MetadataSerializer(); + serializer.registerMetadataSectionType(new net.minecraft.client.resources.data.PackMetadataSectionSerializer(), net.minecraft.client.resources.data.PackMetadataSection.class); + try { + net.minecraft.client.resources.data.PackMetadataSection section = pack.getPackMetadata(serializer, "pack"); + WeatherProbe.require(section.getPackFormat() == 3, "development resources select the native 1.11 language path"); + } catch (java.io.IOException failure) { throw new IllegalStateException("Cannot read development resource metadata", failure); } + net.minecraft.client.resources.SimpleReloadableResourceManager resources = new net.minecraft.client.resources.SimpleReloadableResourceManager(serializer); + resources.reloadResourcePack(pack); + net.minecraft.client.resources.Locale locale = new net.minecraft.client.resources.Locale(); + locale.loadLocaleDataFiles(resources, java.util.Collections.singletonList("en_us")); + WeatherProbe.require(locale.formatMessage("tile.skysrealisticweather.thermometer.name", new Object[0]).equals("Thermometer") + && locale.formatMessage("tile.skysrealisticweather.weather_controller.name", new Object[0]).equals("Weather Controller") + && locale.formatMessage("itemGroup.skysweatheradmin", new Object[0]).equals("Sky's Weather Admin") + && locale.formatMessage("hud.skysrealisticweather.temperature", new Object[0]).equals("Temperature"), "native folder resource loader resolves development translations"); + System.out.println("SKY_WEATHER_CHECK FOLDER_LOCALIZATION PASS " + folder); + } + private void modeUi(Minecraft game) throws ReflectiveOperationException { if (modeUiStage == 0 && !(game.currentScreen instanceof GuiMainMenu)) return; if (++readyTicks % 12 != 0) return; diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta index f3f0504..76248a7 100644 --- a/src/main/resources/pack.mcmeta +++ b/src/main/resources/pack.mcmeta @@ -1 +1 @@ -{"pack":{"pack_format":2,"description":"Sky's Realistic Weather resources"}} +{"pack":{"pack_format":3,"description":"Sky's Realistic Weather resources"}} From ed228dc92360566ab963b9f7df79e3351cbd0a3e Mon Sep 17 00:00:00 2001 From: JohnBraham Date: Fri, 27 Nov 2026 16:47:31 +0000 Subject: [PATCH 7/9] Add multilingual item and thermometer resources --- README.md | 1 + docs/LANGUAGES.md | 52 +++++++++++++++++++ .../skysrealisticweather/lang/de_at.lang | 11 ++++ .../skysrealisticweather/lang/de_au.lang | 11 ++++ .../skysrealisticweather/lang/de_de.lang | 11 ++++ .../skysrealisticweather/lang/en_ca.lang | 11 ++++ .../skysrealisticweather/lang/en_en.lang | 11 ++++ .../skysrealisticweather/lang/en_gb.lang | 11 ++++ .../skysrealisticweather/lang/en_pt.lang | 11 ++++ .../skysrealisticweather/lang/es_es.lang | 11 ++++ .../skysrealisticweather/lang/es_mx.lang | 11 ++++ .../skysrealisticweather/lang/fr_ca.lang | 11 ++++ .../skysrealisticweather/lang/fr_fr.lang | 11 ++++ .../skysrealisticweather/lang/ja_jp.lang | 11 ++++ .../skysrealisticweather/lang/ko_kr.lang | 11 ++++ .../skysrealisticweather/lang/pt_br.lang | 11 ++++ .../skysrealisticweather/lang/pt_pt.lang | 11 ++++ .../skysrealisticweather/lang/ru_ru.lang | 11 ++++ .../skysrealisticweather/lang/zh_cn.lang | 11 ++++ 19 files changed, 240 insertions(+) create mode 100644 docs/LANGUAGES.md create mode 100644 src/main/resources/assets/skysrealisticweather/lang/de_at.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/de_au.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/de_de.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/en_ca.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/en_en.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/en_gb.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/en_pt.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/es_es.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/es_mx.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/fr_ca.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/fr_fr.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/ja_jp.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/ko_kr.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/pt_br.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/pt_pt.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/ru_ru.lang create mode 100644 src/main/resources/assets/skysrealisticweather/lang/zh_cn.lang diff --git a/README.md b/README.md index 4b1a46a..d25ef66 100644 --- a/README.md +++ b/README.md @@ -91,4 +91,5 @@ Weather data provided by [Open-Meteo.com](https://open-meteo.com/). - [Weather events by climate](docs/WEATHER.md) - [Weather controller and server commands](docs/ADMIN.md) - [Build and verification](docs/BUILDING.md) +- [Languages and translation coverage](docs/LANGUAGES.md) - [Licence](LICENSE) and [credits](NOTICE) diff --git a/docs/LANGUAGES.md b/docs/LANGUAGES.md new file mode 100644 index 0000000..427de2c --- /dev/null +++ b/docs/LANGUAGES.md @@ -0,0 +1,52 @@ +# Languages + +Choose a language in Minecraft's **Options → Language** screen. The item names, +weather-admin creative tab, climate HUD keybinding, thermometer HUD labels and +thermometer instructions follow that client setting, including in multiplayer. +The mod name stays Sky's Realistic Weather. + +The translations match Iron Age Furniture's locale set. Austrian German also +uses Minecraft's correct `de_AT` locale; `de_AU` is retained as a legacy alias. +Likewise, `en_EN` is an English alias. These aliases do not add entries to the +vanilla language menu. + +| Locale | Translation | +| --- | --- | +| `de_AT` | German (Austria) | +| `de_AU` | German, legacy alias | +| `de_DE` | German (Germany) | +| `en_CA` | English (Canada) | +| `en_EN` | English, legacy alias | +| `en_GB` | English (United Kingdom) | +| `en_PT` | Pirate English | +| `en_US` | English (United States), fallback | +| `es_ES` | Spanish (Spain) | +| `es_MX` | Spanish (Mexico) | +| `fr_CA` | French (Canada) | +| `fr_FR` | French (France) | +| `ja_JP` | Japanese | +| `ko_KR` | Korean | +| `pt_BR` | Portuguese (Brazil) | +| `pt_PT` | Portuguese (Portugal) | +| `ru_RU` | Russian | +| `zh_CN` | Simplified Chinese | + +The config and admin editors, crop suitability text, climate preset names and +command messages still contain English strings in code. The language files +cover the nine existing translation keys; they do not translate those screens +or player-defined climate and crop names. + +## Editing translations + +Files are UTF-8 without a byte-order mark, under +`src/main/resources/assets/skysrealisticweather/lang`. Keep every English key +in every locale, with exactly one non-empty value per key. Preserve any +formatting placeholders when adding future keys. + +Minecraft 1.10.2 uses mixed-case filenames such as `fr_FR.lang` and pack format 2. +Minecraft 1.11.2 uses lowercase filenames such as `fr_fr.lang` and pack format 3. +When backporting translations, change the filename casing as appropriate. + +Run `gradlew build writeReleaseChecksum prepareEclipseResources syncDevelopmentOutput` +after editing. This packages the translations and refreshes Eclipse's resource +folder. Restart the client to load the rebuilt resources. diff --git a/src/main/resources/assets/skysrealisticweather/lang/de_at.lang b/src/main/resources/assets/skysrealisticweather/lang/de_at.lang new file mode 100644 index 0000000..0656dc4 --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/de_at.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=Wettersteuerung +itemGroup.skysweatheradmin=Skys Wetterverwaltung +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=Klima-HUD umschalten + +tile.skysrealisticweather.thermometer.name=Thermometer +hud.skysrealisticweather.temperature=Temperatur +hud.skysrealisticweather.here=Hier +hud.skysrealisticweather.placed=Platziert + +tooltip.skysrealisticweather.thermometer=In einer beliebigen Hand halten oder an einer Wand bzw. auf dem Boden platzieren. diff --git a/src/main/resources/assets/skysrealisticweather/lang/de_au.lang b/src/main/resources/assets/skysrealisticweather/lang/de_au.lang new file mode 100644 index 0000000..0656dc4 --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/de_au.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=Wettersteuerung +itemGroup.skysweatheradmin=Skys Wetterverwaltung +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=Klima-HUD umschalten + +tile.skysrealisticweather.thermometer.name=Thermometer +hud.skysrealisticweather.temperature=Temperatur +hud.skysrealisticweather.here=Hier +hud.skysrealisticweather.placed=Platziert + +tooltip.skysrealisticweather.thermometer=In einer beliebigen Hand halten oder an einer Wand bzw. auf dem Boden platzieren. diff --git a/src/main/resources/assets/skysrealisticweather/lang/de_de.lang b/src/main/resources/assets/skysrealisticweather/lang/de_de.lang new file mode 100644 index 0000000..0656dc4 --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/de_de.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=Wettersteuerung +itemGroup.skysweatheradmin=Skys Wetterverwaltung +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=Klima-HUD umschalten + +tile.skysrealisticweather.thermometer.name=Thermometer +hud.skysrealisticweather.temperature=Temperatur +hud.skysrealisticweather.here=Hier +hud.skysrealisticweather.placed=Platziert + +tooltip.skysrealisticweather.thermometer=In einer beliebigen Hand halten oder an einer Wand bzw. auf dem Boden platzieren. diff --git a/src/main/resources/assets/skysrealisticweather/lang/en_ca.lang b/src/main/resources/assets/skysrealisticweather/lang/en_ca.lang new file mode 100644 index 0000000..cf86c1e --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/en_ca.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=Weather Controller +itemGroup.skysweatheradmin=Sky's Weather Admin +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=Toggle Climate HUD + +tile.skysrealisticweather.thermometer.name=Thermometer +hud.skysrealisticweather.temperature=Temperature +hud.skysrealisticweather.here=Here +hud.skysrealisticweather.placed=Placed + +tooltip.skysrealisticweather.thermometer=Hold in either hand, or place on a wall or floor. diff --git a/src/main/resources/assets/skysrealisticweather/lang/en_en.lang b/src/main/resources/assets/skysrealisticweather/lang/en_en.lang new file mode 100644 index 0000000..cf86c1e --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/en_en.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=Weather Controller +itemGroup.skysweatheradmin=Sky's Weather Admin +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=Toggle Climate HUD + +tile.skysrealisticweather.thermometer.name=Thermometer +hud.skysrealisticweather.temperature=Temperature +hud.skysrealisticweather.here=Here +hud.skysrealisticweather.placed=Placed + +tooltip.skysrealisticweather.thermometer=Hold in either hand, or place on a wall or floor. diff --git a/src/main/resources/assets/skysrealisticweather/lang/en_gb.lang b/src/main/resources/assets/skysrealisticweather/lang/en_gb.lang new file mode 100644 index 0000000..cf86c1e --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/en_gb.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=Weather Controller +itemGroup.skysweatheradmin=Sky's Weather Admin +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=Toggle Climate HUD + +tile.skysrealisticweather.thermometer.name=Thermometer +hud.skysrealisticweather.temperature=Temperature +hud.skysrealisticweather.here=Here +hud.skysrealisticweather.placed=Placed + +tooltip.skysrealisticweather.thermometer=Hold in either hand, or place on a wall or floor. diff --git a/src/main/resources/assets/skysrealisticweather/lang/en_pt.lang b/src/main/resources/assets/skysrealisticweather/lang/en_pt.lang new file mode 100644 index 0000000..1a3613d --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/en_pt.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=Winds 'n' Weather Helm +itemGroup.skysweatheradmin=Sky's Weather Cap'n +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=Show or Stow Climate HUD + +tile.skysrealisticweather.thermometer.name=Heat Gauge +hud.skysrealisticweather.temperature=Heat +hud.skysrealisticweather.here=Here, matey +hud.skysrealisticweather.placed=Set down + +tooltip.skysrealisticweather.thermometer=Keep in either hand, or stow on a wall or deck. diff --git a/src/main/resources/assets/skysrealisticweather/lang/es_es.lang b/src/main/resources/assets/skysrealisticweather/lang/es_es.lang new file mode 100644 index 0000000..761679b --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/es_es.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=Controlador del tiempo +itemGroup.skysweatheradmin=Administración del tiempo de Sky +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=Activar/desactivar el HUD del clima + +tile.skysrealisticweather.thermometer.name=Termómetro +hud.skysrealisticweather.temperature=Temperatura +hud.skysrealisticweather.here=Aquí +hud.skysrealisticweather.placed=Colocado + +tooltip.skysrealisticweather.thermometer=Sostenlo en cualquiera de las manos o colócalo en una pared o en el suelo. diff --git a/src/main/resources/assets/skysrealisticweather/lang/es_mx.lang b/src/main/resources/assets/skysrealisticweather/lang/es_mx.lang new file mode 100644 index 0000000..4cc127b --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/es_mx.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=Controlador del clima +itemGroup.skysweatheradmin=Administración del clima de Sky +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=Activar/desactivar el HUD del clima + +tile.skysrealisticweather.thermometer.name=Termómetro +hud.skysrealisticweather.temperature=Temperatura +hud.skysrealisticweather.here=Aquí +hud.skysrealisticweather.placed=Colocado + +tooltip.skysrealisticweather.thermometer=Sostenlo en cualquiera de las manos o colócalo en una pared o en el piso. diff --git a/src/main/resources/assets/skysrealisticweather/lang/fr_ca.lang b/src/main/resources/assets/skysrealisticweather/lang/fr_ca.lang new file mode 100644 index 0000000..491ab77 --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/fr_ca.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=Contrôleur météo +itemGroup.skysweatheradmin=Administration météo de Sky +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=Afficher/masquer le HUD du climat + +tile.skysrealisticweather.thermometer.name=Thermomètre +hud.skysrealisticweather.temperature=Température +hud.skysrealisticweather.here=Ici +hud.skysrealisticweather.placed=Posé + +tooltip.skysrealisticweather.thermometer=Tenez-le dans l'une ou l'autre main, ou placez-le sur un mur ou au sol. diff --git a/src/main/resources/assets/skysrealisticweather/lang/fr_fr.lang b/src/main/resources/assets/skysrealisticweather/lang/fr_fr.lang new file mode 100644 index 0000000..491ab77 --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/fr_fr.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=Contrôleur météo +itemGroup.skysweatheradmin=Administration météo de Sky +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=Afficher/masquer le HUD du climat + +tile.skysrealisticweather.thermometer.name=Thermomètre +hud.skysrealisticweather.temperature=Température +hud.skysrealisticweather.here=Ici +hud.skysrealisticweather.placed=Posé + +tooltip.skysrealisticweather.thermometer=Tenez-le dans l'une ou l'autre main, ou placez-le sur un mur ou au sol. diff --git a/src/main/resources/assets/skysrealisticweather/lang/ja_jp.lang b/src/main/resources/assets/skysrealisticweather/lang/ja_jp.lang new file mode 100644 index 0000000..15cd467 --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/ja_jp.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=気象コントローラー +itemGroup.skysweatheradmin=Skyの天候管理 +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=気候HUDの表示を切り替え + +tile.skysrealisticweather.thermometer.name=温度計 +hud.skysrealisticweather.temperature=気温 +hud.skysrealisticweather.here=現在地 +hud.skysrealisticweather.placed=設置場所 + +tooltip.skysrealisticweather.thermometer=どちらかの手に持つか、壁や床に設置できます。 diff --git a/src/main/resources/assets/skysrealisticweather/lang/ko_kr.lang b/src/main/resources/assets/skysrealisticweather/lang/ko_kr.lang new file mode 100644 index 0000000..9cba126 --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/ko_kr.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=날씨 제어기 +itemGroup.skysweatheradmin=Sky의 날씨 관리 +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=기후 HUD 표시 전환 + +tile.skysrealisticweather.thermometer.name=온도계 +hud.skysrealisticweather.temperature=기온 +hud.skysrealisticweather.here=현재 위치 +hud.skysrealisticweather.placed=설치 위치 + +tooltip.skysrealisticweather.thermometer=어느 손에든 들거나 벽 또는 바닥에 설치할 수 있습니다. diff --git a/src/main/resources/assets/skysrealisticweather/lang/pt_br.lang b/src/main/resources/assets/skysrealisticweather/lang/pt_br.lang new file mode 100644 index 0000000..2813d2b --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/pt_br.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=Controlador de clima +itemGroup.skysweatheradmin=Administração do clima de Sky +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=Alternar HUD do clima + +tile.skysrealisticweather.thermometer.name=Termômetro +hud.skysrealisticweather.temperature=Temperatura +hud.skysrealisticweather.here=Aqui +hud.skysrealisticweather.placed=Colocado + +tooltip.skysrealisticweather.thermometer=Segure em qualquer uma das mãos ou coloque em uma parede ou no chão. diff --git a/src/main/resources/assets/skysrealisticweather/lang/pt_pt.lang b/src/main/resources/assets/skysrealisticweather/lang/pt_pt.lang new file mode 100644 index 0000000..6f815fc --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/pt_pt.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=Controlo meteorológico +itemGroup.skysweatheradmin=Administração meteorológica de Sky +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=Alternar HUD do clima + +tile.skysrealisticweather.thermometer.name=Termómetro +hud.skysrealisticweather.temperature=Temperatura +hud.skysrealisticweather.here=Aqui +hud.skysrealisticweather.placed=Colocado + +tooltip.skysrealisticweather.thermometer=Segura em qualquer uma das mãos ou coloca numa parede ou no chão. diff --git a/src/main/resources/assets/skysrealisticweather/lang/ru_ru.lang b/src/main/resources/assets/skysrealisticweather/lang/ru_ru.lang new file mode 100644 index 0000000..1181cd9 --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/ru_ru.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=Контроллер погоды +itemGroup.skysweatheradmin=Управление погодой Sky +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=Переключить климатический HUD + +tile.skysrealisticweather.thermometer.name=Термометр +hud.skysrealisticweather.temperature=Температура +hud.skysrealisticweather.here=Здесь +hud.skysrealisticweather.placed=Установлен + +tooltip.skysrealisticweather.thermometer=Держите в любой руке или разместите на стене либо на полу. diff --git a/src/main/resources/assets/skysrealisticweather/lang/zh_cn.lang b/src/main/resources/assets/skysrealisticweather/lang/zh_cn.lang new file mode 100644 index 0000000..13e6980 --- /dev/null +++ b/src/main/resources/assets/skysrealisticweather/lang/zh_cn.lang @@ -0,0 +1,11 @@ +tile.skysrealisticweather.weather_controller.name=天气控制器 +itemGroup.skysweatheradmin=Sky 的天气管理 +key.categories.skysrealisticweather=Sky's Realistic Weather +key.skysrealisticweather.climateHud=切换气候 HUD + +tile.skysrealisticweather.thermometer.name=温度计 +hud.skysrealisticweather.temperature=气温 +hud.skysrealisticweather.here=当前位置 +hud.skysrealisticweather.placed=放置位置 + +tooltip.skysrealisticweather.thermometer=可拿在任意一只手中,也可放置在墙上或地面上。 From de3efbf5e34ef020b9c626538e38416be4906a8b Mon Sep 17 00:00:00 2001 From: JohnBraham Date: Fri, 27 Nov 2026 23:11:03 +0000 Subject: [PATCH 8/9] Prepare 1.11.2 release and audited publishing --- .github/workflows/ci.yml | 103 ++++ .github/workflows/codeql-analysis.yml | 77 +++ .github/workflows/deploy-release.yml | 635 ++++++++++++++++++++ .github/workflows/release-on-tag.yml | 29 + .github/workflows/validate-gradle-build.yml | 25 + CHANGELOG.md | 21 + README.md | 9 +- build.gradle | 9 + docs/API.md | 5 + docs/PORTING_1_11_2.md | 13 +- docs/PROJECT_DESCRIPTION.md | 5 +- docs/PUBLISHING.md | 8 +- docs/RELEASING.md | 46 ++ gradle.properties | 9 + gradle/eclipse-runs.gradle | 3 + gradle/release.gradle | 223 +++++++ src/apiTest/java/WeatherApiConsumer.java | 18 + 17 files changed, 1222 insertions(+), 16 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/codeql-analysis.yml create mode 100644 .github/workflows/deploy-release.yml create mode 100644 .github/workflows/release-on-tag.yml create mode 100644 .github/workflows/validate-gradle-build.yml create mode 100644 CHANGELOG.md create mode 100644 docs/RELEASING.md create mode 100644 gradle/release.gradle create mode 100644 src/apiTest/java/WeatherApiConsumer.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..bbf2fa3 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,103 @@ +name: Sky's Realistic Weather CI + +on: + push: + branches: + - 'master-*' + - 'feature/**' + - 'release/**' + - 'updates/**' + pull_request: + branches: + - 'master-*' + +permissions: + contents: read + +concurrency: + group: skysrealisticweather-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + name: Build, test, and audit + runs-on: ubuntu-latest + timeout-minutes: 60 + + steps: + - name: Check out source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + + - name: Read target build metadata + id: target + shell: bash + run: | + set -euo pipefail + value() { sed -n "s/^$1=//p" gradle.properties; } + toolchain="$(value java_toolchain_version)" + selector="$(value java_setup_version)" + echo "java_setup_version=${selector:-$toolchain}" >> "$GITHUB_OUTPUT" + echo "java_version=$(value java_version)" >> "$GITHUB_OUTPUT" + echo "minecraft_version=$(value minecraft_version)" >> "$GITHUB_OUTPUT" + echo "gradle_java_version=$(value gradle_java_version)" >> "$GITHUB_OUTPUT" + echo "artifact_prefix=SkysRealisticWeather-$(value mod_version)" >> "$GITHUB_OUTPUT" + + + - name: Install target Java toolchain + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5 + with: + distribution: temurin + java-version: ${{ steps.target.outputs.java_setup_version }} + + - name: Pin production Java + if: steps.target.outputs.java_version == '8' + run: | + echo "SKY_WEATHER_JAVA8_HOME=$JAVA_HOME" >> "$GITHUB_ENV" + + - name: Install Java for Gradle + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5 + with: + distribution: microsoft + java-version: ${{ steps.target.outputs.gradle_java_version }} + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6 + + + - name: Make the wrapper executable + run: chmod +x ./gradlew + + - name: Build, test, and audit release artifacts + run: ./gradlew clean check build verifyReleaseArtifacts writeReleaseChecksums -PweatherProductionOnly=true --max-workers=2 --no-daemon --stacktrace + + - name: Replay artifact checks offline + run: ./gradlew verifyReleaseArtifacts writeReleaseChecksums -PweatherProductionOnly=true --offline --max-workers=2 --no-daemon --stacktrace + + - name: Upload audited release candidate + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: SkysRealisticWeather-${{ steps.target.outputs.minecraft_version }}-${{ github.sha }} + if-no-files-found: error + retention-days: 30 + path: | + build/libs/${{ steps.target.outputs.artifact_prefix }}.jar + build/libs/${{ steps.target.outputs.artifact_prefix }}-sources.jar + build/libs/${{ steps.target.outputs.artifact_prefix }}-javadoc.jar + build/release/SHA256SUMS + build/libs/${{ steps.target.outputs.artifact_prefix }}-api.jar + publishing/curseforge-relations.json + CHANGELOG.md + + - name: Upload diagnostics on failure + if: failure() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: SkysRealisticWeather-${{ steps.target.outputs.minecraft_version }}-diagnostics-${{ github.sha }} + if-no-files-found: ignore + retention-days: 14 + path: | + build/test-results/** + build/reports/** + build/*-run/logs/** + build/*-run/**/*.properties + build/problems/** diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 0000000..a77cdf4 --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,77 @@ +name: CodeQL + +on: + push: + branches: + - 'master-*' + - 'feature/**' + - 'release/**' + - 'updates/**' + pull_request: + branches: + - 'master-*' + schedule: + - cron: '47 7 * * 4' + +permissions: + actions: read + contents: read + security-events: write + +jobs: + analyze: + name: Analyze Java + runs-on: ubuntu-latest + timeout-minutes: 45 + + steps: + - name: Check out source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + + - name: Read target build metadata + id: target + shell: bash + run: | + set -euo pipefail + value() { sed -n "s/^$1=//p" gradle.properties; } + toolchain="$(value java_toolchain_version)" + selector="$(value java_setup_version)" + echo "java_setup_version=${selector:-$toolchain}" >> "$GITHUB_OUTPUT" + echo "java_version=$(value java_version)" >> "$GITHUB_OUTPUT" + echo "minecraft_version=$(value minecraft_version)" >> "$GITHUB_OUTPUT" + echo "gradle_java_version=$(value gradle_java_version)" >> "$GITHUB_OUTPUT" + echo "artifact_prefix=SkysRealisticWeather-$(value mod_version)" >> "$GITHUB_OUTPUT" + + - name: Install target Java toolchain + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5 + with: + distribution: temurin + java-version: ${{ steps.target.outputs.java_setup_version }} + + - name: Pin production Java + if: steps.target.outputs.java_version == '8' + run: | + echo "SKY_WEATHER_JAVA8_HOME=$JAVA_HOME" >> "$GITHUB_ENV" + + - name: Install Java for Gradle + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5 + with: + distribution: microsoft + java-version: ${{ steps.target.outputs.gradle_java_version }} + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6 + + + - name: Initialize CodeQL + uses: github/codeql-action/init@db488ddef3bf6cb639b32c2e9a7c0a7ea8271d28 # v4 + with: + languages: java-kotlin + + - name: Compile production code + run: | + chmod +x ./gradlew + ./gradlew clean classes -PweatherProductionOnly=true --rerun-tasks --no-daemon --stacktrace + + - name: Analyze + uses: github/codeql-action/analyze@db488ddef3bf6cb639b32c2e9a7c0a7ea8271d28 # v4 diff --git a/.github/workflows/deploy-release.yml b/.github/workflows/deploy-release.yml new file mode 100644 index 0000000..520f39d --- /dev/null +++ b/.github/workflows/deploy-release.yml @@ -0,0 +1,635 @@ +name: Release Sky's Realistic Weather + +run-name: Release Sky's Realistic Weather ${{ inputs.release_version }} (CurseForge ${{ inputs.curseforge_release_level }}) + +on: + workflow_dispatch: + inputs: + release_version: + description: Four-component mod version; the target branch is derived from its fourth component. + required: true + type: string + curseforge_release_level: + description: CurseForge release level only; this does not change the GitHub Release type. + required: true + default: release + type: choice + options: + - release + - beta + - alpha + confirm_live_publication: + description: Confirm publication to Maven, CurseForge, and GitHub after the build passes. + required: true + default: false + type: boolean + + validate_access_only: + description: Check shared release credentials without building, tagging or publishing. + required: true + default: false + type: boolean + +permissions: + actions: read + contents: read + +concurrency: + group: skysrealisticweather-release-${{ inputs.release_version }} + cancel-in-progress: false + +jobs: + release_access: + name: Check publication access + if: github.repository == 'MinecraftModDevelopmentMods/SkysRealisticWeather' + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Check credential availability without disclosing values + env: + CURSEFORGE_TOKEN: ${{ secrets.CURSEFORGE_TOKEN }} + MAVEN_UPLOAD_URL: ${{ secrets.MAVEN_UPLOAD_URL }} + MAVEN_UPLOAD_USERNAME: ${{ secrets.MAVEN_UPLOAD_USERNAME }} + MAVEN_UPLOAD_PASSWORD: ${{ secrets.MAVEN_UPLOAD_PASSWORD }} + run: | + set -euo pipefail + missing=() + for name in CURSEFORGE_TOKEN MAVEN_UPLOAD_URL MAVEN_UPLOAD_USERNAME MAVEN_UPLOAD_PASSWORD; do + if [[ -z "${!name:-}" ]]; then missing+=("$name"); fi + done + if (( ${#missing[@]} > 0 )); then + printf 'Required release secret is unavailable: %s\n' "${missing[@]}" >&2 + exit 1 + fi + echo "All four release credentials are available." + + preflight: + needs: release_access + if: ${{ !inputs.validate_access_only }} + name: Validate release request + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + target_branch: ${{ steps.route.outputs.target_branch }} + release_sha: ${{ steps.validate.outputs.release_sha }} + release_version: ${{ steps.validate.outputs.release_version }} + release_tag: ${{ steps.validate.outputs.release_tag }} + minecraft_version: ${{ steps.validate.outputs.minecraft_version }} + loader_name: ${{ steps.validate.outputs.loader_name }} + loader_display: ${{ steps.validate.outputs.loader_display }} + java_version: ${{ steps.validate.outputs.java_version }} + java_toolchain_version: ${{ steps.validate.outputs.java_toolchain_version }} + java_setup_version: ${{ steps.validate.outputs.java_setup_version }} + gradle_java_version: ${{ steps.validate.outputs.gradle_java_version }} + install_gradle_java: ${{ steps.validate.outputs.install_gradle_java }} + curseforge_project_id: ${{ steps.validate.outputs.curseforge_project_id }} + main_jar: ${{ steps.validate.outputs.main_jar }} + sources_jar: ${{ steps.validate.outputs.sources_jar }} + javadoc_jar: ${{ steps.validate.outputs.javadoc_jar }} + api_jar: ${{ steps.validate.outputs.api_jar }} + + steps: + - name: Resolve target branch from version + id: route + env: + GH_TOKEN: ${{ github.token }} + RELEASE_VERSION: ${{ inputs.release_version }} + run: | + set -euo pipefail + + if [[ "$GITHUB_REPOSITORY" != "MinecraftModDevelopmentMods/SkysRealisticWeather" ]]; then + echo "Releases can only run in MinecraftModDevelopmentMods/SkysRealisticWeather" >&2 + exit 1 + fi + if [[ ! "$RELEASE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.([0-9]+)$ ]]; then + echo "release_version must contain four numeric components" >&2 + exit 1 + fi + + target_suffix="${BASH_REMATCH[1]}" + if (( ${#target_suffix} < 6 )); then + echo "Invalid target suffix $target_suffix" >&2 + exit 1 + fi + + loader_code="${target_suffix: -1}" + target_digits="${target_suffix::-1}" + mc_patch_padded="${target_digits: -2}" + without_patch="${target_digits::-2}" + mc_minor_padded="${without_patch: -2}" + mc_major="${without_patch::-2}" + + if [[ -z "$mc_major" || ! "$mc_major" =~ ^[0-9]+$ ]]; then + echo "Invalid Minecraft major version in target suffix $target_suffix" >&2 + exit 1 + fi + mc_minor="$((10#$mc_minor_padded))" + mc_patch="$((10#$mc_patch_padded))" + case "$loader_code" in + 1) loader_suffix= ;; + 2) loader_suffix=-neo ;; + *) echo "Unknown loader code $loader_code in target suffix $target_suffix" >&2; exit 1 ;; + esac + + candidates=( + "master-$mc_major.$mc_minor.$mc_patch$loader_suffix" + "master-$mc_major.$mc_minor$loader_suffix" + ) + target_branch= + for candidate in "${candidates[@]}"; do + if gh api "repos/$GITHUB_REPOSITORY/branches/$candidate" >/dev/null 2>&1; then + target_branch="$candidate" + break + fi + done + if [[ -z "$target_branch" ]]; then + echo "No MMD release branch matches target suffix $target_suffix" >&2 + printf 'Checked branch %s\n' "${candidates[@]}" >&2 + exit 1 + fi + + echo "target_branch=$target_branch" >> "$GITHUB_OUTPUT" + echo "Resolved $RELEASE_VERSION to $target_branch" + + - name: Check out derived release branch + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ steps.route.outputs.target_branch }} + fetch-depth: 0 + + - name: Validate version, target, tag, and prior CI + id: validate + env: + GH_TOKEN: ${{ github.token }} + REQUESTED_VERSION: ${{ inputs.release_version }} + run: | + set -euo pipefail + + value() { sed -n "s/^$1=//p" gradle.properties; } + release_version="$(value mod_version)" + minecraft_version="$(value minecraft_version)" + loader_name="$(value loader_name)" + loader_code="$(value loader_code)" + java_version="$(value java_version)" + java_toolchain_version="$(value java_toolchain_version)" + java_setup_version="$(value java_setup_version)" + gradle_java_version="$(value gradle_java_version)" + curseforge_project_id="$(value curseforge_project_id)" + + if [[ "$(value release_enabled)" != "true" ]]; then + echo "Publication is disabled for this mod" >&2 + exit 1 + fi + + for required in release_version minecraft_version loader_name loader_code \ + java_version gradle_java_version curseforge_project_id; do + if [[ -z "${!required}" ]]; then + echo "Selected ref is missing required release metadata: $required" >&2 + exit 1 + fi + done + java_toolchain_version="${java_toolchain_version:-$java_version}" + java_setup_version="${java_setup_version:-$java_toolchain_version}" + + java_major() { + local version="$1" + if [[ ! "$version" =~ ^([0-9]+)([._+-].*)?$ ]]; then + echo "Invalid Java toolchain version $version" >&2 + return 1 + fi + printf '%s' "${BASH_REMATCH[1]}" + } + requires_separate_gradle_java() { + local toolchain_major + toolchain_major="$(java_major "$1")" + [[ "$toolchain_major" != "$2" ]] + } + + if [[ "$(java_major "$java_setup_version")" != "$(java_major "$java_toolchain_version")" ]]; then + echo "Hosted Java selector $java_setup_version does not match toolchain $java_toolchain_version" >&2 + exit 1 + fi + + install_gradle_java=false + if requires_separate_gradle_java "$java_toolchain_version" "$gradle_java_version"; then + install_gradle_java=true + echo "Gradle Java $gradle_java_version will be installed separately from toolchain $java_toolchain_version" + else + echo "Pinned toolchain $java_toolchain_version also satisfies Gradle Java $gradle_java_version" + fi + + IFS=. read -r mc_major mc_minor mc_patch extra <<<"$minecraft_version" + if [[ -n "${extra:-}" || -z "${mc_major:-}" || -z "${mc_minor:-}" ]]; then + echo "Invalid minecraft_version=$minecraft_version" >&2 + exit 1 + fi + mc_patch="${mc_patch:-0}" + if [[ ! "$mc_major" =~ ^[0-9]+$ || ! "$mc_minor" =~ ^[0-9]+$ || ! "$mc_patch" =~ ^[0-9]+$ ]]; then + echo "Invalid minecraft_version=$minecraft_version" >&2 + exit 1 + fi + case "$loader_name:$loader_code" in + forge:1) loader_display=Forge ;; + neoforge:2) loader_display=NeoForge ;; + *) echo "Invalid loader metadata $loader_name/$loader_code" >&2; exit 1 ;; + esac + if [[ ! "$java_version" =~ ^[0-9]+$ || ! "$gradle_java_version" =~ ^[0-9]+$ ]]; then + echo "Invalid Java metadata $java_version/$gradle_java_version" >&2 + exit 1 + fi + if [[ "$(value release_enabled)" != "true" || ! "$curseforge_project_id" =~ ^[1-9][0-9]*$ ]]; then + echo "Publication is disabled until this mod has its own CurseForge project" >&2 + exit 1 + fi + + printf -v minor_padded '%02d' "$((10#$mc_minor))" + printf -v patch_padded '%02d' "$((10#$mc_patch))" + target_suffix="${mc_major}${minor_padded}${patch_padded}${loader_code}" + if [[ ! "$release_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.${target_suffix}$ ]]; then + echo "mod_version $release_version does not match $minecraft_version $loader_display target $target_suffix" >&2 + exit 1 + fi + if [[ "$REQUESTED_VERSION" != "$release_version" ]]; then + echo "Requested version $REQUESTED_VERSION does not match ${{ steps.route.outputs.target_branch }} mod_version $release_version" >&2 + exit 1 + fi + + release_sha="$(git rev-parse HEAD)" + release_tag="$release_version" + echo "release_sha=$release_sha" >> "$GITHUB_OUTPUT" + echo "release_version=$release_version" >> "$GITHUB_OUTPUT" + echo "release_tag=$release_tag" >> "$GITHUB_OUTPUT" + echo "minecraft_version=$minecraft_version" >> "$GITHUB_OUTPUT" + echo "loader_name=$loader_name" >> "$GITHUB_OUTPUT" + echo "loader_display=$loader_display" >> "$GITHUB_OUTPUT" + echo "java_version=$java_version" >> "$GITHUB_OUTPUT" + echo "java_toolchain_version=$java_toolchain_version" >> "$GITHUB_OUTPUT" + echo "java_setup_version=$java_setup_version" >> "$GITHUB_OUTPUT" + echo "gradle_java_version=$gradle_java_version" >> "$GITHUB_OUTPUT" + echo "install_gradle_java=$install_gradle_java" >> "$GITHUB_OUTPUT" + echo "curseforge_project_id=$curseforge_project_id" >> "$GITHUB_OUTPUT" + echo "main_jar=SkysRealisticWeather-$release_version.jar" >> "$GITHUB_OUTPUT" + echo "sources_jar=SkysRealisticWeather-$release_version-sources.jar" >> "$GITHUB_OUTPUT" + echo "javadoc_jar=SkysRealisticWeather-$release_version-javadoc.jar" >> "$GITHUB_OUTPUT" + echo "api_jar=SkysRealisticWeather-$release_version-api.jar" >> "$GITHUB_OUTPUT" + + successful_ci="$(gh api \ + "repos/$GITHUB_REPOSITORY/commits/$release_sha/check-runs?per_page=100" \ + --jq '[.check_runs[] | select(.name == "Build, test, and audit" and .conclusion == "success")] | length')" + if [[ "$successful_ci" -lt 1 ]]; then + echo "The selected commit has no successful Build, test, and audit check" >&2 + exit 1 + fi + + if tag_json="$(gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$release_tag" 2>/dev/null)"; then + tag_sha="$(jq -r '.object.sha' <<<"$tag_json")" + if [[ "$tag_sha" != "$release_sha" ]]; then + echo "Existing tag $release_tag resolves to $tag_sha instead of $release_sha" >&2 + exit 1 + fi + fi + + build: + name: Build immutable release artifact + needs: preflight + runs-on: ubuntu-latest + timeout-minutes: 60 + env: + MAIN_JAR: ${{ needs.preflight.outputs.main_jar }} + SOURCES_JAR: ${{ needs.preflight.outputs.sources_jar }} + JAVADOC_JAR: ${{ needs.preflight.outputs.javadoc_jar }} + API_JAR: ${{ needs.preflight.outputs.api_jar }} + outputs: + artifact_name: ${{ steps.artifact.outputs.name }} + + steps: + - name: Check out validated release ref + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.preflight.outputs.release_sha }} + + - name: Install target Java toolchain + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5 + with: + distribution: temurin + java-version: ${{ needs.preflight.outputs.java_setup_version }} + + - name: Install separate Java for Gradle + if: needs.preflight.outputs.install_gradle_java == 'true' + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5 + with: + distribution: temurin + java-version: ${{ needs.preflight.outputs.gradle_java_version }} + + - name: Pin Java 8 dependency builds + if: needs.preflight.outputs.java_version == '8' + run: | + echo "SKY_WEATHER_JAVA8_HOME=$JAVA_HOME_8_X64" >> "$GITHUB_ENV" + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6 + + + - name: Build, test, and audit once + run: | + chmod +x ./gradlew + ./gradlew clean check build verifyReleaseArtifacts writeReleaseChecksums \ + -PweatherProductionOnly=true --max-workers=2 --no-daemon --stacktrace + + - name: Stage the immutable release artifact + id: artifact + run: | + set -euo pipefail + bundle="$RUNNER_TEMP/release-bundle" + mkdir -p "$bundle" + cp "build/libs/$MAIN_JAR" "$bundle/" + cp "build/libs/$SOURCES_JAR" "$bundle/" + cp "build/libs/$JAVADOC_JAR" "$bundle/" + cp "build/libs/$API_JAR" "$bundle/" + cp publishing/curseforge-relations.json "$bundle/" + cp build/release/SHA256SUMS "$bundle/" + cp CHANGELOG.md "$bundle/" + (cd "$bundle" && sha256sum --check SHA256SUMS) + echo "name=SkysRealisticWeather-${{ needs.preflight.outputs.minecraft_version }}-${{ needs.preflight.outputs.loader_name }}-${{ needs.preflight.outputs.release_sha }}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" >> "$GITHUB_OUTPUT" + + - name: Upload immutable release artifact + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: ${{ steps.artifact.outputs.name }} + if-no-files-found: error + retention-days: 90 + path: ${{ runner.temp }}/release-bundle/* + + - name: Summarize the prepared release candidate + env: + RELEASE_BRANCH: ${{ needs.preflight.outputs.target_branch }} + RELEASE_LEVEL: ${{ inputs.curseforge_release_level }} + RELEASE_SHA: ${{ needs.preflight.outputs.release_sha }} + RELEASE_VERSION: ${{ needs.preflight.outputs.release_version }} + run: | + { + echo "## Prepared release candidate" + echo + echo "- Version: \`$RELEASE_VERSION\`" + echo "- Target branch: \`$RELEASE_BRANCH\`" + echo "- Commit: \`$RELEASE_SHA\`" + echo "- CurseForge release level: \`$RELEASE_LEVEL\`" + echo "- GitHub Release type: ordinary release" + echo + echo "### Public artifact checksums" + echo '```text' + cat build/release/SHA256SUMS + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + + release_confirmation: + name: Confirm ${{ inputs.release_version }} live publication + needs: + - preflight + - build + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Confirm publication and release-secret access + env: + CONFIRM_LIVE_PUBLICATION: ${{ inputs.confirm_live_publication }} + CURSEFORGE_TOKEN: ${{ secrets.CURSEFORGE_TOKEN }} + MAVEN_UPLOAD_URL: ${{ secrets.MAVEN_UPLOAD_URL }} + MAVEN_UPLOAD_USERNAME: ${{ secrets.MAVEN_UPLOAD_USERNAME }} + MAVEN_UPLOAD_PASSWORD: ${{ secrets.MAVEN_UPLOAD_PASSWORD }} + run: | + set -euo pipefail + if [[ "$CONFIRM_LIVE_PUBLICATION" != "true" ]]; then + echo "Confirm live publication in the workflow form before releasing ${{ needs.preflight.outputs.release_tag }}" >&2 + exit 1 + fi + echo "Live publication confirmed for ${{ needs.preflight.outputs.release_tag }}" + missing=() + for name in CURSEFORGE_TOKEN MAVEN_UPLOAD_URL MAVEN_UPLOAD_USERNAME MAVEN_UPLOAD_PASSWORD; do + if [[ -z "${!name:-}" ]]; then + missing+=("$name") + fi + done + if (( ${#missing[@]} > 0 )); then + printf 'Required release secret is unavailable: %s\n' "${missing[@]}" >&2 + exit 1 + fi + echo "All four required release secrets are available." + + create_release_tag: + name: Create validated release tag + needs: + - preflight + - build + - release_confirmation + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + actions: read + contents: write + + steps: + - name: Create or verify the exact tag + env: + GH_TOKEN: ${{ github.token }} + RELEASE_SHA: ${{ needs.preflight.outputs.release_sha }} + RELEASE_TAG: ${{ needs.preflight.outputs.release_tag }} + run: | + set -euo pipefail + + if tag_json="$(gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$RELEASE_TAG" 2>/dev/null)"; then + tag_sha="$(jq -r '.object.sha' <<<"$tag_json")" + if [[ "$tag_sha" != "$RELEASE_SHA" ]]; then + echo "Existing tag $RELEASE_TAG resolves to $tag_sha instead of $RELEASE_SHA" >&2 + exit 1 + fi + echo "Existing tag $RELEASE_TAG already points to $RELEASE_SHA" + else + gh api --method POST "repos/$GITHUB_REPOSITORY/git/refs" \ + -f ref="refs/tags/$RELEASE_TAG" \ + -f sha="$RELEASE_SHA" >/dev/null + echo "Created tag $RELEASE_TAG at $RELEASE_SHA" + fi + + created_sha="$(gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$RELEASE_TAG" --jq '.object.sha')" + if [[ "$created_sha" != "$RELEASE_SHA" ]]; then + echo "Tag verification returned $created_sha instead of $RELEASE_SHA" >&2 + exit 1 + fi + + publish_maven: + name: Publish Maven + needs: + - preflight + - build + - create_release_tag + runs-on: ubuntu-latest + timeout-minutes: 30 + + steps: + - name: Check out the tagged publication definition + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.preflight.outputs.release_sha }} + + - name: Install target Java toolchain + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5 + with: + distribution: temurin + java-version: ${{ needs.preflight.outputs.java_setup_version }} + + - name: Install separate Java for Gradle + if: needs.preflight.outputs.install_gradle_java == 'true' + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5 + with: + distribution: temurin + java-version: ${{ needs.preflight.outputs.gradle_java_version }} + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6 + + + - name: Download immutable release artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + with: + name: ${{ needs.build.outputs.artifact_name }} + path: ${{ runner.temp }}/release-input + + - name: Verify artifact and Maven credentials + env: + MAVEN_UPLOAD_URL: ${{ secrets.MAVEN_UPLOAD_URL }} + MAVEN_UPLOAD_USERNAME: ${{ secrets.MAVEN_UPLOAD_USERNAME }} + MAVEN_UPLOAD_PASSWORD: ${{ secrets.MAVEN_UPLOAD_PASSWORD }} + run: | + set -euo pipefail + (cd "$RUNNER_TEMP/release-input" && sha256sum --check SHA256SUMS) + if [[ -z "$MAVEN_UPLOAD_URL" || -z "$MAVEN_UPLOAD_USERNAME" || -z "$MAVEN_UPLOAD_PASSWORD" ]]; then + echo "Maven upload URL and credentials must all be configured" >&2 + exit 1 + fi + if [[ "$MAVEN_UPLOAD_URL" == file:* ]]; then + echo "Maven publication cannot target a runner-local repository" >&2 + exit 1 + fi + + - name: Publish the prepared Maven artifacts + env: + MAVEN_UPLOAD_URL: ${{ secrets.MAVEN_UPLOAD_URL }} + MAVEN_UPLOAD_USERNAME: ${{ secrets.MAVEN_UPLOAD_USERNAME }} + MAVEN_UPLOAD_PASSWORD: ${{ secrets.MAVEN_UPLOAD_PASSWORD }} + run: | + chmod +x ./gradlew + ./gradlew publishMavenJavaPublicationToReleaseRepository \ + -PpreparedReleaseDir="$RUNNER_TEMP/release-input" -PweatherProductionOnly=true \ + --no-daemon --stacktrace + + publish_curseforge: + name: Publish CurseForge + needs: + - preflight + - build + - publish_maven + runs-on: ubuntu-latest + timeout-minutes: 20 + + steps: + - name: Download immutable release artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + with: + name: ${{ needs.build.outputs.artifact_name }} + path: ${{ runner.temp }}/release-input + + - name: Verify artifact and CurseForge credential + env: + CURSEFORGE_TOKEN: ${{ secrets.CURSEFORGE_TOKEN }} + run: | + set -euo pipefail + (cd "$RUNNER_TEMP/release-input" && sha256sum --check SHA256SUMS) + if [[ -z "$CURSEFORGE_TOKEN" ]]; then + echo "CURSEFORGE_TOKEN must be configured" >&2 + exit 1 + fi + + - name: Read the version-specific optional relationships + id: relations + run: | + delimiter="RELATIONS_$GITHUB_RUN_ID" + { + echo "dependencies<<$delimiter" + jq -r '.projects[] | "\(.slug)(optional)"' "$RUNNER_TEMP/release-input/curseforge-relations.json" + echo "$delimiter" + } >> "$GITHUB_OUTPUT" + + - name: Publish Sky's Realistic Weather + uses: Kira-NT/mc-publish@52307b03863581dec6b652b83e597aec02ebb075 # v3.3.1 + with: + curseforge-token: ${{ secrets.CURSEFORGE_TOKEN }} + curseforge-id: ${{ needs.preflight.outputs.curseforge_project_id }} + dependencies: ${{ steps.relations.outputs.dependencies }} + # A timeout or HTTP 500 can follow an accepted upload. Check the file before retrying. + curseforge-retry-attempts: 1 + name: Sky's Realistic Weather ${{ needs.preflight.outputs.release_version }} for Minecraft ${{ needs.preflight.outputs.minecraft_version }} (${{ needs.preflight.outputs.loader_display }}) + version: ${{ needs.preflight.outputs.release_version }} + version-type: ${{ inputs.curseforge_release_level }} + changelog-file: ${{ runner.temp }}/release-input/CHANGELOG.md + loaders: ${{ needs.preflight.outputs.loader_name }} + game-versions: ${{ needs.preflight.outputs.minecraft_version }} + game-version-filter: none + environment: client | server + java: Java ${{ needs.preflight.outputs.java_version }} + fail-mode: fail + files: | + ${{ runner.temp }}/release-input/${{ needs.preflight.outputs.main_jar }} + ${{ runner.temp }}/release-input/${{ needs.preflight.outputs.sources_jar }} + ${{ runner.temp }}/release-input/${{ needs.preflight.outputs.javadoc_jar }} + + publish_github: + name: Publish GitHub Release + needs: + - preflight + - build + - publish_curseforge + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + actions: read + contents: write + + steps: + - name: Download immutable release artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + with: + name: ${{ needs.build.outputs.artifact_name }} + path: ${{ runner.temp }}/release-input + + - name: Verify artifact + run: (cd "$RUNNER_TEMP/release-input" && sha256sum --check SHA256SUMS) + + - name: Publish GitHub Release last + uses: Kira-NT/mc-publish@52307b03863581dec6b652b83e597aec02ebb075 # v3.3.1 + with: + github-token: ${{ github.token }} + github-tag: ${{ needs.preflight.outputs.release_tag }} + github-commitish: ${{ needs.preflight.outputs.release_sha }} + github-draft: false + github-prerelease: false + name: Sky's Realistic Weather ${{ needs.preflight.outputs.release_version }} for Minecraft ${{ needs.preflight.outputs.minecraft_version }} (${{ needs.preflight.outputs.loader_display }}) + version: ${{ needs.preflight.outputs.release_version }} + version-type: release + changelog-file: ${{ runner.temp }}/release-input/CHANGELOG.md + fail-mode: fail + files: | + ${{ runner.temp }}/release-input/${{ needs.preflight.outputs.main_jar }} + ${{ runner.temp }}/release-input/${{ needs.preflight.outputs.sources_jar }} + ${{ runner.temp }}/release-input/${{ needs.preflight.outputs.javadoc_jar }} + ${{ runner.temp }}/release-input/${{ needs.preflight.outputs.api_jar }} + ${{ runner.temp }}/release-input/SHA256SUMS + + - name: Keep the newer Minecraft release as the GitHub default + if: needs.preflight.outputs.minecraft_version == '1.10.2' + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ needs.preflight.outputs.release_tag }} + run: | + id="$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$RELEASE_TAG" --jq '.id')" + gh api --method PATCH "repos/$GITHUB_REPOSITORY/releases/$id" -f make_latest=false >/dev/null diff --git a/.github/workflows/release-on-tag.yml b/.github/workflows/release-on-tag.yml new file mode 100644 index 0000000..82501ed --- /dev/null +++ b/.github/workflows/release-on-tag.yml @@ -0,0 +1,29 @@ +name: Validate release tag +on: + push: + tags: ['*.*.*.*'] +permissions: + actions: read + contents: read +jobs: + validate: + name: Validate tag without publication + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - name: Validate version and prior artifact audit + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + version="$(sed -n 's/^mod_version=//p' gradle.properties)" + test "$GITHUB_REF_NAME" = "$version" + minecraft="$(sed -n 's/^minecraft_version=//p' gradle.properties)" + loader="$(sed -n 's/^loader_code=//p' gradle.properties)" + IFS=. read -r major minor patch <<<"$minecraft" + printf -v suffix '%s%02d%02d%s' "$major" "$((10#$minor))" "$((10#${patch:-0}))" "$loader" + [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.${suffix}$ ]] + checks="$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA/check-runs?per_page=100" --jq '[.check_runs[] | select(.name == "Build, test, and audit" and .conclusion == "success")] | length')" + test "$checks" -gt 0 + echo "verifyReleaseArtifacts passed in CI. This tag check publishes nothing." diff --git a/.github/workflows/validate-gradle-build.yml b/.github/workflows/validate-gradle-build.yml new file mode 100644 index 0000000..ec824d9 --- /dev/null +++ b/.github/workflows/validate-gradle-build.yml @@ -0,0 +1,25 @@ +name: Validate Gradle Wrapper + +on: + push: + branches: + - 'master-*' + - 'feature/**' + - 'release/**' + - 'updates/**' + pull_request: + branches: + - 'master-*' + +permissions: + contents: read + +jobs: + validation: + name: Validation + runs-on: ubuntu-latest + steps: + - name: Check out source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - name: Validate wrapper integrity + uses: gradle/actions/wrapper-validation@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..1b3b4f8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,21 @@ +# Changelog + +## 0.1.21.111021 + +Sky's Realistic Weather is now available for Minecraft 1.11.2. This brings over +the changing seasons, local climates, farming support, thermometers and local +heating from the 1.10.2 version. + +- Added support for the 1.11.2 versions of the optional farming, information, + survival and terrain mods listed in the compatibility guide. +- Kept terrain providers' normal tree and park generation working during winter. +- Made the JEI climate panel fit smaller windows, with the full explanation + available from its question-mark tooltip. +- Fixed item names and thermometer labels showing their untranslated keys. +- Added translated item names, thermometer instructions, HUD labels and + keybindings in the same language variants as the other Sky's mods. + +The default year is still 365 Minecraft days, with Per Biome Climate enabled. +RTG, Thaumcraft and AgriCraft support remains available on 1.10.2; they are not +included in the 1.11.2 compatibility list. The config and admin editors still +use English. diff --git a/README.md b/README.md index d25ef66..7889466 100644 --- a/README.md +++ b/README.md @@ -60,9 +60,11 @@ body temperature and survival systems. JEI, Hwyla and The One Probe provide crop climate information. Operator validation and JSON reports help diagnose pack rules. See [modpack support](docs/PACK_SUPPORT.md). -This is the local **1.11.2 port**, version **0.1.21.111021**. See the -[port status and integration matrix](docs/PORTING_1_11_2.md) for tested builds -and remaining acceptance checks. +This branch is for **Minecraft 1.11.2**, version **0.1.21.111021**. See the +[compatibility guide](docs/PORTING_1_11_2.md) for the supported mod versions. +The [changelog](CHANGELOG.md) covers what's changed, and the +[wiki](https://github.com/MinecraftModDevelopmentMods/SkysRealisticWeather/wiki) +has guides for players, pack makers and other mod developers. ## Install @@ -92,4 +94,5 @@ Weather data provided by [Open-Meteo.com](https://open-meteo.com/). - [Weather controller and server commands](docs/ADMIN.md) - [Build and verification](docs/BUILDING.md) - [Languages and translation coverage](docs/LANGUAGES.md) +- [Preparing a release](docs/RELEASING.md) - [Licence](LICENSE) and [credits](NOTICE) diff --git a/build.gradle b/build.gradle index 9fe5a15..4289189 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,7 @@ plugins { id 'java' id 'eclipse' + id 'maven-publish' id 'net.minecraftforge.renamer' version '1.1.5' id 'net.minecraftforge.gradle' version '7.0.34' } @@ -184,6 +185,8 @@ tasks.register('writeReleaseChecksum') { } } +if (!providers.gradleProperty('weatherProductionOnly').getOrElse('false').toBoolean()) { + sourceSets { integrationTest { compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath @@ -264,3 +267,9 @@ def packagedControlProbe = renamer.classes(controlProbe) { output = layout.buildDirectory.file('verification/probe/weather-control-probe.jar') } tasks.register('prepareControlProbe') { dependsOn packagedControlProbe, tasks.named('prepareRuntimeProbe') } + +} + +ext.weatherReleaseJar = releaseJar +ext.weatherApiJar = apiJar +apply from: 'gradle/release.gradle' diff --git a/docs/API.md b/docs/API.md index 0496582..6ed4685 100644 --- a/docs/API.md +++ b/docs/API.md @@ -15,6 +15,11 @@ dependencies { } ``` +The published compile-only coordinate is +`zone.moddev.mc.skysrealisticweather:SkysRealisticWeather:0.1.21.111021:api`. +Use the MMD Maven repository configured by your project. The API jar does not +replace the main mod at runtime. + API 8 retains the API 7 method signatures and appends `FIRE`, `LAVA` and `TORCH` to `TemperatureSample.Source`. Local queries include their server-configured warmth; outdoor and world-generation queries remain independent. The source ID diff --git a/docs/PORTING_1_11_2.md b/docs/PORTING_1_11_2.md index 788356f..1697d63 100644 --- a/docs/PORTING_1_11_2.md +++ b/docs/PORTING_1_11_2.md @@ -1,7 +1,7 @@ # Minecraft 1.11.2 port This checkout targets **Minecraft 1.11.2**, **Forge 13.20.1.2588**, Java 8, -and stable **32-1.11** mappings. The local candidate is **0.1.21.111021**, +and stable **32-1.11** mappings. The release version is **0.1.21.111021**, with **API 8**, **config 8** and **world settings schema 1**. It starts from the merged 1.10.2 implementation at `a4c6f7930c06cd97c2a503deecc6f92137c167f3`. @@ -114,8 +114,9 @@ See `RESULT.md` and artifact-bound receipts in each, including preserved unsuccessful attempts. [Build instructions](BUILDING.md) explain how to repeat the checks with fresh disposable worlds. -The port is local and unpublished. General manual client gameplay and visual -acceptance remain separate work. Targeted JEI client checks, automated -two-client multiplayer and the new whole-chunk baseline are complete for the -documented scenarios. Published 1.10.2 timings and the 1.10.2 Sylvester pack -are not used to claim 1.11.2 coverage. No player world is launched by these tests. +This version has been accepted for release after local gameplay testing. +Targeted JEI client checks, automated two-client multiplayer and the new +whole-chunk baseline cover the documented scenarios. They do not establish +compatibility with every modpack. Published 1.10.2 timings and the 1.10.2 +Sylvester pack are not used to claim 1.11.2 coverage. No player world is +launched by the automated tests. diff --git a/docs/PROJECT_DESCRIPTION.md b/docs/PROJECT_DESCRIPTION.md index 2a4ef9f..4e2f185 100644 --- a/docs/PROJECT_DESCRIPTION.md +++ b/docs/PROJECT_DESCRIPTION.md @@ -63,9 +63,8 @@ All integrations are optional. The table lists the Minecraft versions each integ | **The Lost Cities** | 1.10.2, 1.11.2 | Seasonal snow and ice generation in Lost Cities worlds. | | **Base Metals** | 1.10.2, 1.11.2 | Supplies mercury for the thermometer recipe. Other mods providing the appropriate mercury ingredient can also be used. | -The 1.11.2 entries describe the local port and its pinned integration builds; -that version is not published yet. Its packaged JEI client checks are complete. -See the [version support guide](https://github.com/MinecraftModDevelopmentMods/SkysRealisticWeather/wiki/Version-Support) for current qualification and download status. +The table is kept by Minecraft version so you can check the integrations for +your pack. See the [version support guide](https://github.com/MinecraftModDevelopmentMods/SkysRealisticWeather/wiki/Version-Support) for tested builds and download status. ## Tools for players and pack makers diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md index fbf4f2e..74fcb7b 100644 --- a/docs/PUBLISHING.md +++ b/docs/PUBLISHING.md @@ -24,10 +24,10 @@ the entire object as the value of `relations`, for example: metadata["relations"] = json.loads(Path("publishing/curseforge-relations.json").read_text()) ``` -The repository currently has no automatic CurseForge uploader, so this file is -prepared input, not an active publication step. A manual website upload must -select the matching projects as **Optional Dependency** under Related Projects. -Uploading the jar or placing this JSON beside it does not submit those relations. +The MMD release workflow reads this file and submits its entries as optional +relationships for the selected release. A manual website upload must select +the matching projects under Related Projects. See [releasing](RELEASING.md) +for the build, publication and public-download checks. Keep relations specific to the Minecraft version being uploaded. This list excludes RTG, Thaumcraft, AgriCraft and BYG because this port has no qualified diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 0000000..078a2d8 --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,46 @@ +# Releasing Sky's Realistic Weather + +The build, artifact audit, CodeQL and wrapper checks run on pull requests and +version branches. Gameplay, multiplayer and long climate checks run locally in +disposable profiles. Their results are kept separately from hosted CI. + +Publication uses the same approach as Sky's Building Pieces and Sky's Terrain +Smoother. The MMD workflow builds one bundle from the checked commit, verifies +its contents and checksums, then publishes those files to Maven, CurseForge +and GitHub in that order. A tag by itself does not publish anything. + +The bundle contains the main mod, compile-only API, sources and Javadoc jars. +Maven and GitHub receive all four. CurseForge receives the main mod with its +sources and Javadocs attached. Only the main mod belongs in a playable profile. + +Run **Release Sky's Realistic Weather** from the MMD repository's Actions tab. +Enter the four-component version, choose the CurseForge release level and +confirm publication. The version suffix selects the Minecraft branch. Keep +each version's optional relationships in `publishing/curseforge-relations.json`; +the uploader reads this file rather than relying on `mcmod.info`. + +Use `validate_access_only` to check the shared credentials without building, +tagging or publishing. The workflow needs `CURSEFORGE_TOKEN`, +`MAVEN_UPLOAD_URL`, `MAVEN_UPLOAD_USERNAME` and `MAVEN_UPLOAD_PASSWORD`. +Credentials must be available to this repository before publication starts. +Fork workflows never publish. + +Local release checks: + +```text +gradlew check build verifyReleaseArtifacts writeReleaseChecksums -PweatherProductionOnly=true +``` + +The production-only option skips development compatibility profiles and probe +jars. It keeps the normal runtime, unit tests and artifact checks. Ordinary +Eclipse builds still prepare their separate compatibility launch files. + +The release audit checks Java compatibility, version metadata, translations, +licences and unwanted archive entries. A bundle test also checks that a changed +jar is rejected. Maven publication accepts only the prepared, verified bundle. + +After publication, check every destination and compare the public downloads +with the bundle's checksums. An accepted CurseForge upload can take time to +appear publicly. Keep its file ID and check its status before retrying; a +timeout does not prove that the upload failed. Rerun only the failed stage +when earlier stages have succeeded. diff --git a/gradle.properties b/gradle.properties index c3a137b..74e98da 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,3 +12,12 @@ mod_name=Sky's Realistic Weather mod_version=0.1.21.111021 mod_group=zone.moddev.mc.skysrealisticweather mod_description=Four seasons, local climate and optional real-world weather for the Overworld. + +loader_name=forge +loader_code=1 +java_version=8 +java_toolchain_version=8.0.502+7 +gradle_java_version=17 +release_repository=MinecraftModDevelopmentMods/SkysRealisticWeather +release_enabled=true +curseforge_project_id=1834635 diff --git a/gradle/eclipse-runs.gradle b/gradle/eclipse-runs.gradle index f505079..f7cd315 100644 --- a/gradle/eclipse-runs.gradle +++ b/gradle/eclipse-runs.gradle @@ -1,6 +1,9 @@ import groovy.xml.XmlParser import groovy.xml.XmlUtil +// Hosted release builds do not prepare optional development profiles. +if (providers.gradleProperty('weatherProductionOnly').getOrElse('false').toBoolean()) return + def modCoordinates = [ BoP : 'biomes-o-plenty-220318:2536549', OTG : 'open-terrain-generator-265894:2530369', diff --git a/gradle/release.gradle b/gradle/release.gradle new file mode 100644 index 0000000..c003806 --- /dev/null +++ b/gradle/release.gradle @@ -0,0 +1,223 @@ +import groovy.json.JsonSlurper +import java.nio.charset.StandardCharsets +import java.security.MessageDigest +import java.util.zip.ZipFile +import org.apache.tools.ant.filters.FixCrLfFilter + +// The release jobs all consume these same, audited files. +ext.releaseFiles = providers.provider { + ['', '-sources', '-javadoc', '-api'].collect { "SkysRealisticWeather-${project.version}${it}.jar".toString() } +} +def hash = { File file -> MessageDigest.getInstance('SHA-256').digest(file.bytes).encodeHex().toString() } +def textPatterns = ['**/*.java', '**/*.json', '**/*.lang', '**/*.info', '**/*.mcmeta', '**/*.html', + '**/*.js', '**/*.css', '**/*.txt', '**/*.md', '**/element-list', '**/package-list', + '**/LICENSE', '**/LICENSE.spdx', '**/NOTICE'] +tasks.withType(Jar).configureEach { + filteringCharset = 'UTF-8' + filesMatching(textPatterns) { + filter(FixCrLfFilter, eol: FixCrLfFilter.CrLf.newInstance('lf'), + eof: FixCrLfFilter.AddAsisRemove.newInstance('asis')) + } +} +['sourcesJar', 'javadocJar'].each { name -> + tasks.named(name, Jar) { from(['LICENSE', 'LICENSE.spdx', 'NOTICE']) { into 'META-INF' } } +} + +tasks.register('verifyReleaseMetadata') { + group = 'verification' + doLast { + def mc = project.minecraft_version.tokenize('.')*.toInteger() + String suffix = String.format('%d%02d%02d1', mc[0], mc[1], mc[2]) + if (!(project.version.toString() ==~ /\d+\.\d+\.\d+\.${suffix}/) || project.loader_name != 'forge' || + project.loader_code != '1' || project.java_version != '8' || + project.mod_id != 'skysrealisticweather' || project.curseforge_project_id != '1834635' || + project.release_repository != 'MinecraftModDevelopmentMods/SkysRealisticWeather') { + throw new GradleException('Release version, target or project identity is inconsistent') + } + String header = "## ${project.version}" + if (!file('CHANGELOG.md').getText('UTF-8').readLines().contains(header)) + throw new GradleException("CHANGELOG.md must contain ${header}") + def projects = new JsonSlurper().parse(file('publishing/curseforge-relations.json')).projects + if (!projects || projects*.slug.toSet().size() != projects.size() || projects.any { + !(it.slug ==~ /[a-z0-9-]+/) || it.type != 'optionalDependency' + }) throw new GradleException('Invalid or duplicate optional CurseForge relationships') + } +} + +tasks.register('verifyReleaseArtifacts') { + group = 'verification' + dependsOn tasks.named('assemble'), tasks.named('verifyReleaseMetadata') + doLast { + File libs = layout.buildDirectory.dir('libs').get().asFile + releaseFiles.get().each { name -> + File artifact = new File(libs, name) + if (!artifact.isFile() || artifact.length() == 0) throw new GradleException("Missing ${name}") + new ZipFile(artifact).withCloseable { zip -> + zip.entries().each { entry -> + String lower = entry.name.toLowerCase(Locale.ROOT) + if (lower.tokenize('/').any { it in ['agents.md', 'agent.md', 'agent-notes', 'agent_notes', '.codex', '.claude'] } || + lower.contains('/verify/') || lower.contains('/fixture/') || lower.contains('/test/') || + lower.startsWith('net/minecraft/') || lower.startsWith('net/minecraftforge/')) + throw new GradleException("Unwanted release entry in ${name}: ${entry.name}") + if (!entry.directory) { + byte[] bytes = zip.getInputStream(entry).bytes + if (entry.name.endsWith('.class') && (((bytes[6] & 255) << 8) | (bytes[7] & 255)) != 52) + throw new GradleException("Non-Java-8 class: ${entry.name}") + String content = new String(bytes, StandardCharsets.ISO_8859_1).toLowerCase(Locale.ROOT) + if (content.find(/[a-z]:[\\\/]users[\\\/]|d:[\\\/]skysgrassslabs|ghp_[a-z0-9]{30,}|github_pat_[a-z0-9_]{40,}/)) + throw new GradleException("Local path or possible credential in ${name}: ${entry.name}") + } + } + ['META-INF/LICENSE', 'META-INF/LICENSE.spdx', 'META-INF/NOTICE'].each { + if (zip.getEntry(it) == null) throw new GradleException("${name} is missing ${it}") + } + if (name.endsWith('-api.jar') && zip.entries().any { + it.name.endsWith('.class') && !it.name.startsWith('zone/moddev/mc/skysrealisticweather/api/') + }) throw new GradleException('The API artifact contains implementation classes') + } + } + new ZipFile(new File(libs, releaseFiles.get()[0])).withCloseable { zip -> + def metadata = new JsonSlurper().parseText(zip.getInputStream(zip.getEntry('mcmod.info')).getText('UTF-8'))[0] + if (metadata.modid != project.mod_id || metadata.version != project.version || metadata.mcversion != project.minecraft_version || + metadata.containsKey('dependencies') || metadata.containsKey('useDependencyInformation')) + throw new GradleException('Packaged mod metadata is inconsistent') + def pack = new JsonSlurper().parseText(zip.getInputStream(zip.getEntry('pack.mcmeta')).getText('UTF-8')).pack + boolean legacy = project.minecraft_version == '1.10.2' + if (pack.pack_format != (legacy ? 2 : 3)) throw new GradleException('Incorrect resource pack format') + def locales = ['de_AT','de_AU','de_DE','en_CA','en_EN','en_GB','en_PT','en_US','es_ES','es_MX', + 'fr_CA','fr_FR','ja_JP','ko_KR','pt_BR','pt_PT','ru_RU','zh_CN'] + def read = { String locale -> + String name = "assets/${project.mod_id}/lang/${legacy ? locale : locale.toLowerCase(Locale.ROOT)}.lang" + def entry = zip.getEntry(name) + if (entry == null) throw new GradleException("Missing ${name}") + byte[] bytes = zip.getInputStream(entry).bytes + String text = StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString() + if (text.startsWith('\uFEFF') || text.contains('\uFFFD')) throw new GradleException("Invalid encoding: ${name}") + def result = [:] + text.readLines().findAll { it && !it.startsWith('#') }.each { line -> + int equals = line.indexOf('=') + if (equals < 1 || equals == line.length() - 1 || result.put(line.substring(0, equals), line.substring(equals + 1)) != null) + throw new GradleException("Invalid or duplicate language key in ${name}") + } + return result + } + def english = read('en_US') + locales.each { locale -> + if (read(locale).keySet() != english.keySet()) throw new GradleException("Incomplete ${locale} translations") + } + Set packaged = zip.entries().findAll { it.name.startsWith("assets/${project.mod_id}/lang/") && it.name.endsWith('.lang') }*.name as Set + if (packaged.size() != locales.size()) throw new GradleException('Unexpected language files or filename casing') + if (zip.getEntry('zone/moddev/mc/skysrealisticweather/WeatherMod.class') == null) + throw new GradleException('Main mod class is missing') + } + } +} + +tasks.register('writeReleaseChecksums') { + group = 'verification' + dependsOn tasks.named('verifyReleaseArtifacts') + def output = layout.buildDirectory.file('release/SHA256SUMS') + outputs.file(output) + inputs.files(releaseFiles.map { names -> names.collect { layout.buildDirectory.file("libs/${it}") } }) + doLast { + File target = output.get().asFile + target.parentFile.mkdirs() + target.setText(releaseFiles.get().collect { "${hash(layout.buildDirectory.file('libs/' + it).get().asFile)} ${it}" }.join('\n') + '\n', 'UTF-8') + } +} + +def validateBundle = { File bundle -> + Set expected = (releaseFiles.get() + ['SHA256SUMS','CHANGELOG.md','curseforge-relations.json']) as Set + if ((bundle.listFiles()?.findAll { it.isFile() }*.name as Set) != expected) + throw new GradleException('Prepared release bundle has missing or unexpected files') + Set seen = [] as Set + new File(bundle, 'SHA256SUMS').readLines('UTF-8').each { line -> + def match = line =~ /^([0-9a-fA-F]{64}) ([A-Za-z0-9._-]+)$/ + if (!match.matches() || !expected.contains(match[0][2]) || !seen.add(match[0][2]) || + !hash(new File(bundle, match[0][2])).equalsIgnoreCase(match[0][1])) + throw new GradleException('Prepared artifact checksum mismatch or invalid checksum entry') + } + if (seen != releaseFiles.get().toSet()) throw new GradleException('Prepared release needs four artifact checksums') + if (new File(bundle, 'CHANGELOG.md').getText('UTF-8') != file('CHANGELOG.md').getText('UTF-8') || + new File(bundle, 'curseforge-relations.json').getText('UTF-8') != file('publishing/curseforge-relations.json').getText('UTF-8')) + throw new GradleException('Prepared release notes or optional relationships changed') +} +tasks.register('verifyPreparedReleaseArtifacts') { + doLast { validateBundle(file(providers.gradleProperty('preparedReleaseDir').get())) } +} +tasks.register('verifyReleaseBundleContract') { + dependsOn tasks.named('writeReleaseChecksums') + doLast { + File bundle = layout.buildDirectory.dir("verification/release-contract/${project.version}").get().asFile + bundle.mkdirs() + copy { from layout.buildDirectory.dir('libs'); include releaseFiles.get(); into bundle } + copy { from 'CHANGELOG.md', 'publishing/curseforge-relations.json', layout.buildDirectory.file('release/SHA256SUMS'); into bundle } + validateBundle(bundle) + File main = new File(bundle, releaseFiles.get()[0]) + byte[] original = main.bytes + try { + main.append('changed', 'UTF-8') + boolean rejected = false + try { validateBundle(bundle) } catch (GradleException expected) { rejected = expected.message.contains('checksum mismatch') } + if (!rejected) throw new GradleException('Modified release artifact was accepted') + } finally { main.bytes = original } + } +} +tasks.named('check') { dependsOn 'verifyReleaseBundleContract' } + +tasks.register('compilePublicApiConsumer', JavaCompile) { + group = 'verification' + dependsOn weatherApiJar + source fileTree('src/apiTest/java') + classpath = files(weatherApiJar.flatMap { it.archiveFile }) + sourceSets.main.compileClasspath + destinationDirectory = layout.buildDirectory.dir('verification/api-consumer/classes') + javaCompiler = javaToolchains.compilerFor { languageVersion = JavaLanguageVersion.of(8) } + options.encoding = 'UTF-8' +} +tasks.named('check') { dependsOn 'compilePublicApiConsumer' } + +publishing { + publications { + register('mavenJava', MavenPublication) { + artifactId = 'SkysRealisticWeather' + if (providers.gradleProperty('preparedReleaseDir').isPresent()) { + releaseFiles.get().eachWithIndex { name, index -> + artifact(file("${providers.gradleProperty('preparedReleaseDir').get()}/${name}")) { + extension = 'jar' + if (index > 0) classifier = ['sources','javadoc','api'][index - 1] + } + } + } else { + artifact weatherReleaseJar + artifact tasks.named('sourcesJar') + artifact tasks.named('javadocJar') + artifact weatherApiJar + } + pom { + name = project.mod_name + description = project.mod_description + url = 'https://github.com/' + project.release_repository + licenses { license { name = 'LGPL-2.1-only'; url = 'https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt' } } + scm { url = 'https://github.com/' + project.release_repository; connection = 'scm:git:' + url.get() + '.git' } + } + } + } + repositories { + maven { + name = 'release' + url = uri(providers.environmentVariable('MAVEN_UPLOAD_URL').getOrElse(layout.buildDirectory.dir('forbidden-local-release').get().asFile.toURI().toString())) + credentials { + username = providers.environmentVariable('MAVEN_UPLOAD_USERNAME').getOrElse('') + password = providers.environmentVariable('MAVEN_UPLOAD_PASSWORD').getOrElse('') + } + } + } +} +tasks.withType(PublishToMavenRepository).configureEach { + dependsOn 'verifyPreparedReleaseArtifacts' + doFirst { + if (project.release_enabled != 'true' || !providers.environmentVariable('MAVEN_UPLOAD_URL').getOrElse('').startsWith('https://') || + ['MAVEN_UPLOAD_USERNAME','MAVEN_UPLOAD_PASSWORD'].any { !providers.environmentVariable(it).isPresent() }) + throw new GradleException('Maven release requires an enabled target and remote HTTPS credentials') + } +} diff --git a/src/apiTest/java/WeatherApiConsumer.java b/src/apiTest/java/WeatherApiConsumer.java new file mode 100644 index 0000000..d47bca5 --- /dev/null +++ b/src/apiTest/java/WeatherApiConsumer.java @@ -0,0 +1,18 @@ +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import zone.moddev.mc.skysrealisticweather.api.*; + +/** Compiled against the API artifact, with no implementation classes on its classpath. */ +final class WeatherApiConsumer { + void sample(World world, BlockPos pos) { + WeatherApi.getLocalTemperature(world, pos); + WeatherApi.getTemperatureSample(world, pos); + WeatherApi.getWeather(world, pos); + WeatherApi.getClimate(world, pos); + WeatherApi.getPlantGrowth(world, pos); + TemperatureZone zone = TemperatureZone.celsius( + new net.minecraft.util.ResourceLocation("consumer", "greenhouse"), pos, pos.add(8, 4, 8), 20); + WeatherApi.putTemperatureZone(world, zone); + WeatherApi.removeTemperatureZone(world, zone.id); + } +} From 4c97c8cc6bcb0e13bf1c682b67938f88fa98984f Mon Sep 17 00:00:00 2001 From: JohnBraham Date: Fri, 27 Nov 2026 23:17:53 +0000 Subject: [PATCH 9/9] Handle build-tool rate limits and refresh release checksums --- .github/workflows/codeql-analysis.yml | 2 +- README.md | 2 +- gradle/legacy-tools.gradle | 21 +++++++++++++++++---- gradle/release.gradle | 2 +- 4 files changed, 20 insertions(+), 7 deletions(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index a77cdf4..3e29fac 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -71,7 +71,7 @@ jobs: - name: Compile production code run: | chmod +x ./gradlew - ./gradlew clean classes -PweatherProductionOnly=true --rerun-tasks --no-daemon --stacktrace + ./gradlew clean classes -PweatherProductionOnly=true --rerun-tasks --max-workers=2 --no-daemon --stacktrace - name: Analyze uses: github/codeql-action/analyze@db488ddef3bf6cb639b32c2e9a7c0a7ea8271d28 # v4 diff --git a/README.md b/README.md index 7889466..6e3c50c 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Storm Coast and Two Winters. The standard year lasts 365 Minecraft days. Day/night temperature changes and independent cold spells make weather transitions more noticeable. The British Isles preset represents northern British lowlands, with snowier uplands. See the [climate balance and test -assumptions](docs/TESTING_ASSUMPTIONS.md). The local 1.11.2 candidate also has +assumptions](docs/TESTING_ASSUMPTIONS.md). This version also has [two-client multiplayer and whole-chunk performance results](docs/PERFORMANCE_1_11_2.md). Natural plant growth also follows local temperature. Cool-weather crops, warm diff --git a/gradle/legacy-tools.gradle b/gradle/legacy-tools.gradle index 1f92467..e74c6aa 100644 --- a/gradle/legacy-tools.gradle +++ b/gradle/legacy-tools.gradle @@ -22,10 +22,23 @@ new RandomAccessFile(new File(tool.parentFile, 'specialsource-bootstrap.lock'), if (gradle.startParameter.offline) { throw new GradleException('The pinned legacy SpecialSource tool is missing or invalid. Run once online to restore it.') } - def connection = new URL(toolUrl).openConnection() - connection.connectTimeout = 15000 - connection.readTimeout = 30000 - byte[] downloaded = connection.inputStream.withCloseable { it.bytes } + byte[] downloaded + for (int attempt = 1; attempt <= 3; attempt++) { + def connection = new URL(toolUrl).openConnection() + connection.connectTimeout = 15000 + connection.readTimeout = 30000 + try { + downloaded = connection.inputStream.withCloseable { it.bytes } + break + } catch (IOException failure) { + int status = connection.responseCode + if (attempt == 3 || (status != 429 && status < 500)) throw failure + logger.lifecycle('Legacy build tool download returned HTTP {}; retrying ({}/3).', status, attempt + 1) + Thread.sleep(1000L * attempt) + } finally { + connection.disconnect() + } + } if (digest(downloaded) != toolSha256) { throw new GradleException('The legacy SpecialSource download did not match its pinned SHA-256.') } diff --git a/gradle/release.gradle b/gradle/release.gradle index c003806..f9b77fe 100644 --- a/gradle/release.gradle +++ b/gradle/release.gradle @@ -115,7 +115,7 @@ tasks.register('verifyReleaseArtifacts') { tasks.register('writeReleaseChecksums') { group = 'verification' - dependsOn tasks.named('verifyReleaseArtifacts') + dependsOn tasks.named('verifyReleaseArtifacts'), tasks.named('writeReleaseChecksum') def output = layout.buildDirectory.file('release/SHA256SUMS') outputs.file(output) inputs.files(releaseFiles.map { names -> names.collect { layout.buildDirectory.file("libs/${it}") } })