diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..da5833c --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,2 @@ +ko_fi: Steveplays +patreon: Steveplays28 diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..110dd1c --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,58 @@ +name: Java CI + +on: + push: + branches: + - '**' + pull_request: + branches: + - '**' + +jobs: + skip_duplicate_jobs: + name: Skip duplicate jobs + continue-on-error: true # Uncomment once integration is finished + runs-on: ubuntu-latest + # Map a step output to a job output + outputs: + should_skip: ${{ steps.skip_check.outputs.should_skip }} + steps: + - id: skip_check + uses: fkirc/skip-duplicate-actions@v5 + with: + paths_ignore: '["**/README.md", "**/docs/**", "**/.gitignore", "**/LICENSE"]' + concurrent_skipping: same_content_newer + + run_tests_and_build: + name: Run tests and build + runs-on: ubuntu-latest + needs: skip_duplicate_jobs + if: needs.skip_duplicate_jobs.outputs.should_skip != 'true' + + steps: + - uses: actions/checkout@v3 + + - name: Setup JDK (Temurin 17) + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' + cache: gradle + + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@v1 + + - name: Setup Gradle + uses: gradle/gradle-build-action@v2 + + - name: Change Gradle wrapper permissions + run: chmod +x ./gradlew + + - name: Execute Gradle build + run: ./gradlew build + + - name: Upload Gradle artifacts + uses: actions/upload-artifact@v4 + with: + name: compiled_jar_files + path: "**/build/libs/" diff --git a/.github/workflows/publish-curseforge.yml b/.github/workflows/publish-curseforge.yml new file mode 100644 index 0000000..1d3f714 --- /dev/null +++ b/.github/workflows/publish-curseforge.yml @@ -0,0 +1,101 @@ +name: Publish (CurseForge) + +on: + workflow_dispatch: + +jobs: + build_and_publish: + name: Build and publish + runs-on: ubuntu-latest + permissions: + contents: write + packages: write + + steps: + - uses: actions/checkout@v3 + + - name: Get mod version from Gradle + uses: madhead/read-java-properties@latest + id: mod_version + with: + file: gradle.properties + property: mod_version + default: 0.0.1 + + - name: Get supported Minecraft version from Gradle + uses: madhead/read-java-properties@latest + id: supported_minecraft_version_name + with: + file: gradle.properties + property: supported_minecraft_version_name + default: 0.0.1 + + - name: Print version string + run: echo version string ${{ steps.mod_version.outputs.value }}+mc${{ steps.supported_minecraft_version_name.outputs.value }} + + - name: Set release tag name environment variable + run: echo release_tag_name=v${{ steps.mod_version.outputs.value }}+mc${{ steps.supported_minecraft_version_name.outputs.value }} >> $GITHUB_ENV + + - name: Get existing release + uses: cardinalby/git-get-release-action@v1 + id: get_existing_release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag: ${{ env.release_tag_name }} + doNotFailIfNotFound: true + + - name: Check if an existing release with the same version exists + if: steps.get_existing_release.outputs.tag_name == env.release_tag_name + run: exit 1 + + - name: Setup JDK (Temurin 17) + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' + cache: gradle + + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@v1 + + - name: Setup Gradle + uses: gradle/gradle-build-action@v2 + + - name: Change Gradle wrapper permissions + run: chmod +x ./gradlew + + - name: Execute Gradle build + run: ./gradlew build + + # https://github.com/marketplace/actions/mc-publish + - name: Publish mod (Fabric) + uses: Kir-Antipov/mc-publish@v3.3 + with: + # CurseForge + curseforge-token: ${{ secrets.CURSEFORGE_TOKEN }} + + name: ${{ steps.mod_version.outputs.value }} (${{ steps.supported_minecraft_version_name.outputs.value }}) + github-tag: ${{ env.release_tag_name }} + files: | + fabric/build/libs/!(*-@(sources|dev-shadow|javadoc|transformProduction*).jar) + fabric/build/libs/*-@(sources|javadoc).jar + version-type: release + modrinth-featured: false + changelog-file: CHANGELOG_LATEST.md + + # https://github.com/marketplace/actions/mc-publish + - name: Publish mod (NeoForge/Forge) + uses: Kir-Antipov/mc-publish@v3.3 + with: + # CurseForge + curseforge-token: ${{ secrets.CURSEFORGE_TOKEN }} + + name: ${{ steps.mod_version.outputs.value }} (${{ steps.supported_minecraft_version_name.outputs.value }}) + github-tag: ${{ env.release_tag_name }} + files: | + forge/build/libs/!(*-@(sources|dev-shadow|javadoc|transformProduction*).jar) + forge/build/libs/*-@(sources|javadoc).jar + version-type: release + modrinth-featured: false + changelog-file: CHANGELOG_LATEST.md diff --git a/.github/workflows/publish-github-releases.yml b/.github/workflows/publish-github-releases.yml new file mode 100644 index 0000000..33418c4 --- /dev/null +++ b/.github/workflows/publish-github-releases.yml @@ -0,0 +1,77 @@ +name: Publish (GitHub releases) + +on: + workflow_dispatch: + +jobs: + build_and_publish: + name: Build and publish + runs-on: ubuntu-latest + permissions: + contents: write + packages: write + + steps: + - uses: actions/checkout@v3 + + - name: Get mod version from Gradle + uses: madhead/read-java-properties@latest + id: mod_version + with: + file: gradle.properties + property: mod_version + default: 0.0.1 + + - name: Get supported Minecraft version from Gradle + uses: madhead/read-java-properties@latest + id: supported_minecraft_version_name + with: + file: gradle.properties + property: supported_minecraft_version_name + default: 0.0.1 + + - name: Print version string + run: echo version string ${{ steps.mod_version.outputs.value }}+mc${{ steps.supported_minecraft_version_name.outputs.value }} + + - name: Set release tag name environment variable + run: echo release_tag_name=v${{ steps.mod_version.outputs.value }}+mc${{ steps.supported_minecraft_version_name.outputs.value }} >> $GITHUB_ENV + + - name: Get existing release + uses: cardinalby/git-get-release-action@v1 + id: get_existing_release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag: ${{ env.release_tag_name }} + doNotFailIfNotFound: true + + - name: Check if an existing release with the same version exists + if: steps.get_existing_release.outputs.tag_name == env.release_tag_name + run: exit 1 + + - name: Setup JDK (Temurin 17) + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' + cache: gradle + + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@v1 + + - name: Setup Gradle + uses: gradle/gradle-build-action@v2 + + - name: Change Gradle wrapper permissions + run: chmod +x ./gradlew + + - name: Execute Gradle build + run: ./gradlew build + + - name: Publish mod to GitHub releases + uses: ncipollo/release-action@v1.14.0 + with: + name: ${{ steps.mod_version.outputs.value }} (${{ steps.supported_minecraft_version_name.outputs.value }}) + tag: ${{ env.release_tag_name }} + artifacts: "**/build/libs/!(*-@(dev-shadow|transformProduction*).jar)" + bodyFile: CHANGELOG_LATEST.md diff --git a/.github/workflows/publish-maven.yml b/.github/workflows/publish-maven.yml new file mode 100644 index 0000000..38ba203 --- /dev/null +++ b/.github/workflows/publish-maven.yml @@ -0,0 +1,74 @@ +name: Publish (Maven) + +on: + workflow_dispatch: + +jobs: + build_and_publish: + name: Build and publish + runs-on: ubuntu-latest + permissions: + contents: write + packages: write + + steps: + - uses: actions/checkout@v3 + + - name: Get mod version from Gradle + uses: madhead/read-java-properties@latest + id: mod_version + with: + file: gradle.properties + property: mod_version + default: 0.0.1 + + - name: Get supported Minecraft version from Gradle + uses: madhead/read-java-properties@latest + id: supported_minecraft_version_name + with: + file: gradle.properties + property: supported_minecraft_version_name + default: 0.0.1 + + - name: Print version string + run: echo version string ${{ steps.mod_version.outputs.value }}+mc${{ steps.supported_minecraft_version_name.outputs.value }} + + - name: Set release tag name environment variable + run: echo release_tag_name=v${{ steps.mod_version.outputs.value }}+mc${{ steps.supported_minecraft_version_name.outputs.value }} >> $GITHUB_ENV + + - name: Get existing release + uses: cardinalby/git-get-release-action@v1 + id: get_existing_release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag: ${{ env.release_tag_name }} + doNotFailIfNotFound: true + + - name: Check if an existing release with the same version exists + if: steps.get_existing_release.outputs.tag_name == env.release_tag_name + run: exit 1 + + - name: Setup JDK (Temurin 17) + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' + cache: gradle + + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@v1 + + - name: Setup Gradle + uses: gradle/gradle-build-action@v2 + + - name: Change Gradle wrapper permissions + run: chmod +x ./gradlew + + - name: Execute Gradle build + run: ./gradlew build + + - name: Publish mod to Maven repository + run: ./gradlew publish + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/publish-modrinth.yml b/.github/workflows/publish-modrinth.yml new file mode 100644 index 0000000..2a60985 --- /dev/null +++ b/.github/workflows/publish-modrinth.yml @@ -0,0 +1,101 @@ +name: Publish (Modrinth) + +on: + workflow_dispatch: + +jobs: + build_and_publish: + name: Build and publish + runs-on: ubuntu-latest + permissions: + contents: write + packages: write + + steps: + - uses: actions/checkout@v3 + + - name: Get mod version from Gradle + uses: madhead/read-java-properties@latest + id: mod_version + with: + file: gradle.properties + property: mod_version + default: 0.0.1 + + - name: Get supported Minecraft version from Gradle + uses: madhead/read-java-properties@latest + id: supported_minecraft_version_name + with: + file: gradle.properties + property: supported_minecraft_version_name + default: 0.0.1 + + - name: Print version string + run: echo version string ${{ steps.mod_version.outputs.value }}+mc${{ steps.supported_minecraft_version_name.outputs.value }} + + - name: Set release tag name environment variable + run: echo release_tag_name=v${{ steps.mod_version.outputs.value }}+mc${{ steps.supported_minecraft_version_name.outputs.value }} >> $GITHUB_ENV + + - name: Get existing release + uses: cardinalby/git-get-release-action@v1 + id: get_existing_release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag: v${{ steps.mod_version.outputs.value }}+mc${{ steps.supported_minecraft_version_name.outputs.value }} + doNotFailIfNotFound: true + + - name: Check if an existing release with the same version exists + if: steps.get_existing_release.outputs.tag_name == env.release_tag_name + run: exit 1 + + - name: Setup JDK (Temurin 17) + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' + cache: gradle + + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@v1 + + - name: Setup Gradle + uses: gradle/gradle-build-action@v2 + + - name: Change Gradle wrapper permissions + run: chmod +x ./gradlew + + - name: Execute Gradle build + run: ./gradlew build + + # https://github.com/marketplace/actions/mc-publish + - name: Publish mod (Fabric) + uses: Kir-Antipov/mc-publish@v3.3 + with: + # Modrinth + modrinth-token: ${{ secrets.MODRINTH_TOKEN }} + + name: ${{ steps.mod_version.outputs.value }} (${{ steps.supported_minecraft_version_name.outputs.value }}) + github-tag: ${{ env.release_tag_name }} + files: | + fabric/build/libs/!(*-@(sources|dev-shadow|javadoc|transformProduction*).jar) + fabric/build/libs/*-@(sources|javadoc).jar + version-type: release + modrinth-featured: false + changelog-file: CHANGELOG_LATEST.md + + # https://github.com/marketplace/actions/mc-publish + - name: Publish mod (NeoForge/Forge) + uses: Kir-Antipov/mc-publish@v3.3 + with: + # Modrinth + modrinth-token: ${{ secrets.MODRINTH_TOKEN }} + + name: ${{ steps.mod_version.outputs.value }} (${{ steps.supported_minecraft_version_name.outputs.value }}) + github-tag: ${{ env.release_tag_name }} + files: | + forge/build/libs/!(*-@(sources|dev-shadow|javadoc|transformProduction*).jar) + forge/build/libs/*-@(sources|javadoc).jar + version-type: release + modrinth-featured: false + changelog-file: CHANGELOG_LATEST.md diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..ff6d0e3 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,120 @@ +name: Publish + +on: + workflow_dispatch: + +jobs: + build_and_publish: + name: Build and publish + runs-on: ubuntu-latest + permissions: + contents: write + packages: write + + steps: + - uses: actions/checkout@v3 + + - name: Get mod version from Gradle + uses: madhead/read-java-properties@latest + id: mod_version + with: + file: gradle.properties + property: mod_version + default: 0.0.1 + + - name: Get supported Minecraft version from Gradle + uses: madhead/read-java-properties@latest + id: supported_minecraft_version_name + with: + file: gradle.properties + property: supported_minecraft_version_name + default: 0.0.1 + + - name: Print version string + run: echo version string ${{ steps.mod_version.outputs.value }}+mc${{ steps.supported_minecraft_version_name.outputs.value }} + + - name: Set release tag name environment variable + run: echo release_tag_name=v${{ steps.mod_version.outputs.value }}+mc${{ steps.supported_minecraft_version_name.outputs.value }} >> $GITHUB_ENV + + - name: Get existing release + uses: cardinalby/git-get-release-action@v1 + id: get_existing_release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag: ${{ env.release_tag_name }} + doNotFailIfNotFound: true + + - name: Check if an existing release with the same version exists + if: steps.get_existing_release.outputs.tag_name == env.release_tag_name + run: exit 1 + + - name: Setup JDK (Temurin 17) + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' + cache: gradle + + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@v1 + + - name: Setup Gradle + uses: gradle/gradle-build-action@v2 + + - name: Change Gradle wrapper permissions + run: chmod +x ./gradlew + + - name: Execute Gradle build + run: ./gradlew build + + # https://github.com/marketplace/actions/mc-publish + - name: Publish mod (Fabric) + uses: Kir-Antipov/mc-publish@v3.3 + with: + # Modrinth + modrinth-token: ${{ secrets.MODRINTH_TOKEN }} + + # CurseForge + curseforge-token: ${{ secrets.CURSEFORGE_TOKEN }} + + name: ${{ steps.mod_version.outputs.value }} (${{ steps.supported_minecraft_version_name.outputs.value }}) + github-tag: ${{ env.release_tag_name }} + files: | + fabric/build/libs/!(*-@(sources|dev-shadow|javadoc|transformProduction*).jar) + fabric/build/libs/*-@(sources|javadoc).jar + version-type: release + modrinth-featured: false + changelog-file: CHANGELOG_LATEST.md + + # https://github.com/marketplace/actions/mc-publish + - name: Publish mod (NeoForge/Forge) + uses: Kir-Antipov/mc-publish@v3.3 + with: + # Modrinth + modrinth-token: ${{ secrets.MODRINTH_TOKEN }} + + # CurseForge + curseforge-token: ${{ secrets.CURSEFORGE_TOKEN }} + + name: ${{ steps.mod_version.outputs.value }} (${{ steps.supported_minecraft_version_name.outputs.value }}) + github-tag: ${{ env.release_tag_name }} + files: | + forge/build/libs/!(*-@(sources|dev-shadow|javadoc|transformProduction*).jar) + forge/build/libs/*-@(sources|javadoc).jar + version-type: release + modrinth-featured: false + changelog-file: CHANGELOG_LATEST.md + + - name: Publish mod to GitHub releases + uses: ncipollo/release-action@v1.14.0 + with: + name: ${{ steps.mod_version.outputs.value }} (${{ steps.supported_minecraft_version_name.outputs.value }}) + tag: ${{ env.release_tag_name }} + artifacts: "**/build/libs/!(*-@(dev-shadow|transformProduction*).jar)" + bodyFile: CHANGELOG_LATEST.md + + - name: Publish mod to Maven repository + run: ./gradlew publish + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..98064b1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,118 @@ +# User-specific stuff +.idea/ + +*.iml +*.ipr +*.iws + +# IntelliJ +out/ +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +.gradle +build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Cache of project +.gradletasknamecache + +**/build/ + +# Common working directory +run/ + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Ignore environment variables/secrets +.env diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e02cd1b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,100 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## `v2.2.0` - 21/06/2024 + +### Added + +- Minecraft 1.21 compatibility + +## `v2.1.0` - 26/05/2024 + +### Added + +- Minecraft 1.20.5-1.20.6 compatibility + +### Changed + +- Removed Forge support + - On 1.20.5 and up only + +## `v2.0.3` - 29/04/2024 + +### Fixed + +- Ad Astra compatibility + - Ad Astra and other dimension mods no longer crash when trying to generate chunks in their dimensions + - The code is also slightly faster and more concise, because the chunk sections array is now fetched directly from the chunk that's + being generated, instead of recreating it before noise population, which may result in a very slight performance increase + +## `v2.0.2` - 14/04/2024 + +### Added + +- Lithium compatibility + - You no longer have to sacrifice fish for performance + +### Fixed + +- NeoForge 1.20.2+ support + - Removed the JiJ Mixin Extras, because NeoForge already includes it +- `ChunkSection#populateBiomes` axis order optimisation + - The optimisation's axis order was incorrect (it was reversed) + - Thank you to embeddedt for spotting this issue + +## `v2.0.1` - 05/04/2024 + +### Fixed + +- NeoForge support + - Removed the dependency on (Neo)Forge, so the merged JAR can work for both NeoForge and Forge + +## `v2.0.0` - 05/04/2024 + +### Added + +- Forge support +- NeoForge support +- `GenerationShapeConfig` caching optimisation + - `horizontalCellBlockCount` and `verticalCellBlockCount` are now cached, which skips a `BiomeCoords#toBlock` call every time these + methods are invoked +- ReTerraForged, Nether Depths, and Lost Cities compatibility + - The main optimisation (`NoiseChunkGenerator#populateNoise`) has been rewritten to improve compatibility, by using an `@Inject` and + a `@Redirect` instead of an `@Overwrite` + +## `v1.0.2` - 12/11/2023 + +### Added + +- C2ME recommendation + - Running C2ME alongside Noisium is now recommended to replace the biome population multithreading, since C2ME does it in a much + better/more performant way + +### Changed + +- Removed the biome population multithreading + - See the C2ME recommendation above + +### Fixed + +- Potential race condition due to a non-thread safe `BlockPos.Mutable` instance + +## `v1.0.1` - 05/11/2023 + +### Fixed + +- Occasional missing chunk sections + +## `v1.0.0` - 29/10/2023 + +### Added + +- 4 worldgen performance optimisations + - `ChainedBlockSource#sample` (replace an enhanced for loop with a `fori` loop for faster blockstate sampling) + - `Chunk#populateBiomes` (multithread biome population) + - `NoiseChunkGenerator#populateNoise` (set blockstates directly in the palette storage) + - `NoiseChunkGenerator#populateNoise` (replace an enhanced for loop with a `fori` loop for faster chunk unlocking) diff --git a/CHANGELOG_LATEST.md b/CHANGELOG_LATEST.md new file mode 100644 index 0000000..a8f0a56 --- /dev/null +++ b/CHANGELOG_LATEST.md @@ -0,0 +1,3 @@ +### Added + +- Minecraft 1.21 compatibility diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..13900fa --- /dev/null +++ b/LICENSE @@ -0,0 +1,803 @@ +Copyright (c) 2023-present Darion Spaargaren + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +and a copy of GNU General Public License along with this program. If not, see + + + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS diff --git a/README.md b/README.md new file mode 100644 index 0000000..ff27072 --- /dev/null +++ b/README.md @@ -0,0 +1,77 @@ +![Noisium icon](docs/assets/icon/icon_128x128.png) + +# Noisium + +Optimises worldgen performance for a better gameplay experience. + +The improvements lie between a 20-30% speedup when generating new chunks in vanilla Minecraft (benchmarked on 1.20.1 Fabric). + +Noisium changes some world generation functions that other mods don't touch, to fill in the gaps left by other performance optimisation +mods. +Most notably, `NoiseChunkGenerator#populateNoise` is optimised to speed up blockstate placement when generating new chunks. There are also 3 +other smaller optimisations, that increase biome population speed, chunk unlocking speed, and the speed of sampling blockstates for +generation. +In `NoiseChunkGenerator#populateNoise`, setting the blockstate via abstractions/built-in functions is bypassed. Instead, the blocks are set +directly in the palette storage, thus bypassing a lot of calculations and things Minecraft does that are normally useful when blocks are +set, but when generating the world only slow it down, this is a cycle optimisation. + +Noisium has full 1:1 parity with vanilla worldgen (worldgen without Noisium). + +## Dependencies + +### Required + +None. + +## Compatibility info + +### Compatible mods + +Noisium should be compatible with most, if not all, of the popular optimisation mods currently on Modrinth/CurseForge for +Minecraft `1.20.x`, since Noisium aims to fill in the gaps in performance optimisation left by other mods. +This includes (but is not limited to) C2ME, Lithium, Nvidium, and Sodium. + +- C2ME: every world generation thread runs faster. The biome population multithreading is also done in a much better/more performant way in + C2ME, so it's been removed from Noisium since `v1.0.2`. It's suggested to run C2ME alongside Noisium for even better world generation + performance. +- Distant Horizons: Noisium speeds up LOD world generation threads, since LOD generation depends on Minecraft's world generation speed. +- ReTerraForged: RTF has built-in compatibility with Noisium, to fully utilize the optimisations during RTF world generation. + +### Incompatibilities + +See the [issue tracker](https://github.com/Steveplays28/noisium/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Acompatibility) for +a list of incompatibilities. + +## Download + +[![GitHub](https://github.com/intergrav/devins-badges/raw/2dc967fc44dc73850eee42c133a55c8ffc5e30cb/assets/cozy/available/github_vector.svg)](https://github.com/Steveplays28/noisium) +[![Modrinth](https://github.com/intergrav/devins-badges/raw/2dc967fc44dc73850eee42c133a55c8ffc5e30cb/assets/cozy/available/modrinth_vector.svg)](https://modrinth.com/mod/noisium) +[![CurseForge](https://github.com/intergrav/devins-badges/raw/2dc967fc44dc73850eee42c133a55c8ffc5e30cb/assets/cozy/available/curseforge_vector.svg)](https://www.curseforge.com/minecraft/mc-mods/noisium) + +![Fabric](https://github.com/intergrav/devins-badges/raw/2dc967fc44dc73850eee42c133a55c8ffc5e30cb/assets/compact/supported/fabric_vector.svg) +![Quilt](https://github.com/intergrav/devins-badges/raw/2dc967fc44dc73850eee42c133a55c8ffc5e30cb/assets/compact/supported/quilt_vector.svg) +![Forge](https://github.com/intergrav/devins-badges/raw/2dc967fc44dc73850eee42c133a55c8ffc5e30cb/assets/compact/supported/forge_vector.svg) +![NeoForge](docs/assets/badges/compact/supported/neoforge_vector.svg) + +See the version info in the filename for the supported Minecraft versions. +Made for the Fabric, Quilt, Forge, and NeoForge modloaders. The `merged` JAR works on all aforementioned modloaders. +Server side. + +## FAQ + +- Q: Will you be backporting this mod to lower Minecraft versions? + A: No. + +- Q: Does this mod work in multiplayer? + A: Yes, but it'll only improve performance on the server. + +- Q: Does only the server need this mod or does the client need it too? + A: Only the server needs this mod (but it works on the client too if you're going to host LAN or play singleplayer). + +## Attribution + +- Thanks to [Builderb0y](https://modrinth.com/user/Builderb0y) for giving great starting points and helping with some issues. + +## License + +This project is licensed under LGPLv3, see [LICENSE](https://github.com/Steveplays28/noisium/blob/main/LICENSE). diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..afa4fd1 --- /dev/null +++ b/build.gradle @@ -0,0 +1,95 @@ +//file:noinspection GroovyAccessibility +//file:noinspection GroovyAssignabilityCheck + +plugins { + id "architectury-plugin" version "${architectury_plugin_version}" + id "dev.architectury.loom" version "${architectury_loom_version}" apply false + id "io.github.pacifistmc.forgix" version "${forgix_plugin_version}" +} + +architectury { + minecraft = rootProject.minecraft_version +} + +subprojects { + apply plugin: "dev.architectury.loom" + + dependencies { + minecraft "com.mojang:minecraft:${rootProject.minecraft_version}" + mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" + } +} + +allprojects { + apply plugin: "java" + apply plugin: "architectury-plugin" + apply plugin: "maven-publish" + + version = "${rootProject.mod_version}+mc${rootProject.supported_minecraft_version_name}" + group = rootProject.maven_group + + repositories { + // Add repositories to retrieve artifacts from in here. + // You should only use this when depending on other mods because + // Loom adds the essential maven repositories to download Minecraft and libraries from automatically. + // See https://docs.gradle.org/current/userguide/declaring_repositories.html + // for more information about repositories. + + maven { + name = "Modrinth" + url = "https://api.modrinth.com/maven" + content { + includeGroup "maven.modrinth" + } + } + maven { + name = "NeoForged" + url = "https://maven.neoforged.net/releases/" + } + maven { + name "Xander Maven" + url "https://maven.isxander.dev/releases" + } + } + + tasks.withType(JavaCompile).configureEach { + options.encoding = "UTF-8" + options.release = "${rootProject.java_version}" as int + } + + java { + withSourcesJar() + } + + jar { + from(rootProject.file("LICENSE")) { + rename { "${it}_${rootProject.mod_namespace}" } + } + } +} + +// Clean the previous build output of the root project and all subprojects before building +tasks.named("build") { + dependsOn(clean, subprojects.clean) +} + +publishing { + publications { + mavenJava(MavenPublication) { + groupId = rootProject.maven_group + artifactId = rootProject.archivesBaseName + from components.java + } + } + + repositories { + maven { + name = "GitHubPackages" + url = uri("https://maven.pkg.github.com/Steveplays28/${rootProject.mod_id}") + credentials { + username = System.getenv("GITHUB_ACTOR") + password = System.getenv("GITHUB_TOKEN") + } + } + } +} diff --git a/common/build.gradle b/common/build.gradle new file mode 100644 index 0000000..e2b4565 --- /dev/null +++ b/common/build.gradle @@ -0,0 +1,50 @@ +//file:noinspection GroovyAccessibility +//file:noinspection GroovyAssignabilityCheck + +architectury { + common(rootProject.enabled_platforms.split(",")) +} + +base { + archivesName = "${rootProject.archives_base_name}-common" +} + +loom { + accessWidenerPath = file("src/main/resources/${mod_namespace}.accesswidener") +} + +dependencies { + // We depend on fabric loader here to use the fabric @Environment annotations and get the mixin dependencies + // Do NOT use other classes from fabric loader + modImplementation "net.fabricmc:fabric-loader:${rootProject.fabric_loader_version}" + + // Mixin Extras + compileOnly(annotationProcessor("io.github.llamalad7:mixinextras-common:${rootProject.mixin_extras_version}")) + + // Architectury API + modApi("dev.architectury:architectury:${rootProject.architectury_api_version}") { exclude group: 'net.fabricmc', module: 'fabric-loader' } + + // YetAnotherConfigLib + modImplementation("dev.isxander:yet-another-config-lib:${rootProject.yet_another_config_lib_version}-fabric") + + // Mod Menu + modImplementation("maven.modrinth:modmenu:${rootProject.mod_menu_version}") + + // Distant Horizons + modImplementation("maven.modrinth:distanthorizons:${rootProject.distant_horizons_version}-${rootProject.minecraft_version}") +} + +publishing { + publications { + mavenCommon(MavenPublication) { + groupId = rootProject.maven_group + artifactId = "${rootProject.archives_base_name}-common" + from components.java + } + } + + // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. + repositories { + // Add repositories to publish to here. + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/NoisiumChunkManager.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/NoisiumChunkManager.java new file mode 100644 index 0000000..13ca0fe --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/NoisiumChunkManager.java @@ -0,0 +1,16 @@ +package io.github.steveplays28.noisiumchunkmanager; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NoisiumChunkManager { + public static final String MOD_ID = "noisiumchunkmanager"; + public static final String MOD_NAME = "Noisium Chunk Manager"; + public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); + + public static void initialize() { + LOGGER.info("Loading {}.", MOD_NAME); + + io.github.steveplays28.noisiumchunkmanager.experimental.server.NoisiumChunkManagerServerInitialiser.initialise(); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/client/compat/modmenu/NoisiumChunkManagerModMenuCompat.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/client/compat/modmenu/NoisiumChunkManagerModMenuCompat.java new file mode 100644 index 0000000..b1d9aef --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/client/compat/modmenu/NoisiumChunkManagerModMenuCompat.java @@ -0,0 +1,15 @@ +package io.github.steveplays28.noisiumchunkmanager.client.compat.modmenu; + +import com.terraformersmc.modmenu.api.ConfigScreenFactory; +import com.terraformersmc.modmenu.api.ModMenuApi; +import io.github.steveplays28.noisiumchunkmanager.config.NoisiumChunkManagerConfig; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; + +@Environment(EnvType.CLIENT) +public class NoisiumChunkManagerModMenuCompat implements ModMenuApi { + @Override + public ConfigScreenFactory getModConfigScreenFactory() { + return parent -> NoisiumChunkManagerConfig.HANDLER.generateGui().generateScreen(parent); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/config/NoisiumChunkManagerConfig.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/config/NoisiumChunkManagerConfig.java new file mode 100644 index 0000000..30e3507 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/config/NoisiumChunkManagerConfig.java @@ -0,0 +1,38 @@ +package io.github.steveplays28.noisiumchunkmanager.config; + +import dev.isxander.yacl3.config.v2.api.ConfigClassHandler; +import dev.isxander.yacl3.config.v2.api.SerialEntry; +import dev.isxander.yacl3.config.v2.api.autogen.AutoGen; +import dev.isxander.yacl3.config.v2.api.autogen.IntField; +import dev.isxander.yacl3.config.v2.api.autogen.TickBox; +import dev.isxander.yacl3.config.v2.api.serializer.GsonConfigSerializerBuilder; +import io.github.steveplays28.noisiumchunkmanager.util.ModLoaderUtil; +import net.minecraft.util.Identifier; +import org.jetbrains.annotations.NotNull; + +import static io.github.steveplays28.noisiumchunkmanager.NoisiumChunkManager.MOD_ID; + +public class NoisiumChunkManagerConfig { + public static final @NotNull String JSON_5_FILE_EXTENSION = "json5"; + public static final @NotNull ConfigClassHandler HANDLER = ConfigClassHandler.createBuilder( + NoisiumChunkManagerConfig.class).id(new Identifier(MOD_ID, "config")).serializer( + config -> GsonConfigSerializerBuilder.create(config).setPath( + ModLoaderUtil.getConfigDir().resolve(String.format("%s/config.%s", MOD_ID, JSON_5_FILE_EXTENSION))).setJson5( + true).build()).build(); + + private static final @NotNull String SERVER_CATEGORY = "server"; + private static final @NotNull String SERVER_WORLD_CHUNK_MANAGER_GROUP = "serverWorldChunkManager"; + + @AutoGen(category = SERVER_CATEGORY, group = SERVER_WORLD_CHUNK_MANAGER_GROUP) + @SerialEntry(comment = "A re-implementation of the server world's chunk manager. Every world has its own chunk manager. After changing this option you MUST restart Minecraft.") + @TickBox + public boolean serverWorldChunkManagerEnabled = false; + @AutoGen(category = SERVER_CATEGORY, group = SERVER_WORLD_CHUNK_MANAGER_GROUP) + @SerialEntry(comment = "The amount of threads used by a server world's chunk manager. Every world has its own chunk manager, and thus its own threads. After changing this option you MUST restart the server.") + @IntField(min = 1, format = "%i threads") + public int serverWorldChunkManagerThreads = 2; + @AutoGen(category = SERVER_CATEGORY, group = SERVER_WORLD_CHUNK_MANAGER_GROUP) + @SerialEntry(comment = "The amount of threads used by a server world's chunk manager lighting populator. Every world has its own chunk manager, and thus its own threads. After changing this option you MUST restart the server.") + @IntField(min = 1, format = "%i threads") + public int serverWorldChunkManagerLightingThreads = 2; +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/extension/world/chunk/WorldChunkExtension.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/extension/world/chunk/WorldChunkExtension.java new file mode 100644 index 0000000..f2b634a --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/extension/world/chunk/WorldChunkExtension.java @@ -0,0 +1,9 @@ +package io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.chunk; + +import java.util.BitSet; + +public interface WorldChunkExtension { + BitSet noisiumchunkmanager$getBlockLightBits(); + + BitSet noisiumchunkmanager$getSkyLightBits(); +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/extension/world/server/ServerWorldExtension.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/extension/world/server/ServerWorldExtension.java new file mode 100644 index 0000000..8d029e6 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/extension/world/server/ServerWorldExtension.java @@ -0,0 +1,10 @@ +package io.github.steveplays28.noisiumchunkmanager.extension.world.server; + +import io.github.steveplays28.noisiumchunkmanager.server.world.ServerWorldChunkManager; +import net.minecraft.world.gen.noise.NoiseConfig; + +public interface ServerWorldExtension { + ServerWorldChunkManager noisiumchunkmanager$getServerWorldChunkManager(); + + NoiseConfig noisiumchunkmanager$getNoiseConfig(); +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/NoisiumChunkManagerMixinPlugin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/NoisiumChunkManagerMixinPlugin.java new file mode 100644 index 0000000..5897454 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/NoisiumChunkManagerMixinPlugin.java @@ -0,0 +1,51 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin; + +import com.google.common.collect.ImmutableMap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; + +import static io.github.steveplays28.noisiumchunkmanager.util.ModLoaderUtil.isModPresent; + +public class NoisiumChunkManagerMixinPlugin implements IMixinConfigPlugin { + private static final @NotNull Supplier TRUE = () -> true; + private static final @NotNull String DISTANT_HORIZONS_MOD_ID = "distanthorizons"; + private static final @NotNull Map> CONDITIONS = ImmutableMap.of( + "io.github.steveplays28.noisiumchunkmanager.mixin.experimental.compat.distanthorizons.common.wrappers.world.gen.DHBatchGenerationEnvironmentMixin", + () -> isModPresent(DISTANT_HORIZONS_MOD_ID) + ); + + @Override + public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { + return CONDITIONS.getOrDefault(mixinClassName, TRUE).get(); + } + + @Override + public void onLoad(String mixinPackage) {} + + @Override + public @Nullable String getRefMapperConfig() { + return null; + } + + @Override + public void acceptTargets(Set myTargets, Set otherTargets) {} + + @Override + public @Nullable List getMixins() { + return null; + } + + @Override + public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {} + + @Override + public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {} +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/accessor/server/network/SpawnLocatingAccessor.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/accessor/server/network/SpawnLocatingAccessor.java new file mode 100644 index 0000000..d22a841 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/accessor/server/network/SpawnLocatingAccessor.java @@ -0,0 +1,17 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.accessor.server.network; + +import net.minecraft.server.network.SpawnLocating; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.math.BlockPos; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(SpawnLocating.class) +public interface SpawnLocatingAccessor { + @Invoker + static @Nullable BlockPos invokeFindOverworldSpawn(@NotNull ServerWorld serverWorld, int searchPositionX, int searchPositionZ) { + throw new AssertionError(); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/accessor/util/collection/PackedIntegerArrayAccessor.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/accessor/util/collection/PackedIntegerArrayAccessor.java new file mode 100644 index 0000000..343fad2 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/accessor/util/collection/PackedIntegerArrayAccessor.java @@ -0,0 +1,11 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.accessor.util.collection; + +import net.minecraft.util.collection.PackedIntegerArray; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +@Mixin(PackedIntegerArray.class) +public interface PackedIntegerArrayAccessor { + @Accessor + long getMaxValue(); +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/accessor/world/gen/chunk/ChunkGeneratorAccessor.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/accessor/world/gen/chunk/ChunkGeneratorAccessor.java new file mode 100644 index 0000000..0d037b2 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/accessor/world/gen/chunk/ChunkGeneratorAccessor.java @@ -0,0 +1,19 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.accessor.world.gen.chunk; + +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.gen.StructureAccessor; +import net.minecraft.world.gen.chunk.Blender; +import net.minecraft.world.gen.chunk.ChunkGenerator; +import net.minecraft.world.gen.noise.NoiseConfig; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; + +@Mixin(ChunkGenerator.class) +public interface ChunkGeneratorAccessor { + @SuppressWarnings("UnusedReturnValue") + @Invoker + CompletableFuture invokePopulateNoise(Executor executor, Blender blender, NoiseConfig noiseConfig, StructureAccessor structureAccessor, Chunk chunk); +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/block/LichenGrowerGrowCheckerMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/block/LichenGrowerGrowCheckerMixin.java new file mode 100644 index 0000000..9f1e4bd --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/block/LichenGrowerGrowCheckerMixin.java @@ -0,0 +1,23 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.block; + +import net.minecraft.block.LichenGrower; +import net.minecraft.util.math.ChunkSectionPos; +import net.minecraft.world.WorldAccess; +import org.jetbrains.annotations.NotNull; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.Optional; + +@Mixin(LichenGrower.class) +public class LichenGrowerGrowCheckerMixin { + @Inject(method = "place", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$cancelPlaceIfChunkIsUnloaded(@NotNull WorldAccess world, @NotNull LichenGrower.GrowPos growPosition, boolean markForPostProcessing, @NotNull CallbackInfoReturnable> cir) { + @NotNull final var growBlockPosition = growPosition.pos(); + if (!world.isChunkLoaded(ChunkSectionPos.getSectionCoord(growBlockPosition.getX()), ChunkSectionPos.getSectionCoord(growBlockPosition.getZ()))) { + cir.setReturnValue(Optional.empty()); + } + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/client/gui/hud/DebugHudMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/client/gui/hud/DebugHudMixin.java new file mode 100644 index 0000000..93796ad --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/client/gui/hud/DebugHudMixin.java @@ -0,0 +1,45 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.client.gui.hud; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.gui.hud.DebugHud; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.world.chunk.WorldChunk; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Environment(EnvType.CLIENT) +@Mixin(DebugHud.class) +public abstract class DebugHudMixin { + @Shadow + @Nullable + protected abstract ServerWorld getServerWorld(); + + @Shadow + @Nullable + private ChunkPos pos; + + @Inject(method = "getChunk", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getChunkFromNoisiumServerWorldChunkManager(CallbackInfoReturnable cir) { + @Nullable var serverWorld = this.getServerWorld(); + @Nullable var playerChunkPosition = this.pos; + if (serverWorld == null || playerChunkPosition == null) { + cir.setReturnValue(null); + return; + } + + @NotNull var noisiumServerWorldChunkManager = ((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) serverWorld).noisiumchunkmanager$getServerWorldChunkManager(); + if (!noisiumServerWorldChunkManager.isChunkLoaded(playerChunkPosition)) { + cir.setReturnValue(null); + return; + } + + noisiumServerWorldChunkManager.getChunk(playerChunkPosition); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/compat/distanthorizons/common/wrappers/world/gen/DHBatchGenerationEnvironmentMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/compat/distanthorizons/common/wrappers/world/gen/DHBatchGenerationEnvironmentMixin.java new file mode 100644 index 0000000..c500adf --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/compat/distanthorizons/common/wrappers/world/gen/DHBatchGenerationEnvironmentMixin.java @@ -0,0 +1,21 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.compat.distanthorizons.common.wrappers.world.gen; + +import com.llamalad7.mixinextras.sugar.Local; +import loaderCommon.fabric.com.seibel.distanthorizons.common.wrappers.worldGeneration.BatchGenerationEnvironment; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.server.world.ThreadedAnvilChunkStorage; +import net.minecraft.world.storage.StorageIoWorker; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.objectweb.asm.Opcodes; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(BatchGenerationEnvironment.class) +public class DHBatchGenerationEnvironmentMixin { + @Redirect(method = "getChunkNbtData", at = @At(value = "FIELD", target = "Lnet/minecraft/server/world/ThreadedAnvilChunkStorage;worker:Lnet/minecraft/world/storage/StorageIoWorker;", opcode = Opcodes.GETFIELD)) + private @NotNull StorageIoWorker noisiumchunkmanager$getIoWorkerFromNoisiumServerWorldChunkManager(@Nullable ThreadedAnvilChunkStorage instance, @Local(ordinal = 0) @NotNull ServerWorld serverWorld) { + return (StorageIoWorker) ((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) serverWorld).noisiumchunkmanager$getServerWorldChunkManager().getChunkIoWorker(); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/MinecraftServerMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/MinecraftServerMixin.java new file mode 100644 index 0000000..01e3d35 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/MinecraftServerMixin.java @@ -0,0 +1,46 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.server; + +import com.llamalad7.mixinextras.sugar.Local; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.world.ServerWorld; +import org.jetbrains.annotations.NotNull; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.function.Predicate; +import java.util.stream.Stream; + +@Mixin(MinecraftServer.class) +public abstract class MinecraftServerMixin { +// @Shadow +// public abstract ServerWorld getOverworld(); +// +// @Redirect(method = "prepareStartRegion", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/world/ServerChunkManager;addTicket(Lnet/minecraft/server/world/ChunkTicketType;Lnet/minecraft/util/math/ChunkPos;ILjava/lang/Object;)V")) +// private void noisiumchunkmanager$prepareStartRegionAddTicketForSpawnChunksToNoisiumServerWorldChunkManager(ServerChunkManager instance, ChunkTicketType ticketType, ChunkPos chunkPos, int radius, T argument) { +// ((NoisiumServerWorldExtension) getOverworld()).noisiumchunkmanager$getServerWorldChunkManager().getChunksInRadius(chunkPos, radius); +// } +// +// @Redirect(method = "prepareStartRegion", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/world/ServerChunkManager;getTotalChunksLoadedCount()I")) +// private int noisiumchunkmanager$prepareStartRegionRedirectTotalLoadedChunksToNoisiumServerWorldChunkManager(ServerChunkManager instance) { +// // TODO: Make the loadedWorldChunks field private again and remove this whole vanilla Minecraft system +// return ((NoisiumServerWorldExtension) getOverworld()).noisiumchunkmanager$getServerWorldChunkManager().loadedWorldChunks.size(); +// } +// +// @ModifyConstant(method = "prepareStartRegion", constant = @Constant(intValue = 441)) +// private int noisiumchunkmanager$prepareStartRegionChangeTheAmountOfSpawnChunks(int original) { +// return 484; +// } + + @Redirect(method = "shutdown", at = @At(value = "INVOKE", target = "Ljava/util/stream/Stream;anyMatch(Ljava/util/function/Predicate;)Z")) + private boolean noisiumchunkmanager$shutdownRedirectThreadedAnvilChunkStorageShouldDelayShutdown(@NotNull Stream instance, @NotNull Predicate predicate) { + return false; + } + + @Inject(method = "save", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;getWorlds()Ljava/lang/Iterable;", shift = At.Shift.BEFORE), cancellable = true) + private void noisiumchunkmanager$saveCancelThreadedAnvilChunkStorageLogging(boolean suppressLogs, boolean flush, boolean force, @NotNull CallbackInfoReturnable cir, @Local(ordinal = 3) boolean bl) { + cir.setReturnValue(bl); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/network/ServerPlayerEntityMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/network/ServerPlayerEntityMixin.java new file mode 100644 index 0000000..e5d1526 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/network/ServerPlayerEntityMixin.java @@ -0,0 +1,98 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.server.network; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.mojang.authlib.GameProfile; +import io.github.steveplays28.noisiumchunkmanager.mixin.accessor.server.network.SpawnLocatingAccessor; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.util.math.MathHelper; +import net.minecraft.util.math.random.Random; +import net.minecraft.world.GameMode; +import net.minecraft.world.World; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(ServerPlayerEntity.class) +public abstract class ServerPlayerEntityMixin extends PlayerEntity { + @Shadow + @Final + public MinecraftServer server; + + @Shadow + protected abstract int calculateSpawnOffsetMultiplier(int horizontalSpawnArea); + + public ServerPlayerEntityMixin(World world, BlockPos pos, float yaw, GameProfile gameProfile) { + super(world, pos, yaw, gameProfile); + } + + @WrapOperation(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayerEntity;moveToSpawn(Lnet/minecraft/server/world/ServerWorld;)V")) + private void noisiumchunkmanager$moveToSpawnWrapGetChunkAsyncWhenComplete(@NotNull ServerPlayerEntity instance, @NotNull ServerWorld serverWorld, @NotNull Operation original) { + ((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) serverWorld).noisiumchunkmanager$getServerWorldChunkManager().getChunkAsync( + new ChunkPos(serverWorld.getSpawnPos())).whenComplete((worldChunk, throwable) -> original.call(instance, serverWorld)); + } + + /** + * @author Steveplays28 + * @reason Wait for {@link net.minecraft.world.chunk.WorldChunk}s from the {@link ServerWorld}'s {@link io.github.steveplays28.noisiumchunkmanager.experimental.server.world.ServerWorldChunkManager} asynchronously. + */ + @Overwrite + private void moveToSpawn(@NotNull ServerWorld serverWorld) { + var worldSpawnBlockPosition = serverWorld.getSpawnPos(); + if (!serverWorld.getDimension().hasSkyLight() || serverWorld.getServer().getSaveProperties().getGameMode() == GameMode.ADVENTURE) { + this.refreshPositionAndAngles(worldSpawnBlockPosition, 0.0F, 0.0F); + + while (!serverWorld.isSpaceEmpty(this) && this.getY() < (double) (serverWorld.getTopY() - 1)) { + this.setPosition(this.getX(), this.getY() + 1.0, this.getZ()); + } + } + + int worldSpawnRadius = Math.max(0, this.server.getSpawnRadius(serverWorld)); + int worldSpawnBlockPositionDistanceInsideBorder = MathHelper.floor( + serverWorld.getWorldBorder().getDistanceInsideBorder(worldSpawnBlockPosition.getX(), worldSpawnBlockPosition.getZ())); + if (worldSpawnBlockPositionDistanceInsideBorder < worldSpawnRadius) { + worldSpawnRadius = worldSpawnBlockPositionDistanceInsideBorder; + } + if (worldSpawnBlockPositionDistanceInsideBorder <= 1) { + worldSpawnRadius = 1; + } + + long worldSpawnRadiusExtended = worldSpawnRadius * 2L + 1; + long worldSpawnRadiusExtendedSquared = worldSpawnRadiusExtended * worldSpawnRadiusExtended; + int worldSpawnRadiusLimited = worldSpawnRadiusExtendedSquared > 2147483647L ? Integer.MAX_VALUE : (int) worldSpawnRadiusExtendedSquared; + int worldSpawnOffsetMultiplier = this.calculateSpawnOffsetMultiplier(worldSpawnRadiusLimited); + int randomNumberInWorldSpawnRadiusLimited = Random.create().nextInt(worldSpawnRadiusLimited); + + for (int possibleWorldSpawnRadius = 0; possibleWorldSpawnRadius < worldSpawnRadiusLimited; ++possibleWorldSpawnRadius) { + int q = (randomNumberInWorldSpawnRadiusLimited + worldSpawnOffsetMultiplier * possibleWorldSpawnRadius) % worldSpawnRadiusLimited; + int r = q % (worldSpawnRadius * 2 + 1); + int s = q / (worldSpawnRadius * 2 + 1); + var searchPositionX = worldSpawnBlockPosition.getX() + r - worldSpawnRadius; + var searchPositionZ = worldSpawnBlockPosition.getZ() + s - worldSpawnRadius; + ((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) serverWorld).noisiumchunkmanager$getServerWorldChunkManager().getChunkAsync( + new ChunkPos(searchPositionX, searchPositionZ)).whenComplete((worldChunk, throwable) -> { + @Nullable var overworldSpawnBlockPosition = SpawnLocatingAccessor.invokeFindOverworldSpawn( + serverWorld, searchPositionX, searchPositionZ); + if (overworldSpawnBlockPosition == null) { + return; + } + + this.refreshPositionAndAngles(overworldSpawnBlockPosition, 0.0F, 0.0F); + }); + + if (serverWorld.isSpaceEmpty(this)) { + break; + } + + } + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/network/SpawnLocatingMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/network/SpawnLocatingMixin.java new file mode 100644 index 0000000..1baf94a --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/network/SpawnLocatingMixin.java @@ -0,0 +1,60 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.server.network; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockState; +import net.minecraft.server.network.SpawnLocating; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.util.math.ChunkSectionPos; +import net.minecraft.util.math.Direction; +import net.minecraft.world.Heightmap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; + +@Mixin(SpawnLocating.class) +public class SpawnLocatingMixin { + // TODO: Change to an @Inject at HEAD + /** + * @author Steveplays28 + * @reason + */ + @Overwrite + public static @Nullable BlockPos findOverworldSpawn(@NotNull ServerWorld serverWorld, int searchBlockPosX, int searchBlockPosZ) { + var noisiumServerWorldChunkManager = ((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) serverWorld).noisiumchunkmanager$getServerWorldChunkManager(); + var chunkPosition = new ChunkPos( + ChunkSectionPos.getSectionCoord(searchBlockPosX), ChunkSectionPos.getSectionCoord(searchBlockPosZ)); + if (!noisiumServerWorldChunkManager.isChunkLoaded(chunkPosition)) { + return null; + } + + var chunk = ((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) serverWorld).noisiumchunkmanager$getServerWorldChunkManager().getChunk(chunkPosition); + int i = serverWorld.getDimension().hasCeiling() ? serverWorld.getChunkManager().getChunkGenerator().getSpawnHeight( + serverWorld) : chunk.sampleHeightmap(Heightmap.Type.MOTION_BLOCKING, searchBlockPosX & 15, searchBlockPosZ & 15); + if (i < serverWorld.getBottomY()) { + return null; + } + + int j = chunk.sampleHeightmap(Heightmap.Type.WORLD_SURFACE, searchBlockPosX & 15, searchBlockPosZ & 15); + if (j <= i && j > chunk.sampleHeightmap(Heightmap.Type.OCEAN_FLOOR, searchBlockPosX & 15, searchBlockPosZ & 15)) { + return null; + } + + BlockPos.Mutable mutable = new BlockPos.Mutable(); + for (int k = i + 1; k >= serverWorld.getBottomY(); --k) { + mutable.set(searchBlockPosX, k, searchBlockPosZ); + BlockState blockState = serverWorld.getBlockState(mutable); + if (!blockState.getFluidState().isEmpty()) { + break; + } + + if (Block.isFaceFullSquare(blockState.getCollisionShape(serverWorld, mutable), Direction.UP)) { + return mutable.up().toImmutable(); + } + } + + return null; + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/world/ServerChunkManagerMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/world/ServerChunkManagerMixin.java new file mode 100644 index 0000000..b8b9303 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/world/ServerChunkManagerMixin.java @@ -0,0 +1,234 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.server.world; + +import com.mojang.datafixers.DataFixer; +import io.github.steveplays28.noisiumchunkmanager.experimental.util.world.chunk.networking.packet.PacketUtil; +import net.minecraft.entity.Entity; +import net.minecraft.network.packet.Packet; +import net.minecraft.network.packet.s2c.play.BlockUpdateS2CPacket; +import net.minecraft.registry.RegistryKeys; +import net.minecraft.server.WorldGenerationProgressListener; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.world.ServerChunkManager; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.server.world.ThreadedAnvilChunkStorage; +import net.minecraft.structure.StructureTemplateManager; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.util.math.ChunkSectionPos; +import net.minecraft.world.LightType; +import net.minecraft.world.PersistentStateManager; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.ChunkStatus; +import net.minecraft.world.chunk.ChunkStatusChangeListener; +import net.minecraft.world.chunk.WorldChunk; +import net.minecraft.world.gen.chunk.ChunkGenerator; +import net.minecraft.world.gen.chunk.placement.StructurePlacementCalculator; +import net.minecraft.world.gen.noise.NoiseConfig; +import net.minecraft.world.level.storage.LevelStorage; +import net.minecraft.world.storage.NbtScannable; +import org.jetbrains.annotations.NotNull; +import org.spongepowered.asm.mixin.*; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.concurrent.Executor; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; + +/** + * {@link Mixin} into {@link ServerChunkManager}. + * This {@link Mixin} redirects all method calls from the {@link ServerWorld}'s {@link ServerChunkManager} to the {@link ServerWorld}'s {@link io.github.steveplays28.noisiumchunkmanager.experimental.server.world.ServerWorldChunkManager}. + */ +@Mixin(ServerChunkManager.class) +public abstract class ServerChunkManagerMixin { + @Shadow + public abstract World getWorld(); + + @Mutable + @Shadow + @Final + public ThreadedAnvilChunkStorage threadedAnvilChunkStorage; + + @Shadow + public abstract @NotNull ChunkGenerator getChunkGenerator(); + + @Shadow + public abstract @NotNull NoiseConfig getNoiseConfig(); + + @Unique + private ChunkGenerator noisiumchunkmanager$chunkGenerator; + @Unique + private StructurePlacementCalculator noisiumchunkmanager$structurePlacementCalculator; + + @Inject(method = "", at = @At(value = "TAIL")) + private void noisiumchunkmanager$constructorInject(ServerWorld world, LevelStorage.Session session, DataFixer dataFixer, StructureTemplateManager structureTemplateManager, Executor workerExecutor, @NotNull ChunkGenerator chunkGenerator, int viewDistance, int simulationDistance, boolean dsync, WorldGenerationProgressListener worldGenerationProgressListener, ChunkStatusChangeListener chunkStatusChangeListener, Supplier persistentStateManagerFactory, CallbackInfo ci) { + noisiumchunkmanager$chunkGenerator = chunkGenerator; + noisiumchunkmanager$structurePlacementCalculator = this.getChunkGenerator().createStructurePlacementCalculator( + this.getWorld().getRegistryManager().getWrapperOrThrow(RegistryKeys.STRUCTURE_SET), this.getNoiseConfig(), + ((ServerWorld) this.getWorld()).getSeed() + ); + threadedAnvilChunkStorage = null; + } + + @Inject(method = "executeQueuedTasks", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$stopServerChunkManagerFromRunningTasks(@NotNull CallbackInfoReturnable cir) { + cir.setReturnValue(true); + } + + @Inject(method = "tick(Ljava/util/function/BooleanSupplier;Z)V", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$stopServerChunkManagerFromTicking(@NotNull BooleanSupplier shouldKeepTicking, boolean tickChunks, @NotNull CallbackInfo ci) { + io.github.steveplays28.noisiumchunkmanager.experimental.server.world.event.ServerTickEvent.SERVER_ENTITY_MOVEMENT_TICK.invoker().onServerEntityMovementTick(); + ci.cancel(); + } + + @Inject(method = "close", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/world/ThreadedAnvilChunkStorage;close()V", shift = At.Shift.BEFORE), cancellable = true) + private void noisiumchunkmanager$cancelRemoveThreadedAnvilChunkStorageClose(@NotNull CallbackInfo ci) { + ci.cancel(); + } + + // TODO: Fix infinite loop + @Inject(method = "getChunk(IILnet/minecraft/world/chunk/ChunkStatus;Z)Lnet/minecraft/world/chunk/Chunk;", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getChunkFromNoisiumServerWorldChunkManager(int chunkX, int chunkZ, ChunkStatus leastStatus, boolean create, CallbackInfoReturnable cir) { + var noisiumServerWorldChunkManager = ((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) this.getWorld()).noisiumchunkmanager$getServerWorldChunkManager(); + var chunkPosition = new ChunkPos(chunkX, chunkZ); + if (!noisiumServerWorldChunkManager.isChunkLoaded(chunkPosition)) { + cir.setReturnValue(noisiumServerWorldChunkManager.getIoWorldChunk(chunkPosition)); + return; + } + + cir.setReturnValue(noisiumServerWorldChunkManager.getChunk(chunkPosition)); + } + + @Inject(method = "getChunk(II)Lnet/minecraft/world/chunk/light/LightSourceView;", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getChunkFromNoisiumServerWorldChunkManager(int chunkX, int chunkZ, CallbackInfoReturnable cir) { + var noisiumServerWorldChunkManager = ((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) this.getWorld()).noisiumchunkmanager$getServerWorldChunkManager(); + var chunkPosition = new ChunkPos(chunkX, chunkZ); + if (!noisiumServerWorldChunkManager.isChunkLoaded(chunkPosition)) { + cir.setReturnValue(noisiumServerWorldChunkManager.getIoWorldChunk(chunkPosition)); + return; + } + + cir.setReturnValue(noisiumServerWorldChunkManager.getChunk(chunkPosition)); + } + + @Inject(method = "getWorldChunk", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getWorldChunkFromNoisiumServerWorldChunkManager(int chunkX, int chunkZ, CallbackInfoReturnable cir) { + var noisiumServerWorldChunkManager = ((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) this.getWorld()).noisiumchunkmanager$getServerWorldChunkManager(); + var chunkPosition = new ChunkPos(chunkX, chunkZ); + if (!noisiumServerWorldChunkManager.isChunkLoaded(chunkPosition)) { + cir.setReturnValue(noisiumServerWorldChunkManager.getIoWorldChunk(chunkPosition)); + return; + } + + cir.setReturnValue(noisiumServerWorldChunkManager.getChunk(chunkPosition)); + } + + // TODO: Don't send this packet to players out of range, to save on bandwidth + @SuppressWarnings("ForLoopReplaceableByForEach") + @Inject(method = "sendToNearbyPlayers", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$sendToNearbyPlayersViaNoisiumServerWorldChunkManager(Entity entity, Packet packet, CallbackInfo ci) { + var server = entity.getServer(); + if (server == null) { + return; + } + + var players = server.getPlayerManager().getPlayerList(); + for (int i = 0; i < players.size(); i++) { + players.get(i).networkHandler.sendPacket(packet); + } + + ci.cancel(); + } + + // TODO: Don't send this packet to players out of range, to save on bandwidth + @SuppressWarnings("ForLoopReplaceableByForEach") + @Inject(method = "sendToOtherNearbyPlayers", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$sendToOtherNearbyPlayersViaNoisiumServerWorldChunkManager(Entity entity, Packet packet, CallbackInfo ci) { + var server = entity.getServer(); + if (server == null) { + return; + } + + var players = server.getPlayerManager().getPlayerList(); + for (int i = 0; i < players.size(); i++) { + var player = players.get(i); + if (player.equals(entity)) { + continue; + } + + player.networkHandler.sendPacket(packet); + } + + ci.cancel(); + } + + @Inject(method = {"loadEntity", "unloadEntity"}, at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$cancelEntityLoadingAndUnloading(Entity entity, CallbackInfo ci) { + ci.cancel(); + } + + @Inject(method = "updatePosition", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$cancelPlayerPositionUpdating(ServerPlayerEntity player, CallbackInfo ci) { + ci.cancel(); + } + + @Inject(method = "markForUpdate", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$markForUpdateViaNoisiumServerWorldChunkManager(BlockPos blockPos, CallbackInfo ci) { + // TODO: Optimise using a pending update queue and ChunkDeltaUpdateS2CPacket + // TODO: Implement block entity update packet sending + var serverWorld = (ServerWorld) this.getWorld(); + PacketUtil.sendPacketToPlayers(serverWorld.getPlayers(), new BlockUpdateS2CPacket(blockPos, serverWorld.getBlockState(blockPos))); + ci.cancel(); + } + + @Inject(method = "onLightUpdate", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$updateLightingViaNoisiumServerWorldChunkManager(LightType lightType, ChunkSectionPos chunkSectionPos, CallbackInfo ci) { + io.github.steveplays28.noisiumchunkmanager.experimental.server.world.chunk.event.ServerChunkEvent.LIGHT_UPDATE.invoker().onLightUpdate(lightType, chunkSectionPos); + ci.cancel(); + } + + @Inject(method = "save", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$cancelSave(boolean flush, CallbackInfo ci) { + ci.cancel(); + } + + @Inject(method = "isChunkLoaded", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$isChunkLoadedInNoisiumServerWorldChunkManager(int chunkX, int chunkZ, CallbackInfoReturnable cir) { + cir.setReturnValue(((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) this.getWorld()).noisiumchunkmanager$getServerWorldChunkManager().isChunkLoaded( + new ChunkPos(chunkX, chunkZ))); + } + + @Inject(method = "getStructurePlacementCalculator", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getStructurePlacementCalculatorFromServerChunkManager(CallbackInfoReturnable cir) { + cir.setReturnValue(noisiumchunkmanager$structurePlacementCalculator); + } + + @Inject(method = "getChunkGenerator", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getChunkGeneratorFromServerChunkManager(@NotNull CallbackInfoReturnable cir) { + cir.setReturnValue(noisiumchunkmanager$chunkGenerator); + } + + @Inject(method = "getNoiseConfig", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getNoiseConfigFromServerChunkManager(@NotNull CallbackInfoReturnable cir) { + cir.setReturnValue(((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) this.getWorld()).noisiumchunkmanager$getNoiseConfig()); + } + + @Inject(method = "getChunkIoWorker", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getChunkIoWorkerFromNoisiumServerWorldChunkManager(@NotNull CallbackInfoReturnable cir) { + cir.setReturnValue(((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) this.getWorld()).noisiumchunkmanager$getServerWorldChunkManager().getChunkIoWorker()); + } + + @Inject(method = {"getLoadedChunkCount", "getTotalChunksLoadedCount"}, at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getTotalChunksLoadedCountFromNoisiumServerWorldChunkManager(@NotNull CallbackInfoReturnable cir) { + // TODO: Remove the method call for 441 start chunks, replace the 2 method calls for client/server chunk count debugging with an event listener and remove this mixin injection + cir.setReturnValue(0); + } + + @Inject(method = {"applyViewDistance", "applySimulationDistance"}, at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$cancelApplyViewAndSimulationDistance(int distance, @NotNull CallbackInfo ci) { + ci.cancel(); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/world/ServerEntityManagerMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/world/ServerEntityManagerMixin.java new file mode 100644 index 0000000..036fc65 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/world/ServerEntityManagerMixin.java @@ -0,0 +1,35 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.server.world; + +import net.minecraft.entity.Entity; +import net.minecraft.server.world.ServerEntityManager; +import net.minecraft.world.entity.EntityLike; +import org.jetbrains.annotations.NotNull; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import io.github.steveplays28.noisiumchunkmanager.experimental.server.world.entity.event.ServerEntityEvent; + +@Mixin(value = ServerEntityManager.class, priority = 500) +public class ServerEntityManagerMixin { + @Inject(method = "stopTracking", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$entityRemoveEventImplementation(T entity, CallbackInfo ci) { + if (entity instanceof Entity entityInWorld) { + if (ServerEntityEvent.REMOVE.invoker().onServerEntityRemove( + entityInWorld, entityInWorld.getWorld()).interruptsFurtherEvaluation()) { + ci.cancel(); + } + } + } + + @Inject(method = "save", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$cancelSave(@NotNull CallbackInfo ci) { + // TODO: Invoke an entity manager save event that's used in NoisiumServerWorldEntityTracker + ci.cancel(); + } + + @Inject(method = "flush", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$cancelFlush(@NotNull CallbackInfo ci) { + ci.cancel(); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/world/ServerWorldMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/world/ServerWorldMixin.java new file mode 100644 index 0000000..2bf0208 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/world/ServerWorldMixin.java @@ -0,0 +1,177 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.server.world; + +import com.llamalad7.mixinextras.sugar.Local; +import com.mojang.datafixers.DataFixer; +import dev.architectury.event.events.common.LifecycleEvent; +import dev.architectury.event.events.common.PlayerEvent; +import io.github.steveplays28.noisiumchunkmanager.server.world.ServerWorldChunkManager; +import io.github.steveplays28.noisiumchunkmanager.util.world.chunk.networking.packet.PacketUtil; +import net.minecraft.block.BlockState; +import net.minecraft.entity.Entity; +import net.minecraft.registry.RegistryKey; +import net.minecraft.registry.RegistryKeys; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.WorldGenerationProgressListener; +import net.minecraft.server.world.ChunkLevelType; +import net.minecraft.server.world.ServerEntityManager; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.random.RandomSequencesState; +import net.minecraft.util.profiler.Profiler; +import net.minecraft.world.PersistentStateManager; +import net.minecraft.world.World; +import net.minecraft.world.dimension.DimensionOptions; +import net.minecraft.world.gen.chunk.ChunkGenerator; +import net.minecraft.world.gen.chunk.ChunkGeneratorSettings; +import net.minecraft.world.gen.chunk.NoiseChunkGenerator; +import net.minecraft.world.gen.noise.NoiseConfig; +import net.minecraft.world.level.ServerWorldProperties; +import net.minecraft.world.level.storage.LevelStorage; +import org.jetbrains.annotations.NotNull; +import org.objectweb.asm.Opcodes; +import org.spongepowered.asm.mixin.*; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import io.github.steveplays28.noisiumchunkmanager.extension.world.server.ServerWorldExtension; +import io.github.steveplays28.noisiumchunkmanager.server.world.entity.ServerWorldEntityTracker; +import io.github.steveplays28.noisiumchunkmanager.server.world.entity.player.ServerWorldPlayerChunkLoader; +import io.github.steveplays28.noisiumchunkmanager.server.world.chunk.event.ServerChunkEvent; + +import java.util.List; +import java.util.concurrent.Executor; + +@Debug(export = true) +@Mixin(ServerWorld.class) +public abstract class ServerWorldMixin implements ServerWorldExtension { + @Shadow + @Final + private ServerEntityManager entityManager; + + @Shadow + public abstract boolean isChunkLoaded(long chunkPos); + + @Shadow + public abstract void tickEntity(Entity entity); + + @Shadow + public abstract @NotNull MinecraftServer getServer(); + + @Unique + private NoiseConfig noisiumchunkmanager$noiseConfig; + /** + * Keeps a reference to this {@link ServerWorld}'s {@link ServerWorldChunkManager}, to make sure it doesn't get garbage collected until the object is no longer necessary. + */ + @Unique + private ServerWorldChunkManager noisiumchunkmanager$serverWorldChunkManager; + /** + * Keeps a reference to this {@link ServerWorld}'s {@link ServerWorldEntityTracker}, to make sure it doesn't get garbage collected until the object is no longer necessary. + */ + @SuppressWarnings({"unused", "FieldCanBeLocal"}) + @Unique + private ServerWorldEntityTracker noisiumchunkmanager$serverWorldEntityManager; + /** + * Keeps a reference to this {@link ServerWorld}'s {@link ServerWorldPlayerChunkLoader}, to make sure it doesn't get garbage collected until the object is no longer necessary. + */ + @SuppressWarnings({"unused", "FieldCanBeLocal"}) + @Unique + private ServerWorldPlayerChunkLoader noisiumchunkmanager$serverWorldPlayerChunkLoader; + + @Inject(method = "", at = @At(value = "INVOKE_ASSIGN", target = "Lnet/minecraft/server/MinecraftServer;getDataFixer()Lcom/mojang/datafixers/DataFixer;", shift = At.Shift.AFTER)) + private void noisiumchunkmanager$constructorCreateServerWorldChunkManager(@NotNull MinecraftServer server, Executor workerExecutor, @NotNull LevelStorage.Session session, @NotNull ServerWorldProperties serverWorldProperties, @NotNull RegistryKey worldKey, @NotNull DimensionOptions dimensionOptions, WorldGenerationProgressListener worldGenerationProgressListener, boolean debugWorld, long seed, List spawners, boolean shouldTickTime, RandomSequencesState randomSequencesState, @NotNull CallbackInfo ci, @Local @NotNull DataFixer dataFixer) { + @SuppressWarnings("DataFlowIssue") + var serverWorld = ((ServerWorld) (Object) this); + @NotNull ChunkGenerator chunkGenerator = dimensionOptions.chunkGenerator(); + @NotNull ChunkGeneratorSettings chunkGeneratorSettings; + if (chunkGenerator instanceof NoiseChunkGenerator noiseChunkGenerator) { + chunkGeneratorSettings = noiseChunkGenerator.getSettings().value(); + } else { + chunkGeneratorSettings = ChunkGeneratorSettings.createMissingSettings(); + } + noisiumchunkmanager$noiseConfig = NoiseConfig.create( + chunkGeneratorSettings, serverWorld.getRegistryManager().getWrapperOrThrow(RegistryKeys.NOISE_PARAMETERS), + serverWorld.getSeed() + ); + noisiumchunkmanager$serverWorldChunkManager = new ServerWorldChunkManager( + serverWorld, chunkGenerator, noisiumchunkmanager$noiseConfig, session.getWorldDirectory(worldKey), dataFixer); + noisiumchunkmanager$serverWorldEntityManager = new ServerWorldEntityTracker( + packet -> PacketUtil.sendPacketToPlayers(serverWorld.getPlayers(), packet)); + noisiumchunkmanager$serverWorldPlayerChunkLoader = new ServerWorldPlayerChunkLoader( + serverWorld, noisiumchunkmanager$serverWorldChunkManager::getChunksInRadiusAsync, + noisiumchunkmanager$serverWorldChunkManager::getChunkAsync, + noisiumchunkmanager$serverWorldChunkManager::unloadChunk, server.getPlayerManager()::getViewDistance + ); + + // TODO: Redo the server entity manager entirely, in an event-based way + // Also remove this line when that's done, since this doesn't belong here + PlayerEvent.PLAYER_JOIN.register(player -> { + if (!player.getWorld().equals(serverWorld)) { + return; + } + + this.entityManager.addEntity(player); + }); + + // TODO: Move this event listener registration to ServerEntityManagerMixin + // or (when it's finished and able to completely replace the vanilla class) to NoisiumServerWorldEntityTracker + // More efficient methods can be used when registering the event listener directly in the server entity manager + ServerChunkEvent.WORLD_CHUNK_GENERATED.register(worldChunk -> server.executeSync( + () -> this.entityManager.updateTrackingStatus(worldChunk.getPos(), ChunkLevelType.ENTITY_TICKING))); + LifecycleEvent.SERVER_STOPPED.register(instance -> { + noisiumchunkmanager$serverWorldPlayerChunkLoader = null; + noisiumchunkmanager$serverWorldEntityManager = null; + noisiumchunkmanager$serverWorldChunkManager = null; + noisiumchunkmanager$noiseConfig = null; + }); + } + + @Inject(method = "getPersistentStateManager", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getPersistentStateManagerFromNoisiumServerWorldChunkManager(@NotNull CallbackInfoReturnable cir) { + cir.setReturnValue(((ServerWorldExtension) this).noisiumchunkmanager$getServerWorldChunkManager().getPersistentStateManager()); + } + + @Inject(method = "isTickingFutureReady", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$checkIfTickingFutureIsReadyByCheckingIfTheChunkIsLoaded(long chunkPos, @NotNull CallbackInfoReturnable cir) { + cir.setReturnValue(this.isChunkLoaded(chunkPos)); + } + + @Inject(method = "method_31420", at = @At(value = "FIELD", target = "Lnet/minecraft/server/world/ServerChunkManager;threadedAnvilChunkStorage:Lnet/minecraft/server/world/ThreadedAnvilChunkStorage;", opcode = Opcodes.GETFIELD), cancellable = true) + private void noisiumchunkmanager$redirectShouldTickEntities(@NotNull Profiler profiler, @NotNull Entity entity, @NotNull CallbackInfo ci) { + if (!this.entityManager.shouldTick(entity.getChunkPos())) { + ci.cancel(); + return; + } + + var vehicleEntity = entity.getVehicle(); + if (vehicleEntity != null) { + if (!vehicleEntity.isRemoved() && vehicleEntity.hasPassenger(entity)) { + ci.cancel(); + return; + } + + entity.stopRiding(); + } + + profiler.push("tick"); + this.tickEntity(entity); + profiler.pop(); + ci.cancel(); + } + + @Inject(method = "onBlockChanged", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$redirectOnBlockChangedToNoisiumServerWorldChunkManager(BlockPos blockPos, BlockState oldBlockState, BlockState newBlockState, CallbackInfo ci) { + ServerChunkEvent.BLOCK_CHANGE.invoker().onBlockChange(blockPos, oldBlockState, newBlockState); + ci.cancel(); + } + + @Override + public ServerWorldChunkManager noisiumchunkmanager$getServerWorldChunkManager() { + return noisiumchunkmanager$serverWorldChunkManager; + } + + @Override + public NoiseConfig noisiumchunkmanager$getNoiseConfig() { + return noisiumchunkmanager$noiseConfig; + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/world/ThreadedAnvilChunkStorageMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/world/ThreadedAnvilChunkStorageMixin.java new file mode 100644 index 0000000..63ace79 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/server/world/ThreadedAnvilChunkStorageMixin.java @@ -0,0 +1,25 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.server.world; + +import net.minecraft.network.packet.s2c.play.ChunkDataS2CPacket; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.world.ThreadedAnvilChunkStorage; +import net.minecraft.util.math.ChunkPos; +import org.apache.commons.lang3.mutable.MutableObject; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(ThreadedAnvilChunkStorage.class) +public class ThreadedAnvilChunkStorageMixin { + @Inject(method = "sendWatchPackets", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$cancelSendWatchPackets(ServerPlayerEntity player, ChunkPos pos, MutableObject packet, boolean oldWithinViewDistance, boolean newWithinViewDistance, CallbackInfo ci) { + ci.cancel(); + } + + @Inject(method = "shouldDelayShutdown", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$cancelShutdownDelay(CallbackInfoReturnable cir) { + cir.setReturnValue(false); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/ChunkRegionMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/ChunkRegionMixin.java new file mode 100644 index 0000000..91f3ad9 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/ChunkRegionMixin.java @@ -0,0 +1,104 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.world; + +import net.minecraft.block.BlockState; +import net.minecraft.block.Blocks; +import net.minecraft.fluid.FluidState; +import net.minecraft.registry.DynamicRegistryManager; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.util.math.ChunkSectionPos; +import net.minecraft.world.ChunkRegion; +import net.minecraft.world.Heightmap; +import net.minecraft.world.StructureWorldAccess; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.ChunkStatus; +import org.jetbrains.annotations.NotNull; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.List; + +@Mixin(value = ChunkRegion.class, priority = 200) +public abstract class ChunkRegionMixin implements StructureWorldAccess { + @Shadow + public abstract boolean isChunkLoaded(int chunkX, int chunkZ); + + @Shadow + public abstract int getSeaLevel(); + + @Shadow + @Final + private @NotNull ChunkPos lowerCorner; + + @Shadow + @Final + private @NotNull List chunks; + + @Shadow + @Final + private int width; + + @Shadow + public abstract @NotNull DynamicRegistryManager getRegistryManager(); + + @Shadow + @Final + private @NotNull ServerWorld world; + + @Inject(method = "needsBlending", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$cancelBlending(@NotNull ChunkPos chunkPosition, int checkRadius, @NotNull CallbackInfoReturnable cir) { + // TODO: Reimplement chunk blending + cir.setReturnValue(false); + } + + @Inject(method = "getChunk(IILnet/minecraft/world/chunk/ChunkStatus;Z)Lnet/minecraft/world/chunk/Chunk;", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getIoWorldChunkIfChunkIsUnloaded(int chunkPositionX, int chunkPositionZ, @NotNull ChunkStatus leastStatus, boolean create, @NotNull CallbackInfoReturnable cir) { + if (!this.isChunkLoaded(chunkPositionX, chunkPositionZ)) { + cir.setReturnValue(((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) this.world).noisiumchunkmanager$getServerWorldChunkManager().getIoWorldChunk( + new ChunkPos(chunkPositionX, chunkPositionZ))); + return; + } + + cir.setReturnValue(this.chunks.get(chunkPositionX - this.lowerCorner.x + (chunkPositionZ - this.lowerCorner.z) * this.width)); + } + + @Inject(method = "getBlockState", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getBlockStateFromIoWorldChunkIfChunkIsUnloaded(@NotNull BlockPos blockPos, @NotNull CallbackInfoReturnable cir) { + if (!this.isChunkLoaded(ChunkSectionPos.getSectionCoord(blockPos.getX()), ChunkSectionPos.getSectionCoord(blockPos.getZ()))) { + cir.setReturnValue(Blocks.AIR.getDefaultState()); + } + } + + @Inject(method = "setBlockState", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$setBlockStateToIoWorldChunkIfChunkIsUnloaded(@NotNull BlockPos blockPos, @NotNull BlockState blockState, int flags, int maxUpdateDepth, @NotNull CallbackInfoReturnable cir) { + if (!this.isChunkLoaded(ChunkSectionPos.getSectionCoord(blockPos.getX()), ChunkSectionPos.getSectionCoord(blockPos.getZ()))) { + ((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) this.world).noisiumchunkmanager$getServerWorldChunkManager().getIoWorldChunk( + new ChunkPos(blockPos)).setBlockState(blockPos, blockState, false); + cir.setReturnValue(true); + } + } + + @Inject(method = "getFluidState", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getFluidStateFromIoWorldChunkIfChunkIsUnloaded(@NotNull BlockPos blockPos, @NotNull CallbackInfoReturnable cir) { + if (!this.isChunkLoaded(ChunkSectionPos.getSectionCoord(blockPos.getX()), ChunkSectionPos.getSectionCoord(blockPos.getZ()))) { + cir.setReturnValue(((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) this.world).noisiumchunkmanager$getServerWorldChunkManager().getIoWorldChunk( + new ChunkPos(blockPos)).getFluidState(blockPos)); + } + } + + @Inject(method = "getTopY", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getTopYFromIoWorldChunkIfChunkIsUnloaded(@NotNull Heightmap.Type heightmap, int blockPositionX, int blockPositionZ, @NotNull CallbackInfoReturnable cir) { + if (!this.isChunkLoaded(ChunkSectionPos.getSectionCoord(blockPositionX), ChunkSectionPos.getSectionCoord(blockPositionZ))) { + cir.setReturnValue(((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) this.world).noisiumchunkmanager$getServerWorldChunkManager().getIoWorldChunk( + new ChunkPos( + ChunkSectionPos.getSectionCoord(blockPositionX), + ChunkSectionPos.getSectionCoord(blockPositionZ) + )).getTopY()); + } + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/ChunkSectionCacheMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/ChunkSectionCacheMixin.java new file mode 100644 index 0000000..1ec06d3 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/ChunkSectionCacheMixin.java @@ -0,0 +1,39 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.world; + +import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +import net.minecraft.registry.RegistryKeys; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.util.math.ChunkSectionPos; +import net.minecraft.world.ChunkSectionCache; +import net.minecraft.world.WorldAccess; +import net.minecraft.world.chunk.ChunkSection; +import org.jetbrains.annotations.NotNull; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(ChunkSectionCache.class) +public class ChunkSectionCacheMixin { + @Shadow + @Final + private @NotNull WorldAccess world; + + @Shadow + @Final + private Long2ObjectMap cache; + + @Inject(method = "getSection", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$returnEmptyChunkSectionIfChunkIsUnloaded(@NotNull BlockPos blockPos, @NotNull CallbackInfoReturnable cir) { + if (!world.isChunkLoaded(ChunkSectionPos.getSectionCoord(blockPos.getX()), ChunkSectionPos.getSectionCoord(blockPos.getZ()))) { + // TODO: Get an IoWorldChunk from NoisiumServerWorldChunkManager instead + // Get a World by checking if (world instanceof World worldCasted) + cir.setReturnValue(this.cache.computeIfAbsent(new ChunkPos(blockPos).toLong(), + l -> new ChunkSection(world.getRegistryManager().get(RegistryKeys.BIOME)) + )); + } + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/WorldMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/WorldMixin.java new file mode 100644 index 0000000..06b8882 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/WorldMixin.java @@ -0,0 +1,69 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.world; + +import net.minecraft.block.BlockState; +import net.minecraft.fluid.FluidState; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.ChunkStatus; +import org.jetbrains.annotations.NotNull; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(value = World.class, priority = 200) +public abstract class WorldMixin { + @Shadow + public abstract boolean isClient(); + + @Inject(method = "getChunk(IILnet/minecraft/world/chunk/ChunkStatus;Z)Lnet/minecraft/world/chunk/Chunk;", at = @At(value = "HEAD"), cancellable = true) + private void noisiumchunkmanager$getChunkFromNoisiumServerChunkManager(int chunkPositionX, int chunkPositionZ, @NotNull ChunkStatus leastStatus, boolean create, @NotNull CallbackInfoReturnable cir) { + if (this.isClient()) { + return; + } + + var noisiumServerWorldChunkManager = ((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) this).noisiumchunkmanager$getServerWorldChunkManager(); + var chunkPosition = new ChunkPos(chunkPositionX, chunkPositionZ); + if (!noisiumServerWorldChunkManager.isChunkLoaded(chunkPosition)) { + cir.setReturnValue(noisiumServerWorldChunkManager.getIoWorldChunk(chunkPosition)); + return; + } + + cir.setReturnValue(noisiumServerWorldChunkManager.getChunk(chunkPosition)); + } + + @Inject(method = "getBlockState", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;getChunk(II)Lnet/minecraft/world/chunk/WorldChunk;"), cancellable = true) + private void noisiumchunkmanager$getBlockStateGetChunkFromNoisiumServerChunkManager(@NotNull BlockPos blockPosition, @NotNull CallbackInfoReturnable cir) { + if (this.isClient()) { + return; + } + + var noisiumServerWorldChunkManager = ((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) this).noisiumchunkmanager$getServerWorldChunkManager(); + var chunkPosition = new ChunkPos(blockPosition); + if (!noisiumServerWorldChunkManager.isChunkLoaded(chunkPosition)) { + cir.setReturnValue(noisiumServerWorldChunkManager.getIoWorldChunk(chunkPosition).getBlockState(blockPosition)); + return; + } + + cir.setReturnValue(noisiumServerWorldChunkManager.getChunk(chunkPosition).getBlockState(blockPosition)); + } + + @Inject(method = "getFluidState", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;getWorldChunk(Lnet/minecraft/util/math/BlockPos;)Lnet/minecraft/world/chunk/WorldChunk;"), cancellable = true) + private void noisiumchunkmanager$getFluidStateGetChunkFromNoisiumServerChunkManager(@NotNull BlockPos blockPosition, @NotNull CallbackInfoReturnable cir) { + if (this.isClient()) { + return; + } + + var noisiumServerWorldChunkManager = ((io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.server.ServerWorldExtension) this).noisiumchunkmanager$getServerWorldChunkManager(); + var chunkPosition = new ChunkPos(blockPosition); + if (!noisiumServerWorldChunkManager.isChunkLoaded(chunkPosition)) { + cir.setReturnValue(noisiumServerWorldChunkManager.getIoWorldChunk(chunkPosition).getFluidState(blockPosition)); + return; + } + + cir.setReturnValue(noisiumServerWorldChunkManager.getChunk(chunkPosition).getFluidState(blockPosition)); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/chunk/PalettedContainerMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/chunk/PalettedContainerMixin.java new file mode 100644 index 0000000..74b93b9 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/chunk/PalettedContainerMixin.java @@ -0,0 +1,53 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.world.chunk; + +import net.minecraft.util.thread.LockHelper; +import net.minecraft.world.chunk.PalettedContainer; +import org.jetbrains.annotations.NotNull; +import org.spongepowered.asm.mixin.*; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +@Mixin(PalettedContainer.class) +public class PalettedContainerMixin { + @Shadow + @Final + @Mutable + private LockHelper lockHelper; + + @Unique + private final Lock noisiumchunkmanager$lock = new ReentrantLock(); + + @Inject( + method = { + "(Lnet/minecraft/util/collection/IndexedIterable;Ljava/lang/Object;Lnet/minecraft/world/chunk/PalettedContainer$PaletteProvider;)V", + "(Lnet/minecraft/util/collection/IndexedIterable;Lnet/minecraft/world/chunk/PalettedContainer$PaletteProvider;Lnet/minecraft/world/chunk/PalettedContainer$Data;)V", + "(Lnet/minecraft/util/collection/IndexedIterable;Lnet/minecraft/world/chunk/PalettedContainer$PaletteProvider;Lnet/minecraft/world/chunk/PalettedContainer$DataProvider;Lnet/minecraft/util/collection/PaletteStorage;Ljava/util/List;)V", + }, + at = @At("TAIL") + ) + public void removeLockHelper(@NotNull CallbackInfo ci) { + this.lockHelper = null; + } + + /** + * @reason Optimise locking. + * @author Steveplays28 + */ + @Overwrite + public void lock() { + noisiumchunkmanager$lock.lock(); + } + + /** + * @reason Optimise unlocking. + * @author Steveplays28 + */ + @Overwrite + public void unlock() { + noisiumchunkmanager$lock.unlock(); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/chunk/WorldChunkMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/chunk/WorldChunkMixin.java new file mode 100644 index 0000000..ace9d32 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/chunk/WorldChunkMixin.java @@ -0,0 +1,25 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.world.chunk; + +import net.minecraft.world.chunk.WorldChunk; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; + +import java.util.BitSet; + +@Mixin(WorldChunk.class) +public class WorldChunkMixin implements io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.chunk.WorldChunkExtension { + @Unique + private final BitSet noisiumchunkmanager$blockLightBits = new BitSet(); + @Unique + private final BitSet noisiumchunkmanager$skyLightBits = new BitSet(); + + @Override + public BitSet noisiumchunkmanager$getBlockLightBits() { + return noisiumchunkmanager$blockLightBits; + } + + @Override + public BitSet noisiumchunkmanager$getSkyLightBits() { + return noisiumchunkmanager$skyLightBits; + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/gen/chunk/ChunkGeneratorMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/gen/chunk/ChunkGeneratorMixin.java new file mode 100644 index 0000000..2312bf4 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/gen/chunk/ChunkGeneratorMixin.java @@ -0,0 +1,236 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.world.gen.chunk; + +import it.unimi.dsi.fastutil.ints.IntArraySet; +import it.unimi.dsi.fastutil.ints.IntSet; +import it.unimi.dsi.fastutil.objects.ObjectArraySet; +import net.minecraft.SharedConstants; +import net.minecraft.registry.Registries; +import net.minecraft.registry.Registry; +import net.minecraft.registry.RegistryKeys; +import net.minecraft.registry.entry.RegistryEntry; +import net.minecraft.registry.entry.RegistryEntryList; +import net.minecraft.server.network.DebugInfoSender; +import net.minecraft.structure.StructureStart; +import net.minecraft.util.crash.CrashException; +import net.minecraft.util.crash.CrashReport; +import net.minecraft.util.crash.CrashReportSection; +import net.minecraft.util.math.BlockBox; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.util.math.ChunkSectionPos; +import net.minecraft.util.math.random.ChunkRandom; +import net.minecraft.util.math.random.RandomSeed; +import net.minecraft.util.math.random.Xoroshiro128PlusPlusRandom; +import net.minecraft.world.StructureWorldAccess; +import net.minecraft.world.biome.Biome; +import net.minecraft.world.biome.GenerationSettings; +import net.minecraft.world.biome.source.BiomeSource; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.ChunkSection; +import net.minecraft.world.gen.GenerationStep; +import net.minecraft.world.gen.StructureAccessor; +import net.minecraft.world.gen.chunk.ChunkGenerator; +import net.minecraft.world.gen.feature.PlacedFeature; +import net.minecraft.world.gen.feature.util.PlacedFeatureIndexer; +import net.minecraft.world.gen.structure.Structure; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.*; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +@Mixin(ChunkGenerator.class) +public abstract class ChunkGeneratorMixin { + @Shadow + @Final + private Supplier> indexedFeaturesListSupplier; + + @Shadow + private static BlockBox getBlockBoxForChunk(Chunk chunk) { + throw new RuntimeException(); + } + + @Shadow + @Final + private Function, GenerationSettings> generationSettingsGetter; + + @Shadow + public abstract BiomeSource getBiomeSource(); + + /** + * Replaces {@link ChunkGenerator#addStructureReferences} with a simpler one, that only checks the center chunk, instead of iterating outwards. + * This fixes an infinite loop with {@link io.github.steveplays28.noisiumchunkmanager.experimental.server.world.ServerWorldChunkManager}. + */ + @Inject(method = "addStructureReferences", at = @At(value = "HEAD"), cancellable = true) + public void noisiumchunkmanager$replaceAddStructureReferencesToFixAnInfiniteLoop(StructureWorldAccess world, StructureAccessor structureAccessor, Chunk chunk, CallbackInfo ci) { + var chunkPos = chunk.getPos(); + int chunkPosStartX = chunkPos.getStartX(); + int chunkPosStartZ = chunkPos.getStartZ(); + var chunkSectionPos = ChunkSectionPos.from(chunk); + var chunkPosLong = chunkPos.toLong(); + + for (StructureStart structureStart : chunk.getStructureStarts().values()) { + try { + if (structureStart.hasChildren() && structureStart.getBoundingBox().intersectsXZ( + chunkPosStartX, chunkPosStartZ, chunkPosStartX + 15, chunkPosStartZ + 15) + ) { + structureAccessor.addStructureReference(chunkSectionPos, structureStart.getStructure(), chunkPosLong, chunk); + DebugInfoSender.sendStructureStart(world, structureStart); + } + } catch (Exception e) { + CrashReport crashReport = CrashReport.create(e, "Generating structure reference"); + CrashReportSection crashReportSection = crashReport.addElement("Structure"); + crashReportSection.add( + "Id", + () -> world.getRegistryManager().getOptional(RegistryKeys.STRUCTURE).map( + structureTypeRegistry -> { + var structureId = structureTypeRegistry.getId(structureStart.getStructure()); + if (structureId == null) { + return "UNKNOWN"; + } + + return structureId.toString(); + } + ).orElse("UNKNOWN") + ); + crashReportSection.add( + "Name", + () -> { + var structureTypeId = Registries.STRUCTURE_TYPE.getId(structureStart.getStructure().getType()); + if (structureTypeId == null) { + return "UNKNOWN"; + } + + return structureTypeId.toString(); + } + ); + crashReportSection.add("Class", () -> structureStart.getStructure().getClass().getCanonicalName()); + throw new CrashException(crashReport); + } + } + + ci.cancel(); + } + + /** + * @author Steveplays28 + * @reason TODO + */ + @Overwrite + public void generateFeatures(StructureWorldAccess world, Chunk chunk, StructureAccessor structureAccessor) { + ChunkPos chunkPos = chunk.getPos(); + if (SharedConstants.isOutsideGenerationArea(chunkPos)) { + return; + } + + ChunkSectionPos chunkSectionPos = ChunkSectionPos.from(chunkPos, world.getBottomSectionCoord()); + BlockPos blockPos = chunkSectionPos.getMinPos(); + Registry registry = world.getRegistryManager().get(RegistryKeys.STRUCTURE); + Map> map = registry.stream().collect( + Collectors.groupingBy((structureType) -> structureType.getFeatureGenerationStep().ordinal())); + List indexedFeatures = this.indexedFeaturesListSupplier.get(); + ChunkRandom chunkRandom = new ChunkRandom(new Xoroshiro128PlusPlusRandom(RandomSeed.getSeed())); + long l = chunkRandom.setPopulationSeed(world.getSeed(), blockPos.getX(), blockPos.getZ()); + Set> biomeRegistryEntries = new ObjectArraySet<>(); + for (ChunkSection chunkSection : chunk.getSectionArray()) { + chunkSection.getBiomeContainer().forEachValue(biomeRegistryEntries::add); + } + biomeRegistryEntries.retainAll(this.getBiomeSource().getBiomes()); + int indexedFeaturesSize = indexedFeatures.size(); + + try { + Registry placedFeatureRegistry = world.getRegistryManager().get(RegistryKeys.PLACED_FEATURE); + int j = Math.max(GenerationStep.Feature.values().length, indexedFeaturesSize); + + for (int indexedFeatureIndex = 0; indexedFeatureIndex < j; ++indexedFeatureIndex) { + int m = 0; + CrashReportSection crashReportSection; + if (structureAccessor.shouldGenerateStructures()) { + List list2 = map.getOrDefault(indexedFeatureIndex, Collections.emptyList()); + + for (var biomeRegistryEntriesIterator = list2.iterator(); biomeRegistryEntriesIterator.hasNext(); ++m) { + Structure structure = biomeRegistryEntriesIterator.next(); + chunkRandom.setDecoratorSeed(l, m, indexedFeatureIndex); + Supplier currentlyGeneratingStructureNameSupplier = () -> { + var placedFeatureNameOptional = registry.getKey(structure).map(Object::toString); + Objects.requireNonNull(structure); + return placedFeatureNameOptional.orElseGet(structure::toString); + }; + + try { + world.setCurrentlyGeneratingStructureName(currentlyGeneratingStructureNameSupplier); + //noinspection DataFlowIssue + structureAccessor.getStructureStarts(chunkSectionPos, structure).forEach((start) -> start.place( + world, structureAccessor, (ChunkGenerator) (Object) this, chunkRandom, + getBlockBoxForChunk(chunk), chunkPos + )); + } catch (Exception e) { + CrashReport crashReport = CrashReport.create(e, "Feature placement"); + crashReportSection = crashReport.addElement("Feature"); + Objects.requireNonNull(currentlyGeneratingStructureNameSupplier); + crashReportSection.add("Description", currentlyGeneratingStructureNameSupplier::get); + throw new CrashException(crashReport); + } + } + } + + if (indexedFeatureIndex < indexedFeaturesSize) { + IntSet placedFeatureIndexMappings = new IntArraySet(); + + for (RegistryEntry biomeRegistryEntry : biomeRegistryEntries) { + List> placedFeatureRegistryEntries = this.generationSettingsGetter.apply( + biomeRegistryEntry).getFeatures(); + if (indexedFeatureIndex < placedFeatureRegistryEntries.size()) { + RegistryEntryList registryEntryList = placedFeatureRegistryEntries.get(indexedFeatureIndex); + PlacedFeatureIndexer.IndexedFeatures indexedFeature = indexedFeatures.get(indexedFeatureIndex); + registryEntryList.stream().map(RegistryEntry::value).forEach( + (placedFeature) -> placedFeatureIndexMappings.add( + indexedFeature.indexMapping().applyAsInt(placedFeature))); + } + } + + int placedFeatureIndexMappingsSize = placedFeatureIndexMappings.size(); + int[] placedFeatureIndexMappingsArray = placedFeatureIndexMappings.toIntArray(); + Arrays.sort(placedFeatureIndexMappingsArray); + PlacedFeatureIndexer.IndexedFeatures indexedFeature = indexedFeatures.get(indexedFeatureIndex); + + for (int o = 0; o < placedFeatureIndexMappingsSize; ++o) { + int p = placedFeatureIndexMappingsArray[o]; + PlacedFeature placedFeature = indexedFeature.features().get(p); + Supplier currentlyGeneratingStructureNameSupplier = () -> { + var placedFeatureNameOptional = placedFeatureRegistry.getKey(placedFeature).map(Object::toString); + Objects.requireNonNull(placedFeature); + return placedFeatureNameOptional.orElseGet(placedFeature::toString); + }; + chunkRandom.setDecoratorSeed(l, p, indexedFeatureIndex); + + try { + world.setCurrentlyGeneratingStructureName(currentlyGeneratingStructureNameSupplier); + //noinspection DataFlowIssue + placedFeature.generate(world, (ChunkGenerator) (Object) this, chunkRandom, blockPos); + } catch (Exception e) { + CrashReport crashReport = CrashReport.create(e, "Feature placement"); + crashReportSection = crashReport.addElement("Feature"); + Objects.requireNonNull(currentlyGeneratingStructureNameSupplier); + crashReportSection.add("Description", currentlyGeneratingStructureNameSupplier::get); + throw new CrashException(crashReport); + } + } + } + } + + world.setCurrentlyGeneratingStructureName(null); + } catch (Exception var31) { + CrashReport crashReport3 = CrashReport.create(var31, "Biome decoration"); + crashReport3.addElement("Generation").add("CenterX", chunkPos.x).add("CenterZ", chunkPos.z).add("Seed", l); + throw new CrashException(crashReport3); + } + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/gen/chunk/NoiseChunkGeneratorMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/gen/chunk/NoiseChunkGeneratorMixin.java new file mode 100644 index 0000000..5e14b2b --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/gen/chunk/NoiseChunkGeneratorMixin.java @@ -0,0 +1,19 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.world.gen.chunk; + +import net.minecraft.world.gen.chunk.NoiseChunkGenerator; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.Constant; +import org.spongepowered.asm.mixin.injection.ModifyConstant; + +@Mixin(NoiseChunkGenerator.class) +public class NoiseChunkGeneratorMixin { + @ModifyConstant(method = "carve", constant = @Constant(intValue = 8)) + private int noisiumchunkmanager$modifyCarvingChunkRadiusPositiveToFixAnInfiniteLoop(int chunkRadius) { + return 0; + } + + @ModifyConstant(method = "carve", constant = @Constant(intValue = -8)) + private int noisiumchunkmanager$modifyCarvingChunkRadiusNegativeToFixAnInfiniteLoop(int chunkRadius) { + return 0; + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/gen/feature/OreFeatureMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/gen/feature/OreFeatureMixin.java new file mode 100644 index 0000000..3c66488 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/gen/feature/OreFeatureMixin.java @@ -0,0 +1,141 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.world.gen.feature; + +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.MathHelper; +import net.minecraft.util.math.random.Random; +import net.minecraft.world.StructureWorldAccess; +import net.minecraft.world.gen.feature.OreFeature; +import net.minecraft.world.gen.feature.OreFeatureConfig; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.BitSet; + +import static net.minecraft.world.gen.feature.OreFeature.shouldPlace; + +@Mixin(value = OreFeature.class, priority = 500) +public class OreFeatureMixin { + @Inject(method = "generateVeinPart", at = @At(value = "HEAD"), cancellable = true) + public void noisiumchunkmanager$generateVeinPartWithoutChunkSectionCache( + @NotNull StructureWorldAccess world, + @NotNull Random random, + @NotNull OreFeatureConfig config, + double startX, + double endX, + double startZ, + double endZ, + double startY, + double endY, + int x, + int y, + int z, + int horizontalSize, + int verticalSize, + CallbackInfoReturnable cir + ) { + int i = 0; + BitSet bitSet = new BitSet(horizontalSize * verticalSize * horizontalSize); + BlockPos.Mutable mutableBlockPosition = new BlockPos.Mutable(); + int size = config.size; + final double[] ds = new double[size * 4]; + + for (int k = 0; k < size; ++k) { + float f = (float) k / (float) size; + double d = MathHelper.lerp(f, startX, endX); + double e = MathHelper.lerp(f, startY, endY); + double g = MathHelper.lerp(f, startZ, endZ); + double h = random.nextDouble() * (double) size / 16.0; + double l = ((double) (MathHelper.sin((float) Math.PI * f) + 1.0F) * h + 1.0) / 2.0; + ds[k * 4] = d; + ds[k * 4 + 1] = e; + ds[k * 4 + 2] = g; + ds[k * 4 + 3] = l; + } + + for (int k = 0; k < size - 1; ++k) { + if (!(ds[k * 4 + 3] <= 0.0)) { + for (int m = k + 1; m < size; ++m) { + if (!(ds[m * 4 + 3] <= 0.0)) { + double d = ds[k * 4] - ds[m * 4]; + double e = ds[k * 4 + 1] - ds[m * 4 + 1]; + double g = ds[k * 4 + 2] - ds[m * 4 + 2]; + double h = ds[k * 4 + 3] - ds[m * 4 + 3]; + if (h * h > d * d + e * e + g * g) { + if (h > 0.0) { + ds[m * 4 + 3] = -1.0; + } else { + ds[k * 4 + 3] = -1.0; + } + } + } + } + } + } + + for (int m = 0; m < size; ++m) { + double d = ds[m * 4 + 3]; + if (!(d < 0.0)) { + double e = ds[m * 4]; + double g = ds[m * 4 + 1]; + double h = ds[m * 4 + 2]; + int n = Math.max(MathHelper.floor(e - d), x); + int o = Math.max(MathHelper.floor(g - d), y); + int p = Math.max(MathHelper.floor(h - d), z); + int q = Math.max(MathHelper.floor(e + d), n); + int r = Math.max(MathHelper.floor(g + d), o); + int s = Math.max(MathHelper.floor(h + d), p); + + for (int t = n; t <= q; ++t) { + double u = ((double) t + 0.5 - e) / d; + if (u * u < 1.0) { + for (int v = o; v <= r; ++v) { + double w = ((double) v + 0.5 - g) / d; + if (u * u + w * w < 1.0) { + for (int aa = p; aa <= s; ++aa) { + double ab = ((double) aa + 0.5 - h) / d; + if (u * u + w * w + ab * ab < 1.0 && !world.isOutOfHeightLimit(v)) { + int ac = t - x + (v - y) * horizontalSize + (aa - z) * horizontalSize * verticalSize; + if (bitSet.get(ac)) { + continue; + } + + bitSet.set(ac); + mutableBlockPosition.set(t, v, aa); + if (!world.isValidForSetBlock(mutableBlockPosition)) { + continue; + } + + @Nullable final var chunk = world.getChunk(mutableBlockPosition); + if (chunk == null) { + continue; + } + + @Nullable final var blockState = chunk.getBlockState(mutableBlockPosition); + if (blockState == null) { + continue; + } + + for (OreFeatureConfig.Target target : config.targets) { + if (shouldPlace( + blockState, chunk::getBlockState, random, config, target, mutableBlockPosition)) { + chunk.setBlockState(mutableBlockPosition, target.state, false); + ++i; + break; + } + } + } + } + } + } + } + } + } + } + + cir.setReturnValue(i > 0); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/storage/SerializingRegionBasedStorageMixin.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/storage/SerializingRegionBasedStorageMixin.java new file mode 100644 index 0000000..54db847 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/mixin/world/storage/SerializingRegionBasedStorageMixin.java @@ -0,0 +1,54 @@ +package io.github.steveplays28.noisiumchunkmanager.mixin.world.storage; + +import io.github.steveplays28.noisiumchunkmanager.NoisiumChunkManager; +import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +import net.minecraft.world.storage.SerializingRegionBasedStorage; +import org.jetbrains.annotations.NotNull; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; + +@Mixin(SerializingRegionBasedStorage.class) +public abstract class SerializingRegionBasedStorageMixin { + @Shadow + protected abstract void onUpdate(long pos); + + @Shadow + @Final + private Function factory; + /** + * The loaded elements of this {@link SerializingRegionBasedStorage}. + * Thread-safe. + */ + @Unique + private final @NotNull Map> noisiumchunkmanager$loadedElements = new ConcurrentHashMap<>(); + + @Redirect(method = {"getIfLoaded", "serialize", "onUpdate"}, at = @At(value = "INVOKE", target = "Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;get(J)Ljava/lang/Object;")) + private Object noisiumchunkmanager$getLoadedElementsThreadSafe(@NotNull Long2ObjectMap> instance, long l) { + return noisiumchunkmanager$loadedElements.get(l); + } + + @SuppressWarnings("unchecked") + @Redirect(method = {"getOrCreate", "update"}, at = @At(value = "INVOKE", target = "Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;put(JLjava/lang/Object;)Ljava/lang/Object;")) + private Object noisiumchunkmanager$putLoadedElementsThreadSafe(@NotNull Long2ObjectMap> instance, long l, @NotNull Object object) { + return noisiumchunkmanager$loadedElements.put(l, (Optional) object); + } + + @Inject(method = "getOrCreate", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/Util;throwOrPause(Ljava/lang/Throwable;)Ljava/lang/Throwable;", shift = At.Shift.BEFORE), cancellable = true) + private void noisiumchunkmanager$preventThrowingExceptionOnChunkSectionPositionOutOfBounds(long chunkSectionPosition, @NotNull CallbackInfoReturnable cir) { + NoisiumChunkManager.LOGGER.debug("Chunk section position ({}) was out of bounds.", chunkSectionPosition); + R object = this.factory.apply(() -> this.onUpdate(chunkSectionPosition)); + this.noisiumchunkmanager$loadedElements.put(chunkSectionPosition, Optional.of(object)); + cir.setReturnValue(object); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/NoisiumChunkManagerServerInitialiser.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/NoisiumChunkManagerServerInitialiser.java new file mode 100644 index 0000000..3f8bbf0 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/NoisiumChunkManagerServerInitialiser.java @@ -0,0 +1,16 @@ +package io.github.steveplays28.noisiumchunkmanager.server; + +import dev.architectury.event.events.common.LifecycleEvent; + +public class NoisiumChunkManagerServerInitialiser { + /** + * Keeps a reference to the {@link io.github.steveplays28.noisiumchunkmanager.experimental.server.player.ServerPlayerBlockUpdater}, to make sure it doesn't get garbage collected until the object is no longer necessary. + */ + @SuppressWarnings("unused") + private static io.github.steveplays28.noisiumchunkmanager.experimental.server.player.ServerPlayerBlockUpdater serverPlayerBlockUpdater; + + public static void initialise() { + LifecycleEvent.SERVER_STARTED.register(instance -> serverPlayerBlockUpdater = new io.github.steveplays28.noisiumchunkmanager.experimental.server.player.ServerPlayerBlockUpdater()); + LifecycleEvent.SERVER_STOPPING.register(instance -> serverPlayerBlockUpdater = null); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/player/ServerPlayerBlockUpdater.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/player/ServerPlayerBlockUpdater.java new file mode 100644 index 0000000..e457a0d --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/player/ServerPlayerBlockUpdater.java @@ -0,0 +1,27 @@ +package io.github.steveplays28.noisiumchunkmanager.experimental.server.player; + +import dev.architectury.event.EventResult; +import dev.architectury.event.events.common.BlockEvent; +import io.github.steveplays28.noisiumchunkmanager.experimental.util.world.chunk.ChunkUtil; +import net.minecraft.block.Blocks; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import org.jetbrains.annotations.NotNull; + +public class ServerPlayerBlockUpdater { + public ServerPlayerBlockUpdater() { + // TODO: Replace this event with an event that runs when ServerChunkManager#markForUpdate is called + // The mixin for that event should cancel the existing method to improve performance (it'll do nothing anyway) + BlockEvent.BREAK.register((world, blockPos, blockState, player, xp) -> onBlockBreak(world, blockPos)); + } + + private EventResult onBlockBreak(@NotNull World world, @NotNull BlockPos blockPos) { + if (world.isClient()) { + return EventResult.pass(); + } + + ChunkUtil.sendBlockUpdateToPlayers(((ServerWorld) world).getPlayers(), blockPos, Blocks.AIR.getDefaultState()); + return EventResult.pass(); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/ServerVersionedChunkStorage.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/ServerVersionedChunkStorage.java new file mode 100644 index 0000000..77fc41f --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/ServerVersionedChunkStorage.java @@ -0,0 +1,12 @@ +package io.github.steveplays28.noisiumchunkmanager.experimental.server.world; + +import com.mojang.datafixers.DataFixer; +import net.minecraft.world.storage.VersionedChunkStorage; + +import java.nio.file.Path; + +public class ServerVersionedChunkStorage extends VersionedChunkStorage { + public ServerVersionedChunkStorage(Path directory, DataFixer dataFixer, boolean dsync) { + super(directory, dataFixer, dsync); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/ServerWorldChunkManager.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/ServerWorldChunkManager.java new file mode 100644 index 0000000..4931754 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/ServerWorldChunkManager.java @@ -0,0 +1,464 @@ +package io.github.steveplays28.noisiumchunkmanager.server.world; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import com.mojang.datafixers.DataFixer; +import dev.architectury.event.events.common.LifecycleEvent; +import dev.architectury.event.events.common.TickEvent; +import io.github.steveplays28.noisiumchunkmanager.NoisiumChunkManager; +import io.github.steveplays28.noisiumchunkmanager.config.NoisiumChunkManagerConfig; +import io.github.steveplays28.noisiumchunkmanager.util.world.chunk.ChunkUtil; +import io.github.steveplays28.noisiumchunkmanager.experimental.world.chunk.IoWorldChunk; +import io.github.steveplays28.noisiumchunkmanager.mixin.accessor.util.collection.PackedIntegerArrayAccessor; +import io.github.steveplays28.noisiumchunkmanager.mixin.accessor.world.gen.chunk.ChunkGeneratorAccessor; +import net.minecraft.block.BlockState; +import net.minecraft.block.Blocks; +import net.minecraft.entity.EntityType; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryKeys; +import net.minecraft.registry.entry.RegistryEntry; +import net.minecraft.server.world.ServerLightingProvider; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.collection.PackedIntegerArray; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.util.math.ChunkSectionPos; +import net.minecraft.world.*; +import net.minecraft.world.chunk.*; +import net.minecraft.world.gen.GenerationStep; +import net.minecraft.world.gen.chunk.Blender; +import net.minecraft.world.gen.chunk.ChunkGenerator; +import net.minecraft.world.gen.noise.NoiseConfig; +import net.minecraft.world.poi.PointOfInterestStorage; +import net.minecraft.world.poi.PointOfInterestType; +import net.minecraft.world.poi.PointOfInterestTypes; +import net.minecraft.world.storage.NbtScannable; +import net.minecraft.world.storage.VersionedChunkStorage; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.*; +import java.util.function.Function; + +import static io.github.steveplays28.noisiumchunkmanager.NoisiumChunkManager.MOD_NAME; + +/** + * A chunk manager for {@link ServerWorld}s. + * This class cannot extend {@link net.minecraft.server.world.ServerChunkManager} or {@link ChunkManager} due to {@link ServerWorld}s requiring an implementation of {@link net.minecraft.server.world.ServerChunkManager}, which would slow the chunk manager down. + */ +// TODO: Fix canTickBlockEntities() check +// The check needs to be changed to point to the server world's isChunkLoaded() method +// TODO: Implement chunk ticking +// TODO: Save all chunks when save event is called +public class ServerWorldChunkManager { + private final ServerWorld serverWorld; + private final ChunkGenerator chunkGenerator; + private final NoiseConfig noiseConfig; + private final PersistentStateManager persistentStateManager; + private final PointOfInterestStorage pointOfInterestStorage; + private final VersionedChunkStorage versionedChunkStorage; + private final Executor threadPoolExecutor; + private final Executor noisePopulationThreadPoolExecutor; + private final Executor lightingThreadPoolExecutor; + private final ConcurrentMap> loadingWorldChunks; + private final ConcurrentMap ioWorldChunks; + private final Map loadedWorldChunks; + + private boolean isStopping; + + @SuppressWarnings("ResultOfMethodCallIgnored") + public ServerWorldChunkManager(@NotNull ServerWorld serverWorld, @NotNull ChunkGenerator chunkGenerator, @NotNull NoiseConfig noiseConfig, @NotNull Path worldDirectoryPath, DataFixer dataFixer) { + this.serverWorld = serverWorld; + this.chunkGenerator = chunkGenerator; + this.noiseConfig = noiseConfig; + + var worldDataFile = worldDirectoryPath.resolve("data").toFile(); + worldDataFile.mkdirs(); + this.persistentStateManager = new PersistentStateManager(worldDataFile, dataFixer); + this.pointOfInterestStorage = new PointOfInterestStorage( + worldDirectoryPath.resolve("poi"), dataFixer, false, serverWorld.getRegistryManager(), serverWorld); + this.versionedChunkStorage = new VersionedChunkStorage(worldDirectoryPath.resolve("region"), dataFixer, false); + this.threadPoolExecutor = Executors.newFixedThreadPool( + NoisiumChunkManagerConfig.HANDLER.instance().serverWorldChunkManagerThreads, new ThreadFactoryBuilder().setNameFormat( + "Noisium Server World Chunk Manager " + serverWorld.getDimension().effects() + " %d").build()); + this.noisePopulationThreadPoolExecutor = Executors.newFixedThreadPool( + NoisiumChunkManagerConfig.HANDLER.instance().serverWorldChunkManagerThreads, new ThreadFactoryBuilder().setNameFormat( + "Noisium Server World Chunk Manager Noise Population " + serverWorld.getDimension().effects() + " %d").build()); + this.lightingThreadPoolExecutor = Executors.newFixedThreadPool( + NoisiumChunkManagerConfig.HANDLER.instance().serverWorldChunkManagerLightingThreads, + new ThreadFactoryBuilder().setNameFormat( + "Noisium Server World Chunk Manager Lighting " + serverWorld.getDimension().effects() + " %d").build() + ); + this.loadingWorldChunks = new ConcurrentHashMap<>(); + this.ioWorldChunks = new ConcurrentHashMap<>(); + this.loadedWorldChunks = new HashMap<>(); + + io.github.steveplays28.noisiumchunkmanager.experimental.server.world.chunk.event.ServerChunkEvent.LIGHT_UPDATE.register( + this::onLightUpdateAsync); + io.github.steveplays28.noisiumchunkmanager.experimental.server.world.chunk.event.ServerChunkEvent.BLOCK_CHANGE.register(this::onBlockChange); + TickEvent.SERVER_LEVEL_POST.register(instance -> { + if (!instance.equals(serverWorld) || instance.getPlayers().isEmpty()) { + return; + } + + ((ServerLightingProvider) serverWorld.getLightingProvider()).tick(); + pointOfInterestStorage.tick(() -> true); + }); + LifecycleEvent.SERVER_STOPPING.register(instance -> { + this.isStopping = true; + ((ServerLightingProvider) serverWorld.getLightingProvider()).close(); + for (var loadingWorldChunkCompletableFuture : loadingWorldChunks.values()) { + loadingWorldChunkCompletableFuture.cancel(true); + } + + loadingWorldChunks.clear(); + loadedWorldChunks.clear(); + }); + } + + /** + * Loads the chunk at the specified position, returning the loaded chunk when done. + * Returns the chunk from the {@link ServerWorldChunkManager#loadedWorldChunks} cache if available. + * This method is ran asynchronously. + * + * @param chunkPos The position at which to load the chunk. + * @return The loaded chunk. + */ + public @NotNull CompletableFuture getChunkAsync(ChunkPos chunkPos) { + if (isStopping) { + return CompletableFuture.failedFuture(new IllegalStateException( + String.format("Can't get chunk because %s Server World Chunk Manager is stopping.", MOD_NAME))); + } + + if (loadedWorldChunks.containsKey(chunkPos)) { + return CompletableFuture.completedFuture(loadedWorldChunks.get(chunkPos)); + } else if (loadingWorldChunks.containsKey(chunkPos)) { + return loadingWorldChunks.get(chunkPos); + } + + var worldChunkCompletableFuture = CompletableFuture.supplyAsync(() -> { + var fetchedNbtData = getNbtDataAtChunkPosition(chunkPos); + if (fetchedNbtData == null) { + // TODO: Schedule ProtoChunk worldgen and update loadedWorldChunks incrementally during worldgen steps + return new WorldChunk(serverWorld, generateChunk(chunkPos, this::getIoWorldChunk, ioWorldChunks::remove), null); + } + + versionedChunkStorage.updateChunkNbt( + serverWorld.getRegistryKey(), () -> persistentStateManager, fetchedNbtData, this.chunkGenerator.getCodecKey()); + var fetchedChunk = ChunkSerializer.deserialize(serverWorld, pointOfInterestStorage, chunkPos, fetchedNbtData); + return new WorldChunk(serverWorld, fetchedChunk, + chunkToAddEntitiesTo -> serverWorld.addEntities(EntityType.streamFromNbt(fetchedChunk.getEntities(), serverWorld)) + ); + }, threadPoolExecutor).whenComplete((fetchedWorldChunk, throwable) -> { + if (throwable != null) { + NoisiumChunkManager.LOGGER.error( + "Exception thrown while getting a chunk asynchronously:\n{}", ExceptionUtils.getStackTrace(throwable)); + loadingWorldChunks.remove(chunkPos); + return; + } + + serverWorld.getServer().executeSync(() -> fetchedWorldChunk.addChunkTickSchedulers(serverWorld)); + fetchedWorldChunk.loadEntities(); + loadingWorldChunks.remove(chunkPos); + loadedWorldChunks.put(chunkPos, fetchedWorldChunk); + io.github.steveplays28.noisiumchunkmanager.experimental.server.world.chunk.event.ServerChunkEvent.WORLD_CHUNK_GENERATED.invoker().onWorldChunkGenerated( + fetchedWorldChunk); + }); + loadingWorldChunks.put(chunkPos, worldChunkCompletableFuture); + return worldChunkCompletableFuture; + } + + /** + * Loads the chunk at the specified position, returning the loaded {@link WorldChunk} when done. + * Returns the chunk from the {@link ServerWorldChunkManager#loadedWorldChunks} cache if available. + * WARNING: This method blocks the server thread. Prefer using {@link ServerWorldChunkManager#getChunkAsync} instead. + * + * @param chunkPos The position at which to load the {@link WorldChunk}. + * @return The loaded {@link WorldChunk}. + */ + public @NotNull WorldChunk getChunk(@NotNull ChunkPos chunkPos) { + if (isStopping) { + throw new IllegalStateException(String.format("Can't get chunk because %s Server World Chunk Manager is stopping.", MOD_NAME)); + } + + if (loadedWorldChunks.containsKey(chunkPos)) { + return loadedWorldChunks.get(chunkPos); + } else if (loadingWorldChunks.containsKey(chunkPos)) { + return loadingWorldChunks.get(chunkPos).join(); + } + + var fetchedNbtData = getNbtDataAtChunkPosition(chunkPos); + if (fetchedNbtData == null) { + // TODO: Schedule ProtoChunk worldgen and update loadedWorldChunks incrementally during worldgen steps + var fetchedWorldChunk = new WorldChunk( + serverWorld, generateChunk(chunkPos, this::getIoWorldChunk, ioWorldChunks::remove), null); + loadedWorldChunks.put(chunkPos, fetchedWorldChunk); + io.github.steveplays28.noisiumchunkmanager.experimental.server.world.chunk.event.ServerChunkEvent.WORLD_CHUNK_GENERATED.invoker().onWorldChunkGenerated( + fetchedWorldChunk); + return fetchedWorldChunk; + } + + var fetchedChunk = ChunkSerializer.deserialize(serverWorld, pointOfInterestStorage, chunkPos, fetchedNbtData); + var fetchedWorldChunk = new WorldChunk(serverWorld, fetchedChunk, + chunkToAddEntitiesTo -> serverWorld.addEntities(EntityType.streamFromNbt(fetchedChunk.getEntities(), serverWorld)) + ); + serverWorld.getServer().executeSync(() -> fetchedWorldChunk.addChunkTickSchedulers(serverWorld)); + fetchedWorldChunk.loadEntities(); + loadedWorldChunks.put(chunkPos, fetchedWorldChunk); + io.github.steveplays28.noisiumchunkmanager.experimental.server.world.chunk.event.ServerChunkEvent.WORLD_CHUNK_GENERATED.invoker().onWorldChunkGenerated( + fetchedWorldChunk); + return fetchedWorldChunk; + } + + public @NotNull IoWorldChunk getIoWorldChunk(@NotNull ChunkPos chunkPos) { + if (ioWorldChunks.containsKey(chunkPos)) { + return ioWorldChunks.get(chunkPos); + } + + @NotNull var ioWorldChunk = new IoWorldChunk(serverWorld, chunkPos); + ioWorldChunks.put(chunkPos, ioWorldChunk); + return ioWorldChunk; + } + + /** + * Gets all {@link WorldChunk}s around the specified chunk, using a square radius. + * This method is ran asynchronously. + * + * @param chunkPos The center {@link ChunkPos}. + * @param radius A square radius of chunks. + * @return All the {@link WorldChunk}s around the specified chunk, using a square radius. + */ + public @NotNull Map<@NotNull ChunkPos, @Nullable CompletableFuture> getChunksInRadiusAsync(@NotNull ChunkPos chunkPos, int radius) { + var chunks = new HashMap<@NotNull ChunkPos, @Nullable CompletableFuture>(); + + for (int chunkPosX = chunkPos.x - radius; chunkPosX < chunkPos.x + radius; chunkPosX++) { + for (int chunkPosZ = chunkPos.z - radius; chunkPosZ < chunkPos.z + radius; chunkPosZ++) { + var chunkPosThatShouldBeLoaded = new ChunkPos(chunkPosX, chunkPosZ); + chunks.put(chunkPosThatShouldBeLoaded, getChunkAsync(chunkPosThatShouldBeLoaded)); + } + } + + return chunks; + } + + /** + * Gets all {@link WorldChunk}s around the specified chunk, using a square radius. + * WARNING: This method blocks the server thread. Prefer using {@link ServerWorldChunkManager#getChunksInRadiusAsync(ChunkPos, int)} instead. + * + * @param chunkPos The center {@link ChunkPos}. + * @param radius A square radius of chunks. + * @return All the {@link WorldChunk}s around the specified chunk, using a square radius. + */ + public @NotNull Map<@NotNull ChunkPos, @Nullable WorldChunk> getChunksInRadius(@NotNull ChunkPos chunkPos, int radius) { + var chunks = new HashMap<@NotNull ChunkPos, @Nullable WorldChunk>(); + + for (int chunkPosX = chunkPos.x - radius; chunkPosX < chunkPos.x + radius; chunkPosX++) { + for (int chunkPosZ = chunkPos.z - radius; chunkPosZ < chunkPos.z + radius; chunkPosZ++) { + var chunkPosThatShouldBeLoaded = new ChunkPos(chunkPosX, chunkPosZ); + chunks.put(chunkPosThatShouldBeLoaded, getChunk(chunkPosThatShouldBeLoaded)); + } + } + + return chunks; + } + + public void unloadChunk(@NotNull ChunkPos chunkPosition) { + if (loadingWorldChunks.containsKey(chunkPosition)) { + loadingWorldChunks.get(chunkPosition).whenComplete((chunk, throwable) -> loadedWorldChunks.remove(chunkPosition)); + } + + loadedWorldChunks.remove(chunkPosition); + } + + public boolean isChunkLoaded(ChunkPos chunkPos) { + return this.loadedWorldChunks.containsKey(chunkPos); + } + + public @NotNull NbtScannable getChunkIoWorker() { + return versionedChunkStorage.getWorker(); + } + + public @NotNull PersistentStateManager getPersistentStateManager() { + return persistentStateManager; + } + + // TODO: Move into the ServerLightingProvider + + /** + * Updates the chunk's lighting at the specified {@link ChunkSectionPos}. + * This method is ran asynchronously. + * + * @param lightType The {@link LightType} that should be updated for this {@link WorldChunk}. + * @param chunkSectionPosition The {@link ChunkSectionPos} of the {@link WorldChunk}. + */ + private void onLightUpdateAsync(@NotNull LightType lightType, @NotNull ChunkSectionPos chunkSectionPosition) { + var lightingProvider = serverWorld.getLightingProvider(); + int bottomY = lightingProvider.getBottomY(); + var chunkSectionYPosition = chunkSectionPosition.getSectionY(); + if (chunkSectionYPosition < bottomY || chunkSectionYPosition > lightingProvider.getTopY()) { + return; + } + + var chunkPosition = chunkSectionPosition.toChunkPos(); + getChunkAsync(chunkPosition).whenCompleteAsync((worldChunk, throwable) -> { + var worldChunkExtension = (io.github.steveplays28.noisiumchunkmanager.experimental.extension.world.chunk.WorldChunkExtension) worldChunk; + var skyLightBits = worldChunkExtension.noisiumchunkmanager$getBlockLightBits(); + var blockLightBits = worldChunkExtension.noisiumchunkmanager$getSkyLightBits(); + int chunkSectionYPositionDifference = chunkSectionYPosition - bottomY; + + skyLightBits.clear(); + blockLightBits.clear(); + if (lightType == LightType.SKY) { + skyLightBits.set(chunkSectionYPositionDifference); + } else { + blockLightBits.set(chunkSectionYPositionDifference); + } + ChunkUtil.sendLightUpdateToPlayers(serverWorld.getPlayers(), lightingProvider, chunkPosition, skyLightBits, blockLightBits); + }, lightingThreadPoolExecutor); + } + + // TODO: Check if this can be ran asynchronously + @SuppressWarnings("OptionalIsPresent") + private void onBlockChange(@NotNull BlockPos blockPos, @NotNull BlockState oldBlockState, @NotNull BlockState newBlockState) { + Optional> oldBlockStatePointOfInterestTypeOptional = PointOfInterestTypes.getTypeForState( + oldBlockState); + Optional> newBlockStatePointOfInterestTypeOptional = PointOfInterestTypes.getTypeForState( + newBlockState); + if (oldBlockStatePointOfInterestTypeOptional.equals(newBlockStatePointOfInterestTypeOptional)) { + return; + } + + BlockPos immutableBlockPos = blockPos.toImmutable(); + if (oldBlockStatePointOfInterestTypeOptional.isPresent()) { + pointOfInterestStorage.remove(immutableBlockPos); + // TODO: Add sendPoiRemoval method call into DebugInfoSenderMixin using an event + } + if (newBlockStatePointOfInterestTypeOptional.isPresent()) { + pointOfInterestStorage.add(immutableBlockPos, newBlockStatePointOfInterestTypeOptional.get()); + // TODO: Add sendPoiRemoval method call into DebugInfoSenderMixin using an event + } + } + + private @Nullable NbtCompound getNbtDataAtChunkPosition(ChunkPos chunkPos) { + try { + var fetchedNbtCompoundOptionalFuture = versionedChunkStorage.getNbt(chunkPos).get(); + if (fetchedNbtCompoundOptionalFuture.isPresent()) { + return fetchedNbtCompoundOptionalFuture.get(); + } + } catch (Exception ex) { + NoisiumChunkManager.LOGGER.error("Error occurred while fetching NBT data for chunk at {}", chunkPos); + } + + return null; + } + + // TODO: Move this into the constructor as a Supplier + private @NotNull ProtoChunk generateChunk(@NotNull ChunkPos chunkPos, @NotNull Function ioWorldChunkGetFunction, @NotNull Function ioWorldChunkRemoveFunction) { + var serverLightingProvider = (ServerLightingProvider) serverWorld.getLightingProvider(); + var protoChunk = new ProtoChunk(chunkPos, UpgradeData.NO_UPGRADE_DATA, serverWorld, + serverWorld.getRegistryManager().get(RegistryKeys.BIOME), null + ); + List chunkRegionChunks = List.of(protoChunk); + var chunkRegion = new ChunkRegion(serverWorld, chunkRegionChunks, ChunkStatus.FULL, 1); + var blender = Blender.getBlender(chunkRegion); + var chunkRegionStructureAccessor = serverWorld.getStructureAccessor().forRegion(chunkRegion); + + protoChunk.setStatus(ChunkStatus.STRUCTURE_STARTS); + // TODO: Move the structure placement calculator into NoisiumServerWorldChunkManager + // TODO: Pass the structure template manager into NoisiumServerWorldChunkManager + // TODO: Pass the shouldGenerateStructures boolean into NoisiumServerWorldChunkManager + if (serverWorld.getServer().getSaveProperties().getGeneratorOptions().shouldGenerateStructures()) { + chunkGenerator.setStructureStarts( + serverWorld.getRegistryManager(), serverWorld.getChunkManager().getStructurePlacementCalculator(), + chunkRegionStructureAccessor, protoChunk, serverWorld.getServer().getStructureTemplateManager() + ); + } + serverWorld.cacheStructures(protoChunk); + + protoChunk.setStatus(ChunkStatus.STRUCTURE_REFERENCES); + chunkGenerator.addStructureReferences(chunkRegion, chunkRegionStructureAccessor, protoChunk); + + protoChunk.setStatus(ChunkStatus.BIOMES); + protoChunk.populateBiomes(chunkGenerator.getBiomeSource(), noiseConfig.getMultiNoiseSampler()); + + protoChunk.setStatus(ChunkStatus.NOISE); + protoChunk = (ProtoChunk) ((ChunkGeneratorAccessor) chunkGenerator).invokePopulateNoise( + noisePopulationThreadPoolExecutor, blender, noiseConfig, chunkRegionStructureAccessor, protoChunk).join(); + + protoChunk.setStatus(ChunkStatus.SURFACE); + chunkGenerator.buildSurface(chunkRegion, chunkRegionStructureAccessor, noiseConfig, protoChunk); + + protoChunk.setStatus(ChunkStatus.CARVERS); + chunkGenerator.carve( + chunkRegion, chunkRegion.getSeed(), noiseConfig, chunkRegion.getBiomeAccess(), chunkRegionStructureAccessor, protoChunk, + GenerationStep.Carver.AIR + ); + + protoChunk.setStatus(ChunkStatus.FEATURES); + Heightmap.populateHeightmaps( + protoChunk, + EnumSet.of( + Heightmap.Type.MOTION_BLOCKING, Heightmap.Type.MOTION_BLOCKING_NO_LEAVES, + Heightmap.Type.OCEAN_FLOOR, Heightmap.Type.WORLD_SURFACE + ) + ); + chunkGenerator.generateFeatures(chunkRegion, protoChunk, chunkRegionStructureAccessor); + Blender.tickLeavesAndFluids(chunkRegion, protoChunk); + + @NotNull var ioWorldChunkSectionArray = ioWorldChunkGetFunction.apply(chunkPos).getSectionArray(); + for (int chunkSectionIndex = 0; chunkSectionIndex < ioWorldChunkSectionArray.length; chunkSectionIndex++) { + @NotNull var ioWorldChunkSection = ioWorldChunkSectionArray[chunkSectionIndex]; + if (ioWorldChunkSection.isEmpty()) { + continue; + } + + @NotNull var ioWorldChunkSectionBlockStateContainer = ioWorldChunkSection.getBlockStateContainer(); + ioWorldChunkSectionBlockStateContainer.lock(); + + @NotNull var protoChunkSectionBlockStateContainer = protoChunk.getSectionArray()[chunkSectionIndex].getBlockStateContainer(); + protoChunkSectionBlockStateContainer.lock(); + + @NotNull var protoChunkPalettedContainerData = protoChunkSectionBlockStateContainer.data; + @NotNull var protoChunkPaletteStorage = protoChunkPalettedContainerData.storage(); + @NotNull var ioWorldChunkPalettedContainerData = ioWorldChunkSectionBlockStateContainer.data; + @NotNull var ioWorldChunkPaletteStorage = ioWorldChunkPalettedContainerData.storage(); + var ioWorldChunkPaletteStorageSize = ioWorldChunkPaletteStorage.getSize(); + if (protoChunkPaletteStorage.getData().length == 0) { + protoChunkPaletteStorage = new PackedIntegerArray( + ioWorldChunkPaletteStorage.getElementBits(), ioWorldChunkPaletteStorageSize); + } + + for (int blockIndex = 0; blockIndex < ioWorldChunkPaletteStorageSize; blockIndex++) { + @NotNull var blockState = ioWorldChunkPalettedContainerData.palette().get(ioWorldChunkPaletteStorage.get(blockIndex)); + var blockStatePaletteValue = protoChunkPalettedContainerData.palette.index(blockState); + if (blockState.equals(Blocks.AIR.getDefaultState()) + || blockStatePaletteValue > ((PackedIntegerArrayAccessor) protoChunkPaletteStorage).getMaxValue()) { + continue; + } + + protoChunkPaletteStorage.set(blockIndex, blockStatePaletteValue); + } + + ioWorldChunkSectionBlockStateContainer.unlock(); + protoChunkSectionBlockStateContainer.unlock(); + } + + ioWorldChunkRemoveFunction.apply(chunkPos); + + protoChunk.setStatus(ChunkStatus.INITIALIZE_LIGHT); + protoChunk.refreshSurfaceY(); + serverLightingProvider.initializeLight(protoChunk, protoChunk.isLightOn()); + + protoChunk.setStatus(ChunkStatus.LIGHT); + serverLightingProvider.light(protoChunk, protoChunk.isLightOn()); + + protoChunk.setStatus(ChunkStatus.FULL); + pointOfInterestStorage.saveChunk(chunkPos); + versionedChunkStorage.setNbt(chunkPos, ChunkSerializer.serialize(serverWorld, protoChunk)); + // TODO: Add a (Neo)Forge ChunkDataEvent.Save invoker + // Also add a Fabric/Architectury chunk save event invoker + return protoChunk; + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/chunk/event/ServerChunkEvent.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/chunk/event/ServerChunkEvent.java new file mode 100644 index 0000000..98485fb --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/chunk/event/ServerChunkEvent.java @@ -0,0 +1,60 @@ +package io.github.steveplays28.noisiumchunkmanager.server.world.chunk.event; + +import dev.architectury.event.Event; +import dev.architectury.event.EventFactory; +import net.minecraft.block.BlockState; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkSectionPos; +import net.minecraft.world.LightType; +import net.minecraft.world.chunk.WorldChunk; +import org.jetbrains.annotations.NotNull; + +public interface ServerChunkEvent { + /** + * @see WorldChunkGenerated + */ + Event WORLD_CHUNK_GENERATED = EventFactory.createLoop(); + + /** + * @see WorldChunkGenerated + */ + Event LIGHT_UPDATE = EventFactory.createLoop(); + + /** + * @see WorldChunkGenerated + */ + Event BLOCK_CHANGE = EventFactory.createLoop(); + + @FunctionalInterface + interface WorldChunkGenerated { + /** + * Invoked after a {@link WorldChunk} has been generated by {@link io.github.steveplays28.noisiumchunkmanager.experimental.server.world.ServerWorldChunkManager}. + * + * @param worldChunk The generated {@link WorldChunk}. + */ + void onWorldChunkGenerated(WorldChunk worldChunk); + } + + @FunctionalInterface + interface LightUpdate { + /** + * Invoked before a {@link WorldChunk} has had a light update processed by {@link io.github.steveplays28.noisiumchunkmanager.experimental.server.world.ServerWorldChunkManager}. + * + * @param lightType The {@link LightType} of the {@link WorldChunk}. + * @param chunkSectionPosition The {@link ChunkSectionPos} of the {@link WorldChunk}. + */ + void onLightUpdate(@NotNull LightType lightType, @NotNull ChunkSectionPos chunkSectionPosition); + } + + @FunctionalInterface + interface BlockChange { + /** + * Invoked before a {@link WorldChunk} has had a block change processed by {@link io.github.steveplays28.noisiumchunkmanager.experimental.server.world.ServerWorldChunkManager}. + * + * @param blockPos The {@link BlockPos} where the block change has happened. + * @param oldBlockState The old {@link BlockState} at the {@link BlockPos}. + * @param newBlockState The new {@link BlockState} at the {@link BlockPos}. + */ + void onBlockChange(@NotNull BlockPos blockPos, @NotNull BlockState oldBlockState, @NotNull BlockState newBlockState); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/entity/ServerWorldEntityTracker.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/entity/ServerWorldEntityTracker.java new file mode 100644 index 0000000..ea3623c --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/entity/ServerWorldEntityTracker.java @@ -0,0 +1,80 @@ +package io.github.steveplays28.noisiumchunkmanager.server.world.entity; + +import dev.architectury.event.EventResult; +import dev.architectury.event.events.common.EntityEvent; +import io.github.steveplays28.noisiumchunkmanager.server.world.entity.event.ServerEntityEvent; +import io.github.steveplays28.noisiumchunkmanager.server.world.event.ServerTickEvent; +import net.minecraft.entity.Entity; +import net.minecraft.network.packet.Packet; +import net.minecraft.server.network.EntityTrackerEntry; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.world.World; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + +// TODO: Reimplement the rest of ServerEntityManager and replace it +// TODO: Reimplement vanilla's ServerEntityManager's save method +public class ServerWorldEntityTracker { + private static final @NotNull Logger LOGGER = LoggerFactory.getLogger("Noisium Server World Entity Tracker"); + + private final @NotNull Consumer> packetSendConsumer; + private final @NotNull Map entityTrackerEntries; + + public ServerWorldEntityTracker(@NotNull Consumer> packetSendConsumer) { + this.packetSendConsumer = packetSendConsumer; + + this.entityTrackerEntries = new HashMap<>(); + + EntityEvent.ADD.register(this::onEntityAdded); + ServerEntityEvent.REMOVE.register(this::onEntityRemoved); + ServerTickEvent.SERVER_ENTITY_MOVEMENT_TICK.register(this::onTick); + } + + @SuppressWarnings("ForLoopReplaceableByForEach") + private EventResult onEntityAdded(@NotNull Entity entity, @NotNull World world) { + if (world.isClient()) { + return EventResult.pass(); + } + + var entityType = entity.getType(); + var entityTrackerEntry = new EntityTrackerEntry( + (ServerWorld) world, entity, entityType.getTrackTickInterval(), entityType.alwaysUpdateVelocity(), + packetSendConsumer + ); + entityTrackerEntries.put(entity.getId(), entityTrackerEntry); + + var players = ((ServerWorld) world).getPlayers(); + for (int i = 0; i < players.size(); i++) { + entityTrackerEntry.startTracking(players.get(i)); + } + return EventResult.interruptTrue(); + } + + @SuppressWarnings("ForLoopReplaceableByForEach") + private EventResult onEntityRemoved(@NotNull Entity entity, @NotNull World world) { + var entityId = entity.getId(); + var entityTrackerEntry = entityTrackerEntries.get(entityId); + if (entityTrackerEntry == null) { + LOGGER.error("Tried removing an entity's entity tracker, but it was null. Entity: {}", entity); + return EventResult.interruptDefault(); + } + + var players = ((ServerWorld) world).getPlayers(); + for (int i = 0; i < players.size(); i++) { + entityTrackerEntry.stopTracking(players.get(i)); + } + entityTrackerEntries.remove(entityId); + return EventResult.interruptDefault(); + } + + private void onTick() { + for (var entityTrackerEntry : entityTrackerEntries.values()) { + entityTrackerEntry.tick(); + } + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/entity/event/ServerEntityEvent.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/entity/event/ServerEntityEvent.java new file mode 100644 index 0000000..c615015 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/entity/event/ServerEntityEvent.java @@ -0,0 +1,23 @@ +package io.github.steveplays28.noisiumchunkmanager.server.world.entity.event; + +import dev.architectury.event.Event; +import dev.architectury.event.EventFactory; +import dev.architectury.event.EventResult; +import net.minecraft.entity.Entity; +import net.minecraft.world.World; +import org.jetbrains.annotations.NotNull; + +public interface ServerEntityEvent { + /** + * @see Remove + */ + @NotNull Event REMOVE = EventFactory.createEventResult(); + + @FunctionalInterface + interface Remove { + /** + * Invoked when the server is about to remove an entity. + */ + @NotNull EventResult onServerEntityRemove(@NotNull Entity entity, @NotNull World world); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/entity/player/ServerWorldPlayerChunkLoader.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/entity/player/ServerWorldPlayerChunkLoader.java new file mode 100644 index 0000000..3d50e07 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/entity/player/ServerWorldPlayerChunkLoader.java @@ -0,0 +1,137 @@ +package io.github.steveplays28.noisiumchunkmanager.server.world.entity.player; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import dev.architectury.event.events.common.PlayerEvent; +import dev.architectury.event.events.common.TickEvent; +import io.github.steveplays28.noisiumchunkmanager.util.world.chunk.ChunkUtil; +import net.minecraft.network.packet.s2c.play.ChunkRenderDistanceCenterS2CPacket; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.util.math.ChunkSectionPos; +import net.minecraft.util.math.Vec3d; +import net.minecraft.world.chunk.WorldChunk; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +public class ServerWorldPlayerChunkLoader { + private final @NotNull ServerWorld serverWorld; + private final @NotNull Function> worldChunkLoadFunction; + private final @NotNull Consumer worldChunkUnloadConsumer; + private final @NotNull Supplier serverViewDistanceSupplier; + + private final @NotNull Executor threadPoolExecutor; + private final @NotNull Map previousPlayerPositions; + + public ServerWorldPlayerChunkLoader( + @NotNull ServerWorld serverWorld, + @NotNull BiFunction>> worldChunksInRadiusLoadFunction, + @NotNull Function> worldChunkLoadFunction, + @NotNull Consumer worldChunkUnloadConsumer, + @NotNull Supplier serverViewDistanceSupplier + ) { + this.serverWorld = serverWorld; + this.worldChunkLoadFunction = worldChunkLoadFunction; + this.worldChunkUnloadConsumer = worldChunkUnloadConsumer; + this.serverViewDistanceSupplier = serverViewDistanceSupplier; + + this.threadPoolExecutor = Executors.newFixedThreadPool( + 1, new ThreadFactoryBuilder().setNameFormat("Noisium Server Player Chunk Loader %d").build()); + this.previousPlayerPositions = new HashMap<>(); + + PlayerEvent.PLAYER_JOIN.register(player -> { + if (!player.getServerWorld().equals(serverWorld)) { + return; + } + + @NotNull var playerBlockPosition = player.getBlockPos(); + // Send new render distance center to the player asynchronously + CompletableFuture.runAsync(() -> player.networkHandler.sendPacket( + new ChunkRenderDistanceCenterS2CPacket( + ChunkSectionPos.getSectionCoord(playerBlockPosition.getX()), + ChunkSectionPos.getSectionCoord(playerBlockPosition.getZ()) + )), threadPoolExecutor); + // Send chunks around the player to the player asynchronously + ChunkUtil.sendWorldChunksToPlayerAsync( + serverWorld, + new ArrayList<>(worldChunksInRadiusLoadFunction.apply(player.getChunkPos(), serverViewDistanceSupplier.get()).values()), + threadPoolExecutor + ); + previousPlayerPositions.put(player.getId(), player.getPos()); + }); + PlayerEvent.PLAYER_QUIT.register(player -> previousPlayerPositions.remove(player.getId())); + TickEvent.SERVER_LEVEL_POST.register(instance -> { + if (!instance.equals(serverWorld)) { + return; + } + + tick(); + }); + } + + // TODO: Enable ticking/update chunk tracking in ServerEntityManager + @SuppressWarnings("ForLoopReplaceableByForEach") + private void tick() { + @NotNull var players = serverWorld.getPlayers(); + if (players.isEmpty() || previousPlayerPositions.isEmpty()) { + return; + } + + for (int i = 0; i < players.size(); i++) { + @NotNull var player = players.get(i); + @NotNull var playerBlockPos = player.getBlockPos(); + @Nullable var previousPlayerPos = previousPlayerPositions.get(player.getId()); + if (previousPlayerPos == null || playerBlockPos.isWithinDistance(previousPlayerPos, 16d)) { + continue; + } + + // Send world chunks that should be loaded to the player asynchronously + @NotNull var previousPlayerChunkPositionsInServerViewDistance = ChunkUtil.getChunkPositionsAtPositionInRadius( + new ChunkPos( + new BlockPos( + Math.round((float) previousPlayerPos.getX()), + Math.round((float) previousPlayerPos.getY()), + Math.round((float) previousPlayerPos.getZ()) + ) + ), serverViewDistanceSupplier.get() + ); + @NotNull var playerChunkPositionsInServerViewDistance = ChunkUtil.getChunkPositionsAtPositionInRadius( + player.getChunkPos(), serverViewDistanceSupplier.get()); + @NotNull final var chunkPositionsToLoad = ChunkUtil.getChunkPositionDifferences( + playerChunkPositionsInServerViewDistance, previousPlayerChunkPositionsInServerViewDistance); + for (int chunkPositionsToLoadIndex = 0; chunkPositionsToLoadIndex < chunkPositionsToLoad.size(); chunkPositionsToLoadIndex++) { + ChunkUtil.sendWorldChunkToPlayerAsync( + serverWorld, worldChunkLoadFunction.apply(chunkPositionsToLoad.get(chunkPositionsToLoadIndex)), threadPoolExecutor); + } + + // Send new render distance center to the player asynchronously + CompletableFuture.runAsync(() -> player.networkHandler.sendPacket( + new ChunkRenderDistanceCenterS2CPacket( + ChunkSectionPos.getSectionCoord(playerBlockPos.getX()), + ChunkSectionPos.getSectionCoord(playerBlockPos.getZ()) + )), threadPoolExecutor); + + // Unload world chunks that aren't required anymore asynchronously + // TODO: Check if other players are still in range of these chunks + // Unload chunks at the end of the players fori loop instead + @NotNull final var chunkPositionsToUnload = ChunkUtil.getChunkPositionDifferences( + previousPlayerChunkPositionsInServerViewDistance, playerChunkPositionsInServerViewDistance); + for (int chunkPositionsToUnloadIndex = 0; chunkPositionsToUnloadIndex < chunkPositionsToUnload.size(); chunkPositionsToUnloadIndex++) { + worldChunkUnloadConsumer.accept(chunkPositionsToUnload.get(chunkPositionsToUnloadIndex)); + } + + previousPlayerPositions.put(player.getId(), player.getPos()); + } + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/event/ServerTickEvent.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/event/ServerTickEvent.java new file mode 100644 index 0000000..2cbcd06 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/server/world/event/ServerTickEvent.java @@ -0,0 +1,19 @@ +package io.github.steveplays28.noisiumchunkmanager.server.world.event; + +import dev.architectury.event.Event; +import dev.architectury.event.EventFactory; + +public interface ServerTickEvent { + /** + * @see ServerEntityMovementTick + */ + Event SERVER_ENTITY_MOVEMENT_TICK = EventFactory.createLoop(); + + @FunctionalInterface + interface ServerEntityMovementTick { + /** + * Invoked before the server starts processing entity movement ticks. + */ + void onServerEntityMovementTick(); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/ModLoaderUtil.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/ModLoaderUtil.java new file mode 100644 index 0000000..0eca59b --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/ModLoaderUtil.java @@ -0,0 +1,25 @@ +package io.github.steveplays28.noisiumchunkmanager.util; + +import dev.architectury.injectables.annotations.ExpectPlatform; +import org.jetbrains.annotations.NotNull; + +import java.nio.file.Path; + +@SuppressWarnings("unused") +public abstract class ModLoaderUtil { + /** + * Checks if a mod is present during loading. + */ + @ExpectPlatform + public static boolean isModPresent(String id) { + throw new AssertionError("Platform implementation expected."); + } + + /** + * @return The config directory of the mod loader. + */ + @ExpectPlatform + public static @NotNull Path getConfigDir() { + throw new AssertionError("Platform implementation expected."); + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/world/chunk/ChunkUtil.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/world/chunk/ChunkUtil.java new file mode 100644 index 0000000..bc1b9ca --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/world/chunk/ChunkUtil.java @@ -0,0 +1,143 @@ +package io.github.steveplays28.noisiumchunkmanager.util.world.chunk; + +import io.github.steveplays28.noisiumchunkmanager.NoisiumChunkManager; +import net.minecraft.block.BlockState; +import net.minecraft.network.packet.s2c.play.BlockUpdateS2CPacket; +import net.minecraft.network.packet.s2c.play.ChunkDataS2CPacket; +import net.minecraft.network.packet.s2c.play.LightUpdateS2CPacket; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.crash.CrashException; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.world.chunk.WorldChunk; +import net.minecraft.world.chunk.light.LightingProvider; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.BitSet; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; + +public class ChunkUtil { + /** + * Sends a {@link WorldChunk} to all players in the specified world. + * WARNING: This method blocks the server thread. Prefer using {@link ChunkUtil#sendWorldChunkToPlayerAsync(ServerWorld, CompletableFuture, Executor)} instead. + * + * @param serverWorld The world the {@link WorldChunk} resides in. + * @param worldChunk The {@link WorldChunk}. + */ + public static void sendWorldChunkToPlayer(@NotNull ServerWorld serverWorld, @NotNull WorldChunk worldChunk) { + try { + var chunkDataS2CPacket = new ChunkDataS2CPacket(worldChunk, serverWorld.getLightingProvider(), null, null); + for (int i = 0; i < serverWorld.getPlayers().size(); i++) { + serverWorld.getPlayers().get(i).sendChunkPacket(worldChunk.getPos(), chunkDataS2CPacket); + } + } catch (CrashException e) { + NoisiumChunkManager.LOGGER.error( + "Exception thrown while trying to send a chunk packet to all players in a server world:\n{}", + ExceptionUtils.getStackTrace(e) + ); + } + } + + /** + * Sends a {@link WorldChunk} to all players in the specified world. + * This method is ran asynchronously. + * + * @param serverWorld The world the {@link WorldChunk} resides in. + * @param worldChunkFuture The {@link CompletableFuture}. + */ + public static void sendWorldChunkToPlayerAsync(@NotNull ServerWorld serverWorld, @NotNull CompletableFuture worldChunkFuture, @NotNull Executor executor) { + worldChunkFuture.whenCompleteAsync((worldChunk, throwable) -> sendWorldChunkToPlayer(serverWorld, worldChunk), executor); + } + + /** + * Sends a {@link List} of {@link WorldChunk}s to all players in the specified world. + * WARNING: This method blocks the server thread. Prefer using {@link ChunkUtil#sendWorldChunksToPlayerAsync(ServerWorld, List, Executor)} instead. + * + * @param serverWorld The world the {@link WorldChunk} resides in. + * @param worldChunks The {@link List} of {@link WorldChunk}s. + */ + @SuppressWarnings("ForLoopReplaceableByForEach") + public static void sendWorldChunksToPlayer(@NotNull ServerWorld serverWorld, @NotNull List worldChunks) { + // TODO: Send a whole batch of chunks to the player at once to save on network traffic + for (int i = 0; i < worldChunks.size(); i++) { + sendWorldChunkToPlayer(serverWorld, worldChunks.get(i)); + } + } + + /** + * Sends a {@link List} of {@link CompletableFuture}s to all players in the specified world. + * This method is ran asynchronously. + * + * @param serverWorld The world the {@link WorldChunk} resides in. + * @param worldChunkFutures The {@link List} of {@link CompletableFuture}s + */ + @SuppressWarnings("ForLoopReplaceableByForEach") + public static void sendWorldChunksToPlayerAsync(@NotNull ServerWorld serverWorld, @NotNull List> worldChunkFutures, @NotNull Executor executor) { + // TODO: Send a whole batch of chunks to the player at once to save on network traffic + for (int i = 0; i < worldChunkFutures.size(); i++) { + worldChunkFutures.get(i).whenCompleteAsync( + (worldChunk, throwable) -> sendWorldChunkToPlayer(serverWorld, worldChunk), executor); + } + } + + /** + * Sends a light update to a {@link List} of players. + * + * @param players The {@link List} of players. + * @param lightingProvider The {@link LightingProvider} of the world. + * @param chunkPos The {@link ChunkPos} at which the light update happened. + * @param skyLightBits The skylight {@link BitSet}. + * @param blockLightBits The blocklight {@link BitSet}. + */ + @SuppressWarnings("ForLoopReplaceableByForEach") + public static void sendLightUpdateToPlayers(@NotNull List players, @NotNull LightingProvider lightingProvider, @NotNull ChunkPos chunkPos, @NotNull BitSet skyLightBits, @NotNull BitSet blockLightBits) { + for (int i = 0; i < players.size(); i++) { + players.get(i).networkHandler.sendPacket(new LightUpdateS2CPacket(chunkPos, lightingProvider, skyLightBits, blockLightBits)); + } + } + + /** + * Sends a block update to a {@link List} of players. + * + * @param players The {@link List} of players. + * @param blockPos The {@link BlockPos} of the block update that should be sent to the {@link List} of players. + * @param blockState The {@link BlockState} at the specified {@link BlockPos} of the block update that should be sent to the {@link List} of players. + */ + @SuppressWarnings("ForLoopReplaceableByForEach") + public static void sendBlockUpdateToPlayers(@NotNull List players, @NotNull BlockPos blockPos, @NotNull BlockState blockState) { + for (int i = 0; i < players.size(); i++) { + players.get(i).networkHandler.sendPacket(new BlockUpdateS2CPacket(blockPos, blockState)); + } + } + + public static @NotNull List getChunkPositionsAtPositionInRadius(@NotNull ChunkPos chunkPosition, int radius) { + @NotNull final List chunkPositions = new ArrayList<>(); + for (int chunkPositionX = chunkPosition.x - radius; chunkPositionX < chunkPosition.x + radius; chunkPositionX++) { + for (int chunkPositionZ = chunkPosition.z - radius; chunkPositionZ < chunkPosition.z + radius; chunkPositionZ++) { + chunkPositions.add(new ChunkPos(chunkPositionX, chunkPositionZ)); + } + } + + return chunkPositions; + } + + /** + * @param chunkPositions A {@link List} of {@link ChunkPos}s. + * @param otherChunkPositions Another {@link List} of {@link ChunkPos}s. + * @return The {@link ChunkPos}s that are in {@code chunkPositions}, but not in {@code otherChunkPositions}. + */ + @SuppressWarnings("ForLoopReplaceableByForEach") + public static @NotNull List getChunkPositionDifferences(@NotNull List chunkPositions, @NotNull List otherChunkPositions) { + @NotNull final List chunkPositionDifferences = new ArrayList<>(chunkPositions); + for (int i = 0; i < otherChunkPositions.size(); i++) { + chunkPositionDifferences.remove(otherChunkPositions.get(i)); + } + + return chunkPositionDifferences; + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/world/chunk/networking/packet/PacketUtil.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/world/chunk/networking/packet/PacketUtil.java new file mode 100644 index 0000000..fbdcce5 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/world/chunk/networking/packet/PacketUtil.java @@ -0,0 +1,22 @@ +package io.github.steveplays28.noisiumchunkmanager.util.world.chunk.networking.packet; + +import net.minecraft.network.packet.Packet; +import net.minecraft.server.network.ServerPlayerEntity; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public class PacketUtil { + /** + * Sends a packet to a {@link List} of players. + * + * @param players The {@link List} of players. + * @param packet The {@link Packet} that should be sent to the {@link List} of players. + */ + @SuppressWarnings("ForLoopReplaceableByForEach") + public static void sendPacketToPlayers(@NotNull List players, @NotNull Packet packet) { + for (int i = 0; i < players.size(); i++) { + players.get(i).networkHandler.sendPacket(packet); + } + } +} diff --git a/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/world/chunk/IoWorldChunk.java b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/world/chunk/IoWorldChunk.java new file mode 100644 index 0000000..09349c6 --- /dev/null +++ b/common/src/main/java/io/github/steveplays28/noisiumchunkmanager/world/chunk/IoWorldChunk.java @@ -0,0 +1,44 @@ +package io.github.steveplays28.noisiumchunkmanager.experimental.world.chunk; + +import net.minecraft.block.Block; +import net.minecraft.fluid.Fluid; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; +import net.minecraft.world.World; +import net.minecraft.world.chunk.WorldChunk; +import net.minecraft.world.tick.BasicTickScheduler; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * A {@link ServerWorld} {@link WorldChunk} with disk (IO) access. + */ +// TODO: Add disk (IO) access +public class IoWorldChunk extends WorldChunk { + public IoWorldChunk(@NotNull World world, @NotNull ChunkPos chunkPosition) { + super(world, chunkPosition); + } + + @Override + public @Nullable BasicTickScheduler getBlockTickScheduler() { + return null; + } + + @Override + public @Nullable BasicTickScheduler getFluidTickScheduler() { + return null; + } + + @Override + public @Nullable TickSchedulers getTickSchedulers() { + return null; + } + + @Override + public @NotNull NbtCompound getPackedBlockEntityNbt(@NotNull BlockPos blockPosition) { + @Nullable var packedBlockEntityNbt = super.getPackedBlockEntityNbt(blockPosition); + return packedBlockEntityNbt == null ? new NbtCompound() : packedBlockEntityNbt; + } +} diff --git a/common/src/main/resources/architectury.common.json b/common/src/main/resources/architectury.common.json new file mode 100644 index 0000000..d1f13c9 --- /dev/null +++ b/common/src/main/resources/architectury.common.json @@ -0,0 +1,3 @@ +{ + "accessWidener": "noisium.accesswidener" +} diff --git a/common/src/main/resources/assets/noisiumchunkmanager/icon.png b/common/src/main/resources/assets/noisiumchunkmanager/icon.png new file mode 100644 index 0000000..f54c693 Binary files /dev/null and b/common/src/main/resources/assets/noisiumchunkmanager/icon.png differ diff --git a/common/src/main/resources/assets/noisiumchunkmanager/lang/en_us.json b/common/src/main/resources/assets/noisiumchunkmanager/lang/en_us.json new file mode 100644 index 0000000..320e73f --- /dev/null +++ b/common/src/main/resources/assets/noisiumchunkmanager/lang/en_us.json @@ -0,0 +1,7 @@ +{ + "yacl3.config.noisium:config.category.server": "Server", + "yacl3.config.noisium:config.category.server.group.serverWorldChunkManager": "Server World Chunk Manager (experimental)", + "yacl3.config.noisium:config.serverWorldChunkManagerEnabled": "Server World Chunk Manager", + "yacl3.config.noisium:config.serverWorldChunkManagerThreads": "Server World Chunk Manager Threads", + "yacl3.config.noisium:config.serverWorldChunkManagerLightingThreads": "Server World Chunk Manager Lighting Threads" +} diff --git a/common/src/main/resources/noisiumchunkmanager-common.mixins.json b/common/src/main/resources/noisiumchunkmanager-common.mixins.json new file mode 100644 index 0000000..a8c59a6 --- /dev/null +++ b/common/src/main/resources/noisiumchunkmanager-common.mixins.json @@ -0,0 +1,36 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "io.github.steveplays28.noisiumchunkmanager.mixin", + "compatibilityLevel": "JAVA_17", + "plugin": "io.github.steveplays28.noisiumchunkmanager.mixin.NoisiumChunkManagerMixinPlugin", + "mixins": [ + "accessor.server.network.SpawnLocatingAccessor", + "accessor.util.collection.PackedIntegerArrayAccessor", + "accessor.world.gen.chunk.ChunkGeneratorAccessor", + "block.LichenGrowerGrowCheckerMixin", + "compat.distanthorizons.common.wrappers.world.gen.DHBatchGenerationEnvironmentMixin", + "server.MinecraftServerMixin", + "server.network.ServerPlayerEntityMixin", + "server.network.SpawnLocatingMixin", + "server.world.ServerChunkManagerMixin", + "server.world.ServerEntityManagerMixin", + "server.world.ServerWorldMixin", + "server.world.ThreadedAnvilChunkStorageMixin", + "world.ChunkRegionMixin", + "world.ChunkSectionCacheMixin", + "world.WorldMixin", + "world.chunk.PalettedContainerMixin", + "world.chunk.WorldChunkMixin", + "world.gen.chunk.ChunkGeneratorMixin", + "world.gen.chunk.NoiseChunkGeneratorMixin", + "world.gen.feature.OreFeatureMixin", + "world.storage.SerializingRegionBasedStorageMixin" + ], + "client": [ + "client.gui.hud.DebugHudMixin" + ], + "injectors": { + "defaultRequire": 1 + } +} diff --git a/common/src/main/resources/noisiumchunkmanager.accesswidener b/common/src/main/resources/noisiumchunkmanager.accesswidener new file mode 100644 index 0000000..95f7370 --- /dev/null +++ b/common/src/main/resources/noisiumchunkmanager.accesswidener @@ -0,0 +1,12 @@ +accessWidener v2 named + +accessible field net/minecraft/world/chunk/ChunkSection blockStateContainer Lnet/minecraft/world/chunk/PalettedContainer; +accessible field net/minecraft/world/chunk/ChunkSection nonEmptyBlockCount S +accessible field net/minecraft/world/chunk/ChunkSection nonEmptyFluidCount S +accessible field net/minecraft/world/chunk/ChunkSection randomTickableBlockCount S + +accessible field net/minecraft/world/chunk/PalettedContainer data Lnet/minecraft/world/chunk/PalettedContainer$Data; +accessible field net/minecraft/world/chunk/PalettedContainer paletteProvider Lnet/minecraft/world/chunk/PalettedContainer$PaletteProvider; + +accessible class net/minecraft/world/chunk/PalettedContainer$Data +accessible field net/minecraft/world/chunk/PalettedContainer$Data palette Lnet/minecraft/world/chunk/Palette; diff --git a/docs/NoiseChunkGenerator_populateNoise_optimisation.md b/docs/NoiseChunkGenerator_populateNoise_optimisation.md new file mode 100644 index 0000000..e6e27c2 --- /dev/null +++ b/docs/NoiseChunkGenerator_populateNoise_optimisation.md @@ -0,0 +1,110 @@ +# NoiseChunkGenerator#populateNoise optimisations + +This is what Noisium's code does, after the `@Redirect` mixin is applied. This provides a 20-30% speedup in `NoiseChunkGenerator#populateNoise`. +This is also a completely mapped version of `NoiseChunkGenerator#populateNoise` (including local variables), for future reference. + +```java +private Chunk populateNoise(Blender blender, StructureAccessor structureAccessor, NoiseConfig noiseConfig, Chunk chunk, int minimumCellY, int cellHeight) { + final ChunkNoiseSampler chunkNoiseSampler = chunk.getOrCreateChunkNoiseSampler( + chunk2 -> ((NoiseChunkGenerator) (Object) this).createChunkNoiseSampler(chunk2, structureAccessor, blender, noiseConfig)); + final Heightmap oceanFloorHeightMap = chunk.getHeightmap(Heightmap.Type.OCEAN_FLOOR_WG); + final Heightmap worldSurfaceHeightMap = chunk.getHeightmap(Heightmap.Type.WORLD_SURFACE_WG); + final ChunkPos chunkPos = chunk.getPos(); + final int chunkPosStartX = chunkPos.getStartX(); + final int chunkPosStartZ = chunkPos.getStartZ(); + final var aquiferSampler = chunkNoiseSampler.getAquiferSampler(); + + chunkNoiseSampler.sampleStartDensity(); + + final int horizontalCellBlockCount = chunkNoiseSampler.getHorizontalCellBlockCount(); + final int verticalCellBlockCount = chunkNoiseSampler.getVerticalCellBlockCount(); + final int horizontalCellCount = 16 / horizontalCellBlockCount; + final var mutableBlockPos = new BlockPos.Mutable(); + + for (int baseHorizontalWidthCellIndex = 0; baseHorizontalWidthCellIndex < horizontalCellCount; ++baseHorizontalWidthCellIndex) { + chunkNoiseSampler.sampleEndDensity(baseHorizontalWidthCellIndex); + + for (int baseHorizontalLengthCellIndex = 0; baseHorizontalLengthCellIndex < horizontalCellCount; ++baseHorizontalLengthCellIndex) { + var nextChunkSectionIndex = chunk.countVerticalSections() - 1; + var chunkSection = chunk.getSection(nextChunkSectionIndex); + + for (int verticalCellHeightIndex = cellHeight - 1; verticalCellHeightIndex >= 0; --verticalCellHeightIndex) { + chunkNoiseSampler.onSampledCellCorners(verticalCellHeightIndex, baseHorizontalLengthCellIndex); + + for (int verticalCellBlockIndex = verticalCellBlockCount - 1; verticalCellBlockIndex >= 0; --verticalCellBlockIndex) { + int blockPosY = (minimumCellY + verticalCellHeightIndex) * verticalCellBlockCount + verticalCellBlockIndex; + int chunkSectionBlockPosY = blockPosY & 0xF; + int chunkSectionIndex = chunk.getSectionIndex(blockPosY); + + if (nextChunkSectionIndex != chunkSectionIndex) { + nextChunkSectionIndex = chunkSectionIndex; + chunkSection = chunk.getSection(chunkSectionIndex); + } + + double deltaY = (double) verticalCellBlockIndex / verticalCellBlockCount; + chunkNoiseSampler.interpolateY(blockPosY, deltaY); + + for (int horizontalWidthCellBlockIndex = 0; horizontalWidthCellBlockIndex < horizontalCellBlockCount; ++horizontalWidthCellBlockIndex) { + int blockPosX = chunkPosStartX + baseHorizontalWidthCellIndex * horizontalCellBlockCount + horizontalWidthCellBlockIndex; + int chunkSectionBlockPosX = blockPosX & 0xF; + double deltaX = (double) horizontalWidthCellBlockIndex / horizontalCellBlockCount; + + chunkNoiseSampler.interpolateX(blockPosX, deltaX); + + for (int horizontalLengthCellBlockIndex = 0; horizontalLengthCellBlockIndex < horizontalCellBlockCount; ++horizontalLengthCellBlockIndex) { + int blockPosZ = chunkPosStartZ + baseHorizontalLengthCellIndex * horizontalCellBlockCount + horizontalLengthCellBlockIndex; + int chunkSectionBlockPosZ = blockPosZ & 0xF; + double deltaZ = (double) horizontalLengthCellBlockIndex / horizontalCellBlockCount; + + chunkNoiseSampler.interpolateZ(blockPosZ, deltaZ); + BlockState blockState = chunkNoiseSampler.sampleBlockState(); + + if (blockState == null) { + blockState = ((NoiseChunkGenerator) (Object) this).settings.value().defaultBlock(); + } + + if (blockState == NoiseChunkGenerator.AIR || SharedConstants.isOutsideGenerationArea(chunk.getPos())) { + continue; + } + + // Update the non empty block count to avoid issues with MC's lighting engine and other systems not recognising the direct palette storage set + // See ChunkSection#setBlockState + chunkSection.nonEmptyBlockCount += 1; + + if (!blockState.getFluidState().isEmpty()) { + chunkSection.nonEmptyFluidCount += 1; + } + + if (blockState.hasRandomTicks()) { + chunkSection.randomTickableBlockCount += 1; + } + + // Set the blockstate in the palette storage directly to improve performance + var blockStateId = chunkSection.blockStateContainer.data.palette.index(blockState); + chunkSection.blockStateContainer.data.storage().set( + chunkSection.blockStateContainer.paletteProvider.computeIndex(chunkSectionBlockPosX, + chunkSectionBlockPosY, chunkSectionBlockPosZ + ), blockStateId); + + oceanFloorHeightMap.trackUpdate(chunkSectionBlockPosX, blockPosY, chunkSectionBlockPosZ, blockState); + worldSurfaceHeightMap.trackUpdate(chunkSectionBlockPosX, blockPosY, chunkSectionBlockPosZ, blockState); + + if (!aquiferSampler.needsFluidTick() || blockState.getFluidState().isEmpty()) { + continue; + } + + mutableBlockPos.set(blockPosX, blockPosY, blockPosZ); + chunk.markBlockForPostProcessing(mutableBlockPos); + } + } + } + } + } + + chunkNoiseSampler.swapBuffers(); + } + + chunkNoiseSampler.stopInterpolation(); + return chunk; +} +``` diff --git a/docs/assets/badges/compact/supported/neoforge_vector.svg b/docs/assets/badges/compact/supported/neoforge_vector.svg new file mode 100644 index 0000000..e960ec5 --- /dev/null +++ b/docs/assets/badges/compact/supported/neoforge_vector.svg @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/assets/banner/banner.xcf b/docs/assets/banner/banner.xcf new file mode 100644 index 0000000..ec9e3b3 Binary files /dev/null and b/docs/assets/banner/banner.xcf differ diff --git a/docs/assets/banner/banner_1088x612.png b/docs/assets/banner/banner_1088x612.png new file mode 100644 index 0000000..a886614 Binary files /dev/null and b/docs/assets/banner/banner_1088x612.png differ diff --git a/docs/assets/banner/banner_1920x1080.png b/docs/assets/banner/banner_1920x1080.png new file mode 100644 index 0000000..21dd23f Binary files /dev/null and b/docs/assets/banner/banner_1920x1080.png differ diff --git a/docs/assets/banner/banner_vibrant_1920x1080.png b/docs/assets/banner/banner_vibrant_1920x1080.png new file mode 100644 index 0000000..c20c7b4 Binary files /dev/null and b/docs/assets/banner/banner_vibrant_1920x1080.png differ diff --git a/docs/assets/banner/banner_without_author_text_1920x1080.png b/docs/assets/banner/banner_without_author_text_1920x1080.png new file mode 100644 index 0000000..17440f4 Binary files /dev/null and b/docs/assets/banner/banner_without_author_text_1920x1080.png differ diff --git a/docs/assets/icon/icon.xcf b/docs/assets/icon/icon.xcf new file mode 100644 index 0000000..6bac25a Binary files /dev/null and b/docs/assets/icon/icon.xcf differ diff --git a/docs/assets/icon/icon_1080x1080.png b/docs/assets/icon/icon_1080x1080.png new file mode 100644 index 0000000..2204acc Binary files /dev/null and b/docs/assets/icon/icon_1080x1080.png differ diff --git a/docs/assets/icon/icon_128x128.png b/docs/assets/icon/icon_128x128.png new file mode 100644 index 0000000..f54c693 Binary files /dev/null and b/docs/assets/icon/icon_128x128.png differ diff --git a/docs/assets/icon/icon_vibrant_1080x1080.png b/docs/assets/icon/icon_vibrant_1080x1080.png new file mode 100644 index 0000000..4a128e9 Binary files /dev/null and b/docs/assets/icon/icon_vibrant_1080x1080.png differ diff --git a/fabric/build.gradle b/fabric/build.gradle new file mode 100644 index 0000000..b294829 --- /dev/null +++ b/fabric/build.gradle @@ -0,0 +1,120 @@ +//file:noinspection GroovyAccessibility +//file:noinspection GroovyAssignabilityCheck + +plugins { + id "com.github.johnrengelman.shadow" version "${shadow_plugin_version}" +} + +def archivesNameFabric = "${rootProject.archives_base_name}-fabric" + +architectury { + platformSetupLoomIde() + fabric() +} + +base { + archivesName = archivesNameFabric +} + +loom { + accessWidenerPath = project(":common").loom.accessWidenerPath +} + +configurations { + common + shadowCommon // Don't use shadow from the shadow plugin since it *excludes* files. + compileClasspath.extendsFrom common + runtimeClasspath.extendsFrom common + developmentFabric.extendsFrom common +} + +dependencies { + modImplementation "net.fabricmc:fabric-loader:${rootProject.fabric_loader_version}" + + // Mixin Extras + include(implementation(annotationProcessor("io.github.llamalad7:mixinextras-fabric:${project.mixin_extras_version}"))) + + // Architectury API + modRuntimeOnly("dev.architectury:architectury-fabric:${rootProject.architectury_api_version}") { exclude group: 'net.fabricmc', module: 'fabric-loader' } + + // Fabric API + modImplementation "net.fabricmc.fabric-api:fabric-api:${rootProject.fabric_api_version}" + + // YetAnotherConfigLib + modRuntimeOnly("dev.isxander:yet-another-config-lib:${rootProject.yet_another_config_lib_version}-fabric") + + // Mod Menu + modRuntimeOnly "maven.modrinth:modmenu:${rootProject.mod_menu_version}" + + common(project(path: ":common", configuration: "namedElements")) { transitive false } + shadowCommon(project(path: ":common", configuration: "transformProductionFabric")) { transitive false } +} + +processResources { + inputs.property "version", project.version + + from(project(":common").sourceSets["main"].resources) { + include("assets", "data", "resourcepacks") + } + + filesMatching("fabric.mod.json") { + expand "version": project.version, + "mod_id": rootProject.mod_id, + "mod_namespace": rootProject.mod_namespace, + "mod_name": rootProject.mod_name, + "mod_description": rootProject.mod_description, + "mod_license": rootProject.mod_license, + "curseforge_project_id": rootProject.curseforge_project_id, + "modrinth_project_id": rootProject.modrinth_project_id, + "fabric_loader_version": rootProject.fabric_loader_version, + "supported_minecraft_version": rootProject.supported_minecraft_version, + "architectury_api_version": rootProject.architectury_api_version, + "yet_another_config_lib_version": rootProject.yet_another_config_lib_version + } +} + +shadowJar { + exclude "architectury.common.json" + + configurations = [project.configurations.shadowCommon] + archiveClassifier = "dev-shadow" +} + +remapJar { + injectAccessWidener = true + inputFile.set shadowJar.archiveFile + dependsOn shadowJar +} + +sourcesJar { + def commonSources = project(":common").sourcesJar + dependsOn commonSources + from commonSources.archiveFile.map { zipTree(it) } +} + +components.java { + withVariantsFromConfiguration(project.configurations.shadowRuntimeElements) { + skip() + } +} + +publishing { + publications { + mavenJava(MavenPublication) { + groupId = rootProject.maven_group + artifactId = archivesNameFabric + from components.java + } + } + + repositories { + maven { + name = "GitHubPackages" + url = uri("https://maven.pkg.github.com/Steveplays28/${rootProject.mod_id}") + credentials { + username = System.getenv("GITHUB_ACTOR") + password = System.getenv("GITHUB_TOKEN") + } + } + } +} diff --git a/fabric/src/main/java/io/github/steveplays28/noisiumchunkmanager/fabric/NoisiumFabric.java b/fabric/src/main/java/io/github/steveplays28/noisiumchunkmanager/fabric/NoisiumFabric.java new file mode 100644 index 0000000..a5d4253 --- /dev/null +++ b/fabric/src/main/java/io/github/steveplays28/noisiumchunkmanager/fabric/NoisiumFabric.java @@ -0,0 +1,11 @@ +package io.github.steveplays28.noisiumchunkmanager.fabric; + +import io.github.steveplays28.noisiumchunkmanager.NoisiumChunkManager; +import net.fabricmc.api.ModInitializer; + +public class NoisiumFabric implements ModInitializer { + @Override + public void onInitialize() { + NoisiumChunkManager.initialize(); + } +} diff --git a/fabric/src/main/java/io/github/steveplays28/noisiumchunkmanager/fabric/mixin/experimental/compat/fabric/api/networking/v1/NoisiumFabricMixinPlugin.java b/fabric/src/main/java/io/github/steveplays28/noisiumchunkmanager/fabric/mixin/experimental/compat/fabric/api/networking/v1/NoisiumFabricMixinPlugin.java new file mode 100644 index 0000000..5aa0832 --- /dev/null +++ b/fabric/src/main/java/io/github/steveplays28/noisiumchunkmanager/fabric/mixin/experimental/compat/fabric/api/networking/v1/NoisiumFabricMixinPlugin.java @@ -0,0 +1,49 @@ +package io.github.steveplays28.noisiumchunkmanager.fabric.mixin.experimental.compat.fabric.api.networking.v1; + +import com.google.common.collect.ImmutableMap; +import net.fabricmc.loader.api.FabricLoader; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; + +public class NoisiumFabricMixinPlugin implements IMixinConfigPlugin { + private static final @NotNull Supplier TRUE = () -> true; + private static final @NotNull String FABRIC_API_MOD_ID = "fabric-api"; + private static final @NotNull Map> CONDITIONS = ImmutableMap.of( + "io.github.steveplays28.noisiumchunkmanager.fabric.mixin.PlayerLookupMixin", () -> FabricLoader.getInstance().isModLoaded(FABRIC_API_MOD_ID) + ); + + @Override + public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { + return CONDITIONS.getOrDefault(mixinClassName, TRUE).get(); + } + + @Override + public void onLoad(String mixinPackage) {} + + @Override + public @Nullable String getRefMapperConfig() { + return null; + } + + @Override + public void acceptTargets(Set myTargets, Set otherTargets) {} + + @Override + public @Nullable List getMixins() { + return null; + } + + @Override + public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {} + + @Override + public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {} +} diff --git a/fabric/src/main/java/io/github/steveplays28/noisiumchunkmanager/fabric/mixin/experimental/compat/fabric/api/networking/v1/PlayerLookupMixin.java b/fabric/src/main/java/io/github/steveplays28/noisiumchunkmanager/fabric/mixin/experimental/compat/fabric/api/networking/v1/PlayerLookupMixin.java new file mode 100644 index 0000000..f2f1654 --- /dev/null +++ b/fabric/src/main/java/io/github/steveplays28/noisiumchunkmanager/fabric/mixin/experimental/compat/fabric/api/networking/v1/PlayerLookupMixin.java @@ -0,0 +1,31 @@ +package io.github.steveplays28.noisiumchunkmanager.fabric.mixin.experimental.compat.fabric.api.networking.v1; + +import net.fabricmc.fabric.api.networking.v1.PlayerLookup; +import net.minecraft.entity.Entity; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.math.ChunkPos; +import org.jetbrains.annotations.NotNull; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.Collection; + +@Mixin(PlayerLookup.class) +public class PlayerLookupMixin { + @Inject(method = "tracking(Lnet/minecraft/entity/Entity;)Ljava/util/Collection;", at = @At(value = "HEAD"), cancellable = true) + private static void noisiumchunkmanager$returnAllPlayersInTheEntityWorld(@NotNull Entity entity, @NotNull CallbackInfoReturnable> cir) { + if (!(entity.getWorld() instanceof @NotNull final ServerWorld serverWorld)) { + return; + } + + cir.setReturnValue(serverWorld.getPlayers()); + } + + @Inject(method = "tracking(Lnet/minecraft/server/world/ServerWorld;Lnet/minecraft/util/math/ChunkPos;)Ljava/util/Collection;", at = @At(value = "HEAD"), cancellable = true) + private static void noisiumchunkmanager$returnAllPlayersInTheSpecifiedWorld(@NotNull ServerWorld serverWorld, @NotNull ChunkPos chunkPos, @NotNull CallbackInfoReturnable> cir) { + cir.setReturnValue(serverWorld.getPlayers()); + } +} diff --git a/fabric/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/fabric/ModLoaderUtilImpl.java b/fabric/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/fabric/ModLoaderUtilImpl.java new file mode 100644 index 0000000..1770139 --- /dev/null +++ b/fabric/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/fabric/ModLoaderUtilImpl.java @@ -0,0 +1,27 @@ +package io.github.steveplays28.noisiumchunkmanager.util.fabric; + +import io.github.steveplays28.noisiumchunkmanager.util.ModLoaderUtil; +import net.fabricmc.loader.api.FabricLoader; +import org.jetbrains.annotations.NotNull; + +import java.nio.file.Path; + +/** + * Implements {@link ModLoaderUtil}. + */ +@SuppressWarnings("unused") +public class ModLoaderUtilImpl { + /** + * Checks if a mod is present during loading. + */ + public static boolean isModPresent(String id) { + return FabricLoader.getInstance().isModLoaded(id); + } + + /** + * @return The config directory of the mod loader. + */ + public static @NotNull Path getConfigDir() { + return FabricLoader.getInstance().getConfigDir(); + } +} diff --git a/fabric/src/main/resources/fabric.mod.json b/fabric/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..597c46f --- /dev/null +++ b/fabric/src/main/resources/fabric.mod.json @@ -0,0 +1,59 @@ +{ + "schemaVersion": 1, + "id": "${mod_id}", + "version": "${version}", + "name": "${mod_name}", + "description": "${mod_description}", + "authors": [ + "Steveplays28" + ], + "contact": { + "homepage": "https://modrinth.com/mod/${mod_id}", + "sources": "https://github.com/steves-underwater-paradise/${mod_id}", + "issues": "https://github.com/steves-underwater-paradise/${mod_id}/issues" + }, + "license": "${mod_license}", + "icon": "assets/${mod_namespace}/icon.png", + "custom": { + "modmenu": { + "links": { + "modmenu.discord": "https://discord.gg/KbWxgGg" + } + }, + "mc-publish": { + "loaders": [ + "fabric", + "quilt" + ], + "curseforge": "${curseforge_project_id}", + "modrinth": "${modrinth_project_id}" + }, + "lithium:options": { + "world.inline_block_access": false, + "gen.chunk_region": false, + "chunk.no_locking": false + } + }, + "environment": "*", + "entrypoints": { + "main": [ + "io.github.steveplays28.noisium.fabric.NoisiumFabric" + ], + "modmenu": [ + "io.github.steveplays28.noisium.client.compat.modmenu.NoisiumChunkManagerModMenuCompat" + ] + }, + "mixins": [ + "${mod_namespace}-common.mixins.json", + "${mod_namespace}-fabric.mixins.json" + ], + "depends": { + "fabricloader": ">=${fabric_loader_version}", + "minecraft": "${supported_minecraft_version}", + "architectury": ">=${architectury_api_version}", + "yet_another_config_lib_v3": ">=${yet_another_config_lib_version}-fabric" + }, + "suggests": { + "c2me": "*" + } +} diff --git a/fabric/src/main/resources/noisiumchunkmanager-fabric.mixins.json b/fabric/src/main/resources/noisiumchunkmanager-fabric.mixins.json new file mode 100644 index 0000000..15e95fa --- /dev/null +++ b/fabric/src/main/resources/noisiumchunkmanager-fabric.mixins.json @@ -0,0 +1,14 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "io.github.steveplays28.noisiumchunkmanager.fabric.mixin", + "compatibilityLevel": "JAVA_17", + "plugin": "io.github.steveplays28.noisiumchunkmanager.fabric.mixin.experimental.compat.fabric.api.networking.v1.NoisiumFabricMixinPlugin", + "mixins": [ + "experimental.compat.fabric.api.networking.v1.PlayerLookupMixin" + ], + "client": [], + "injectors": { + "defaultRequire": 1 + } +} diff --git a/forge/build.gradle b/forge/build.gradle new file mode 100644 index 0000000..e33f72d --- /dev/null +++ b/forge/build.gradle @@ -0,0 +1,121 @@ +//file:noinspection GroovyAccessibility +//file:noinspection GroovyAssignabilityCheck + +plugins { + id "com.github.johnrengelman.shadow" version "${shadow_plugin_version}" +} + +def archivesNameForge = "${rootProject.archives_base_name}-forge" + +architectury { + platformSetupLoomIde() + forge() +} + +base { + archivesName = archivesNameForge +} + +loom { + accessWidenerPath = project(":common").loom.accessWidenerPath + + forge { + convertAccessWideners = true + extraAccessWideners.add loom.accessWidenerPath.get().asFile.name + + mixinConfig "${mod_namespace}-common.mixins.json" + } +} + +configurations { + common + shadowCommon // Don't use shadow from the shadow plugin since it *excludes* files. + compileClasspath.extendsFrom common + runtimeClasspath.extendsFrom common + developmentForge.extendsFrom common +} + +dependencies { + forge "net.neoforged:forge:${rootProject.minecraft_version}-${rootProject.neoforge_version}" + + // Mixin Extras + include(implementation(annotationProcessor("io.github.llamalad7:mixinextras-forge:${project.mixin_extras_version}"))) + + // Architectury API + modRuntimeOnly("dev.architectury:architectury-forge:${rootProject.architectury_api_version}") + + // YetAnotherConfigLib + modRuntimeOnly("dev.isxander:yet-another-config-lib:${rootProject.yet_another_config_lib_version}-forge") + + common(project(path: ":common", configuration: "namedElements")) { transitive false } + shadowCommon(project(path: ":common", configuration: "transformProductionForge")) { transitive = false } +} + +processResources { + inputs.property "version", "${project.version}-forge" + + from(project(":common").sourceSets["main"].resources) { + include("assets", "data", "resourcepacks") + } + + filesMatching("META-INF/mods.toml") { + expand "version": project.version, + "mod_id": rootProject.mod_id, + "mod_namespace": rootProject.mod_namespace, + "mod_name": rootProject.mod_name, + "mod_description": rootProject.mod_description, + "mod_license": rootProject.mod_license, + "curseforge_project_id": rootProject.curseforge_project_id, + "modrinth_project_id": rootProject.modrinth_project_id, + "forge_version": rootProject.neoforge_version, + "supported_minecraft_version": rootProject.supported_minecraft_version, + "architectury_api_version": rootProject.architectury_api_version, + "yet_another_config_lib_version": rootProject.yet_another_config_lib_version + } +} + +shadowJar { + exclude "fabric.mod.json" + exclude "architectury.common.json" + + configurations = [project.configurations.shadowCommon] + archiveClassifier = "dev-shadow" +} + +remapJar { + inputFile.set shadowJar.archiveFile + dependsOn shadowJar +} + +sourcesJar { + def commonSources = project(":common").sourcesJar + dependsOn commonSources + from commonSources.archiveFile.map { zipTree(it) } +} + +components.java { + withVariantsFromConfiguration(project.configurations.shadowRuntimeElements) { + skip() + } +} + +publishing { + publications { + mavenJava(MavenPublication) { + groupId = rootProject.maven_group + artifactId = archivesNameForge + from components.java + } + } + + repositories { + maven { + name = "GitHubPackages" + url = uri("https://maven.pkg.github.com/Steveplays28/${rootProject.mod_id}") + credentials { + username = System.getenv("GITHUB_ACTOR") + password = System.getenv("GITHUB_TOKEN") + } + } + } +} diff --git a/forge/gradle.properties b/forge/gradle.properties new file mode 100644 index 0000000..32f842a --- /dev/null +++ b/forge/gradle.properties @@ -0,0 +1 @@ +loom.platform=forge \ No newline at end of file diff --git a/forge/src/main/java/io/github/steveplays28/noisiumchunkmanager/forge/NoisiumForge.java b/forge/src/main/java/io/github/steveplays28/noisiumchunkmanager/forge/NoisiumForge.java new file mode 100644 index 0000000..3fc7da8 --- /dev/null +++ b/forge/src/main/java/io/github/steveplays28/noisiumchunkmanager/forge/NoisiumForge.java @@ -0,0 +1,11 @@ +package io.github.steveplays28.noisiumchunkmanager.forge; + +import io.github.steveplays28.noisiumchunkmanager.NoisiumChunkManager; +import net.minecraftforge.fml.common.Mod; + +@Mod(NoisiumChunkManager.MOD_ID) +public class NoisiumForge { + public NoisiumForge() { + NoisiumChunkManager.initialize(); + } +} diff --git a/forge/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/forge/ModLoaderUtilImpl.java b/forge/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/forge/ModLoaderUtilImpl.java new file mode 100644 index 0000000..75a82ce --- /dev/null +++ b/forge/src/main/java/io/github/steveplays28/noisiumchunkmanager/util/forge/ModLoaderUtilImpl.java @@ -0,0 +1,28 @@ +package io.github.steveplays28.noisiumchunkmanager.util.forge; + +import io.github.steveplays28.noisiumchunkmanager.util.ModLoaderUtil; +import net.minecraftforge.fml.loading.FMLPaths; +import net.minecraftforge.fml.loading.LoadingModList; +import org.jetbrains.annotations.NotNull; + +import java.nio.file.Path; + +/** + * Implements {@link ModLoaderUtil}. + */ +@SuppressWarnings("unused") +public class ModLoaderUtilImpl { + /** + * Checks if a mod is present during loading. + */ + public static boolean isModPresent(String id) { + return LoadingModList.get().getModFileById(id) != null; + } + + /** + * @return The config directory of the mod loader. + */ + public static @NotNull Path getConfigDir() { + return FMLPaths.CONFIGDIR.get(); + } +} diff --git a/forge/src/main/resources/META-INF/mods.toml b/forge/src/main/resources/META-INF/mods.toml new file mode 100644 index 0000000..1e2b2c2 --- /dev/null +++ b/forge/src/main/resources/META-INF/mods.toml @@ -0,0 +1,48 @@ +modLoader = "javafml" +loaderVersion = ">=${forge_version}" +license = "${mod_license}" +issueTrackerURL = "https://github.com/steves-underwater-paradise/${mod_id}/issues" + +[[mods]] +modId = "${mod_id}" +version = "${version}" +displayName = "${mod_name}" +authors = "Steveplays28" +description = ''' +${mod_description} +''' +logoFile = "assets/${mod_namespace}/icon.png" +displayURL = "https://github.com/Steveplays28/${mod_id}" + +[mc-publish] +loaders = ["forge", "neoforge"] +curseforge = "${curseforge_project_id}" +modrinth = "${modrinth_project_id}" + +[[dependencies.${mod_id}]] +modId = "minecraft" +mandatory = true +versionRange = "${supported_minecraft_version}" +ordering = "NONE" +side = "BOTH" + +[[dependencies.${mod_id}]] +modId = "forge" +mandatory = true +versionRange = ">=${forge_version}" +ordering = "NONE" +side = "BOTH" + +[[dependencies.${mod_id}]] +modId = "architectury" +mandatory = true +versionRange = ">=${architectury_api_version}" +ordering = "NONE" +side = "BOTH" + +[[dependencies.${mod_id}]] +modId = "yet_another_config_lib_v3" +mandatory = true +versionRange = ">=${yet_another_config_lib_version}" +ordering = "NONE" +side = "BOTH" diff --git a/forge/src/main/resources/pack.mcmeta b/forge/src/main/resources/pack.mcmeta new file mode 100644 index 0000000..e9313c7 --- /dev/null +++ b/forge/src/main/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "description": "", + "pack_format": 15 + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..f993f2c --- /dev/null +++ b/gradle.properties @@ -0,0 +1,47 @@ +# Gradle settings +# Increase memory available to Gradle, enable parallelism, and enable caching +org.gradle.jvmargs=-Xmx2G +org.gradle.parallel=true +org.gradle.caching=true + +# Mod properties +maven_group=io.github.steveplays28 +archives_base_name=noisiumchunkmanager +mod_id=noisiumchunkmanager +mod_namespace=noisiumchunkmanager +mod_name=Noisium Chunk Manager +mod_description=A rewrite of Minecraft's server world chunk manager. +mod_license=LGPL-3.0 +mod_version=2.2.0 +supported_minecraft_version=>=1.20 <=1.20.1 +supported_minecraft_version_name=1.20-1.20.1 + +# Multiloader properties +architectury_plugin_version=3.4-SNAPSHOT +architectury_loom_version=1.6-SNAPSHOT +shadow_plugin_version=7.1.2 +forgix_plugin_version=1.2.6 +minecraft_version=1.20.1 +java_version=17 +enabled_platforms=fabric,forge + +# mc-publish properties +# TODO: Add project IDs +curseforge_project_id=0 +modrinth_project_id=UNDEFINED + +# Fabric properties +# Check these on https://modmuss50.me/fabric.html +yarn_mappings=1.20.1+build.10 +fabric_loader_version=0.14.25 + +# (Neo)Forge properties +neoforge_version=47.1.100 + +# Dependencies +mixin_extras_version=0.3.5 +architectury_api_version=9.2.14 +fabric_api_version=0.90.7+1.20.1 +yet_another_config_lib_version=3.4.4+1.20.1 +mod_menu_version=7.2.2 +distant_horizons_version=2.1.2-a diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..c1962a7 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..509c4a2 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..aeb74cb --- /dev/null +++ b/gradlew @@ -0,0 +1,245 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..a2567e4 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,14 @@ +pluginManagement { + repositories { + maven { url "https://maven.fabricmc.net/" } + maven { url "https://maven.architectury.dev/" } + maven { url "https://maven.neoforged.net/releases/" } + gradlePluginPortal() + } +} + +include("common") +include("fabric") +include("forge") + +rootProject.name = "${mod_id}"