diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..ed71ba6 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,24 @@ +name: Build +on: + pull_request: + types: [opened, synchronize] + +jobs: + build: + runs-on: ubuntu-20.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v3 + + - uses: actions/setup-java@v3 + with: + java-version: 17 + distribution: temurin + + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@v1 + + - name: Build + uses: gradle/gradle-build-action@v2 + with: + arguments: build \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..00b4b81 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,46 @@ +name: Release +on: + release: + types: [created] + +jobs: + build: + runs-on: ubuntu-20.04 + timeout-minutes: 20 + permissions: + contents: write + packages: write + steps: + - uses: actions/checkout@v3 + + - uses: actions/setup-java@v3 + with: + java-version: 17 + distribution: temurin + + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@v1 + + - name: Update mod version + uses: christian-draeger/write-properties@1.0.1 + with: + path: "gradle.properties" + property: "mod_version" + value: ${{ github.event.release.tag_name }} + + - name: Build and upload + uses: gradle/gradle-build-action@v2 + with: + arguments: build curseforge modrinth publish + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }} + CURSEFORGE_TOKEN: ${{ secrets.CURSEFORGE_TOKEN }} + CHANGELOG: ${{ github.event.release.body }} + CI: true + + - name: Upload to github releases + if: ${{ github.event_name == 'release' }} + uses: svenstaro/upload-release-action@v2 + with: + file: build/libs/atheneum_connector-${{ github.event.release.tag_name }}.jar diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml new file mode 100644 index 0000000..7b9c941 --- /dev/null +++ b/.github/workflows/sonar.yml @@ -0,0 +1,39 @@ +name: Analyze +on: + push: + branches: ["[0-9]+.[0-9]+.x"] + +jobs: + build: + name: Analyze + runs-on: ubuntu-latest + timeout-minutes: 40 + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + fetch-depth: 0 + + - uses: actions/setup-java@v3 + with: + java-version: 17 + distribution: temurin + + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@v1 + + - name: Cache SonarQube packages + uses: actions/cache@v2 + with: + path: ~/.sonar/cache + key: ${{ runner.os }}-sonar + restore-keys: ${{ runner.os }}-sonar + + - name: Build and upload + uses: gradle/gradle-build-action@v2 + with: + arguments: build sonar + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..64029e1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +# eclipse +bin +*.launch +.settings +.metadata +.classpath +.project + +# idea +out +*.ipr +*.iws +*.iml +.idea + +# gradle +build +.gradle + +# other +eclipse +run + +# Files from Forge MDK +forge*changelog.txt + +**.env \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..604e032 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,35 @@ +Copyright (c) 2020 possible_triangle. All Rights Reserved. + +Permissions are hereby granted below to any person having a copy of +this software and/or its associated files: + +Usage - You may use this software for private and public use. You may use this software as a library +or integrate it with your code with the predicate being it must be downloaded from our sources and a soft or hard dependency. +Copying - You may copy this software for private use or to contribute to this software. +Modification - You may modify this software for private use or to contribute to this software. +Publishing - You may not publish copies of this software. +Distributing - You may not distribute this software. +Sublicensing - You may not sublicense this software. +Selling - You may not sell this software. + +Modpack Clarification: +Permission is granted for Modpacks to include this software as long +as the copy of this software in the pack is an unmodified public copy +from our public sources and is marked as included in the Modpack. + +Definition of 'Our Sources' in this license: +Our Sources in this license means a copy +of this software or its associated files that come +directly from the owners of this software, an example +are the files uploaded by us on our Curse Page. + +The above copyright notice and these permission notices 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/README.md b/README.md new file mode 100644 index 0000000..e6f7796 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# Atheneum Connector diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..abfdcea --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,75 @@ +import com.expediagroup.graphql.plugin.gradle.config.GraphQLSerializer +import com.expediagroup.graphql.plugin.gradle.graphql + +val mc_version: String by extra +val rabbitmq_version: String by extra +val travelers_titles_version: String by extra +val yungs_api_version: String by extra +val graphql_client_version: String by extra +val kotlin_forge_version: String by extra + +plugins { + idea + id("com.possible-triangle.gradle") version ("0.1.5") + id("com.expediagroup.graphql") version ("8.1.0") +} + +withKotlin() + +forge { + includesLibrary("com.rabbitmq:amqp-client:$rabbitmq_version") + includesLibrary("com.expediagroup:graphql-kotlin-ktor-client:$graphql_client_version") + + kotlinForgeVersion = null +} + +repositories { + modrinthMaven() +} + +// required because of duplicate package export +configurations.named("minecraftLibrary") { + exclude(group = "org.jetbrains", module = "annotations") +} + +dependencies { + modImplementation("maven.modrinth:travelers-titles:${travelers_titles_version}") + modRuntimeOnly("maven.modrinth:yungs-api:${yungs_api_version}") + + // required because of duplicate package export by thedarkcolour:kotlinforforge:all + implementation("thedarkcolour:kffmod:${kotlin_forge_version}") + implementation("thedarkcolour:kfflang:${kotlin_forge_version}") + implementation("thedarkcolour:kfflib:${kotlin_forge_version}") + + //add("minecraftLibrary", "org.jetbrains.kotlin:kotlin-reflect:${kotlin.coreLibrariesVersion}") + + /* + "minecraftLibrary"("com.expediagroup:graphql-kotlin-ktor-client:$graphql_client_version") { + exclude(group = "org.jetbrains.kotlinx") + exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib") + exclude(group = "org.jetbrains") + } + + "jarJar"("com.expediagroup:graphql-kotlin-ktor-client:$graphql_client_version") { + jarJar.pin(this, "[${graphql_client_version},)") + } + */ +} + +graphql { + client { + endpoint = "http://localhost:8080/api/graphql" + packageName = "com.possible_triangle.atheneum_connector.generated" + serializer = GraphQLSerializer.KOTLINX + } +} + +enablePublishing { + githubPackages() +} + +uploadToModrinth { + syncBodyFromReadme() +} + +enableSonarQube() diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..774827c --- /dev/null +++ b/gradle.properties @@ -0,0 +1,22 @@ +kotlin.code.style=official +org.gradle.jvmargs=-Xmx2G +org.gradle.daemon=false + +mc_version=1.20.1 +forge_version=47.1.3 + +mod_id=atheneum_connector +mod_version=0.0.0-dev +release_type=release +mod_name=Atheneum Connector +mod_author=possible_triangle +maven_group=com.possible-triangle + +kotlin_forge_version=4.11.0 +rabbitmq_version=5.22.0 +travelers_titles_version=oUSK4sOQ +yungs_api_version=PJOYAmAs +graphql_client_version=8.1.0 + +repository=voidshake/atheneumconnector +modrinth_project_id=WIPHNZss 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..37aef8d --- /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.1.1-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.kts b/settings.gradle.kts new file mode 100644 index 0000000..e40816f --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,7 @@ +pluginManagement { + repositories { + gradlePluginPortal() + maven { url = uri("https://maven.minecraftforge.net/") } + maven { url = uri("https://repo.spongepowered.org/repository/maven-public/") } + } +} \ No newline at end of file diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 0000000..bc7124c --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1 @@ +sonar.exclusions=src/main/kotlin/com/possible_triangle/atheneum_connector/generated/** \ No newline at end of file diff --git a/src/main/java/com/possible_triangle/atheneum_connector/mixins/.gitkeep b/src/main/java/com/possible_triangle/atheneum_connector/mixins/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/kotlin/com/possible_triangle/atheneum_connector/AtheneumConnector.kt b/src/main/kotlin/com/possible_triangle/atheneum_connector/AtheneumConnector.kt new file mode 100644 index 0000000..5f7ad93 --- /dev/null +++ b/src/main/kotlin/com/possible_triangle/atheneum_connector/AtheneumConnector.kt @@ -0,0 +1,39 @@ +package com.possible_triangle.atheneum_connector + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonBuilder +import net.minecraftforge.api.distmarker.Dist +import net.minecraftforge.event.server.ServerStoppingEvent +import net.minecraftforge.fml.DistExecutor +import net.minecraftforge.fml.common.Mod +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import thedarkcolour.kotlinforforge.forge.FORGE_BUS + +@Mod("atheneum_connector") +object AtheneumConnector { + + fun JsonBuilder.configure() { + // Nothing for now + } + + val JSON = Json { configure() } + + val LOG: Logger = LoggerFactory.getLogger("Atheneum Connector") + + init { + DistExecutor.unsafeRunWhenOn(Dist.DEDICATED_SERVER) { + Runnable(::serverInit) + } + } + + private fun serverInit() { + RabbitMQ.connect("amqp://guest:guest@localhost:5672/") + LocationCache.initialize() + + FORGE_BUS.addListener { _: ServerStoppingEvent -> + RabbitMQ.close() + } + } + +} \ No newline at end of file diff --git a/src/main/kotlin/com/possible_triangle/atheneum_connector/DebugCommand.kt b/src/main/kotlin/com/possible_triangle/atheneum_connector/DebugCommand.kt new file mode 100644 index 0000000..5b5b44b --- /dev/null +++ b/src/main/kotlin/com/possible_triangle/atheneum_connector/DebugCommand.kt @@ -0,0 +1,33 @@ +package com.possible_triangle.atheneum_connector + +import com.mojang.brigadier.context.CommandContext +import net.minecraft.commands.CommandSourceStack +import net.minecraft.commands.Commands.literal +import net.minecraft.network.chat.Component +import net.minecraftforge.api.distmarker.Dist +import net.minecraftforge.event.RegisterCommandsEvent +import net.minecraftforge.eventbus.api.SubscribeEvent +import net.minecraftforge.fml.common.Mod.EventBusSubscriber + +@EventBusSubscriber(Dist.DEDICATED_SERVER) +object DebugCommand { + + @SubscribeEvent + fun register(event: RegisterCommandsEvent) { + event.dispatcher.register( + literal("atheneum") + .then(literal("reload") + .executes(::reload) + ) + ) + } + + private fun reload(ctx: CommandContext): Int { + LocationCache.reload() + + ctx.source.sendSuccess({ Component.literal("Reloaded cache!") }, true) + + return 1 + } + +} \ No newline at end of file diff --git a/src/main/kotlin/com/possible_triangle/atheneum_connector/GraphQL.kt b/src/main/kotlin/com/possible_triangle/atheneum_connector/GraphQL.kt new file mode 100644 index 0000000..49373e7 --- /dev/null +++ b/src/main/kotlin/com/possible_triangle/atheneum_connector/GraphQL.kt @@ -0,0 +1,21 @@ +package com.possible_triangle.atheneum_connector + +import com.expediagroup.graphql.client.ktor.GraphQLKtorClient +import com.expediagroup.graphql.client.serialization.GraphQLClientKotlinxSerializer +import com.expediagroup.graphql.client.types.GraphQLClientRequest +import com.possible_triangle.atheneum_connector.AtheneumConnector.configure +import java.net.URL + +object GraphQL { + + private val client = GraphQLKtorClient( + URL("http://localhost:8080/api/graphql"), + serializer = GraphQLClientKotlinxSerializer { configure() } + ) + + suspend fun query(query: GraphQLClientRequest): T { + val response = client.execute(query) + return response.data ?: throw GraphQLException(response.errors ?: emptyList()) + } + +} \ No newline at end of file diff --git a/src/main/kotlin/com/possible_triangle/atheneum_connector/GraphQLException.kt b/src/main/kotlin/com/possible_triangle/atheneum_connector/GraphQLException.kt new file mode 100644 index 0000000..9660b8c --- /dev/null +++ b/src/main/kotlin/com/possible_triangle/atheneum_connector/GraphQLException.kt @@ -0,0 +1,7 @@ +package com.possible_triangle.atheneum_connector + +import com.expediagroup.graphql.client.types.GraphQLClientError + +class GraphQLException(val errors: List) : RuntimeException(errors.joinToString(", ") { + it.message +}) \ No newline at end of file diff --git a/src/main/kotlin/com/possible_triangle/atheneum_connector/LocationCache.kt b/src/main/kotlin/com/possible_triangle/atheneum_connector/LocationCache.kt new file mode 100644 index 0000000..9a022e1 --- /dev/null +++ b/src/main/kotlin/com/possible_triangle/atheneum_connector/LocationCache.kt @@ -0,0 +1,94 @@ +package com.possible_triangle.atheneum_connector + +import com.mojang.datafixers.util.Either +import com.possible_triangle.atheneum_connector.generated.AreasQuery +import com.possible_triangle.atheneum_connector.generated.areasquery.Area +import com.possible_triangle.atheneum_connector.generated.areasquery.FlatPoint +import com.possible_triangle.atheneum_connector.generated.placesquery.Place +import kotlinx.coroutines.runBlocking +import net.minecraft.core.BlockPos +import net.minecraft.core.SectionPos.blockToSectionCoord +import net.minecraft.core.registries.Registries +import net.minecraft.resources.ResourceKey +import net.minecraft.resources.ResourceLocation +import net.minecraft.world.level.ChunkPos +import net.minecraft.world.level.Level + +class LocationCache { + + private val lookup = hashMapOf, MutableMap>() + private val reverseLookup = hashMapOf, List>>() + + companion object { + private val AREAS = LocationCache() + + fun reload() { + AREAS.clear() + initialize() + } + + fun initialize() = runBlocking { + val areas = GraphQL.query(AreasQuery()).areas + areas.nodes.forEach { area -> + val level = ResourceKey.create(Registries.DIMENSION, ResourceLocation(area.world)) + val chunks = area.points.containingChunks() + AREAS.reverseLookup[area.id] = level to chunks + + AREAS.lookup.getOrPut(level, ::hashMapOf).apply { + chunks.forEach { put(it, area) } + } + } + } + + private fun List.containingChunks(): List { + val xs = map { it.x } + val zs = map { it.z } + val minX = xs.min() + val maxX = xs.max() + val minZ = zs.min() + val maxZ = zs.max() + + val possibleChunks = (minX..maxX step 16).flatMap { x -> + (minZ..maxZ step 16).map { z -> + FlatPoint(x + 8, z + 8) + } + } + + return possibleChunks.filter { point -> + var previous = last() + var odd = false + + forEach { current -> + if ( + (current.z > point.z) != (previous.z > point.z) + && (point.x < (previous.x - current.x) * (point.z - current.z) / (previous.z - current.z) + current.x) + ) { + odd = !odd + } + previous = current + } + + odd + }.map { + ChunkPos( + blockToSectionCoord(it.x), + blockToSectionCoord(it.z), + ) + } + } + + fun containing(level: ResourceKey, pos: BlockPos): Either? { + val chunk = ChunkPos(pos) + + val area = AREAS.lookup[level]?.get(chunk) + + return area?.let { Either.left(area) } + } + } + + private fun clear() { + lookup.clear() + reverseLookup.clear() + } + +} \ No newline at end of file diff --git a/src/main/kotlin/com/possible_triangle/atheneum_connector/RabbitMQ.kt b/src/main/kotlin/com/possible_triangle/atheneum_connector/RabbitMQ.kt new file mode 100644 index 0000000..6afa968 --- /dev/null +++ b/src/main/kotlin/com/possible_triangle/atheneum_connector/RabbitMQ.kt @@ -0,0 +1,86 @@ +package com.possible_triangle.atheneum_connector + +import com.rabbitmq.client.Channel +import com.rabbitmq.client.ConnectionFactory +import kotlinx.serialization.InternalSerializationApi +import kotlinx.serialization.serializer +import net.minecraftforge.fml.ModList +import org.objectweb.asm.Type +import java.lang.annotation.ElementType +import kotlin.reflect.KParameter +import kotlin.reflect.full.hasAnnotation +import kotlin.reflect.full.memberFunctions + +object RabbitMQ { + + private const val EXCHANGE_KEY = "exchange" + + private lateinit var channel: Channel + + fun connect(url: String) { + AtheneumConnector.LOG.info("Connecting to RabbitMQ") + + val connection = ConnectionFactory().newConnection(url) + + channel = connection.createChannel() + val queue = channel.queueDeclare().queue + + val consumers = hashMapOf Unit>>() + loadConsumers { topic, consumer -> + channel.queueBind(queue, EXCHANGE_KEY, topic) + consumers.getOrPut(topic, ::arrayListOf).add(consumer) + } + + channel.basicConsume(queue, true, { _, message -> + val routingKey = message.envelope.routingKey + consumers[routingKey]?.forEach { + it(message.body) + } + }, { _ -> }) + } + + fun close() { + channel.connection.close() + } + + fun publish(routingKey: String, bytes: ByteArray) { + channel.basicPublish(EXCHANGE_KEY, routingKey, null, bytes) + } + + private fun loadConsumers(consume: (String, (ByteArray) -> Unit) -> Unit) { + val annotations = ModList.get().allScanData + .flatMap { it.annotations } + .filter { it.annotationType == Type.getType(SubscribeMessage::class.java) } + .filter { it.targetType == ElementType.METHOD } + .groupBy { it.clazz } + .mapKeys { Class.forName(it.key.className).kotlin } + + annotations.forEach { (clazz) -> + clazz.memberFunctions + .filter { it.hasAnnotation() } + .forEach { method -> + val messageType = method.parameters.first { it.kind == KParameter.Kind.VALUE }.type + val topic = Class.forName(messageType.toString()).simpleName + val deserializer = serializer(messageType) + + if (method.parameters.size != 2) { + throw IllegalArgumentException("@SubscribeMessage handlers may only accept one parameter, the message itself") + } + + consume(topic) { + val message = AtheneumConnector.JSON.decodeFromString(deserializer, it.decodeToString()) + method.call(clazz.objectInstance, message) + } + } + } + } + +} + +@OptIn(InternalSerializationApi::class) +inline fun RabbitMQ.publish(message: T, routingKey: String = T::class.simpleName!!) { + val serializer = T::class.serializer() + val bytes = AtheneumConnector.JSON.encodeToString(serializer, message).toByteArray() + + publish(routingKey, bytes) +} \ No newline at end of file diff --git a/src/main/kotlin/com/possible_triangle/atheneum_connector/SubscribeMessage.kt b/src/main/kotlin/com/possible_triangle/atheneum_connector/SubscribeMessage.kt new file mode 100644 index 0000000..fa85f9b --- /dev/null +++ b/src/main/kotlin/com/possible_triangle/atheneum_connector/SubscribeMessage.kt @@ -0,0 +1,4 @@ +package com.possible_triangle.atheneum_connector + +@Target(AnnotationTarget.FUNCTION) +annotation class SubscribeMessage diff --git a/src/main/kotlin/com/possible_triangle/atheneum_connector/consumers/LocationsConsumer.kt b/src/main/kotlin/com/possible_triangle/atheneum_connector/consumers/LocationsConsumer.kt new file mode 100644 index 0000000..b86bba0 --- /dev/null +++ b/src/main/kotlin/com/possible_triangle/atheneum_connector/consumers/LocationsConsumer.kt @@ -0,0 +1,14 @@ +package com.possible_triangle.atheneum_connector.consumers + +import com.possible_triangle.atheneum_connector.AtheneumConnector +import com.possible_triangle.atheneum_connector.SubscribeMessage +import com.possible_triangle.atheneum_connector.messages.CreatedPlaceMessage + +object LocationsConsumer { + + @SubscribeMessage + fun onPlaceCreate(message: CreatedPlaceMessage) { + AtheneumConnector.LOG.info("new place with id {} has been created", message.placeId) + } + +} \ No newline at end of file diff --git a/src/main/kotlin/com/possible_triangle/atheneum_connector/events/PlayerEvents.kt b/src/main/kotlin/com/possible_triangle/atheneum_connector/events/PlayerEvents.kt new file mode 100644 index 0000000..2716d89 --- /dev/null +++ b/src/main/kotlin/com/possible_triangle/atheneum_connector/events/PlayerEvents.kt @@ -0,0 +1,39 @@ +package com.possible_triangle.atheneum_connector.events + +import com.possible_triangle.atheneum_connector.LocationCache +import com.possible_triangle.atheneum_connector.RabbitMQ +import com.possible_triangle.atheneum_connector.messages.PlayerMoveMessage +import com.possible_triangle.atheneum_connector.network.DisplayTitlePaket +import com.possible_triangle.atheneum_connector.network.Network +import com.possible_triangle.atheneum_connector.publish +import net.minecraft.network.chat.Component +import net.minecraft.server.level.ServerPlayer +import net.minecraftforge.api.distmarker.Dist +import net.minecraftforge.event.TickEvent.PlayerTickEvent +import net.minecraftforge.eventbus.api.SubscribeEvent +import net.minecraftforge.fml.common.Mod.EventBusSubscriber + +@EventBusSubscriber(Dist.DEDICATED_SERVER) +object PlayerEvents { + + @SubscribeEvent + fun onPlayerTick(event: PlayerTickEvent) { + val player = event.player as ServerPlayer + val level = player.level() + + if (level.gameTime % 20 != 0L) return + + RabbitMQ.publish(PlayerMoveMessage.from(player)) + + val location = LocationCache.containing(level.dimension(), player.onPos) ?: return + + location.ifLeft { + Network.sendTo(player, DisplayTitlePaket(Component.literal("You entered ${it.name}"), "area-${it.id}")) + } + + location.ifRight { + Network.sendTo(player, DisplayTitlePaket(Component.literal("You are close to ${it.name}"), "place-${it.id}")) + } + } + +} \ No newline at end of file diff --git a/src/main/kotlin/com/possible_triangle/atheneum_connector/messages/CreatedPlaceMessage.kt b/src/main/kotlin/com/possible_triangle/atheneum_connector/messages/CreatedPlaceMessage.kt new file mode 100644 index 0000000..555d95a --- /dev/null +++ b/src/main/kotlin/com/possible_triangle/atheneum_connector/messages/CreatedPlaceMessage.kt @@ -0,0 +1,6 @@ +package com.possible_triangle.atheneum_connector.messages + +import kotlinx.serialization.Serializable + +@Serializable +data class CreatedPlaceMessage(val placeId: Int) \ No newline at end of file diff --git a/src/main/kotlin/com/possible_triangle/atheneum_connector/messages/PlayerMoveMessage.kt b/src/main/kotlin/com/possible_triangle/atheneum_connector/messages/PlayerMoveMessage.kt new file mode 100644 index 0000000..0559cdb --- /dev/null +++ b/src/main/kotlin/com/possible_triangle/atheneum_connector/messages/PlayerMoveMessage.kt @@ -0,0 +1,21 @@ +package com.possible_triangle.atheneum_connector.messages + +import com.possible_triangle.atheneum_connector.generated.areas.Point +import kotlinx.serialization.Serializable +import net.minecraft.world.entity.player.Player + +@Serializable +data class PlayerMoveMessage( + val player: String, + val pos: Point, +) { + companion object { + fun from(player: Player) = PlayerMoveMessage( + player.uuid.toString(), + Point( + player.blockX, player.blockY, player.blockZ, + player.level().dimension().location().path, + ) + ) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/possible_triangle/atheneum_connector/network/DisplayTitlePaket.kt b/src/main/kotlin/com/possible_triangle/atheneum_connector/network/DisplayTitlePaket.kt new file mode 100644 index 0000000..d288e4b --- /dev/null +++ b/src/main/kotlin/com/possible_triangle/atheneum_connector/network/DisplayTitlePaket.kt @@ -0,0 +1,30 @@ +package com.possible_triangle.atheneum_connector.network + +import com.possible_triangle.atheneum_connector.titles.TitlesCompat +import net.minecraft.network.FriendlyByteBuf +import net.minecraft.network.chat.Component +import net.minecraftforge.network.NetworkEvent +import java.util.function.Supplier + +data class DisplayTitlePaket(val component: Component, val id: String) { + + fun encode(buf: FriendlyByteBuf) { + buf.writeComponent(component) + buf.writeUtf(id) + } + + fun handle(contextSupplier: Supplier) { + val context = contextSupplier.get() + + context.enqueueWork { + TitlesCompat.setTitle(this) + } + + context.packetHandled = true + } + + companion object { + fun decode(buf: FriendlyByteBuf) = DisplayTitlePaket(buf.readComponent(), buf.readUtf()) + } + +} diff --git a/src/main/kotlin/com/possible_triangle/atheneum_connector/network/Network.kt b/src/main/kotlin/com/possible_triangle/atheneum_connector/network/Network.kt new file mode 100644 index 0000000..bb76b18 --- /dev/null +++ b/src/main/kotlin/com/possible_triangle/atheneum_connector/network/Network.kt @@ -0,0 +1,30 @@ +package com.possible_triangle.atheneum_connector.network + +import net.minecraft.resources.ResourceLocation +import net.minecraft.server.level.ServerPlayer +import net.minecraftforge.fml.common.Mod.EventBusSubscriber +import net.minecraftforge.network.NetworkRegistry +import net.minecraftforge.network.PacketDistributor + +@Suppress("INACCESSIBLE_TYPE") +@EventBusSubscriber +object Network { + + private const val VERSION = "1.0" + + private val CHANNEL = NetworkRegistry.newSimpleChannel( + ResourceLocation("arva", "atheneum_connector"), + { VERSION }, + VERSION::equals, + VERSION::equals, + ) + + fun sendTo(player: ServerPlayer, packet: Any) { + CHANNEL.send(PacketDistributor.PLAYER.with { player }, packet) + } + + init { + CHANNEL.registerMessage(0, DisplayTitlePaket::class.java, DisplayTitlePaket::encode, DisplayTitlePaket::decode, DisplayTitlePaket::handle) + } + +} \ No newline at end of file diff --git a/src/main/kotlin/com/possible_triangle/atheneum_connector/titles/TitlesCompat.kt b/src/main/kotlin/com/possible_triangle/atheneum_connector/titles/TitlesCompat.kt new file mode 100644 index 0000000..9026f99 --- /dev/null +++ b/src/main/kotlin/com/possible_triangle/atheneum_connector/titles/TitlesCompat.kt @@ -0,0 +1,51 @@ +package com.possible_triangle.atheneum_connector.titles + +import com.possible_triangle.atheneum_connector.network.DisplayTitlePaket +import com.yungnickyoung.minecraft.travelerstitles.TravelersTitlesCommon +import com.yungnickyoung.minecraft.travelerstitles.render.TitleRenderer +import net.minecraft.client.Minecraft +import net.minecraftforge.api.distmarker.Dist +import net.minecraftforge.client.event.RenderGuiEvent +import net.minecraftforge.event.TickEvent.ClientTickEvent +import net.minecraftforge.eventbus.api.SubscribeEvent +import net.minecraftforge.fml.common.Mod.EventBusSubscriber + +@EventBusSubscriber(Dist.CLIENT) +object TitlesCompat { + + private val RENDERER: TitleRenderer = TitleRenderer( + 1, + TravelersTitlesCommon.CONFIG.waystones.enabled, + TravelersTitlesCommon.CONFIG.waystones.textFadeInTime, + TravelersTitlesCommon.CONFIG.waystones.textDisplayTime, + TravelersTitlesCommon.CONFIG.waystones.textFadeOutTime, + TravelersTitlesCommon.CONFIG.waystones.textColor, + TravelersTitlesCommon.CONFIG.waystones.renderShadow, + TravelersTitlesCommon.CONFIG.waystones.textSize, + TravelersTitlesCommon.CONFIG.waystones.textXOffset, + TravelersTitlesCommon.CONFIG.waystones.textYOffset, + TravelersTitlesCommon.CONFIG.waystones.centerText + ) + + @SubscribeEvent + fun clientTick(event: ClientTickEvent) { + if (!Minecraft.getInstance().isPaused) { + RENDERER.tick() + } + } + + @SubscribeEvent + fun renderTitles(event: RenderGuiEvent.Pre) { + if (!Minecraft.getInstance().options.renderDebug) { + RENDERER.renderText(event.partialTick, event.guiGraphics) + } + } + + fun setTitle(packet: DisplayTitlePaket) { + if (!RENDERER.matchesAnyRecentEntry { it.id == packet.id }) { + RENDERER.displayTitle(packet.component, null) + RENDERER.addRecentEntry(packet) + } + } + +} \ No newline at end of file diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml new file mode 100644 index 0000000..ee11eba --- /dev/null +++ b/src/main/resources/META-INF/mods.toml @@ -0,0 +1,33 @@ +modLoader="kotlinforforge" +loaderVersion="[4.10,)" +license = "https://github.com/${repository}/blob/main/LICENSE.txt" +issueTrackerURL = "https://github.com/${repository}/issues" + +[[mods]] +modId = "${mod_id}" +version = "${mod_version}" +displayName = "${mod_name}" +authors = "${mod_author}" +description = '''exposes and consumes messages from the atheneum backend''' +updateJSONURL = "https://api.modrinth.com/updates/atheneum-connector/forge_updates.json" + +[[dependencies.${mod_id}]] + modId = "forge" + mandatory = true + versionRange = "[4,)" + ordering = "NONE" + side = "BOTH" + +[[dependencies.${mod_id}]] + modId = "minecraft" + mandatory = true + versionRange = "[1.20.1,)" + ordering = "NONE" + side = "BOTH" + +[[dependencies.${mod_id}]] + modId="kotlinforforge" + mandatory=true + versionRange="[4.3.0,)" + ordering="NONE" + side="BOTH" diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta new file mode 100644 index 0000000..496b51a --- /dev/null +++ b/src/main/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "description": "${mod_name} resources", + "pack_format": 6 + } +} diff --git a/src/main/resources/queries/areas.graphql b/src/main/resources/queries/areas.graphql new file mode 100644 index 0000000..e3f3df7 --- /dev/null +++ b/src/main/resources/queries/areas.graphql @@ -0,0 +1,15 @@ +query areasQuery { + areas { + nodes { + id + name + world + minY + maxY + points { + x, + z + } + } + } +} \ No newline at end of file diff --git a/src/main/resources/queries/places.graphql b/src/main/resources/queries/places.graphql new file mode 100644 index 0000000..b89d44a --- /dev/null +++ b/src/main/resources/queries/places.graphql @@ -0,0 +1,14 @@ +query placesQuery { + places { + nodes { + id + name + pos { + x, + y, + z, + world + } + } + } +} \ No newline at end of file