commit 01817fbec1c2879d2663b46c614b7075010e6749 Author: richard Date: Tue Oct 27 10:10:43 2026 +0100 Repaired the index diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dcb0537 --- /dev/null +++ b/.gitignore @@ -0,0 +1,19 @@ +# gradle +.gradle +build +out +classes +# idea +.idea +*.iml +*.ipr +*.iws +# eclipse +*.launch +.settings +.metadata +.classpath +.project +# runs +run +run-data diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..dd60e75 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 yuseflc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..faf18a7 --- /dev/null +++ b/build.gradle @@ -0,0 +1,98 @@ +plugins { + id 'eclipse' + id 'idea' + id 'net.minecraftforge.gradle' version '[6.0.16,6.2)' + id 'org.parchmentmc.librarian.forgegradle' version '1.+' +} + + +group = mod_group_id +version = mod_version + +base { + archivesName = mod_id +} + +java { + toolchain.languageVersion = JavaLanguageVersion.of(17) +} + +minecraft { + mappings channel: mapping_channel, version: mapping_version + copyIdeResources = true + runs { + + configureEach { + workingDirectory project.file('run') + + property 'forge.logging.markers', 'REGISTRIES' + + property 'forge.logging.console.level', 'debug' + + mods { + "${mod_id}" { + source sourceSets.main + } + } + } + + client { + } + + server { + args '--nogui' + } + } +} + +repositories { + exclusiveContent { + forRepository { + maven { + name = "Modrinth" + url = "https://api.modrinth.com/maven" + } + } + forRepositories(fg.repository) + filter { + includeGroup "maven.modrinth" + } + } + // Warium VS is not on Modrinth, it is compiled against the jar in libs/ + flatDir { + dir 'libs' + } + mavenCentral() +} + +dependencies { + minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" + + // Valkyrien Skies 2.4.11 (hard dependency). Its core API ships jar-in-jar, so those jars are extracted into libs/ + compileOnly fg.deobf("maven.modrinth:valkyrien-skies:pOkdwuUh") + compileOnly files('libs/vs-core-api-1.1.0.jar', 'libs/vs-core-util-1.1.0.jar', 'libs/joml-primitives-1.10.0.jar') + compileOnly 'org.jetbrains.kotlin:kotlin-stdlib:1.9.22' + + // Warium VS 1.1.6 (optional dependency, for the planned flight physics overhaul) + compileOnly fg.deobf("blank:WariumVS:1.1.6") +} + + +tasks.named('processResources', ProcessResources).configure { + var replaceProperties = [minecraft_version : minecraft_version, minecraft_version_range: minecraft_version_range, + forge_version : forge_version, forge_version_range: forge_version_range, + loader_version_range: loader_version_range, + mod_id : mod_id, mod_name: mod_name, mod_license: mod_license, mod_version: mod_version, + mod_authors : mod_authors, mod_description: mod_description,] + + inputs.properties replaceProperties + + filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) { + expand replaceProperties + [project: project] + } +} + + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..c5442aa --- /dev/null +++ b/gradle.properties @@ -0,0 +1,18 @@ +org.gradle.jvmargs=-Xmx3G +org.gradle.daemon=false +org.gradle.warning.mode=none +minecraft_version=1.20.1 +minecraft_version_range=[1.20,) +forge_version=47.4.10 +forge_version_range=[47,) +loader_version_range=[47,) + +mapping_channel=parchment +mapping_version=2023.09.03-1.20.1 +mod_id=improved_aerodynamics +mod_name=VS: Improved Aerodynamics +mod_license=MIT +mod_version=0.1.0 +mod_group_id=dev.lumareth.improvedaerodynamics +mod_authors=Lumareth +mod_description=Valkyrien Skies addon that keeps terrain streaming ahead of fast ships, so they no longer slam into invisible walls at unloaded chunks. diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 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..a441313 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..b740cf1 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/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/platforms/jvm/plugins-application/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##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +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=SC2039,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=SC2039,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, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +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..25da30d --- /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. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +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/libs/WariumVS-1.1.6.jar b/libs/WariumVS-1.1.6.jar new file mode 100644 index 0000000..58e0b44 Binary files /dev/null and b/libs/WariumVS-1.1.6.jar differ diff --git a/libs/joml-primitives-1.10.0.jar b/libs/joml-primitives-1.10.0.jar new file mode 100644 index 0000000..c886ca2 Binary files /dev/null and b/libs/joml-primitives-1.10.0.jar differ diff --git a/libs/vs-core-api-1.1.0.jar b/libs/vs-core-api-1.1.0.jar new file mode 100644 index 0000000..633fdec Binary files /dev/null and b/libs/vs-core-api-1.1.0.jar differ diff --git a/libs/vs-core-util-1.1.0.jar b/libs/vs-core-util-1.1.0.jar new file mode 100644 index 0000000..116bbba Binary files /dev/null and b/libs/vs-core-util-1.1.0.jar differ diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..5bcfaa7 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,17 @@ +pluginManagement { + repositories { + gradlePluginPortal() + maven { + name = 'MinecraftForge' + url = 'https://maven.minecraftforge.net/' + } + maven { url = 'https://maven.parchmentmc.org' } + maven { url = 'https://repo.spongepowered.org/repository/maven-public/' } + } +} + +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.7.0' +} + +rootProject.name = 'improved_aerodynamics' diff --git a/src/main/java/dev/lumareth/improvedAerodynamics/Config.java b/src/main/java/dev/lumareth/improvedAerodynamics/Config.java new file mode 100644 index 0000000..333ca8f --- /dev/null +++ b/src/main/java/dev/lumareth/improvedAerodynamics/Config.java @@ -0,0 +1,55 @@ +package dev.lumareth.improvedAerodynamics; + +import net.minecraftforge.common.ForgeConfigSpec; + +public final class Config { + private static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder(); + + static { + BUILDER.push("terrainStreaming"); + } + + public static final ForgeConfigSpec.DoubleValue LOOKAHEAD_SECONDS = BUILDER + .comment("How many seconds of flight ahead of each ship terrain is loaded for") + .defineInRange("lookaheadSeconds", 3.0D, 0.5D, 20.0D); + + public static final ForgeConfigSpec.DoubleValue MIN_SHIP_SPEED = BUILDER + .comment("Ships slower than this (blocks per second) are left to normal player chunk loading") + .defineInRange("minShipSpeed", 8.0D, 0.0D, 1000.0D); + + public static final ForgeConfigSpec.IntValue CORRIDOR_MARGIN_CHUNKS = BUILDER + .comment("Extra chunks loaded on each side of a ship's predicted path") + .defineInRange("corridorMarginChunks", 1, 0, 8); + + public static final ForgeConfigSpec.IntValue MAX_NEW_CHUNKS_PER_TICK = BUILDER + .comment("Upper limit of chunks newly requested (and newly given an air placeholder) per tick, protects the tick rate") + .defineInRange("maxNewChunksPerTick", 64, 1, 1024); + + static { + BUILDER.pop(); + BUILDER.push("airPlaceholder"); + } + + public static final ForgeConfigSpec.BooleanValue ENABLE_AIR_PLACEHOLDER = BUILDER + .comment("Valkyrien Skies treats terrain it has not received yet as solid, so ships hit a wall at unloaded chunks.", + "When enabled, chunks on a ship's path that are not loaded yet are treated as air above the estimated", + "world generation surface until the real terrain arrives. Everything below that stays solid.") + .define("enableAirPlaceholder", false); + + public static final ForgeConfigSpec.IntValue PLACEHOLDER_SURFACE_MARGIN = BUILDER + .comment("Blocks above the estimated surface that stay solid, covers trees and structures") + .defineInRange("placeholderSurfaceMargin", 32, 0, 256); + + public static final ForgeConfigSpec.IntValue PLACEHOLDER_RELEASE_TICKS = BUILDER + .comment("Ticks a placeholder chunk stays air after no ship needs it anymore, then it goes back to solid") + .defineInRange("placeholderReleaseTicks", 100, 20, 6000); + + static { + BUILDER.pop(); + } + + static final ForgeConfigSpec SPEC = BUILDER.build(); + + private Config() { + } +} diff --git a/src/main/java/dev/lumareth/improvedAerodynamics/ImprovedAerodynamics.java b/src/main/java/dev/lumareth/improvedAerodynamics/ImprovedAerodynamics.java new file mode 100644 index 0000000..1d288ea --- /dev/null +++ b/src/main/java/dev/lumareth/improvedAerodynamics/ImprovedAerodynamics.java @@ -0,0 +1,21 @@ +package dev.lumareth.improvedAerodynamics; + +import com.mojang.logging.LogUtils; +import dev.lumareth.improvedAerodynamics.terrain.LookaheadLoader; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.ModLoadingContext; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.config.ModConfig; +import org.slf4j.Logger; + +@Mod(ImprovedAerodynamics.MOD_ID) +public class ImprovedAerodynamics { + + public static final String MOD_ID = "improved_aerodynamics"; + public static final Logger LOGGER = LogUtils.getLogger(); + + public ImprovedAerodynamics() { + MinecraftForge.EVENT_BUS.register(LookaheadLoader.class); + ModLoadingContext.get().registerConfig(ModConfig.Type.SERVER, Config.SPEC); + } +} diff --git a/src/main/java/dev/lumareth/improvedAerodynamics/terrain/AirPlaceholder.java b/src/main/java/dev/lumareth/improvedAerodynamics/terrain/AirPlaceholder.java new file mode 100644 index 0000000..5f0f2c9 --- /dev/null +++ b/src/main/java/dev/lumareth/improvedAerodynamics/terrain/AirPlaceholder.java @@ -0,0 +1,169 @@ +package dev.lumareth.improvedAerodynamics.terrain; + +import dev.lumareth.improvedAerodynamics.Config; +import dev.lumareth.improvedAerodynamics.ImprovedAerodynamics; +import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.longs.LongLinkedOpenHashSet; +import it.unimi.dsi.fastutil.objects.ObjectIterator; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerChunkCache; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.levelgen.Heightmap; +import org.valkyrienskies.core.internal.VsiCore; +import org.valkyrienskies.core.internal.world.chunks.VsiTerrainUpdate; +import org.valkyrienskies.mod.common.VSGameUtilsKt; +import org.valkyrienskies.mod.common.ValkyrienSkiesMod; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Optional: hands VS empty sections for not yet loaded chunks on a ship's path, so physics sees air there instead of + * its solid "unloaded" fallback. Only sections fully above the generator's estimated surface (plus a margin) are + * replaced, everything lower stays solid so a ship can never end up inside terrain that has not loaded yet. + * Once the real chunk loads, VS overwrites every section of it with the actual terrain. + *

+ * This uses VS internals (its terrain update API and the mixin field listing its loaded chunks), so it switches + * itself off if those are missing. + */ +final class AirPlaceholder { + // Chunks VS has handed to physics, merged into ServerLevel by its MixinServerLevel + private static final Field KNOWN_CHUNKS = findKnownChunks(); + private static final int[][] SURFACE_SAMPLES = {{0, 0}, {15, 0}, {0, 15}, {15, 15}, {8, 8}}; + + private static final Map, Long2ObjectOpenHashMap> PLACEHOLDERS = new HashMap<>(); + + /** Sections of one chunk that were replaced with air, and the last tick a ship's path still covered it. */ + private static final class Placeholder { + final int minSectionY; + final int maxSectionY; + long lastWanted; + + Placeholder(int minSectionY, int maxSectionY, long lastWanted) { + this.minSectionY = minSectionY; + this.maxSectionY = maxSectionY; + this.lastWanted = lastWanted; + } + } + + private AirPlaceholder() { + } + + static void update(ServerLevel level, LongLinkedOpenHashSet corridor, long tick) { + boolean enabled = Config.ENABLE_AIR_PLACEHOLDER.get() && KNOWN_CHUNKS != null; + Long2ObjectOpenHashMap placeholders = PLACEHOLDERS.get(level.dimension()); + if (!enabled && placeholders == null) { + return; + } + Map knownChunks = getKnownChunks(level); + if (knownChunks == null) { + return; + } + if (placeholders == null) { + placeholders = new Long2ObjectOpenHashMap<>(); + PLACEHOLDERS.put(level.dimension(), placeholders); + } + + VsiCore core = ValkyrienSkiesMod.getVsCore(); + List updates = new ArrayList<>(); + + if (enabled) { + int budget = Config.MAX_NEW_CHUNKS_PER_TICK.get(); + int surfaceMargin = Config.PLACEHOLDER_SURFACE_MARGIN.get(); + for (long chunk : corridor) { + Placeholder placeholder = placeholders.get(chunk); + if (placeholder != null) { + placeholder.lastWanted = tick; + continue; + } + ChunkPos pos = new ChunkPos(chunk); + // Loaded or already in physics: the real terrain is there or arrives next tick, never cover it with air + if (knownChunks.containsKey(pos) || level.getChunkSource().getChunkNow(pos.x, pos.z) != null) { + continue; + } + if (budget-- <= 0) { + break; + } + int minSectionY = Math.floorDiv(estimateSurface(level, pos) + surfaceMargin, 16) + 1; + int maxSectionY = level.getMaxSection() - 1; + if (minSectionY > maxSectionY) { + continue; + } + for (int sectionY = minSectionY; sectionY <= maxSectionY; sectionY++) { + updates.add(core.newEmptyVoxelShapeUpdate(pos.x, sectionY, pos.z, true)); + } + placeholders.put(chunk, new Placeholder(minSectionY, maxSectionY, tick)); + } + } + + int releaseTicks = Config.PLACEHOLDER_RELEASE_TICKS.get(); + ObjectIterator> iterator = placeholders.long2ObjectEntrySet().fastIterator(); + while (iterator.hasNext()) { + Long2ObjectMap.Entry entry = iterator.next(); + ChunkPos pos = new ChunkPos(entry.getLongKey()); + Placeholder placeholder = entry.getValue(); + if (knownChunks.containsKey(pos)) { + // VS loaded the chunk and replaced every section with the real terrain + iterator.remove(); + } else if (!enabled || tick - placeholder.lastWanted > releaseTicks) { + // Deleting the sections puts the chunk back to VS's solid "unloaded" state. Terrain updates apply + // in order, so if the chunk loads later its real terrain still wins + for (int sectionY = placeholder.minSectionY; sectionY <= placeholder.maxSectionY; sectionY++) { + updates.add(core.newDeleteTerrainUpdate(pos.x, sectionY, pos.z)); + } + iterator.remove(); + } + } + + if (!updates.isEmpty()) { + VSGameUtilsKt.getShipObjectWorld(level).addTerrainUpdates(VSGameUtilsKt.getDimensionId(level), updates); + } + if (!enabled && placeholders.isEmpty()) { + PLACEHOLDERS.remove(level.dimension()); + } + } + + static void clear() { + PLACEHOLDERS.clear(); + } + + /** Highest world generation surface at the chunk's corners and center, sampled from noise without generating the chunk. */ + private static int estimateSurface(ServerLevel level, ChunkPos pos) { + ServerChunkCache chunkSource = level.getChunkSource(); + int surface = level.getMinBuildHeight(); + for (int[] sample : SURFACE_SAMPLES) { + surface = Math.max(surface, chunkSource.getGenerator().getBaseHeight(pos.getMinBlockX() + sample[0], + pos.getMinBlockZ() + sample[1], Heightmap.Types.WORLD_SURFACE_WG, level, chunkSource.randomState())); + } + return surface; + } + + @SuppressWarnings("unchecked") + private static Map getKnownChunks(ServerLevel level) { + if (KNOWN_CHUNKS == null) { + return null; + } + try { + return (Map) KNOWN_CHUNKS.get(level); + } catch (IllegalAccessException e) { + return null; + } + } + + private static Field findKnownChunks() { + try { + Field field = ServerLevel.class.getDeclaredField("vs$knownChunks"); + field.setAccessible(true); + return field; + } catch (ReflectiveOperationException | RuntimeException e) { + ImprovedAerodynamics.LOGGER.warn("VS's loaded chunk list was not found, the air placeholder is disabled", e); + return null; + } + } +} diff --git a/src/main/java/dev/lumareth/improvedAerodynamics/terrain/LookaheadLoader.java b/src/main/java/dev/lumareth/improvedAerodynamics/terrain/LookaheadLoader.java new file mode 100644 index 0000000..5fe7839 --- /dev/null +++ b/src/main/java/dev/lumareth/improvedAerodynamics/terrain/LookaheadLoader.java @@ -0,0 +1,116 @@ +package dev.lumareth.improvedAerodynamics.terrain; + +import dev.lumareth.improvedAerodynamics.Config; +import it.unimi.dsi.fastutil.longs.Long2LongMap; +import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; +import it.unimi.dsi.fastutil.longs.LongLinkedOpenHashSet; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.TicketType; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.event.server.ServerStoppedEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import org.joml.Vector3dc; +import org.joml.primitives.AABBdc; +import org.valkyrienskies.core.api.ships.LoadedServerShip; +import org.valkyrienskies.mod.common.VSGameUtilsKt; + +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; + +/** + * Valkyrien Skies only gives its physics engine the terrain of chunks Minecraft has fully loaded, and treats every + * other chunk as solid. Nothing loads terrain ahead of a ship, so fast ships slam into an invisible wall wherever + * the player's view distance has not caught up yet. + *

+ * This puts a short-lived ticket on every chunk along each fast ship's predicted path, so the terrain is loaded + * (and handed to physics by VS) before the ship gets there. + */ +public final class LookaheadLoader { + private static final int TICKET_LIFETIME = 40; + // Distance 0 gives ticket level 33 (FULL), the lowest level VS feeds to physics. VS also requires the ticket on the chunk itself. + private static final int TICKET_DISTANCE = 0; + private static final TicketType SHIP_LOOKAHEAD = TicketType.create("improved_aerodynamics_lookahead", + Comparator.comparingLong(ChunkPos::toLong), TICKET_LIFETIME); + + // Last tick each chunk was ticketed, per dimension + private static final Map, Long2LongMap> TICKETED = new HashMap<>(); + + private LookaheadLoader() { + } + + // Runs after ServerLevel.tick, so VS has already fed this tick's loaded chunks to physics + @SubscribeEvent + public static void onLevelTick(TickEvent.LevelTickEvent event) { + if (event.phase != TickEvent.Phase.END || !(event.level instanceof ServerLevel level)) { + return; + } + LongLinkedOpenHashSet corridor = collectCorridor(level); + long tick = level.getGameTime(); + int budget = Config.MAX_NEW_CHUNKS_PER_TICK.get(); + + Long2LongMap ticketed = TICKETED.computeIfAbsent(level.dimension(), key -> new Long2LongOpenHashMap()); + ticketed.values().removeIf(lastTick -> tick - lastTick >= TICKET_LIFETIME); + for (long chunk : corridor) { + boolean isNew = !ticketed.containsKey(chunk); + if (isNew && budget-- <= 0) { + continue; + } + // Re-adding an existing ticket only refreshes its timeout + ChunkPos pos = new ChunkPos(chunk); + level.getChunkSource().addRegionTicket(SHIP_LOOKAHEAD, pos, TICKET_DISTANCE, pos); + ticketed.put(chunk, tick); + } + + AirPlaceholder.update(level, corridor, tick); + } + + @SubscribeEvent + public static void onServerStopped(ServerStoppedEvent event) { + TICKETED.clear(); + AirPlaceholder.clear(); + } + + /** World chunks swept by every fast ship's AABB over the lookahead time, nearest first. */ + private static LongLinkedOpenHashSet collectCorridor(ServerLevel level) { + LongLinkedOpenHashSet corridor = new LongLinkedOpenHashSet(); + String dimension = VSGameUtilsKt.getDimensionId(level); + double minSpeed = Config.MIN_SHIP_SPEED.get(); + double lookahead = Config.LOOKAHEAD_SECONDS.get(); + int margin = Config.CORRIDOR_MARGIN_CHUNKS.get(); + + for (LoadedServerShip ship : VSGameUtilsKt.getShipObjectWorld(level).getLoadedShips()) { + if (!dimension.equals(ship.getChunkClaimDimension())) { + continue; + } + Vector3dc velocity = ship.getVelocity(); + double speed = Math.sqrt(velocity.x() * velocity.x() + velocity.z() * velocity.z()); + if (speed < minSpeed) { + continue; + } + AABBdc box = ship.getWorldAABB(); + // Step at most one chunk at a time so no chunk on the path is skipped + int steps = (int) Math.ceil(speed * lookahead / 16D); + for (int step = 0; step <= steps; step++) { + double t = lookahead * step / Math.max(steps, 1); + double dx = velocity.x() * t; + double dz = velocity.z() * t; + int minX = ((int) Math.floor(box.minX() + dx) >> 4) - margin; + int maxX = ((int) Math.floor(box.maxX() + dx) >> 4) + margin; + int minZ = ((int) Math.floor(box.minZ() + dz) >> 4) - margin; + int maxZ = ((int) Math.floor(box.maxZ() + dz) >> 4) + margin; + for (int x = minX; x <= maxX; x++) { + for (int z = minZ; z <= maxZ; z++) { + if (!VSGameUtilsKt.isChunkInShipyard(level, x, z)) { + corridor.add(ChunkPos.asLong(x, z)); + } + } + } + } + } + return corridor; + } +} diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml new file mode 100644 index 0000000..37471fe --- /dev/null +++ b/src/main/resources/META-INF/mods.toml @@ -0,0 +1,39 @@ +modLoader = "javafml" +loaderVersion = "${loader_version_range}" +license = "${mod_license}" + +[[mods]] +modId = "${mod_id}" +version = "${mod_version}" +displayName = "${mod_name}" +authors = "${mod_authors}" +description = '''${mod_description}''' + +[[dependencies."${mod_id}"]] +modId = "forge" +mandatory = true +versionRange = "${forge_version_range}" +ordering = "NONE" +side = "BOTH" + +[[dependencies."${mod_id}"]] +modId = "minecraft" +mandatory = true +versionRange = "${minecraft_version_range}" +ordering = "NONE" +side = "BOTH" + +[[dependencies."${mod_id}"]] +modId = "valkyrienskies" +mandatory = true +versionRange = "[2.4.11,)" +ordering = "AFTER" +side = "BOTH" + +# Optional, for the planned Warium VS flight physics overhaul +[[dependencies."${mod_id}"]] +modId = "valkyrien_warium" +mandatory = false +versionRange = "[1.1.6,)" +ordering = "AFTER" +side = "BOTH" diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta new file mode 100644 index 0000000..3e9c0a4 --- /dev/null +++ b/src/main/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "description": "improved_aerodynamics resources", + "pack_format": 15 + } +}