diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml deleted file mode 100644 index 215629f..0000000 --- a/.github/FUNDING.yml +++ /dev/null @@ -1,12 +0,0 @@ -# These are supported funding model platforms - -github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -custom: ['https://money.yandex.ru/to/410015993365458', 'https://paypal.me/mairwunnx'] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 128a543..0000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve -title: '' -labels: waiting issue review -assignees: '' - ---- - -### Description of the problem - -### Steps to reproduce this problem - -### Expected behavior - -### Additional materials - -### Environment information - -### Your comment. - -### Log files. (latest.log and debug.log file in attachment) diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index a30d13f..0000000 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project -title: '' -labels: feature request -assignees: '' - ---- - -### Is your feature request related to a problem? Please describe. -> - A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -### Describe the solution you'd like -> - A clear and concise description of what you want to happen. - -### Describe alternatives you've considered -> - A clear and concise description of any alternative solutions or features you've considered. - -### Additional context -> - Add any other context or screenshots about the feature request here. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index a6e72bb..0000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,21 +0,0 @@ -## Description - -Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. - -Fixes # (issue) - -# How Has This Been Tested? - -Please describe the tests that you ran to verify your changes. Please also note any relevant details for your test configuration. - -- [ ] Test A -- [ ] Test B - -# Checklist: - -- [ ] My code follows the style guidelines of this project -- [ ] I have performed a self-review of my own code -- [ ] I have commented my code, particularly in hard-to-understand areas -- [ ] I have made corresponding changes to the documentation -- [ ] My changes generate no new warnings -- [ ] Any dependent changes have been merged and published in downstream modules diff --git a/build.gradle b/build.gradle index fd03d91..efd4ff3 100644 --- a/build.gradle +++ b/build.gradle @@ -1,143 +1,89 @@ buildscript { - repositories { - maven { url 'https://files.minecraftforge.net/maven' } - } - dependencies { - classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '3.+', changing: true - } + repositories { jcenter() } + dependencies { classpath 'org.koin:koin-gradle-plugin:2.2.1' } } plugins { - id 'org.jetbrains.kotlin.jvm' version '1.3.72' - id 'org.jetbrains.kotlin.plugin.serialization' version '1.3.72' - id 'org.jetbrains.dokka' version '0.10.1' - id 'maven-publish' - id 'java-library' -} - -apply plugin: 'net.minecraftforge.gradle' - -String packagesToken = new String(package_public_token.decodeBase64()) - -version = module_version -group = "com.projectessentials.core" -archivesBaseName = module_name - -configurations { - internal - implementation.extendsFrom internal + id 'org.jetbrains.kotlin.jvm' version '1.4.21' apply false + id 'org.jetbrains.kotlin.plugin.serialization' version '1.4.21' + id 'io.gitlab.arturbosch.detekt' version '1.15.0-RC1' + id 'org.jlleitschuh.gradle.ktlint' version '9.4.1' + id 'org.jetbrains.dokka' version '1.4.20' } -minecraft { - accessTransformer = file 'src/main/resources/META-INF/accesstransformer.cfg' - mappings channel: forge_mappings_channel_type, version: forge_mappings_channel_version -} +allprojects { + apply plugin: 'java' + apply plugin: 'org.jetbrains.kotlin.plugin.serialization' + apply plugin: 'io.gitlab.arturbosch.detekt' + apply plugin: 'org.jlleitschuh.gradle.ktlint' + apply plugin: 'koin' -repositories { - maven { url 'https://libraries.minecraft.net' } - mavenCentral() - jcenter() -} + group = dist_group + version = dist_version + archivesBaseName = "Project Essentials ${dist_module_name.capitalize()}" -dependencies { - minecraft "net.minecraftforge:forge:$forge_version" - internal "org.jetbrains.kotlinx:kotlinx-serialization-runtime:$kotlinx_serialization_version" - internal "org.jetbrains.kotlin:kotlin-stdlib-$kotlin_jdk_version_target:$kotlin_version" - internal "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinx_coroutines_version" - internal "org.json:json:$json_version" -} - -dokka { - outputFormat = 'html' - outputDirectory = "$buildDir/libs/docs" -} - -task sourcesJar(type: Jar) { - classifier = 'sources' - from sourceSets.main.allSource -} - -task dokkaJar(type: Jar) { - group = JavaBasePlugin.DOCUMENTATION_GROUP - classifier = 'javadoc' - from tasks.dokka as Object -} - -task modJar(type: Jar) { - with tasks.jar - from configurations.internal.collect { it.isDirectory() ? it : zipTree(it) } - - manifest { - attributes([ - "Specification-Title" : module_name, - "Specification-Vendor" : module_version, - "Specification-Version" : module_vendor, - "Implementation-Title" : module_name, - "Implementation-Version" : module_version, - "Implementation-Vendor" : module_vendor, - "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") - ]) + configurations { + internal + implementation.extendsFrom internal } - baseName = module_name + '-MOD' -} - -jar { - manifest { - attributes([ - "Specification-Title" : module_name, - "Specification-Vendor" : module_vendor, - "Specification-Version" : module_version, - "Implementation-Title" : module_name, - "Implementation-Version" : module_version, - "Implementation-Vendor" : module_vendor, - "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") - ]) + repositories { + mavenCentral() + jcenter() + maven { url 'https://kotlin.bintray.com/kotlinx/' } } - baseName = module_name + '-NoRT' -} - -reobf { - modJar { - dependsOn jar - mappings = createMcpToSrg.outputs.files.singleFile + dependencies { + internal 'org.jetbrains.kotlin:kotlin-stdlib:1.4.21' + internal 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2' + internal 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.0.1' + internal 'org.jetbrains.kotlinx:kotlinx-datetime:0.1.1' + internal 'org.koin:koin-core:2.1.6' + testImplementation 'org.koin:koin-test:2.1.6' + testImplementation 'io.kotest:kotest-runner-junit5-jvm:4.3.1' + testImplementation 'io.kotest:kotest-assertions-core-jvm:4.3.1' + testImplementation 'io.kotest:kotest-property-jvm:4.3.1' + testImplementation 'org.jetbrains.kotlin:kotlin-test-junit5' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.0' } -} -project.tasks['jar'].dependsOn project.tasks['dokka'] -project.tasks['modJar'].dependsOn project.tasks['jar'] - -sourceCompatibility = targetCompatibility = - compileJava.sourceCompatibility = - compileJava.targetCompatibility = project_jvm_version_target - -compileKotlin.kotlinOptions.jvmTarget = - compileTestKotlin.kotlinOptions.jvmTarget = project_jvm_version_target - -publishing { - repositories { - maven { - name = 'GitHubPackages' - url = uri 'https://maven.pkg.github.com/projectessentials/projectessentials-core' - credentials { - username = System.getenv('GradleUser') - password = System.getenv('GradlePass') + test { useJUnitPlatform() } + + detekt { + toolVersion = '1.12.0' + input = files 'src/main/kotlin', 'gensrc/main/kotlin' + config = files '../config/detekt/detekt.yml' + parallel = true + buildUponDefaultConfig = true + disableDefaultRuleSets = false + debug = false + ignoreFailures = false + reports { + html { + enabled = true + destination = file 'build/reports/detekt.html' } } } - publications { - gpr(MavenPublication) { - version = (module_version as String).split('\\+')[0] - from components.java - artifact sourcesJar - artifact dokkaJar + + ktlint { + outputColorName = 'GREEN' + enableExperimentalRules = true + additionalEditorconfigFile = file('..\\.editorconfig') + filter { + exclude '**/generated/**' + include '**/kotlin/**' } } -} -tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { - kotlinOptions { - freeCompilerArgs += '-Xopt-in=kotlin.RequiresOptIn' + sourceCompatibility = targetCompatibility = + compileJava.sourceCompatibility = + compileJava.targetCompatibility = '1.8' + + tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { + kotlinOptions { + freeCompilerArgs += '-Xopt-in=kotlin.RequiresOptIn' + } } } diff --git a/buzzy-bees/build.gradle b/buzzy-bees/build.gradle new file mode 100644 index 0000000..b824cb3 --- /dev/null +++ b/buzzy-bees/build.gradle @@ -0,0 +1,18 @@ +plugins { + id 'org.jetbrains.kotlin.jvm' +} + +group = 'com.projectessentials' +version = '1.0.0-SNAPSHOT.1' + +dependencies { + implementation project(':common') +} + +compileKotlin { + kotlinOptions.jvmTarget = '1.8' +} + +compileTestKotlin { + kotlinOptions.jvmTarget = '1.8' +} diff --git a/codestyle-git-hook.sh b/codestyle-git-hook.sh new file mode 100644 index 0000000..6ee73a9 --- /dev/null +++ b/codestyle-git-hook.sh @@ -0,0 +1,38 @@ +#!/bin/bash +file_location=.git/hooks/pre-commit + +cat >$file_location < \$OUTPUT +EXIT_CODE=\$? +if [ \$EXIT_CODE -ne 0 ]; then + cat \$OUTPUT + rm \$OUTPUT + echo "***********************************************" + echo " Detekt failed " + echo " Please fix the above issues before committing " + echo "***********************************************" + exit \$EXIT_CODE +fi +rm \$OUTPUT +EOF diff --git a/common/build.gradle b/common/build.gradle new file mode 100644 index 0000000..8f23448 --- /dev/null +++ b/common/build.gradle @@ -0,0 +1,6 @@ +plugins { + id 'org.jetbrains.kotlin.jvm' +} + +apply plugin: 'org.jetbrains.dokka' + diff --git a/common/src/main/kotlin/com/projectessentials/core/Json.kt b/common/src/main/kotlin/com/projectessentials/core/Json.kt new file mode 100644 index 0000000..6019daa --- /dev/null +++ b/common/src/main/kotlin/com/projectessentials/core/Json.kt @@ -0,0 +1,13 @@ +package com.projectessentials.core + +import kotlinx.serialization.json.Json + +val json = Json { + encodeDefaults = true + ignoreUnknownKeys = true + isLenient = false + allowSpecialFloatingPointValues = true + allowStructuredMapKeys = true + prettyPrint = true + useArrayPolymorphism = false +} diff --git a/common/src/main/kotlin/com/projectessentials/core/Meta.kt b/common/src/main/kotlin/com/projectessentials/core/Meta.kt new file mode 100644 index 0000000..f98a2c2 --- /dev/null +++ b/common/src/main/kotlin/com/projectessentials/core/Meta.kt @@ -0,0 +1,51 @@ +@file:Suppress("NOTHING_TO_INLINE") + +package com.projectessentials.core + +import java.lang.reflect.Field + +/** + * Return the version of this implementation. It consists of + * any string assigned by the vendor of this implementation + * and does not have any particular syntax specified or expected + * by the Java runtime. It may be compared for equality with + * other package version strings used for this implementation + * by this vendor for this package. + * + * @since 3.0.0 + * @receiver Class<*> any java class as receiver. + * @return implementation version, represented as single integer, + * if it's null returns `-1`. + */ +inline fun T.implVersion() = + this!!::class.java.`package`.implementationVersion?.toIntOrNull() ?: -1 + +/** + * Return the title of this package. + * + * @since 3.0.0 + * @receiver Class<*> any java class as receiver. + * @return implementation name, represented as string, if it's + * null returns `unknown`. + */ +inline fun T.implName() = this!!::class.java.`package`.implementationTitle ?: "unknown" + +/** + * Return the fields of class passed in generic to this + * method. + * + * @since 3.0.0 + * @receiver `Class<*>` any java class as receiver. + * @return immutable list of [Field] object. + */ +@OptIn(ExperimentalStdlibApi::class) +inline fun T.fields(): List { + buildList { + var c: Class<*>? = this::class.java + while (c != null) { + addAll(c.declaredFields) + c = c.superclass + } + return this + } +} diff --git a/common/src/main/kotlin/com/projectessentials/core/Reloadable.kt b/common/src/main/kotlin/com/projectessentials/core/Reloadable.kt new file mode 100644 index 0000000..d53bde0 --- /dev/null +++ b/common/src/main/kotlin/com/projectessentials/core/Reloadable.kt @@ -0,0 +1,17 @@ +package com.projectessentials.core + +/** + * Implementation contract marks the object + * is reloadable, and contains one [reload] + * method. + * + * @since 3.0.0 + */ +interface Reloadable { + /** + * Performs reload action for this object. + * + * @since 3.0.0 + */ + fun reload() +} diff --git a/common/src/main/kotlin/com/projectessentials/core/module/Module.kt b/common/src/main/kotlin/com/projectessentials/core/module/Module.kt new file mode 100644 index 0000000..be193fa --- /dev/null +++ b/common/src/main/kotlin/com/projectessentials/core/module/Module.kt @@ -0,0 +1,28 @@ +package com.projectessentials.core.module + +import com.projectessentials.core.Reloadable + +/** + * Implementation contract of Project Essentials + * modules. + * + * @property id id of the module separated by underscores. + * @property priority priority of module for loading. + * @property version version of the module represented as + * incremental integer number. + * @since 3.0.0 + */ +interface Module : Reloadable { + val id: String + val priority: Int + val version: Int + + /** + * Will called when module will ready to use + * other objects of mod loader platform and + * other configurations, this will called asynchronously. + * + * @since 3.0.0 + */ + suspend fun initialize() +} diff --git a/common/src/test/kotlin/com/projectessentials/core/MetaKtTest.kt b/common/src/test/kotlin/com/projectessentials/core/MetaKtTest.kt new file mode 100644 index 0000000..73953d4 --- /dev/null +++ b/common/src/test/kotlin/com/projectessentials/core/MetaKtTest.kt @@ -0,0 +1,14 @@ +package com.projectessentials.core + +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.shouldBe + +class MetaKtTest : FunSpec({ + test("implVersion") { + implVersion().shouldBe(-1) + } + + test("implName") { + implName().shouldBe("unknown") + } +}) diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml new file mode 100644 index 0000000..4261ff5 --- /dev/null +++ b/config/detekt/detekt.yml @@ -0,0 +1,3 @@ +complexity: + LongParameterList: + ignoreDefaultParameters: true diff --git a/gradle.properties b/gradle.properties index dd083fb..7619c5c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,29 +1,7 @@ -# Gradle settings. -org.gradle.jvmargs=-Xmx3G -org.gradle.daemon=false -org.gradle.caching=true -# Forge mappings channel type and version. -forge_mappings_channel_type=snapshot -forge_mappings_channel_version=20190719-1.14.3 -# Forge dependencies. -forge_version=1.14.4-28.2.0 -brigadier_version=1.0.17 -# Project compatibility settings. -kotlin_jdk_version_target=jdk8 -project_jvm_version_target=1.8 kotlin.code.style=official -# Project external dependencies. -kotlin_version=1.3.72 -kotlinx_serialization_version=0.20.0 -kotlinx_coroutines_version=1.3.7 -json_version=20190722 -# Module informatation. -module_version=2.1.0+MC-1.14.4 -module_name=Project Essentials Core -module_id=project_essentials_core -module_vendor=MairwunNx (Pavel Erokhin) -# Public packages information for getting other dependencies. -package_public_token=ZDhjMjgyNjlhM2E0ZTQ0MmM2Mjk5ZWI4YmMyZjI0YzNjOTNkMDVkZA== -package_maven_repo=https://maven.pkg.github.com/projectessentials/projectessentials -package_maven_repo_name=GitHubPackages -package_maven_repo_mail=MairwunNx@gmail.com +org.gradle.parallel=true +org.gradle.vfs.watch=true +org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 +dist_version=3.0.0-SNAPSHOT.1 +dist_group=com.projectessentials.core +dist_module_name=core diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 5c2d1cf..e708b1c 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 5028f28..12d38de 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 83f2acf..4f906e0 100644 --- a/gradlew +++ b/gradlew @@ -82,6 +82,7 @@ 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 @@ -129,6 +130,7 @@ fi if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath @@ -154,19 +156,19 @@ if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then else eval `echo args$i`="\"$arg\"" fi - i=$((i+1)) + i=`expr $i + 1` done case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi @@ -175,14 +177,9 @@ save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } -APP_ARGS=$(save "$@") +APP_ARGS=`save "$@"` # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 9618d8d..107acd3 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -29,6 +29,9 @@ if "%DIRNAME%" == "" set DIRNAME=. 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" @@ -37,7 +40,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -51,7 +54,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -61,28 +64,14 @@ echo location of your Java installation. goto fail -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - :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 %CMD_LINE_ARGS% +"%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 diff --git a/nether-update/build.gradle b/nether-update/build.gradle new file mode 100644 index 0000000..b824cb3 --- /dev/null +++ b/nether-update/build.gradle @@ -0,0 +1,18 @@ +plugins { + id 'org.jetbrains.kotlin.jvm' +} + +group = 'com.projectessentials' +version = '1.0.0-SNAPSHOT.1' + +dependencies { + implementation project(':common') +} + +compileKotlin { + kotlinOptions.jvmTarget = '1.8' +} + +compileTestKotlin { + kotlinOptions.jvmTarget = '1.8' +} diff --git a/readme.md b/readme.md index 0f70291..1fdf7fa 100644 --- a/readme.md +++ b/readme.md @@ -1,16 +1,15 @@ -### What is it +⚠ Project Essentials v3 under development ⚠ -Base module for all Project Essentials modules, API for creating modules of Project Essentials and reduce code duplication, also core module contains kotlin runtime and libraries. Also contains some settings for vanilla commands and events. +You can see any changed in commit history, when first snapshot v3 will ready, changes from this branch will merge in master branch. -### Explore +Now Project Essentials repository structure and project structure will change, all modules have a names related to minecraft update version and every module with minecraft version will have a two submodules contains implementation for different mod loaders, `forge` and `fabric` at now. -#### [Download mod](https://github.com/ProjectEssentials/ProjectEssentials-Core/releases/download/2.1.0%2BMC-1.14.4/Project.Essentials.Core-MOD-2.1.0+MC-1.14.4.jar) · [User guide](https://mairwunnx.gitbook.io/project-essentials/project-essentials-core#how-to-install) · [Developer documentation](https://mairwunnx.gitbook.io/project-essentials/project-essentials-core#using-as-api) · [Troubleshooting](https://github.com/ProjectEssentials/ProjectEssentials-Core/issues/new/choose) · [Telegram](https://t.me/minecraftforge) · [Discord](https://discord.gg/VU9XZAt) · [Change log](https://github.com/ProjectEssentials/ProjectEssentials-Core/blob/master/changelog.md) +Also, will change module system and improved API of every module, I'll make more easily installing a modules, directly in a chat, but it will restart the game anyway. -[![](https://github.com/ProjectEssentials/ProjectEssentials-Assets/raw/ASSETS-20-Q2/assets/common/support.png)](https://gist.github.com/MairwunNx/fda95062618db6880ef8ee06e1bba54f) +I'll fix my errors in structure, I'll improve memory using for your server feeling better when you have a many mods, and much of operations will be asynchronously. -### Credits +Also, will implement in-game update checking for much faster and easily updating process. -- `hujle` for testing this mod and almost all modules in production -- [JetBrains](https://www.jetbrains.com/) for product licenses -- Inspired by: [EssentialsX](https://github.com/EssentialsX) -- [KuroNoSeiHai](https://github.com/KuroNoSeiHai) for Chinese simplified translation +Little later, when v3 will release, I'll remove old 1.14.4\1.15.2 branches, and it will mark as deprecated. + +Thanks to `@hujle` for supporting me and makes motivation for me. diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..eb3fea5 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,14 @@ +pluginManagement { + repositories { + gradlePluginPortal() + jcenter() + } +} + +rootProject.name = 'ProjectEssentials-Core' + +include(':common') +include(':village-pillage') +include(':buzzy-bees') +include(':nether-update') + diff --git a/src/main/java/com/mairwunnx/projectessentials/core/impl/events/EventBridge.java b/src/main/java/com/mairwunnx/projectessentials/core/impl/events/EventBridge.java deleted file mode 100644 index 60007a3..0000000 --- a/src/main/java/com/mairwunnx/projectessentials/core/impl/events/EventBridge.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.mairwunnx.projectessentials.core.impl.events; - -import com.mairwunnx.projectessentials.core.api.v1.events.ModuleEventAPI; -import com.mairwunnx.projectessentials.core.api.v1.events.forge.*; -import net.minecraftforge.fml.event.lifecycle.*; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; - -public class EventBridge { - public static void initialize() { - FMLJavaModLoadingContext.get().getModEventBus().addListener(EventBridge::setup); - FMLJavaModLoadingContext.get().getModEventBus().addListener(EventBridge::enqueueIMC); - FMLJavaModLoadingContext.get().getModEventBus().addListener(EventBridge::processIMC); - FMLJavaModLoadingContext.get().getModEventBus().addListener(EventBridge::doClientStuff); - FMLJavaModLoadingContext.get().getModEventBus().addListener(EventBridge::complete); - } - - public static void setup(final FMLCommonSetupEvent event) { - ModuleEventAPI.INSTANCE.fire( - ForgeEventType.SetupEvent, new FMLCommonSetupEventData(event) - ); - } - - public static void doClientStuff(final FMLClientSetupEvent event) { - ModuleEventAPI.INSTANCE.fire( - ForgeEventType.DoClientStuffEvent, new FMLClientSetupEventData(event) - ); - } - - public static void enqueueIMC(final InterModEnqueueEvent event) { - ModuleEventAPI.INSTANCE.fire( - ForgeEventType.EnqueueIMCEvent, new InterModEnqueueEventData(event) - ); - } - - public static void processIMC(final InterModProcessEvent event) { - ModuleEventAPI.INSTANCE.fire( - ForgeEventType.ProcessIMCEvent, new InterModProcessEventData(event) - ); - } - - public static void complete(final FMLLoadCompleteEvent event) { - ModuleEventAPI.INSTANCE.fire( - ForgeEventType.LoadComplete, new LoadCompleteEventData(event) - ); - } -} diff --git a/src/main/java/com/mairwunnx/projectessentials/core/impl/vanilla/commands/TeleportCommand.java b/src/main/java/com/mairwunnx/projectessentials/core/impl/vanilla/commands/TeleportCommand.java deleted file mode 100644 index 1edb4b8..0000000 --- a/src/main/java/com/mairwunnx/projectessentials/core/impl/vanilla/commands/TeleportCommand.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * ! This command implementation by Mojang Studios! - * - * Decompiled with idea source code was converted to kotlin code. - * But with additions such as permissions checking and etc. - * - * 1. This can be bad code. - * 2. This file can be not formatter pretty. - */ -package com.mairwunnx.projectessentials.core.impl.vanilla.commands; - -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAPI; -import com.mairwunnx.projectessentials.core.api.v1.commands.back.BackLocationAPI; -import com.mojang.brigadier.CommandDispatcher; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.tree.LiteralCommandNode; -import net.minecraft.command.CommandSource; -import net.minecraft.command.Commands; -import net.minecraft.command.arguments.*; -import net.minecraft.entity.Entity; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.player.ServerPlayerEntity; -import net.minecraft.network.play.server.SPlayerPositionLookPacket; -import net.minecraft.util.math.*; -import net.minecraft.util.text.TranslationTextComponent; -import net.minecraft.world.server.ServerWorld; -import net.minecraft.world.server.TicketType; -import org.jetbrains.annotations.NotNull; - -import javax.annotation.Nullable; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.Set; - -public class TeleportCommand extends VanillaCommandBase { - public TeleportCommand() { - super("teleport"); - } - - @Override - public void register(@NotNull CommandDispatcher dispatcher) { - super.register(dispatcher); - CommandAPI.INSTANCE.removeCommand("tp"); - LiteralCommandNode literalcommandnode = dispatcher.register(Commands.literal("teleport").requires((p_198816_0_) -> { - return isAllowed(p_198816_0_, "teleport", 2); - }).then(Commands.argument("targets", EntityArgument.entities()).then(Commands.argument("location", Vec3Argument.vec3()).executes((p_198807_0_) -> { - return teleportToPos(p_198807_0_.getSource(), EntityArgument.getEntities(p_198807_0_, "targets"), p_198807_0_.getSource().getWorld(), Vec3Argument.getLocation(p_198807_0_, "location"), null, null); - }).then(Commands.argument("rotation", RotationArgument.rotation()).executes((p_198811_0_) -> { - return teleportToPos(p_198811_0_.getSource(), EntityArgument.getEntities(p_198811_0_, "targets"), p_198811_0_.getSource().getWorld(), Vec3Argument.getLocation(p_198811_0_, "location"), RotationArgument.getRotation(p_198811_0_, "rotation"), null); - })).then(Commands.literal("facing").then(Commands.literal("entity").then(Commands.argument("facingEntity", EntityArgument.entity()).executes((p_198806_0_) -> { - return teleportToPos(p_198806_0_.getSource(), EntityArgument.getEntities(p_198806_0_, "targets"), p_198806_0_.getSource().getWorld(), Vec3Argument.getLocation(p_198806_0_, "location"), null, new Facing(EntityArgument.getEntity(p_198806_0_, "facingEntity"), EntityAnchorArgument.Type.FEET)); - }).then(Commands.argument("facingAnchor", EntityAnchorArgument.entityAnchor()).executes((p_198812_0_) -> { - return teleportToPos(p_198812_0_.getSource(), EntityArgument.getEntities(p_198812_0_, "targets"), p_198812_0_.getSource().getWorld(), Vec3Argument.getLocation(p_198812_0_, "location"), null, new Facing(EntityArgument.getEntity(p_198812_0_, "facingEntity"), EntityAnchorArgument.getEntityAnchor(p_198812_0_, "facingAnchor"))); - })))).then(Commands.argument("facingLocation", Vec3Argument.vec3()).executes((p_198805_0_) -> { - return teleportToPos(p_198805_0_.getSource(), EntityArgument.getEntities(p_198805_0_, "targets"), p_198805_0_.getSource().getWorld(), Vec3Argument.getLocation(p_198805_0_, "location"), null, new Facing(Vec3Argument.getVec3(p_198805_0_, "facingLocation"))); - })))).then(Commands.argument("destination", EntityArgument.entity()).executes((p_198814_0_) -> { - return teleportToEntity(p_198814_0_.getSource(), EntityArgument.getEntities(p_198814_0_, "targets"), EntityArgument.getEntity(p_198814_0_, "destination")); - }))).then(Commands.argument("location", Vec3Argument.vec3()).executes((p_200560_0_) -> { - return teleportToPos(p_200560_0_.getSource(), Collections.singleton(p_200560_0_.getSource().assertIsEntity()), p_200560_0_.getSource().getWorld(), Vec3Argument.getLocation(p_200560_0_, "location"), LocationInput.current(), null); - })).then(Commands.argument("destination", EntityArgument.entity()).executes((p_200562_0_) -> { - return teleportToEntity(p_200562_0_.getSource(), Collections.singleton(p_200562_0_.getSource().assertIsEntity()), EntityArgument.getEntity(p_200562_0_, "destination")); - }))); - dispatcher.register(Commands.literal("tp").requires((it) -> isAllowed(it, "teleport", 2)).redirect(literalcommandnode)); - } - - private static int teleportToEntity(CommandSource source, Collection targets, Entity destination) { - commitBack(source); - return net.minecraft.command.impl.TeleportCommand.teleportToEntity(source, targets, destination); - } - - private static int teleportToPos(CommandSource source, Collection targets, ServerWorld worldIn, ILocationArgument position, @Nullable ILocationArgument rotationIn, @Nullable Facing facing) { - commitBack(source); - Vec3d vec3d = position.getPosition(source); - Vec2f vec2f = rotationIn == null ? null : rotationIn.getRotation(source); - Set set = EnumSet.noneOf(SPlayerPositionLookPacket.Flags.class); - if (position.isXRelative()) { - set.add(SPlayerPositionLookPacket.Flags.X); - } - - if (position.isYRelative()) { - set.add(SPlayerPositionLookPacket.Flags.Y); - } - - if (position.isZRelative()) { - set.add(SPlayerPositionLookPacket.Flags.Z); - } - - if (rotationIn == null) { - set.add(SPlayerPositionLookPacket.Flags.X_ROT); - set.add(SPlayerPositionLookPacket.Flags.Y_ROT); - } else { - if (rotationIn.isXRelative()) { - set.add(SPlayerPositionLookPacket.Flags.X_ROT); - } - - if (rotationIn.isYRelative()) { - set.add(SPlayerPositionLookPacket.Flags.Y_ROT); - } - } - - for (Entity entity : targets) { - if (rotationIn == null) { - teleport(source, entity, worldIn, vec3d.x, vec3d.y, vec3d.z, set, entity.rotationYaw, entity.rotationPitch, facing); - } else { - teleport(source, entity, worldIn, vec3d.x, vec3d.y, vec3d.z, set, vec2f.y, vec2f.x, facing); - } - } - - if (targets.size() == 1) { - source.sendFeedback(new TranslationTextComponent("commands.teleport.success.location.single", targets.iterator().next().getDisplayName(), vec3d.x, vec3d.y, vec3d.z), true); - } else { - source.sendFeedback(new TranslationTextComponent("commands.teleport.success.location.multiple", targets.size(), vec3d.x, vec3d.y, vec3d.z), true); - } - - return targets.size(); - } - - public static void teleport(CommandSource source, Entity entityIn, ServerWorld worldIn, double x, double y, double z, Set relativeList, float yaw, float pitch, @Nullable Facing facing) { - if (entityIn instanceof ServerPlayerEntity) { - ChunkPos chunkpos = new ChunkPos(new BlockPos(x, y, z)); - worldIn.getChunkProvider().func_217228_a(TicketType.POST_TELEPORT, chunkpos, 1, entityIn.getEntityId()); - entityIn.stopRiding(); - if (((ServerPlayerEntity) entityIn).isSleeping()) { - ((ServerPlayerEntity) entityIn).wakeUpPlayer(true, true, false); - } - - if (worldIn == entityIn.world) { - ((ServerPlayerEntity) entityIn).connection.setPlayerLocation(x, y, z, yaw, pitch, relativeList); - } else { - ((ServerPlayerEntity) entityIn).teleport(worldIn, x, y, z, yaw, pitch); - } - - entityIn.setRotationYawHead(yaw); - } else { - float f1 = MathHelper.wrapDegrees(yaw); - float f = MathHelper.wrapDegrees(pitch); - f = MathHelper.clamp(f, -90.0F, 90.0F); - if (worldIn == entityIn.world) { - entityIn.setLocationAndAngles(x, y, z, f1, f); - entityIn.setRotationYawHead(f1); - } else { - entityIn.detach(); - entityIn.dimension = worldIn.dimension.getType(); - Entity entity = entityIn; - entityIn = entityIn.getType().create(worldIn); - if (entityIn == null) { - return; - } - - entityIn.copyDataFromOld(entity); - entityIn.setLocationAndAngles(x, y, z, f1, f); - entityIn.setRotationYawHead(f1); - worldIn.func_217460_e(entityIn); - } - } - - if (facing != null) { - facing.updateLook(source, entityIn); - } - - if (!(entityIn instanceof LivingEntity) || !((LivingEntity) entityIn).isElytraFlying()) { - entityIn.setMotion(entityIn.getMotion().mul(1.0D, 0.0D, 1.0D)); - entityIn.onGround = true; - } - - } - - static class Facing { - private final Vec3d position; - private final Entity entity; - private final EntityAnchorArgument.Type anchor; - - public Facing(Entity entityIn, EntityAnchorArgument.Type anchorIn) { - this.entity = entityIn; - this.anchor = anchorIn; - this.position = anchorIn.apply(entityIn); - } - - public Facing(Vec3d positionIn) { - this.entity = null; - this.position = positionIn; - this.anchor = null; - } - - public void updateLook(CommandSource source, Entity entityIn) { - if (this.entity != null) { - if (entityIn instanceof ServerPlayerEntity) { - ((ServerPlayerEntity) entityIn).lookAt(source.getEntityAnchorType(), this.entity, this.anchor); - } else { - entityIn.lookAt(source.getEntityAnchorType(), this.position); - } - } else { - entityIn.lookAt(source.getEntityAnchorType(), this.position); - } - } - } - - private static void commitBack(CommandSource source) { - try { - BackLocationAPI.INSTANCE.commit(source.asPlayer()); - } catch (CommandSyntaxException e) { - // Suppressed. Sorry. - } - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/EntryPoint.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/EntryPoint.kt deleted file mode 100644 index 34c6f8e..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/EntryPoint.kt +++ /dev/null @@ -1,105 +0,0 @@ -@file:Suppress("UNUSED_PARAMETER") - -package com.mairwunnx.projectessentials.core - -import com.mairwunnx.projectessentials.core.api.v1.IMCLocalizationMessage -import com.mairwunnx.projectessentials.core.api.v1.IMCProvidersMessage -import com.mairwunnx.projectessentials.core.api.v1.configuration.ConfigurationAPI -import com.mairwunnx.projectessentials.core.api.v1.events.ModuleEventAPI.subscribeOn -import com.mairwunnx.projectessentials.core.api.v1.events.forge.ForgeEventType -import com.mairwunnx.projectessentials.core.api.v1.events.forge.InterModProcessEventData -import com.mairwunnx.projectessentials.core.api.v1.localization.LocalizationAPI -import com.mairwunnx.projectessentials.core.api.v1.localizationMarker -import com.mairwunnx.projectessentials.core.api.v1.module.ModuleAPI -import com.mairwunnx.projectessentials.core.api.v1.providers.ProviderAPI -import com.mairwunnx.projectessentials.core.api.v1.providersMarker -import com.mairwunnx.projectessentials.core.impl.ModuleObject -import com.mairwunnx.projectessentials.core.impl.commands.BackLocationCommand -import com.mairwunnx.projectessentials.core.impl.commands.ConfigureEssentialsCommand -import com.mairwunnx.projectessentials.core.impl.configurations.GeneralConfiguration -import com.mairwunnx.projectessentials.core.impl.configurations.NativeMappingsConfiguration -import com.mairwunnx.projectessentials.core.impl.events.EventBridge -import net.minecraftforge.common.MinecraftForge.EVENT_BUS -import net.minecraftforge.eventbus.api.SubscribeEvent -import net.minecraftforge.fml.ModList -import net.minecraftforge.fml.common.Mod -import net.minecraftforge.fml.event.server.FMLServerAboutToStartEvent -import org.apache.logging.log4j.LogManager - -@Suppress("unused") -@Mod("project_essentials_core") -internal class EntryPoint { - private val logger = LogManager.getLogger() - - init { - EventBridge.initialize() - EVENT_BUS.register(this) - initProviders() - initLocalization() - subscribeEvents() - } - - @SubscribeEvent - fun onServerPreStart(event: FMLServerAboutToStartEvent) { - ConfigurationAPI.loadAll() - ModuleAPI.initializeOrdered() - } - - private fun subscribeEvents() { - subscribeOn( - ForgeEventType.ProcessIMCEvent - ) { event -> - processLocalizationRequest(event) - processProvidersRequest(event) - } - } - - private fun initProviders() { - listOf( - GeneralConfiguration::class.java, - NativeMappingsConfiguration::class.java, - ModuleObject::class.java, - BackLocationCommand::class.java, - ConfigureEssentialsCommand::class.java - ).forEach(ProviderAPI::addProvider) - } - - private fun initLocalization() { - LocalizationAPI.apply(this.javaClass) { - mutableListOf( - "/assets/projectessentialscore/lang/en_us.json", - "/assets/projectessentialscore/lang/ru_ru.json", - "/assets/projectessentialscore/lang/zh_cn.json" - ) - } - } - - private fun processLocalizationRequest(event: InterModProcessEventData) { - event.event.getIMCStream { method -> - method == IMCLocalizationMessage - }.also { stream -> - stream.forEach { message -> - val clazz = ModList.get().getModContainerById(message.modId).get().mod.javaClass - message.getMessageSupplier<() -> List>().get().also { - logger.debug( - localizationMarker, "Localization got from ${message.senderModId}" - ).run { LocalizationAPI.apply(clazz, it) } - } - } - } - } - - private fun processProvidersRequest(event: InterModProcessEventData) { - event.event.getIMCStream { method -> - method == IMCProvidersMessage - }.also { stream -> - stream.forEach { message -> - message.getMessageSupplier<() -> List>>().get().also { - logger.debug( - providersMarker, "Providers got from ${message.senderModId}" - ).run { it().forEach(ProviderAPI::addProvider) } - } - } - } - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/InternalConstants.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/InternalConstants.kt deleted file mode 100644 index fbd7b67..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/InternalConstants.kt +++ /dev/null @@ -1,62 +0,0 @@ -@file:Suppress("EXPERIMENTAL_UNSIGNED_LITERALS", "unused") - -package com.mairwunnx.projectessentials.core.api.v1 - -/** - * Configuration processor loading index order. - * @since 2.0.0-SNAPSHOT.1. - */ -const val CONFIGURATION_PROCESSOR_INDEX = 0 - -/** - * Module processor loading index order. - * @since 2.0.0-SNAPSHOT.1. - */ -const val MODULE_PROCESSOR_INDEX = 1 - -/** - * Localization processor loading index order. - * @since 2.0.0-SNAPSHOT.1. - */ -const val LOCALIZATION_PROCESSOR_INDEX = 2 - -/** - * Command processor loading index order. - * @since 2.0.0-SNAPSHOT.1. - */ -const val COMMAND_PROCESSOR_INDEX = 3 - -/** - * Initial fall back language, uses before - * configuration loading. - * @since 2.0.0-SNAPSHOT.1. - */ -const val INITIAL_FALLBACK_LANGUAGE = "en_us" - -/** - * Prefix for localized messages for core module. - * @since 2.0.0-SNAPSHOT.1. - */ -const val MESSAGE_CORE_PREFIX = "project_essentials_core" - -/** - * Prefix for localized messages for other modules. - * @since 2.0.0-SNAPSHOT.1. - */ -const val MESSAGE_MODULE_PREFIX = "project_essentials_" - -const val SETTING_LOC_ENABLED = "v2-localization-enabled" -const val SETTING_LOC_FALLBACK_LANG = "v2-localization-fallback-lang" -const val SETTING_DISABLE_SAFE_ENCHANT = "disable-safely-enchant-level" -const val SETTING_NATIVE_COMMAND_REPLACE = "enable-native-command-replace" -const val SETTING_NATIVE_COMMAND_REQUIRE_PREDICATE_REPLACE = - "enable-native-command-require-predicate-replace" -const val SETTING_NATIVE_COMMAND_ALIASES_REPLACE = "enable-native-command-aliases-replace" -const val SETTING_LOCATE_COMMAND_FIND_RADIUS = "locate-command-find-radius" -const val SETTING_DISABLE_PORTAL_SPAWNING = "disable-portal-spawning" -const val SETTING_DEOP_COMMAND_REMOVE_OP_PERM = "deop-command-remove-op-perm" -const val SETTING_LIST_MAX_ELEMENTS_IN_PAGE = "list-max-elements-in-page" -const val SETTING_ENABLE_CONSOLE_COLORS = "enable-console-colors" - -const val IMCLocalizationMessage = "localization-request" -const val IMCProvidersMessage = "providers-request" diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/InternalMarkers.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/InternalMarkers.kt deleted file mode 100644 index fea4ac8..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/InternalMarkers.kt +++ /dev/null @@ -1,6 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1 - -import org.apache.logging.log4j.MarkerManager - -val localizationMarker = MarkerManager.getMarker("L10N") -val providersMarker = MarkerManager.getMarker("PROVIDERS") diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/CommandAPI.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/CommandAPI.kt deleted file mode 100644 index a80a4b3..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/CommandAPI.kt +++ /dev/null @@ -1,283 +0,0 @@ -@file:Suppress("unused") - -package com.mairwunnx.projectessentials.core.api.v1.commands - -import com.mairwunnx.projectessentials.core.api.v1.events.ModuleEventAPI -import com.mairwunnx.projectessentials.core.api.v1.events.internal.CommandEventData -import com.mairwunnx.projectessentials.core.api.v1.events.internal.ModuleCoreEventType -import com.mairwunnx.projectessentials.core.api.v1.providers.ProviderAPI -import com.mairwunnx.projectessentials.core.api.v1.providers.ProviderType -import com.mojang.brigadier.CommandDispatcher -import com.mojang.brigadier.arguments.BoolArgumentType -import com.mojang.brigadier.arguments.IntegerArgumentType -import com.mojang.brigadier.arguments.StringArgumentType -import com.mojang.brigadier.context.CommandContext -import net.minecraft.command.CommandSource -import net.minecraft.command.arguments.EntityArgument -import net.minecraft.entity.Entity -import net.minecraft.entity.player.ServerPlayerEntity -import org.apache.logging.log4j.LogManager - -/** - * Class for interacting with command api. - * @since 2.0.0-SNAPSHOT.1. - */ -object CommandAPI { - private val logger = LogManager.getLogger() - private var commands = listOf() - - private lateinit var dispatcher: CommandDispatcher - private var dispatcherAssigned = false - - /** - * Assign dispatcher for command registering. - * @param dispatcher command dispatcher. - * @since 2.0.0-SNAPSHOT.1. - */ - fun assignDispatcher( - dispatcher: CommandDispatcher - ) { - if (!dispatcherAssigned) dispatcherAssigned = true - this.dispatcher = dispatcher - } - - /** - * @return server command dispatcher. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getDispatcher() = dispatcher - - /** - * @return true if dispatcher assigned. - * @since 2.0.0-SNAPSHOT.1. - */ - fun isAssignedDispatcher() = dispatcherAssigned - - /** - * @return all installed and checked commands. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getCommands() = commands - - /** - * Remove already registered command with - * specified name. - * @param command command name to remove without `/`. - * @return true if command removed, false otherwise. - * @since 2.0.0-SNAPSHOT.1. - */ - fun removeCommand(command: String) = - dispatcher.root.children.removeIf { it.name == command } - - /** - * @param context command context. - * @param argumentName argument name. - * @return true if string exist. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getStringExisting( - context: CommandContext, - argumentName: String - ): Boolean = try { - StringArgumentType.getString(context, argumentName) - true - } catch (_: IllegalArgumentException) { - false - } - - /** - * @param context command context. - * @param argumentName argument name. - * @return string from command. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getString( - context: CommandContext, - argumentName: String - ): String = StringArgumentType.getString(context, argumentName) - - /** - * @param context command context. - * @param argumentName argument name. - * @return true if int exist. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getIntExisting( - context: CommandContext, - argumentName: String - ): Boolean = try { - IntegerArgumentType.getInteger(context, argumentName) - true - } catch (_: IllegalArgumentException) { - false - } - - /** - * @param context command context. - * @param argumentName argument name. - * @return int from command. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getInt( - context: CommandContext, - argumentName: String - ): Int = IntegerArgumentType.getInteger(context, argumentName) - - /** - * @param context command context. - * @param argumentName argument name. - * @return true if bool exist. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getBoolExisting( - context: CommandContext, - argumentName: String - ): Boolean = try { - BoolArgumentType.getBool(context, argumentName) - true - } catch (_: IllegalArgumentException) { - false - } - - /** - * @param context command context. - * @param argumentName argument name. - * @return bool from command. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getBool( - context: CommandContext, - argumentName: String - ): Boolean = BoolArgumentType.getBool(context, argumentName) - - /** - * @param context command context. - * @param argumentName argument name. - * @return true if entity exist. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getEntityExisting( - context: CommandContext, - argumentName: String - ): Boolean = try { - EntityArgument.getEntity(context, argumentName) - true - } catch (_: IllegalArgumentException) { - false - } - - /** - * @param context command context. - * @param argumentName argument name. - * @return entity from command. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getEntity( - context: CommandContext, - argumentName: String - ): Entity = EntityArgument.getEntity(context, argumentName) - - /** - * @param context command context. - * @param argumentName argument name. - * @return true if entities exist. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getEntitiesExisting( - context: CommandContext, - argumentName: String - ): Boolean = try { - EntityArgument.getEntities(context, argumentName) - true - } catch (_: IllegalArgumentException) { - false - } - - /** - * @param context command context. - * @param argumentName argument name. - * @return entities from command. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getEntities( - context: CommandContext, - argumentName: String - ): MutableCollection = EntityArgument.getEntities(context, argumentName) - - /** - * @param context command context. - * @param argumentName argument name. - * @return true if player exist. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getPlayerExisting( - context: CommandContext, - argumentName: String - ): Boolean = try { - EntityArgument.getPlayer(context, argumentName) - true - } catch (_: IllegalArgumentException) { - false - } - - /** - * @param context command context. - * @param argumentName argument name. - * @return player from command. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getPlayer( - context: CommandContext, - argumentName: String - ): ServerPlayerEntity = EntityArgument.getPlayer(context, argumentName) - - /** - * @param context command context. - * @param argumentName argument name. - * @return true if players exist. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getPlayersExisting( - context: CommandContext, - argumentName: String - ): Boolean = try { - EntityArgument.getPlayers(context, argumentName) - true - } catch (_: IllegalArgumentException) { - false - } - - /** - * @param context command context. - * @param argumentName argument name. - * @return players from command. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getPlayers( - context: CommandContext, - argumentName: String - ): MutableCollection = EntityArgument.getPlayers(context, argumentName) - - internal fun registerAll() { - ProviderAPI.getProvidersByType(ProviderType.Command).forEach { - val clazz = it.getDeclaredField("INSTANCE").get(null) as ICommand - ModuleEventAPI.fire( - ModuleCoreEventType.OnCommandClassProcessing, CommandEventData(clazz) - ) - logger.debug( - "Command taken! ${clazz.javaClass.simpleName}, name: ${clazz.name}, aliases: ${clazz.aliases}" - ) - commands = commands + clazz - register(clazz) - ModuleEventAPI.fire( - ModuleCoreEventType.OnCommandClassProcessed, CommandEventData(clazz) - ) - } - } - - private fun register(command: ICommand) = - logger.info("Starting registering command ${command.name}").also { - command.initialize() - command.register(getDispatcher()) - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/CommandAliases.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/CommandAliases.kt deleted file mode 100644 index 0f0cc2b..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/CommandAliases.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.commands - -/** - * Command aliases basically for working with - * command cooldowns. - * - * @since 2.0.0-RC.2. - */ -object CommandAliases { - /** - * This stores all aliases, just add your alias here. - * - * Where `String` - command for aliases. - * - * Where `MutableList` - aliases of command. - * - * @since 2.0.0-RC.2. - */ - val aliases: HashMap> = hashMapOf() -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/CommandBase.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/CommandBase.kt deleted file mode 100644 index 64fccfb..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/CommandBase.kt +++ /dev/null @@ -1,91 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.commands - - -import com.mairwunnx.projectessentials.core.api.v1.extensions.playerName -import com.mairwunnx.projectessentials.core.api.v1.module.ModuleAPI -import com.mojang.brigadier.CommandDispatcher -import com.mojang.brigadier.builder.LiteralArgumentBuilder -import com.mojang.brigadier.context.CommandContext -import net.minecraft.command.CommandSource -import org.apache.logging.log4j.LogManager -import org.apache.logging.log4j.MarkerManager - -/** - * Base abstract class for commands. Has common - * logic for registering commands. - * @since 2.0.0-SNAPSHOT.1. - */ -abstract class CommandBase( - /** - * Command literal for working with command. - * @since 2.0.0-SNAPSHOT.1. - */ - var literal: LiteralArgumentBuilder, - /** - * If value true then action for command will added - * automatically with reference on method [process]. - * @since 2.0.0-SNAPSHOT.1. - */ - val actionNeed: Boolean = true -) : ICommand { - private val marker = MarkerManager.Log4jMarker("COMMAND OUT") - private val logger = LogManager.getLogger() - - abstract override val name: String - override val aliases: List = emptyList() - override val override: Boolean = false - - /** - * Initializing command. For this case, just - * remove already registered command if needed. - * @since 2.0.0-SNAPSHOT.1. - */ - override fun initialize() { - if (override) CommandAPI.removeCommand(name) - } - - /** - * Register command. - * @param dispatcher command dispatcher. - * @since 2.0.0-SNAPSHOT.1. - */ - override fun register(dispatcher: CommandDispatcher) { - fun hack(value: String) = try { - with(literal.javaClass.getDeclaredField("literal")) { - isAccessible = true - set(literal, value) - } - } catch (any: Exception) { - logger.error("Failed register alias $value for $name") - } - - if (ModuleAPI.isModuleExist("cooldown")) { - CommandAliases.aliases[name] = aliases.toMutableList() - } - - if (actionNeed) { - dispatcher.register(literal.executes { process(it) }) - aliases.filter { it != name }.forEach { alias -> - hack(alias).run { dispatcher.register(literal.executes { process(it) }) } - } - } else { - dispatcher.register(literal) - aliases.filter { it != name }.forEach { alias -> - hack(alias).run { dispatcher.register(literal) } - } - } - } - - /** - * Process command, i.e execute command. - * @param context command context. - * @return int. Command execution result. - * @since 2.0.0-SNAPSHOT.1. - */ - override fun process(context: CommandContext): Int { - logger.debug( - marker, " :: Executed command ${context.input} by ${context.playerName()}" - ) - return 0 - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/ICommand.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/ICommand.kt deleted file mode 100644 index 03e1ec8..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/ICommand.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.commands - -import com.mojang.brigadier.CommandDispatcher -import com.mojang.brigadier.context.CommandContext -import net.minecraft.command.CommandSource - -/** - * Base interface for all command classes. - * @since 2.0.0-SNAPSHOT.1. - */ -interface ICommand { - /** - * Command name without `/`. - * @since 2.0.0-RC.2. - */ - val name: String - - /** - * Command aliases as array. - * @since 2.0.0-RC.2. - */ - val aliases: List - - /** - * Override already command. If value - * true then already registered command by - * other mod will be replaced. - * @since 2.0.0-RC.2. - */ - val override: Boolean - - /** - * Initialize command, assign data and other. - * @since 2.0.0-SNAPSHOT.1. - */ - fun initialize() - - /** - * Register command. - * @param dispatcher command dispatcher. - * @since 2.0.0-SNAPSHOT.1. - */ - fun register(dispatcher: CommandDispatcher) - - /** - * Process command, i.e execute command. - * @param context command context. - * @return int. Command execution result. - * @since 2.0.0-SNAPSHOT.1. - */ - fun process(context: CommandContext): Int -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/arguments/StringArrayArgument.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/arguments/StringArrayArgument.kt deleted file mode 100644 index 590013a..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/arguments/StringArrayArgument.kt +++ /dev/null @@ -1,60 +0,0 @@ -@file:Suppress("DEPRECATION") - -package com.mairwunnx.projectessentials.core.api.v1.commands.arguments - -import com.mojang.brigadier.StringReader -import com.mojang.brigadier.arguments.ArgumentType -import com.mojang.brigadier.context.CommandContext -import com.mojang.brigadier.suggestion.Suggestions -import com.mojang.brigadier.suggestion.SuggestionsBuilder -import net.minecraft.command.CommandSource -import net.minecraft.command.ISuggestionProvider -import java.util.concurrent.CompletableFuture - -/** - * String argument type class, for commands. - * - * **It probably not work, this must not use by other modules!** - * - * *Will removed in next major version.* - * - * @param array array with accepted values for command. - * @since 2.0.0-SNAPSHOT.1. - */ -@Deprecated("Use custom arguments, this unified argument type and may not work.") -class StringArrayArgument(private val array: List) : ArgumentType { - override fun parse(reader: StringReader): String { - val value = reader.readUnquotedString() - return if (value in array) { - array.find { it == value } ?: value - } else throw IllegalArgumentException("No value found for name $value in array.") - } - - override fun listSuggestions( - context: CommandContext, builder: SuggestionsBuilder - ): CompletableFuture = ISuggestionProvider.suggest(array, builder) - - companion object { - /** - * Creates new instance of [StringArrayArgument]. - * - * @param array array with accepted value for command. - * @return new instance of [StringArrayArgument] for command. - * @since 2.0.0-SNAPSHOT.1. - */ - @JvmStatic - fun with(array: List) = StringArrayArgument(array) - - /** - * @param context command context with parameter type [CommandSource]. - * @param name argument name what contains your argument value. - * @throws IllegalArgumentException when argument not exist in command context. - * @return selected value by player in command. - * @since 2.0.0-SNAPSHOT.1. - */ - @JvmStatic - fun getValue( - context: CommandContext, name: String - ): String = context.getArgument(name, String::class.java) - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/back/BackLocationAPI.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/back/BackLocationAPI.kt deleted file mode 100644 index abd1641..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/back/BackLocationAPI.kt +++ /dev/null @@ -1,56 +0,0 @@ -@file:Suppress("unused") - -package com.mairwunnx.projectessentials.core.api.v1.commands.back - -import net.minecraft.entity.player.ServerPlayerEntity - -// todo: time based back location if community it feature need. - -/** - * Back location provider for other teleport commands, - * for creating ability to rollback location. - * @since 2.0.0-SNAPSHOT.1. - */ -object BackLocationAPI { - private val commits = hashMapOf() - - /** - * Commits back ticket with player data in hashmap. - * @param player server player entity instance. - * @since 2.0.0-SNAPSHOT.1. - */ - fun commit(player: ServerPlayerEntity) { - if (exist(player)) revoke(player) - commits[player.name.string] = BackLocationData(player) - } - - /** - * @param player server player entity instance. - * @return `BackLocationData` data class instance - * (nullable), check before using. - * @since 2.0.0-SNAPSHOT.1. - */ - fun take(player: ServerPlayerEntity) = commits[player.name.string] - - /** - * Removing player ticket from commits hashmap. - * @param player server player entity instance. - * @return response as BackLocationResponse enum - * element. - * @since 2.0.0-SNAPSHOT.1. - */ - fun revoke(player: ServerPlayerEntity) = - if (exist(player)) { - commits.remove(player.name.string) - BackLocationResponse.SUCCESS - } else { - BackLocationResponse.ALREADY_REVOKED - } - - /** - * @param player server player entity instance. - * @return `true` if player back ticket exist, `false` otherwise. - * @since 2.0.0-SNAPSHOT.1. - */ - fun exist(player: ServerPlayerEntity) = commits.containsKey(player.name.string) -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/back/BackLocationData.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/back/BackLocationData.kt deleted file mode 100644 index 1ecc735..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/back/BackLocationData.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.commands.back - -import net.minecraft.entity.player.ServerPlayerEntity -import net.minecraft.world.server.ServerWorld - -/** - * Back location data for BackLocationAPI. - * @since 2.0.0-SNAPSHOT.1. - */ -data class BackLocationData( - /** - * Server player entity class instance. - * @since 2.0.0-SNAPSHOT.1. - */ - val player: ServerPlayerEntity, - /** - * Player world at the time of teleportation. - * @since 2.0.0-SNAPSHOT.1. - */ - val world: ServerWorld = player.serverWorld, - /** - * Player position at the time of teleportation. - * @since 2.0.0-SNAPSHOT.1. - */ - val position: Position = Position( - player.posX, player.posY, player.posZ - ), - /** - * Player camera head at the time of teleportation. - * @since 2.0.0-SNAPSHOT.1. - */ - val rotation: Rotation = Rotation( - player.rotationYaw, player.rotationPitch - ) -) { - data class Position( - val xPos: Double, val yPos: Double, val zPos: Double - ) - - data class Rotation( - val yaw: Float, val pitch: Float - ) -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/back/BackLocationResponse.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/back/BackLocationResponse.kt deleted file mode 100644 index 0d4f4a6..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/back/BackLocationResponse.kt +++ /dev/null @@ -1,26 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.commands.back - -/** - * Enum class of back location responses. - * @since 2.0.0-SNAPSHOT.1. - */ -enum class BackLocationResponse { - /** - * If back location exist and able to teleport. - * @since 2.0.0-SNAPSHOT.1. - */ - SUCCESS, - - /** - * If back location not exist. - * @since 2.0.0-SNAPSHOT.1. - */ - ALREADY_REVOKED, - - /** - * If back location expired and not able for teleport. - * @since 2.0.0-SNAPSHOT.1. - */ - @Suppress("unused") - EXPIRED // todo: implement it, if community it need. -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/package-info.java b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/package-info.java deleted file mode 100644 index 5dbc152..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/commands/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Package contains API classes for interacting with commands. - */ -package com.mairwunnx.projectessentials.core.api.v1.commands; diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/configuration/ConfigurationAPI.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/configuration/ConfigurationAPI.kt deleted file mode 100644 index 90b2f2b..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/configuration/ConfigurationAPI.kt +++ /dev/null @@ -1,100 +0,0 @@ -@file:Suppress("unused") - -package com.mairwunnx.projectessentials.core.api.v1.configuration - -import com.mairwunnx.projectessentials.core.api.v1.events.ModuleEventAPI -import com.mairwunnx.projectessentials.core.api.v1.events.internal.ConfigurationEventData -import com.mairwunnx.projectessentials.core.api.v1.events.internal.ModuleCoreEventType -import com.mairwunnx.projectessentials.core.api.v1.providers.ProviderAPI -import com.mairwunnx.projectessentials.core.api.v1.providers.ProviderType -import org.apache.logging.log4j.LogManager - -/** - * Configuration API, for interacting with configurations. - * @since 2.0.0-SNAPSHOT.1. - */ -object ConfigurationAPI { - private val logger = LogManager.getLogger() - private var configurations = mutableListOf>() - - /** - * Removes all registered configurations. - * @since 2.1.0. - */ - fun dispose() = configurations.clear() - - /** - * @return all installed and checked configurations. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getConfigurations() = configurations - - /** - * @param name processor name. - * @throws ConfigurationNotFoundException - * @return configuration by name. If configuration with - * name not exist then throws `ConfigurationNotFoundException`. - * @since 2.0.0-SNAPSHOT.1. - */ - @Suppress("UNCHECKED_CAST") - fun getConfigurationByName(name: String): T where T : IConfiguration<*> = - configurations.asSequence().find { - it.name.toLowerCase() == name.toLowerCase() - }?.let { - return@let it as T - } ?: throw ConfigurationNotFoundException("Configuration with name $name not found.") - - /** - * Reloads all initialized and processed configurations. - * @param saveBeforeLoad if value is true then configuration - * will be saved before loading. Default value is `true`. - * @since 2.0.0-SNAPSHOT.1. - */ - fun reloadAll(saveBeforeLoad: Boolean = true) { - getConfigurations().forEach { cfg -> - if (saveBeforeLoad) cfg.save().also { cfg.load() } - } - } - - /** - * Reloads specified configuration. - * @param configuration configuration for reloading. - * @param saveBeforeLoad if value is true then configuration - * will be saved before loading. Default value is `true`. - * @since 2.0.0-SNAPSHOT.1. - */ - fun reloadSpecified( - configuration: IConfiguration<*>, - saveBeforeLoad: Boolean = true - ) { - if (saveBeforeLoad) configuration.save().also { configuration.load() } - } - - /** - * Saves all initialized and processed configurations. - * @since 2.0.0-SNAPSHOT.1. - */ - fun saveAll() = getConfigurations().forEach { it.save() } - - internal fun loadAll() { - ProviderAPI.getProvidersByType(ProviderType.Configuration).forEach { - val clazz = it.getDeclaredField("INSTANCE").get(null) as IConfiguration<*> - ModuleEventAPI.fire( - ModuleCoreEventType.OnConfigurationClassProcessing, ConfigurationEventData(clazz) - ) - logger.debug( - "Configuration taken! ${it.simpleName}, name: ${clazz.name}, version: ${clazz.version}, at ${clazz.path}" - ) - configurations.add(clazz) - load(clazz) - ModuleEventAPI.fire( - ModuleCoreEventType.OnConfigurationClassProcessed, ConfigurationEventData(clazz) - ) - } - } - - private fun load(configuration: IConfiguration<*>) = - logger.info("Starting loading configuration ${configuration.name}").also { - configuration.load() - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/configuration/ConfigurationNotFoundException.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/configuration/ConfigurationNotFoundException.kt deleted file mode 100644 index 224510b..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/configuration/ConfigurationNotFoundException.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.configuration - -import com.mairwunnx.projectessentials.core.api.v1.extensions.empty - -/** - * Throws when configuration not found. - * @param message exception message. - * @since 2.0.0-SNAPSHOT.1. - */ -class ConfigurationNotFoundException(message: String = String.empty) : Exception(message) diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/configuration/IConfiguration.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/configuration/IConfiguration.kt deleted file mode 100644 index f753510..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/configuration/IConfiguration.kt +++ /dev/null @@ -1,56 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.configuration - -/** - * Configuration interface for all configuration - * in project essentials modules. - * - * @param T configuration data class. - * - * @since 2.0.0-SNAPSHOT.1. - */ -interface IConfiguration { - /** - * Configuration instance (must initialized in - * `load` method). - * @since 2.0.0-SNAPSHOT.1. - */ - val configuration: T - - /** - * Path to configuration. - * @since 2.0.0-SNAPSHOT.1. - */ - val path: String - - /** - * Configuration name, for working with it later. - * @since 2.0.0-RC.2. - */ - val name: String - - /** - * Configuration version, for compatibility checking. By - * default value is 0. - * @since 2.0.0-RC.2. - */ - val version: Int - - /** - * Load configuration from local storage or memory. - * Also initializing configuration field. - * @since 2.0.0-SNAPSHOT.1. - */ - fun load() - - /** - * Save configuration to local storage. - * @since 2.0.0-SNAPSHOT.1. - */ - fun save() - - /** - * @return configuration model instance. - * @since 2.0.0-SNAPSHOT.1. - */ - fun take(): T -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/configuration/package-info.java b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/configuration/package-info.java deleted file mode 100644 index 1cc4bdc..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/configuration/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Package contains classes for working with configurations - * and contains configuration api. - */ -package com.mairwunnx.projectessentials.core.api.v1.configuration; diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/EmptyEventData.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/EmptyEventData.kt deleted file mode 100644 index f2602c2..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/EmptyEventData.kt +++ /dev/null @@ -1,10 +0,0 @@ -@file:Suppress("unused") - -package com.mairwunnx.projectessentials.core.api.v1.events - -/** - * Empty event data class, use it if your - * event not send any event data. - * @since 2.0.0-SNAPSHOT.1. - */ -class EmptyEventData : IModuleEventData diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/EventNotFoundException.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/EventNotFoundException.kt deleted file mode 100644 index 327ee2e..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/EventNotFoundException.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.events - -import com.mairwunnx.projectessentials.core.api.v1.extensions.empty - -/** - * Throws when module event not found. - * @param message exception message. - * @since 2.0.0-SNAPSHOT.1. - */ -class EventNotFoundException(message: String = String.empty) : Exception(message) diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/IModuleEventData.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/IModuleEventData.kt deleted file mode 100644 index 0752634..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/IModuleEventData.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.events - -/** - * Base interface for all module events. - * @since 2.0.0-SNAPSHOT.1. - */ -interface IModuleEventData diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/IModuleEventType.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/IModuleEventType.kt deleted file mode 100644 index cfff4fa..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/IModuleEventType.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.events - -/** - * Base interface for all module event types. - * @since 2.0.0-SNAPSHOT.1. - */ -interface IModuleEventType diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/ModuleEventAPI.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/ModuleEventAPI.kt deleted file mode 100644 index 2558275..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/ModuleEventAPI.kt +++ /dev/null @@ -1,97 +0,0 @@ -@file:Suppress("unused", "MemberVisibilityCanBePrivate") - -package com.mairwunnx.projectessentials.core.api.v1.events - -import org.apache.logging.log4j.LogManager -import org.apache.logging.log4j.MarkerManager - -/** - * Event API class, contains all methods for interacting - * with events. - * @since 2.0.0-SNAPSHOT.1. - */ -object ModuleEventAPI { - private val logger = LogManager.getLogger() - private val marker = MarkerManager.Log4jMarker("EVENT MANAGER") - - private val events: HashMap Unit>> = hashMapOf() - - /** - * Fire target event type. And send some data. - * @param eventType event type. - * @param eventData event data. - * @since 2.0.0-SNAPSHOT.1. - */ - fun fire( - eventType: IModuleEventType, - eventData: IModuleEventData - ) { - events.keys.find { it == eventType }?.let { type -> - logger.debug(marker, "Firing all methods event types of `$type`") - events[type]?.forEach { it.invoke(eventData) } - } - } - - /** - * Subscribe on target event type. - * @param T event data data type. - * @param event target event type. - * @param action action or method reference what will - * be called on event firing. Method must return `Unit` or - * in java it `void`. - * @since 2.0.0-SNAPSHOT.1. - */ - @Suppress("UNCHECKED_CAST") - fun subscribeOn( - event: IModuleEventType, - action: (T) -> Unit - ) { - val pushedAction = action as (IModuleEventData) -> Unit - val eventCollection = events[event] - - if (eventCollection == null) { - events[event] = mutableListOf(pushedAction) - } else { - eventCollection.add(pushedAction) - } - } - - /** - * @return all subscribed events. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getAllEvents() = events - - /** - * @param eventType target event type. - * @return mutable list with references on subscribed methods. - * @throws EventNotFoundException when event type not found. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getEventsByType( - eventType: IModuleEventType - ): MutableList<(IModuleEventData) -> Unit> = - events.keys.find { it == eventType }?.let { type -> - getAllEvents()[type]?.let { return it } - } ?: throw EventNotFoundException() - - /** - * Removing all method references for specified event type. - * @param eventType target event type. - * @throws EventNotFoundException when event type not found. - * @since 2.0.0-SNAPSHOT.1. - */ - fun killEventsByType(eventType: IModuleEventType) = - events.keys.find { it == eventType }?.let { - logger.debug(marker, "Removing methods references from event types of `$it`") - getAllEvents()[it]?.clear() - } ?: throw EventNotFoundException() - - /** - * Removing all methods references from all event types. - * @since 2.0.0-SNAPSHOT.1. - */ - fun killAllEvents() = events.clear() -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/FMLClientSetupEventData.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/FMLClientSetupEventData.kt deleted file mode 100644 index 1bda0ab..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/FMLClientSetupEventData.kt +++ /dev/null @@ -1,9 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.events.forge - -import com.mairwunnx.projectessentials.core.api.v1.events.IModuleEventData -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent - -/** - * @since 2.0.0-SNAPSHOT.1. - */ -class FMLClientSetupEventData(val event: FMLClientSetupEvent) : IModuleEventData diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/FMLCommonSetupEventData.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/FMLCommonSetupEventData.kt deleted file mode 100644 index 1f50d89..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/FMLCommonSetupEventData.kt +++ /dev/null @@ -1,9 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.events.forge - -import com.mairwunnx.projectessentials.core.api.v1.events.IModuleEventData -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent - -/** - * @since 2.0.0-SNAPSHOT.1. - */ -class FMLCommonSetupEventData(val event: FMLCommonSetupEvent) : IModuleEventData diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/ForgeEventType.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/ForgeEventType.kt deleted file mode 100644 index 77d7118..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/ForgeEventType.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.events.forge - -import com.mairwunnx.projectessentials.core.api.v1.events.IModuleEventType - -/** - * Some event types of forge, EventAPI. - * @since 2.0.0-SNAPSHOT.1. - */ -enum class ForgeEventType : IModuleEventType { - /** - * `setup` method for modloading. - * @since 2.0.0-SNAPSHOT.1. - */ - SetupEvent, - - /** - * `enqueueIMC` method for modloading. - * @since 2.0.0-SNAPSHOT.1. - */ - EnqueueIMCEvent, - - /** - * `processIMC` method for modloading. - * @since 2.0.0-SNAPSHOT.1. - */ - ProcessIMCEvent, - - /** - * `doClientStuff` method for modloading. - * @since 2.0.0-SNAPSHOT.1. - */ - DoClientStuffEvent, - - /** - * `complete` method for modloading. - * @since 2.0.1. - */ - LoadComplete, -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/InterModEnqueueEventData.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/InterModEnqueueEventData.kt deleted file mode 100644 index 92339ec..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/InterModEnqueueEventData.kt +++ /dev/null @@ -1,9 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.events.forge - -import com.mairwunnx.projectessentials.core.api.v1.events.IModuleEventData -import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent - -/** - * @since 2.0.0-SNAPSHOT.1. - */ -class InterModEnqueueEventData(val event: InterModEnqueueEvent) : IModuleEventData diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/InterModProcessEventData.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/InterModProcessEventData.kt deleted file mode 100644 index 850085b..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/InterModProcessEventData.kt +++ /dev/null @@ -1,9 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.events.forge - -import com.mairwunnx.projectessentials.core.api.v1.events.IModuleEventData -import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent - -/** - * @since 2.0.0-SNAPSHOT.1. - */ -class InterModProcessEventData(val event: InterModProcessEvent) : IModuleEventData diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/LoadCompleteEventData.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/LoadCompleteEventData.kt deleted file mode 100644 index 4f2ea5c..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/forge/LoadCompleteEventData.kt +++ /dev/null @@ -1,9 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.events.forge - -import com.mairwunnx.projectessentials.core.api.v1.events.IModuleEventData -import net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent - -/** - * @since 2.0.1. - */ -class LoadCompleteEventData(val event: FMLLoadCompleteEvent) : IModuleEventData diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/CommandEventData.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/CommandEventData.kt deleted file mode 100644 index 6dee60b..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/CommandEventData.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.events.internal - -import com.mairwunnx.projectessentials.core.api.v1.commands.ICommand -import com.mairwunnx.projectessentials.core.api.v1.events.IModuleEventData - -/** - * Command event data, stores command instance. - * @since 2.0.0-SNAPSHOT.1. - */ -class CommandEventData(val command: ICommand) : IModuleEventData diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/ConfigurationEventData.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/ConfigurationEventData.kt deleted file mode 100644 index 9dfa078..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/ConfigurationEventData.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.events.internal - -import com.mairwunnx.projectessentials.core.api.v1.configuration.IConfiguration -import com.mairwunnx.projectessentials.core.api.v1.events.IModuleEventData - -/** - * Configuration event data, stores configuration instance. - * @since 2.0.0-SNAPSHOT.1. - */ -class ConfigurationEventData(val configuration: IConfiguration<*>) : IModuleEventData diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/LocalizationEventData.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/LocalizationEventData.kt deleted file mode 100644 index 3ccbf9e..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/LocalizationEventData.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.events.internal - -import com.mairwunnx.projectessentials.core.api.v1.events.IModuleEventData -import com.mairwunnx.projectessentials.core.api.v1.localization.Localization - -/** - * Localization event data, stores localization instance. - * @since 2.0.0-SNAPSHOT.1. - */ -class LocalizationEventData(val localization: Localization) : IModuleEventData diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/ModuleCoreEventType.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/ModuleCoreEventType.kt deleted file mode 100644 index c7012c6..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/ModuleCoreEventType.kt +++ /dev/null @@ -1,58 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.events.internal - -import com.mairwunnx.projectessentials.core.api.v1.events.IModuleEventType - -/** - * Event types for core module, EventAPI. - * @since 2.0.0-SNAPSHOT.1. - */ -enum class ModuleCoreEventType : IModuleEventType { - /** - * This event type will be fired on - * module class processing. - * @since 2.0.0-SNAPSHOT.1. - */ - OnModuleClassProcessing, - - /** - * This event type will be fired after - * module class processing. - * @since 2.0.0-SNAPSHOT.1. - */ - OnModuleClassProcessed, - - /** - * This event type will be fired on - * processor processing. - * @since 2.0.0-SNAPSHOT.1. - */ - OnProcessorProcessing, - - /** - * This event type will be fired on - * configuration class processing. - * @since 2.0.0-SNAPSHOT.1. - */ - OnConfigurationClassProcessing, - - /** - * This event type will be fired after - * configuration class processing. - * @since 2.0.0-SNAPSHOT.1. - */ - OnConfigurationClassProcessed, - - /** - * This event type will be fired on - * command class processing. - * @since 2.0.0-SNAPSHOT.1. - */ - OnCommandClassProcessing, - - /** - * This event type will be fired after - * command class processing. - * @since 2.0.0-SNAPSHOT.1. - */ - OnCommandClassProcessed -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/ModuleEventData.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/ModuleEventData.kt deleted file mode 100644 index dac771f..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/ModuleEventData.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.events.internal - -import com.mairwunnx.projectessentials.core.api.v1.events.IModuleEventData -import com.mairwunnx.projectessentials.core.api.v1.module.IModule - -/** - * Domain event data, stores domain name (package path). - * @since 2.0.0-SNAPSHOT.1. - */ -class ModuleEventData(val module: IModule) : IModuleEventData diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/package-info.java b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/package-info.java deleted file mode 100644 index 809a90b..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/internal/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Contains internal implementation some event types - * and event data classes. But it able for calling from - * other java modules. - */ -package com.mairwunnx.projectessentials.core.api.v1.events.internal; diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/package-info.java b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/package-info.java deleted file mode 100644 index da866cf..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/events/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Package contains all classes and interfaces for interacting - * with module events. - */ -package com.mairwunnx.projectessentials.core.api.v1.events; diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/extensions/Extensions.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/extensions/Extensions.kt deleted file mode 100644 index ee34fca..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/extensions/Extensions.kt +++ /dev/null @@ -1,291 +0,0 @@ -@file:Suppress("unused") - -package com.mairwunnx.projectessentials.core.api.v1.extensions - -import com.mairwunnx.projectessentials.core.api.v1.SETTING_LOC_ENABLED -import com.mairwunnx.projectessentials.core.api.v1.configuration.ConfigurationAPI.getConfigurationByName -import com.mairwunnx.projectessentials.core.api.v1.localization.LocalizationAPI.getLocalizedString -import com.mairwunnx.projectessentials.core.impl.configurations.GeneralConfiguration -import com.mojang.brigadier.context.CommandContext -import net.minecraft.client.Minecraft -import net.minecraft.command.CommandSource -import net.minecraft.entity.LivingEntity -import net.minecraft.entity.player.PlayerEntity -import net.minecraft.entity.player.ServerPlayerEntity -import net.minecraft.util.SoundCategory -import net.minecraft.util.SoundEvent -import net.minecraft.util.text.ITextComponent -import net.minecraft.util.text.TextComponentUtils -import net.minecraft.util.text.TranslationTextComponent -import net.minecraft.util.text.event.HoverEvent -import net.minecraft.world.World -import net.minecraft.world.dimension.DimensionType -import net.minecraftforge.api.distmarker.Dist -import net.minecraftforge.event.CommandEvent -import net.minecraftforge.fml.DistExecutor -import net.minecraftforge.fml.server.ServerLifecycleHooks -import java.io.File - -private val generalConfiguration by lazy { - getConfigurationByName("general") -} - -/** - * Plays sound to player at player position on both sides. - * @param player target player to play sound. - * @param sound sound to play. - * @param category sound category, default value is [SoundCategory.AMBIENT]. - * @param volume sound volume, default value is `1.0f`. - * @param pitch sound pitch, default value is `1.0f`. - */ -fun ServerPlayerEntity.playSound( - player: PlayerEntity, - sound: SoundEvent, - category: SoundCategory = SoundCategory.AMBIENT, - volume: Float = 1.0f, - pitch: Float = 1.0f -) { - val pos = player.positionVec - DistExecutor.runWhenOn(Dist.CLIENT) { - Runnable { - Minecraft.getInstance().world.playSound( - pos.x, pos.y + player.eyeHeight.toDouble(), pos.z, - sound, category, volume, pitch, false - ) - player.entity.playSound(sound, volume, pitch) - } - } - DistExecutor.runWhenOn(Dist.DEDICATED_SERVER) { - Runnable { - player.world.playSound( - null, pos.x, pos.y + player.eyeHeight.toDouble(), pos.z, - sound, category, volume, pitch - ) - } - } -} - -/** - * @return true if command sender is player. - * @since 2.0.0-SNAPSHOT.1. - */ -fun CommandContext.isPlayerSender() = this.source.entity is ServerPlayerEntity - -/** - * @return player if sender is player, if sender is - * entity or server then return null. - * @since 2.0.0-SNAPSHOT.1. - */ -fun CommandContext.getPlayer() = - if (this.isPlayerSender()) this.source.asPlayer() else null - -/** - * @return if command source is player then nickname - * from CommandContext. If command source is server - * then return `#server`. - * @since 2.0.0-SNAPSHOT.1. - */ -fun CommandContext.playerName(): String = - if (this.isPlayerSender()) this.source.asPlayer().name.string else "#server" - -/** - * Return command name as string. - * - * Example: player execute command **`/heal MairwunNx`**, - * then you get **`heal`** as string. - * @since 2.0.0-SNAPSHOT.1. - */ -val CommandEvent.commandName - get() = this.executedCommand.replace("/", "").split(" ")[0] - -/** - * Return fully executed command as string. - * - * Example: player execute command **`/heal MairwunNx`**, - * then you get **`/heal MairwunNx`** as string. - * @since 2.0.0-SNAPSHOT.1. - */ -val CommandEvent.executedCommand: String get() = this.parseResults.reader.string - -/** - * @return true if source is player. - * @since 2.0.0-SNAPSHOT.1. - */ -fun CommandEvent.isPlayerSender() = this.source.entity is ServerPlayerEntity - -/** - * Return **`ServerPlayerEntity?`** class instance from - * **`CommandEvent`** class instance. If source is server - * then return null. - * @since 2.0.0-SNAPSHOT.1. - */ -fun CommandEvent.getPlayer() = if (this.isPlayerSender()) this.source.asPlayer() else null - -/** - * Return command **`source`** from **`CommandEvent`** - * class instance. - * @since 2.0.0-SNAPSHOT.1. - */ -val CommandEvent.source: CommandSource get() = this.parseResults.context.source - -/** - * @param player server player entity instance. - * @param safeLocalization if safe localization - * enabled then will be used non-client localization. - * @param l10n localization string for indexing localized - * string. - * @param args additional arguments for localized string. - * @return HoverEvent instance with your localized string. - * @since 2.0.0-SNAPSHOT.1. - */ -fun hoverEventFrom( - player: ServerPlayerEntity, - safeLocalization: Boolean = generalConfiguration.getBool(SETTING_LOC_ENABLED), - l10n: String, - vararg args: String -) = if (safeLocalization) { - HoverEvent( - HoverEvent.Action.SHOW_TEXT, - TextComponentUtils.toTextComponent { - getLocalizedString(player.language, l10n, *args) - } - ) -} else { - HoverEvent(HoverEvent.Action.SHOW_TEXT, TranslationTextComponent(l10n, *args)) -} - -/** - * @param player server player entity instance. - * @param safeLocalization if safe localization - * enabled then will be used non-client localization. - * @param l10n localization string for indexing localized - * string. - * @param args additional arguments for localized string. - * @return ITextComponent implements class instance with - * your localized string. - * @since 2.0.0-SNAPSHOT.1. - */ -fun textComponentFrom( - player: ServerPlayerEntity, - safeLocalization: Boolean = generalConfiguration.getBool(SETTING_LOC_ENABLED), - l10n: String, - vararg args: String -): ITextComponent = TextComponentUtils.toTextComponent { - if (safeLocalization) { - getLocalizedString(player.language, l10n, *args) - } else { - TranslationTextComponent(l10n, *args).formattedText - } -} - -/** - * Capitalize each word in string. - * @return capitalized each word string. - * @since 2.0.0-SNAPSHOT.1. - */ -fun String.capitalizeWords() = split(" ").joinToString(" ") { it.capitalize() } - -/** - * Return empty string. - * @since 2.0.0-SNAPSHOT.1. - */ -val String.Companion.empty get() = "" - -/** - * Returns world name. - * - * In case with server: - * ``` - * - world directory is `world` (like default name), - * then you will get `world` as world name. - * ``` - * - * In case with client: - * ``` - * - world directory is `New World` (like default name), - * then you will get `New World` as world name, but if - * you have duplicate, for example directory `New World (2)`, - * but world name is `New World`, you will get `New World` as - * world name. - * ``` - * - * @since 2.0.0-SNAPSHOT.1. - */ -val World.name: String - get() { - var wName = String.empty - DistExecutor.runWhenOn(Dist.CLIENT) { - Runnable { wName = ServerLifecycleHooks.getCurrentServer().worldName } - } - DistExecutor.runWhenOn(Dist.DEDICATED_SERVER) { - Runnable { wName = ServerLifecycleHooks.getCurrentServer().folderName } - } - return wName - } - -/** - * Returns world directory name, for server this will - * return server world directory name, for client, see [World.name]. - * - * @since 2.0.0-SNAPSHOT.1. - */ -val World.directoryName: String get() = ServerLifecycleHooks.getCurrentServer().folderName - -/** - * Returns full path as string to world directory. - * - * For client it `saves/` - * - * For server it `./` - * - * @since 2.0.0-SNAPSHOT.1. - */ -val World.directoryPath: String - get() { - var wPath = String.empty - DistExecutor.runWhenOn(Dist.CLIENT) { - Runnable { - val folderName = ServerLifecycleHooks.getCurrentServer().folderName - wPath = "saves${File.pathSeparator}${folderName}" - } - } - DistExecutor.runWhenOn(Dist.DEDICATED_SERVER) { - Runnable { wPath = ServerLifecycleHooks.getCurrentServer().folderName } - } - return wPath - } - -/** - * Returns current player dimension type. - * - * @since 2.0.0-SNAPSHOT.1. - */ -val PlayerEntity.currentDimension: DimensionType get() = this.dimension - -/** - * Returns current dimension registry name. - * - * @since 2.0.0-SNAPSHOT.1. - */ -val PlayerEntity.currentDimensionName get() = this.currentDimension.registryName.toString() - -/** - * Returns current dimension id. - * - * @since 2.0.0-SNAPSHOT.1. - */ -val PlayerEntity.currentDimensionId get() = this.currentDimension.id - -/** - * Returns true if living entity is player. - * - * @since 2.0.0-SNAPSHOT.1. - */ -val LivingEntity.isPlayerEntity get() = this is ServerPlayerEntity - -/** - * Returns [ServerPlayerEntity] instance of player from [LivingEntity]. - * - * @since 2.0.0-SNAPSHOT.1. - */ -val LivingEntity.asPlayerEntity get() = this as ServerPlayerEntity diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/extensions/package-info.java b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/extensions/package-info.java deleted file mode 100644 index 7d6bb10..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/extensions/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * This package contains extensions for simplify code. - */ -package com.mairwunnx.projectessentials.core.api.v1.extensions; diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/helpers/Helpers.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/helpers/Helpers.kt deleted file mode 100644 index 6c90c11..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/helpers/Helpers.kt +++ /dev/null @@ -1,90 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.helpers - -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonConfiguration -import java.io.File -import java.io.FileOutputStream -import java.io.IOException -import java.lang.reflect.Field - -/** - * @param classLoader class loaded. - * @param resourcePath path to resource file. - * @return resource file as file. Return null - * if file not exist or if was throw `IOException`. - * @since 2.0.0-SNAPSHOT.1. - */ -fun getResourceAsFile( - classLoader: ClassLoader, resourcePath: String -): File? { - return try { - val inputStream = classLoader.getResourceAsStream( - resourcePath - ) ?: return null - - val tempFile = File.createTempFile( - java.lang.String.valueOf(inputStream.hashCode()), ".tmp" - ) - tempFile.deleteOnExit() - - FileOutputStream(tempFile).use { out -> - val buffer = ByteArray(1024) - var bytesRead: Int - while (inputStream.read(buffer).also { bytesRead = it } != -1) { - out.write(buffer, 0, bytesRead) - } - } - tempFile - } catch (e: IOException) { - e.printStackTrace() - null - } -} - -/** - * @return absolutely path to minecraft client or server root dir. - * @since 2.0.0-SNAPSHOT.1. - */ -fun getRootDirectory(): String = File(".").absolutePath - -/** - * Common json instance with default configuration - * for Project Essentials modules, if module using - * json configuration, then you need use this property. - * @since 1.14.4-1.0.3.2 / 2.0.0-SNAPSHOT.1. - */ -@OptIn(kotlinx.serialization.UnstableDefault::class) -val jsonInstance = Json( - JsonConfiguration( - encodeDefaults = true, - ignoreUnknownKeys = true, - isLenient = false, - serializeSpecialFloatingPointValues = false, - allowStructuredMapKeys = true, - prettyPrint = true, - unquotedPrint = false, - useArrayPolymorphism = false - ) -) - -/** - * Minecraft config folder absolutely path. - * @since 2.0.0-SNAPSHOT.1. - */ -val configDirectory = getRootDirectory() + File.separator + "config" - -/** - * Project Essentials mod config folder. - * @since 2.0.0-SNAPSHOT.1. - */ -val projectConfigDirectory = configDirectory + File.separator + "ProjectEssentials" - -fun getFieldsOf(type: Class<*>?) = - with(mutableListOf()) { - var c = type - while (c != null) { - addAll(c.declaredFields) - c = c.superclass - } - return@with this - } diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/helpers/package-info.java b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/helpers/package-info.java deleted file mode 100644 index b810fc5..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/helpers/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * This package contains some helpers for reducing code - * duplicates. - */ -package com.mairwunnx.projectessentials.core.api.v1.helpers; diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/localization/Localization.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/localization/Localization.kt deleted file mode 100644 index 38655ad..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/localization/Localization.kt +++ /dev/null @@ -1,5 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.localization - -data class Localization( - val sources: MutableList, val sourceName: String, val sourceClass: Class<*> -) diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/localization/LocalizationAPI.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/localization/LocalizationAPI.kt deleted file mode 100644 index 9feb08b..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/localization/LocalizationAPI.kt +++ /dev/null @@ -1,148 +0,0 @@ -@file:Suppress("unused", "MemberVisibilityCanBePrivate", "DEPRECATION", "RedundantAsync") - -package com.mairwunnx.projectessentials.core.api.v1.localization - -import com.mairwunnx.projectessentials.core.api.v1.INITIAL_FALLBACK_LANGUAGE -import com.mairwunnx.projectessentials.core.api.v1.SETTING_LOC_FALLBACK_LANG -import com.mairwunnx.projectessentials.core.api.v1.extensions.empty -import com.mairwunnx.projectessentials.core.api.v1.helpers.getResourceAsFile -import com.mairwunnx.projectessentials.core.api.v1.localizationMarker -import com.mairwunnx.projectessentials.core.impl.generalConfiguration -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.async -import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import net.minecraft.entity.player.ServerPlayerEntity -import org.apache.logging.log4j.LogManager -import org.json.JSONObject -import java.util.* -import kotlin.system.measureTimeMillis - -/** - * Localization API class, for interacting with - * localization. - * @since 2.0.0-SNAPSHOT.1. - */ -object LocalizationAPI { - private val logger = LogManager.getLogger()!! - private val mutex = Mutex() - - private val localizations: MutableMap>> = - Collections.synchronizedMap(mutableMapOf()) - - fun apply(clazz: Class<*>, entries: () -> List) { - CoroutineScope(Dispatchers.Default).launch { - async { - entries().asSequence().forEach { - val name = it.substring(it.lastIndexOf("/")).drop(1).dropLast(5) - measureTimeMillis { - val json = getResourceAsFile( - clazz.classLoader, it - )?.readText() ?: error("Localization $it / $name failed to process") - JSONObject(json).also { jsonObject -> - jsonObject.keys().asSequence().filter { predicate -> - predicate != "_comment" - }.forEach { key -> - val value = jsonObject.get(key) as String - change(name, key, value) - } - } - }.also { time -> - logger.debug( - localizationMarker, "Localization `$name` processed with ${time}ms" - ) - } - } - }.await() - } - } - - @Synchronized - private suspend fun change(name: String, key: String, value: String) { - mutex.withLock { - val result = localizations[name] - if (result == null) { - localizations[name] = mutableListOf(hashMapOf(key to value)) - } else { - result.add(hashMapOf(Pair(key, value))) - } - } - } - - /** - * Applying localization, without (with since 2.0.1) processing. Thread safe. - * - * @param localization localization data class instance. - * @since 2.0.0-SNAPSHOT.1. - */ - fun apply(localization: Localization) = apply(localization.sourceClass) { localization.sources } - - /** - * @return fall back localizations language. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getFallBackLanguage() = generalConfiguration.getStringOrDefault( - SETTING_LOC_FALLBACK_LANG, INITIAL_FALLBACK_LANGUAGE - ) - - /** - * Install new fall back localizations language. - * @param language language string in format `xx_xx`. - * code is illegal. - * @since 2.0.0-SNAPSHOT.1. - */ - fun setFallBackLanguage(language: String) = - if (language.matches(Regex("^[a-z]{2}_[a-z]{2}$"))) { - generalConfiguration.put(SETTING_LOC_FALLBACK_LANG, language) - } else throw error("Language code format $language incorrect and unsupported.") - - /** - * @param targetLanguage target language, in format `xx_xx`. - * @param l10nString minecraft localization string. - * @param args some arguments for string if provided. - * @param argumentChar argument char for processing arguments. - * @return localized string, if localization string - * not found, then return empty string. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getLocalizedString( - targetLanguage: String, - l10nString: String, - vararg args: String, - argumentChar: Char = 's' - ): String { - var msg = String.empty - val messagesList = localizations[ - targetLanguage.toLowerCase() - ] ?: localizations[getFallBackLanguage()] - - messagesList!!.asSequence().forEach { - it[l10nString]?.let { message -> msg = message } - }.also { - for (i in 0 until msg.asSequence().filter { it == '%' }.count()) { - msg = msg.replaceFirst("%$argumentChar", args[i]) - } - } - - if (msg.isEmpty()) { - StringBuilder(msg).apply { - append("Probably localization error occurred:\n") - append(" > Requested language: $targetLanguage,\n") - append(" > Requested string: $l10nString,\n") - append(" > Fallback language: ${getFallBackLanguage()},\n") - append(" > Messages count: ${messagesList.count()},\n") - append(" > Registered localizations: ${localizations.count()}") - }.toString().also { logger.error(it) } - } - return msg - } - - /** - * @param player target player to get result. - * @return player language. - * @since 2.0.0. - */ - fun getPlayerLanguage(player: ServerPlayerEntity): String = player.language -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/localization/package-info.java b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/localization/package-info.java deleted file mode 100644 index f427f96..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/localization/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Package contains classes manages server-side localization. - */ -package com.mairwunnx.projectessentials.core.api.v1.localization; diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/messaging/MessagingAPI.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/messaging/MessagingAPI.kt deleted file mode 100644 index 2fbb3b9..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/messaging/MessagingAPI.kt +++ /dev/null @@ -1,253 +0,0 @@ -@file:Suppress("unused") - -package com.mairwunnx.projectessentials.core.api.v1.messaging - -import com.mairwunnx.projectessentials.core.api.v1.SETTING_LIST_MAX_ELEMENTS_IN_PAGE -import com.mairwunnx.projectessentials.core.api.v1.SETTING_LOC_ENABLED -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAPI -import com.mairwunnx.projectessentials.core.api.v1.extensions.getPlayer -import com.mairwunnx.projectessentials.core.api.v1.extensions.isPlayerSender -import com.mairwunnx.projectessentials.core.api.v1.localization.LocalizationAPI -import com.mairwunnx.projectessentials.core.impl.generalConfiguration -import com.mojang.brigadier.context.CommandContext -import net.minecraft.command.CommandSource -import net.minecraft.entity.player.ServerPlayerEntity -import net.minecraft.server.MinecraftServer -import net.minecraft.util.text.StringTextComponent -import net.minecraft.util.text.TextComponentUtils -import net.minecraft.util.text.TranslationTextComponent -import net.minecraft.util.text.event.ClickEvent -import net.minecraft.util.text.event.HoverEvent - -/** - * This class contains all methods for interacting - * with player messages. - * @since 2.0.0-SNAPSHOT.1. - */ -object MessagingAPI { - /** - * Send message to player with localized string - * or simple message. - * @param player target player, server player instance. - * @param l10nString localization string or message. - * @param safeLocalization if true then localization - * will provided by server false if localization - * will provided by client resource pack. - * @param args localization string arguments. - * @param argumentChar localization argument char. - * @param clickEvent click event for message. - * @param hoverEvent hover event for message. - * @since 2.0.0-SNAPSHOT.1. - */ - fun sendMessage( - player: ServerPlayerEntity, - l10nString: String, - safeLocalization: Boolean = generalConfiguration.getBool(SETTING_LOC_ENABLED), - vararg args: String, - argumentChar: Char = 's', - clickEvent: ClickEvent? = null, - hoverEvent: HoverEvent? = null - ) = player.sendMessage( - if (safeLocalization) { - TextComponentUtils.toTextComponent { - val msg = LocalizationAPI.getLocalizedString( - player.language, l10nString, *args, argumentChar = argumentChar - ) - if (msg.isEmpty()) return@toTextComponent l10nString else return@toTextComponent msg - }.apply { - clickEvent?.let { style.clickEvent = it } - hoverEvent?.let { style.hoverEvent = it } - } - } else { - TranslationTextComponent(l10nString, *args).apply { - clickEvent?.let { style.clickEvent = it } - hoverEvent?.let { style.hoverEvent = it } - } - } - ) - - /** - * Send list like response to player in chat. - * With pages (passed as argument in [context]) - * with name `page`. - * - * Max displayed lines per page defined in - * setting `list-max-elements-in-page`. - * - * @param context command context. - * @param list list to display in server console. - * @param title list title, list name or something like that. - * @since 2.0.0-RC.3. - */ - fun sendListAsMessage( - context: CommandContext, - list: List, - title: () -> String - ) { - require(context.isPlayerSender()) { - "Command sender is no player, use [ServerMessagingAPI.listAsResponse] for server" - } - val linesPerPage = generalConfiguration.getIntOrDefault( - SETTING_LIST_MAX_ELEMENTS_IN_PAGE, 8 - ) - val pages = list.count() / linesPerPage + 1 - val page = when { - CommandAPI.getIntExisting(context, "page") -> { - CommandAPI.getInt(context, "page") - } - else -> 1 - } - sendListAsMessage(context.getPlayer()!!, list, page, pages, linesPerPage, title()) - } - - /** - * Send list like response to player in chat. - * - * Max displayed lines per page defined in - * setting `list-max-elements-in-page`. - * - * @param player player to send list. - * @param list list to display in server console. - * @param page list page. (unchecked page!) - * @param maxPage pages total to can be displayed. - * @param linesPerPage lines per page. - * @param title list title, list name or something like that. - * @since 2.0.0-RC.3. - */ - fun sendListAsMessage( - player: ServerPlayerEntity, - list: List, - page: Int, - maxPage: Int, - linesPerPage: Int, - title: String - ) { - val displayedLines = page * linesPerPage - val droppedLines = displayedLines - linesPerPage - val values = list.take(displayedLines).drop(droppedLines) - val pageString = LocalizationAPI.getLocalizedString( - player.language, - "project_essentials_core.simple.page", - page.toString(), - maxPage.toString() - ).let { - if (it.isEmpty()) { - return@let TranslationTextComponent( - "project_essentials_core.simple.page", - page, maxPage - ).formattedText - } - return@let it - } - val message = - """ -§7$title $pageString - -§7${values.joinToString(separator = "\n") { " §c> §7$it" }} - """ - player.commandSource.sendFeedback(StringTextComponent(message), false) - } - - /** - * Send message to all player on server with localized - * string or simple message. - * @param server minecraft server instance. - * @param l10nString localization string or message. - * @param safeLocalization if true then localization - * will provided by server false if localization - * will provided by client resource pack. - * @param args localization string arguments. - * @param argumentChar localization argument char. - * @param clickEvent click event for message. - * @param hoverEvent hover event for message. - * @since 2.0.0-SNAPSHOT.1. - */ - fun sendMessageToAll( - server: MinecraftServer, - l10nString: String, - safeLocalization: Boolean = generalConfiguration.getBool(SETTING_LOC_ENABLED), - vararg args: String, - argumentChar: Char = 's', - clickEvent: ClickEvent? = null, - hoverEvent: HoverEvent? = null - ) = server.playerList.players.forEach { - sendMessage( - player = it, - l10nString = l10nString, - safeLocalization = safeLocalization, - args = *args, - argumentChar = argumentChar, - clickEvent = clickEvent, - hoverEvent = hoverEvent - ) - } - - /** - * Send message to all player in specified world id - * with localized string or simple message. - * @param worldId target world id. - * @param server minecraft server instance. - * @param l10nString localization string or message. - * @param safeLocalization if true then localization - * will provided by server false if localization - * will provided by client resource pack. - * @param args localization string arguments. - * @param argumentChar localization argument char. - * @param clickEvent click event for message. - * @param hoverEvent hover event for message. - * @since 2.0.0-SNAPSHOT.1. - */ - fun sendMessageToAllInWorld( - worldId: Int, - server: MinecraftServer, - l10nString: String, - safeLocalization: Boolean = generalConfiguration.getBool(SETTING_LOC_ENABLED), - vararg args: String, - argumentChar: Char = 's', - clickEvent: ClickEvent? = null, - hoverEvent: HoverEvent? = null - ) = server.playerList.players.forEach { - if (it.serverWorld.dimension.type.id == worldId) { - sendMessage( - player = it, - l10nString = l10nString, - safeLocalization = safeLocalization, - args = *args, - argumentChar = argumentChar, - clickEvent = clickEvent, - hoverEvent = hoverEvent - ) - } - } - - /** - * Send message to player action bar with localized - * string or simple message. - * @param player target player, server player instance. - * @param l10nString localization string or message. - * @param safeLocalization if true then localization - * will provided by server false if localization - * will provided by client resource pack. - * @param args localization string arguments. - * @param argumentChar localization argument char. - * @since 2.0.0-SNAPSHOT.1. - */ - fun sendActionBarMessage( - player: ServerPlayerEntity, - l10nString: String, - safeLocalization: Boolean = generalConfiguration.getBool(SETTING_LOC_ENABLED), - vararg args: String, - argumentChar: Char = 's' - ) = player.sendStatusMessage( - if (safeLocalization) { - TextComponentUtils.toTextComponent { - val msg = LocalizationAPI.getLocalizedString( - player.language, l10nString, *args, argumentChar = argumentChar - ) - if (msg.isEmpty()) return@toTextComponent l10nString else return@toTextComponent msg - } - } else { - TranslationTextComponent(l10nString, *args) - }, true - ) -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/messaging/ServerMessagingAPI.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/messaging/ServerMessagingAPI.kt deleted file mode 100644 index 76f59b2..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/messaging/ServerMessagingAPI.kt +++ /dev/null @@ -1,68 +0,0 @@ -@file:Suppress("unused") - -package com.mairwunnx.projectessentials.core.api.v1.messaging - -import com.mairwunnx.projectessentials.core.api.v1.SETTING_ENABLE_CONSOLE_COLORS -import com.mairwunnx.projectessentials.core.api.v1.extensions.empty -import com.mairwunnx.projectessentials.core.impl.generalConfiguration -import org.apache.logging.log4j.LogManager - -/** - * Provides API for messaging with server. - * @since 2.0.0-SNAPSHOT.1. - */ -object ServerMessagingAPI { - private val logger = LogManager.getLogger() - - /** - * Throw in console warning message with reason: - * only player can execute command. - * - * @since 2.0.0-SNAPSHOT.1. - */ - fun throwOnlyPlayerCan() { - if (!generalConfiguration.getBool(SETTING_ENABLE_CONSOLE_COLORS)) { - logger.warn("> Only player can execute this command") - } else { - logger.warn("§7> §cOnly player can execute this command") - } - } - - /** - * Send response message on something to server console. - * @param message response message. - * @since 2.0.0-SNAPSHOT.1. - */ - fun response(message: String) = response { message } - - /** - * Send response message on something to server console. - * @param message response message. - * @since 2.0.0-SNAPSHOT.2. - */ - fun response(message: () -> String) = logger.info( - "§7> §r${if (!generalConfiguration.getBool(SETTING_ENABLE_CONSOLE_COLORS)) { - message().replace(Regex("[&§][0-9a-fk-or]"), String.empty) - } else { - message().replace("&", "§") - }}" - ) - - /** - * Send list like response to server. - * - * For example, list all player homes or - * warps or permissions, etc. - * - * @param list list to display in server console. - * @param title list title, list name or something like that. - * @since 2.0.0-RC.3. - */ - fun listAsResponse(list: List, title: () -> String) = response { - """ - §6${title()} - -${list.joinToString(separator = ",\n") { " §7> §c$it" }} - """ - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/messaging/package-info.java b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/messaging/package-info.java deleted file mode 100644 index 3109e50..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/messaging/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Package contains classes and other for interacting - * with player messages and something like messaging. - */ -package com.mairwunnx.projectessentials.core.api.v1.messaging; diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/IModule.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/IModule.kt deleted file mode 100644 index 65e9cb0..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/IModule.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.module - -/** - * Base interface for all Project Essentials modules. - * @since 2.0.0-SNAPSHOT.1. - */ -interface IModule { - /** - * Module name, for example `core` or `basic`. - * @since 2.0.0-RC.2. - */ - val name: String - - /** - * Module version, for example `1.0.0-SNAPSHOT.1+`, or - * `1.15.2-1.606.31.91`. - * - * @since 2.0.0-RC.2. - */ - val version: String - - /** - * Loading index, can't contains two and more - * modules with same load index. - * - * Affects on loading order, for example: - * - * > 0 - first to load. 100 - last to load. - * - * @since 2.0.0-RC.2. - */ - val loadIndex: Int - - /** - * Initialize the module, calling main mod functions. - * @since 2.0.0-SNAPSHOT.1. - */ - fun init() -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/ModuleAPI.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/ModuleAPI.kt deleted file mode 100644 index a888487..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/ModuleAPI.kt +++ /dev/null @@ -1,93 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.module - -import com.mairwunnx.projectessentials.core.api.v1.events.ModuleEventAPI -import com.mairwunnx.projectessentials.core.api.v1.events.internal.ModuleCoreEventType -import com.mairwunnx.projectessentials.core.api.v1.events.internal.ModuleEventData -import com.mairwunnx.projectessentials.core.api.v1.extensions.empty -import com.mairwunnx.projectessentials.core.api.v1.providers.ProviderAPI -import com.mairwunnx.projectessentials.core.api.v1.providers.ProviderType -import net.minecraftforge.fml.ModList -import net.minecraftforge.fml.common.Mod -import org.apache.logging.log4j.LogManager - -/** - * Class for interacting with other modules. - * @since 2.0.0-SNAPSHOT.1. - */ -@Suppress("unused", "MemberVisibilityCanBePrivate") -object ModuleAPI { - private val logger = LogManager.getLogger() - private var modules = mutableListOf() - - /** - * Removes all registered modules. - * @since 2.1.0. - */ - fun dispose() = modules.clear() - - /** - * @return all installed and checked modules. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getModules() = modules - - /** - * @return module mod id what declared in `@Mod` annotation. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getModuleModId(module: IModule): String { - if (module.javaClass.isAnnotationPresent(Mod::class.java)) { - return module.javaClass.getAnnotation(Mod::class.java).value - } - return "project_essentials_${module.name.toLowerCase()}" - } - - /** - * @return module by provided name. - * @throws ModuleNotFoundException when module not found. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getModuleByName(name: String) = - getModules().asSequence().find { it.name.toLowerCase() == name.toLowerCase() }?.let { - return@let it - } ?: throw ModuleNotFoundException( - "Module with name $name not found and not processed." - ) - - /** - * @param module module name what provided in Module annotation. - * @return true if module existing or installed. - * @since 2.0.0-SNAPSHOT.1. - */ - fun isModuleExist(module: String) = getModules().asSequence().find { - it.name.toLowerCase() == module.toLowerCase() - }.let { return@let it != null } - - internal fun initializeOrdered() { - ProviderAPI.getProvidersByType(ProviderType.Module).forEach { - val clazz = if (it.isAnnotationPresent(Mod::class.java)) { - ModList.get().getModObjectById( - it.getAnnotation(Mod::class.java)?.value ?: String.empty - ).get() - } else it.newInstance() as IModule - ModuleEventAPI.fire(ModuleCoreEventType.OnModuleClassProcessing, ModuleEventData(clazz)) - processIndexes(clazz.loadIndex) - logger.debug( - "Project Essentials module found: ${it.simpleName}, name: ${clazz.name}, version: ${clazz.version}" - ) - modules.add(clazz) - ModuleEventAPI.fire(ModuleCoreEventType.OnModuleClassProcessed, ModuleEventData(clazz)) - }.run { initialize() } - } - - private fun initialize() = - modules.asSequence().sortedWith(compareBy { by -> by.loadIndex }).forEach { module -> - logger.info("Starting initializing module ${module.name}").also { module.init() } - } - - private fun processIndexes(index: Int) { - modules.asSequence().find { it.loadIndex == index }?.let { - throw ModuleIndexDuplicateException("Module with same load index $index already processed.") - } - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/ModuleIndexDuplicateException.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/ModuleIndexDuplicateException.kt deleted file mode 100644 index 6028d4a..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/ModuleIndexDuplicateException.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.module - -import com.mairwunnx.projectessentials.core.api.v1.extensions.empty - -/** - * Throws when module with same load index already exist. - * @param message exception message. - * @since 2.0.0-SNAPSHOT.1. - */ -class ModuleIndexDuplicateException(message: String = String.empty) : Exception(message) diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/ModuleNotFoundException.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/ModuleNotFoundException.kt deleted file mode 100644 index 4373468..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/ModuleNotFoundException.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.module - -import com.mairwunnx.projectessentials.core.api.v1.extensions.empty - -/** - * Throws when module not found. - * @param message exception message. - * @since 2.0.0-SNAPSHOT.1. - */ -class ModuleNotFoundException(message: String = String.empty) : Exception(message) diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/package-info.java b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/package-info.java deleted file mode 100644 index cc96901..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/module/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Package contains all classes \ interfaces and other - * for module system. - */ -package com.mairwunnx.projectessentials.core.api.v1.module; diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/package-info.java b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/package-info.java deleted file mode 100644 index b8b6961..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Represent core api as first version of api. - */ -package com.mairwunnx.projectessentials.core.api.v1; diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/permissions/PermissionAPI.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/permissions/PermissionAPI.kt deleted file mode 100644 index 3516f3b..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/permissions/PermissionAPI.kt +++ /dev/null @@ -1,36 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.permissions - -import com.mairwunnx.projectessentials.core.api.v1.permissions.strategy.DefaultPermissionResolutionStrategy -import com.mairwunnx.projectessentials.core.api.v1.permissions.strategy.IPermissionResolutionStrategy -import net.minecraft.entity.player.ServerPlayerEntity - -/** - * Permission resolution strategy. - * - * By default uses default resolution strategy - * [DefaultPermissionResolutionStrategy] class. - * - * You can change resolution strategy at any time. - * - * @since 2.0.0-RC.2. - */ -var permissionResolutionStrategy: IPermissionResolutionStrategy = - DefaultPermissionResolutionStrategy() - -/** - * Uses installed forge permissions provider for - * checking permissions. - * - * This like extension but it also checks operator level - * if permission node not exist. - * - * @param player target player for checking - * permissions. - * @param node required permission node. - * @param opLevel required operator level. - * @return true if player has permission. - * @since 2.0.0-SNAPSHOT.1. - */ -fun hasPermission( - player: ServerPlayerEntity, node: String, opLevel: Int -) = permissionResolutionStrategy.hasPermission(player, node, opLevel) diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/permissions/package-info.java b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/permissions/package-info.java deleted file mode 100644 index 53bbd8b..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/permissions/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Package contains classes for interacting with - * permissions api. - */ -package com.mairwunnx.projectessentials.core.api.v1.permissions; diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/permissions/strategy/DefaultPermissionResolutionStrategy.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/permissions/strategy/DefaultPermissionResolutionStrategy.kt deleted file mode 100644 index 3035740..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/permissions/strategy/DefaultPermissionResolutionStrategy.kt +++ /dev/null @@ -1,27 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.permissions.strategy - -import net.minecraft.entity.player.ServerPlayerEntity -import net.minecraftforge.server.permission.DefaultPermissionHandler -import net.minecraftforge.server.permission.PermissionAPI - -/** - * Default permission resolution strategy. - * - * Checks permission node existing, and - * if permission node not exist, will check - * operator level. - * - * @since 2.0.0-RC.2. - */ -class DefaultPermissionResolutionStrategy : IPermissionResolutionStrategy { - override fun hasPermission( - player: ServerPlayerEntity, node: String, opLevel: Int - ) = if (PermissionAPI.getPermissionHandler() is DefaultPermissionHandler) { - when { - PermissionAPI.hasPermission(player, node) -> true - else -> player.hasPermissionLevel(opLevel) - } - } else { - PermissionAPI.hasPermission(player, node) - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/permissions/strategy/IPermissionResolutionStrategy.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/permissions/strategy/IPermissionResolutionStrategy.kt deleted file mode 100644 index f074480..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/permissions/strategy/IPermissionResolutionStrategy.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.permissions.strategy - -import net.minecraft.entity.player.ServerPlayerEntity - -/** - * Permission resolution strategy base interface - * for classes. - * - * @since 2.0.0-RC.2. - */ -interface IPermissionResolutionStrategy { - /** - * @param player [ServerPlayerEntity] class instance. - * @param node permission node to check. - * @param opLevel callback operator level, for additional checking. - * @return true if user has permission node - * or op level *(depends on resolution strategy)*. - * - * @since 2.0.0-RC.2. - */ - fun hasPermission( - player: ServerPlayerEntity, node: String, opLevel: Int - ): Boolean -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/providers/ProviderAPI.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/providers/ProviderAPI.kt deleted file mode 100644 index 1297c22..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/providers/ProviderAPI.kt +++ /dev/null @@ -1,79 +0,0 @@ -@file:Suppress("MemberVisibilityCanBePrivate") - -package com.mairwunnx.projectessentials.core.api.v1.providers - -import com.mairwunnx.projectessentials.core.api.v1.commands.ICommand -import com.mairwunnx.projectessentials.core.api.v1.configuration.IConfiguration -import com.mairwunnx.projectessentials.core.api.v1.module.IModule -import com.mairwunnx.projectessentials.core.api.v1.providersMarker -import org.apache.logging.log4j.LogManager -import java.util.* -import kotlin.collections.HashMap - - -/** - * Provider API class. If you build new module - * for project essentials then you must use this class. - * - * @since 2.0.0-SNAPSHOT.1. - */ -object ProviderAPI { - private val logger = LogManager.getLogger() - private val providers = Collections.synchronizedMap( - HashMap>>() - ) - - /** - * Adds target provider. (provider type will determine automatically) - * - * @param clazz provider class. - * @since 2.0.0-SNAPSHOT.1. - */ - fun addProvider(clazz: Class<*>) { - fun out(type: String) = logger.debug( - providersMarker, "Provider class found: Type: `$type`, Class: `${clazz.simpleName}`" - ) - - when { - IConfiguration::class.java.isAssignableFrom(clazz) -> { - addProvider(ProviderType.Configuration, clazz).run { out("Configuration") } - } - IModule::class.java.isAssignableFrom(clazz) -> { - addProvider(ProviderType.Module, clazz).run { out("Module") } - } - ICommand::class.java.isAssignableFrom(clazz) -> { - addProvider(ProviderType.Command, clazz).run { out("Command") } - } - else -> logger.warn( - providersMarker, - "Incorrect provider class found! (skipped to load): Class: `${clazz.simpleName}`" - ) - } - } - - /** - * Adds target provider with specified type. - * - * @param type provider type. - * @param clazz provider class. - * @since 2.0.0-SNAPSHOT.1. - */ - fun addProvider(type: ProviderType, clazz: Class<*>) { - synchronized(providers) { - providers[type]?.add(clazz) ?: providers.put(type, mutableListOf(clazz)) - } - } - - /** - * @return all added providers. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getProviders() = providers - - /** - * @param type provider type to return. - * @return all specified for type providers. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getProvidersByType(type: ProviderType) = getProviders()[type] ?: mutableListOf() -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/providers/ProviderType.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/providers/ProviderType.kt deleted file mode 100644 index 169b2e6..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/providers/ProviderType.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.mairwunnx.projectessentials.core.api.v1.providers - -/** - * Enum class of provider types. - * @since 2.0.0-SNAPSHOT.1. - */ -enum class ProviderType { Configuration, Module, Command } diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/providers/package-info.java b/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/providers/package-info.java deleted file mode 100644 index b60f0ac..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/api/v1/providers/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Package contains classes for interaction with providers. - */ -package com.mairwunnx.projectessentials.core.api.v1.providers; diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/GlobalScope.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/GlobalScope.kt deleted file mode 100644 index a31fffc..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/GlobalScope.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.mairwunnx.projectessentials.core.impl - -import com.mairwunnx.projectessentials.core.api.v1.configuration.ConfigurationAPI.getConfigurationByName -import com.mairwunnx.projectessentials.core.impl.configurations.GeneralConfiguration -import com.mairwunnx.projectessentials.core.impl.configurations.NativeMappingsConfiguration - -val generalConfiguration by lazy { - getConfigurationByName("general") -} - -val nativeMappingsConfiguration by lazy { - getConfigurationByName("native-mappings").take() -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/ModuleObject.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/ModuleObject.kt deleted file mode 100644 index 3648d5a..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/ModuleObject.kt +++ /dev/null @@ -1,169 +0,0 @@ -@file:Suppress("unused") - -package com.mairwunnx.projectessentials.core.impl - -import com.mairwunnx.projectessentials.core.api.v1.* -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAPI -import com.mairwunnx.projectessentials.core.api.v1.commands.back.BackLocationAPI -import com.mairwunnx.projectessentials.core.api.v1.configuration.ConfigurationAPI -import com.mairwunnx.projectessentials.core.api.v1.extensions.asPlayerEntity -import com.mairwunnx.projectessentials.core.api.v1.extensions.isPlayerEntity -import com.mairwunnx.projectessentials.core.api.v1.helpers.projectConfigDirectory -import com.mairwunnx.projectessentials.core.api.v1.messaging.MessagingAPI -import com.mairwunnx.projectessentials.core.api.v1.module.IModule -import com.mairwunnx.projectessentials.core.api.v1.module.ModuleAPI -import com.mairwunnx.projectessentials.core.api.v1.permissions.hasPermission -import com.mairwunnx.projectessentials.core.impl.commands.ConfigureEssentialsCommandAPI -import com.mairwunnx.projectessentials.core.impl.utils.NativeCommandUtils.insertNativeAliases -import com.mairwunnx.projectessentials.core.impl.utils.NativeCommandUtils.replaceRequirementPredicates -import com.mairwunnx.projectessentials.core.impl.vanilla.commands.* -import com.mojang.brigadier.CommandDispatcher -import net.minecraft.command.CommandSource -import net.minecraft.entity.player.ServerPlayerEntity -import net.minecraft.util.text.event.ClickEvent -import net.minecraftforge.common.MinecraftForge -import net.minecraftforge.event.entity.living.LivingDeathEvent -import net.minecraftforge.event.entity.player.PlayerEvent -import net.minecraftforge.event.world.BlockEvent -import net.minecraftforge.eventbus.api.EventPriority -import net.minecraftforge.eventbus.api.SubscribeEvent -import net.minecraftforge.fml.event.server.FMLServerStartingEvent -import net.minecraftforge.fml.event.server.FMLServerStoppingEvent -import org.apache.logging.log4j.LogManager -import java.io.File - -internal class ModuleObject : IModule { - override val name = this::class.java.`package`.implementationTitle.split(" ").last() - override val version = this::class.java.`package`.implementationVersion!! - override val loadIndex = 0 - - private var dudeFuckedOff = true - - init { - MinecraftForge.EVENT_BUS.register(this) - } - - override fun init() = initializeModuleSettings() - - @SubscribeEvent - fun onPortalSpawning(event: BlockEvent.PortalSpawnEvent) { - if (generalConfiguration.getBool(SETTING_DISABLE_PORTAL_SPAWNING)) { - event.isCanceled = true - return - } - } - - @SubscribeEvent - fun onPlayerDeath(event: LivingDeathEvent) { - if (event.entityLiving.isPlayerEntity) { - with(event.entityLiving.asPlayerEntity) { - if ( - hasPermission(this, "ess.teleport.back.ondeath", 3) || - hasPermission(this, "ess.back.ondeath", 3) - ) BackLocationAPI.commit(this) - } - } - } - - @SubscribeEvent - fun onServerStopping( - @Suppress("UNUSED_PARAMETER") - event: FMLServerStoppingEvent - ) = ConfigurationAPI.saveAll().also { ModuleAPI.dispose() }.also { ConfigurationAPI.dispose() } - - @SubscribeEvent(priority = EventPriority.HIGHEST) - fun onServerStarting(event: FMLServerStartingEvent) { - dudeFuckedOff = File( - projectConfigDirectory + File.separator + "fuck-off-dude.txt" - ).exists().also { if (!it) printGreetingMessage() } - - CommandAPI.assignDispatcher(event.commandDispatcher) - if (generalConfiguration.getBool(SETTING_NATIVE_COMMAND_REPLACE)) { - registerNativeCommands(event.commandDispatcher) - } - if (generalConfiguration.getBool(SETTING_NATIVE_COMMAND_REQUIRE_PREDICATE_REPLACE)) { - replaceRequirementPredicates() - } - if (generalConfiguration.getBool(SETTING_NATIVE_COMMAND_ALIASES_REPLACE)) { - insertNativeAliases() - } - CommandAPI.registerAll() - } - - @SubscribeEvent - fun onPlayerLeave(event: PlayerEvent.PlayerLoggedOutEvent) { - BackLocationAPI.revoke(event.player as ServerPlayerEntity) - } - - @SubscribeEvent - fun onPlayerJoin(event: PlayerEvent.PlayerLoggedInEvent) { - if (!dudeFuckedOff) { - val player = event.player as ServerPlayerEntity - - when { - hasPermission(player, "ess.notification.support", 4) -> MessagingAPI.sendMessage( - player, - """ -§6Notification from §7Project Essentials - -§fProject Essentials - the project is based on the enthusiasm of the author, the project is completely free to use and distribute. However, the author needs material support, that is, a donate. -Project Essentials §c§ois not a commercial project §fand all its modules distributed free and not have any restrictions. - -§7[ §c-> §7Support the project §6§nhttps://git.io/JfZ1V§7 ] - """.trim(), - false, - clickEvent = ClickEvent(ClickEvent.Action.OPEN_URL, "https://git.io/JfZ1V") - ) - } - } - } - - private fun initializeModuleSettings() { - generalConfiguration.getBoolOrDefault(SETTING_LOC_ENABLED, false) - generalConfiguration.getStringOrDefault(SETTING_LOC_FALLBACK_LANG, "en_us") - generalConfiguration.getBoolOrDefault(SETTING_DISABLE_SAFE_ENCHANT, false) - generalConfiguration.getBoolOrDefault(SETTING_NATIVE_COMMAND_ALIASES_REPLACE, true) - generalConfiguration.getIntOrDefault(SETTING_LOCATE_COMMAND_FIND_RADIUS, 100) - generalConfiguration.getBoolOrDefault(SETTING_DISABLE_PORTAL_SPAWNING, false) - generalConfiguration.getBoolOrDefault(SETTING_DEOP_COMMAND_REMOVE_OP_PERM, true) - generalConfiguration.getIntOrDefault(SETTING_LIST_MAX_ELEMENTS_IN_PAGE, 8) - generalConfiguration.getBoolOrDefault(SETTING_ENABLE_CONSOLE_COLORS, false) - generalConfiguration.getBoolOrDefault(SETTING_NATIVE_COMMAND_REPLACE, true) - generalConfiguration.getBoolOrDefault( - SETTING_NATIVE_COMMAND_REQUIRE_PREDICATE_REPLACE, true - ) - - ConfigureEssentialsCommandAPI.required(SETTING_NATIVE_COMMAND_REPLACE) - ConfigureEssentialsCommandAPI.required(SETTING_NATIVE_COMMAND_REQUIRE_PREDICATE_REPLACE) - ConfigureEssentialsCommandAPI.required(SETTING_NATIVE_COMMAND_ALIASES_REPLACE) - } - - private fun printGreetingMessage() = LogManager.getLogger().warn( - """ - -Notification from Project Essentials - -Project Essentials - the project is based on the enthusiasm of the author, the project is completely free to use and distribute. However, the author needs material support, that is, a donate. -Project Essentials **is not a commercial project** and all its modules distributed free and not have any restrictions. - -I will be very happy with your support, below is a link to the donation documentation and how to disable this annoying alert. -For support project you can also put an star on the Project Essentials repository. - -Thanks for using my project! Github organization https://github.com/ProjectEssentials ] -[ -> Support the project https://git.io/JfZ1V ] - - """ - ) - - private fun registerNativeCommands(dispatcher: CommandDispatcher) { - EnchantCommand.register(dispatcher) - GameModeCommand.register(dispatcher) - ReloadCommand.register(dispatcher) - SaveAllCommand.register(dispatcher) - TimeCommand.register(dispatcher) - WeatherCommand.register(dispatcher) - TeleportCommand().register(dispatcher) - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/commands/BackLocationCommand.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/commands/BackLocationCommand.kt deleted file mode 100644 index 5fee581..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/commands/BackLocationCommand.kt +++ /dev/null @@ -1,50 +0,0 @@ -package com.mairwunnx.projectessentials.core.impl.commands - -import com.mairwunnx.projectessentials.core.api.v1.MESSAGE_CORE_PREFIX -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandBase -import com.mairwunnx.projectessentials.core.api.v1.commands.back.BackLocationAPI -import com.mairwunnx.projectessentials.core.api.v1.extensions.getPlayer -import com.mairwunnx.projectessentials.core.api.v1.extensions.isPlayerSender -import com.mairwunnx.projectessentials.core.api.v1.messaging.MessagingAPI -import com.mairwunnx.projectessentials.core.api.v1.messaging.ServerMessagingAPI -import com.mairwunnx.projectessentials.core.api.v1.permissions.hasPermission -import com.mojang.brigadier.builder.LiteralArgumentBuilder.literal -import com.mojang.brigadier.context.CommandContext -import net.minecraft.command.CommandSource - -internal object BackLocationCommand : CommandBase(literal("back")) { - override val name = "back" - - override fun process(context: CommandContext): Int { - if (context.isPlayerSender()) { - val player = context.getPlayer()!! - - if ( - hasPermission(player, "ess.teleport.back", 2) || - hasPermission(player, "ess.back", 2) - ) { - val data = BackLocationAPI.take(player) - - if (data != null) { - val pos = data.position - val rot = data.rotation - - player.teleport( - data.world, pos.xPos, pos.yPos, pos.zPos, rot.yaw, rot.pitch - ) - - BackLocationAPI.revoke(player) - MessagingAPI.sendMessage(player, "$MESSAGE_CORE_PREFIX.back.success") - } else { - MessagingAPI.sendMessage(player, "$MESSAGE_CORE_PREFIX.back.tickets_not_exists") - } - super.process(context) - } else { - MessagingAPI.sendMessage(player, "$MESSAGE_CORE_PREFIX.back.restricted") - } - } else { - ServerMessagingAPI.throwOnlyPlayerCan() - } - return 0 - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/commands/CommandLiterals.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/commands/CommandLiterals.kt deleted file mode 100644 index ebcf7d5..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/commands/CommandLiterals.kt +++ /dev/null @@ -1,28 +0,0 @@ -package com.mairwunnx.projectessentials.core.impl.commands - -import com.mairwunnx.projectessentials.core.api.v1.configuration.ConfigurationAPI.getConfigurationByName -import com.mairwunnx.projectessentials.core.impl.configurations.GeneralConfiguration -import com.mojang.brigadier.arguments.StringArgumentType -import com.mojang.brigadier.builder.LiteralArgumentBuilder -import net.minecraft.command.CommandSource -import net.minecraft.command.Commands -import net.minecraft.command.ISuggestionProvider - -inline val configureEssentialsLiteral: LiteralArgumentBuilder - get() = Commands.literal("configure-essentials").then( - Commands.argument( - "setting", StringArgumentType.string() - ).suggests { _, builder -> - ISuggestionProvider.suggest( - getConfigurationByName( - "general" - ).take().keys.map { it as String }, builder - ) - }.then( - Commands.literal("set").then( - Commands.argument("value", StringArgumentType.string()).executes { - ConfigureEssentialsCommand.process(it) - } - ) - ) - ) diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/commands/ConfigureEssentialsCommand.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/commands/ConfigureEssentialsCommand.kt deleted file mode 100644 index e7e334e..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/commands/ConfigureEssentialsCommand.kt +++ /dev/null @@ -1,128 +0,0 @@ -package com.mairwunnx.projectessentials.core.impl.commands - -import com.mairwunnx.projectessentials.core.api.v1.MESSAGE_CORE_PREFIX -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAPI -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandBase -import com.mairwunnx.projectessentials.core.api.v1.extensions.getPlayer -import com.mairwunnx.projectessentials.core.api.v1.extensions.isPlayerSender -import com.mairwunnx.projectessentials.core.api.v1.extensions.playerName -import com.mairwunnx.projectessentials.core.api.v1.messaging.MessagingAPI -import com.mairwunnx.projectessentials.core.api.v1.messaging.ServerMessagingAPI -import com.mairwunnx.projectessentials.core.api.v1.permissions.hasPermission -import com.mairwunnx.projectessentials.core.impl.commands.ConfigureEssentialsCommandAPI.requiredServerRestart -import com.mairwunnx.projectessentials.core.impl.generalConfiguration -import com.mojang.brigadier.context.CommandContext -import net.minecraft.command.CommandSource -import org.apache.logging.log4j.LogManager - -/** - * Configure essentials command api, basically stores - * only [requiredServerRestart] list with setting names - * what after change requires server restart. - * - * @since 2.0.0-SNAPSHOT.1. - */ -@Suppress("unused") -object ConfigureEssentialsCommandAPI { - private val requiredServerRestart = mutableListOf() - - /** - * Adds setting to list with configurations what after change - * requires server restart or configuration reloading. - * - * @param setting setting name. - * @return true if setting added. - * @since 2.0.0-SNAPSHOT.1. - */ - fun required(setting: String) = requiredServerRestart.add(setting) - - /** - * @param setting setting name. - * @return true if [setting] is requires server restart - * after value change. - * @since 2.0.0-SNAPSHOT.1. - */ - fun isRequired(setting: String) = requiredServerRestart.contains(setting) - - /** - * @return list with settings what requires server restart - * after value changing. - * @since 2.0.0-SNAPSHOT.1. - */ - fun getRequired() = requiredServerRestart.toList() -} - -object ConfigureEssentialsCommand : CommandBase( - configureEssentialsLiteral, false -) { - override val name = "configure-essentials" - - override fun process(context: CommandContext): Int { - val setting = CommandAPI.getString(context, "setting") - val value = CommandAPI.getString(context, "value") - - if (!validateArguments(setting, value)) { - if (context.isPlayerSender()) { - MessagingAPI.sendMessage( - context.getPlayer()!!, - "$MESSAGE_CORE_PREFIX.configure.not_found", - args = *arrayOf(name) - ) - } else { - ServerMessagingAPI.response { "Setting with name $name not exist or value has incorrect format." } - } - return 0 - } - - val oldValue = generalConfiguration.take().getValue(setting).toString() - - if (context.isPlayerSender()) { - if (hasPermission(context.getPlayer()!!, "ess.configure.essentials.$setting", 4)) { - if (ConfigureEssentialsCommandAPI.isRequired(setting)) { - LogManager.getLogger().info( - "Setting name `$setting` value changed by ${context.playerName()} from `$oldValue` to $value, but restart required for applying changes." - ) - MessagingAPI.sendMessage( - context.getPlayer()!!, - "$MESSAGE_CORE_PREFIX.configure.successfully_required_restart", - args = *arrayOf(setting, oldValue, value) - ) - } else { - LogManager.getLogger().info( - "Setting name `$setting` value changed by ${context.playerName()} from `$oldValue` to $value" - ) - MessagingAPI.sendMessage( - context.getPlayer()!!, - "$MESSAGE_CORE_PREFIX.configure.successfully", - args = *arrayOf(setting, oldValue, value) - ) - } - generalConfiguration.put(setting, value) - super.process(context) - } else { - MessagingAPI.sendMessage( - context.getPlayer()!!, - "$MESSAGE_CORE_PREFIX.configure.restricted", - args = *arrayOf(setting) - ) - } - } else { - if (ConfigureEssentialsCommandAPI.isRequired(setting)) { - ServerMessagingAPI.response( - "Setting name `$setting` value changed from `$oldValue` to $value, but restart required for applying changes." - ) - } else { - ServerMessagingAPI.response( - "Setting name `$setting` value changed from `$oldValue` to $value" - ) - } - generalConfiguration.put(setting, value) - super.process(context) - } - return 0 - } - - private fun validateArguments(setting: String, value: String) = - generalConfiguration.take().keys.filter { it as String == setting }.count() > 0 && - value.isNotBlank() && !Regex("[=|:@$^*]").containsMatchIn(value) -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/configurations/GeneralConfiguration.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/configurations/GeneralConfiguration.kt deleted file mode 100644 index fa7614b..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/configurations/GeneralConfiguration.kt +++ /dev/null @@ -1,117 +0,0 @@ -@file:Suppress("unused") - -package com.mairwunnx.projectessentials.core.impl.configurations - -import com.mairwunnx.projectessentials.core.api.v1.configuration.IConfiguration -import com.mairwunnx.projectessentials.core.api.v1.extensions.empty -import com.mairwunnx.projectessentials.core.api.v1.helpers.projectConfigDirectory -import org.apache.logging.log4j.LogManager -import java.io.File -import java.io.FileInputStream -import java.io.FileOutputStream -import java.io.IOException -import java.util.* - -object GeneralConfiguration : IConfiguration { - private val logger = LogManager.getLogger() - private val properties = Properties() - - override val name = "general" - override val version = 1 - override val configuration = take() - override val path = projectConfigDirectory + File.separator + "general.properties" - - override fun load() = try { - File(path).parentFile.mkdirs() - File(path).createNewFile() - FileInputStream(path).use { input -> - properties.load(input) - } - } catch (ex: IOException) { - logger.error("An error occurred while loading general configuration.", ex) - } - - override fun save() = try { - logger.info("Saving configuration `${name}`") - FileOutputStream(path).use { output -> - properties.store(output, null) - } - } catch (ex: IOException) { - logger.error("An error occurred while saving general configuration.", ex) - } - - override fun take() = properties - - @Synchronized - fun getDoubleOrDefault(key: String, value: Double): Double { - val property = properties[key] - if (property == null) put(key, value.toString()) - return properties[key]?.toString()?.toDouble() ?: value - } - - @Synchronized - fun getDouble(key: String) = properties[key].toString().toDouble() - - @Synchronized - fun getFloatOrDefault(key: String, value: Float): Float { - val property = properties[key] - if (property == null) put(key, value.toString()) - return properties[key]?.toString()?.toFloat() ?: value - } - - @Synchronized - fun getFloatInt(key: String) = properties[key].toString().toFloat() - - @Synchronized - fun getIntOrDefault(key: String, value: Int): Int { - val property = properties[key] - if (property == null) put(key, value.toString()) - return properties[key]?.toString()?.toInt() ?: value - } - - @Synchronized - fun getInt(key: String) = properties[key].toString().toInt() - - @Synchronized - fun getBoolOrDefault(key: String, value: Boolean): Boolean { - val property = properties[key] - if (property == null) put(key, value.toString()) - return properties[key]?.toString()?.toBoolean() ?: value - } - - @Synchronized - fun getBool(key: String) = properties[key].toString().toBoolean() - - @Synchronized - fun getStringOrDefault(key: String, value: String): String { - val property = properties[key] - if (property == null) put(key, value) - return properties[key]?.toString() ?: value - } - - @Synchronized - fun getString(key: String) = properties[key].toString() - - @Synchronized - fun getList( - key: String, defaultValue: ArrayList = arrayListOf() - ): List { - val rawList = getStringOrDefault(key, String.empty) - if (rawList.isBlank()) return defaultValue.also { putList(key, defaultValue) } - return rawList.trim('[', ']').replace("\"", "").let { - val list = mutableListOf() - if (it.contains(',') && it.count() > 3) { - it.split(',').forEach { value -> list.add(value.trim()) } - } else if (it.count() >= 1) { - list.add(it.trim()) - } - return@let list - } - } - - @Synchronized - fun putList(key: String, value: List) = properties.set(key, value.toString()) - - @Synchronized - fun put(key: String, value: String) = properties.set(key, value) -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/configurations/NativeMappingsConfiguration.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/configurations/NativeMappingsConfiguration.kt deleted file mode 100644 index 9a57268..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/configurations/NativeMappingsConfiguration.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.mairwunnx.projectessentials.core.impl.configurations - -import com.mairwunnx.projectessentials.core.api.v1.configuration.IConfiguration -import com.mairwunnx.projectessentials.core.api.v1.helpers.jsonInstance -import com.mairwunnx.projectessentials.core.api.v1.helpers.projectConfigDirectory -import org.apache.logging.log4j.LogManager -import java.io.File -import java.io.FileNotFoundException - -object NativeMappingsConfiguration : IConfiguration { - private val logger = LogManager.getLogger() - private var configurationData = NativeMappingsConfigurationModel() - - override val name = "native-mappings" - override val version = 1 - override val configuration = take() - override val path = projectConfigDirectory + File.separator + "native-mappings.json" - - override fun load() { - try { - val configRaw = File(path).readText() - configurationData = jsonInstance.parse( - NativeMappingsConfigurationModel.serializer(), configRaw - ) - } catch (ex: FileNotFoundException) { - logger.error("Configuration file ($path) not found!") - logger.warn("The default configuration will be used") - } - } - - override fun save() { - File(path).parentFile.mkdirs() - - logger.info("Saving configuration `${name}`") - val raw = jsonInstance.stringify( - NativeMappingsConfigurationModel.serializer(), configurationData - ) - try { - File(path).writeText(raw) - } catch (ex: SecurityException) { - logger.error( - "An error occurred while saving commands configuration", ex - ) - } - } - - override fun take() = configurationData -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/configurations/NativeMappingsConfigurationModel.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/configurations/NativeMappingsConfigurationModel.kt deleted file mode 100644 index 568b948..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/configurations/NativeMappingsConfigurationModel.kt +++ /dev/null @@ -1,44 +0,0 @@ -package com.mairwunnx.projectessentials.core.impl.configurations - -import kotlinx.serialization.Serializable - -@Serializable -data class NativeMappingsConfigurationModel( - val comment: String = "That is configuration still in experimental state! Something may work unstable.", - val permissions: MutableMap = mutableMapOf( - "_comment" to "Hello there! You can change permissions mappings there, in format \"command\":\"node@op-level\". By removing command there, Project Essentials will generate permissions node automatically bases on command name, for command advancements will generated permissions `native.advancements` with op level provided in `https://minecraft.gamepedia.com/Commands`.", - "ban" to "native.moderation.ban@3", - "ban-ip" to "native.moderation.banip@3", - "banlist" to "native.moderation.banlist@3", - "pardon" to "native.moderation.pardon@3", - "pardon-ip" to "native.moderation.pardonip@3", - "kick" to "native.moderation.kick@3", - "deop" to "native.stuff.operator.remove@3", - "op" to "native.stuff.operator.add@3", - "me" to "native.messaging.me@0", - "message" to "native.messaging.message@0", - "teammsg" to "native.messaging.teammsg@0", - "playsound" to "native.sound.play@2", - "stopsound" to "native.sound.stop@2", - "reload" to "native.server.reload@2", - "stop" to "native.server.stop@4", - "save-off" to "native.save.off@4", - "save-on" to "native.save.on@4", - "say" to "native.messaging.say@1" - ), - val aliases: MutableMap = mutableMapOf( - "_comment" to "There are command aliases, leave this empty if you want commands without aliases, if you want many aliases, enumerate that with `,`.", - "clear" to "ci", - "list" to "online", - "locate" to "find,where", - "pardon" to "unban", - "gamerule" to "gr", - "summon" to "spawnmob", - "pardonip" to "unbanip", - "sun" to "weatherclear,clearsky,sky", - "thunder" to "storm,goodweather", - "noon" to "midday,noonday", - "sunset" to "dusk,sundown,evening", - "sunrise" to "dawn,morning,morn" - ) -) diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/package-info.java b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/package-info.java deleted file mode 100644 index c6bfcbc..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Stores internal api and implementation for core module. - */ -package com.mairwunnx.projectessentials.core.impl; diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/utils/NativeCommandUtils.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/utils/NativeCommandUtils.kt deleted file mode 100644 index 62f69b4..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/utils/NativeCommandUtils.kt +++ /dev/null @@ -1,95 +0,0 @@ -package com.mairwunnx.projectessentials.core.impl.utils - -import com.mairwunnx.projectessentials.core.api.v1.SETTING_NATIVE_COMMAND_REPLACE -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAPI -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAliases -import com.mairwunnx.projectessentials.core.api.v1.helpers.getFieldsOf -import com.mairwunnx.projectessentials.core.api.v1.permissions.hasPermission -import com.mairwunnx.projectessentials.core.impl.generalConfiguration -import com.mairwunnx.projectessentials.core.impl.nativeMappingsConfiguration -import com.mojang.brigadier.tree.LiteralCommandNode -import com.mojang.brigadier.tree.RootCommandNode -import net.minecraft.command.CommandSource -import net.minecraft.command.Commands.literal -import net.minecraft.entity.player.PlayerEntity -import org.apache.logging.log4j.LogManager -import java.util.function.Predicate - -object NativeCommandUtils { - private val logger = LogManager.getLogger() - - private fun isOverridden(name: String) = - if (generalConfiguration.getBool(SETTING_NATIVE_COMMAND_REPLACE)) name in overridden else false - - internal fun replaceRequirementPredicates() { - logger.debug("Replacing native requirement predicates ...") - - CommandAPI.getDispatcher().root.children.asSequence().filter { node -> - node.name in natives && !isOverridden(node.name) - }.forEach { node -> - logger.debug("Replacing requirement predicate for ${node.name}") - try { - getFieldsOf(node.javaClass).find { field -> - field.name == "requirement" - }?.let { field -> - field.isAccessible = true - val cond = nativeMappingsConfiguration.permissions[node.name]?.let { notation -> - Predicate { source: CommandSource -> - if (source.entity is PlayerEntity) { - val pair = notation.split('@') - hasPermission(source.asPlayer(), pair.first(), pair.last().toInt()) - } else true - } - } ?: let { - node.requirement.or { source -> - if (source.entity is PlayerEntity) { - hasPermission(source.asPlayer(), "native.${node.name}", 4) - } else true - } - } - field.set(node, cond) - } ?: run { logger.debug("Not found requirement predicate field for ${node.name}") } - } catch (any: Exception) { - logger.error("Failed to replace requirement predicate for ${node.name}", any) - } - } - } - - internal fun insertNativeAliases() { - logger.debug("Replacing and inserting native aliases ...") - CommandAPI.getDispatcher().root.children.filter { node -> - node.name in natives && !isOverridden(node.name) - }.forEach { node -> - node as LiteralCommandNode - nativeMappingsConfiguration.aliases[node.literal]?.split(',')?.let { aliases -> - CommandAliases.aliases[node.name] = aliases.toMutableList() - if (aliases.isNotEmpty()) { - aliases.filter { it != node.literal }.forEach { alias -> - val lit = literal(alias).requires { - node.requirement.test(it) - }.executes { return@executes node.command?.run(it) ?: 0 } - node.children.forEach { if (node !is RootCommandNode<*>) lit.then(it) } - CommandAPI.getDispatcher().register(lit) - logger.debug("Alias literal ${lit.literal} registered for ${node.name}") - } - } - } - } - } - - val natives = listOf( - "advancement", "ban", "ban-ip", "banlist", "bossbar", "clear", "clone", "data", "datapack", - "debug", "defaultgamemode", "deop", "difficulty", "effect", "enchant", "execute", - "experience", "fill", "forceload", "function", "gamemode", "gamerule", "give", "help", - "kick", "kill", "list", "locate", "loot", "me", "msg", "op", "pardon", "particle", - "playsound", "publish", "recipe", "reload", "replaceitem", "save-all", "save-off", - "save-on", "say", "schedule", "scoreboard", "seed", "setblock", "setidletimeout", - "setworldspawn", "spawnpoint", "spectate", "spreadplayers", "stop", "stopsound", "summon", - "tag", "team", "teammsg", "teleport", "tell", "tellraw", "time", "title", "tp", "trigger", - "w", "weather", "whitelist", "worldborder", "xp" - ) - - val overridden = listOf( - "weather", "time", "save-all", "reload", "gamemode", "enchant", "teleport" - ) -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/EnchantCommand.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/EnchantCommand.kt deleted file mode 100644 index d97e83a..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/EnchantCommand.kt +++ /dev/null @@ -1,120 +0,0 @@ -/** - * ! This command implementation by Mojang Studios! - * - * Decompiled with idea source code was converted to kotlin code. - * But with additions such as permissions checking and etc. - * - * 1. This can be bad code. - * 2. This file can be not formatter pretty. - */ -package com.mairwunnx.projectessentials.core.impl.vanilla.commands - -import com.mairwunnx.projectessentials.core.api.v1.SETTING_DISABLE_SAFE_ENCHANT -import com.mairwunnx.projectessentials.core.impl.generalConfiguration -import com.mojang.brigadier.CommandDispatcher -import com.mojang.brigadier.arguments.IntegerArgumentType -import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType -import com.mojang.brigadier.exceptions.DynamicCommandExceptionType -import com.mojang.brigadier.exceptions.SimpleCommandExceptionType -import net.minecraft.command.CommandSource -import net.minecraft.command.Commands -import net.minecraft.command.arguments.EnchantmentArgument -import net.minecraft.command.arguments.EntityArgument -import net.minecraft.enchantment.Enchantment -import net.minecraft.enchantment.EnchantmentHelper.areAllCompatibleWith -import net.minecraft.enchantment.EnchantmentHelper.getEnchantments -import net.minecraft.entity.Entity -import net.minecraft.entity.LivingEntity -import net.minecraft.item.ItemStack -import java.util.function.Function -import net.minecraft.util.text.TranslationTextComponent as textComponentOf - -internal object EnchantCommand : VanillaCommandBase("enchant") { - override fun register(dispatcher: CommandDispatcher) { - super.register(dispatcher).also { - dispatcher.register( - Commands.literal(name).requires { - isAllowed(it, "enchant", 2) - }.then( - Commands.argument("targets", EntityArgument.entities()).requires { - isAllowed(it, "enchant.other", 3) - }.then( - Commands.argument( - "enchantment", EnchantmentArgument.enchantment() - ).executes { - enchant( - it.source, EntityArgument.getEntities(it, "targets"), - EnchantmentArgument.getEnchantment(it, "enchantment"), 1 - ) - }.then( - Commands.argument("level", IntegerArgumentType.integer(0)).executes { - enchant( - it.source, - EntityArgument.getEntities(it, "targets"), - EnchantmentArgument.getEnchantment(it, "enchantment"), - IntegerArgumentType.getInteger(it, "level") - ) - } - ) - ) - ) - ) - } - } - - private fun enchant( - source: CommandSource, targets: Collection, enchantmentIn: Enchantment, level: Int - ): Int { - if ( - level > enchantmentIn.maxLevel && - !generalConfiguration.getBool(SETTING_DISABLE_SAFE_ENCHANT) - ) throw invalidLevel.create(level, enchantmentIn.maxLevel) - - var counter = 0 - targets.forEach { entity -> - if (entity is LivingEntity) { - val iStack = entity.heldItemMainhand - if (!iStack.isEmpty) { - if (enchantmentIn.canApply(iStack) && validate(iStack, enchantmentIn)) { - iStack.addEnchantment(enchantmentIn, level).let { ++counter } - } else if (targets.size == 1) { - throw incompatibleEnchantsException.create(iStack.item.getDisplayName(iStack).string) - } - } else if (targets.size == 1) throw itemlessException.create(entity.name.string) - } else if (targets.size == 1) throw nonLivingEntityException.create(entity.name.string) - } - if (counter == 0) throw failedException.create() else { - if (targets.size == 1) { - feedback( - source, "single", enchantmentIn.getDisplayName(level), - targets.iterator().next().displayName - ) - } else feedback(source, "multiple", enchantmentIn.getDisplayName(level), targets.size) - } - return counter - } - - private fun feedback(source: CommandSource, mode: String, vararg args: Any) = - source.sendFeedback(textComponentOf("commands.enchant.success.$mode", args), true) - - private fun validate(iStack: ItemStack, enchantmentIn: Enchantment) = - areAllCompatibleWith(getEnchantments(iStack).keys, enchantmentIn) - - private val nonLivingEntityException = DynamicCommandExceptionType( - Function { textComponentOf("commands.enchant.failed.entity", it) } - ) - private val itemlessException = DynamicCommandExceptionType( - Function { textComponentOf("commands.enchant.failed.itemless", it) } - ) - private val incompatibleEnchantsException = DynamicCommandExceptionType( - Function { textComponentOf("commands.enchant.failed.incompatible", it) } - ) - private val invalidLevel = Dynamic2CommandExceptionType( - Dynamic2CommandExceptionType.Function { p_208840_0_, p_208840_1_ -> - textComponentOf("commands.enchant.failed.level", p_208840_0_, p_208840_1_) - } - ) - private val failedException = SimpleCommandExceptionType( - textComponentOf("commands.enchant.failed") - ) -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/GameModeCommand.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/GameModeCommand.kt deleted file mode 100644 index 3fb5815..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/GameModeCommand.kt +++ /dev/null @@ -1,81 +0,0 @@ -/** - * ! This command implementation by Mojang Studios! - * - * Decompiled with idea source code was converted to kotlin code. - * But with additions such as permissions checking and etc. - * - * 1. This can be bad code. - * 2. This file can be not formatter pretty. - */ -package com.mairwunnx.projectessentials.core.impl.vanilla.commands - -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAPI -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAliases -import com.mojang.brigadier.CommandDispatcher -import net.minecraft.command.CommandSource -import net.minecraft.command.Commands -import net.minecraft.command.arguments.EntityArgument -import net.minecraft.command.impl.GameModeCommand -import net.minecraft.world.GameType - -internal object GameModeCommand : VanillaCommandBase("gamemode") { - override fun register(dispatcher: CommandDispatcher) { - super.register(dispatcher).also { aliases() } - // @formatter:off - GameType.values().forEach { - if (it != GameType.NOT_SET) { - if (!it.getName().startsWith("sp")) short("gm${it.getName()[0]}", it) else short("gmsp", it) - } - } - // @formatter:on - val literal = Commands.literal(name) - GameType.values().forEach { type -> - if (type != GameType.NOT_SET) { - literal.requires { - isAllowedAny(it) { - listOf( - "native.gamemode.survival" to 2, - "native.gamemode.creative" to 2, - "native.gamemode.adventure" to 2, - "native.gamemode.spectator" to 2 - ) - } - }.then( - Commands.literal(type.getName()).requires { - isAllowed(it, "gamemode.${type.getName()}", 2) - }.executes { - GameModeCommand.setGameMode(it, setOf(it.source.asPlayer()), type) - }.then( - Commands.argument("target", EntityArgument.players()).requires { - isAllowed(it, "gamemode.${type.getName()}.other", 3) - }.executes { - GameModeCommand.setGameMode( - it, EntityArgument.getPlayers(it, "target"), type - ) - } - ) - ) - } - }.also { dispatcher.register(literal) } - } - - private fun aliases() { - CommandAliases.aliases["gamemode"]?.addAll(listOf("gmc", "gms", "gma", "gmsp")) ?: run { - CommandAliases.aliases.put("gamemode", mutableListOf("gmc", "gms", "gma", "gmsp")) - } - } - - private fun short(short: String, mode: GameType) { - Commands.literal(short).requires { - isAllowed(it, "gamemode.${mode.getName()}", 2) - }.executes { - GameModeCommand.setGameMode(it, setOf(it.source.asPlayer()), mode) - }.then( - Commands.argument("target", EntityArgument.players()).requires { - isAllowed(it, "gamemode.${mode.getName()}.other", 3) - }.executes { - GameModeCommand.setGameMode(it, EntityArgument.getPlayers(it, "target"), mode) - } - ).also { CommandAPI.getDispatcher().register(it) } - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/ReloadCommand.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/ReloadCommand.kt deleted file mode 100644 index effdc8f..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/ReloadCommand.kt +++ /dev/null @@ -1,30 +0,0 @@ -/** - * ! This command implementation by Mojang Studios! - * - * Decompiled with idea source code was converted to kotlin code. - * But with additions such as permissions checking and etc. - * - * 1. This can be bad code. - * 2. This file can be not formatter pretty. - */ -package com.mairwunnx.projectessentials.core.impl.vanilla.commands - -import com.mairwunnx.projectessentials.core.api.v1.configuration.ConfigurationAPI -import com.mojang.brigadier.CommandDispatcher -import net.minecraft.command.CommandSource -import net.minecraft.command.Commands -import net.minecraft.util.text.TranslationTextComponent - -internal object ReloadCommand : VanillaCommandBase("reload") { - override fun register(dispatcher: CommandDispatcher) { - super.register(dispatcher) - dispatcher.register( - Commands.literal(name).requires { - isAllowed(it, "server.reload", 2) - }.executes { - it.source.sendFeedback(TranslationTextComponent("commands.reload.success"), true) - it.source.server.reload().also { ConfigurationAPI.reloadAll() }.let { 0 } - } - ) - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/SaveAllCommand.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/SaveAllCommand.kt deleted file mode 100644 index 1fa2c18..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/SaveAllCommand.kt +++ /dev/null @@ -1,35 +0,0 @@ -/** - * ! This command implementation by Mojang Studios! - * - * Decompiled with idea source code was converted to kotlin code. - * But with additions such as permissions checking and etc. - * - * 1. This can be bad code. - * 2. This file can be not formatter pretty. - */ -package com.mairwunnx.projectessentials.core.impl.vanilla.commands - -import com.mairwunnx.projectessentials.core.api.v1.configuration.ConfigurationAPI -import com.mojang.brigadier.CommandDispatcher -import net.minecraft.command.CommandSource -import net.minecraft.command.Commands -import net.minecraft.command.impl.SaveAllCommand - -internal object SaveAllCommand : VanillaCommandBase("save-all") { - override fun register(dispatcher: CommandDispatcher) { - super.register(dispatcher) - dispatcher.register( - Commands.literal(name).requires { - isAllowed(it, "save.all", 4) - }.executes { - ConfigurationAPI.saveAll() - SaveAllCommand.saveAll(it.source, false) - }.then( - Commands.literal("flush").executes { - ConfigurationAPI.saveAll() - SaveAllCommand.saveAll(it.source, true) - } - ) - ) - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/TimeCommand.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/TimeCommand.kt deleted file mode 100644 index 1fbe2ac..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/TimeCommand.kt +++ /dev/null @@ -1,129 +0,0 @@ -/** - * ! This command implementation by Mojang Studios! - * - * Decompiled with idea source code was converted to kotlin code. - * But with additions such as permissions checking and etc. - * - * 1. This can be bad code. - * 2. This file can be not formatter pretty. - */ -package com.mairwunnx.projectessentials.core.impl.vanilla.commands - -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAPI.getDispatcher -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAliases -import com.mairwunnx.projectessentials.core.impl.nativeMappingsConfiguration -import com.mojang.brigadier.CommandDispatcher -import com.mojang.brigadier.arguments.IntegerArgumentType -import net.minecraft.command.CommandSource -import net.minecraft.command.Commands -import net.minecraft.command.Commands.literal -import net.minecraft.command.arguments.TimeArgument -import net.minecraft.command.impl.TimeCommand - -internal object TimeCommand : VanillaCommandBase("time") { - override fun register(dispatcher: CommandDispatcher) { - super.register(dispatcher) - short("day", 1000) - short("noon", 6000) - short("sunset", 12000) - short("night", 13000) - short("midnight", 18000) - short("sunrise", 23000) - aliases() - - dispatcher.register( - literal("time").requires { - isAllowedAny(it) { - listOf("time.change.set" to 2, "time.change.add" to 2, "time.query" to 2) - } - }.then( - literal("set").requires { permission(it, "set") }.then( - literal("day").executes { - TimeCommand.setTime(it.source, 1000) - } - ).then( - literal("noon").executes { - TimeCommand.setTime(it.source, 6000) - } - ).then( - literal("sunset").executes { - TimeCommand.setTime(it.source, 12000) - } - ).then( - literal("night").executes { - TimeCommand.setTime(it.source, 13000) - } - ).then( - literal("midnight").executes { - TimeCommand.setTime(it.source, 18000) - } - ).then( - literal("sunrise").executes { - TimeCommand.setTime(it.source, 23000) - } - ).then( - Commands.argument( - "time", TimeArgument.func_218091_a() - ).executes { - TimeCommand.setTime(it.source, IntegerArgumentType.getInteger(it, "time")) - } - ) - ).then( - literal("add").requires { permission(it, "add") }.then( - Commands.argument( - "time", TimeArgument.func_218091_a() - ).executes { - TimeCommand.addTime(it.source, IntegerArgumentType.getInteger(it, "time")) - } - ) - ).then( - literal("query").requires { permission(it, "query") }.then( - literal("daytime").executes { - TimeCommand.sendQueryResults( - it.source, TimeCommand.getDayTime(it.source.world) - ) - } - ).then( - literal("gametime").executes { - TimeCommand.sendQueryResults( - it.source, (it.source.world.gameTime % 2147483647L).toInt() - ) - } - ).then( - literal("day").executes { - TimeCommand.sendQueryResults( - it.source, (it.source.world.dayTime / 24000L % 2147483647L).toInt() - ) - } - ) - ) - ) - } - - private fun permission(source: CommandSource, type: String): Boolean { - val node = if (type == "add" || type == "set") { - "time.change.$type" - } else "time.query" - return isAllowed(source, node, 2) - } - - fun short(name: String, time: Int) { - aliasesOf(name).forEach { command -> - getDispatcher().register(literal(command).requires { - permission(it, "set") - }.executes { TimeCommand.setTime(it.source, time) }) - } - } - - private fun aliases() { - CommandAliases.aliases["noon"] = (aliasesOf("noon") + "time").toMutableList() - CommandAliases.aliases["sunset"] = (aliasesOf("sunset") + "time").toMutableList() - CommandAliases.aliases["sunrise"] = (aliasesOf("sunrise") + "time").toMutableList() - CommandAliases.aliases["night"] = (aliasesOf("night") + "time").toMutableList() - CommandAliases.aliases["midnight"] = (aliasesOf("midnight") + "time").toMutableList() - } - - private fun aliasesOf(origin: String) = nativeMappingsConfiguration.aliases[origin]?.let { - return@let it.split(',') + origin - } ?: let { return@let listOf(origin) } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/VanillaCommandBase.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/VanillaCommandBase.kt deleted file mode 100644 index 726a03d..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/VanillaCommandBase.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.mairwunnx.projectessentials.core.impl.vanilla.commands - -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAPI -import com.mairwunnx.projectessentials.core.api.v1.permissions.hasPermission -import com.mojang.brigadier.CommandDispatcher -import net.minecraft.command.CommandSource -import net.minecraft.entity.player.ServerPlayerEntity -import org.apache.logging.log4j.LogManager - -abstract class VanillaCommandBase(val name: String) { - open fun register(dispatcher: CommandDispatcher) { - CommandAPI.removeCommand(name) - LogManager.getLogger().info("Native command replacing implementation for $name") - } - - companion object { - @JvmStatic - fun isAllowed(source: CommandSource, node: String, opLevel: Int) = - if (source.entity is ServerPlayerEntity) { - hasPermission(source.asPlayer(), "native.$node", opLevel) - } else true - - @JvmStatic - fun isAllowedAny(source: CommandSource, notation: () -> List>) = - if (source.entity is ServerPlayerEntity) { - notation().forEach { - if (hasPermission(source.asPlayer(), it.first, it.second)) return true - }.let { false } - } else true - } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/WeatherCommand.kt b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/WeatherCommand.kt deleted file mode 100644 index 39487da..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/WeatherCommand.kt +++ /dev/null @@ -1,101 +0,0 @@ -/** - * ! This command implementation by Mojang Studios! - * - * Decompiled with idea source code was converted to kotlin code. - * But with additions such as permissions checking and etc. - * - * 1. This can be bad code. - * 2. This file can be not formatter pretty. - */ -package com.mairwunnx.projectessentials.core.impl.vanilla.commands - -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAPI -import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAliases -import com.mairwunnx.projectessentials.core.impl.nativeMappingsConfiguration -import com.mojang.brigadier.CommandDispatcher -import com.mojang.brigadier.arguments.IntegerArgumentType.getInteger -import com.mojang.brigadier.arguments.IntegerArgumentType.integer -import net.minecraft.command.CommandSource -import net.minecraft.command.Commands -import net.minecraft.command.impl.WeatherCommand - -internal object WeatherCommand : VanillaCommandBase("weather") { - private val durationArgument = Commands.argument( - "duration", integer(0, 1000000) - ) - - override fun register(dispatcher: CommandDispatcher) { - super.register(dispatcher) - short("sun").also { short("rain") }.also { short("thunder") }.also { aliases() } - dispatcher.register( - Commands.literal(name).requires { - isAllowedAny(it) { - listOf("weather.sun" to 2, "weather.rain" to 2, "weather.thunder" to 2) - } - }.then( - Commands.literal("clear").requires { - isAllowed(it, "weather.sun", 2) - }.executes { - WeatherCommand.setClear(it.source, 6000) - }.then( - durationArgument.executes { - WeatherCommand.setClear(it.source, getInteger(it, "duration") * 20) - } - ) - ).then( - Commands.literal("rain").requires { - isAllowed(it, "weather.rain", 2) - }.executes { - WeatherCommand.setRain(it.source, 6000) - }.then( - durationArgument.executes { - WeatherCommand.setRain(it.source, getInteger(it, "duration") * 20) - } - ) - ).then( - Commands.literal("thunder").requires { - isAllowed(it, "weather.thunder", 2) - }.executes { - WeatherCommand.setThunder(it.source, 6000) - }.then( - durationArgument.executes { - WeatherCommand.setThunder(it.source, getInteger(it, "duration") * 20) - } - ) - ) - ) - } - - private fun short(name: String) { - aliasesOf(name).forEach { command -> - CommandAPI.getDispatcher().register(Commands.literal(command).requires { - isAllowed(it, "weather.$name", 2) - }.then( - durationArgument.executes { - val duration = getInteger(it, "duration") * 20 - val source = it.source - if (name == "sun") WeatherCommand.setClear(source, duration) - if (name == "rain") WeatherCommand.setRain(source, duration) - if (name == "thunder") WeatherCommand.setThunder(source, duration) - else return@executes -1 - } - ).executes { - val source = it.source - if (name == "sun") WeatherCommand.setClear(source, 6000) - if (name == "rain") WeatherCommand.setRain(source, 6000) - if (name == "thunder") WeatherCommand.setThunder(source, 6000) - else return@executes -1 - }) - } - } - - private fun aliases() { - CommandAliases.aliases["sun"] = (aliasesOf("sun") + "weather").toMutableList() - CommandAliases.aliases["thunder"] = (aliasesOf("thunder") + "weather").toMutableList() - CommandAliases.aliases["rain"] = (aliasesOf("rain") + "weather").toMutableList() - } - - private fun aliasesOf(origin: String) = nativeMappingsConfiguration.aliases[origin]?.let { - return@let it.split(',') + origin - } ?: let { return@let listOf(origin) } -} diff --git a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/package-info.java b/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/package-info.java deleted file mode 100644 index 4e8bd6a..0000000 --- a/src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * CODE IN THIS PACKAGE PROVIDED BY VANILLA AND CONVERTED - * TO KOTLIN LANGUAGE VIA INTELLIJ IDEA!!! - *

- * It means: - *
- * > The code may look bad and not fully formatted. - *
- * > The code may not be optimal. - */ -package com.mairwunnx.projectessentials.core.impl.vanilla.commands; diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg deleted file mode 100644 index ce3952f..0000000 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ /dev/null @@ -1,11 +0,0 @@ -public net.minecraft.entity.player.ServerPlayerEntity field_71148_cg # language -public net.minecraft.command.impl.GameModeCommand func_198484_a(Lcom/mojang/brigadier/context/CommandContext;Ljava/util/Collection;Lnet/minecraft/world/GameType;)I # setGameMode -public net.minecraft.command.impl.SaveAllCommand func_198614_a(Lnet/minecraft/command/CommandSource;Z)I # saveAll -public net.minecraft.command.impl.TimeCommand func_198824_c(Lnet/minecraft/command/CommandSource;I)I # sendQueryResults -public net.minecraft.command.impl.TimeCommand func_198833_a(Lnet/minecraft/world/server/ServerWorld;)I # getDayTime -public net.minecraft.command.impl.WeatherCommand func_198869_a(Lnet/minecraft/command/CommandSource;I)I # setClear -public net.minecraft.command.impl.WeatherCommand func_198865_b(Lnet/minecraft/command/CommandSource;I)I # setRain -public net.minecraft.command.impl.WeatherCommand func_198863_c(Lnet/minecraft/command/CommandSource;I)I # setThunder -public net.minecraft.command.impl.TeleportCommand func_200559_a(Lnet/minecraft/command/CommandSource;Ljava/util/Collection;Lnet/minecraft/world/server/ServerWorld;Lnet/minecraft/command/arguments/ILocationArgument;Lnet/minecraft/command/arguments/ILocationArgument;Lnet/minecraft/command/impl/TeleportCommand$Facing;)I # teleportToPos -public net.minecraft.command.impl.TeleportCommand func_201126_a(Lnet/minecraft/command/CommandSource;Ljava/util/Collection;Lnet/minecraft/entity/Entity;)I # teleportToEntity -public net.minecraft.command.impl.TeleportCommand func_201127_a(Lnet/minecraft/command/CommandSource;Lnet/minecraft/entity/Entity;Lnet/minecraft/world/server/ServerWorld;DDDLjava/util/Set;FFLnet/minecraft/command/impl/TeleportCommand$Facing;)V # teleport diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml deleted file mode 100644 index ada70f6..0000000 --- a/src/main/resources/META-INF/mods.toml +++ /dev/null @@ -1,31 +0,0 @@ -modLoader="javafml" -loaderVersion="[28,)" -issueTrackerURL="https://github.com/ProjectEssentials/ProjectEssentials-Core/issues" - -[[mods]] - modId="project_essentials_core" - version="${file.jarVersion}" - displayName="Project Essentials Core" - updateJSONURL="https://raw.githubusercontent.com/ProjectEssentials/ProjectEssentials-Core/MC-1.14.4/updatev2.json" - displayURL="https://github.com/ProjectEssentials/ProjectEssentials-Core" - credits="hujle, KuroNoSeiHai, JetBrains, all forge developers, and other contributors" - authors="MairwunNx (Pavel Erokhin)" - description=''' - API for creating modules of Project Essentials and reduce code duplication, - also core module contains kotlin runtime and libraries. Also contains some - settings for vanilla commands and events. - ''' - -[[dependencies.project_essentials_core]] - modId="forge" - mandatory=true - versionRange="[28,)" - ordering="NONE" - side="BOTH" - -[[dependencies.project_essentials_core]] - modId="minecraft" - mandatory=true - versionRange="[1.14.4]" - ordering="NONE" - side="BOTH" diff --git a/src/main/resources/assets/projectessentialscore/lang/en_us.json b/src/main/resources/assets/projectessentialscore/lang/en_us.json deleted file mode 100644 index 72ce487..0000000 --- a/src/main/resources/assets/projectessentialscore/lang/en_us.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "native.command.restricted": "§cYou §7don't have permission §cto execute this command.", - "native.command.restricted_hover": "§7For executing it command, need permission \"§c%s§7\" or op level more or equal \"§c%s§7\".", - "project_essentials_core.back.success": "§6Rolling back your location ...", - "project_essentials_core.back.tickets_not_exists": "§cBack location ticket not exist, sorry.", - "project_essentials_core.back.restricted": "§cYou §7don't have permission §cto rolling back your location.", - "project_essentials_core.configure.successfully": "§6Setting name \"§7%s§6\" value changed from \"§7%s§6\" to \"§7%s§6\"", - "project_essentials_core.configure.successfully_required_restart": "§6Setting name \"§7%s§6\" value changed from \"§7%s§6\" to \"§7%s§6\", but §crestart required §6for applying changes.", - "project_essentials_core.configure.restricted": "§cYou §7don't have permission §cto change setting (§8\"§7%s§8\"§c) value.", - "project_essentials_core.simple.page": "§7page §c%s §7of §c%s" -} diff --git a/src/main/resources/assets/projectessentialscore/lang/ru_ru.json b/src/main/resources/assets/projectessentialscore/lang/ru_ru.json deleted file mode 100644 index 58ceec3..0000000 --- a/src/main/resources/assets/projectessentialscore/lang/ru_ru.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "native.command.restricted": "§cУ вас §7нет прав §cчтобы выполнить эту команду.", - "native.command.restricted_hover": "§7Для выполнения этой команды, нужно право \"§c%s§7\" или уровень оператора больший или равный \"§c%s§7\".", - "project_essentials_core.back.success": "§6Откат вашей локации к предыдущей ...", - "project_essentials_core.back.tickets_not_exists": "§cОткат локации недоступен. Не было телепортации.", - "project_essentials_core.back.restricted": "§cУ вас §7нет прав §cчтобы выполнить откат вашей локации.", - "project_essentials_core.configure.successfully": "§6Значение настройки \"§7%s§6\" было изменено с \"§7%s§6\" на \"§7%s§6\"", - "project_essentials_core.configure.successfully_required_restart": "§6Значение настройки \"§7%s§6\" было изменено с \"§7%s§6\" на \"§7%s§6\", но для применения изменений §cтребуется перезагрузка §6сервера или клиента.", - "project_essentials_core.configure.restricted": "§cУ вас §7нет прав §cчто бы изменить значение настройки (§8\"§7%s§8\"§c).", - "project_essentials_core.simple.page": "§7страница §c%s §7из §c%s" -} diff --git a/src/main/resources/assets/projectessentialscore/lang/zh_cn.json b/src/main/resources/assets/projectessentialscore/lang/zh_cn.json deleted file mode 100644 index 8549e2c..0000000 --- a/src/main/resources/assets/projectessentialscore/lang/zh_cn.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "native.command.restricted": "§c你 §7没有权限 §c使用这个命令。", - "native.command.restricted_hover": "§7要使用此命令, 需要权限 \"§c%s§7\" 或者OP等级大于等于 \"§c%s§7\"。", - "project_essentials_core.back.success": "§6回滚到 你的位置...", - "project_essentials_core.back.tickets_not_exists": "§c回滚位置的票不存在, 抱歉。", - "project_essentials_core.back.restricted": "§c你 §7没有权限 §c回滚到你的位置。", - "project_essentials_core.configure.successfully": "§6设置 \"§7%s§6\" 的值由 \"§7%s§6\" 变更为 \"§7%s§6\"", - "project_essentials_core.configure.successfully_required_restart": "§6设置 \"§7%s§6\" 的值由 \"§7%s§6\" 变更为 \"§7%s§6\", 但是 §c需要重启 §6才能应用变更。", - "project_essentials_core.configure.restricted": "§c你 §7没有权限 §c改变设置 (§8\"§7%s§8\"§c) 的值。", - "project_essentials_core.simple.page": "§7页码 §c%s §7总页数 §c%s" -} diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta deleted file mode 100644 index 628c352..0000000 --- a/src/main/resources/pack.mcmeta +++ /dev/null @@ -1,7 +0,0 @@ -{ - "pack": { - "description": "Project Essentials Core resources", - "pack_format": 4, - "_comment": "A pack_format of 4 requires json lang files. Note: we require v4 pack meta for all mods." - } -} diff --git a/update.json b/update.json deleted file mode 100644 index 697212f..0000000 --- a/update.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "homepage": "https://github.com/ProjectEssentials/ProjectEssentials-Core", - "1.14.4": { - "1.14.4-1.3.0": "Changelog for 1.3.0 https://github.com/ProjectEssentials/ProjectEssentials-Core/blob/MC-1.14.4/changelog.md#1144-130---2020-03-12", - "1.14.4-1.2.1": "Changelog for 1.2.1 https://github.com/ProjectEssentials/ProjectEssentials-Core/blob/MC-1.14.4/changelog.md#1144-121---2020-02-07", - "1.14.4-1.2.0": " - Wrong op level for `pardon-ip` command fixed.\n - Localizaton for restricted messages added.\n - Hover event with restricred message description added.", - "1.14.4-1.0.1.0": " - Added cooldown and permission modules as not mandatory dependency.\n - Added configuration for native vanilla commands.\n - Implemented all vanilla commands.\n - Permission checking on all vanilla commands.\n - Cooldown checking on all vanilla commands.\n - Added NativeCommandUtils with ability to remove command.", - "1.14.4-1.0.3.2": " - Added JsonHelper.kt with jsonInstance.", - "1.14.4-1.0.3.1": " - Package name changed to correctly.\n - Added empty line after startup message.\n - Added logo file.\n - Fixed `cr` symbols in mod info.", - "1.14.4-1.0.3.0": " - Bumped kotlin, kotlinx serialization and forge version.\n - Improved build script.\n - Bumped dokka version. \n - Added compatibility with forge 28.1.X. \n - Improved logging on mod startup and on forge version incompatibility.", - "1.14.4-1.0.2.0": " - Fixed crash while dependency using CoreAPI." - }, - "promos": { - "1.14.4-latest": "1.14.4-1.3.0", - "1.14.4-recommended": "1.14.4-1.3.0" - } -} diff --git a/updatev2.json b/updatev2.json deleted file mode 100644 index 44fc0d5..0000000 --- a/updatev2.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "homepage": "https://github.com/ProjectEssentials/ProjectEssentials-Core", - "1.14.4": { - "2.1.0": "change log -> https://github.com/ProjectEssentials/ProjectEssentials-Core/blob/master/changelog.md#210---2020-06-11", - "2.0.3": "change log -> https://github.com/ProjectEssentials/ProjectEssentials-Core/blob/master/changelog.md#203---2020-06-08", - "2.0.2": "change log -> https://github.com/ProjectEssentials/ProjectEssentials-Core/blob/master/changelog.md#202---2020-06-05", - "2.0.1": "change log -> https://github.com/ProjectEssentials/ProjectEssentials-Core/blob/master/changelog.md#201---2020-06-01", - "2.0.0": "change log -> https://github.com/ProjectEssentials/ProjectEssentials-Core/blob/master/changelog.md#200---2020-05-17", - "2.0.0-RC.5": "change log -> https://git.io/Jf05P", - "2.0.0-RC.4": "change log -> https://git.io/JfRaD", - "2.0.0-RC.3": "change log -> https://git.io/JfRlp", - "2.0.0-RC.2": "change log -> https://git.io/JfBYX", - "2.0.0-RC.1": "change log -> https://git.io/JfC5F" - }, - "promos": { - "1.14.4-latest": "2.1.0", - "1.14.4-recommended": "2.1.0" - } -} diff --git a/village-pillage/build.gradle b/village-pillage/build.gradle new file mode 100644 index 0000000..b824cb3 --- /dev/null +++ b/village-pillage/build.gradle @@ -0,0 +1,18 @@ +plugins { + id 'org.jetbrains.kotlin.jvm' +} + +group = 'com.projectessentials' +version = '1.0.0-SNAPSHOT.1' + +dependencies { + implementation project(':common') +} + +compileKotlin { + kotlinOptions.jvmTarget = '1.8' +} + +compileTestKotlin { + kotlinOptions.jvmTarget = '1.8' +}