Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bc6bbc448a |
@@ -1,7 +1,6 @@
|
||||
# User-specific stuff
|
||||
.idea/
|
||||
urlaub/
|
||||
.kotlin/
|
||||
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2024 skippyall
|
||||
Copyright (c) 2024
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
Module ohne Instruction nicht bei Instruction Auswahl vorschlagen ✓
|
||||
Mob Spawning durch Instruction an/aus
|
||||
Referenz kopieren als Item, das beim linken verschwindet ✓
|
||||
zurück-Button (Jain)
|
||||
Instructions stoppen / einfrieren bei Entfernung des Moduls ✓
|
||||
Verbindung mit Minion anzeigen ✓
|
||||
Schlagen auf Entities fixen ✓
|
||||
Signaländerung bei Trigger nach Tod des Minions mit Minion synchronisieren ✓
|
||||
Menüführung für Argumente verbessern (Nö)
|
||||
direkt Wert zeigen ✓
|
||||
@@ -1,35 +0,0 @@
|
||||
- Module:
|
||||
- Bewegungsmodul ✓
|
||||
- Angriffsmodul ✓
|
||||
- Abbaumodul ✓
|
||||
- Platziermodul / Verwendungsmodul ✓
|
||||
- Werfmodul
|
||||
- Inventarmanagementmodul (Noch nicht wirklich)
|
||||
- Inventaropenmodul (Nä)
|
||||
|
||||
- Detektoren:
|
||||
- Blockdetektor
|
||||
- Entitydetektor
|
||||
- Dimensiondetektor
|
||||
- Positiondetektor
|
||||
- Inventardetektor
|
||||
|
||||
- Programmieren: Nö
|
||||
- Variablen Nö
|
||||
- (Listen) Nö
|
||||
- Warten Nö
|
||||
- Wiederholen Nö
|
||||
- Wiederhole bis/während Nö
|
||||
- Wiederhole x mal/(für jedes Element) Nö
|
||||
- Bedingung Nö
|
||||
|
||||
- VariableTypen:
|
||||
- Integer ✓
|
||||
- String ✓
|
||||
- Position (Nö)
|
||||
- Block (weisned)
|
||||
- BlockType
|
||||
- (NBT) Nö
|
||||
- (World) Nö
|
||||
- (Chunk) Nö
|
||||
- Inventory (weisned)
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
plugins {
|
||||
id 'net.fabricmc.fabric-loom-remap' version '1.14-SNAPSHOT'
|
||||
id 'maven-publish'
|
||||
}
|
||||
|
||||
version = project.mod_version
|
||||
group = project.maven_group
|
||||
|
||||
base {
|
||||
archivesName = project.archives_base_name
|
||||
}
|
||||
|
||||
loom {
|
||||
accessWidenerPath = file("src/main/resources/minions.accesswidener")
|
||||
splitEnvironmentSourceSets()
|
||||
|
||||
mods {
|
||||
minions {
|
||||
sourceSet sourceSets.main
|
||||
sourceSet sourceSets.client
|
||||
}
|
||||
}
|
||||
|
||||
runs.forEach {
|
||||
it.vmArg("-XX:+AllowEnhancedClassRedefinition")
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
// Add repositories to retrieve artifacts from in here.
|
||||
// You should only use this when depending on other mods because
|
||||
// Loom adds the essential maven repositories to download Minecraft and libraries from automatically.
|
||||
// See https://docs.gradle.org/current/userguide/declaring_repositories.html
|
||||
// for more information about repositories.
|
||||
maven { url 'https://maven.nucleoid.xyz' }
|
||||
|
||||
exclusiveContent {
|
||||
forRepository {
|
||||
maven {
|
||||
name = "Modrinth"
|
||||
url = "https://api.modrinth.com/maven"
|
||||
}
|
||||
}
|
||||
filter {
|
||||
includeGroup "maven.modrinth"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// To change the versions see the gradle.properties file
|
||||
minecraft "com.mojang:minecraft:${project.minecraft_version}"
|
||||
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
|
||||
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
|
||||
|
||||
// Fabric API. This is technically optional, but you probably want it anyway.
|
||||
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
|
||||
|
||||
modImplementation "eu.pb4:polymer-core:${project.polymer_version}"
|
||||
modImplementation "eu.pb4:polymer-virtual-entity:${project.polymer_version}"
|
||||
modImplementation "eu.pb4:polymer-resource-pack:${project.polymer_version}"
|
||||
modLocalRuntime "eu.pb4:polymer-autohost:${project.polymer_version}"
|
||||
modImplementation include("eu.pb4:sgui:${project.sgui_version}")
|
||||
modImplementation include("xyz.nucleoid:server-translations-api:${project.server_translations_version}")
|
||||
|
||||
implementation include("com.electronwill.night-config:toml:${project.night_config_version}")
|
||||
compileOnly("io.netty:netty-codec-http:${project.netty_version}.Final")
|
||||
|
||||
modCompileOnly "maven.modrinth:universal-graves:${project.universal_graves_version}"
|
||||
}
|
||||
|
||||
processResources {
|
||||
inputs.property "version", project.version
|
||||
inputs.property "minecraft_version", project.minecraft_version
|
||||
inputs.property "loader_version", project.loader_version
|
||||
filteringCharset "UTF-8"
|
||||
|
||||
filesMatching("fabric.mod.json") {
|
||||
expand "version": project.version,
|
||||
"minecraft_version": project.minecraft_version,
|
||||
"loader_version": project.loader_version
|
||||
}
|
||||
}
|
||||
|
||||
def targetJavaVersion = 21
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
// ensure that the encoding is set to UTF-8, no matter what the system default is
|
||||
// this fixes some edge cases with special characters not displaying correctly
|
||||
// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html
|
||||
// If Javadoc is generated, this must be specified in that task too.
|
||||
it.options.encoding = "UTF-8"
|
||||
if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) {
|
||||
it.options.release.set(targetJavaVersion)
|
||||
}
|
||||
}
|
||||
|
||||
java {
|
||||
def javaVersion = JavaVersion.toVersion(targetJavaVersion)
|
||||
if (JavaVersion.current() < javaVersion) {
|
||||
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
|
||||
}
|
||||
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
|
||||
// if it is present.
|
||||
// If you remove this line, sources will not be generated.
|
||||
withSourcesJar()
|
||||
}
|
||||
|
||||
jar {
|
||||
from("LICENSE") {
|
||||
rename { "${it}_${project.archives_base_name}"}
|
||||
}
|
||||
}
|
||||
|
||||
// configure the maven publication
|
||||
publishing {
|
||||
publications {
|
||||
maven (MavenPublication) {
|
||||
from components.java
|
||||
}
|
||||
}
|
||||
|
||||
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
|
||||
repositories {
|
||||
// Add repositories to publish to here.
|
||||
// Notice: This block does NOT have the same function as the block in the top level.
|
||||
// The repositories here will be used for publishing your artifact, not for
|
||||
// retrieving dependencies.
|
||||
if(project.hasProperty("foxgalaxy_user_name") && project.hasProperty("foxgalaxy_password")) {
|
||||
maven {
|
||||
url = "https://maven.foxgalaxy.de/private"
|
||||
|
||||
credentials {
|
||||
username = project.property("foxgalaxy_user_name")
|
||||
password = project.property("foxgalaxy_password")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
|
||||
plugins {
|
||||
id("net.fabricmc.fabric-loom")
|
||||
`maven-publish`
|
||||
id("org.jetbrains.kotlin.jvm") version "2.3.21"
|
||||
}
|
||||
|
||||
version = providers.gradleProperty("mod_version").get()
|
||||
group = providers.gradleProperty("maven_group").get()
|
||||
|
||||
repositories {
|
||||
// Add repositories to retrieve artifacts from in here.
|
||||
// You should only use this when depending on other mods because
|
||||
// Loom adds the essential maven repositories to download Minecraft and libraries from automatically.
|
||||
// See https://docs.gradle.org/current/userguide/declaring_repositories.html
|
||||
// for more information about repositories.
|
||||
|
||||
maven("https://maven.nucleoid.xyz")
|
||||
|
||||
exclusiveContent {
|
||||
forRepository {
|
||||
maven ("https://api.modrinth.com/maven")
|
||||
}
|
||||
filter {
|
||||
includeGroup("maven.modrinth")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loom {
|
||||
splitEnvironmentSourceSets()
|
||||
|
||||
mods {
|
||||
register("minions") {
|
||||
sourceSet(sourceSets.main.get())
|
||||
sourceSet(sourceSets.getByName("client"))
|
||||
}
|
||||
}
|
||||
|
||||
for (settings in runs) {
|
||||
settings.vmArg("-XX:+AllowEnhancedClassRedefinition")
|
||||
}
|
||||
|
||||
accessWidenerPath = file("src/main/resources/minions.classtweaker")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// To change the versions see the gradle.properties file
|
||||
minecraft("com.mojang:minecraft:${providers.gradleProperty("minecraft_version").get()}")
|
||||
|
||||
implementation("net.fabricmc:fabric-loader:${providers.gradleProperty("loader_version").get()}")
|
||||
|
||||
// Fabric API. This is technically optional, but you probably want it anyway.
|
||||
implementation("net.fabricmc.fabric-api:fabric-api:${providers.gradleProperty("fabric_api_version").get()}")
|
||||
implementation("net.fabricmc:fabric-language-kotlin:${providers.gradleProperty("fabric_kotlin_version").get()}")
|
||||
|
||||
val polymer_version = providers.gradleProperty("polymer_version").get()
|
||||
implementation("eu.pb4:polymer-core:${polymer_version}")
|
||||
implementation("eu.pb4:polymer-virtual-entity:${polymer_version}")
|
||||
implementation("eu.pb4:polymer-resource-pack:${polymer_version}")
|
||||
localRuntime("eu.pb4:polymer-autohost:${polymer_version}")
|
||||
implementation("eu.pb4:sgui:${providers.gradleProperty("sgui_version").get()}")
|
||||
implementation("xyz.nucleoid:server-translations-api:${providers.gradleProperty("server_translations_version").get()}")
|
||||
|
||||
implementation("com.electronwill.night-config:toml:${providers.gradleProperty("night_config_version").get()}")
|
||||
|
||||
compileOnly("maven.modrinth:universal-graves:${providers.gradleProperty("universal_graves_version").get()}")
|
||||
}
|
||||
|
||||
tasks.processResources {
|
||||
val version = version
|
||||
inputs.property("version", version)
|
||||
|
||||
filesMatching("fabric.mod.json") {
|
||||
expand("version" to version)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<JavaCompile>().configureEach {
|
||||
options.release = 25
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget = JvmTarget.JVM_25
|
||||
}
|
||||
}
|
||||
|
||||
java {
|
||||
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
|
||||
// if it is present.
|
||||
// If you remove this line, sources will not be generated.
|
||||
withSourcesJar()
|
||||
|
||||
sourceCompatibility = JavaVersion.VERSION_25
|
||||
targetCompatibility = JavaVersion.VERSION_25
|
||||
}
|
||||
|
||||
tasks.jar {
|
||||
val projectName = project.name
|
||||
inputs.property("projectName", projectName)
|
||||
|
||||
from("LICENSE") {
|
||||
rename { "${it}_$projectName" }
|
||||
}
|
||||
}
|
||||
|
||||
// configure the maven publication
|
||||
publishing {
|
||||
publications {
|
||||
register<MavenPublication>("mavenJava") {
|
||||
from(components["java"])
|
||||
}
|
||||
}
|
||||
|
||||
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
|
||||
repositories {
|
||||
// Add repositories to publish to here.
|
||||
// Notice: This block does NOT have the same function as the block in the top level.
|
||||
// The repositories here will be used for publishing your artifact, not for
|
||||
// retrieving dependencies.
|
||||
maven("https://maven.foxgalaxy.de/private") {
|
||||
name = "foxgalaxy"
|
||||
credentials(PasswordCredentials::class.java)
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
-10
@@ -3,24 +3,24 @@ org.gradle.jvmargs=-Xmx1G
|
||||
|
||||
# Fabric Properties
|
||||
# check these on https://modmuss50.me/fabric.html
|
||||
loom_version=1.16-SNAPSHOT
|
||||
minecraft_version=26.1.2
|
||||
loader_version=0.19.2
|
||||
minecraft_version=1.21.7
|
||||
loader_version=0.16.14
|
||||
yarn_mappings=1.21.7+build.2
|
||||
|
||||
# Mod Properties
|
||||
mod_version = 1.0.0-TEST-1
|
||||
mod_version = 1.0.0-SNAPSHOT-1
|
||||
maven_group = io.github.skippyall
|
||||
archives_base_name = Minions
|
||||
|
||||
# Dependencies
|
||||
# check this on https://modmuss50.me/fabric.html
|
||||
fabric_api_version=0.147.0+26.1.2
|
||||
fabric_kotlin_version=1.13.11+kotlin.2.3.21
|
||||
fabric_version=0.128.1+1.21.7
|
||||
|
||||
polymer_version=0.16.3+26.1.2
|
||||
sgui_version=2.0.0+26.1
|
||||
server_translations_version=3.0.3+26.1
|
||||
polymer_version=0.13.3+1.21.6
|
||||
sgui_version=1.10.0+1.21.6
|
||||
server_translations_version=2.5.1+1.21.5
|
||||
|
||||
night_config_version=3.8.3
|
||||
netty_version=4.1.130
|
||||
|
||||
universal_graves_version=3.11.0+26.1.2
|
||||
universal_graves_version=3.8.0+1.21.6
|
||||
|
||||
Vendored
BIN
Binary file not shown.
+1
-7
@@ -1,7 +1 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip
|
||||
|
||||
@@ -1,248 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
-93
@@ -1,93 +0,0 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -1,2 +0,0 @@
|
||||
#!/bin/bash
|
||||
bash gradlew publish -PfoxgalaxyPassword=$(read -s -p "Enter Password: ")
|
||||
@@ -0,0 +1,9 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
maven {
|
||||
name = 'Fabric'
|
||||
url = 'https://maven.fabricmc.net/'
|
||||
}
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
maven {
|
||||
name = "Fabric"
|
||||
url = uri("https://maven.fabricmc.net/")
|
||||
}
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
|
||||
plugins {
|
||||
id("net.fabricmc.fabric-loom") version providers.gradleProperty("loom_version")
|
||||
}
|
||||
}
|
||||
|
||||
// Should match your modid
|
||||
rootProject.name = "minions"
|
||||
@@ -1,12 +1,17 @@
|
||||
package io.github.skippyall.minions.client;
|
||||
|
||||
import eu.pb4.polymer.networking.api.client.PolymerClientNetworking;
|
||||
import io.github.skippyall.minions.polymer.VersionSync;
|
||||
import io.github.skippyall.minions.registration.MinionBlocks;
|
||||
import io.github.skippyall.minions.util.PolymerUtil;
|
||||
import net.fabricmc.api.ClientModInitializer;
|
||||
import net.fabricmc.fabric.api.client.rendering.v1.BlockRenderLayerMap;
|
||||
import net.minecraft.client.render.BlockRenderLayer;
|
||||
|
||||
public class MinionsClient implements ClientModInitializer {
|
||||
@Override
|
||||
public void onInitializeClient() {
|
||||
PolymerClientNetworking.registerCommonHandler(VersionSync.VersionSyncPayload.class, (client, handler, payload) -> {});
|
||||
BlockRenderLayerMap.putBlock(MinionBlocks.MINION_TRIGGER_BLOCK, BlockRenderLayer.TRANSLUCENT);
|
||||
|
||||
PolymerClientNetworking.registerCommonHandler(PolymerUtil.VersionSyncPayload.class, (client, handler, payload) -> {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package io.github.skippyall.minions;
|
||||
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
|
||||
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
|
||||
@@ -16,17 +15,16 @@ public class MinionMixinConfigPlugin implements IMixinConfigPlugin {
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String getRefMapperConfig() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldApplyMixin(String targetClassName, String mixinClassName) {
|
||||
if(mixinClassName.startsWith("io.github.skippyall.minions.mixins.compat.universal_graves.")) {
|
||||
if(mixinClassName.startsWith("io.github.skippyall.mixins.compat.universal_graves.")) {
|
||||
return MinionsConfig.get().compat.enableGravesCompat && FabricLoader.getInstance().isModLoaded("universal-graves");
|
||||
}
|
||||
if(mixinClassName.startsWith("io.github.skippyall.minions.mixins.antimobcap.")) {
|
||||
if(mixinClassName.startsWith("io.github.skippyall.mixins.antimobcap.")) {
|
||||
return MinionsConfig.get().minion.enableMobCapHacks;
|
||||
}
|
||||
return true;
|
||||
@@ -36,7 +34,6 @@ public class MinionMixinConfigPlugin implements IMixinConfigPlugin {
|
||||
public void acceptTargets(Set<String> myTargets, Set<String> otherTargets) {}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public List<String> getMixins() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
package io.github.skippyall.minions;
|
||||
|
||||
import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils;
|
||||
import io.github.skippyall.minions.command.MinionsCommand;
|
||||
import io.github.skippyall.minions.docs.DocsManager;
|
||||
import io.github.skippyall.minions.minion.MinionPersistentState;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.polymer.PolymerRegistration;
|
||||
import io.github.skippyall.minions.minion.MinionPersistentState;
|
||||
import io.github.skippyall.minions.registration.MinionRegistration;
|
||||
import io.github.skippyall.minions.util.PolymerUtil;
|
||||
import net.fabricmc.api.ModInitializer;
|
||||
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
|
||||
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
|
||||
import net.fabricmc.fabric.api.resource.v1.ResourceLoader;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@@ -26,18 +23,24 @@ public class Minions implements ModInitializer {
|
||||
|
||||
MinionRegistration.register();
|
||||
|
||||
PolymerUtil.register();
|
||||
|
||||
ServerLifecycleEvents.SERVER_STARTED.register(server -> {
|
||||
MinionPersistentState.get(server).getMinionData().forEach((uuid, data) -> {
|
||||
if(data.isSpawned()) {
|
||||
MinionFakePlayer.spawnMinion(data, server.overworld(), null, null, true);
|
||||
MinionFakePlayer.spawnMinion(data, server.getOverworld(), null, null, true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
CommandRegistrationCallback.EVENT.register(MinionsCommand::register);
|
||||
|
||||
PolymerRegistration.register();
|
||||
/*ServerBlockEntityEvents.BLOCK_ENTITY_LOAD.register((blockEntity, world) -> {
|
||||
if(blockEntity instanceof MinionTriggerBlockEntity) {
|
||||
world.updateComparators(blockEntity.getPos(), MinionBlocks.MINION_TRIGGER_BLOCK);
|
||||
}
|
||||
});*/
|
||||
|
||||
ResourceLoader.get(PackType.SERVER_DATA).registerReloadListener(Identifier.fromNamespaceAndPath(Minions.MOD_ID, "docs"), new DocsManager());
|
||||
PolymerResourcePackUtils.addModAssets(Minions.MOD_ID);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,33 +8,40 @@ import com.electronwill.nightconfig.core.serde.ObjectDeserializer;
|
||||
import com.electronwill.nightconfig.core.serde.ObjectSerializer;
|
||||
import com.electronwill.nightconfig.core.serde.SerdeException;
|
||||
import com.electronwill.nightconfig.core.serde.annotations.SerdeComment;
|
||||
import com.electronwill.nightconfig.core.serde.annotations.SerdeSkipDeserializingIf;
|
||||
import com.electronwill.nightconfig.toml.TomlFormat;
|
||||
import com.electronwill.nightconfig.toml.TomlParser;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class MinionsConfig {
|
||||
private static @Nullable MinionsConfig INSTANCE;
|
||||
import static com.electronwill.nightconfig.core.serde.annotations.SerdeSkipDeserializingIf.SkipDeIf.IS_MISSING;
|
||||
|
||||
public class MinionsConfig {
|
||||
private static MinionsConfig INSTANCE;
|
||||
|
||||
@SerdeSkipDeserializingIf(IS_MISSING)
|
||||
public Minion minion = new Minion();
|
||||
|
||||
public static class Minion {
|
||||
@SerdeComment("The prefix for all minion names")
|
||||
@SerdeSkipDeserializingIf(IS_MISSING)
|
||||
public String minionPrefix = "+";
|
||||
|
||||
@SerdeComment("Makes minions not raise the mob cap if they can't spawn mobs.")
|
||||
@SerdeComment("Might cause incompatibilities.")
|
||||
@SerdeSkipDeserializingIf(IS_MISSING)
|
||||
public boolean enableMobCapHacks = true;
|
||||
}
|
||||
|
||||
@SerdeSkipDeserializingIf(IS_MISSING)
|
||||
public Compat compat = new Compat();
|
||||
|
||||
public static class Compat {
|
||||
@SerdeComment("Enables compat with Universal Graves, which allows everyone to pick up graves from minions")
|
||||
@SerdeSkipDeserializingIf(IS_MISSING)
|
||||
public boolean enableGravesCompat = true;
|
||||
}
|
||||
|
||||
@@ -59,15 +66,12 @@ public class MinionsConfig {
|
||||
|
||||
public static void loadConfig() {
|
||||
try {
|
||||
CommentedConfig defaultConfig = ObjectSerializer.standard().serializeFields(new MinionsConfig(), TomlFormat::newConfig);
|
||||
|
||||
CommentedConfig config = new TomlParser().parse(getPath(), (file, configFormat) -> {
|
||||
CommentedConfig defaultConfig = ObjectSerializer.standard().serializeFields(new MinionsConfig(), TomlFormat::newConfig);
|
||||
configFormat.createWriter().write(defaultConfig, file, WritingMode.REPLACE);
|
||||
return true;
|
||||
});
|
||||
|
||||
//Always use default values when entries are missing
|
||||
config.addAll(defaultConfig);
|
||||
INSTANCE = ObjectDeserializer.standard().deserializeFields(config, MinionsConfig::new);
|
||||
} catch (SerdeException | ParsingException | WritingException e) {
|
||||
Minions.LOGGER.error("Error while reading config", e);
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
package io.github.skippyall.minions.block.input;
|
||||
|
||||
import io.github.skippyall.minions.clipboard.ClipboardItem;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
|
||||
public class AnalogInputBlock extends Block {
|
||||
public AnalogInputBlock(Properties settings) {
|
||||
super(settings);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected InteractionResult useWithoutItem(BlockState state, Level world, BlockPos pos, Player player, BlockHitResult hit) {
|
||||
if(!world.isClientSide()) {
|
||||
player.getInventory().placeItemBackInInventory(ClipboardItem.createBlockPosReference(world, pos), true);
|
||||
}
|
||||
return InteractionResult.SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
@NullMarked
|
||||
package io.github.skippyall.minions.block.input;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
package io.github.skippyall.minions.block.instruction_bound;
|
||||
|
||||
import io.github.skippyall.minions.block.miniontrigger.MinionTriggerBlockEntity;
|
||||
import io.github.skippyall.minions.clipboard.InstructionClipboard;
|
||||
import io.github.skippyall.minions.minion.MinionPersistentState;
|
||||
import io.github.skippyall.minions.registration.MinionBlocks;
|
||||
import io.github.skippyall.minions.registration.MinionComponentTypes;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.protocol.game.ClientboundSoundPacket;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.sounds.SoundEvents;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.EntityBlock;
|
||||
import net.minecraft.world.level.block.entity.BlockEntityType;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
|
||||
public abstract class InstructionBoundBlock extends Block implements EntityBlock {
|
||||
public InstructionBoundBlock(Properties settings) {
|
||||
super(settings);
|
||||
}
|
||||
|
||||
protected abstract BlockEntityType<? extends InstructionBoundBlockEntity<?>> getBlockEntityType();
|
||||
|
||||
@Override
|
||||
protected InteractionResult useItemOn(ItemStack stack, BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) {
|
||||
if(stack.get(MinionComponentTypes.REFERENCE) instanceof InstructionClipboard instruction && player instanceof ServerPlayer serverPlayer) {
|
||||
world.getBlockEntity(pos, getBlockEntityType()).ifPresent(be -> {
|
||||
be.setInstruction(instruction.selectedMinion(), instruction.selectedInstruction());
|
||||
serverPlayer.connection.send(new ClientboundSoundPacket(SoundEvents.NOTE_BLOCK_CHIME, SoundSource.BLOCKS, pos.getX(), pos.getY(), pos.getZ(), 1, 1, 0));
|
||||
stack.shrink(1);
|
||||
});
|
||||
return InteractionResult.SUCCESS;
|
||||
}
|
||||
|
||||
return super.useItemOn(stack, state, world, pos, player, hand, hit);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected InteractionResult useWithoutItem(BlockState state, Level world, BlockPos pos, Player player, BlockHitResult hit) {
|
||||
if(world.isClientSide()) {
|
||||
return InteractionResult.CONSUME;
|
||||
}
|
||||
|
||||
world.getBlockEntity(pos, getBlockEntityType()).ifPresent(be -> {
|
||||
String name = MinionPersistentState.get(world.getServer()).getMinionData(be.getMinionUuid()).getName();
|
||||
player.sendSystemMessage(Component.translatable("minions.reference.instruction.tooltip", be.getInstructionName(), name));
|
||||
});
|
||||
return InteractionResult.SUCCESS;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel world, BlockPos pos, boolean moved) {
|
||||
super.affectNeighborsAfterRemoval(state, world, pos, moved);
|
||||
world.getBlockEntity(pos, MinionBlocks.MINION_TRIGGER_BE_TYPE).ifPresent(MinionTriggerBlockEntity::removeListener);
|
||||
}
|
||||
}
|
||||
-79
@@ -1,79 +0,0 @@
|
||||
package io.github.skippyall.minions.block.instruction_bound;
|
||||
|
||||
import io.github.skippyall.minions.listener.BlockEntityMinionListener;
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.BlockEntityType;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class InstructionBoundBlockEntity<L extends BlockEntityMinionListener<?>> extends BlockEntity {
|
||||
protected @Nullable UUID minionUuid;
|
||||
protected String instructionName = "";
|
||||
|
||||
public InstructionBoundBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
|
||||
super(type, pos, state);
|
||||
}
|
||||
|
||||
protected abstract L createListener();
|
||||
|
||||
protected abstract Class<L> getListenerClass();
|
||||
|
||||
public void removeListener() {
|
||||
if(level instanceof ServerLevel serverWorld) {
|
||||
L listener = getListener();
|
||||
if(listener != null) {
|
||||
listener.remove(serverWorld.getServer());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void addListener() {
|
||||
if(level instanceof ServerLevel serverWorld) {
|
||||
L listener = createListener();
|
||||
listener.add(serverWorld.getServer());
|
||||
}
|
||||
}
|
||||
|
||||
public void setInstruction(UUID minionUuid, String instructionName) {
|
||||
removeListener();
|
||||
this.minionUuid = minionUuid;
|
||||
this.instructionName = instructionName;
|
||||
addListener();
|
||||
setChanged();
|
||||
}
|
||||
|
||||
public Optional<MinionFakePlayer> getMinion() {
|
||||
if(minionUuid != null && level != null && level.getPlayerByUUID(minionUuid) instanceof MinionFakePlayer minion) {
|
||||
return Optional.of(minion);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public @Nullable UUID getMinionUuid() {
|
||||
return minionUuid;
|
||||
}
|
||||
|
||||
public String getInstructionName() {
|
||||
return instructionName;
|
||||
}
|
||||
|
||||
public Optional<ConfiguredInstruction<MinionRuntime>> getInstruction(MinionFakePlayer minion) {
|
||||
return Optional.ofNullable(minion.getInstructionManager().getInstruction(instructionName));
|
||||
}
|
||||
|
||||
public Optional<ConfiguredInstruction<MinionRuntime>> getInstruction() {
|
||||
return getMinion().flatMap(this::getInstruction);
|
||||
}
|
||||
|
||||
public @Nullable L getListener() {
|
||||
return BlockEntityMinionListener.getListener(level, worldPosition, minionUuid, getListenerClass());
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
@NullMarked
|
||||
package io.github.skippyall.minions.block.instruction_bound;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
+129
-42
@@ -1,90 +1,177 @@
|
||||
package io.github.skippyall.minions.block.miniontrigger;
|
||||
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import io.github.skippyall.minions.block.instruction_bound.InstructionBoundBlock;
|
||||
import eu.pb4.polymer.core.api.block.PolymerBlock;
|
||||
import eu.pb4.polymer.core.api.utils.PolymerClientDecoded;
|
||||
import eu.pb4.polymer.core.api.utils.PolymerKeepModel;
|
||||
import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils;
|
||||
import eu.pb4.polymer.virtualentity.api.BlockWithElementHolder;
|
||||
import eu.pb4.polymer.virtualentity.api.ElementHolder;
|
||||
import eu.pb4.polymer.virtualentity.api.elements.ItemDisplayElement;
|
||||
import io.github.skippyall.minions.registration.MinionBlocks;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.LevelReader;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.SupportType;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.BlockEntityType;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.StateDefinition;
|
||||
import net.minecraft.world.level.block.state.properties.BooleanProperty;
|
||||
import net.minecraft.world.level.redstone.Orientation;
|
||||
import net.minecraft.world.phys.shapes.CollisionContext;
|
||||
import net.minecraft.world.phys.shapes.VoxelShape;
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import io.github.skippyall.minions.Minions;
|
||||
import io.github.skippyall.minions.minion.MinionPersistentState;
|
||||
import io.github.skippyall.minions.clipboard.InstructionClipboard;
|
||||
import io.github.skippyall.minions.registration.MinionComponentTypes;
|
||||
import io.github.skippyall.minions.util.PolymerUtil;
|
||||
import net.minecraft.block.AbstractRedstoneGateBlock;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.block.BlockWithEntity;
|
||||
import net.minecraft.block.ShapeContext;
|
||||
import net.minecraft.block.SideShapeType;
|
||||
import net.minecraft.block.entity.BlockEntity;
|
||||
import net.minecraft.component.DataComponentTypes;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.server.network.ServerPlayNetworkHandler;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.sound.SoundCategory;
|
||||
import net.minecraft.sound.SoundEvents;
|
||||
import net.minecraft.state.StateManager;
|
||||
import net.minecraft.state.property.BooleanProperty;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.ActionResult;
|
||||
import net.minecraft.util.Hand;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.hit.BlockHitResult;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Direction;
|
||||
import net.minecraft.util.shape.VoxelShape;
|
||||
import net.minecraft.world.BlockView;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.WorldView;
|
||||
import net.minecraft.world.block.WireOrientation;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import xyz.nucleoid.packettweaker.PacketContext;
|
||||
|
||||
public class MinionTriggerBlock extends InstructionBoundBlock {
|
||||
public static final MapCodec<MinionTriggerBlock> CODEC = simpleCodec(MinionTriggerBlock::new);
|
||||
public class MinionTriggerBlock extends BlockWithEntity implements PolymerBlock, PolymerKeepModel, PolymerClientDecoded, BlockWithElementHolder {
|
||||
public static final MapCodec<MinionTriggerBlock> CODEC = createCodec(MinionTriggerBlock::new);
|
||||
|
||||
public static final BooleanProperty POWERED = BooleanProperty.create("powered");
|
||||
public static final VoxelShape SHAPE = Block.column(16.0, 0.0, 2.0);
|
||||
public static final BooleanProperty POWERED = BooleanProperty.of("powered");
|
||||
public static final VoxelShape SHAPE = Block.createColumnShape(16.0, 0.0, 2.0);
|
||||
|
||||
public MinionTriggerBlock(Properties settings) {
|
||||
public MinionTriggerBlock(Settings settings) {
|
||||
super(settings);
|
||||
registerDefaultState(defaultBlockState().setValue(POWERED, false));
|
||||
setDefaultState(getDefaultState().with(POWERED, false));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) {
|
||||
protected VoxelShape getOutlineShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) {
|
||||
return SHAPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) {
|
||||
BlockPos blockPos = pos.below();
|
||||
protected boolean canPlaceAt(BlockState state, WorldView world, BlockPos pos) {
|
||||
BlockPos blockPos = pos.down();
|
||||
return this.canPlaceAbove(world, blockPos, world.getBlockState(blockPos));
|
||||
}
|
||||
|
||||
protected boolean canPlaceAbove(LevelReader world, BlockPos pos, BlockState state) {
|
||||
return state.isFaceSturdy(world, pos, Direction.UP, SupportType.RIGID);
|
||||
protected boolean canPlaceAbove(WorldView world, BlockPos pos, BlockState state) {
|
||||
return state.isSideSolid(world, pos, Direction.UP, SideShapeType.RIGID);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
|
||||
protected void onStateReplaced(BlockState state, ServerWorld world, BlockPos pos, boolean moved) {
|
||||
super.onStateReplaced(state, world, pos, moved);
|
||||
world.getBlockEntity(pos, MinionBlocks.MINION_TRIGGER_BE_TYPE).ifPresent(MinionTriggerBlockEntity::removeListener);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {
|
||||
builder.add(POWERED);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NullMarked
|
||||
protected void neighborChanged(BlockState state, Level world, BlockPos pos, Block sourceBlock, @Nullable Orientation wireOrientation, boolean notify) {
|
||||
if(!canSurvive(state, world, pos)) {
|
||||
dropResources(state, world, pos);
|
||||
protected ActionResult onUseWithItem(ItemStack stack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {
|
||||
if(stack.get(MinionComponentTypes.REFERENCE) instanceof InstructionClipboard instruction) {
|
||||
world.getBlockEntity(pos, MinionBlocks.MINION_TRIGGER_BE_TYPE).ifPresent(be -> {
|
||||
be.setInstruction(instruction.selectedMinion(), instruction.selectedInstruction());
|
||||
player.playSoundToPlayer(SoundEvents.BLOCK_NOTE_BLOCK_CHIME.value(), SoundCategory.BLOCKS, 1, 1);
|
||||
stack.decrement(1);
|
||||
});
|
||||
return ActionResult.SUCCESS;
|
||||
}
|
||||
|
||||
return super.onUseWithItem(stack, state, world, pos, player, hand, hit);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, BlockHitResult hit) {
|
||||
if(world.isClient()) {
|
||||
return ActionResult.CONSUME;
|
||||
}
|
||||
|
||||
world.getBlockEntity(pos, MinionBlocks.MINION_TRIGGER_BE_TYPE).ifPresent(be -> {
|
||||
String name = MinionPersistentState.get(world.getServer()).getMinionData(be.getMinionUuid()).name();
|
||||
player.sendMessage(Text.translatable("minions.reference.instruction.tooltip", name, be.getInstructionName()), true);
|
||||
});
|
||||
return ActionResult.SUCCESS;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void neighborUpdate(BlockState state, World world, BlockPos pos, Block sourceBlock, @Nullable WireOrientation wireOrientation, boolean notify) {
|
||||
if(!canPlaceAt(state, world, pos)) {
|
||||
dropStacks(state, world, pos);
|
||||
world.removeBlock(pos, false);
|
||||
return;
|
||||
}
|
||||
|
||||
boolean newPower = world.hasNeighborSignal(pos);
|
||||
if(state.getValue(POWERED) != newPower) {
|
||||
world.setBlockAndUpdate(pos, state.setValue(POWERED, newPower));
|
||||
boolean newPower = world.isReceivingRedstonePower(pos);
|
||||
if(state.get(POWERED) != newPower) {
|
||||
world.setBlockState(pos, state.with(POWERED, newPower));
|
||||
world.getBlockEntity(pos, MinionBlocks.MINION_TRIGGER_BE_TYPE).ifPresent(MinionTriggerBlockEntity::updatePower);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean hasAnalogOutputSignal(BlockState state) {
|
||||
protected boolean hasComparatorOutput(BlockState state) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getAnalogOutputSignal(BlockState state, Level world, BlockPos pos, Direction direction) {
|
||||
protected int getComparatorOutput(BlockState state, World world, BlockPos pos) {
|
||||
return world.getBlockEntity(pos, MinionBlocks.MINION_TRIGGER_BE_TYPE).map(MinionTriggerBlockEntity::getComparatorOutput).orElse(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
|
||||
protected MapCodec<? extends BlockWithEntity> getCodec() {
|
||||
return CODEC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable BlockEntity createBlockEntity(BlockPos pos, BlockState state) {
|
||||
return new MinionTriggerBlockEntity(pos, state);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BlockEntityType<MinionTriggerBlockEntity> getBlockEntityType() {
|
||||
return MinionBlocks.MINION_TRIGGER_BE_TYPE;
|
||||
public BlockState getPolymerBlockState(BlockState state, PacketContext context) {
|
||||
return PolymerUtil.isOnClient(context) ? state : net.minecraft.block.Blocks.COMPARATOR.getDefaultState().with(AbstractRedstoneGateBlock.POWERED, state.get(POWERED));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleMiningOnServer(ItemStack tool, BlockState state, BlockPos pos, ServerPlayerEntity player) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable ElementHolder createElementHolder(ServerWorld world, BlockPos pos, BlockState initialBlockState) {
|
||||
ElementHolder holder = new ElementHolder() {
|
||||
@Override
|
||||
public boolean startWatching(ServerPlayNetworkHandler player) {
|
||||
if(PolymerResourcePackUtils.hasMainPack(player)) {
|
||||
return super.startWatching(player);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
ItemStack stack = new ItemStack(Items.BARRIER);
|
||||
stack.set(DataComponentTypes.ITEM_MODEL, Identifier.of(Minions.MOD_ID, "minion_trigger_no_plate_" + (initialBlockState.get(MinionTriggerBlock.POWERED) ? "active" : "inactive")));
|
||||
|
||||
holder.addElement(new ItemDisplayElement(stack));
|
||||
return holder;
|
||||
}
|
||||
}
|
||||
|
||||
+63
-20
@@ -1,30 +1,46 @@
|
||||
package io.github.skippyall.minions.block.miniontrigger;
|
||||
|
||||
import io.github.skippyall.minions.block.instruction_bound.InstructionBoundBlockEntity;
|
||||
import io.github.skippyall.minions.listener.BlockEntityMinionListener;
|
||||
import io.github.skippyall.minions.registration.MinionBlocks;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.UUIDUtil;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.storage.ValueInput;
|
||||
import net.minecraft.world.level.storage.ValueOutput;
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.block.entity.BlockEntity;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
import net.minecraft.util.Uuids;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public class MinionTriggerBlockEntity extends BlockEntity {
|
||||
private UUID minionUuid;
|
||||
private String instructionName = "";
|
||||
|
||||
public class MinionTriggerBlockEntity extends InstructionBoundBlockEntity<MinionTriggerMinionListener> {
|
||||
public MinionTriggerBlockEntity(BlockPos pos, BlockState state) {
|
||||
super(MinionBlocks.MINION_TRIGGER_BE_TYPE, pos, state);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected MinionTriggerMinionListener createListener() {
|
||||
return new MinionTriggerMinionListener(level.dimension(), worldPosition, minionUuid, instructionName);
|
||||
public void removeListener() {
|
||||
MinionTriggerMinionListener.removeListener(world, pos, minionUuid, instructionName);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<MinionTriggerMinionListener> getListenerClass() {
|
||||
return MinionTriggerMinionListener.class;
|
||||
public void addListener() {
|
||||
MinionTriggerMinionListener.addListener(world, pos, minionUuid, instructionName);
|
||||
}
|
||||
|
||||
public void setInstruction(UUID minionUuid, String instructionName) {
|
||||
removeListener();
|
||||
this.minionUuid = minionUuid;
|
||||
this.instructionName = instructionName;
|
||||
addListener();
|
||||
markDirty();
|
||||
}
|
||||
|
||||
public void updatePower() {
|
||||
boolean powered = getBlockState().getValue(MinionTriggerBlock.POWERED);
|
||||
boolean powered = getCachedState().get(MinionTriggerBlock.POWERED);
|
||||
|
||||
MinionTriggerMinionListener listener = getListener();
|
||||
if(listener != null) {
|
||||
@@ -50,16 +66,43 @@ public class MinionTriggerBlockEntity extends InstructionBoundBlockEntity<Minion
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void loadAdditional(ValueInput view) {
|
||||
minionUuid = view.read("minionUuid", UUIDUtil.AUTHLIB_CODEC).orElse(null);
|
||||
instructionName = view.getStringOr("instructionName", "");
|
||||
public Optional<MinionFakePlayer> getMinion() {
|
||||
if(minionUuid != null && world != null && world.getPlayerByUuid(minionUuid) instanceof MinionFakePlayer minion) {
|
||||
return Optional.of(minion);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public UUID getMinionUuid() {
|
||||
return minionUuid;
|
||||
}
|
||||
|
||||
public String getInstructionName() {
|
||||
return instructionName;
|
||||
}
|
||||
|
||||
public Optional<ConfiguredInstruction<MinionRuntime>> getInstruction(MinionFakePlayer minion) {
|
||||
return Optional.ofNullable(minion.getInstructionManager().getInstruction(instructionName));
|
||||
}
|
||||
|
||||
public Optional<ConfiguredInstruction<MinionRuntime>> getInstruction() {
|
||||
return getMinion().flatMap(this::getInstruction);
|
||||
}
|
||||
|
||||
public MinionTriggerMinionListener getListener() {
|
||||
return BlockEntityMinionListener.getListener(world, pos, minionUuid, MinionTriggerMinionListener.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void saveAdditional(ValueOutput view) {
|
||||
protected void readData(ReadView view) {
|
||||
minionUuid = view.read("minionUuid", Uuids.CODEC).orElse(null);
|
||||
instructionName = view.getString("instructionName", "");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void writeData(WriteView view) {
|
||||
if(minionUuid != null) {
|
||||
view.store("minionUuid", UUIDUtil.AUTHLIB_CODEC, minionUuid);
|
||||
view.put("minionUuid", Uuids.CODEC, minionUuid);
|
||||
}
|
||||
view.putString("instructionName", instructionName);
|
||||
}
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package io.github.skippyall.minions.block.miniontrigger;
|
||||
|
||||
import eu.pb4.polymer.core.api.item.PolymerBlockItem;
|
||||
import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.util.Identifier;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import xyz.nucleoid.packettweaker.PacketContext;
|
||||
|
||||
public class MinionTriggerBlockItem extends PolymerBlockItem {
|
||||
public MinionTriggerBlockItem(Block block, Settings settings, Item polymerItem) {
|
||||
super(block, settings, polymerItem, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable Identifier getPolymerItemModel(ItemStack stack, PacketContext context) {
|
||||
if(PolymerResourcePackUtils.hasMainPack(context)) {
|
||||
return super.getPolymerItemModel(stack, context);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
-14
@@ -5,16 +5,16 @@ import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import io.github.skippyall.minions.Minions;
|
||||
import io.github.skippyall.minions.listener.BlockEntityMinionInstructionListener;
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.registration.MinionBlocks;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstructionListener;
|
||||
import io.github.skippyall.minions.registration.MinionBlocks;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.UUIDUtil;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.registry.RegistryKey;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.Uuids;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -24,9 +24,9 @@ import java.util.UUID;
|
||||
public class MinionTriggerMinionListener extends BlockEntityMinionInstructionListener<MinionTriggerBlockEntity> {
|
||||
public static final Codec<MinionTriggerMinionListener> CODEC = RecordCodecBuilder.create(instance ->
|
||||
instance.group(
|
||||
Level.RESOURCE_KEY_CODEC.fieldOf("world").forGetter(listener -> listener.worldKey),
|
||||
World.CODEC.fieldOf("world").forGetter(listener -> listener.worldKey),
|
||||
BlockPos.CODEC.fieldOf("pos").forGetter(listener -> listener.pos),
|
||||
UUIDUtil.AUTHLIB_CODEC.fieldOf("minionUuid").forGetter(listener -> listener.minionUuid),
|
||||
Uuids.CODEC.fieldOf("minionUuid").forGetter(listener -> listener.minionUuid),
|
||||
Codec.STRING.fieldOf("instructionName").forGetter(listener -> listener.instructionName)
|
||||
).apply(instance, MinionTriggerMinionListener::new));
|
||||
|
||||
@@ -36,11 +36,23 @@ public class MinionTriggerMinionListener extends BlockEntityMinionInstructionLis
|
||||
boolean runningCache;
|
||||
boolean incomingPowerCache;
|
||||
|
||||
MinionTriggerMinionListener(ResourceKey<Level> worldKey, BlockPos pos, UUID minionUuid, String instructionName) {
|
||||
private MinionTriggerMinionListener(RegistryKey<World> worldKey, BlockPos pos, UUID minionUuid, String instructionName) {
|
||||
super(worldKey, pos, minionUuid, MinionBlocks.MINION_TRIGGER_BE_TYPE);
|
||||
this.instructionName = Objects.requireNonNull(instructionName);
|
||||
}
|
||||
|
||||
public static void addListener(World world, BlockPos pos, UUID minion, String instructionName) {
|
||||
MinionTriggerMinionListener listener = new MinionTriggerMinionListener(world.getRegistryKey(), pos, minion, instructionName);
|
||||
listener.add(world.getServer());
|
||||
}
|
||||
|
||||
public static void removeListener(World world, BlockPos pos, UUID minion, String instructionName) {
|
||||
MinionTriggerMinionListener old = getListener(world, pos, minion, MinionTriggerMinionListener.class);
|
||||
if(old != null) {
|
||||
old.remove(world.getServer());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Map<String, ConfiguredInstructionListener> getInstructionListeners() {
|
||||
return Map.of(instructionName, listener);
|
||||
@@ -76,7 +88,7 @@ public class MinionTriggerMinionListener extends BlockEntityMinionInstructionLis
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(MinecraftServer server) {
|
||||
protected void add(MinecraftServer server) {
|
||||
super.add(server);
|
||||
runningCache = minion.getInstructionManager().getInstruction(instructionName).isRunning();
|
||||
updateComparatorsIfLoaded(server);
|
||||
@@ -84,13 +96,13 @@ public class MinionTriggerMinionListener extends BlockEntityMinionInstructionLis
|
||||
|
||||
@Override
|
||||
public Optional<Identifier> getCodecId() {
|
||||
return Optional.of(Identifier.fromNamespaceAndPath(Minions.MOD_ID, "minion_trigger"));
|
||||
return Optional.of(Identifier.of(Minions.MOD_ID, "minion_trigger"));
|
||||
}
|
||||
|
||||
public void updateComparatorsIfLoaded(MinecraftServer server) {
|
||||
Level world = server.getLevel(worldKey);
|
||||
if(world.isLoaded(pos)) {
|
||||
world.updateNeighbourForOutputSignal(pos, MinionBlocks.MINION_TRIGGER_BLOCK);
|
||||
World world = server.getWorld(worldKey);
|
||||
if(world.isPosLoaded(pos)) {
|
||||
world.updateComparators(pos, MinionBlocks.MINION_TRIGGER_BLOCK);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
@NullMarked
|
||||
package io.github.skippyall.minions.block.miniontrigger;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
@@ -1,4 +0,0 @@
|
||||
@NullMarked
|
||||
package io.github.skippyall.minions.block;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
@@ -1,33 +0,0 @@
|
||||
package io.github.skippyall.minions.clipboard;
|
||||
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.component.DataComponentGetter;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.TooltipFlag;
|
||||
import net.minecraft.world.level.Level;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public record BlockPosClipboard(ResourceKey<Level> world, BlockPos pos) implements Clipboard {
|
||||
public static final MapCodec<BlockPosClipboard> CODEC = RecordCodecBuilder.mapCodec(instance ->
|
||||
instance.group(
|
||||
Level.RESOURCE_KEY_CODEC.fieldOf("world").forGetter(BlockPosClipboard::world),
|
||||
BlockPos.CODEC.fieldOf("pos").forGetter(BlockPosClipboard::pos)
|
||||
).apply(instance, BlockPosClipboard::new)
|
||||
);
|
||||
|
||||
|
||||
@Override
|
||||
public MapCodec<BlockPosClipboard> getCodec() {
|
||||
return CODEC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addToTooltip(Item.TooltipContext context, Consumer<Component> textConsumer, TooltipFlag type, DataComponentGetter components) {
|
||||
textConsumer.accept(Component.translatable("minions.reference.block.tooltip", pos.toString()));
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,12 @@ package io.github.skippyall.minions.clipboard;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import net.minecraft.world.item.component.TooltipProvider;
|
||||
import net.minecraft.item.tooltip.TooltipAppender;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public interface Clipboard extends TooltipProvider {
|
||||
Codec<Clipboard> CODEC = MinionRegistries.CLIPBOARD_TYPES.byNameCodec().dispatch(Clipboard::getCodec, Function.identity());
|
||||
public interface Clipboard extends TooltipAppender {
|
||||
Codec<Clipboard> CODEC = MinionRegistries.CLIPBOARD_TYPES.getCodec().dispatch(Clipboard::getCodec, Function.identity());
|
||||
|
||||
MapCodec<? extends Clipboard> getCodec();
|
||||
}
|
||||
|
||||
@@ -1,23 +1,43 @@
|
||||
package io.github.skippyall.minions.clipboard;
|
||||
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import eu.pb4.polymer.core.api.item.PolymerItem;
|
||||
import io.github.skippyall.minions.registration.MinionComponentTypes;
|
||||
import io.github.skippyall.minions.registration.MinionItems;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.Level;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import net.minecraft.component.DataComponentTypes;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.item.tooltip.TooltipType;
|
||||
import net.minecraft.util.Identifier;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import xyz.nucleoid.packettweaker.PacketContext;
|
||||
|
||||
public class ClipboardItem {
|
||||
public class ClipboardItem extends Item implements PolymerItem {
|
||||
public ClipboardItem(Settings settings) {
|
||||
super(settings);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Item getPolymerItem(ItemStack itemStack, PacketContext context) {
|
||||
return Items.PAPER;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable Identifier getPolymerItemModel(ItemStack stack, PacketContext context) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getPolymerItemStack(ItemStack itemStack, TooltipType tooltipType, PacketContext context) {
|
||||
ItemStack stack = PolymerItem.super.getPolymerItemStack(itemStack, tooltipType, context);
|
||||
stack.set(DataComponentTypes.ENCHANTMENT_GLINT_OVERRIDE, true);
|
||||
return stack;
|
||||
}
|
||||
|
||||
public static ItemStack createInstructionReference(MinionFakePlayer minion, String instructionName) {
|
||||
ItemStack stack = new ItemStack(MinionItems.REFERENCE_ITEM);
|
||||
stack.set(MinionComponentTypes.REFERENCE, new InstructionClipboard(minion.getUUID(), instructionName, minion.getGameProfile().name()));
|
||||
return stack;
|
||||
}
|
||||
|
||||
public static ItemStack createBlockPosReference(Level world, BlockPos pos) {
|
||||
ItemStack stack = new ItemStack(MinionItems.REFERENCE_ITEM);
|
||||
stack.set(MinionComponentTypes.REFERENCE, new BlockPosClipboard(world.dimension(), pos));
|
||||
stack.set(MinionComponentTypes.REFERENCE, new InstructionClipboard(minion.getUuid(), instructionName, minion.getGameProfile().getName()));
|
||||
return stack;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,11 +3,11 @@ package io.github.skippyall.minions.clipboard;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import net.minecraft.core.UUIDUtil;
|
||||
import net.minecraft.core.component.DataComponentGetter;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.TooltipFlag;
|
||||
import net.minecraft.component.ComponentsAccess;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.tooltip.TooltipType;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.Uuids;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
@@ -15,7 +15,7 @@ import java.util.function.Consumer;
|
||||
public record InstructionClipboard(UUID selectedMinion, String selectedInstruction, String visualMinionName) implements Clipboard {
|
||||
public static final MapCodec<InstructionClipboard> CODEC = RecordCodecBuilder.mapCodec(instance ->
|
||||
instance.group(
|
||||
UUIDUtil.AUTHLIB_CODEC.fieldOf("selectedMinion").forGetter(InstructionClipboard::selectedMinion),
|
||||
Uuids.CODEC.fieldOf("selectedMinion").forGetter(InstructionClipboard::selectedMinion),
|
||||
Codec.STRING.fieldOf("selectedInstruction").forGetter(InstructionClipboard::selectedInstruction),
|
||||
Codec.STRING.fieldOf("visualMinionName").forGetter(InstructionClipboard::visualMinionName)
|
||||
).apply(instance, InstructionClipboard::new));
|
||||
@@ -26,7 +26,7 @@ public record InstructionClipboard(UUID selectedMinion, String selectedInstructi
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addToTooltip(Item.TooltipContext context, Consumer<Component> textConsumer, TooltipFlag type, DataComponentGetter components) {
|
||||
textConsumer.accept(Component.translatable("minions.reference.instruction.tooltip", selectedInstruction, visualMinionName));
|
||||
public void appendTooltip(Item.TooltipContext context, Consumer<Text> textConsumer, TooltipType type, ComponentsAccess components) {
|
||||
textConsumer.accept(Text.translatable("minions.reference.instruction.tooltip", selectedInstruction, visualMinionName));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
@NullMarked
|
||||
package io.github.skippyall.minions.clipboard;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
@@ -1,36 +0,0 @@
|
||||
package io.github.skippyall.minions.command;
|
||||
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import io.github.skippyall.minions.docs.DocsManager;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.arguments.IdentifierArgument;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static net.minecraft.commands.Commands.argument;
|
||||
import static net.minecraft.commands.Commands.literal;
|
||||
|
||||
public class DocsSubcommand {
|
||||
public static final LiteralArgumentBuilder<CommandSourceStack> DOCS = literal("docs")
|
||||
.then(
|
||||
argument("docName", IdentifierArgument.id())
|
||||
.suggests(DocsSubcommand::getSuggestions)
|
||||
.executes(DocsSubcommand::execute)
|
||||
);
|
||||
|
||||
public static CompletableFuture<Suggestions> getSuggestions(CommandContext<CommandSourceStack> context, SuggestionsBuilder builder) {
|
||||
DocsManager.getDocsEntryIds().forEach(id -> builder.suggest(id.toString()));
|
||||
return CompletableFuture.completedFuture(builder.build());
|
||||
}
|
||||
|
||||
public static int execute(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
|
||||
Identifier id = IdentifierArgument.getId(context, "docName");
|
||||
DocsManager.showDocsEntry(context.getSource().getPlayerOrException(), id);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -4,21 +4,21 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import io.github.skippyall.minions.minion.MinionData;
|
||||
import io.github.skippyall.minions.minion.MinionPersistentState;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import static net.minecraft.commands.Commands.literal;
|
||||
import static net.minecraft.server.command.CommandManager.literal;
|
||||
|
||||
public class ListSubcommand {
|
||||
public static final LiteralArgumentBuilder<CommandSourceStack> LIST = literal("list")
|
||||
public static final LiteralArgumentBuilder<ServerCommandSource> LIST = literal("list")
|
||||
.executes(ListSubcommand::list);
|
||||
|
||||
public static int list(CommandContext<CommandSourceStack> context) {
|
||||
public static int list(CommandContext<ServerCommandSource> context) {
|
||||
Collection<MinionData> minions = MinionPersistentState.get(context.getSource().getServer()).getMinionData().values();
|
||||
for (MinionData minion : minions) {
|
||||
context.getSource().sendSuccess(() -> Component.literal(minion.getName() + "(" + minion.getUuid() + "):" + minion.isSpawned()), false);
|
||||
context.getSource().sendFeedback(() -> Text.literal(minion.name() + "(" + minion.uuid() + "):" + minion.isSpawned()), false);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -9,15 +9,16 @@ import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import io.github.skippyall.minions.minion.MinionData;
|
||||
import io.github.skippyall.minions.minion.MinionPersistentState;
|
||||
import io.github.skippyall.minions.minion.MinionProfileUtils;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class MinionArgument {
|
||||
public static final SimpleCommandExceptionType MINION_NOT_PRESENT = new SimpleCommandExceptionType(Component.translatable("minions.command.minion.not_present"));
|
||||
public static final SimpleCommandExceptionType MINION_NOT_PRESENT = new SimpleCommandExceptionType(Text.translatable("minions.command.minion.not_present"));
|
||||
|
||||
public static final MinionSuggestionProvider SUGGESTION_PROVIDER = new MinionSuggestionProvider();
|
||||
|
||||
@@ -37,11 +38,11 @@ public class MinionArgument {
|
||||
return data.get();
|
||||
}
|
||||
|
||||
public static class MinionSuggestionProvider implements SuggestionProvider<CommandSourceStack> {
|
||||
public static class MinionSuggestionProvider implements SuggestionProvider<ServerCommandSource> {
|
||||
@Override
|
||||
public CompletableFuture<Suggestions> getSuggestions(CommandContext<CommandSourceStack> context, SuggestionsBuilder builder) throws CommandSyntaxException {
|
||||
public CompletableFuture<Suggestions> getSuggestions(CommandContext<ServerCommandSource> context, SuggestionsBuilder builder) throws CommandSyntaxException {
|
||||
for (MinionData data : MinionPersistentState.get(context.getSource().getServer()).getMinionDataList()) {
|
||||
builder.suggest(data.getName());
|
||||
builder.suggest(data.name());
|
||||
}
|
||||
|
||||
return builder.buildFuture();
|
||||
|
||||
@@ -3,19 +3,17 @@ package io.github.skippyall.minions.command;
|
||||
import com.mojang.brigadier.CommandDispatcher;
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import io.github.skippyall.minions.MinionsConfig;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.command.CommandRegistryAccess;
|
||||
import net.minecraft.server.command.CommandManager;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
|
||||
import static net.minecraft.commands.Commands.literal;
|
||||
import static net.minecraft.server.command.CommandManager.literal;
|
||||
|
||||
public class MinionsCommand {
|
||||
public static void register(CommandDispatcher<CommandSourceStack> dispatcher, CommandBuildContext access, Commands.CommandSelection environment) {
|
||||
LiteralArgumentBuilder<CommandSourceStack> builder = literal("minions")
|
||||
public static void register(CommandDispatcher<ServerCommandSource> dispatcher, CommandRegistryAccess access, CommandManager.RegistrationEnvironment environment) {
|
||||
LiteralArgumentBuilder<ServerCommandSource> builder = literal("minions")
|
||||
.then(SpawnSubcommand.SPAWN)
|
||||
.then(ListSubcommand.LIST)
|
||||
.then(DocsSubcommand.DOCS)
|
||||
.then(TestSubcommand.TEST);
|
||||
.then(ListSubcommand.LIST);
|
||||
|
||||
if(MinionsConfig.get().minion.enableMobCapHacks) {
|
||||
builder.then(MobCapDebugSubcommand.MOB_CAP_DEBUG);
|
||||
|
||||
@@ -4,21 +4,21 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import io.github.skippyall.minions.mixinhelper.antimobcap.ChunkLevelManager$DistanceFromNearestPlayerTrackerAccessor;
|
||||
import io.github.skippyall.minions.mixinhelper.antimobcap.ChunkLevelManagerAccessor;
|
||||
import io.github.skippyall.minions.mixins.antimobcap.ServerChunkCacheAccessor;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.DistanceManager;
|
||||
import io.github.skippyall.minions.mixins.antimobcap.ServerChunkManagerAccessor;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.server.world.ChunkLevelManager;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import static net.minecraft.commands.Commands.literal;
|
||||
import static net.minecraft.server.command.CommandManager.literal;
|
||||
|
||||
public class MobCapDebugSubcommand {
|
||||
public static final LiteralArgumentBuilder<CommandSourceStack> MOB_CAP_DEBUG = literal("mobcapdebug")
|
||||
public static final LiteralArgumentBuilder<ServerCommandSource> MOB_CAP_DEBUG = literal("mobcapdebug")
|
||||
.executes(MobCapDebugSubcommand::mobcapdebugCommand);
|
||||
|
||||
public static int mobcapdebugCommand(CommandContext<CommandSourceStack> context) {
|
||||
DistanceManager levelManager = ((ServerChunkCacheAccessor)context.getSource().getLevel().getChunkSource()).getDistanceManager();
|
||||
public static int mobcapdebugCommand(CommandContext<ServerCommandSource> context) {
|
||||
ChunkLevelManager levelManager = ((ServerChunkManagerAccessor)context.getSource().getWorld().getChunkManager()).getLevelManager();
|
||||
int tickedChunkCount = ((ChunkLevelManager$DistanceFromNearestPlayerTrackerAccessor)((ChunkLevelManagerAccessor)levelManager).minions$getMinionless()).minions$getTickedChunkCount();
|
||||
context.getSource().sendSuccess(() -> Component.nullToEmpty(String.valueOf(tickedChunkCount)), false);
|
||||
context.getSource().sendFeedback(() -> Text.of(String.valueOf(tickedChunkCount)), false);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,26 +6,24 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import io.github.skippyall.minions.minion.MinionData;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.arguments.coordinates.Coordinates;
|
||||
import net.minecraft.commands.arguments.coordinates.Vec3Argument;
|
||||
import net.minecraft.server.permissions.Permissions;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import net.minecraft.command.argument.PosArgument;
|
||||
import net.minecraft.command.argument.Vec3ArgumentType;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
|
||||
import static net.minecraft.commands.Commands.argument;
|
||||
import static net.minecraft.commands.Commands.literal;
|
||||
import static net.minecraft.server.command.CommandManager.argument;
|
||||
import static net.minecraft.server.command.CommandManager.literal;
|
||||
|
||||
public class SpawnSubcommand {
|
||||
public static final LiteralArgumentBuilder<CommandSourceStack> SPAWN = literal("spawn")
|
||||
.requires(source -> source.permissions().hasPermission(Permissions.COMMANDS_GAMEMASTER))
|
||||
public static final LiteralArgumentBuilder<ServerCommandSource> SPAWN = literal("spawn")
|
||||
.requires(source -> source.hasPermissionLevel(2))
|
||||
.then(argument("minion", StringArgumentType.word())
|
||||
.suggests(MinionArgument.SUGGESTION_PROVIDER)
|
||||
.then(argument("pos", Vec3Argument.vec3())
|
||||
.then(argument("pos", Vec3ArgumentType.vec3())
|
||||
.executes(context ->
|
||||
spawnCommand(
|
||||
context.getSource(),
|
||||
StringArgumentType.getString(context, "minion"),
|
||||
Vec3Argument.getCoordinates(context, "pos"),
|
||||
Vec3ArgumentType.getPosArgument(context, "pos"),
|
||||
false
|
||||
)
|
||||
)
|
||||
@@ -34,7 +32,7 @@ public class SpawnSubcommand {
|
||||
spawnCommand(
|
||||
context.getSource(),
|
||||
StringArgumentType.getString(context, "minion"),
|
||||
Vec3Argument.getCoordinates(context, "pos"),
|
||||
Vec3ArgumentType.getPosArgument(context, "pos"),
|
||||
BoolArgumentType.getBool(context, "force")
|
||||
)
|
||||
)
|
||||
@@ -49,9 +47,9 @@ public class SpawnSubcommand {
|
||||
))
|
||||
);
|
||||
|
||||
public static int spawnCommand(CommandSourceStack source, String minion, @Nullable Coordinates pos, boolean force) throws CommandSyntaxException {
|
||||
public static int spawnCommand(ServerCommandSource source, String minion, PosArgument pos, boolean force) throws CommandSyntaxException {
|
||||
MinionData data = MinionArgument.parse(source.getServer(), minion);
|
||||
MinionFakePlayer.spawnMinion(data, source.getLevel(), pos != null ? pos.getPosition(source) : null, pos != null ? pos.getRotation(source) : null, force);
|
||||
MinionFakePlayer.spawnMinion(data, source.getWorld(), pos != null ? pos.getPos(source) : null, pos != null ? pos.getRotation(source) : null, force);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
package io.github.skippyall.minions.command;
|
||||
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import io.github.skippyall.minions.Minions;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
|
||||
import static net.minecraft.commands.Commands.argument;
|
||||
import static net.minecraft.commands.Commands.literal;
|
||||
|
||||
public class TestSubcommand {
|
||||
public static LiteralArgumentBuilder<CommandSourceStack> TEST = literal("test")
|
||||
.then(argument("pos", BlockPosArgument.blockPos())
|
||||
.executes(TestSubcommand::execute)
|
||||
);
|
||||
|
||||
|
||||
private static int execute(CommandContext<CommandSourceStack> context) {
|
||||
try {
|
||||
BlockPos pos = BlockPosArgument.getBlockPos(context, "pos");
|
||||
Collection<BlockPos> result = findInputs(context.getSource().getLevel(), pos);
|
||||
for (BlockPos resultPos : result) {
|
||||
context.getSource().sendSuccess(() -> Component.literal(resultPos.toShortString()), false);
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
Minions.LOGGER.error("Error", e);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static Collection<BlockPos> findInputs(Level world, BlockPos pos) {
|
||||
//positions that are already processed
|
||||
Collection<BlockPos> visitedPositions = new HashSet<>();
|
||||
//positions we are currently looking at
|
||||
Collection<BlockPos> currentPositions = new HashSet<>();
|
||||
//new positions are added here
|
||||
Collection<BlockPos> newPositions = new HashSet<>();
|
||||
//resulting machines
|
||||
Collection<BlockPos> machines = new HashSet<>();
|
||||
|
||||
currentPositions.add(pos);
|
||||
|
||||
while(!currentPositions.isEmpty()) {
|
||||
for(BlockPos currentPosition : currentPositions) {
|
||||
for(Direction dir : Direction.values()) {
|
||||
//check each neighbor of the current positions
|
||||
BlockPos newPos = currentPosition.relative(dir);
|
||||
//Do not check blocks that were already checked
|
||||
if(!visitedPositions.contains(newPos)) {
|
||||
if (world.getBlockState(newPos).getBlock() == Blocks.REDSTONE_BLOCK) {
|
||||
//Add pipes to positions for the next iteration
|
||||
newPositions.add(newPos);
|
||||
} else if (world.getBlockState(newPos).getBlock() == Blocks.IRON_BLOCK) {
|
||||
//Add machines to output set
|
||||
machines.add(newPos);
|
||||
}
|
||||
//Add checked blocks here so that they are not checked again
|
||||
visitedPositions.add(newPos);
|
||||
}
|
||||
}
|
||||
}
|
||||
//Check the new positions in the next iteration
|
||||
currentPositions = newPositions;
|
||||
newPositions = new HashSet<>();
|
||||
}
|
||||
|
||||
return machines;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
@NullMarked
|
||||
package io.github.skippyall.minions.command;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
@@ -1,29 +0,0 @@
|
||||
package io.github.skippyall.minions.docs;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.server.dialog.body.DialogBody;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
public interface DocsEntry {
|
||||
Codec<DocsEntry> CODEC = MinionRegistries.DOCS_ENTRY_TYPES.byNameCodec().dispatch(DocsEntry::getCodec, Function.identity());
|
||||
|
||||
Metadata getMetadata();
|
||||
|
||||
List<DialogBody> getDialog(RegistryAccess manager);
|
||||
|
||||
MapCodec<? extends DocsEntry> getCodec();
|
||||
|
||||
record Metadata(String titleKey) {
|
||||
public static final MapCodec<Metadata> CODEC = RecordCodecBuilder.mapCodec(instance ->
|
||||
instance.group(
|
||||
Codec.STRING.fieldOf("title").forGetter(Metadata::titleKey)
|
||||
).apply(instance, Metadata::new)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
package io.github.skippyall.minions.docs;
|
||||
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import io.github.skippyall.minions.Minions;
|
||||
import net.fabricmc.fabric.api.resource.v1.reloader.SimpleReloadListener;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.network.chat.ClickEvent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.dialog.ActionButton;
|
||||
import net.minecraft.server.dialog.CommonButtonData;
|
||||
import net.minecraft.server.dialog.CommonDialogData;
|
||||
import net.minecraft.server.dialog.DialogAction;
|
||||
import net.minecraft.server.dialog.MultiActionDialog;
|
||||
import net.minecraft.server.dialog.action.StaticAction;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.packs.resources.Resource;
|
||||
import net.minecraft.util.StrictJsonParser;
|
||||
import net.minecraft.util.Tuple;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public class DocsManager extends SimpleReloadListener<Tuple<Map<Identifier, DocsEntry>, DocsTree>> {
|
||||
private static @Nullable Map<Identifier, DocsEntry> docs;
|
||||
private static @Nullable DocsTree tree;
|
||||
|
||||
public static @Nullable DocsTree getTree() {
|
||||
return tree;
|
||||
}
|
||||
|
||||
public static void showDocsEntry(ServerPlayer player, Identifier id) {
|
||||
DocsEntry entry = getDocsEntry(id);
|
||||
if(entry == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<ActionButton> buttons = new ArrayList<>();
|
||||
if(tree != null) {
|
||||
DocsTree.DocElement element = tree.getElement(id);
|
||||
if (element.previous() != null) {
|
||||
Identifier previousId = element.previous().getId();
|
||||
buttons.add(getDialogButton(Component.literal("<- ").append(Component.translatable(getDocsEntry(previousId).getMetadata().titleKey())), previousId.toString()));
|
||||
}
|
||||
if (element.next() != null) {
|
||||
Identifier nextId = element.next().getId();
|
||||
buttons.add(getDialogButton(Component.translatable(getDocsEntry(nextId).getMetadata().titleKey()).append(Component.literal(" ->")), nextId.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
buttons.add(new ActionButton(
|
||||
new CommonButtonData(Component.translatable("gui.ok"), 100),
|
||||
Optional.empty()
|
||||
));
|
||||
|
||||
player.openDialog(Holder.direct(new MultiActionDialog(
|
||||
new CommonDialogData(
|
||||
Component.translatable(entry.getMetadata().titleKey()),
|
||||
Optional.empty(),
|
||||
true,
|
||||
false,
|
||||
DialogAction.CLOSE,
|
||||
entry.getDialog(player.registryAccess()),
|
||||
List.of()
|
||||
),
|
||||
buttons,
|
||||
Optional.empty(),
|
||||
2
|
||||
)));
|
||||
}
|
||||
|
||||
private static ActionButton getDialogButton(Component text, String dialogToOpen) {
|
||||
return new ActionButton(
|
||||
new CommonButtonData(
|
||||
text, 100
|
||||
),
|
||||
Optional.of(new StaticAction(new ClickEvent.RunCommand("/minions docs " + dialogToOpen)))
|
||||
);
|
||||
}
|
||||
|
||||
public static @Nullable DocsEntry getDocsEntry(Identifier id) {
|
||||
if(docs != null) {
|
||||
return docs.get(id);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static @Nullable Collection<Identifier> getDocsEntryIds() {
|
||||
if (docs != null) {
|
||||
return docs.keySet();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Tuple<Map<Identifier, DocsEntry>, DocsTree> prepare(SharedState state) {
|
||||
Map<Identifier, Resource> resources = state.resourceManager().listResources("docs", id -> id.getNamespace().equals(Minions.MOD_ID) && id.getPath().endsWith(".json"));
|
||||
|
||||
final DocsTree. @Nullable BranchElement[] root = {null};
|
||||
Map<Identifier, DocsEntry> docsEntries = new HashMap<>();
|
||||
resources.forEach((id, resource) -> {
|
||||
try(Reader reader = resource.openAsReader()) {
|
||||
if(id.getPath().equals("docs/tree.json")) {
|
||||
DocsTree.BranchElement.CODEC.decode(JsonOps.INSTANCE, StrictJsonParser.parse(reader))
|
||||
.ifSuccess(entry -> root[0] = entry.getFirst())
|
||||
.ifError(error -> Minions.LOGGER.warn("Could not parse docs tree {}: {}", id, error.message()));
|
||||
} else {
|
||||
Identifier docId = Identifier.fromNamespaceAndPath(id.getNamespace(), id.getPath().substring("docs/".length(), id.getPath().length() - ".json".length()));
|
||||
DocsEntry.CODEC.decode(JsonOps.INSTANCE, StrictJsonParser.parse(reader))
|
||||
.ifSuccess(entry -> docsEntries.put(docId, entry.getFirst()))
|
||||
.ifError(error -> Minions.LOGGER.warn("Could not parse docs entry {}: {}", id, error.message()));
|
||||
}
|
||||
} catch (IOException | JsonParseException e) {
|
||||
Minions.LOGGER.warn("Could not read file {}", id, e);
|
||||
}
|
||||
});
|
||||
if(root[0] != null) {
|
||||
DocsTree tree = new DocsTree(root[0]);
|
||||
return new Tuple<>(docsEntries, tree);
|
||||
} else {
|
||||
return new Tuple<>(docsEntries, null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void apply(Tuple<Map<Identifier, DocsEntry>, DocsTree> o, SharedState state) {
|
||||
docs = o.getA();
|
||||
tree = o.getB();
|
||||
}
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
package io.github.skippyall.minions.docs;
|
||||
|
||||
import com.mojang.datafixers.util.Either;
|
||||
import com.mojang.serialization.Codec;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class DocsTree {
|
||||
private final BranchElement root;
|
||||
private final Map<Identifier, DocElement> entries = new HashMap<>();
|
||||
|
||||
public DocsTree(BranchElement root) {
|
||||
this.root = root;
|
||||
initEntries();
|
||||
}
|
||||
|
||||
private void initEntries() {
|
||||
DocElement element = root.first();
|
||||
do {
|
||||
entries.put(element.id, element);
|
||||
element = element.next();
|
||||
} while (element != null);
|
||||
}
|
||||
|
||||
public BranchElement getRoot() {
|
||||
return root;
|
||||
}
|
||||
|
||||
public DocElement getElement(Identifier id) {
|
||||
return entries.get(id);
|
||||
}
|
||||
|
||||
public static abstract sealed class Element {
|
||||
private @Nullable BranchElement parent;
|
||||
|
||||
public @Nullable BranchElement getParent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
void setParent(BranchElement parent) {
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
public @Nullable DocElement next() {
|
||||
if (parent != null) {
|
||||
return parent.next(this);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public @Nullable DocElement previous() {
|
||||
if (parent != null) {
|
||||
return parent.previous(this);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static final class DocElement extends Element {
|
||||
public static final Codec<DocElement> CODEC = Identifier.CODEC.xmap(DocElement::new, DocElement::getId);
|
||||
|
||||
private final Identifier id;
|
||||
|
||||
public DocElement(Identifier element) {
|
||||
this.id = element;
|
||||
}
|
||||
|
||||
public Identifier getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class BranchElement extends Element {
|
||||
public static final Codec<BranchElement> CODEC = Codec.<BranchElement>recursive("DocsBranch", codec ->
|
||||
Codec.either(codec, DocElement.CODEC)
|
||||
.xmap(
|
||||
Either::unwrap,
|
||||
element -> switch (element) {
|
||||
case BranchElement branch -> Either.left(branch);
|
||||
case DocElement doc -> Either.right(doc);
|
||||
}
|
||||
).listOf()
|
||||
.xmap(BranchElement::new, branch -> branch.e)
|
||||
).xmap(BranchElement::setParents, Function.identity());
|
||||
|
||||
private final List<Element> e;
|
||||
|
||||
public BranchElement(List<Element> elements) {
|
||||
e = elements;
|
||||
}
|
||||
|
||||
public DocElement first() {
|
||||
return switch (e.getFirst()) {
|
||||
case BranchElement branch -> branch.first();
|
||||
case DocElement doc -> doc;
|
||||
};
|
||||
}
|
||||
|
||||
public DocElement last() {
|
||||
return switch (e.getLast()) {
|
||||
case BranchElement branch -> branch.last();
|
||||
case DocElement doc -> doc;
|
||||
};
|
||||
}
|
||||
|
||||
public @Nullable DocElement next(Element current) {
|
||||
int nextIndex = e.indexOf(current) + 1;
|
||||
if(nextIndex < e.size()) {
|
||||
return switch (e.get(nextIndex)) {
|
||||
case BranchElement branch -> branch.first();
|
||||
case DocElement doc -> doc;
|
||||
};
|
||||
} else {
|
||||
if(getParent() != null) {
|
||||
return getParent().next(this);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public @Nullable DocElement previous(Element current) {
|
||||
int previousIndex = e.indexOf(current) - 1;
|
||||
if(previousIndex >= 0) {
|
||||
return switch (e.get(previousIndex)) {
|
||||
case BranchElement branch -> branch.first();
|
||||
case DocElement doc -> doc;
|
||||
};
|
||||
} else {
|
||||
if(getParent() != null) {
|
||||
return getParent().previous(this);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private BranchElement setParents() {
|
||||
for(Element element : e) {
|
||||
element.setParent(this);
|
||||
if(element instanceof BranchElement branch) {
|
||||
branch.setParents();
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,82 +1,14 @@
|
||||
package io.github.skippyall.minions.docs;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import io.github.skippyall.minions.gui.GuiDisplay;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.ComponentSerialization;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.dialog.body.DialogBody;
|
||||
import net.minecraft.server.dialog.body.ItemBody;
|
||||
import net.minecraft.server.dialog.body.PlainMessage;
|
||||
import net.minecraft.world.item.Item;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.text.TextCodecs;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public record ReferenceEntry(Metadata metadata, ResourceKey<?> object, Component shortDescription, Component longDescription) implements DocsEntry {
|
||||
private static final Codec<ResourceKey<?>> REGISTRY_KEY_CODEC = RecordCodecBuilder.create(instance ->
|
||||
public record ReferenceEntry(Text shortDescription, Text longDescription) {
|
||||
public static final Codec<ReferenceEntry> CODEC = RecordCodecBuilder.create(instance ->
|
||||
instance.group(
|
||||
Identifier.CODEC.fieldOf("registry").forGetter(ResourceKey::registry),
|
||||
Identifier.CODEC.fieldOf("value").forGetter(ResourceKey::identifier)
|
||||
).apply(instance, (registry, value) -> ResourceKey.create(ResourceKey.createRegistryKey(registry), value))
|
||||
);
|
||||
|
||||
public static final MapCodec<ReferenceEntry> CODEC = RecordCodecBuilder.mapCodec(instance ->
|
||||
instance.group(
|
||||
Metadata.CODEC.fieldOf("metadata").forGetter(ReferenceEntry::getMetadata),
|
||||
REGISTRY_KEY_CODEC.fieldOf("object").forGetter(ReferenceEntry::object),
|
||||
ComponentSerialization.CODEC.fieldOf("shortDescription").forGetter(ReferenceEntry::shortDescription),
|
||||
ComponentSerialization.CODEC.fieldOf("longDescription").forGetter(ReferenceEntry::longDescription)
|
||||
TextCodecs.CODEC.fieldOf("shortDescription").forGetter(ReferenceEntry::shortDescription),
|
||||
TextCodecs.CODEC.fieldOf("longDescription").forGetter(ReferenceEntry::longDescription)
|
||||
).apply(instance, ReferenceEntry::new));
|
||||
|
||||
@Override
|
||||
public Metadata getMetadata() {
|
||||
return metadata;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DialogBody> getDialog(RegistryAccess manager) {
|
||||
List<DialogBody> bodyElements = new ArrayList<>();
|
||||
|
||||
GuiDisplay display = getObjectDisplay(manager);
|
||||
if(display != null) {
|
||||
bodyElements.add(new ItemBody(display.createItemStackTemplate(), Optional.empty(), false, false, 16, 16));
|
||||
}
|
||||
bodyElements.add(new PlainMessage(Component.translatable(object.identifier().toLanguageKey(object.registry().getPath())), 200));
|
||||
bodyElements.add(new PlainMessage(longDescription, 200));
|
||||
|
||||
return bodyElements;
|
||||
}
|
||||
|
||||
public @Nullable GuiDisplay getObjectDisplay(RegistryAccess manager) {
|
||||
GuiDisplay display = GuiDisplay.DEFAULT_DISPLAY;
|
||||
if(object.isFor(Registries.ITEM) || object.isFor(Registries.BLOCK)) {
|
||||
Item item;
|
||||
if(object.isFor(Registries.ITEM)) {
|
||||
item = BuiltInRegistries.ITEM.getValue(object.identifier());
|
||||
} else {
|
||||
item = BuiltInRegistries.BLOCK.getValue(object.identifier()).asItem();
|
||||
}
|
||||
if(item != null) {
|
||||
display = new GuiDisplay.ItemBased(item);
|
||||
}
|
||||
} else {
|
||||
Identifier displayId = object.identifier().withPrefix(object.registry().getPath() + "/");
|
||||
display = GuiDisplay.getGuiDisplay(displayId, manager);
|
||||
}
|
||||
return display;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MapCodec<? extends DocsEntry> getCodec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
@NullMarked
|
||||
package io.github.skippyall.minions.docs;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
@@ -0,0 +1,117 @@
|
||||
package io.github.skippyall.minions.gui;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import io.github.skippyall.minions.gui.input.ChoiceInput;
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import io.github.skippyall.minions.program.supplier.Parameter;
|
||||
import io.github.skippyall.minions.clipboard.ClipboardItem;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.sound.SoundCategory;
|
||||
import net.minecraft.sound.SoundEvents;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
public class ConfigureInstructionGui extends InstructionBoundSimpleGui {
|
||||
private String name;
|
||||
|
||||
private ConfigureInstructionGui(ScreenHandlerType<?> type, ServerPlayerEntity player, MinionFakePlayer minion, ConfiguredInstruction<MinionRuntime> configuredInstruction, String name) {
|
||||
super(type, player, minion, configuredInstruction);
|
||||
this.name = name;
|
||||
init();
|
||||
}
|
||||
|
||||
public static void configureInstructionMenu(String name, ConfiguredInstruction<MinionRuntime> instruction, MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
if(!InstructionGui.checkInstructionExists(name, instruction, minion, player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ConfigureInstructionGui gui = new ConfigureInstructionGui(ScreenHandlerType.GENERIC_9X3, player, minion, instruction, name);
|
||||
|
||||
gui.open();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
setTitle(Text.literal(name));
|
||||
|
||||
setSlot(7, new GuiElementBuilder(Items.ANVIL)
|
||||
.setName(Text.translatable("minions.gui.instruction.configure.rename"))
|
||||
.setCallback(() -> InstructionGui.inputInstructionName(minion, player, name).thenAccept(newName -> {
|
||||
minion.getInstructionManager().setInstructionName(name, newName);
|
||||
configureInstructionMenu(newName, instruction, minion, player);
|
||||
}))
|
||||
);
|
||||
|
||||
setSlot(8, new GuiElementBuilder(Items.LAVA_BUCKET)
|
||||
.setName(Text.translatable("minions.gui.instruction.configure.delete"))
|
||||
.setCallback(() -> ChoiceInput.confirm(player, Text.translatable("minions.gui.instruction.configure.delete.confirm", name))
|
||||
.thenAccept(v -> {
|
||||
minion.getInstructionManager().removeInstruction(name);
|
||||
InstructionGui.instructionList(minion, player);
|
||||
}))
|
||||
);
|
||||
|
||||
updateSuppliers();
|
||||
|
||||
setSlot(13, InstructionGui.createInstructionElement(instruction.getInstruction(), player.getRegistryManager()));
|
||||
|
||||
setSlot(25, new GuiElementBuilder(Items.FEATHER)
|
||||
.setName(Text.translatable("minions.gui.instruction.configure.copy"))
|
||||
.addLoreLine(Text.translatable("minions.gui.instruction.configure.copy.description"))
|
||||
.setCallback(() -> {
|
||||
player.getInventory().offer(ClipboardItem.createInstructionReference(minion, name), true);
|
||||
player.playSoundToPlayer(SoundEvents.BLOCK_NOTE_BLOCK_CHIME.value(), SoundCategory.BLOCKS, 1, 1);
|
||||
})
|
||||
);
|
||||
|
||||
updateRunSlot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInstructionRename(MinionFakePlayer minion, ConfiguredInstruction<?> instruction, String oldName, String newName) {
|
||||
this.setTitle(Text.literal(newName));
|
||||
name = newName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRun(ConfiguredInstruction<?> instruction) {
|
||||
updateRunSlot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStop(ConfiguredInstruction<?> instruction) {
|
||||
updateRunSlot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSupplierChange(ConfiguredInstruction<?> instruction, Parameter<?> parameter) {
|
||||
updateSuppliers();
|
||||
}
|
||||
|
||||
private void updateRunSlot() {
|
||||
if(!instruction.isRunning()) {
|
||||
setSlot(26, new GuiElementBuilder(Items.ARROW)
|
||||
.setName(Text.translatable("minions.gui.instruction.run"))
|
||||
.setCallback(() -> instruction.run(minion.getInstructionManager()))
|
||||
);
|
||||
} else {
|
||||
setSlot(26, new GuiElementBuilder(Items.BARRIER)
|
||||
.setName(Text.translatable("minions.gui.instruction.stop"))
|
||||
.setCallback(() -> instruction.stop(minion.getInstructionManager()))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateSuppliers() {
|
||||
int slot = 12;
|
||||
for(Parameter<?> parameter : instruction.getInstruction().getParameters().reversed()) {
|
||||
setSlot(slot, InstructionGui.createParameterElement(parameter, instruction.getArguments().getArgument(parameter), player.getRegistryManager())
|
||||
.setCallback(() -> InstructionGui.configureArgumentMenu(name, instruction, parameter, minion, player))
|
||||
);
|
||||
slot--;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,74 +1,56 @@
|
||||
package io.github.skippyall.minions.gui;
|
||||
|
||||
import com.mojang.authlib.properties.PropertyMap;
|
||||
import com.mojang.serialization.Codec;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import io.github.skippyall.minions.util.TranslationUtil;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.UUIDUtil;
|
||||
import net.minecraft.core.component.DataComponentPatch;
|
||||
import net.minecraft.core.component.DataComponentType;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.ItemStackTemplate;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.item.Rarity;
|
||||
import net.minecraft.world.item.component.ResolvableProfile;
|
||||
import net.minecraft.world.item.component.TooltipDisplay;
|
||||
import it.unimi.dsi.fastutil.objects.ReferenceSortedSets;
|
||||
import net.minecraft.component.DataComponentTypes;
|
||||
import net.minecraft.component.type.ProfileComponent;
|
||||
import net.minecraft.component.type.TooltipDisplayComponent;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.registry.DynamicRegistryManager;
|
||||
import net.minecraft.registry.Registries;
|
||||
import net.minecraft.registry.Registry;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.Rarity;
|
||||
import net.minecraft.util.Uuids;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface GuiDisplay {
|
||||
Codec<GuiDisplay> CODEC = MinionRegistries.GUI_DISPLAY_TYPE.byNameCodec().dispatch(GuiDisplay::getCodec, codec -> codec.fieldOf("data"));
|
||||
Codec<GuiDisplay> CODEC = MinionRegistries.GUI_DISPLAY_TYPE.getCodec().dispatch(GuiDisplay::getCodec, codec -> codec.fieldOf("data"));
|
||||
GuiDisplay DEFAULT_DISPLAY = new ItemBased(Items.BARRIER);
|
||||
|
||||
TooltipDisplay TOOLTIP_HIDE_ALL_COMPONENTS = createHideAllTooltip();
|
||||
|
||||
private static TooltipDisplay createHideAllTooltip() {
|
||||
LinkedHashSet<DataComponentType<?>> set = new LinkedHashSet<>();
|
||||
for(DataComponentType<?> type : BuiltInRegistries.DATA_COMPONENT_TYPE) {
|
||||
if(type != DataComponents.LORE) {
|
||||
set.add(type);
|
||||
}
|
||||
}
|
||||
return new TooltipDisplay(false, set);
|
||||
static GuiDisplay getGuiDisplay(Identifier id, DynamicRegistryManager manager) {
|
||||
return manager.getOptional(MinionRegistries.GUI_DISPLAY).map(registry -> registry.get(id)).orElse(DEFAULT_DISPLAY);
|
||||
}
|
||||
|
||||
static GuiDisplay getGuiDisplay(Identifier id, RegistryAccess manager) {
|
||||
return manager.lookup(MinionRegistries.GUI_DISPLAY).map(registry -> registry.getValue(id)).orElse(DEFAULT_DISPLAY);
|
||||
}
|
||||
|
||||
static <T> GuiDisplay getGuiDisplayFor(Registry<T> registry, T element, RegistryAccess manager) {
|
||||
Identifier elementId = registry.getKey(element);
|
||||
static <T> GuiDisplay getGuiDisplayFor(Registry<T> registry, T element, DynamicRegistryManager manager) {
|
||||
Identifier elementId = registry.getId(element);
|
||||
if(elementId == null) {
|
||||
return DEFAULT_DISPLAY;
|
||||
}
|
||||
Identifier displayId = elementId.withPrefix(registry.key().identifier().getPath() + "/");
|
||||
Identifier displayId = elementId.withPrefixedPath(registry.getKey().getValue().getPath() + "/");
|
||||
|
||||
return getGuiDisplay(displayId, manager);
|
||||
}
|
||||
|
||||
static <T> ItemStack getDisplayStack(Registry<T> registry, T element, RegistryAccess manager) {
|
||||
static <T> ItemStack getDisplayStack(Registry<T> registry, T element, DynamicRegistryManager manager) {
|
||||
return getGuiDisplayFor(registry, element, manager).createItemStack();
|
||||
}
|
||||
|
||||
static <T> ItemStack getDisplayStackWithName(Registry<T> registry, T element, RegistryAccess manager) {
|
||||
static <T> ItemStack getDisplayStackWithName(Registry<T> registry, T element, DynamicRegistryManager manager) {
|
||||
ItemStack stack = getDisplayStack(registry, element, manager);
|
||||
stack.set(DataComponents.CUSTOM_NAME, Component.translatable(TranslationUtil.getTranslationKey(element, registry)).withStyle(style -> style.withItalic(false).withColor(ChatFormatting.WHITE)));
|
||||
stack.set(DataComponentTypes.ITEM_NAME, Text.translatable(TranslationUtil.getTranslationKey(element, registry)));
|
||||
return stack;
|
||||
}
|
||||
|
||||
ItemStackTemplate createItemStackTemplate();
|
||||
|
||||
default ItemStack createItemStack() {
|
||||
return createItemStackTemplate().create();
|
||||
}
|
||||
ItemStack createItemStack();
|
||||
|
||||
Codec<? extends GuiDisplay> getCodec();
|
||||
|
||||
@@ -82,11 +64,10 @@ public interface GuiDisplay {
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStackTemplate createItemStackTemplate() {
|
||||
return new ItemStackTemplate(Items.BARRIER, DataComponentPatch.builder()
|
||||
.set(DataComponents.ITEM_MODEL, model)
|
||||
.build()
|
||||
);
|
||||
public ItemStack createItemStack() {
|
||||
ItemStack stack = new ItemStack(Items.BARRIER);
|
||||
stack.set(DataComponentTypes.ITEM_MODEL, model);
|
||||
return stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -96,7 +77,7 @@ public interface GuiDisplay {
|
||||
}
|
||||
|
||||
class ItemBased implements GuiDisplay {
|
||||
public static final Codec<ItemBased> CODEC = BuiltInRegistries.ITEM.byNameCodec().xmap(ItemBased::new, display -> display.item);
|
||||
public static final Codec<ItemBased> CODEC = Registries.ITEM.getCodec().xmap(ItemBased::new, display -> display.item);
|
||||
|
||||
private final Item item;
|
||||
|
||||
@@ -105,11 +86,11 @@ public interface GuiDisplay {
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStackTemplate createItemStackTemplate() {
|
||||
return new ItemStackTemplate(item, DataComponentPatch.builder()
|
||||
.set(DataComponents.TOOLTIP_DISPLAY, TOOLTIP_HIDE_ALL_COMPONENTS)
|
||||
.set(DataComponents.RARITY, Rarity.COMMON)
|
||||
.build());
|
||||
public ItemStack createItemStack() {
|
||||
ItemStack stack = new ItemStack(item);
|
||||
stack.set(DataComponentTypes.TOOLTIP_DISPLAY, new TooltipDisplayComponent(true, ReferenceSortedSets.emptySet()));
|
||||
stack.set(DataComponentTypes.RARITY, Rarity.COMMON);
|
||||
return stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -119,7 +100,7 @@ public interface GuiDisplay {
|
||||
}
|
||||
|
||||
class HeadBased implements GuiDisplay {
|
||||
public static final Codec<HeadBased> CODEC = UUIDUtil.AUTHLIB_CODEC.xmap(HeadBased::new, display -> display.uuid);
|
||||
public static final Codec<HeadBased> CODEC = Uuids.CODEC.xmap(HeadBased::new, display -> display.uuid);
|
||||
|
||||
private final UUID uuid;
|
||||
|
||||
@@ -128,12 +109,10 @@ public interface GuiDisplay {
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStackTemplate createItemStackTemplate() {
|
||||
return new ItemStackTemplate(Items.PLAYER_HEAD, DataComponentPatch.builder()
|
||||
.set(DataComponents.PROFILE, ResolvableProfile.createUnresolved(uuid))
|
||||
.set(DataComponents.TOOLTIP_DISPLAY, TOOLTIP_HIDE_ALL_COMPONENTS)
|
||||
.build()
|
||||
);
|
||||
public ItemStack createItemStack() {
|
||||
ItemStack stack = new ItemStack(Items.PLAYER_HEAD);
|
||||
stack.set(DataComponentTypes.PROFILE, new ProfileComponent(Optional.empty(), Optional.of(uuid), new PropertyMap()));
|
||||
return stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -143,17 +122,17 @@ public interface GuiDisplay {
|
||||
}
|
||||
|
||||
class StackBased implements GuiDisplay {
|
||||
public static final Codec<StackBased> CODEC = ItemStackTemplate.CODEC.xmap(StackBased::new, StackBased::createItemStackTemplate);
|
||||
public static final Codec<StackBased> CODEC = ItemStack.CODEC.xmap(StackBased::new, StackBased::createItemStack);
|
||||
|
||||
private final ItemStackTemplate template;
|
||||
private final ItemStack stack;
|
||||
|
||||
public StackBased(ItemStackTemplate template) {
|
||||
this.template = template;
|
||||
public StackBased(ItemStack stack) {
|
||||
this.stack = stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStackTemplate createItemStackTemplate() {
|
||||
return template;
|
||||
public ItemStack createItemStack() {
|
||||
return stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package io.github.skippyall.minions.gui;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstructionListener;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
|
||||
public class InstructionBoundSimpleGui extends MinionBoundSimpleGui implements ConfiguredInstructionListener {
|
||||
protected final ConfiguredInstruction<MinionRuntime> instruction;
|
||||
|
||||
public InstructionBoundSimpleGui(ScreenHandlerType<?> type, ServerPlayerEntity player, MinionFakePlayer minion, ConfiguredInstruction<MinionRuntime> instruction) {
|
||||
super(type, player, minion);
|
||||
this.instruction = instruction;
|
||||
instruction.addListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInstructionRemove(ConfiguredInstruction<?> instruction) {
|
||||
close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose() {
|
||||
super.onClose();
|
||||
instruction.removeListener(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package io.github.skippyall.minions.gui;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import io.github.skippyall.minions.program.value.ValueType;
|
||||
import io.github.skippyall.minions.registration.MinionComponentTypes;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import io.github.skippyall.minions.gui.input.Result;
|
||||
import io.github.skippyall.minions.gui.input.TextInput;
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.module.MinionModule;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplier;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierType;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import io.github.skippyall.minions.program.instruction.InstructionType;
|
||||
import io.github.skippyall.minions.program.supplier.Parameter;
|
||||
import io.github.skippyall.minions.util.TranslationUtil;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.registry.DynamicRegistryManager;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class InstructionGui {
|
||||
public static void openInstructionMainMenu(MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
SimpleGui gui = new MinionBoundSimpleGui(ScreenHandlerType.GENERIC_3X3, player, minion);
|
||||
gui.setTitle(Text.translatable("minions.gui.instruction.title"));
|
||||
|
||||
gui.setSlot(3, new GuiElementBuilder()
|
||||
.setItem(Items.BOOK)
|
||||
.setName(Text.translatable("minions.gui.instruction.list"))
|
||||
.setCallback(() -> instructionList(minion, player))
|
||||
);
|
||||
gui.setSlot(5, new GuiElementBuilder()
|
||||
.setItem(Items.WRITABLE_BOOK)
|
||||
.setName(Text.translatable("minions.gui.instruction.create"))
|
||||
.setCallback(() -> createNewInstruction(minion, player))
|
||||
);
|
||||
|
||||
gui.open();
|
||||
}
|
||||
|
||||
public static void instructionList(MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
SimpleGui gui = new MinionBoundSimpleGui(ScreenHandlerType.GENERIC_9X3, player, minion) {
|
||||
@Override
|
||||
public void onInstructionsUpdate(MinionFakePlayer minion) {
|
||||
resetInstructionList(this, minion, player);
|
||||
}
|
||||
};
|
||||
gui.setTitle(Text.translatable("minions.gui.instruction.title"));
|
||||
resetInstructionList(gui, minion, player);
|
||||
|
||||
gui.open();
|
||||
}
|
||||
|
||||
private static void resetInstructionList(SimpleGui gui, MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
int i = 0;
|
||||
for (String instructionName : minion.getInstructionManager().getInstructionNames()) {
|
||||
ConfiguredInstruction<MinionRuntime> instruction = minion.getInstructionManager().getInstruction(instructionName);
|
||||
gui.setSlot(i, new GuiElementBuilder(GuiDisplay.getGuiDisplayFor(MinionRegistries.INSTRUCTION_TYPES, instruction.getInstruction(), player.getRegistryManager()).createItemStack())
|
||||
.setName(Text.literal(instructionName))
|
||||
.setCallback(() -> ConfigureInstructionGui.configureInstructionMenu(instructionName, instruction, minion, player))
|
||||
);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
public static void createNewInstruction(MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
selectInstructionModuleMenu(minion, player).thenAccept(instructionType ->
|
||||
inputInstructionName(minion, player, "Instruction").thenAccept(name -> {
|
||||
if (!minion.isRemoved() && !minion.isDisconnected()) {
|
||||
ConfiguredInstruction<MinionRuntime> configuredInstruction = minion.getInstructionManager().createInstruction(name, instructionType);
|
||||
ConfigureInstructionGui.configureInstructionMenu(name, configuredInstruction, minion, player);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
public static CompletableFuture<String> inputInstructionName(MinionFakePlayer minion, ServerPlayerEntity player, String defaultValue) {
|
||||
return TextInput.inputSync(player, Text.translatable("minions.gui.instruction.enter_name"), defaultValue, name -> {
|
||||
if (minion.getInstructionManager().hasInstruction(name)) {
|
||||
return new Result.Error<>(Text.translatable("minions.gui.instruction.name_already_used"));
|
||||
}
|
||||
return new Result.Success<>(name);
|
||||
});
|
||||
}
|
||||
|
||||
public static boolean checkInstructionExists(String name, ConfiguredInstruction<?> instruction, MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
boolean stillExists = !minion.isRemoved() && !minion.isDisconnected() && minion.getInstructionManager().getInstruction(name) == instruction;
|
||||
if (!stillExists) {
|
||||
player.closeHandledScreen();
|
||||
player.sendMessage(Text.translatable("minions.gui.instruction.removed"));
|
||||
}
|
||||
return stillExists;
|
||||
}
|
||||
|
||||
|
||||
public static <T, A extends ValueSupplier<T, MinionRuntime>> void configureArgumentMenu(String instructionName, ConfiguredInstruction<MinionRuntime> instruction, Parameter<T> parameter, MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
if (!checkInstructionExists(instructionName, instruction, minion, player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@Nullable A argument = instruction.getArguments().getArgument(parameter);
|
||||
|
||||
if(argument == null) {
|
||||
configureTypeAndValue(instructionName, instruction, parameter, minion, player);
|
||||
return;
|
||||
}
|
||||
|
||||
SimpleGui gui = new InstructionBoundSimpleGui(ScreenHandlerType.GENERIC_3X3, player, minion, instruction);
|
||||
|
||||
ItemStack displayStack = GuiDisplay.getDisplayStack(MinionRegistries.VALUE_SUPPLIER_TYPES, argument.getType(), player.getRegistryManager());
|
||||
|
||||
gui.setSlot(3, new GuiElementBuilder(displayStack)
|
||||
.setName(Text.translatable("minions.gui.instruction.argument.configure.type", Text.translatable(TranslationUtil.getTranslationKey(argument.getType(), MinionRegistries.VALUE_SUPPLIER_TYPES, "minions.gui.instruction.argument.configure.type.unset"))))
|
||||
.setCallback(() -> configureTypeAndValue(instructionName, instruction, parameter, minion, player))
|
||||
);
|
||||
gui.setSlot(5, new GuiElementBuilder(Items.STRUCTURE_VOID)
|
||||
.setName(Text.literal("Configure"))
|
||||
.setCallback(() -> argument.getType().openConfiguration(player, argument.getValueType(), argument)
|
||||
.thenAccept(newArgument -> instruction.getArguments().setArgument(parameter, newArgument))
|
||||
)
|
||||
);
|
||||
gui.open();
|
||||
}
|
||||
|
||||
public static CompletableFuture<ValueSupplierType<MinionRuntime>> selectArgumentType(ServerPlayerEntity player, MinionFakePlayer minion, ValueType<?> valueType, ConfiguredInstruction<MinionRuntime> instruction) {
|
||||
CompletableFuture<ValueSupplierType<MinionRuntime>> future = new CompletableFuture<>();
|
||||
SimpleGui gui = new InstructionBoundSimpleGui(ScreenHandlerType.GENERIC_9X3, player, minion, instruction);
|
||||
for (ValueSupplierType<MinionRuntime> type : MinionRegistries.VALUE_SUPPLIER_TYPES) {
|
||||
if(type.isConfigurable(player, valueType, minion)) {
|
||||
gui.addSlot(new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.VALUE_SUPPLIER_TYPES, type, player.getRegistryManager()))
|
||||
.setCallback(() -> future.complete(type))
|
||||
);
|
||||
}
|
||||
}
|
||||
gui.open();
|
||||
return future;
|
||||
}
|
||||
|
||||
public static <T> void configureTypeAndValue(String name, ConfiguredInstruction<MinionRuntime> instruction, Parameter<T> parameter, MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
selectArgumentType(player, minion, parameter.type(), instruction)
|
||||
.thenApply(type -> type.openConfiguration(player, parameter.type(), null)
|
||||
.thenAccept(newArgument -> {
|
||||
instruction.getArguments().setArgument(parameter, newArgument);
|
||||
configureArgumentMenu(name, instruction, parameter, minion, player);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
public static CompletableFuture<InstructionType<MinionRuntime>> selectInstructionModuleMenu(MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
if (minion.getModuleInventory().getModules().isEmpty()) {
|
||||
player.sendMessage(Text.translatable("minions.gui.instruction.no_modules"));
|
||||
return CompletableFuture.failedFuture(new NoSuchElementException("No modules"));
|
||||
}
|
||||
|
||||
CompletableFuture<InstructionType<MinionRuntime>> future = new CompletableFuture<>();
|
||||
|
||||
SimpleGui gui = new MinionBoundSimpleGui(ScreenHandlerType.GENERIC_9X3, player, minion) {
|
||||
@Override
|
||||
public void onClose() {
|
||||
if (!future.isDone()) {
|
||||
future.cancel(false);
|
||||
}
|
||||
super.onClose();
|
||||
}
|
||||
};
|
||||
gui.setTitle(Text.translatable("minions.gui.instruction.select_instruction"));
|
||||
|
||||
for (int i = 0; i < minion.getModuleInventory().size(); i++) {
|
||||
ItemStack moduleItem = minion.getModuleInventory().getStack(i);
|
||||
MinionModule module = moduleItem.get(MinionComponentTypes.MODULE);
|
||||
if (module != null && !module.instructions().isEmpty()) {
|
||||
gui.addSlot(new GuiElementBuilder(moduleItem)
|
||||
.setCallback(() -> selectInstructionMenu(module, minion, player)
|
||||
.thenApply(future::complete)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
gui.open();
|
||||
return future;
|
||||
}
|
||||
|
||||
public static CompletableFuture<InstructionType<MinionRuntime>> selectInstructionMenu(MinionModule module, MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
CompletableFuture<InstructionType<MinionRuntime>> future = new CompletableFuture<>();
|
||||
|
||||
SimpleGui gui = new MinionBoundSimpleGui(ScreenHandlerType.GENERIC_9X3, player, minion) {
|
||||
@Override
|
||||
public void onClose() {
|
||||
if (!future.isDone()) {
|
||||
future.cancel(false);
|
||||
}
|
||||
super.onClose();
|
||||
}
|
||||
};
|
||||
gui.setTitle(Text.translatable("minions.gui.instruction.select_instruction"));
|
||||
|
||||
for (InstructionType<MinionRuntime> instructionType : module.instructions()) {
|
||||
gui.addSlot(createInstructionElement(instructionType, player.getRegistryManager())
|
||||
.setCallback(() -> future.complete(instructionType))
|
||||
);
|
||||
}
|
||||
|
||||
gui.open();
|
||||
return future;
|
||||
}
|
||||
|
||||
public static GuiElementBuilder createInstructionElement(InstructionType<MinionRuntime> instructionType, DynamicRegistryManager manager) {
|
||||
GuiElementBuilder instructionBuilder;
|
||||
if (instructionType != null) {
|
||||
instructionBuilder = new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.INSTRUCTION_TYPES, instructionType, manager));
|
||||
} else {
|
||||
instructionBuilder = new GuiElementBuilder(Items.RED_WOOL)
|
||||
.setName(Text.translatable("minions.gui.instruction.no_instruction_set"));
|
||||
}
|
||||
return instructionBuilder;
|
||||
}
|
||||
|
||||
public static GuiElementBuilder createParameterElement(Parameter<?> parameter, @Nullable ValueSupplier<?,?> valueSupplier, DynamicRegistryManager manager) {
|
||||
GuiElementBuilder builder = new GuiElementBuilder(GuiDisplay.getDisplayStack(MinionRegistries.VALUE_TYPES, parameter.type(), manager))
|
||||
.setName(Text.translatable("minions.gui.instruction.parameter", parameter.name(), Text.translatable(TranslationUtil.getTranslationKey(parameter.type(), MinionRegistries.VALUE_TYPES))));
|
||||
if(valueSupplier != null) {
|
||||
builder.addLoreLine(Text.translatable("minions.gui.instruction.argument", valueSupplier.getDisplayText()));
|
||||
}
|
||||
return builder;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package io.github.skippyall.minions.gui;
|
||||
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import io.github.skippyall.minions.minion.MinionListener;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
|
||||
public class MinionBoundSimpleGui extends SimpleGui implements MinionListener {
|
||||
protected final MinionFakePlayer minion;
|
||||
|
||||
public MinionBoundSimpleGui(ScreenHandlerType<?> type, ServerPlayerEntity player, MinionFakePlayer minion) {
|
||||
super(type, player, false);
|
||||
this.minion = minion;
|
||||
minion.addMinionListener(this);
|
||||
}
|
||||
|
||||
public MinionFakePlayer getMinion() {
|
||||
return minion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMinionRemove(MinionFakePlayer minion) {
|
||||
close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose() {
|
||||
minion.removeMinionListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof MinionBoundSimpleGui that)) return false;
|
||||
return minion == that.minion && player == that.player;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package io.github.skippyall.minions.gui;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.module.ModuleInventory;
|
||||
import net.minecraft.entity.EquipmentSlot;
|
||||
import net.minecraft.entity.player.PlayerInventory;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.screen.slot.ArmorSlot;
|
||||
import net.minecraft.screen.slot.Slot;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
public class MinionGui {
|
||||
public static void openInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
|
||||
openServerSideInventory(player, minion);
|
||||
}
|
||||
|
||||
public static void openServerSideInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
|
||||
SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_3X3, player, false);
|
||||
gui.setTitle(minion.getName());
|
||||
|
||||
gui.setSlot(1, new GuiElementBuilder()
|
||||
.setItem(Items.COMMAND_BLOCK)
|
||||
.setName(Text.translatable("minions.gui.main.instructions"))
|
||||
.setCallback((i, clickType, slotActionType) -> {
|
||||
InstructionGui.openInstructionMainMenu(minion, player);
|
||||
})
|
||||
);
|
||||
gui.setSlot(3, new GuiElementBuilder()
|
||||
.setItem(Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE)
|
||||
.setName(Text.translatable("minions.gui.main.modules"))
|
||||
.setCallback(() -> {
|
||||
ModuleInventory.openModuleInventory(player, minion);
|
||||
})
|
||||
);
|
||||
gui.setSlot(5, new GuiElementBuilder()
|
||||
.setItem(Items.CHEST)
|
||||
.setName(Text.translatable("minions.gui.main.inventory"))
|
||||
.setCallback(() -> {
|
||||
openMinionInventory(player, minion);
|
||||
})
|
||||
);
|
||||
gui.setSlot(7, new GuiElementBuilder()
|
||||
.setItem(Items.BARRIER)
|
||||
.setName(Text.translatable("minions.gui.main.pickup"))
|
||||
.setCallback(() -> {
|
||||
minion.kill(minion.getWorld());
|
||||
})
|
||||
);
|
||||
gui.open();
|
||||
}
|
||||
|
||||
public static void openMinionInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
|
||||
SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_9X6, player, false);
|
||||
gui.setTitle(Text.translatable("minions.gui.inventory.title"));
|
||||
|
||||
for(int i = 0; i < 18; i++) {
|
||||
gui.setSlot(i, new ItemStack(Items.BARRIER));
|
||||
}
|
||||
|
||||
gui.setSlot(2, new ItemStack(Items.LEATHER_HELMET));
|
||||
gui.setSlot(3, new ItemStack(Items.LEATHER_CHESTPLATE));
|
||||
gui.setSlot(4, new ItemStack(Items.LEATHER_LEGGINGS));
|
||||
gui.setSlot(5, new ItemStack(Items.LEATHER_BOOTS));
|
||||
gui.setSlot(6, new ItemStack(Items.SHIELD));
|
||||
|
||||
gui.setSlotRedirect(2 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.HEAD, EquipmentSlot.HEAD.getOffsetEntitySlotId(PlayerInventory.MAIN_SIZE), 0, 0, null));
|
||||
gui.setSlotRedirect(3 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.CHEST, EquipmentSlot.CHEST.getOffsetEntitySlotId(PlayerInventory.MAIN_SIZE), 0, 0, null));
|
||||
gui.setSlotRedirect(4 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.LEGS, EquipmentSlot.LEGS.getOffsetEntitySlotId(PlayerInventory.MAIN_SIZE), 0, 0, null));
|
||||
gui.setSlotRedirect(5 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.FEET, EquipmentSlot.FEET.getOffsetEntitySlotId(PlayerInventory.MAIN_SIZE), 0, 0, null));
|
||||
gui.setSlotRedirect(6 + 9, new Slot(minion.getInventory(), PlayerInventory.OFF_HAND_SLOT, 0, 0));
|
||||
|
||||
for (int i = PlayerInventory.HOTBAR_SIZE; i < PlayerInventory.MAIN_SIZE; i++) {
|
||||
gui.setSlotRedirect(i + 9, new Slot(minion.getInventory(), i, 0, 0));
|
||||
}
|
||||
|
||||
for (int i = 0; i < PlayerInventory.HOTBAR_SIZE; i++) {
|
||||
gui.setSlotRedirect(i + 45, new Slot(minion.getInventory(), i, 0, 0));
|
||||
}
|
||||
gui.open();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package io.github.skippyall.minions.gui;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import io.github.skippyall.minions.gui.input.TextInput;
|
||||
import io.github.skippyall.minions.minion.MinionData;
|
||||
import io.github.skippyall.minions.minion.MinionItem;
|
||||
import io.github.skippyall.minions.minion.MinionProfileUtils;
|
||||
import io.github.skippyall.minions.minion.skin.SkinProvider;
|
||||
import io.github.skippyall.minions.registration.SkinProviders;
|
||||
import net.minecraft.component.DataComponentTypes;
|
||||
import net.minecraft.component.type.ProfileComponent;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class MinionLookGui extends SimpleGui {
|
||||
private ItemStack minionItem;
|
||||
private SkinProvider currentSkinProvider;
|
||||
|
||||
public MinionLookGui(ServerPlayerEntity player, ItemStack minionItem) {
|
||||
super(ScreenHandlerType.GENERIC_9X3, player, false);
|
||||
this.minionItem = minionItem;
|
||||
this.currentSkinProvider = SkinProviders.NAME;
|
||||
}
|
||||
|
||||
public void update() {
|
||||
updateName();
|
||||
updateSkin();
|
||||
updateSkinProvider();
|
||||
}
|
||||
|
||||
private void updateName() {
|
||||
setSlot(10, new GuiElementBuilder()
|
||||
.setItem(Items.OAK_SIGN)
|
||||
.setName(Text.literal(getData().name()))
|
||||
.setCallback(() -> {
|
||||
openRenameGui(player, minionItem);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private void updateSkin() {
|
||||
GuiElementBuilder builder = new GuiElementBuilder()
|
||||
.setItem(Items.PLAYER_HEAD)
|
||||
.setCallback(() -> currentSkinProvider.openSkinMenu(player).thenAccept(skin -> {
|
||||
MinionItem.setData(player.getServer(), getData().withSkin(skin), minionItem);
|
||||
}));
|
||||
if(MinionItem.getData(player.getServer(), minionItem) != null && MinionItem.getData(player.getServer(), minionItem).skin().isPresent()) {
|
||||
builder.setComponent(DataComponentTypes.PROFILE, new ProfileComponent(Optional.empty(), Optional.empty(), getData().skin().get()));
|
||||
}
|
||||
setSlot(16, builder);
|
||||
}
|
||||
|
||||
private void cycleSkinProvider() {
|
||||
int currentId = MinionRegistries.SKIN_PROVIDERS.getRawId(currentSkinProvider);
|
||||
currentId++;
|
||||
if(MinionRegistries.SKIN_PROVIDERS.size() == currentId) {
|
||||
currentId = 0;
|
||||
}
|
||||
|
||||
currentSkinProvider = MinionRegistries.SKIN_PROVIDERS.get(currentId);
|
||||
updateSkinProvider();
|
||||
}
|
||||
|
||||
private void updateSkinProvider() {
|
||||
setSlot(25, new GuiElementBuilder()
|
||||
.setItem(Items.GREEN_STAINED_GLASS_PANE)
|
||||
.setComponent(DataComponentTypes.CUSTOM_NAME, currentSkinProvider.getDisplayName())
|
||||
.setCallback(this::cycleSkinProvider)
|
||||
);
|
||||
}
|
||||
|
||||
private MinionData getData() {
|
||||
return MinionItem.getDataOrDefault(player.getServer(), minionItem);
|
||||
}
|
||||
|
||||
public static void open(ServerPlayerEntity player, ItemStack minionItem) {
|
||||
MinionLookGui gui = new MinionLookGui(player, minionItem);
|
||||
gui.update();
|
||||
gui.open();
|
||||
}
|
||||
|
||||
public void openRenameGui(ServerPlayerEntity player, ItemStack minionItem) {
|
||||
TextInput.inputSync(player, Text.translatable("minions.gui.look.rename.title"), "Minion", name -> MinionProfileUtils.checkMinionNameWithoutPrefix(player.getServer(), name))
|
||||
.thenAccept(name -> {
|
||||
MinionItem.setData(player.getServer(), getData().withName(MinionProfileUtils.getPrefix() + name), minionItem);
|
||||
open();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
package io.github.skippyall.minions.gui
|
||||
|
||||
import com.mojang.authlib.GameProfile
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder
|
||||
import eu.pb4.sgui.api.gui.SimpleGui
|
||||
import io.github.skippyall.minions.gui.input.TextInput
|
||||
import io.github.skippyall.minions.minion.MinionData
|
||||
import io.github.skippyall.minions.minion.MinionItem
|
||||
import io.github.skippyall.minions.minion.MinionProfileUtils
|
||||
import io.github.skippyall.minions.minion.skin.SkinProvider
|
||||
import io.github.skippyall.minions.registration.MinionRegistries
|
||||
import io.github.skippyall.minions.registration.SkinProviders
|
||||
import kotlinx.coroutines.future.await
|
||||
import kotlinx.coroutines.launch
|
||||
import net.fabricmc.fabric.api.entity.FakePlayer
|
||||
import net.minecraft.core.component.DataComponents
|
||||
import net.minecraft.network.chat.Component
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
import net.minecraft.world.inventory.MenuType
|
||||
import net.minecraft.world.item.ItemStack
|
||||
import net.minecraft.world.item.Items
|
||||
import net.minecraft.world.item.component.ResolvableProfile
|
||||
import java.util.*
|
||||
|
||||
class MinionLookGui(
|
||||
viewer: ServerPlayer,
|
||||
private val minionItem: ItemStack
|
||||
) : MinionsGui(viewer) {
|
||||
private lateinit var gui: SimpleGui
|
||||
|
||||
private var currentSkinProvider: SkinProvider = SkinProviders.NAME
|
||||
|
||||
private val data: MinionData
|
||||
get() = MinionItem.getDataOrDefault(viewer.level().server, minionItem)
|
||||
|
||||
init {
|
||||
open()
|
||||
}
|
||||
|
||||
override fun open() {
|
||||
gui = object : SimpleGui(MenuType.GENERIC_9x3, viewer, false) {
|
||||
override fun onPlayerClose(success: Boolean) {
|
||||
onBackingClosed()
|
||||
}
|
||||
}
|
||||
update()
|
||||
gui.open()
|
||||
}
|
||||
|
||||
override fun closeBacking() {
|
||||
gui.close()
|
||||
}
|
||||
|
||||
fun update() {
|
||||
updateName()
|
||||
updateSkin()
|
||||
updateSkinProvider()
|
||||
}
|
||||
|
||||
private fun updateName() {
|
||||
gui.setSlot(
|
||||
10, GuiElementBuilder()
|
||||
.setItem(Items.OAK_SIGN)
|
||||
.setName(Component.literal(this.data.name))
|
||||
.setCallback(this::openRenameGui)
|
||||
)
|
||||
}
|
||||
|
||||
private fun updateSkin() {
|
||||
val builder = GuiElementBuilder()
|
||||
.setItem(Items.PLAYER_HEAD)
|
||||
.setCallback(this::openSkinGui)
|
||||
|
||||
if (MinionItem.getData(viewer.level().server, minionItem)?.skin?.isPresent ?: false) {
|
||||
builder.setComponent(
|
||||
DataComponents.PROFILE,
|
||||
ResolvableProfile.createResolved(GameProfile(FakePlayer.DEFAULT_UUID, "", this.data.skin.get()))
|
||||
)
|
||||
}
|
||||
|
||||
gui.setSlot(16, builder)
|
||||
}
|
||||
|
||||
private fun updateSkinProvider() {
|
||||
gui.setSlot(
|
||||
25, GuiElementBuilder()
|
||||
.setItem(Items.GREEN_STAINED_GLASS_PANE)
|
||||
.setComponent(DataComponents.CUSTOM_NAME, currentSkinProvider.getDisplayName())
|
||||
.setCallback(Runnable { this.cycleSkinProvider() })
|
||||
)
|
||||
}
|
||||
|
||||
fun openSkinGui() {
|
||||
scope.launch {
|
||||
val profile = currentSkinProvider.openSkinMenu(this@MinionLookGui).await()
|
||||
val skin = profile?.resolveProfile(viewer.level().server.services().profileResolver())?.await()
|
||||
|
||||
data.skin = Optional.ofNullable(skin?.properties())
|
||||
|
||||
updateSkin()
|
||||
}
|
||||
}
|
||||
|
||||
private fun cycleSkinProvider() {
|
||||
var currentId = MinionRegistries.SKIN_PROVIDERS.getId(currentSkinProvider)
|
||||
currentId++
|
||||
if (MinionRegistries.SKIN_PROVIDERS.size() == currentId) {
|
||||
currentId = 0
|
||||
}
|
||||
|
||||
currentSkinProvider = MinionRegistries.SKIN_PROVIDERS.byId(currentId)!!
|
||||
updateSkinProvider()
|
||||
}
|
||||
|
||||
fun openRenameGui() {
|
||||
scope.launch {
|
||||
val newName = TextInput.input(
|
||||
this@MinionLookGui,
|
||||
Component.translatable("minions.gui.look.rename.title"),
|
||||
"Minion",
|
||||
) { name ->
|
||||
MinionProfileUtils.checkMinionNameWithoutPrefix(viewer.level().server, name)
|
||||
}.await()
|
||||
|
||||
if(newName != null) {
|
||||
data.name = newName
|
||||
updateName()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package io.github.skippyall.minions.gui
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder
|
||||
import kotlinx.coroutines.CompletableJob
|
||||
import kotlinx.coroutines.CoroutineName
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.cancel
|
||||
import net.minecraft.network.chat.Component
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
import net.minecraft.world.item.Items
|
||||
|
||||
abstract class MinionsGui {
|
||||
protected val parent: MinionsGui?
|
||||
@JvmField
|
||||
val viewer: ServerPlayer
|
||||
protected var child: MinionsGui? = null
|
||||
private var open = true
|
||||
|
||||
private val job: CompletableJob
|
||||
val scope: CoroutineScope
|
||||
|
||||
constructor(parent: MinionsGui) {
|
||||
this.viewer = parent.viewer
|
||||
this.parent = parent
|
||||
parent.child = this
|
||||
job = Job(parent.job)
|
||||
scope = CoroutineScope(Dispatchers.Unconfined.plus(CoroutineName("MinionsGui")).plus(job))
|
||||
}
|
||||
|
||||
constructor(viewer: ServerPlayer) {
|
||||
this.viewer = viewer
|
||||
this.parent = null
|
||||
job = Job(null)
|
||||
scope = CoroutineScope(Dispatchers.Unconfined.plus(CoroutineName("MinionsGui")).plus(job))
|
||||
}
|
||||
|
||||
protected abstract fun open()
|
||||
|
||||
protected open fun reopen() {
|
||||
open()
|
||||
}
|
||||
|
||||
fun onBackingClosed() {
|
||||
if (child != null && child!!.open) {
|
||||
return
|
||||
}
|
||||
|
||||
close(true)
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
fun close(alreadyClosed: Boolean = false) {
|
||||
if (open) {
|
||||
scope.cancel(null)
|
||||
open = false
|
||||
if (child != null) {
|
||||
child!!.close(alreadyClosed)
|
||||
} else if (!alreadyClosed) {
|
||||
closeBacking()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun goBack() {
|
||||
if (parent != null) {
|
||||
open = false
|
||||
parent.child = null
|
||||
parent.reopen()
|
||||
close(true)
|
||||
} else {
|
||||
close(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun backButton(): GuiElementBuilder? {
|
||||
return GuiElementBuilder(Items.MANGROVE_DOOR)
|
||||
.setName(Component.translatable("gui.back"))
|
||||
.setCallback(Runnable { this.goBack() })
|
||||
}
|
||||
|
||||
protected abstract fun closeBacking()
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
package io.github.skippyall.minions.gui;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import net.minecraft.core.IdMap;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.inventory.MenuType;
|
||||
import net.minecraft.world.item.Items;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class PaginatedList extends MinionsGui {
|
||||
private int page = 0;
|
||||
private SimpleGui gui;
|
||||
private final Component title;
|
||||
private final int size;
|
||||
private final BiFunction<Integer, PaginatedList, GuiElementBuilder> display;
|
||||
private @Nullable Runnable onClose = null;
|
||||
|
||||
public PaginatedList(MinionsGui parent, Component title, int size, BiFunction<Integer, PaginatedList, GuiElementBuilder> display) {
|
||||
super(parent);
|
||||
this.title = title;
|
||||
this.size = size;
|
||||
this.display = display;
|
||||
open();
|
||||
}
|
||||
|
||||
public PaginatedList(MinionsGui parent, Component title, int size, BiFunction<Integer, PaginatedList, GuiElementBuilder> display, Runnable onClose) {
|
||||
this(parent, title, size, display);
|
||||
this.onClose = onClose;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void open() {
|
||||
gui = new SimpleGui(MenuType.GENERIC_9x6, viewer, false) {
|
||||
@Override
|
||||
public void onPlayerClose(boolean success) {
|
||||
onBackingClosed();
|
||||
if(onClose != null) {
|
||||
onClose.run();
|
||||
}
|
||||
}
|
||||
};
|
||||
gui.setTitle(title);
|
||||
|
||||
gui.setSlot(8, backButton());
|
||||
addItems();
|
||||
gui.open();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void closeBacking() {
|
||||
gui.close();
|
||||
}
|
||||
|
||||
public static <T> void createList(MinionsGui parent, Component title, List<T> list, BiFunction<T, PaginatedList, GuiElementBuilder> display) {
|
||||
new PaginatedList(parent, title, list.size(), (i, gui) -> display.apply(list.get(i), gui));
|
||||
}
|
||||
|
||||
public static <T> void createList(MinionsGui parent, Component title, IdMap<T> list, BiFunction<T, PaginatedList, GuiElementBuilder> display) {
|
||||
new PaginatedList(parent, title, list.size(), (i, gui) -> display.apply(list.byId(i), gui));
|
||||
}
|
||||
|
||||
public static <T> CompletableFuture<T> createListFuture(MinionsGui parent, Component title, List<T> list, Function<T, GuiElementBuilder> display) {
|
||||
CompletableFuture<T> future = new CompletableFuture<>();
|
||||
new PaginatedList(parent, title, list.size(), (i, me) -> display.apply(list.get(i))
|
||||
.setCallback(() -> {
|
||||
future.complete(list.get(i));
|
||||
me.goBack();
|
||||
})
|
||||
);
|
||||
return future;
|
||||
}
|
||||
|
||||
private void addItems() {
|
||||
int slot = 9;
|
||||
for(int i = 36 * page; i < Math.min(36 * (page + 1), size); i++) {
|
||||
gui.setSlot(slot, display.apply(i, this));
|
||||
slot++;
|
||||
}
|
||||
|
||||
if(page > 0) {
|
||||
gui.setSlot(48, new GuiElementBuilder(Items.SPECTRAL_ARROW)
|
||||
.setItemName(Component.translatable("book.page_button.previous"))
|
||||
.setCallback(() -> {
|
||||
page--;
|
||||
addItems();
|
||||
})
|
||||
);
|
||||
} else {
|
||||
gui.clearSlot(48);
|
||||
}
|
||||
|
||||
if(27 * (page + 1) < size) {
|
||||
gui.setSlot(50, new GuiElementBuilder(Items.ARROW)
|
||||
.setItemName(Component.translatable("book.page_button.next"))
|
||||
.setCallback(() -> {
|
||||
page++;
|
||||
addItems();
|
||||
})
|
||||
);
|
||||
} else {
|
||||
gui.clearSlot(50);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package io.github.skippyall.minions.gui.input
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder
|
||||
import eu.pb4.sgui.api.gui.SimpleGui
|
||||
import io.github.skippyall.minions.gui.MinionsGui
|
||||
import io.github.skippyall.minions.gui.minion.SimpleMinionsGui
|
||||
import net.minecraft.network.chat.Component
|
||||
import net.minecraft.world.inventory.MenuType
|
||||
import net.minecraft.world.item.Items
|
||||
import java.util.concurrent.CompletableFuture
|
||||
|
||||
object BooleanInput {
|
||||
@JvmStatic
|
||||
@JvmOverloads
|
||||
fun confirm(
|
||||
parent: MinionsGui,
|
||||
title: Component,
|
||||
falseText: Component = Component.translatable("minions.gui.abort"),
|
||||
trueText: Component = Component.translatable("minions.gui.confirm")
|
||||
): CompletableFuture<Boolean> {
|
||||
val future = CompletableFuture<Boolean>()
|
||||
|
||||
SimpleMinionsGui(parent) { onClose: Runnable, me: SimpleMinionsGui ->
|
||||
val gui: SimpleGui = object : SimpleGui(MenuType.GENERIC_3x3, parent.viewer, false) {
|
||||
override fun onPlayerClose(success: Boolean) {
|
||||
future.complete(false)
|
||||
onClose.run()
|
||||
}
|
||||
}
|
||||
gui.setTitle(title)
|
||||
|
||||
gui.setSlot(
|
||||
3, GuiElementBuilder(Items.REDSTONE_BLOCK)
|
||||
.setName(falseText)
|
||||
.setCallback(Runnable {
|
||||
future.complete(false)
|
||||
me.goBack()
|
||||
})
|
||||
)
|
||||
|
||||
gui.setSlot(
|
||||
5, GuiElementBuilder(Items.EMERALD_BLOCK)
|
||||
.setName(trueText)
|
||||
.setCallback(Runnable {
|
||||
future.complete(true)
|
||||
me.goBack()
|
||||
})
|
||||
)
|
||||
|
||||
gui.open()
|
||||
gui
|
||||
}
|
||||
return future
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package io.github.skippyall.minions.gui.input;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import io.github.skippyall.minions.gui.Displayable;
|
||||
import io.github.skippyall.minions.gui.GuiDisplay;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class ChoiceInput {
|
||||
public static <T> BiFunction<ServerPlayerEntity, T, CompletableFuture<T>> createDialogOpener(ScreenHandlerType<?> screen, Text title, Function<T, GuiDisplay> displayFunction, T[] values, @Nullable T fallback) {
|
||||
return (player, object) -> {
|
||||
CompletableFuture<T> future = new CompletableFuture<>();
|
||||
|
||||
SimpleGui gui = new SimpleGui(screen, player, false) {
|
||||
@Override
|
||||
public void onClose() {
|
||||
if(fallback == null) {
|
||||
future.cancel(false);
|
||||
} else {
|
||||
future.complete(fallback);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
gui.setTitle(title);
|
||||
|
||||
for(T value : values) {
|
||||
gui.addSlot(new GuiElementBuilder(displayFunction.apply(value).createItemStack())
|
||||
.setCallback(() -> future.complete(value))
|
||||
);
|
||||
}
|
||||
gui.open();
|
||||
return future;
|
||||
};
|
||||
}
|
||||
|
||||
public static <T extends Displayable> BiFunction<ServerPlayerEntity, T, CompletableFuture<T>> createDialogOpener(T[] values) {
|
||||
return createDialogOpener(ScreenHandlerType.GENERIC_9X3, Text.empty(), t -> t != null ? t.getDisplay() : null, values, null);
|
||||
}
|
||||
|
||||
public static CompletableFuture<Void> confirm(ServerPlayerEntity player, Text title) {
|
||||
CompletableFuture<Void> future = new CompletableFuture<>();
|
||||
|
||||
SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_3X3, player, false) {
|
||||
@Override
|
||||
public void onClose() {
|
||||
future.cancel(false);
|
||||
}
|
||||
};
|
||||
|
||||
gui.setTitle(title);
|
||||
|
||||
gui.setSlot(3, new GuiElementBuilder(Items.REDSTONE_BLOCK)
|
||||
.setName(Text.translatable("minions.gui.abort"))
|
||||
.setCallback(() -> future.cancel(false))
|
||||
);
|
||||
|
||||
gui.setSlot(5, new GuiElementBuilder(Items.EMERALD_BLOCK)
|
||||
.setName(Text.translatable("minions.gui.confirm"))
|
||||
.setCallback(() -> future.complete(null))
|
||||
);
|
||||
|
||||
gui.open();
|
||||
return future;
|
||||
}
|
||||
|
||||
public static BiFunction<ServerPlayerEntity, Boolean, CompletableFuture<Boolean>> inputBoolean(Text title) {
|
||||
return createDialogOpener(ScreenHandlerType.GENERIC_3X3, title, value -> {
|
||||
if(value) {
|
||||
return new GuiDisplay.ItemBased(Items.EMERALD_BLOCK);
|
||||
} else {
|
||||
return new GuiDisplay.ItemBased(Items.REDSTONE_BLOCK);
|
||||
}
|
||||
}, new Boolean[]{false, true}, false);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,12 @@
|
||||
package io.github.skippyall.minions.gui.input;
|
||||
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public sealed interface Result<T, E> permits Result.Success, Result.Error {
|
||||
public interface Result<T, E> {
|
||||
static <T> Result<T, String> wrap(UnsafeOperation<T> toWrap) {
|
||||
return wrapCustomError(toWrap, Exception::getMessage);
|
||||
}
|
||||
@@ -24,157 +23,92 @@ public sealed interface Result<T, E> permits Result.Success, Result.Error {
|
||||
}
|
||||
}
|
||||
|
||||
static <T, E> Result<T, E> ofNullable(@Nullable T value, E error) {
|
||||
if(value != null) {
|
||||
return new Success<T, E>(value);
|
||||
} else {
|
||||
return new Error<>(error);
|
||||
}
|
||||
}
|
||||
|
||||
static <T, E> Result<T, E> ofNullable(@Nullable T value, Supplier<E> error) {
|
||||
if(value != null) {
|
||||
return new Success<T, E>(value);
|
||||
} else {
|
||||
return new Error<>(error.get());
|
||||
}
|
||||
}
|
||||
|
||||
boolean isSuccess();
|
||||
|
||||
T getOrDefault(T defaultValue);
|
||||
@NotNull T getOrDefault(@NotNull T defaultValue);
|
||||
|
||||
T getOrThrow();
|
||||
@NotNull T getOrThrow();
|
||||
|
||||
E getErrorOrThrow();
|
||||
@NotNull E getErrorOrThrow();
|
||||
|
||||
Optional<T> getOptional();
|
||||
@NotNull Optional<T> getOptional();
|
||||
|
||||
Optional<E> getOptionalError();
|
||||
void ifSuccess(@NotNull Consumer<T> handler);
|
||||
|
||||
void ifSuccess(Consumer<T> handler);
|
||||
void ifError(@NotNull Consumer<Error<T, E>> handler);
|
||||
|
||||
void ifError(Consumer<Error<T, E>> handler);
|
||||
|
||||
<U> Result<U,E> map(Function<T, U> mapper);
|
||||
|
||||
<U> Result<U,E> flatMap(Function<T, Result<U, E>> mapper);
|
||||
|
||||
<U> Result<T,U> mapError(Function<E, U> mapper);
|
||||
|
||||
record Success<T, E>(T result) implements Result<T, E> {
|
||||
record Success<T, E>(@NotNull T result) implements Result<T, E> {
|
||||
@Override
|
||||
public boolean isSuccess() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getOrDefault(T defaultValue) {
|
||||
public @NotNull T getOrDefault(@NotNull T defaultValue) {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<E> getOptionalError() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getOrThrow() {
|
||||
public @NotNull T getOrThrow() {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public E getErrorOrThrow() {
|
||||
public @NotNull E getErrorOrThrow() {
|
||||
throw new RuntimeException("Result was not an Error");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<T> getOptional() {
|
||||
return Optional.ofNullable(result);
|
||||
public @NotNull Optional<T> getOptional() {
|
||||
return Optional.of(result);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ifSuccess(Consumer<T> handler) {
|
||||
public void ifSuccess(@NotNull Consumer<T> handler) {
|
||||
handler.accept(result);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ifError(Consumer<Error<T, E>> handler) {
|
||||
public void ifError(@NotNull Consumer<Error<T, E>> handler) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public <U> Result<U, E> map(Function<T, U> mapper) {
|
||||
return new Success<>(mapper.apply(result));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <U> Result<U, E> flatMap(Function<T, Result<U, E>> mapper) {
|
||||
return mapper.apply(result);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <U> Result<T, U> mapError(Function<E, U> mapper) {
|
||||
return new Success<>(result);
|
||||
}
|
||||
}
|
||||
|
||||
record Error<T, E>(E message) implements Result<T, E> {
|
||||
record Error<T, E>(@NotNull E message) implements Result<T, E> {
|
||||
@Override
|
||||
public boolean isSuccess() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getOrDefault(
|
||||
T defaultValue) {
|
||||
public @NotNull T getOrDefault(@NotNull T defaultValue) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getOrThrow() {
|
||||
public @NotNull T getOrThrow() {
|
||||
throw new RuntimeException("Result was an error: " + message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public E getErrorOrThrow() {
|
||||
public @NotNull E getErrorOrThrow() {
|
||||
return message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<T> getOptional() {
|
||||
public @NotNull Optional<T> getOptional() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<E> getOptionalError() {
|
||||
return Optional.ofNullable(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ifSuccess(Consumer<T> handler) {
|
||||
public void ifSuccess(@NotNull Consumer<T> handler) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ifError(Consumer<Error<T, E>> handler) {
|
||||
public void ifError(@NotNull Consumer<Error<T, E>> handler) {
|
||||
handler.accept(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <U> Result<U, E> map(Function<T, U> mapper) {
|
||||
return new Error<>(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <U> Result<U, E> flatMap(Function<T, Result<U, E>> mapper) {
|
||||
return new Error<>(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <U> Result<T, U> mapError(Function<E, U> mapper) {
|
||||
return new Error<>(mapper.apply(message));
|
||||
}
|
||||
}
|
||||
|
||||
interface UnsafeOperation<T> {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package io.github.skippyall.minions.gui.input;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import eu.pb4.sgui.api.gui.AnvilInputGui;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.screen.AnvilScreenHandler;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class TextInput<T> extends AnvilInputGui {
|
||||
private final GuiElementBuilder valid = new GuiElementBuilder()
|
||||
.setItem(Items.EMERALD_BLOCK)
|
||||
.setName(Text.literal("OK"))
|
||||
.setCallback(this::onConfirm);
|
||||
|
||||
private final GuiElementBuilder invalid = new GuiElementBuilder()
|
||||
.setItem(Items.REDSTONE_BLOCK);
|
||||
private final Function<String, CompletableFuture<Result<T, Text>>> parser;
|
||||
private final CompletableFuture<T> future;
|
||||
private Result<T, Text> result;
|
||||
private boolean isConfirm;
|
||||
|
||||
public TextInput(ServerPlayerEntity player, Text title, String defaultValue, Function<String, CompletableFuture<Result<T, Text>>> parser, CompletableFuture<T> future) {
|
||||
super(player, false);
|
||||
setTitle(title);
|
||||
setDefaultInputValue(defaultValue);
|
||||
this.parser = parser;
|
||||
this.future = future;
|
||||
|
||||
updateConfirmButton(defaultValue);
|
||||
}
|
||||
|
||||
public static <T> CompletableFuture<T> inputSync(ServerPlayerEntity player, Text title, String defaultValue, Function<String, Result<T, Text>> parser) {
|
||||
return input(player, title, defaultValue, (String string) -> CompletableFuture.completedFuture(parser.apply(string)));
|
||||
}
|
||||
|
||||
public static <T> CompletableFuture<T> input(ServerPlayerEntity player, Text title, String defaultValue, Function<String, CompletableFuture<Result<T, Text>>> parser) {
|
||||
CompletableFuture<T> future = new CompletableFuture<>();
|
||||
new TextInput<>(player, title, defaultValue, parser, future).open();
|
||||
return future;
|
||||
}
|
||||
|
||||
public static CompletableFuture<String> inputString(ServerPlayerEntity player, Text title, String defaultValue) {
|
||||
return inputSync(player, title, defaultValue, Result.Success::new);
|
||||
}
|
||||
|
||||
public static CompletableFuture<Long> inputLong(ServerPlayerEntity player, Text title, String defaultValue) {
|
||||
return inputSync(player, title, defaultValue, string -> Result.wrapCustomError(() -> Long.valueOf(string), Text.translatable("minions.command.input.int.fail")));
|
||||
}
|
||||
|
||||
public static CompletableFuture<Double> inputDouble(ServerPlayerEntity player, Text title, String defaultValue) {
|
||||
return inputSync(player, title, defaultValue, string -> Result.wrapCustomError(() -> Double.valueOf(string), Text.translatable("minions.command.input.float.fail")));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInput(String input) {
|
||||
updateConfirmButton(input);
|
||||
}
|
||||
|
||||
public void updateConfirmButton(String input) {
|
||||
parser.apply(input).thenAccept(result -> {
|
||||
this.result = result;
|
||||
if(result.isSuccess()) {
|
||||
setSlot(AnvilScreenHandler.OUTPUT_ID, valid);
|
||||
} else {
|
||||
Text text = result.getErrorOrThrow();
|
||||
setSlot(AnvilScreenHandler.OUTPUT_ID, invalid.setName(text));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose() {
|
||||
if(!future.isDone() && !isConfirm) {
|
||||
future.cancel(false);
|
||||
}
|
||||
}
|
||||
|
||||
public void onConfirm() {
|
||||
if(result != null) {
|
||||
result.ifSuccess(success -> {
|
||||
isConfirm = true;
|
||||
close();
|
||||
future.complete(success);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
package io.github.skippyall.minions.gui.input
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder
|
||||
import eu.pb4.sgui.api.gui.AnvilInputGui
|
||||
import io.github.skippyall.minions.gui.MinionsGui
|
||||
import kotlinx.coroutines.launch
|
||||
import net.minecraft.network.chat.Component
|
||||
import net.minecraft.world.inventory.AnvilMenu
|
||||
import net.minecraft.world.item.Items
|
||||
import java.util.concurrent.CompletableFuture
|
||||
|
||||
class TextInput<T : Any>(
|
||||
parent: MinionsGui,
|
||||
val title: Component,
|
||||
val defaultValue: String,
|
||||
val parser: suspend (String) -> Result<T, Component>
|
||||
) : MinionsGui(parent) {
|
||||
private val valid: GuiElementBuilder = GuiElementBuilder()
|
||||
.setItem(Items.EMERALD_BLOCK)
|
||||
.setName(Component.literal("OK"))
|
||||
.setCallback(Runnable { this.onConfirm() })
|
||||
|
||||
private val invalid: GuiElementBuilder = GuiElementBuilder()
|
||||
.setItem(Items.REDSTONE_BLOCK)
|
||||
|
||||
private lateinit var gui: AnvilInputGui
|
||||
|
||||
private var result: Result<T, Component>? = null
|
||||
val future = CompletableFuture<T?>()
|
||||
|
||||
init {
|
||||
open()
|
||||
}
|
||||
|
||||
override fun open() {
|
||||
gui = object : AnvilInputGui(viewer, false) {
|
||||
override fun onInput(input: String) {
|
||||
updateConfirmButton(input)
|
||||
}
|
||||
|
||||
override fun onPlayerClose(success: Boolean) {
|
||||
onBackingClosed()
|
||||
if (!future.isDone) {
|
||||
future.complete(null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
gui.setTitle(title)
|
||||
gui.setDefaultInputValue(defaultValue)
|
||||
updateConfirmButton(defaultValue)
|
||||
gui.open()
|
||||
}
|
||||
|
||||
override fun closeBacking() {
|
||||
gui.close()
|
||||
}
|
||||
|
||||
fun updateConfirmButton(input: String) {
|
||||
scope.launch {
|
||||
val result = parser(input)
|
||||
this@TextInput.result = result
|
||||
if (result.isSuccess()) {
|
||||
gui.setSlot(AnvilMenu.RESULT_SLOT, valid)
|
||||
} else {
|
||||
val text = result.getErrorOrThrow()
|
||||
gui.setSlot(AnvilMenu.RESULT_SLOT, invalid.setName(text))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onConfirm() {
|
||||
result?.ifSuccess { success: T ->
|
||||
future.complete(success)
|
||||
goBack()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun <T : Any>input(
|
||||
gui: MinionsGui,
|
||||
title: Component,
|
||||
defaultValue: String,
|
||||
parser: suspend (String) -> Result<T, Component>,
|
||||
): CompletableFuture<T?> {
|
||||
val input = TextInput(
|
||||
parent = gui,
|
||||
title = title,
|
||||
defaultValue = defaultValue,
|
||||
parser = parser,
|
||||
)
|
||||
|
||||
return input.future
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun inputString(
|
||||
gui: MinionsGui,
|
||||
title: Component,
|
||||
defaultValue: String,
|
||||
): CompletableFuture<String?> {
|
||||
return input<String>(
|
||||
gui = gui,
|
||||
title = title,
|
||||
defaultValue = defaultValue,
|
||||
parser = { result -> Result.Success(result) },
|
||||
)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun inputLong(
|
||||
gui: MinionsGui,
|
||||
title: Component,
|
||||
defaultValue: Long,
|
||||
): CompletableFuture<Long?> {
|
||||
return input<Long>(
|
||||
gui = gui,
|
||||
title = title,
|
||||
defaultValue = defaultValue.toString(),
|
||||
parser = { string ->
|
||||
Result.wrapCustomError<Long, Component>(
|
||||
{ string.toLong() },
|
||||
Component.translatable("value_type.minions.long.not_long")
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun inputDouble(
|
||||
gui: MinionsGui,
|
||||
title: Component,
|
||||
defaultValue: Double,
|
||||
): CompletableFuture<Double?> {
|
||||
return input<Double>(
|
||||
gui = gui,
|
||||
title = title,
|
||||
defaultValue = defaultValue.toString(),
|
||||
parser = { string ->
|
||||
Result.wrapCustomError<Double, Component>(
|
||||
{ string.toDouble() },
|
||||
Component.translatable("value_type.minions.long.not_long")
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
@NullMarked
|
||||
package io.github.skippyall.minions.gui.input;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
@@ -1,154 +0,0 @@
|
||||
package io.github.skippyall.minions.gui.instruction;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import io.github.skippyall.minions.gui.GuiDisplay;
|
||||
import io.github.skippyall.minions.gui.MinionsGui;
|
||||
import io.github.skippyall.minions.gui.PaginatedList;
|
||||
import io.github.skippyall.minions.gui.minion.GuiContext;
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import io.github.skippyall.minions.program.supplier.Parameter;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplier;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierList;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierType;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import io.github.skippyall.minions.util.TranslationUtil;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.inventory.MenuType;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
public class ArgumentGui extends MinionsGui {
|
||||
private final GuiContext.ValueSupplier context;
|
||||
private final ConfiguredInstruction<MinionRuntime> instruction;
|
||||
private final Parameter<?> parameter;
|
||||
|
||||
private SimpleGui gui;
|
||||
|
||||
private @Nullable ValueSupplierType<MinionRuntime> argumentType;
|
||||
private ValueSupplierList. @Nullable ValueSupplierEntry<?, MinionRuntime> entry;
|
||||
|
||||
public ArgumentGui(MinionsGui parent, GuiContext.ValueSupplier context) {
|
||||
super(parent);
|
||||
instruction = context.getInstruction();
|
||||
this.parameter = context.getParameter();
|
||||
this.context = context;
|
||||
|
||||
this.entry = instruction.getArguments().getEntry(parameter);
|
||||
this.argumentType = entry.getSupplier().getType();
|
||||
open();
|
||||
}
|
||||
|
||||
public String getInstructionName() {
|
||||
return context.getName();
|
||||
}
|
||||
|
||||
public @Nullable ValueSupplier<?, MinionRuntime> getArgument() {
|
||||
if(entry != null) {
|
||||
return entry.getSupplier();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void open() {
|
||||
gui = new SimpleGui(MenuType.GENERIC_3x3, viewer, false) {
|
||||
@Override
|
||||
public void onPlayerClose(boolean success) {
|
||||
onBackingClosed();
|
||||
}
|
||||
};
|
||||
gui.setTitle(Component.translatable(
|
||||
"minions.gui.instruction.argument.title",
|
||||
parameter.name(),
|
||||
Component.translatable(TranslationUtil.getTranslationKey(parameter.type(), MinionRegistries.VALUE_TYPES))
|
||||
));
|
||||
|
||||
gui.setSlot(2, backButton());
|
||||
|
||||
updateTypeConfiguration();
|
||||
updateArgumentConfiguration();
|
||||
updateConverterConfiguration();
|
||||
gui.open();
|
||||
}
|
||||
|
||||
private void updateTypeConfiguration() {
|
||||
ItemStack displayStack;
|
||||
if(argumentType != null) {
|
||||
displayStack = GuiDisplay.getDisplayStack(MinionRegistries.VALUE_SUPPLIER_TYPES, argumentType, viewer.registryAccess());
|
||||
} else {
|
||||
displayStack = new ItemStack(Items.BARRIER);
|
||||
}
|
||||
|
||||
gui.setSlot(3, new GuiElementBuilder(displayStack)
|
||||
.setName(Component.translatable("minions.gui.instruction.argument.configure.type"))
|
||||
.addLoreLine(Component.translatable(TranslationUtil.getTranslationKey(
|
||||
argumentType,
|
||||
MinionRegistries.VALUE_SUPPLIER_TYPES,
|
||||
"minions.gui.not_set"
|
||||
)))
|
||||
.setCallback(this::selectArgumentType)
|
||||
);
|
||||
}
|
||||
|
||||
private void updateArgumentConfiguration() {
|
||||
if(argumentType != null) {
|
||||
gui.setSlot(4, new GuiElementBuilder(Items.STRUCTURE_VOID)
|
||||
.setName(Component.translatable("minions.gui.instruction.argument.configure.data"))
|
||||
.addLoreLine(getArgument() != null ? getArgument().getDisplayText() : Component.translatable("minions.gui.not_set"))
|
||||
.setCallback(() -> argumentType.openConfiguration(this, parameter.type(), getArgument())
|
||||
.thenAccept(this::setArgument)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateConverterConfiguration() {
|
||||
if(entry != null) {
|
||||
gui.setSlot(5, new GuiElementBuilder(Items.CRAFTER)
|
||||
.setName(Component.translatable("minions.gui.instruction.converters"))
|
||||
.setCallback(this::configureConvertersMenu)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void closeBacking() {
|
||||
gui.close();
|
||||
}
|
||||
|
||||
public void setArgumentType(ValueSupplierType<MinionRuntime> type) {
|
||||
this.argumentType = type;
|
||||
if(entry != null && getArgument().getType() != argumentType) {
|
||||
instruction.getArguments().removeEntry(parameter);
|
||||
entry = null;
|
||||
}
|
||||
updateTypeConfiguration();
|
||||
}
|
||||
|
||||
public void setArgument(ValueSupplier<?, MinionRuntime> argument) {
|
||||
if(entry != null) {
|
||||
entry.setSupplier(argument);
|
||||
} else {
|
||||
entry = instruction.getArguments().createEntry(parameter, argument);
|
||||
}
|
||||
}
|
||||
|
||||
public void selectArgumentType() {
|
||||
PaginatedList.createList(this, Component.translatable("minions.gui.instruction.argument.configure.type.title"), MinionRegistries.VALUE_SUPPLIER_TYPES, (type, me) ->
|
||||
new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.VALUE_SUPPLIER_TYPES, type, viewer.registryAccess()))
|
||||
.setCallback(() -> {
|
||||
setArgumentType(type);
|
||||
me.goBack();
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
public void configureConvertersMenu() {
|
||||
if(entry != null) {
|
||||
new ConverterListGui(this, entry.getConverters(), entry.getSupplier().getValueType(), entry.getParameter().type());
|
||||
}
|
||||
}
|
||||
}
|
||||
-172
@@ -1,172 +0,0 @@
|
||||
package io.github.skippyall.minions.gui.instruction;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import io.github.skippyall.minions.clipboard.ClipboardItem;
|
||||
import io.github.skippyall.minions.gui.MinionsGui;
|
||||
import io.github.skippyall.minions.gui.input.BooleanInput;
|
||||
import io.github.skippyall.minions.gui.minion.GuiContext;
|
||||
import io.github.skippyall.minions.minion.MinionListener;
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstructionListener;
|
||||
import io.github.skippyall.minions.program.supplier.Parameter;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket;
|
||||
import net.minecraft.sounds.SoundEvents;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.world.inventory.MenuType;
|
||||
import net.minecraft.world.item.Items;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ConfigureInstructionGui extends MinionsGui implements ConfiguredInstructionListener, MinionListener {
|
||||
private String name;
|
||||
private final ConfiguredInstruction<MinionRuntime> instruction;
|
||||
private final MinionFakePlayer minion;
|
||||
|
||||
private final GuiContext.Instruction context;
|
||||
|
||||
private SimpleGui gui;
|
||||
|
||||
public ConfigureInstructionGui(MinionsGui parent, GuiContext.Instruction context) {
|
||||
super(parent);
|
||||
this.name = context.getName();
|
||||
this.instruction = context.getInstruction();
|
||||
this.minion = context.getMinion();
|
||||
this.context = context;
|
||||
minion.addMinionListener(this);
|
||||
instruction.addListener(this);
|
||||
open();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void open() {
|
||||
gui = new SimpleGui(MenuType.GENERIC_9x3, viewer, false) {
|
||||
@Override
|
||||
public void onPlayerClose(boolean success) {
|
||||
onBackingClosed();
|
||||
}
|
||||
};
|
||||
|
||||
gui.setTitle(Component.literal(name));
|
||||
|
||||
gui.setSlot(6, new GuiElementBuilder(Items.ANVIL)
|
||||
.setName(Component.translatable("minions.gui.instruction.configure.rename"))
|
||||
.setCallback(() -> InstructionGui.inputInstructionName(this, context, name).thenAccept(newName -> {
|
||||
if(newName != null) {
|
||||
minion.getInstructionManager().setInstructionName(name, newName);
|
||||
}
|
||||
reopen();
|
||||
}))
|
||||
);
|
||||
|
||||
gui.setSlot(7, new GuiElementBuilder(Items.LAVA_BUCKET)
|
||||
.setName(Component.translatable("minions.gui.instruction.configure.delete"))
|
||||
.setCallback(() -> BooleanInput.confirm(this, Component.translatable("minions.gui.instruction.configure.delete.confirm", name))
|
||||
.thenAccept((confirmed) -> {
|
||||
if(confirmed) {
|
||||
minion.getInstructionManager().removeInstruction(name);
|
||||
goBack();
|
||||
}
|
||||
}))
|
||||
);
|
||||
|
||||
gui.setSlot(8, backButton());
|
||||
|
||||
updateSuppliers();
|
||||
|
||||
gui.setSlot(13, InstructionGui.createInstructionElement(instruction.getInstruction(), viewer.registryAccess()));
|
||||
|
||||
gui.setSlot(25, new GuiElementBuilder(Items.FEATHER)
|
||||
.setName(Component.translatable("minions.gui.instruction.configure.copy"))
|
||||
.addLoreLine(Component.translatable("minions.gui.instruction.configure.copy.description"))
|
||||
.setCallback(() -> {
|
||||
viewer.getInventory().placeItemBackInInventory(ClipboardItem.createInstructionReference(minion, name), true);
|
||||
viewer.connection.send(new ClientboundSoundEntityPacket(SoundEvents.NOTE_BLOCK_CHIME, SoundSource.BLOCKS, viewer, 1, 1, 0));
|
||||
})
|
||||
);
|
||||
|
||||
updateLastError();
|
||||
updateRunSlot();
|
||||
gui.open();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void closeBacking() {
|
||||
gui.close();
|
||||
minion.removeMinionListener(this);
|
||||
instruction.removeListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInstructionRename(MinionFakePlayer minion, ConfiguredInstruction<?> instruction, String oldName, String newName) {
|
||||
gui.setTitle(Component.literal(newName));
|
||||
name = newName;
|
||||
context.setName(newName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRun(ConfiguredInstruction<?> instruction) {
|
||||
updateRunSlot();
|
||||
updateLastError();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStop(ConfiguredInstruction<?> instruction) {
|
||||
updateRunSlot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSupplierChange(ConfiguredInstruction<?> instruction, Parameter<?> parameter) {
|
||||
updateSuppliers();
|
||||
}
|
||||
|
||||
private void updateRunSlot() {
|
||||
List<Component> errors = instruction.preCheck();
|
||||
if(errors.isEmpty()) {
|
||||
if (!instruction.isRunning()) {
|
||||
gui.setSlot(26, new GuiElementBuilder(Items.ARROW)
|
||||
.setName(Component.translatable("minions.gui.instruction.run"))
|
||||
.setCallback(() -> instruction.run(minion.getInstructionManager()))
|
||||
);
|
||||
} else {
|
||||
gui.setSlot(26, new GuiElementBuilder(Items.BARRIER)
|
||||
.setName(Component.translatable("minions.gui.instruction.stop"))
|
||||
.setCallback(() -> instruction.stop(minion.getInstructionManager()))
|
||||
);
|
||||
}
|
||||
} else {
|
||||
GuiElementBuilder builder = new GuiElementBuilder(Items.RED_WOOL)
|
||||
.setName(Component.translatable("minions.gui.instruction.errors"));
|
||||
for(Component error : errors) {
|
||||
builder.addLoreLine(error);
|
||||
}
|
||||
gui.setSlot(26, builder);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateLastError() {
|
||||
List<Component> errors = instruction.getLastErrors();
|
||||
if(!errors.isEmpty()) {
|
||||
GuiElementBuilder builder = new GuiElementBuilder(Items.RED_WOOL)
|
||||
.setName(Component.translatable("minions.gui.instruction.last_errors"));
|
||||
for(Component error : errors) {
|
||||
builder.addLoreLine(error);
|
||||
}
|
||||
gui.setSlot(17, builder);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateSuppliers() {
|
||||
int slot = 12;
|
||||
for(Parameter<?> parameter : instruction.getInstruction().getParameters().reversed()) {
|
||||
gui.setSlot(slot, InstructionGui.createParameterElement(parameter, instruction.getArguments().getArgument(parameter), viewer.registryAccess())
|
||||
.setCallback(() -> new ArgumentGui(this, GuiContext.ValueSupplier.create(context, parameter)))
|
||||
);
|
||||
slot--;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
package io.github.skippyall.minions.gui.instruction;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import io.github.skippyall.minions.gui.GuiDisplay;
|
||||
import io.github.skippyall.minions.gui.MinionsGui;
|
||||
import io.github.skippyall.minions.gui.PaginatedList;
|
||||
import io.github.skippyall.minions.program.conversion.ConverterList;
|
||||
import io.github.skippyall.minions.program.conversion.ValueConverter;
|
||||
import io.github.skippyall.minions.program.conversion.ValueConverterType;
|
||||
import io.github.skippyall.minions.program.value.ValueType;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.inventory.MenuType;
|
||||
import net.minecraft.world.item.Items;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
public class ConverterGui extends MinionsGui {
|
||||
private @Nullable ValueConverterType<?> valueConverterType;
|
||||
private @Nullable ValueConverter<?,?> converter;
|
||||
private ConverterList list;
|
||||
private ValueType<?> from, to;
|
||||
|
||||
private SimpleGui gui;
|
||||
private boolean isNew;
|
||||
private int index;
|
||||
|
||||
public ConverterGui(MinionsGui parent, @Nullable ValueConverter<?,?> converter, ValueType<?> from, ValueType<?> to, ConverterList list, boolean isNew, int index) {
|
||||
super(parent);
|
||||
this.converter = converter;
|
||||
if(converter != null) {
|
||||
this.valueConverterType = converter.getType();
|
||||
}
|
||||
this.from = from;
|
||||
this.to = to;
|
||||
this.list = list;
|
||||
this.isNew = isNew;
|
||||
this.index = index;
|
||||
|
||||
open();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void open() {
|
||||
gui = new SimpleGui(MenuType.GENERIC_3x3, viewer, false) {
|
||||
@Override
|
||||
public void onPlayerClose(boolean success) {
|
||||
onBackingClosed();
|
||||
}
|
||||
};
|
||||
|
||||
gui.setTitle(Component.translatable("minions.gui.instruction.converter.title"));
|
||||
|
||||
updateTypeDisplay();
|
||||
updateConverterDisplay();
|
||||
gui.setSlot(8, backButton());
|
||||
|
||||
gui.open();
|
||||
}
|
||||
|
||||
private void updateTypeDisplay() {
|
||||
gui.setSlot(3, new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.VALUE_CONVERTER_TYPES, valueConverterType, viewer.registryAccess()))
|
||||
.setCallback(this::configureType)
|
||||
);
|
||||
}
|
||||
|
||||
private void updateConverterDisplay() {
|
||||
gui.setSlot(5, new GuiElementBuilder(Items.STRUCTURE_VOID)
|
||||
.setName(Component.translatable("minions.gui.instruction.converter.title"))
|
||||
.addLoreLine(converter == null ? Component.translatable("minions.gui.not_set") : converter.getDisplayText())
|
||||
.setCallback(this::configureData)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void closeBacking() {
|
||||
gui.close();
|
||||
}
|
||||
|
||||
private void setType(ValueConverterType<?> valueConverterType) {
|
||||
this.valueConverterType = valueConverterType;
|
||||
updateTypeDisplay();
|
||||
}
|
||||
|
||||
public void setConverter(ValueConverter<?,?> converter) {
|
||||
this.converter = converter;
|
||||
if(isNew) {
|
||||
list.getConverters().add(index, converter);
|
||||
isNew = false;
|
||||
} else {
|
||||
list.getConverters().set(index, converter);
|
||||
}
|
||||
updateConverterDisplay();
|
||||
}
|
||||
|
||||
private void configureType() {
|
||||
PaginatedList.createList(
|
||||
this,
|
||||
Component.translatable("minions.gui.instruction.converter.type.title"),
|
||||
MinionRegistries.VALUE_CONVERTER_TYPES,
|
||||
(type, me) -> new GuiElementBuilder(
|
||||
GuiDisplay.getDisplayStackWithName(MinionRegistries.VALUE_CONVERTER_TYPES, type, viewer.registryAccess())
|
||||
).setCallback(() -> {
|
||||
setType(type);
|
||||
me.goBack();
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private void configureData() {
|
||||
if(valueConverterType != null) {
|
||||
valueConverterType.configure(this, from, to, converter)
|
||||
.thenAccept(this::setConverter);
|
||||
}
|
||||
}
|
||||
|
||||
public static GuiElementBuilder createConverterElement(ValueConverter<?,?> converter, RegistryAccess manager) {
|
||||
GuiElementBuilder builder = new GuiElementBuilder(GuiDisplay.getDisplayStack(MinionRegistries.VALUE_CONVERTER_TYPES, converter.getType(), manager));
|
||||
builder.addLoreLine(converter.getDisplayText());
|
||||
return builder;
|
||||
}
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
package io.github.skippyall.minions.gui.instruction;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import io.github.skippyall.minions.gui.GuiDisplay;
|
||||
import io.github.skippyall.minions.gui.MinionsGui;
|
||||
import io.github.skippyall.minions.program.conversion.ConverterList;
|
||||
import io.github.skippyall.minions.program.conversion.ValueConverter;
|
||||
import io.github.skippyall.minions.program.value.ValueType;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import io.github.skippyall.minions.util.TranslationUtil;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.inventory.MenuType;
|
||||
import net.minecraft.world.item.Items;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
public class ConverterListGui extends MinionsGui {
|
||||
private ConverterList converters;
|
||||
|
||||
private SimpleGui gui;
|
||||
private int page = 0;
|
||||
|
||||
private ValueType<?> inputType;
|
||||
private ValueType<?> outputType;
|
||||
|
||||
public ConverterListGui(MinionsGui parent, ConverterList converters, ValueType<?> inputType, ValueType<?> outputType) {
|
||||
super(parent);
|
||||
this.converters = converters;
|
||||
this.inputType = inputType;
|
||||
this.outputType = outputType;
|
||||
open();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void open() {
|
||||
gui = new SimpleGui(MenuType.GENERIC_9x3, viewer, false) {
|
||||
@Override
|
||||
public void onPlayerClose(boolean success) {
|
||||
onBackingClosed();
|
||||
}
|
||||
};
|
||||
|
||||
gui.setTitle(Component.translatable("minions.gui.instruction.converters"));
|
||||
|
||||
updateConverters();
|
||||
|
||||
gui.setSlot(21, new GuiElementBuilder(Items.SPECTRAL_ARROW)
|
||||
.setCallback(() -> {
|
||||
if(page > 0) {
|
||||
page--;
|
||||
updateConverters();
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
gui.setSlot(23, new GuiElementBuilder(Items.ARROW)
|
||||
.setCallback(() -> {
|
||||
if(page * 4 + 4 < converters.getConverters().size() + 1) {
|
||||
page++;
|
||||
updateConverters();
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
gui.setSlot(26, backButton());
|
||||
|
||||
gui.open();
|
||||
}
|
||||
|
||||
private ValueType<?> getInputTypeOfConverter(int converterIndex) {
|
||||
if(converterIndex < converters.getConverters().size() && converterIndex >= 0) {
|
||||
return converters.getConverters().get(converterIndex).getFrom();
|
||||
} else if(converterIndex == converters.getConverters().size()) {
|
||||
return outputType;
|
||||
} else {
|
||||
throw new IndexOutOfBoundsException("Can't get input type of converter " + converterIndex + ", list size " + converters.getConverters().size());
|
||||
}
|
||||
}
|
||||
|
||||
private ValueType<?> getOutputTypeOfConverter(int converterIndex) {
|
||||
if(converterIndex < converters.getConverters().size() && converterIndex >= 0) {
|
||||
return converters.getConverters().get(converterIndex).getTo();
|
||||
} else if(converterIndex == -1) {
|
||||
return inputType;
|
||||
} else {
|
||||
throw new IndexOutOfBoundsException("Can't get output type of converter " + converterIndex + ", list size " + converters.getConverters().size());
|
||||
}
|
||||
}
|
||||
|
||||
public void updateConverters() {
|
||||
for(int slot = 0; slot < 18; slot++) {
|
||||
gui.clearSlot(slot);
|
||||
}
|
||||
|
||||
int lastConverter = Math.min(5, converters.getConverters().size() + 2 - page * 4);
|
||||
for(int i = 0; i < lastConverter; i++) {
|
||||
//Each page has 5 converters, but the last is displayed on the next page as well
|
||||
//The input element index is -1, the output element index is the list size
|
||||
int converterIndex = page * 4 + i - 1;
|
||||
int slot = 9 + 2 * i;
|
||||
|
||||
if(converterIndex == converters.getConverters().size()) {
|
||||
gui.setSlot(slot, new GuiElementBuilder(Items.HOPPER));
|
||||
} else {
|
||||
ValueType<?> thisConverterOutput = getOutputTypeOfConverter(converterIndex);
|
||||
ValueType<?> nextConverterInput = getInputTypeOfConverter(converterIndex + 1);
|
||||
|
||||
//What should be shown at the converter's slot
|
||||
if (converterIndex == -1) {
|
||||
gui.setSlot(slot, new GuiElementBuilder(Items.DROPPER));
|
||||
} else {
|
||||
ValueType<?> previousConverterOutput = getOutputTypeOfConverter(converterIndex - 1);
|
||||
|
||||
ValueConverter<?, ?> converter = converters.getConverters().get(converterIndex);
|
||||
gui.setSlot(slot, createConverterDisplay(converter, previousConverterOutput, nextConverterInput, converterIndex));
|
||||
|
||||
GuiElementBuilder warning = createConverterWarning(converter);
|
||||
if (warning != null) {
|
||||
gui.setSlot(slot - 8, warning);
|
||||
}
|
||||
}
|
||||
|
||||
//show cast in the next slot
|
||||
if (i != 4 && converterIndex != converters.getConverters().size()) {
|
||||
gui.setSlot(slot + 1, createCastDisplay(thisConverterOutput, nextConverterInput, converterIndex + 1));
|
||||
|
||||
GuiElementBuilder warning = createCastWarning(thisConverterOutput, nextConverterInput);
|
||||
if (warning != null) {
|
||||
gui.setSlot(slot - 8, warning);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private GuiElementBuilder createConverterDisplay(ValueConverter<?, ?> converter, ValueType<?> fromType, ValueType<?> toType, int converterIndex) {
|
||||
return new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.VALUE_CONVERTER_TYPES, converter.getType(), viewer.registryAccess()))
|
||||
.addLoreLine(converter.getDisplayText())
|
||||
.setCallback(() -> new ConverterGui(this, converter, fromType, toType, converters, false, converterIndex));
|
||||
}
|
||||
|
||||
private GuiElementBuilder createCastDisplay(ValueType<?> fromType, ValueType<?> toType, int newConverterIndex) {
|
||||
return new GuiElementBuilder(Items.MAGENTA_GLAZED_TERRACOTTA)
|
||||
.setName(Component.translatable(
|
||||
"minions.gui.instruction.converters.cast",
|
||||
Component.translatable(TranslationUtil.getTranslationKey(fromType, MinionRegistries.VALUE_TYPES)),
|
||||
Component.translatable(TranslationUtil.getTranslationKey(toType, MinionRegistries.VALUE_TYPES))
|
||||
))
|
||||
.setCallback(() -> new ConverterGui(this, null, fromType, toType, converters, true, newConverterIndex));
|
||||
}
|
||||
|
||||
private @Nullable GuiElementBuilder createCastWarning(ValueType<?> fromType, ValueType<?> toType) {
|
||||
Component warning = ConverterList.createCastWarning(fromType, toType);
|
||||
|
||||
if(warning != null) {
|
||||
return new GuiElementBuilder(Items.RED_BANNER)
|
||||
.setName(Component.translatable("minions.generic.error"))
|
||||
.addLoreLine(warning);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private @Nullable GuiElementBuilder createConverterWarning(ValueConverter<?,?> converter) {
|
||||
Component warning = ConverterList.createConverterWarning(converter);
|
||||
|
||||
if(warning != null) {
|
||||
return new GuiElementBuilder(Items.RED_BANNER)
|
||||
.setName(Component.translatable("minions.generic.error"))
|
||||
.addLoreLine(warning);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void closeBacking() {
|
||||
gui.close();
|
||||
}
|
||||
}
|
||||
@@ -1,185 +0,0 @@
|
||||
package io.github.skippyall.minions.gui.instruction;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import io.github.skippyall.minions.gui.GuiDisplay;
|
||||
import io.github.skippyall.minions.gui.MinionsGui;
|
||||
import io.github.skippyall.minions.gui.input.Result;
|
||||
import io.github.skippyall.minions.gui.input.TextInput;
|
||||
import io.github.skippyall.minions.gui.minion.GuiContext;
|
||||
import io.github.skippyall.minions.gui.minion.SimpleMinionsGui;
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.module.MinionModule;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import io.github.skippyall.minions.program.instruction.InstructionType;
|
||||
import io.github.skippyall.minions.program.supplier.Parameter;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplier;
|
||||
import io.github.skippyall.minions.registration.MinionComponentTypes;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import io.github.skippyall.minions.util.TranslationUtil;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.inventory.MenuType;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class InstructionGui {
|
||||
public static void openInstructionMainMenu(MinionsGui parent, GuiContext.Minion context) {
|
||||
new SimpleMinionsGui(parent, (onClose, me) -> {
|
||||
ServerPlayer player = parent.viewer;
|
||||
|
||||
SimpleGui gui = new SimpleGui(MenuType.GENERIC_3x3, player, false) {
|
||||
@Override
|
||||
public void onPlayerClose(boolean success) {
|
||||
onClose.run();
|
||||
}
|
||||
};
|
||||
gui.setTitle(Component.translatable("minions.gui.instruction.title"));
|
||||
|
||||
gui.setSlot(2, me.backButton());
|
||||
gui.setSlot(3, new GuiElementBuilder()
|
||||
.setItem(Items.BOOK)
|
||||
.setName(Component.translatable("minions.gui.instruction.list"))
|
||||
.setCallback(() -> new InstructionListGui(me, context))
|
||||
);
|
||||
gui.setSlot(5, new GuiElementBuilder()
|
||||
.setItem(Items.WRITABLE_BOOK)
|
||||
.setName(Component.translatable("minions.gui.instruction.create"))
|
||||
.setCallback(() -> createNewInstruction(me, context))
|
||||
);
|
||||
|
||||
gui.open();
|
||||
return gui;
|
||||
});
|
||||
}
|
||||
|
||||
public static void createNewInstruction(MinionsGui parent, GuiContext.Minion context) {
|
||||
MinionFakePlayer minion = context.getMinion();
|
||||
ServerPlayer viewer = parent.viewer;
|
||||
selectInstructionModuleMenu(parent, context).thenAccept(instructionType ->
|
||||
inputInstructionName(parent, context, "Instruction").thenAccept(name -> {
|
||||
if (!minion.isRemoved() && !minion.hasDisconnected() && name != null) {
|
||||
ConfiguredInstruction<MinionRuntime> configuredInstruction = minion.getInstructionManager().createInstruction(name, instructionType);
|
||||
new ConfigureInstructionGui(parent, GuiContext.Instruction.create(context, configuredInstruction, name));
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
public static CompletableFuture<@Nullable String> inputInstructionName(MinionsGui parent, GuiContext.Minion context, String defaultValue) {
|
||||
return TextInput.input(parent, Component.translatable("minions.gui.instruction.enter_name"), defaultValue, (name, _) -> {
|
||||
if (context.getMinion().getInstructionManager().hasInstruction(name)) {
|
||||
return new Result.Error<>(Component.translatable("minions.gui.instruction.name_already_used"));
|
||||
}
|
||||
return new Result.Success<>(name);
|
||||
});
|
||||
}
|
||||
|
||||
public static boolean checkInstructionExists(String name, ConfiguredInstruction<?> instruction, MinionFakePlayer minion, ServerPlayer player) {
|
||||
boolean stillExists = !minion.isRemoved() && !minion.hasDisconnected() && minion.getInstructionManager().getInstruction(name) == instruction;
|
||||
if (!stillExists) {
|
||||
player.closeContainer();
|
||||
player.sendSystemMessage(Component.translatable("minions.gui.instruction.removed"));
|
||||
}
|
||||
return stillExists;
|
||||
}
|
||||
|
||||
public static CompletableFuture<InstructionType<MinionRuntime>> selectInstructionModuleMenu(MinionsGui parent, GuiContext.Minion context) {
|
||||
MinionFakePlayer minion = context.getMinion();
|
||||
ServerPlayer viewer = parent.viewer;
|
||||
|
||||
if (minion.getModuleInventory().getModules().isEmpty()) {
|
||||
viewer.sendSystemMessage(Component.translatable("minions.gui.instruction.no_modules"));
|
||||
return CompletableFuture.failedFuture(new NoSuchElementException("No modules"));
|
||||
}
|
||||
|
||||
CompletableFuture<InstructionType<MinionRuntime>> future = new CompletableFuture<>();
|
||||
|
||||
new SimpleMinionsGui(parent, (closeHandler, me) -> {
|
||||
SimpleGui gui = new SimpleGui(MenuType.GENERIC_9x4, viewer, false) {
|
||||
@Override
|
||||
public void onPlayerClose(boolean success) {
|
||||
if (!future.isDone()) {
|
||||
future.cancel(false);
|
||||
}
|
||||
closeHandler.run();
|
||||
}
|
||||
};
|
||||
gui.setTitle(Component.translatable("minions.gui.instruction.select_instruction"));
|
||||
|
||||
gui.setSlot(8, me.backButton());
|
||||
|
||||
for (int i = 0; i < minion.getModuleInventory().getContainerSize(); i++) {
|
||||
ItemStack moduleItem = minion.getModuleInventory().getItem(i);
|
||||
MinionModule module = moduleItem.get(MinionComponentTypes.MODULE);
|
||||
if (module != null && !module.instructions().isEmpty()) {
|
||||
gui.setSlot(i + 9, new GuiElementBuilder(moduleItem)
|
||||
.setCallback(() -> selectInstructionMenu(parent, context, module)
|
||||
.thenApply(future::complete)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
gui.open();
|
||||
return gui;
|
||||
});
|
||||
return future;
|
||||
}
|
||||
|
||||
public static CompletableFuture<InstructionType<MinionRuntime>> selectInstructionMenu(MinionsGui parent, GuiContext.Minion context, MinionModule module) {
|
||||
CompletableFuture<InstructionType<MinionRuntime>> future = new CompletableFuture<>();
|
||||
|
||||
new SimpleMinionsGui(parent, (closeHandler, me) -> {
|
||||
SimpleGui gui = new SimpleGui(MenuType.GENERIC_9x4, parent.viewer, false) {
|
||||
@Override
|
||||
public void onPlayerClose(boolean success) {
|
||||
if (!future.isDone()) {
|
||||
future.cancel(false);
|
||||
}
|
||||
closeHandler.run();
|
||||
}
|
||||
};
|
||||
gui.setTitle(Component.translatable("minions.gui.instruction.select_instruction"));
|
||||
|
||||
gui.setSlot(8, me.backButton());
|
||||
int slot = 9;
|
||||
for (InstructionType<MinionRuntime> instructionType : module.instructions()) {
|
||||
gui.setSlot(slot, createInstructionElement(instructionType, parent.viewer.registryAccess())
|
||||
.setCallback(() -> future.complete(instructionType))
|
||||
);
|
||||
slot++;
|
||||
}
|
||||
|
||||
gui.open();
|
||||
return gui;
|
||||
});
|
||||
return future;
|
||||
}
|
||||
|
||||
public static GuiElementBuilder createInstructionElement(@Nullable InstructionType<MinionRuntime> instructionType, RegistryAccess manager) {
|
||||
GuiElementBuilder instructionBuilder;
|
||||
if (instructionType != null) {
|
||||
instructionBuilder = new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.INSTRUCTION_TYPES, instructionType, manager));
|
||||
} else {
|
||||
instructionBuilder = new GuiElementBuilder(Items.RED_WOOL)
|
||||
.setName(Component.translatable("minions.gui.instruction.no_instruction_set"));
|
||||
}
|
||||
return instructionBuilder;
|
||||
}
|
||||
|
||||
public static GuiElementBuilder createParameterElement(Parameter<?> parameter, @Nullable ValueSupplier<?,?> valueSupplier, RegistryAccess manager) {
|
||||
GuiElementBuilder builder = new GuiElementBuilder(GuiDisplay.getDisplayStack(MinionRegistries.VALUE_TYPES, parameter.type(), manager))
|
||||
.setName(Component.translatable("minions.gui.instruction.parameter", parameter.name(), Component.translatable(TranslationUtil.getTranslationKey(parameter.type(), MinionRegistries.VALUE_TYPES))));
|
||||
if(valueSupplier != null) {
|
||||
builder.addLoreLine(Component.translatable("minions.gui.instruction.argument", valueSupplier.getDisplayText()));
|
||||
}
|
||||
return builder;
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package io.github.skippyall.minions.gui.instruction;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import io.github.skippyall.minions.gui.GuiDisplay;
|
||||
import io.github.skippyall.minions.gui.MinionsGui;
|
||||
import io.github.skippyall.minions.gui.minion.GuiContext;
|
||||
import io.github.skippyall.minions.minion.MinionListener;
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.inventory.MenuType;
|
||||
|
||||
public class InstructionListGui extends MinionsGui implements MinionListener {
|
||||
private final GuiContext.Minion context;
|
||||
private final MinionFakePlayer minion;
|
||||
private SimpleGui gui;
|
||||
|
||||
public InstructionListGui(MinionsGui parent, GuiContext.Minion context) {
|
||||
super(parent);
|
||||
this.context = context;
|
||||
this.minion = context.getMinion();
|
||||
open();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInstructionsUpdate(MinionFakePlayer minion) {
|
||||
resetInstructionList();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void open() {
|
||||
minion.addMinionListener(this);
|
||||
gui = new SimpleGui(MenuType.GENERIC_9x4, viewer, false) {
|
||||
@Override
|
||||
public void onPlayerClose(boolean success) {
|
||||
onBackingClosed();
|
||||
}
|
||||
};
|
||||
gui.setTitle(Component.translatable("minions.gui.instruction.title"));
|
||||
|
||||
gui.setSlot(8, backButton());
|
||||
resetInstructionList();
|
||||
gui.open();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void closeBacking() {
|
||||
minion.removeMinionListener(this);
|
||||
gui.close();
|
||||
}
|
||||
|
||||
private void resetInstructionList() {
|
||||
int i = 9;
|
||||
for (String instructionName : minion.getInstructionManager().getInstructionNames()) {
|
||||
ConfiguredInstruction<MinionRuntime> instruction = minion.getInstructionManager().getInstruction(instructionName);
|
||||
gui.setSlot(i, new GuiElementBuilder(GuiDisplay.getGuiDisplayFor(MinionRegistries.INSTRUCTION_TYPES, instruction.getInstruction(), viewer.registryAccess()).createItemStack())
|
||||
.setName(Component.literal(instructionName))
|
||||
.setCallback(() -> new ConfigureInstructionGui(this, GuiContext.Instruction.create(context, instruction, instructionName)))
|
||||
);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
@NullMarked
|
||||
package io.github.skippyall.minions.gui.instruction;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
@@ -1,66 +0,0 @@
|
||||
package io.github.skippyall.minions.gui.minion
|
||||
|
||||
import io.github.skippyall.minions.gui.minion.GuiContextImpl.InstructionImpl
|
||||
import io.github.skippyall.minions.gui.minion.GuiContextImpl.MinionImpl
|
||||
import io.github.skippyall.minions.gui.minion.GuiContextImpl.ValueSupplierImpl
|
||||
import io.github.skippyall.minions.minion.MinionRuntime
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction
|
||||
import io.github.skippyall.minions.program.supplier.Parameter
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
|
||||
interface GuiContext {
|
||||
val viewer: ServerPlayer
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun create(viewer: ServerPlayer): GuiContext {
|
||||
return GuiContextImpl(viewer)
|
||||
}
|
||||
}
|
||||
|
||||
interface Minion : GuiContext {
|
||||
val minion: MinionFakePlayer
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun create(context: GuiContext, minion: MinionFakePlayer): Minion {
|
||||
return MinionImpl(
|
||||
if(context is MinionImpl) context.context else context,
|
||||
minion
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface Instruction : Minion {
|
||||
val instruction: ConfiguredInstruction<MinionRuntime>
|
||||
|
||||
var name: String
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun create(context: Minion, instruction: ConfiguredInstruction<MinionRuntime>, name: String): Instruction {
|
||||
return InstructionImpl(
|
||||
if(context is InstructionImpl) context.context else context,
|
||||
instruction,
|
||||
name
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface ValueSupplier : Instruction {
|
||||
val parameter: Parameter<*>
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun create(context: Instruction, parameter: Parameter<*>): ValueSupplier {
|
||||
return ValueSupplierImpl(
|
||||
if(context is ValueSupplierImpl) context.context else context,
|
||||
parameter
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package io.github.skippyall.minions.gui.minion
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction
|
||||
import io.github.skippyall.minions.program.supplier.Parameter
|
||||
import net.minecraft.server.level.ServerPlayer
|
||||
|
||||
//Thank you kotlin
|
||||
class GuiContextImpl(override val viewer: ServerPlayer) : GuiContext {
|
||||
class MinionImpl(
|
||||
val context: GuiContext,
|
||||
override val minion: MinionFakePlayer
|
||||
) : GuiContext by context, GuiContext.Minion
|
||||
|
||||
class InstructionImpl(
|
||||
val context: GuiContext.Minion,
|
||||
override val instruction: ConfiguredInstruction<MinionRuntime>,
|
||||
override var name: String
|
||||
) : GuiContext.Minion by context, GuiContext.Instruction
|
||||
|
||||
class ValueSupplierImpl(
|
||||
val context: GuiContext.Instruction,
|
||||
override val parameter: Parameter<*>
|
||||
) : GuiContext.Instruction by context, GuiContext.ValueSupplier
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package io.github.skippyall.minions.gui.minion;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import io.github.skippyall.minions.gui.MinionsGui;
|
||||
import io.github.skippyall.minions.gui.instruction.InstructionGui;
|
||||
import io.github.skippyall.minions.minion.MinionListener;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.module.ModuleInventory;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.inventory.MenuType;
|
||||
import net.minecraft.world.item.Items;
|
||||
|
||||
public class MinionGui extends MinionsGui implements MinionListener {
|
||||
private final MinionFakePlayer minion;
|
||||
private SimpleGui gui;
|
||||
|
||||
public MinionGui(ServerPlayer viewer, MinionFakePlayer minion) {
|
||||
super(viewer);
|
||||
this.minion = minion;
|
||||
minion.addMinionListener(this);
|
||||
open();
|
||||
}
|
||||
|
||||
public MinionFakePlayer getMinion() {
|
||||
return minion;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void open() {
|
||||
gui = new SimpleGui(MenuType.GENERIC_3x3, viewer, false) {
|
||||
@Override
|
||||
public void onPlayerClose(boolean success) {
|
||||
onBackingClosed();
|
||||
}
|
||||
};
|
||||
|
||||
gui.setTitle(minion.getName());
|
||||
|
||||
gui.setSlot(1, new GuiElementBuilder()
|
||||
.setItem(Items.COMMAND_BLOCK)
|
||||
.setName(Component.translatable("minions.gui.main.instructions"))
|
||||
.setCallback(() -> {
|
||||
InstructionGui.openInstructionMainMenu(this, GuiContext.Minion.create(GuiContext.create(viewer), minion));
|
||||
})
|
||||
);
|
||||
gui.setSlot(3, new GuiElementBuilder()
|
||||
.setItem(Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE)
|
||||
.setName(Component.translatable("minions.gui.main.modules"))
|
||||
.setCallback(() -> {
|
||||
ModuleInventory.openModuleInventory(viewer, minion);
|
||||
})
|
||||
);
|
||||
gui.setSlot(5, new GuiElementBuilder()
|
||||
.setItem(Items.CHEST)
|
||||
.setName(Component.translatable("minions.gui.main.inventory"))
|
||||
.setCallback(() -> new MinionInventoryGui(this))
|
||||
);
|
||||
gui.setSlot(7, new GuiElementBuilder()
|
||||
.setItem(Items.BARRIER)
|
||||
.setName(Component.translatable("minions.gui.main.pickup"))
|
||||
.setCallback(() -> minion.kill(minion.level()))
|
||||
);
|
||||
gui.open();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void closeBacking() {
|
||||
gui.close();
|
||||
minion.removeMinionListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMinionRemove(MinionFakePlayer minion) {
|
||||
close();
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package io.github.skippyall.minions.gui.minion;
|
||||
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import io.github.skippyall.minions.gui.MinionsGui;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
import net.minecraft.world.inventory.ArmorSlot;
|
||||
import net.minecraft.world.inventory.MenuType;
|
||||
import net.minecraft.world.inventory.Slot;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
|
||||
public class MinionInventoryGui extends MinionsGui {
|
||||
protected final MinionGui parent;
|
||||
private final MinionFakePlayer minion;
|
||||
|
||||
private SimpleGui gui;
|
||||
|
||||
public MinionInventoryGui(MinionGui parent) {
|
||||
super(parent);
|
||||
this.parent = parent;
|
||||
this.minion = parent.getMinion();
|
||||
open();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void open() {
|
||||
gui = new SimpleGui(MenuType.GENERIC_9x6, viewer, false) {
|
||||
@Override
|
||||
public void onPlayerClose(boolean success) {
|
||||
onBackingClosed();
|
||||
}
|
||||
};
|
||||
gui.setTitle(Component.translatable("minions.gui.inventory.title"));
|
||||
|
||||
for(int i = 0; i < 18; i++) {
|
||||
gui.setSlot(i, new ItemStack(Items.BARRIER));
|
||||
}
|
||||
|
||||
gui.setSlot(2, new ItemStack(Items.LEATHER_HELMET));
|
||||
gui.setSlot(3, new ItemStack(Items.LEATHER_CHESTPLATE));
|
||||
gui.setSlot(4, new ItemStack(Items.LEATHER_LEGGINGS));
|
||||
gui.setSlot(5, new ItemStack(Items.LEATHER_BOOTS));
|
||||
gui.setSlot(6, new ItemStack(Items.SHIELD));
|
||||
|
||||
gui.setSlot(8, backButton());
|
||||
|
||||
gui.setSlot(2 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.HEAD, EquipmentSlot.HEAD.getIndex(Inventory.INVENTORY_SIZE), 0, 0, null));
|
||||
gui.setSlot(3 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.CHEST, EquipmentSlot.CHEST.getIndex(Inventory.INVENTORY_SIZE), 0, 0, null));
|
||||
gui.setSlot(4 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.LEGS, EquipmentSlot.LEGS.getIndex(Inventory.INVENTORY_SIZE), 0, 0, null));
|
||||
gui.setSlot(5 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.FEET, EquipmentSlot.FEET.getIndex(Inventory.INVENTORY_SIZE), 0, 0, null));
|
||||
gui.setSlot(6 + 9, new Slot(minion.getInventory(), Inventory.SLOT_OFFHAND, 0, 0));
|
||||
|
||||
for (int i = Inventory.SELECTION_SIZE; i < Inventory.INVENTORY_SIZE; i++) {
|
||||
gui.setSlot(i + 9, new Slot(minion.getInventory(), i, 0, 0));
|
||||
}
|
||||
|
||||
for (int i = 0; i < Inventory.SELECTION_SIZE; i++) {
|
||||
gui.setSlot(i + 45, new Slot(minion.getInventory(), i, 0, 0));
|
||||
}
|
||||
gui.open();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void closeBacking() {
|
||||
gui.close();
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package io.github.skippyall.minions.gui.minion;
|
||||
|
||||
import eu.pb4.sgui.api.gui.GuiLike;
|
||||
import io.github.skippyall.minions.gui.MinionsGui;
|
||||
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
public class SimpleMinionsGui extends MinionsGui {
|
||||
private GuiLike gui;
|
||||
private final BiFunction<Runnable, SimpleMinionsGui, GuiLike> guiFactory;
|
||||
|
||||
public SimpleMinionsGui(MinionsGui parent, BiFunction<Runnable, SimpleMinionsGui, GuiLike> guiFactory) {
|
||||
super(parent);
|
||||
this.guiFactory = guiFactory;
|
||||
open();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void open() {
|
||||
gui = guiFactory.apply(this::onBackingClosed, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void closeBacking() {
|
||||
gui.close();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
@NullMarked
|
||||
package io.github.skippyall.minions.gui.minion;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
@@ -1,4 +0,0 @@
|
||||
@NullMarked
|
||||
package io.github.skippyall.minions.gui;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
+7
-7
@@ -1,12 +1,12 @@
|
||||
package io.github.skippyall.minions.minion.program.instruction;
|
||||
package io.github.skippyall.minions.instruction;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.EntityPlayerActionPack;
|
||||
import io.github.skippyall.minions.program.consumer.ValueConsumerList;
|
||||
import io.github.skippyall.minions.program.instruction.execution.ContinuousInstructionExecution;
|
||||
import io.github.skippyall.minions.program.supplier.ParameterValueList;
|
||||
import net.minecraft.world.level.storage.ValueInput;
|
||||
import net.minecraft.world.level.storage.ValueOutput;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierList;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
|
||||
public class ActionExecution implements ContinuousInstructionExecution<MinionRuntime> {
|
||||
private final EntityPlayerActionPack.ActionType action;
|
||||
@@ -39,13 +39,13 @@ public class ActionExecution implements ContinuousInstructionExecution<MinionRun
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readArguments(ParameterValueList parameters, MinionRuntime minion) {}
|
||||
public void readArguments(ValueSupplierList<MinionRuntime> parameters, MinionRuntime minion) {}
|
||||
|
||||
@Override
|
||||
public void save(ValueOutput view, MinionRuntime minion) {}
|
||||
public void save(WriteView view, MinionRuntime minion) {}
|
||||
|
||||
@Override
|
||||
public void load(ValueInput view, MinionRuntime runtime) {
|
||||
public void load(ReadView view, MinionRuntime runtime) {
|
||||
runtime.getMinion().getMinionActionPack().start(action, EntityPlayerActionPack.Action.continuous());
|
||||
}
|
||||
}
|
||||
+31
-31
@@ -1,25 +1,24 @@
|
||||
//partially code from https://github.com/gnembon/fabric-carpet (EntityPlayerActionPack)
|
||||
package io.github.skippyall.minions.minion.program.instruction;
|
||||
package io.github.skippyall.minions.instruction;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.EntityPlayerActionPack;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.consumer.ValueConsumerList;
|
||||
import io.github.skippyall.minions.program.instruction.InstructionExecution;
|
||||
import io.github.skippyall.minions.program.supplier.ParameterValueList;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.storage.ValueInput;
|
||||
import net.minecraft.world.level.storage.ValueOutput;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraft.world.phys.HitResult;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierList;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.network.packet.c2s.play.PlayerActionC2SPacket;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
import net.minecraft.util.Hand;
|
||||
import net.minecraft.util.hit.BlockHitResult;
|
||||
import net.minecraft.util.hit.HitResult;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Direction;
|
||||
|
||||
public class MineBlockExecution implements InstructionExecution<MinionRuntime> {
|
||||
private @Nullable BlockPos currentBlock;
|
||||
private BlockPos currentBlock;
|
||||
private float currentBlockDamage = 0;
|
||||
private boolean first = true;
|
||||
private boolean done = false;
|
||||
@@ -37,8 +36,9 @@ public class MineBlockExecution implements InstructionExecution<MinionRuntime> {
|
||||
done = true;
|
||||
return;
|
||||
}
|
||||
if (player.blockActionRestricted(player.level(), hit.getBlockPos(), player.gameMode.getGameModeForPlayer())) {
|
||||
if (player.isBlockBreakingRestricted(player.getWorld(), hit.getBlockPos(), player.interactionManager.getGameMode())) {
|
||||
done = true;
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
done = true;
|
||||
@@ -66,37 +66,37 @@ public class MineBlockExecution implements InstructionExecution<MinionRuntime> {
|
||||
return;
|
||||
}
|
||||
|
||||
if (player.level().getBlockState(currentBlock).isAir()) {
|
||||
if (player.getWorld().getBlockState(currentBlock).isAir()) {
|
||||
done = true;
|
||||
return;
|
||||
}
|
||||
BlockState state = player.level().getBlockState(currentBlock);
|
||||
BlockState state = player.getWorld().getBlockState(currentBlock);
|
||||
boolean blockBroken = false;
|
||||
if (first) {
|
||||
first = false;
|
||||
player.gameMode.handleBlockBreakAction(currentBlock, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, newBlockHit.getDirection(), player.level().getMaxY(), -1);
|
||||
player.interactionManager.processBlockBreakingAction(currentBlock, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, newBlockHit.getSide(), player.getWorld().getTopYInclusive(), -1);
|
||||
boolean notAir = !state.isAir();
|
||||
if (notAir)
|
||||
{
|
||||
state.attack(player.level(), currentBlock, player);
|
||||
state.onBlockBreakStart(player.getWorld(), currentBlock, player);
|
||||
}
|
||||
if (notAir && state.getDestroyProgress(player, player.level(), currentBlock) >= 1)
|
||||
if (notAir && state.calcBlockBreakingDelta(player, player.getWorld(), currentBlock) >= 1)
|
||||
{
|
||||
//instamine??
|
||||
blockBroken = true;
|
||||
}
|
||||
} else {
|
||||
currentBlockDamage += state.getDestroyProgress(player, player.level(), currentBlock);
|
||||
currentBlockDamage += state.calcBlockBreakingDelta(player, player.getWorld(), currentBlock);
|
||||
if (currentBlockDamage >= 1) {
|
||||
player.gameMode.handleBlockBreakAction(currentBlock, ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, newBlockHit.getDirection(), player.level().getMaxY(), -1);
|
||||
player.interactionManager.processBlockBreakingAction(currentBlock, PlayerActionC2SPacket.Action.STOP_DESTROY_BLOCK, newBlockHit.getSide(), player.getWorld().getTopYInclusive(), -1);
|
||||
ap.blockHitDelay = 5;
|
||||
blockBroken = true;
|
||||
}
|
||||
player.level().destroyBlockProgress(-1, currentBlock, (int) (currentBlockDamage * 10));
|
||||
player.getWorld().setBlockBreakingInfo(-1, currentBlock, (int) (currentBlockDamage * 10));
|
||||
|
||||
}
|
||||
player.resetLastActionTime();
|
||||
player.swing(InteractionHand.MAIN_HAND);
|
||||
player.updateLastActionTime();
|
||||
player.swingHand(Hand.MAIN_HAND);
|
||||
|
||||
if(blockBroken) {
|
||||
done = true;
|
||||
@@ -115,26 +115,26 @@ public class MineBlockExecution implements InstructionExecution<MinionRuntime> {
|
||||
EntityPlayerActionPack ap = player.getMinionActionPack();
|
||||
|
||||
if(currentBlock != null) {
|
||||
player.level().destroyBlockProgress(-1, currentBlock, -1);
|
||||
player.gameMode.handleBlockBreakAction(currentBlock, ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, Direction.DOWN, player.level().getMaxY(), -1);
|
||||
player.getWorld().setBlockBreakingInfo(-1, currentBlock, -1);
|
||||
player.interactionManager.processBlockBreakingAction(currentBlock, PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, Direction.DOWN, player.getWorld().getTopYInclusive(), -1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readArguments(ParameterValueList arguments, MinionRuntime runtime) {
|
||||
public void readArguments(ValueSupplierList<MinionRuntime> arguments, MinionRuntime runtime) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(ValueOutput view, MinionRuntime runtime) {
|
||||
view.store("currentBlock", BlockPos.CODEC, currentBlock);
|
||||
public void save(WriteView view, MinionRuntime runtime) {
|
||||
view.put("currentBlock", BlockPos.CODEC, currentBlock);
|
||||
view.putFloat("currentBlockDamage", currentBlockDamage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(ValueInput view, MinionRuntime runtime) {
|
||||
public void load(ReadView view, MinionRuntime runtime) {
|
||||
currentBlock = view.read("currentBlock", BlockPos.CODEC).orElse(null);
|
||||
currentBlockDamage = view.getFloatOr("currentBlockDamage", 0);
|
||||
currentBlockDamage = view.getFloat("currentBlockDamage", 0);
|
||||
if(currentBlock == null) {
|
||||
done = true;
|
||||
}
|
||||
+30
-30
@@ -1,18 +1,18 @@
|
||||
package io.github.skippyall.minions.minion.program.instruction.inventory;
|
||||
package io.github.skippyall.minions.instruction.inventory;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.consumer.ValueConsumerList;
|
||||
import io.github.skippyall.minions.program.instruction.InstructionExecution;
|
||||
import io.github.skippyall.minions.program.supplier.Parameter;
|
||||
import io.github.skippyall.minions.program.supplier.ParameterValueList;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierList;
|
||||
import io.github.skippyall.minions.registration.ValueTypes;
|
||||
import net.minecraft.world.inventory.AbstractContainerMenu;
|
||||
import net.minecraft.world.inventory.ContainerInput;
|
||||
import net.minecraft.world.inventory.Slot;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.storage.ValueInput;
|
||||
import net.minecraft.world.level.storage.ValueOutput;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.screen.ScreenHandler;
|
||||
import net.minecraft.screen.slot.Slot;
|
||||
import net.minecraft.screen.slot.SlotActionType;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
|
||||
public class SwapItemExecution implements InstructionExecution<MinionRuntime> {
|
||||
public static final Parameter<Long> FROM_SLOT = new Parameter<>("from_slot", ValueTypes.LONG);
|
||||
@@ -31,7 +31,7 @@ public class SwapItemExecution implements InstructionExecution<MinionRuntime> {
|
||||
public void start(MinionRuntime runtime) {
|
||||
MinionFakePlayer minion = runtime.getMinion();
|
||||
|
||||
if((fromScreen || toScreen) && minion.containerMenu == null) {
|
||||
if((fromScreen || toScreen) && minion.currentScreenHandler == null) {
|
||||
return;
|
||||
}
|
||||
if(!(checkBounds(minion, fromSlot, fromScreen) && checkBounds(minion, toSlot, toScreen))) {
|
||||
@@ -48,14 +48,14 @@ public class SwapItemExecution implements InstructionExecution<MinionRuntime> {
|
||||
simulateClick(minion, fromSlot, fromScreen);
|
||||
simulateClick(minion, toSlot, toScreen);
|
||||
simulateClick(minion, fromSlot, fromScreen);
|
||||
minion.getInventory().placeItemBackInInventory(cursor);
|
||||
minion.getInventory().offerOrDrop(cursor);
|
||||
}
|
||||
|
||||
private AbstractContainerMenu getScreen(MinionFakePlayer minion, boolean screen) {
|
||||
private ScreenHandler getScreen(MinionFakePlayer minion, boolean screen) {
|
||||
if(screen) {
|
||||
return minion.containerMenu;
|
||||
return minion.currentScreenHandler;
|
||||
} else {
|
||||
return minion.inventoryMenu;
|
||||
return minion.playerScreenHandler;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,16 +64,16 @@ public class SwapItemExecution implements InstructionExecution<MinionRuntime> {
|
||||
}
|
||||
|
||||
private ItemStack getStack(MinionFakePlayer minion, int slot, boolean screen) {
|
||||
return getScreen(minion, screen).getSlot(slot).getItem();
|
||||
return getScreen(minion, screen).getSlot(slot).getStack();
|
||||
}
|
||||
|
||||
private boolean canExchange(MinionFakePlayer minion, int slotIndex, boolean screen, ItemStack newStack) {
|
||||
AbstractContainerMenu screenHandler = getScreen(minion, screen);
|
||||
ScreenHandler screenHandler = getScreen(minion, screen);
|
||||
Slot slot = screenHandler.getSlot(slotIndex);
|
||||
if(!slot.getItem().isEmpty() && !slot.mayPickup(minion)) {
|
||||
if(!slot.getStack().isEmpty() && !slot.canTakeItems(minion)) {
|
||||
return false;
|
||||
}
|
||||
if(!newStack.isEmpty() && !slot.mayPlace(newStack)) {
|
||||
if(!newStack.isEmpty() && !slot.canInsert(newStack)) {
|
||||
return false;
|
||||
}
|
||||
/*else {
|
||||
@@ -90,12 +90,12 @@ public class SwapItemExecution implements InstructionExecution<MinionRuntime> {
|
||||
}
|
||||
|
||||
private void simulateClick(MinionFakePlayer minion, int slotIndex, boolean screen) {
|
||||
AbstractContainerMenu screenHandler = getScreen(minion, screen);
|
||||
ItemStack previousCursor = screenHandler.getCarried();
|
||||
screenHandler.setCarried(cursor);
|
||||
screenHandler.clicked(slotIndex, 0, ContainerInput.SWAP, minion);
|
||||
cursor = screenHandler.getCarried();
|
||||
screenHandler.setCarried(previousCursor);
|
||||
ScreenHandler screenHandler = getScreen(minion, screen);
|
||||
ItemStack previousCursor = screenHandler.getCursorStack();
|
||||
screenHandler.setCursorStack(cursor);
|
||||
screenHandler.onSlotClick(slotIndex, 0, SlotActionType.SWAP, minion);
|
||||
cursor = screenHandler.getCursorStack();
|
||||
screenHandler.setCursorStack(previousCursor);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -114,20 +114,20 @@ public class SwapItemExecution implements InstructionExecution<MinionRuntime> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readArguments(ParameterValueList arguments, MinionRuntime runtime) {
|
||||
fromSlot = Math.clamp(arguments.getValue(FROM_SLOT), 0, Integer.MAX_VALUE);
|
||||
fromScreen = arguments.getValue(FROM_SCREEN);
|
||||
toSlot = Math.clamp(arguments.getValue(TO_SLOT), 0, Integer.MAX_VALUE);
|
||||
toScreen = arguments.getValue(TO_SCREEN);
|
||||
public void readArguments(ValueSupplierList<MinionRuntime> arguments, MinionRuntime runtime) {
|
||||
fromSlot = Math.clamp(arguments.getValue(FROM_SLOT, runtime), 0, Integer.MAX_VALUE);
|
||||
fromScreen = arguments.getValue(FROM_SCREEN, runtime);
|
||||
toSlot = Math.clamp(arguments.getValue(TO_SLOT, runtime), 0, Integer.MAX_VALUE);
|
||||
toScreen = arguments.getValue(TO_SCREEN, runtime);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(ValueOutput view, MinionRuntime runtime) {
|
||||
public void save(WriteView view, MinionRuntime runtime) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(ValueInput view, MinionRuntime runtime) {
|
||||
public void load(ReadView view, MinionRuntime runtime) {
|
||||
|
||||
}
|
||||
}
|
||||
+10
-10
@@ -1,9 +1,9 @@
|
||||
package io.github.skippyall.minions.minion.program.instruction.move;
|
||||
package io.github.skippyall.minions.instruction.move;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.program.instruction.InstructionExecution;
|
||||
import net.minecraft.world.level.storage.ValueInput;
|
||||
import net.minecraft.world.level.storage.ValueOutput;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
|
||||
public abstract class AbstractTurnExecution implements InstructionExecution<MinionRuntime> {
|
||||
protected float targetYaw;
|
||||
@@ -13,26 +13,26 @@ public abstract class AbstractTurnExecution implements InstructionExecution<Mini
|
||||
|
||||
@Override
|
||||
public void tick(MinionRuntime minion) {
|
||||
float rotateYaw = targetYaw - minion.getMinion().getYRot();
|
||||
float rotatePitch = targetPitch - minion.getMinion().getXRot();
|
||||
float rotateYaw = targetYaw - minion.getMinion().getYaw();
|
||||
float rotatePitch = targetPitch - minion.getMinion().getPitch();
|
||||
|
||||
minion.getMinion().getMinionActionPack().turn(Math.min(rotateYaw, anglePerTick), Math.min(rotatePitch, anglePerTick));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDone(MinionRuntime minion) {
|
||||
return Math.abs(targetYaw - minion.getMinion().getYRot()) < 0.001F && Math.abs(targetPitch - minion.getMinion().getXRot()) < 0.001F;
|
||||
return Math.abs(targetYaw - minion.getMinion().getYaw()) < 0.001F && Math.abs(targetPitch - minion.getMinion().getPitch()) < 0.001F;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(ValueOutput view, MinionRuntime runtime) {
|
||||
public void save(WriteView view, MinionRuntime runtime) {
|
||||
view.putFloat("targetYaw", targetYaw);
|
||||
view.putFloat("targetPitch", targetPitch);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(ValueInput view, MinionRuntime runtime) {
|
||||
targetYaw = view.getFloatOr("targetYaw", 0);
|
||||
targetPitch = view.getFloatOr("targetPitch", 0);
|
||||
public void load(ReadView view, MinionRuntime runtime) {
|
||||
targetYaw = view.getFloat("targetYaw", 0);
|
||||
targetPitch = view.getFloat("targetPitch", 0);
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -1,13 +1,13 @@
|
||||
package io.github.skippyall.minions.minion.program.instruction.move;
|
||||
package io.github.skippyall.minions.instruction.move;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.program.instruction.InstructionExecution;
|
||||
import io.github.skippyall.minions.program.instruction.execution.ContinuousInstructionExecution;
|
||||
import net.minecraft.world.entity.MoverType;
|
||||
import net.minecraft.entity.MovementType;
|
||||
|
||||
public class ContinuousWalkExecution implements ContinuousInstructionExecution<MinionRuntime>, InstructionExecution.Stateless<MinionRuntime> {
|
||||
@Override
|
||||
public void tick(MinionRuntime minion) {
|
||||
minion.getMinion().move(MoverType.SELF, minion.getMinion().getDirection().getUnitVec3().normalize().scale(minion.getMinion().getSpeed()));
|
||||
minion.getMinion().move(MovementType.SELF, minion.getMinion().getHorizontalFacing().getDoubleVector().normalize().multiply(minion.getMinion().getMovementSpeed()));
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -1,19 +1,19 @@
|
||||
package io.github.skippyall.minions.minion.program.instruction.move;
|
||||
package io.github.skippyall.minions.instruction.move;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import io.github.skippyall.minions.gui.Displayable;
|
||||
import io.github.skippyall.minions.gui.GuiDisplay;
|
||||
import net.minecraft.util.StringRepresentable;
|
||||
import net.minecraft.util.StringIdentifiable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public enum TurnDirection implements StringRepresentable, Displayable {
|
||||
public enum TurnDirection implements StringIdentifiable, Displayable {
|
||||
LEFT("left", -1, 0),
|
||||
UP("up", 0, -1),
|
||||
RIGHT("right", 1, 0),
|
||||
DOWN("down", 0, 1);
|
||||
|
||||
public static final Codec<TurnDirection> CODEC = StringRepresentable.fromEnum(TurnDirection::values);
|
||||
public static final Codec<TurnDirection> CODEC = StringIdentifiable.createCodec(TurnDirection::values);
|
||||
|
||||
private static final UUID MHF_ArrowLeft = UUID.fromString("a68f0b64-8d14-4000-a95f-4b9ba14f8df9");
|
||||
private static final UUID MHF_ArrowUp = UUID.fromString("fef039ef-e6cd-4987-9c84-26a3e6134277");
|
||||
@@ -31,7 +31,7 @@ public enum TurnDirection implements StringRepresentable, Displayable {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSerializedName() {
|
||||
public String asString() {
|
||||
return name;
|
||||
}
|
||||
|
||||
+7
-7
@@ -1,8 +1,8 @@
|
||||
package io.github.skippyall.minions.minion.program.instruction.move;
|
||||
package io.github.skippyall.minions.instruction.move;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierList;
|
||||
import io.github.skippyall.minions.program.supplier.Parameter;
|
||||
import io.github.skippyall.minions.program.supplier.ParameterValueList;
|
||||
import io.github.skippyall.minions.registration.ValueTypes;
|
||||
|
||||
public class TurnExecution extends AbstractTurnExecution {
|
||||
@@ -10,14 +10,14 @@ public class TurnExecution extends AbstractTurnExecution {
|
||||
public static final Parameter<TurnDirection> DIRECTION = new Parameter<>("direction", ValueTypes.TURN_DIRECTION);
|
||||
|
||||
@Override
|
||||
public void readArguments(ParameterValueList arguments, MinionRuntime minion) {
|
||||
float maxAngle = arguments.getValue(ANGLE).floatValue();
|
||||
TurnDirection direction = arguments.getValue(DIRECTION);
|
||||
public void readArguments(ValueSupplierList<MinionRuntime> arguments, MinionRuntime minion) {
|
||||
float maxAngle = arguments.getValue(ANGLE, minion).floatValue();
|
||||
TurnDirection direction = arguments.getValue(DIRECTION, minion);
|
||||
|
||||
float turnYaw = maxAngle * direction.xFactor;
|
||||
float turnPitch = maxAngle * direction.yFactor;
|
||||
|
||||
targetYaw = minion.getMinion().getYRot() + turnYaw;
|
||||
targetPitch = minion.getMinion().getXRot() + turnPitch;
|
||||
targetYaw = minion.getMinion().getYaw() + turnYaw;
|
||||
targetPitch = minion.getMinion().getPitch() + turnPitch;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package io.github.skippyall.minions.instruction.move;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.program.supplier.Parameter;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierList;
|
||||
import io.github.skippyall.minions.registration.ValueTypes;
|
||||
import net.minecraft.util.math.MathHelper;
|
||||
import net.minecraft.util.math.Vec2f;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
public class TurnVectorExecution extends AbstractTurnExecution {
|
||||
public static final Parameter<Double> X = new Parameter<>("x", ValueTypes.DOUBLE);
|
||||
public static final Parameter<Double> Y = new Parameter<>("y", ValueTypes.DOUBLE);
|
||||
public static final Parameter<Double> Z = new Parameter<>("z", ValueTypes.DOUBLE);
|
||||
|
||||
@Override
|
||||
public void readArguments(ValueSupplierList<MinionRuntime> arguments, MinionRuntime runtime) {
|
||||
double x = arguments.getValue(X, runtime);
|
||||
double y = arguments.getValue(Y, runtime);
|
||||
double z = arguments.getValue(Z, runtime);
|
||||
|
||||
Vec3d vector = new Vec3d(x, y, z);
|
||||
Vec2f rotation = vectorToRotation(vector);
|
||||
targetYaw = rotation.x;
|
||||
targetPitch = rotation.y;
|
||||
}
|
||||
|
||||
//copied from Entity#lookAt (why no helper, Mojang?)
|
||||
public static Vec2f vectorToRotation(Vec3d vector) {
|
||||
double g = Math.sqrt(vector.x * vector.x + vector.z * vector.z);
|
||||
float pitch = MathHelper.wrapDegrees((float)(-(MathHelper.atan2(vector.y, g) * 180.0F / (float)Math.PI)));
|
||||
float yaw = MathHelper.wrapDegrees((float)(MathHelper.atan2(vector.z, vector.x) * 180.0F / (float)Math.PI) - 90.0F);
|
||||
|
||||
return new Vec2f(yaw, pitch);
|
||||
}
|
||||
}
|
||||
+13
-13
@@ -1,13 +1,13 @@
|
||||
package io.github.skippyall.minions.minion.program.instruction.move;
|
||||
package io.github.skippyall.minions.instruction.move;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.program.instruction.InstructionExecution;
|
||||
import io.github.skippyall.minions.program.supplier.Parameter;
|
||||
import io.github.skippyall.minions.program.supplier.ParameterValueList;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierList;
|
||||
import io.github.skippyall.minions.registration.ValueTypes;
|
||||
import net.minecraft.world.entity.MoverType;
|
||||
import net.minecraft.world.level.storage.ValueInput;
|
||||
import net.minecraft.world.level.storage.ValueOutput;
|
||||
import net.minecraft.entity.MovementType;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
|
||||
public class WalkExecution implements InstructionExecution<MinionRuntime> {
|
||||
public static final Parameter<Double> blocksToMoveParam = new Parameter<>("blocksToMove", ValueTypes.DOUBLE);
|
||||
@@ -18,8 +18,8 @@ public class WalkExecution implements InstructionExecution<MinionRuntime> {
|
||||
|
||||
@Override
|
||||
public void tick(MinionRuntime minion) {
|
||||
double speed = Math.min(minion.getMinion().getSpeed(), totalBlocksToMove - blocksMoved);
|
||||
minion.getMinion().move(MoverType.SELF, minion.getMinion().getDirection().getUnitVec3().normalize().scale(speed));
|
||||
double speed = Math.min(minion.getMinion().getMovementSpeed(), totalBlocksToMove - blocksMoved);
|
||||
minion.getMinion().move(MovementType.SELF, minion.getMinion().getHorizontalFacing().getDoubleVector().normalize().multiply(speed));
|
||||
blocksMoved += speed;
|
||||
}
|
||||
|
||||
@@ -29,20 +29,20 @@ public class WalkExecution implements InstructionExecution<MinionRuntime> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readArguments(ParameterValueList parameters, MinionRuntime minion) {
|
||||
totalBlocksToMove = parameters.getValue(blocksToMoveParam).floatValue();
|
||||
public void readArguments(ValueSupplierList<MinionRuntime> parameters, MinionRuntime minion) {
|
||||
totalBlocksToMove = parameters.getValue(blocksToMoveParam, minion).floatValue();
|
||||
blocksMoved = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(ValueOutput view, MinionRuntime minion) {
|
||||
public void save(WriteView view, MinionRuntime minion) {
|
||||
view.putDouble("totalBlocksToMove", totalBlocksToMove);
|
||||
view.putDouble("blocksMoved", blocksMoved);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(ValueInput view, MinionRuntime minion) {
|
||||
totalBlocksToMove = view.getDoubleOr("totalBlocksToMove", 0F);
|
||||
blocksMoved = view.getDoubleOr("blocksMoved", 0F);
|
||||
public void load(ReadView view, MinionRuntime minion) {
|
||||
totalBlocksToMove = view.getDouble("totalBlocksToMove", 0F);
|
||||
blocksMoved = view.getDouble("blocksMoved", 0F);
|
||||
}
|
||||
}
|
||||
+8
-7
@@ -2,17 +2,18 @@ package io.github.skippyall.minions.listener;
|
||||
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstructionListener;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.block.entity.BlockEntity;
|
||||
import net.minecraft.block.entity.BlockEntityType;
|
||||
import net.minecraft.registry.RegistryKey;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.BlockEntityType;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class BlockEntityMinionInstructionListener<E extends BlockEntity> extends BlockEntityMinionListener<E> {
|
||||
protected BlockEntityMinionInstructionListener(ResourceKey<Level> worldKey, BlockPos pos, UUID minionUuid, BlockEntityType<E> type) {
|
||||
protected BlockEntityMinionInstructionListener(RegistryKey<World> worldKey, BlockPos pos, UUID minionUuid, BlockEntityType<E> type) {
|
||||
super(worldKey, pos, minionUuid, type);
|
||||
}
|
||||
|
||||
@@ -25,7 +26,7 @@ public abstract class BlockEntityMinionInstructionListener<E extends BlockEntity
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(MinecraftServer server) {
|
||||
protected void add(MinecraftServer server) {
|
||||
super.add(server);
|
||||
if(minion != null) {
|
||||
registerInstructionListeners();
|
||||
|
||||
@@ -6,26 +6,26 @@ import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import io.github.skippyall.minions.minion.MinionListener;
|
||||
import io.github.skippyall.minions.minion.MinionPersistentState;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.UUIDUtil;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.block.entity.BlockEntity;
|
||||
import net.minecraft.block.entity.BlockEntityType;
|
||||
import net.minecraft.registry.RegistryKey;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.BlockEntityType;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import net.minecraft.util.Uuids;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.world.World;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class BlockEntityMinionListener<E extends BlockEntity> implements MinionListener {
|
||||
protected ResourceKey<Level> worldKey;
|
||||
protected RegistryKey<World> worldKey;
|
||||
protected BlockPos pos;
|
||||
protected UUID minionUuid;
|
||||
protected BlockEntityType<E> type;
|
||||
protected @Nullable MinionFakePlayer minion;
|
||||
|
||||
protected BlockEntityMinionListener(ResourceKey<Level> worldKey, BlockPos pos, UUID minionUuid, BlockEntityType<E> type) {
|
||||
protected BlockEntityMinionListener(RegistryKey<World> worldKey, BlockPos pos, UUID minionUuid, BlockEntityType<E> type) {
|
||||
this.worldKey = worldKey;
|
||||
this.pos = pos;
|
||||
this.minionUuid = minionUuid;
|
||||
@@ -45,10 +45,10 @@ public abstract class BlockEntityMinionListener<E extends BlockEntity> implement
|
||||
this.minion = null;
|
||||
}
|
||||
|
||||
public static <T extends BlockEntityMinionListener<?>> @Nullable T getListener(Level world, BlockPos pos, @Nullable UUID minionUuid, Class<T> clazz) {
|
||||
public static <T extends BlockEntityMinionListener<?>> T getListener(World world, BlockPos pos, UUID minionUuid, Class<T> clazz) {
|
||||
if(minionUuid != null) {
|
||||
for (MinionListener listener : MinionPersistentState.get(world.getServer()).getMinionData(minionUuid).getListeners()) {
|
||||
if (listener instanceof BlockEntityMinionListener<?> tl && tl.pos.equals(pos) && tl.worldKey.equals(world.dimension()) && clazz.isInstance(tl)) {
|
||||
for (MinionListener listener : MinionPersistentState.get(world.getServer()).getMinionData(minionUuid).listeners()) {
|
||||
if (listener instanceof BlockEntityMinionListener<?> tl && tl.pos.equals(pos) && tl.worldKey.equals(world.getRegistryKey()) && clazz.isInstance(tl)) {
|
||||
return clazz.cast(tl);
|
||||
}
|
||||
}
|
||||
@@ -56,18 +56,18 @@ public abstract class BlockEntityMinionListener<E extends BlockEntity> implement
|
||||
return null;
|
||||
}
|
||||
|
||||
public static <L extends BlockEntityMinionListener<?>> Codec<L> getCodec(Function3<ResourceKey<Level>, BlockPos, UUID, L> constructor) {
|
||||
public static <L extends BlockEntityMinionListener<?>> Codec<L> getCodec(Function3<RegistryKey<World>, BlockPos, UUID, L> constructor) {
|
||||
return RecordCodecBuilder.create(instance ->
|
||||
instance.group(
|
||||
Level.RESOURCE_KEY_CODEC.fieldOf("world").forGetter(listener -> listener.worldKey),
|
||||
World.CODEC.fieldOf("world").forGetter(listener -> listener.worldKey),
|
||||
BlockPos.CODEC.fieldOf("pos").forGetter(listener -> listener.pos),
|
||||
UUIDUtil.AUTHLIB_CODEC.fieldOf("minionUuid").forGetter(listener -> listener.minionUuid)
|
||||
Uuids.CODEC.fieldOf("minionUuid").forGetter(listener -> listener.minionUuid)
|
||||
).apply(instance, constructor));
|
||||
}
|
||||
|
||||
private BlockEntityState getBlockEntityState(MinecraftServer server) {
|
||||
Level world = server.getLevel(worldKey);
|
||||
if(world == null || !world.isLoaded(pos)) {
|
||||
World world = server.getWorld(worldKey);
|
||||
if(world == null || !world.isPosLoaded(pos)) {
|
||||
return BlockEntityState.UNLOADED;
|
||||
}
|
||||
|
||||
@@ -79,8 +79,8 @@ public abstract class BlockEntityMinionListener<E extends BlockEntity> implement
|
||||
}
|
||||
|
||||
public Optional<E> getBlockEntity(MinecraftServer server) {
|
||||
Level world = server.getLevel(worldKey);
|
||||
if(world != null && world.isLoaded(pos)) {
|
||||
World world = server.getWorld(worldKey);
|
||||
if(world != null && world.isPosLoaded(pos)) {
|
||||
return world.getBlockEntity(pos, type);
|
||||
}
|
||||
return Optional.empty();
|
||||
@@ -94,15 +94,15 @@ public abstract class BlockEntityMinionListener<E extends BlockEntity> implement
|
||||
return false;
|
||||
}
|
||||
|
||||
public void add(MinecraftServer server) {
|
||||
MinionPersistentState.get(server).getMinionData(minionUuid).getListeners().addListener(this);
|
||||
MinionPersistentState.get(server).setDirty();
|
||||
this.minion = (MinionFakePlayer) server.getPlayerList().getPlayer(minionUuid);
|
||||
protected void add(MinecraftServer server) {
|
||||
MinionPersistentState.get(server).getMinionData(minionUuid).listeners().addListener(this);
|
||||
MinionPersistentState.get(server).markDirty();
|
||||
this.minion = (MinionFakePlayer) server.getPlayerManager().getPlayer(minionUuid);
|
||||
}
|
||||
|
||||
public void remove(MinecraftServer server) {
|
||||
MinionPersistentState.get(server).getMinionData(minionUuid).getListeners().removeListener(this);
|
||||
MinionPersistentState.get(server).setDirty();
|
||||
MinionPersistentState.get(server).getMinionData(minionUuid).listeners().removeListener(this);
|
||||
MinionPersistentState.get(server).markDirty();
|
||||
}
|
||||
|
||||
public enum BlockEntityState {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package io.github.skippyall.minions.listener;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CopyOnWriteArraySet;
|
||||
|
||||
public class ListenerManager<T> implements Iterable<T> {
|
||||
protected final Set<T> listeners;
|
||||
|
||||
public ListenerManager() {
|
||||
this(new CopyOnWriteArraySet<>());
|
||||
}
|
||||
|
||||
protected ListenerManager(Set<T> listeners) {
|
||||
this.listeners = listeners;
|
||||
}
|
||||
|
||||
public void addListener(T listener) {
|
||||
listeners.add(listener);
|
||||
}
|
||||
|
||||
public void removeListener(T listener) {
|
||||
listeners.remove(listener);
|
||||
}
|
||||
|
||||
public boolean hasListener(T listener) {
|
||||
return listeners.contains(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Iterator<T> iterator() {
|
||||
return listeners.iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return super.equals(obj);
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package io.github.skippyall.minions.listener
|
||||
|
||||
import java.util.concurrent.CopyOnWriteArraySet
|
||||
|
||||
open class ListenerManager<T>(
|
||||
protected val listeners: MutableSet<T> = CopyOnWriteArraySet(),
|
||||
val onChange: () -> Unit = {},
|
||||
) : MutableIterable<T> by listeners {
|
||||
|
||||
fun addListener(listener: T) {
|
||||
listeners.add(listener)
|
||||
onChange()
|
||||
}
|
||||
|
||||
fun removeListener(listener: T) {
|
||||
listeners.remove(listener)
|
||||
onChange()
|
||||
}
|
||||
|
||||
override fun iterator(): MutableIterator<T> {
|
||||
val iterator = listeners.iterator()
|
||||
return object : MutableIterator<T> by iterator {
|
||||
override fun remove() {
|
||||
iterator.remove()
|
||||
onChange()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package io.github.skippyall.minions.listener;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import net.minecraft.registry.Registry;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
import net.minecraft.util.Identifier;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CopyOnWriteArraySet;
|
||||
|
||||
public class SerializableListenerManager<T extends SerializableListenerManager.SerializableListener> extends ListenerManager<T> {
|
||||
private final Registry<Codec<? extends T>> registry;
|
||||
|
||||
public SerializableListenerManager(Registry<Codec<? extends T>> registry) {
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
private SerializableListenerManager(Registry<Codec<? extends T>> registry, Set<T> listeners) {
|
||||
super(listeners);
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
public static <T extends SerializableListener> Codec<SerializableListenerManager<T>> getCodec(Registry<Codec<? extends T>> registry) {
|
||||
return registry.getCodec().<T>dispatch(
|
||||
listener -> listener.getCodecId().map(registry::get).orElse(Codec.unit(null)),
|
||||
codec -> codec.fieldOf("data")
|
||||
).listOf().xmap(
|
||||
list -> new SerializableListenerManager<>(registry, new CopyOnWriteArraySet<>(list)),
|
||||
manager -> {
|
||||
List<T> serializableListeners = new ArrayList<>();
|
||||
for(T listener : manager.listeners) {
|
||||
if(listener.getCodecId().isPresent()) {
|
||||
serializableListeners.add(listener);
|
||||
}
|
||||
}
|
||||
return serializableListeners;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
public void save(WriteView view) {
|
||||
WriteView.ListView listView = view.getList("listeners");
|
||||
for (T listener : listeners) {
|
||||
if(listener.getCodecId().isPresent()) {
|
||||
WriteView listenerView = listView.add();
|
||||
Codec<? extends T> codec = registry.get(listener.getCodecId().get());
|
||||
listenerView.put("id", Identifier.CODEC, listener.getCodecId().get());
|
||||
//noinspection unchecked
|
||||
listenerView.put("data", (Codec<T>) codec, listener);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void load(ReadView view) {
|
||||
ReadView.ListReadView listView = view.getListReadView("listeners");
|
||||
for (ReadView listenerView : listView) {
|
||||
Optional<Identifier> id = listenerView.read("id", Identifier.CODEC);
|
||||
if(id.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Codec<? extends T> codec = registry.get(id.get());
|
||||
|
||||
Optional<? extends T> listener = listenerView.read("data", codec);
|
||||
|
||||
if(listener.isPresent()) {
|
||||
listeners.add(listener.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public interface SerializableListener {
|
||||
default Optional<Identifier> getCodecId() {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package io.github.skippyall.minions.listener
|
||||
|
||||
import com.mojang.serialization.Codec
|
||||
import com.mojang.serialization.MapCodec
|
||||
import io.github.skippyall.minions.listener.SerializableListenerManager.SerializableListener
|
||||
import net.minecraft.core.Registry
|
||||
import net.minecraft.resources.Identifier
|
||||
import java.util.*
|
||||
import java.util.concurrent.CopyOnWriteArraySet
|
||||
|
||||
class SerializableListenerManager<T : SerializableListener>(
|
||||
listeners: MutableSet<T> = CopyOnWriteArraySet(),
|
||||
onChange: () -> Unit = {},
|
||||
) : ListenerManager<T>(listeners, onChange) {
|
||||
|
||||
interface SerializableListener {
|
||||
val codecId: Optional<Identifier>
|
||||
get() = Optional.empty<Identifier>()
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
@JvmOverloads
|
||||
fun <T : SerializableListener> getCodec(
|
||||
registry: Registry<Codec<out T>>,
|
||||
onChange: () -> Unit = {},
|
||||
): Codec<SerializableListenerManager<T>> {
|
||||
return registry.byNameCodec().dispatch(
|
||||
{ listener -> listener.codecId.map(registry::getValue)
|
||||
.orElseGet { MapCodec.unitCodec(null) }
|
||||
},
|
||||
{ codec -> codec.fieldOf("data") }
|
||||
).listOf().xmap(
|
||||
{ list -> SerializableListenerManager<T>(CopyOnWriteArraySet<T>(list), onChange) },
|
||||
{ manager ->
|
||||
val serializableListeners: MutableList<T> = mutableListOf()
|
||||
for (listener in manager.listeners) {
|
||||
if (listener.codecId.isPresent) {
|
||||
serializableListeners.add(listener)
|
||||
}
|
||||
}
|
||||
return@xmap serializableListeners
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
@NullMarked
|
||||
package io.github.skippyall.minions.listener;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
@@ -2,7 +2,7 @@ package io.github.skippyall.minions.minion;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.util.Identifier;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
@@ -10,7 +10,7 @@ import java.util.Objects;
|
||||
|
||||
public class MinionConfig {
|
||||
public static final Codec<MinionConfig> CODEC = Codec.<Option<?>, Object>dispatchedMap(
|
||||
MinionRegistries.MINION_CONFIG_OPTIONS.byNameCodec(),
|
||||
MinionRegistries.MINION_CONFIG_OPTIONS.getCodec(),
|
||||
Option::codec
|
||||
).xmap(MinionConfig::new, config -> config.values);
|
||||
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package io.github.skippyall.minions.minion;
|
||||
|
||||
import com.mojang.authlib.properties.PropertyMap;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import io.github.skippyall.minions.listener.SerializableListenerManager;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.util.Uuids;
|
||||
import net.minecraft.util.dynamic.Codecs;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public record MinionData(
|
||||
UUID uuid,
|
||||
String name,
|
||||
Optional<PropertyMap> skin,
|
||||
boolean isSpawned,
|
||||
SerializableListenerManager<MinionListener> listeners,
|
||||
MinionConfig config
|
||||
) {
|
||||
public static final Codec<MinionData> CODEC = RecordCodecBuilder.create(instance ->
|
||||
instance.group(
|
||||
Uuids.CODEC.fieldOf("uuid").forGetter(MinionData::uuid),
|
||||
Codec.STRING.fieldOf("name").forGetter(MinionData::name),
|
||||
Codecs.GAME_PROFILE_PROPERTY_MAP.optionalFieldOf("skin").forGetter(MinionData::skin),
|
||||
Codec.BOOL.optionalFieldOf("isSpawned", false).forGetter(MinionData::isSpawned),
|
||||
SerializableListenerManager.getCodec(MinionRegistries.MINION_LISTENER_CODECS).optionalFieldOf("listeners").xmap(
|
||||
optional -> optional.orElseGet(() -> new SerializableListenerManager<>(MinionRegistries.MINION_LISTENER_CODECS)),
|
||||
Optional::of
|
||||
).forGetter(MinionData::listeners),
|
||||
MinionConfig.CODEC.optionalFieldOf("config", new MinionConfig()).forGetter(MinionData::config)
|
||||
).apply(instance, MinionData::new)
|
||||
);
|
||||
|
||||
public static MinionData createDefault(MinecraftServer server) {
|
||||
return new MinionData(
|
||||
UUID.randomUUID(),
|
||||
MinionProfileUtils.newDefaultMinionName(server),
|
||||
Optional.empty(),
|
||||
false,
|
||||
new SerializableListenerManager<>(MinionRegistries.MINION_LISTENER_CODECS),
|
||||
new MinionConfig()
|
||||
);
|
||||
}
|
||||
|
||||
public MinionData withName(String name) {
|
||||
return new MinionData(uuid, name, skin, isSpawned, listeners, config);
|
||||
}
|
||||
|
||||
public MinionData withSkin(Optional<PropertyMap> skin) {
|
||||
return new MinionData(uuid, name, skin, isSpawned, listeners, config);
|
||||
}
|
||||
|
||||
public MinionData withSpawned(boolean isSpawned) {
|
||||
return new MinionData(uuid, name, skin, isSpawned, listeners, config);
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package io.github.skippyall.minions.minion
|
||||
|
||||
import com.mojang.authlib.properties.PropertyMap
|
||||
import com.mojang.serialization.Codec
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder
|
||||
import io.github.skippyall.minions.listener.SerializableListenerManager
|
||||
import io.github.skippyall.minions.registration.MinionRegistries
|
||||
import net.minecraft.core.UUIDUtil
|
||||
import net.minecraft.server.MinecraftServer
|
||||
import net.minecraft.util.ExtraCodecs
|
||||
import java.util.*
|
||||
import kotlin.properties.ReadWriteProperty
|
||||
import kotlin.reflect.KProperty
|
||||
|
||||
class MinionData(
|
||||
initialUuid: UUID,
|
||||
initialName: String,
|
||||
initialSkin: Optional<PropertyMap>,
|
||||
initialIsSpawned: Boolean,
|
||||
val listeners: SerializableListenerManager<MinionListener>,
|
||||
initialConfig: MinionConfig,
|
||||
var onDirty: Runnable = {},
|
||||
) {
|
||||
var uuid by DirtyProperty(initialUuid, this::setDirty)
|
||||
var name by DirtyProperty(initialName, this::setDirty)
|
||||
var skin by DirtyProperty(initialSkin, this::setDirty)
|
||||
var isSpawned by DirtyProperty(initialIsSpawned, this::setDirty)
|
||||
var config by DirtyProperty(initialConfig, this::setDirty)
|
||||
|
||||
fun setDirty() {
|
||||
this@MinionData.onDirty.run()
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmField
|
||||
val CODEC: Codec<MinionData> =
|
||||
RecordCodecBuilder.create { instance ->
|
||||
instance.group(
|
||||
UUIDUtil.AUTHLIB_CODEC.fieldOf("uuid").forGetter(MinionData::uuid),
|
||||
Codec.STRING.fieldOf("name").forGetter(MinionData::name),
|
||||
ExtraCodecs.PROPERTY_MAP.optionalFieldOf("skin").forGetter(MinionData::skin),
|
||||
Codec.BOOL.optionalFieldOf("isSpawned", false).forGetter(MinionData::isSpawned),
|
||||
SerializableListenerManager.getCodec<MinionListener>(MinionRegistries.MINION_LISTENER_CODECS)
|
||||
.optionalFieldOf("listeners").xmap(
|
||||
{ optional -> optional.orElseGet { SerializableListenerManager() } },
|
||||
Optional<SerializableListenerManager<MinionListener>>::of
|
||||
).forGetter(MinionData::listeners),
|
||||
MinionConfig.CODEC.optionalFieldOf("config", MinionConfig())
|
||||
.forGetter(MinionData::config)
|
||||
).apply(
|
||||
instance,
|
||||
::MinionData
|
||||
)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun createDefault(server: MinecraftServer): MinionData {
|
||||
return MinionData(
|
||||
UUID.randomUUID(),
|
||||
MinionProfileUtils.newDefaultMinionName(server),
|
||||
Optional.empty<PropertyMap>(),
|
||||
false,
|
||||
SerializableListenerManager(),
|
||||
MinionConfig()
|
||||
) {
|
||||
MinionPersistentState.get(server).isDirty = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DirtyProperty<V>(var value: V, val onDirty: () -> Unit) : ReadWriteProperty<Any?, V> {
|
||||
override fun getValue(thisRef: Any?, property: KProperty<*>): V {
|
||||
return value
|
||||
}
|
||||
|
||||
override fun setValue(thisRef: Any?, property: KProperty<*>, value: V) {
|
||||
this.value = value
|
||||
onDirty()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,63 +1,91 @@
|
||||
package io.github.skippyall.minions.minion;
|
||||
|
||||
import eu.pb4.polymer.core.api.item.PolymerItem;
|
||||
import eu.pb4.polymer.core.api.item.PolymerItemUtils;
|
||||
import io.github.skippyall.minions.gui.MinionLookGui;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.registration.MinionComponentTypes;
|
||||
import net.minecraft.component.DataComponentTypes;
|
||||
import net.minecraft.component.type.TooltipDisplayComponent;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.ItemUsageContext;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.item.tooltip.TooltipType;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.context.UseOnContext;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.phys.Vec2;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.ActionResult;
|
||||
import net.minecraft.util.Hand;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.math.Vec2f;
|
||||
import net.minecraft.world.World;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import xyz.nucleoid.packettweaker.PacketContext;
|
||||
|
||||
public class MinionItem extends Item {
|
||||
public MinionItem(Properties settings) {
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class MinionItem extends Item implements PolymerItem {
|
||||
public MinionItem(Settings settings) {
|
||||
super(settings);
|
||||
}
|
||||
|
||||
/*@Override
|
||||
public void appendHoverText(ItemStack stack, TooltipContext context, TooltipDisplay component, Consumer<Component> tooltip, TooltipFlag type) {
|
||||
//MinionData data = getData(stack);
|
||||
//if(data != null) {
|
||||
// tooltip.accept(Component.translatable("minions.minion_item.tooltip", data.name()));
|
||||
//}
|
||||
}*/
|
||||
|
||||
@Override
|
||||
public InteractionResult use(Level world, Player user, InteractionHand hand) {
|
||||
if(user instanceof ServerPlayer serverPlayer) {
|
||||
ItemStack stack = user.getItemInHand(hand);
|
||||
new MinionLookGui(serverPlayer, stack);
|
||||
return InteractionResult.SUCCESS;
|
||||
}
|
||||
|
||||
return InteractionResult.SUCCESS_SERVER;
|
||||
public @Nullable Identifier getPolymerItemModel(ItemStack stack, PacketContext context) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InteractionResult useOn(UseOnContext context) {
|
||||
if(!context.getLevel().isClientSide()) {
|
||||
MinionData data = getDataOrDefault(context.getLevel().getServer(), context.getItemInHand());
|
||||
MinionFakePlayer.spawnMinion(data, (ServerLevel) context.getLevel(), context.getClickedPos().getCenter().add(0,0.5,0), new Vec2(0, 0));
|
||||
public Item getPolymerItem(ItemStack itemStack, PacketContext player) {
|
||||
return Items.ARMOR_STAND;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getPolymerItemStack(ItemStack stack, TooltipType tooltipType, PacketContext player) {
|
||||
ItemStack out = PolymerItemUtils.createItemStack(stack, tooltipType, player);
|
||||
out.set(DataComponentTypes.ENCHANTMENT_GLINT_OVERRIDE, true);
|
||||
return out;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void appendTooltip(ItemStack stack, TooltipContext context, TooltipDisplayComponent component, Consumer<Text> tooltip, TooltipType type) {
|
||||
MinionData data = null /*getData(stack)*/;
|
||||
if(data != null) {
|
||||
tooltip.accept(Text.translatable("minions.minion_item.tooltip", data.name()));
|
||||
}
|
||||
context.getItemInHand().shrink(1);
|
||||
return InteractionResult.SUCCESS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActionResult use(World world, PlayerEntity user, Hand hand) {
|
||||
if(user instanceof ServerPlayerEntity serverPlayer) {
|
||||
ItemStack stack = user.getStackInHand(hand);
|
||||
MinionLookGui.open(serverPlayer, stack);
|
||||
return ActionResult.SUCCESS;
|
||||
}
|
||||
|
||||
return ActionResult.SUCCESS_SERVER;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActionResult useOnBlock(ItemUsageContext context) {
|
||||
if(!context.getWorld().isClient) {
|
||||
MinionData data = getDataOrDefault(context.getWorld().getServer(), context.getStack());
|
||||
MinionFakePlayer.spawnMinion(data, (ServerWorld) context.getWorld(), context.getBlockPos().toCenterPos().add(0,0.5,0), new Vec2f(0, 0));
|
||||
}
|
||||
context.getStack().decrement(1);
|
||||
return ActionResult.SUCCESS;
|
||||
}
|
||||
|
||||
public static void setData(MinecraftServer server, MinionData data, ItemStack item) {
|
||||
item.set(MinionComponentTypes.MINION_DATA, data.getUuid());
|
||||
item.set(MinionComponentTypes.MINION_DATA, data.uuid());
|
||||
MinionPersistentState.get(server).updateMinionData(data);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static MinionData getData(MinecraftServer server, ItemStack item) {
|
||||
if(item.has(MinionComponentTypes.MINION_DATA)) {
|
||||
if(item.contains(MinionComponentTypes.MINION_DATA)) {
|
||||
return MinionPersistentState.get(server).getMinionData(item.get(MinionComponentTypes.MINION_DATA));
|
||||
}
|
||||
return null;
|
||||
@@ -73,6 +101,6 @@ public class MinionItem extends Item {
|
||||
}
|
||||
|
||||
public static boolean containsData(ItemStack item) {
|
||||
return item.has(MinionComponentTypes.MINION_DATA);
|
||||
return item.contains(MinionComponentTypes.MINION_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package io.github.skippyall.minions.minion;
|
||||
|
||||
import io.github.skippyall.minions.listener.SerializableListenerManager;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import io.github.skippyall.minions.listener.SerializableListenerManager;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public interface MinionListener extends SerializableListenerManager.SerializableListener {
|
||||
default void onMinionSpawn(MinionFakePlayer minion) {}
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
package io.github.skippyall.minions.minion;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import io.github.skippyall.minions.Minions;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.saveddata.SavedData;
|
||||
import net.minecraft.world.level.saveddata.SavedDataType;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import net.minecraft.world.PersistentState;
|
||||
import net.minecraft.world.PersistentStateType;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -15,15 +12,10 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public class MinionPersistentState extends SavedData {
|
||||
public class MinionPersistentState extends PersistentState {
|
||||
public static final Codec<MinionPersistentState> CODEC = MinionData.CODEC.listOf().xmap(MinionPersistentState::new, MinionPersistentState::getMinionDataList);
|
||||
|
||||
public static SavedDataType<MinionPersistentState> TYPE = new SavedDataType<>(
|
||||
Identifier.fromNamespaceAndPath(Minions.MOD_ID, "minion"),
|
||||
MinionPersistentState::new,
|
||||
MinionPersistentState.CODEC,
|
||||
null
|
||||
);
|
||||
public static PersistentStateType<MinionPersistentState> TYPE = new PersistentStateType<>("minion", MinionPersistentState::new, MinionPersistentState.CODEC, null);
|
||||
|
||||
private final Map<UUID, MinionData> minionData = new HashMap<>();
|
||||
|
||||
@@ -33,12 +25,11 @@ public class MinionPersistentState extends SavedData {
|
||||
|
||||
public MinionPersistentState(List<MinionData> dataList) {
|
||||
for (MinionData data : dataList) {
|
||||
data.setOnDirty(this::setDirty);
|
||||
minionData.put(data.getUuid(), data);
|
||||
minionData.put(data.uuid(), data);
|
||||
}
|
||||
}
|
||||
|
||||
public @Nullable MinionData getMinionData(UUID uuid) {
|
||||
public MinionData getMinionData(UUID uuid) {
|
||||
return minionData.get(uuid);
|
||||
}
|
||||
|
||||
@@ -51,9 +42,8 @@ public class MinionPersistentState extends SavedData {
|
||||
}
|
||||
|
||||
public void updateMinionData(MinionData data) {
|
||||
minionData.put(data.getUuid(), data);
|
||||
data.setOnDirty(this::setDirty);
|
||||
setDirty();
|
||||
minionData.put(data.uuid(), data);
|
||||
markDirty();
|
||||
}
|
||||
|
||||
public boolean isMinion(UUID uuid) {
|
||||
@@ -66,11 +56,11 @@ public class MinionPersistentState extends SavedData {
|
||||
|
||||
public Optional<MinionData> getMinionWithName(String name) {
|
||||
return minionData.values().stream()
|
||||
.filter(data -> data.getName().equals(name))
|
||||
.filter(data -> data.name().equals(name))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
public static MinionPersistentState get(MinecraftServer server) {
|
||||
return server.getLevel(Level.OVERWORLD).getDataStorage().computeIfAbsent(TYPE);
|
||||
return server.getWorld(World.OVERWORLD).getPersistentStateManager().getOrCreate(TYPE);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,10 +5,9 @@ import com.mojang.authlib.properties.PropertyMap;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import io.github.skippyall.minions.MinionsConfig;
|
||||
import io.github.skippyall.minions.gui.input.Result;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.util.StringUtil;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.StringHelper;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -19,33 +18,36 @@ public class MinionProfileUtils {
|
||||
return MinionsConfig.get().minion.minionPrefix;
|
||||
}
|
||||
|
||||
public static GameProfile makeNewMinionProfile(@Nullable UUID uuidMinion, String username, @Nullable PropertyMap skin) {
|
||||
public static GameProfile makeNewMinionProfile(UUID uuidMinion, String username, PropertyMap skin) {
|
||||
if(uuidMinion == null) {
|
||||
uuidMinion = UUID.randomUUID();
|
||||
}
|
||||
|
||||
GameProfile newProfile = new GameProfile(uuidMinion, username, skin != null ? skin : PropertyMap.EMPTY);
|
||||
GameProfile newProfile = new GameProfile(uuidMinion, username);
|
||||
if (skin != null) {
|
||||
newProfile.getProperties().putAll(skin);
|
||||
}
|
||||
LOGGER.info("Minion Profile: {}", newProfile);
|
||||
return newProfile;
|
||||
}
|
||||
|
||||
public static Result<String, Component> checkMinionNameWithoutPrefix(MinecraftServer server, String name) {
|
||||
public static Result<String, Text> checkMinionNameWithoutPrefix(MinecraftServer server, String name) {
|
||||
for(char c : name.toCharArray()) {
|
||||
if(!StringReader.isAllowedInUnquotedString(c)) {
|
||||
return new Result.Error<>(Component.translatable("minions.generic.name.invalid_char"));
|
||||
return new Result.Error<>(Text.translatable("minions.generic.name.invalid_char"));
|
||||
}
|
||||
}
|
||||
|
||||
if((getPrefix() + name).length() > 16) {
|
||||
return new Result.Error<>(Component.translatable("minions.generic.name.too_long"));
|
||||
return new Result.Error<>(Text.translatable("minions.generic.name.too_long"));
|
||||
}
|
||||
|
||||
if(!StringUtil.isValidPlayerName(getPrefix() + name)) {
|
||||
return new Result.Error<>(Component.translatable("minions.generic.name.invalid"));
|
||||
if(!StringHelper.isValidPlayerName(getPrefix() + name)) {
|
||||
return new Result.Error<>(Text.translatable("minions.generic.name.invalid"));
|
||||
}
|
||||
|
||||
if(MinionPersistentState.get(server).isMinionNameTaken(getPrefix() + name)) {
|
||||
return new Result.Error<>(Component.translatable("minions.generic.name.taken"));
|
||||
return new Result.Error<>(Text.translatable("minions.generic.name.taken"));
|
||||
}
|
||||
|
||||
return new Result.Success<>(name);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user