Compare commits

..
7 Commits
48 changed files with 682 additions and 461 deletions

No files matched your search

-17
View File
@@ -1,17 +0,0 @@
name: Optimize images
on:
pull_request:
branches: [ master, main, release/** ]
paths:
- "**/*.png"
push:
branches: [ master, main, release/** ]
paths:
- "**/*.png"
jobs:
optimize-images:
uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/optimize-images.yml@master
secrets: inherit
+2 -3
View File
@@ -1,10 +1,9 @@
// Add your dependencies here // Add your dependencies here
dependencies { dependencies {
api("com.github.GTNewHorizons:GTNHLib:0.9.47:dev") api("com.github.GTNewHorizons:GTNHLib:0.7.1:dev")
implementation("com.github.GTNewHorizons:NotEnoughItems:2.8.84-GTNH:dev") implementation("com.github.GTNewHorizons:NotEnoughItems:2.8.21-GTNH:dev")
testImplementation(platform('org.junit:junit-bom:5.9.2')) testImplementation(platform('org.junit:junit-bom:5.9.2'))
testImplementation('org.junit.jupiter:junit-jupiter') testImplementation('org.junit.jupiter:junit-jupiter')
testRuntimeOnly ('org.junit.platform:junit-platform-launcher')
} }
+3 -36
View File
@@ -39,33 +39,9 @@ remoteMappings = https\://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/co
# `./gradlew runClient --username=AnotherPlayer`, or configuring this command in your IDE. # `./gradlew runClient --username=AnotherPlayer`, or configuring this command in your IDE.
developmentEnvironmentUserName = Developer developmentEnvironmentUserName = Developer
# Enables modern Java syntax support. Valid values: # Enables using modern Java syntax (up to version 17) via Jabel, while still targeting JVM 8.
# - false: No modern syntax, Java 8 only # See https://github.com/bsideup/jabel for details on how this works.
# - jabel: Jabel syntax-only support, compiles to J8 bytecode enableModernJavaSyntax = true
# - jvmDowngrader: Full modern Java via JVM Downgrader (syntax + stdlib APIs)
# - modern: Native modern Java bytecode, no downgrading
enableModernJavaSyntax = jabel
# If set, ignores the above setting and compiles with the given toolchain. This may cause unexpected issues,
# and should *not* be used in most situations. -1 disables this.
# forceToolchainVersion = -1
# Target JVM version for JVM Downgrader bytecode downgrading.
# Only used when enableModernJavaSyntax = jvmDowngrader
# downgradeTargetVersion = 8
# Comma-separated list of Java versions for multi-release jar support (JVM Downgrader only).
# Classes will be available in META-INF/versions/N/ for each version N in this list.
# Default: "21,25" (J25+ gets native classes, J21-24 gets partial downgrade, J8-20 gets full downgrade).
# jvmDowngraderMultiReleaseVersions = 21,25
# Specifies how JVM Downgrader API stubs are provided. Options:
# - shade: Shade minimized stubs into the jar
# - gtnhlib: GTNHLib provides stubs at runtime (adds version constraint)
# - external: Another dependency provides stubs (no constraint, no warning)
# - (empty): Warning reminding you to configure stubs
# Note: 'shade' option requires you to verify license compliance, see: https://github.com/unimined/JvmDowngrader/blob/main/LICENSE.md
# jvmDowngraderStubsProvider =
# Enables injecting missing generics into the decompiled source code for a better coding experience. # Enables injecting missing generics into the decompiled source code for a better coding experience.
# Turns most publicly visible List, Map, etc. into proper List<E>, Map<K, V> types. # Turns most publicly visible List, Map, etc. into proper List<E>, Map<K, V> types.
@@ -198,12 +174,6 @@ curseForgeRelations =
# projects. New projects should not use this parameter. # projects. New projects should not use this parameter.
# customArchiveBaseName = # customArchiveBaseName =
# Optional parameter to customize the default working directory used by the runClient* tasks. Relative to the project directory.
# runClientWorkingDirectory = run/client
# Optional parameter to customize the default working directory used by the runServer* tasks. Relative to the project directory.
# runServerWorkingDirectory = run/server
# Optional parameter to have the build automatically fail if an illegal version is used. # Optional parameter to have the build automatically fail if an illegal version is used.
# This can be useful if you e.g. only want to allow versions in the form of '1.1.xxx'. # This can be useful if you e.g. only want to allow versions in the form of '1.1.xxx'.
# The check is ONLY performed if the version is a git tag. # The check is ONLY performed if the version is a git tag.
@@ -233,6 +203,3 @@ curseForgeRelations =
# This is meant to be set in $HOME/.gradle/gradle.properties. # This is meant to be set in $HOME/.gradle/gradle.properties.
# ideaCheckSpotlessOnBuild = true # ideaCheckSpotlessOnBuild = true
# Non-GTNH properties
org.gradle.configuration-cache = true
org.gradle.parallel = true
-12
View File
@@ -1,12 +0,0 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/1630f7ebef05444cb27a2709ea0249b3/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/cd495626d2ee49a75447e3fdc6afb287/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/1630f7ebef05444cb27a2709ea0249b3/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/cd495626d2ee49a75447e3fdc6afb287/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/d4fd992c9557644e637ebe98263e0ae7/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/faa12903720d410b387cc69ccafb1a74/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/1630f7ebef05444cb27a2709ea0249b3/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/cd495626d2ee49a75447e3fdc6afb287/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/a4c09dd2e2d7079373d30e524bbc2829/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/8e1d9ee5d0f13e442218f6884a306da1/redirect
toolchainVersion=25
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
Vendored
+6 -3
View File
@@ -1,7 +1,7 @@
#!/bin/sh #!/bin/sh
# #
# Copyright © 2015 the original authors. # Copyright © 2015-2021 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -57,7 +57,7 @@
# Darwin, MinGW, and NonStop. # Darwin, MinGW, and NonStop.
# #
# (3) This script is generated from the Groovy template # (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/b631911858264c0b6e4d6603d677ff5218766cee/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project. # within the Gradle project.
# #
# You can find Gradle at https://github.com/gradle/gradle/. # You can find Gradle at https://github.com/gradle/gradle/.
@@ -114,6 +114,7 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;; NONSTOP* ) nonstop=true ;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM. # Determine the Java command to use to start the JVM.
@@ -171,6 +172,7 @@ fi
# For Cygwin or MSYS, switch paths to Windows format before running java # For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" ) JAVACMD=$( cygpath --unix "$JAVACMD" )
@@ -210,7 +212,8 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
set -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ -classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@" "$@"
# Stop when "xargs" is not available. # Stop when "xargs" is not available.
Vendored
+2 -1
View File
@@ -70,10 +70,11 @@ goto fail
:execute :execute
@rem Setup the command line @rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @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" %* "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
+1 -1
View File
@@ -17,7 +17,7 @@ pluginManagement {
} }
plugins { plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '2.0.24' id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.47'
} }
@@ -5,7 +5,11 @@ import static java.lang.Math.abs;
import net.minecraft.util.Vec3; import net.minecraft.util.Vec3;
import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.common.util.ForgeDirection;
import org.joml.Vector3i;
import com.gtnewhorizon.structurelib.alignment.enumerable.Direction; import com.gtnewhorizon.structurelib.alignment.enumerable.Direction;
import com.gtnewhorizon.structurelib.coords.CoordinateSystem;
import com.gtnewhorizon.structurelib.coords.Position;
import com.gtnewhorizon.structurelib.util.Vec3Impl; import com.gtnewhorizon.structurelib.util.Vec3Impl;
public class IntegerAxisSwap { public class IntegerAxisSwap {
@@ -91,4 +95,32 @@ public class IntegerAxisSwap {
out[1] = forFirstAxis.get1() * point[0] + forSecondAxis.get1() * point[1] + forThirdAxis.get1() * point[2]; out[1] = forFirstAxis.get1() * point[0] + forSecondAxis.get1() * point[1] + forThirdAxis.get1() * point[2];
out[2] = forFirstAxis.get2() * point[0] + forSecondAxis.get2() * point[1] + forThirdAxis.get2() * point[2]; out[2] = forFirstAxis.get2() * point[0] + forSecondAxis.get2() * point[1] + forThirdAxis.get2() * point[2];
} }
public Vector3i translate(Vector3i point) {
return new Vector3i(
forFirstAxis.get0() * point.x() + forFirstAxis.get1() * point.y() + forFirstAxis.get2() * point.z(),
forSecondAxis.get0() * point.x() + forSecondAxis.get1() * point.y() + forSecondAxis.get2() * point.z(),
forThirdAxis.get0() * point.x() + forThirdAxis.get1() * point.y() + forThirdAxis.get2() * point.z());
}
public Vector3i inverseTranslate(Vector3i point) {
return new Vector3i(
forFirstAxis.get0() * point.x() + forSecondAxis.get0() * point.y() + forThirdAxis.get0() * point.z(),
forFirstAxis.get1() * point.x() + forSecondAxis.get1() * point.y() + forThirdAxis.get1() * point.z(),
forFirstAxis.get2() * point.x() + forSecondAxis.get2() * point.y() + forThirdAxis.get2() * point.z());
}
public <C extends CoordinateSystem<C, ?>> Position<C> translate(Position<?> point) {
return new Position<>(
forFirstAxis.get0() * point.x() + forFirstAxis.get1() * point.y() + forFirstAxis.get2() * point.z(),
forSecondAxis.get0() * point.x() + forSecondAxis.get1() * point.y() + forSecondAxis.get2() * point.z(),
forThirdAxis.get0() * point.x() + forThirdAxis.get1() * point.y() + forThirdAxis.get2() * point.z());
}
public <C extends CoordinateSystem<C, ?>> Position<C> inverseTranslate(Position<?> point) {
return new Position<>(
forFirstAxis.get0() * point.x() + forSecondAxis.get0() * point.y() + forThirdAxis.get0() * point.z(),
forFirstAxis.get1() * point.x() + forSecondAxis.get1() * point.y() + forThirdAxis.get1() * point.z(),
forFirstAxis.get2() * point.x() + forSecondAxis.get2() * point.y() + forThirdAxis.get2() * point.z());
}
} }
@@ -24,6 +24,7 @@ import net.minecraftforge.common.util.ForgeDirection;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.gtnewhorizon.structurelib.alignment.IAlignment; import com.gtnewhorizon.structurelib.alignment.IAlignment;
import com.gtnewhorizon.structurelib.alignment.IntegerAxisSwap; import com.gtnewhorizon.structurelib.alignment.IntegerAxisSwap;
import com.gtnewhorizon.structurelib.coords.StructureRelativeCoords;
import com.gtnewhorizon.structurelib.util.Vec3Impl; import com.gtnewhorizon.structurelib.util.Vec3Impl;
public enum ExtendedFacing { public enum ExtendedFacing {
@@ -166,6 +167,7 @@ public enum ExtendedFacing {
private final String name; private final String name;
private final IntegerAxisSwap integerAxisSwap; private final IntegerAxisSwap integerAxisSwap;
private final StructureRelativeCoords coordinateSystem;
ExtendedFacing(String name) { ExtendedFacing(String name) {
this.name = name; this.name = name;
@@ -247,6 +249,7 @@ public enum ExtendedFacing {
this.b = b; this.b = b;
this.c = c; this.c = c;
integerAxisSwap = new IntegerAxisSwap(a, b, c); integerAxisSwap = new IntegerAxisSwap(a, b, c);
coordinateSystem = new StructureRelativeCoords(integerAxisSwap);
} }
public static ExtendedFacing of(ForgeDirection direction, Rotation rotation, Flip flip) { public static ExtendedFacing of(ForgeDirection direction, Rotation rotation, Flip flip) {
@@ -437,4 +440,8 @@ public enum ExtendedFacing {
public ForgeDirection getRelativeForwardInWorld() { public ForgeDirection getRelativeForwardInWorld() {
return c.getOpposite(); return c.getOpposite();
} }
public StructureRelativeCoords asCoordinateSystem() {
return coordinateSystem;
}
} }
@@ -0,0 +1,40 @@
package com.gtnewhorizon.structurelib.coords;
/**
* Controller-relative coordinates. The controller is at 0,0,0. No axis swapping takes place, each axis points in the
* same directions as the matching world axis.
*/
public class ControllerRelativeCoords implements CoordinateSystem<ControllerRelativeCoords, WorldCoords> {
public final int controllerX, controllerY, controllerZ;
public ControllerRelativeCoords(int controllerX, int controllerY, int controllerZ) {
this.controllerX = controllerX;
this.controllerY = controllerY;
this.controllerZ = controllerZ;
}
@Override
public Position<ControllerRelativeCoords> translate(Position<WorldCoords> position) {
return translate(position, controllerX, controllerY, controllerZ);
}
@Override
public Position<WorldCoords> translateInverse(Position<ControllerRelativeCoords> position) {
return translateInverse(position, controllerX, controllerY, controllerZ);
}
public static Position<ControllerRelativeCoords> translate(Position<WorldCoords> position, int controllerX,
int controllerY, int controllerZ) {
position.sub(controllerX, controllerY, controllerZ);
return CoordinateSystem.transmute(position);
}
public static Position<WorldCoords> translateInverse(Position<ControllerRelativeCoords> position, int controllerX,
int controllerY, int controllerZ) {
position.add(controllerX, controllerY, controllerZ);
return CoordinateSystem.transmute(position);
}
}
@@ -0,0 +1,34 @@
package com.gtnewhorizon.structurelib.coords;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
/**
* A coordinate system is a statically-checked helper for determining which coordinates a {@link Position} has.
* Translation methods never copy a {@link Position} - if a position must remain unchanged, it must be copied
* separately. Most coordinate systems will have static methods that allow you to avoid allocations, though some (such
* as the ones provided by {@link ExtendedFacing#asCoordinateSystem()}) have no reason to be static.
*
* @param <Self>
* @param <Parent>
*/
public interface CoordinateSystem<Self extends CoordinateSystem<Self, Parent>, Parent extends CoordinateSystem<Parent, ?>> {
/**
* Translates a position from the parent coordinate system into this one.
*/
Position<Self> translate(Position<Parent> position);
/**
* Translates a position from this coordinate system into the parent.
*/
Position<Parent> translateInverse(Position<Self> position);
/**
* Helper method that converts a position's coordinate system. Should not be used unless you know it's correct.
*/
static <P1 extends CoordinateSystem<P1, ?>, P2 extends CoordinateSystem<P2, ?>> Position<P1> transmute(
Position<P2> pos) {
// noinspection unchecked
return (Position<P1>) pos;
}
}
@@ -0,0 +1,73 @@
package com.gtnewhorizon.structurelib.coords;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
import net.minecraft.world.ChunkPosition;
import org.joml.Vector3f;
import org.joml.Vector3i;
import com.gtnewhorizon.gtnhlib.blockpos.BlockPos;
import com.gtnewhorizon.structurelib.util.Vec3Impl;
/**
* A {@link BlockPos} with a statically-checked coordinate system.
*/
public class Position<C extends CoordinateSystem<C, ?>> extends BlockPos {
public Position() {
}
public Position(int x, int y, int z) {
super(x, y, z);
}
public Position(float x, float y, float z) {
super(MathHelper.floor_float(x), MathHelper.floor_float(y), MathHelper.floor_float(z));
}
public Position(double x, double y, double z) {
super(MathHelper.floor_double(x), MathHelper.floor_double(y), MathHelper.floor_double(z));
}
public Position(ChunkPosition chunkPosition) {
super(chunkPosition);
}
public Position(Vector3i v) {
super(v.x, v.y, v.z);
}
public Position(Vector3f v) {
this(v.x, v.y, v.z);
}
public Position(Vec3 v) {
this(v.xCoord, v.yCoord, v.zCoord);
}
public Position(Vec3Impl v) {
this(v.get0(), v.get1(), v.get2());
}
public Position<C> copy() {
return new Position<>(x, y, z);
}
public Vector3i toVector3i() {
return new Vector3i(x, y, z);
}
public Vector3f toVector3f() {
return new Vector3f(x, y, z);
}
public Vec3 toVec3() {
return Vec3.createVectorHelper(x, y, z);
}
public Vec3Impl toVec3Impl() {
return new Vec3Impl(x, y, z);
}
}
@@ -0,0 +1,38 @@
package com.gtnewhorizon.structurelib.coords;
/// The structure definition-local coords. 0,0,0 is the front-most left-most top-most element. Coordinates increase as
/// you go down, right, or back.
public class StructureDefinitionCoords implements CoordinateSystem<StructureDefinitionCoords, StructureRelativeCoords> {
public final int offsetX, offsetY, offsetZ;
public StructureDefinitionCoords(int offsetX, int offsetY, int offsetZ) {
this.offsetX = offsetX;
this.offsetY = offsetY;
this.offsetZ = offsetZ;
}
@Override
public Position<StructureDefinitionCoords> translate(Position<StructureRelativeCoords> position) {
return translate(position, offsetX, offsetY, offsetZ);
}
@Override
public Position<StructureRelativeCoords> translateInverse(Position<StructureDefinitionCoords> position) {
return translateInverse(position, offsetX, offsetY, offsetZ);
}
public static Position<StructureDefinitionCoords> translate(Position<StructureRelativeCoords> position, int offsetX,
int offsetY, int offsetZ) {
position.add(offsetX, offsetY, offsetZ);
return CoordinateSystem.transmute(position);
}
public static Position<StructureRelativeCoords> translateInverse(Position<StructureDefinitionCoords> position,
int offsetX, int offsetY, int offsetZ) {
position.sub(offsetX, offsetY, offsetZ);
return CoordinateSystem.transmute(position);
}
}
@@ -0,0 +1,31 @@
package com.gtnewhorizon.structurelib.coords;
import com.gtnewhorizon.structurelib.alignment.IntegerAxisSwap;
/**
* Coordinates relative to the structure. 0,0,0 is the controller. 0,0,1 is the block immediately behind the controller
* (looking at it from its face). 1,0,0 is the block to the right of the controller. 0,1,0 is the block below the
* controller.
*/
public class StructureRelativeCoords implements CoordinateSystem<StructureRelativeCoords, ControllerRelativeCoords> {
public final IntegerAxisSwap axisSwap;
public StructureRelativeCoords(IntegerAxisSwap axisSwap) {
this.axisSwap = axisSwap;
}
@Override
public Position<StructureRelativeCoords> translate(Position<ControllerRelativeCoords> position) {
position.set(axisSwap.translate(position));
return CoordinateSystem.transmute(position);
}
@Override
public Position<ControllerRelativeCoords> translateInverse(Position<StructureRelativeCoords> position) {
position.set(axisSwap.inverseTranslate(position));
return CoordinateSystem.transmute(position);
}
}
@@ -0,0 +1,21 @@
package com.gtnewhorizon.structurelib.coords;
/**
* World block coordinates
*/
public class WorldCoords implements CoordinateSystem<WorldCoords, WorldCoords> {
public static final WorldCoords INSTANCE = new WorldCoords();
private WorldCoords() {}
@Override
public Position<WorldCoords> translate(Position<WorldCoords> position) {
return position;
}
@Override
public Position<WorldCoords> translateInverse(Position<WorldCoords> position) {
return position;
}
}
@@ -261,11 +261,6 @@ public class GuiScreenConfigureChannels extends GuiContainer implements IGuiScre
switch (aKey) { switch (aKey) {
case Keyboard.KEY_TAB: case Keyboard.KEY_TAB:
if (key.isFocused()) { if (key.isFocused()) {
if (autoCompleteList.getSelectedElement() != null) {
key.setText(autoCompleteList.getSelectedElement());
return;
}
key.setFocused(false); key.setFocused(false);
value.setFocused(true); value.setFocused(true);
} else { } else {
@@ -3,8 +3,11 @@ package com.gtnewhorizon.structurelib.structure;
import static com.gtnewhorizon.structurelib.structure.IStructureWalker.ignoreBlockUnloaded; import static com.gtnewhorizon.structurelib.structure.IStructureWalker.ignoreBlockUnloaded;
import static com.gtnewhorizon.structurelib.structure.IStructureWalker.skipBlockUnloaded; import static com.gtnewhorizon.structurelib.structure.IStructureWalker.skipBlockUnloaded;
import java.util.List;
import java.util.function.Function; import java.util.function.Function;
import javax.annotation.Nonnull;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
@@ -15,6 +18,8 @@ import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor; import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor;
import com.gtnewhorizon.structurelib.alignment.constructable.ISurvivalConstructable; import com.gtnewhorizon.structurelib.alignment.constructable.ISurvivalConstructable;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing; import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.coords.Position;
import com.gtnewhorizon.structurelib.coords.StructureDefinitionCoords;
/** /**
* This is the structure definition of your multi. You will have one of these for each multi. * This is the structure definition of your multi. You will have one of these for each multi.
@@ -335,6 +340,49 @@ public interface IStructureDefinition<T> {
"customIterate"); "customIterate");
} }
/**
* Gets the controller position for a piece. Controller positions are denoted by a tilde.
*
* @param piece The piece name
* @return The controller position, or null if it doesn't exist for the given piece
*/
Position<StructureDefinitionCoords> getControllerPosition(String piece);
/**
* Gets the coordinate system for a piece. This is used to translate structure definition coordinates into structure
* relative coordinates.
*
* @param piece The piece
* @return The coordinate system
* @throws IllegalArgumentException When the piece does not exist
*/
StructureDefinitionCoords getCoordinateSystem(String piece);
/**
* Gets a socket from a piece.
*
* @param piece The piece name
* @param socket The socket character
* @return The socket's position
* @throws IllegalArgumentException When the piece does not exist
* @throws IllegalArgumentException When the socket does not exist
* @throws IllegalStateException When more than one socket exists with this character
* @see StructureDefinition.Builder#addSocket(char, char)
*/
Position<StructureDefinitionCoords> getSocket(String piece, char socket);
/**
* Gets all sockets with a given character for a piece.
*
* @param piece The piece name
* @param socket The socket character
* @return The list of socket positions, or an empty list if the socket is not present
* @throws IllegalArgumentException When the piece does not exist
* @see StructureDefinition.Builder#addSocket(char, char)
*/
@Nonnull
List<Position<StructureDefinitionCoords>> getAllSockets(String piece, char socket);
/** /**
* Low level utility. * Low level utility.
* *
@@ -5,7 +5,6 @@ import static com.gtnewhorizon.structurelib.StructureLib.PANIC_MODE;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Predicate; import java.util.function.Predicate;
@@ -43,30 +42,6 @@ public interface IStructureElement<T> {
return true; return true;
} }
/**
* Returns a human-readable description of what block(s) this element accepts. Used for diagnostic messages when
* structure checks fail (e.g. "expected Input Bus at (1, 2, 3)").
* <p>
* Unlike {@link #getBlocksToPlace}, which returns the full set of concrete block variants for autoplacing (e.g.
* every tier of Input Bus), this method returns <b>category-level</b> descriptions suitable for display to the
* player (e.g. just "Input Bus"). It also requires no parameters, no world, trigger item, or environment, making it
* usable in contexts where those are unavailable.
* <p>
* Implementations should return <b>lang keys</b> (e.g. {@code "tile.blockGlass.name"}) rather than pre-translated
* display names. The caller is responsible for translating these keys on the client side via
* {@code StatCollector.translateToLocal()}. If a key has no matching translation, {@code translateToLocal} returns
* the input string unchanged, so pre-translated fallback strings also work.
*
* @param context the context object (e.g. the multiblock controller), used to determine state-dependent
* descriptions
* @return a list of accepted block descriptions as lang keys (or display names as fallback), or null if no
* description is available
*/
@Nullable
default List<String> getDescription(T context) {
return null;
}
boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger); boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger);
boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger); boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger);
@@ -96,7 +71,7 @@ public interface IStructureElement<T> {
"Default implementation of survivalPlaceBlock hit! Things aren't going to work well! IStructureElement class: {}", "Default implementation of survivalPlaceBlock hit! Things aren't going to work well! IStructureElement class: {}",
getClass().getName()); getClass().getName());
if (!StructureLibAPI.isBlockTriviallyReplaceable(world, x, y, z, actor)) return PlaceResult.REJECT; if (!StructureLibAPI.isBlockTriviallyReplaceable(world, x, y, z, actor)) return PlaceResult.REJECT;
return PlaceResult.REJECT_CONTINUE; return PlaceResult.SKIP;
} }
/** /**
@@ -206,7 +181,7 @@ public interface IStructureElement<T> {
if (StructureLibAPI.isDebugEnabled()) LOGGER.info( if (StructureLibAPI.isDebugEnabled()) LOGGER.info(
"Fallback shim code of survivalPlaceBlock hit! Things aren't going to work well! IStructureElement class: {}", "Fallback shim code of survivalPlaceBlock hit! Things aren't going to work well! IStructureElement class: {}",
getClass().getName()); getClass().getName());
return PlaceResult.REJECT_CONTINUE; return PlaceResult.SKIP;
} }
/** /**
@@ -229,12 +204,6 @@ public interface IStructureElement<T> {
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) { public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
return IStructureElement.this.spawnHint(t, world, x, y, z, trigger); return IStructureElement.this.spawnHint(t, world, x, y, z, trigger);
} }
@Nullable
@Override
public List<String> getDescription(T context) {
return IStructureElement.this.getDescription(context);
}
}; };
} }
@@ -268,21 +237,16 @@ public interface IStructureElement<T> {
enum PlaceResult { enum PlaceResult {
/** /**
* The element's check passed, the position is already valid. No placement is needed. In the walker: continue * This element either exists already, or does not yet have an implementation for survivalPlaceBlock, or some
* iteration (no error, not counted as placed). In ofChain: short-circuits, remaining alternatives are skipped. * other unforeseen situations. TODO this definition doesn't seem right. Should we separate SKIP from EXISTS, or
* SKIP from ERROR?
*/ */
SKIP, SKIP,
/** /**
* The element cannot handle this position (occupied, missing resources, etc.). In the walker: stop iteration * This element's space is occupied by other stuff and require player attention, or player missing required
* with error particles. In ofChain: try next alternative. * resource, or the block cannot be placed due to obscure mechanisms, or some other unforeseen situations.
*/ */
REJECT, REJECT,
/**
* This element has no survivalPlaceBlock implementation (default fallback), or otherwise cannot place but is
* not an error condition. In the walker: continue iteration silently (like SKIP). In ofChain: try next
* alternative (like REJECT), so a better-suited element can handle it.
*/
REJECT_CONTINUE,
/** /**
* Autoplace cannot proceed within this tick. To proceed further would require stopping the placement and wait * Autoplace cannot proceed within this tick. To proceed further would require stopping the placement and wait
* for next round. * for next round.
@@ -1,9 +1,7 @@
package com.gtnewhorizon.structurelib.structure; package com.gtnewhorizon.structurelib.structure;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Predicate; import java.util.function.Predicate;
@@ -63,19 +61,6 @@ public interface IStructureElementChain<T> extends IStructureElement<T> {
return false; return false;
} }
@Nullable
@Override
default List<String> getDescription(T context) {
Set<String> descriptions = new LinkedHashSet<>();
for (IStructureElement<T> fallback : fallbacks()) {
List<String> desc = fallback.getDescription(context);
if (desc != null) {
descriptions.addAll(desc);
}
}
return descriptions.isEmpty() ? null : new ArrayList<>(descriptions);
}
@Nullable @Nullable
@Override @Override
default BlocksToPlace getBlocksToPlace(T t, World world, int x, int y, int z, ItemStack trigger, default BlocksToPlace getBlocksToPlace(T t, World world, int x, int y, int z, ItemStack trigger,
@@ -97,51 +82,47 @@ public interface IStructureElementChain<T> extends IStructureElement<T> {
@Override @Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, IItemSource s, default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, IItemSource s,
EntityPlayerMP actor, Consumer<IChatComponent> chatter) { EntityPlayerMP actor, Consumer<IChatComponent> chatter) {
boolean allContinue = true; boolean haveSkip = false;
List<IChatComponent> bufferedNoise = new ArrayList<>(); List<IChatComponent> bufferedNoise = new ArrayList<>();
for (IStructureElement<T> fallback : fallbacks()) { for (IStructureElement<T> fallback : fallbacks()) {
PlaceResult result = fallback.survivalPlaceBlock(t, world, x, y, z, trigger, s, actor, bufferedNoise::add); PlaceResult result = fallback.survivalPlaceBlock(t, world, x, y, z, trigger, s, actor, bufferedNoise::add);
switch (result) { switch (result) {
case REJECT_CONTINUE:
break;
case REJECT: case REJECT:
allContinue = false;
break; break;
case SKIP: case SKIP:
bufferedNoise.forEach(chatter); haveSkip = true;
return PlaceResult.SKIP; break;
default: default:
return result; return result;
} }
} }
// dump all that noise back into upstream // dump all that noise back into upstream
bufferedNoise.forEach(chatter); bufferedNoise.forEach(chatter);
return allContinue ? PlaceResult.REJECT_CONTINUE : PlaceResult.REJECT; // TODO need reconsider to ensure this is the right course of action
return haveSkip ? PlaceResult.SKIP : PlaceResult.REJECT;
} }
@Override @Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) { AutoPlaceEnvironment env) {
boolean allContinue = true; boolean haveSkip = false;
List<IChatComponent> bufferedNoise = new ArrayList<>(); List<IChatComponent> bufferedNoise = new ArrayList<>();
for (IStructureElement<T> fallback : fallbacks()) { for (IStructureElement<T> fallback : fallbacks()) {
PlaceResult result = fallback PlaceResult result = fallback
.survivalPlaceBlock(t, world, x, y, z, trigger, env.withChatter(bufferedNoise::add)); .survivalPlaceBlock(t, world, x, y, z, trigger, env.withChatter(bufferedNoise::add));
switch (result) { switch (result) {
case REJECT_CONTINUE:
break;
case REJECT: case REJECT:
allContinue = false;
break; break;
case SKIP: case SKIP:
bufferedNoise.forEach(env.getChatter()); haveSkip = true;
return PlaceResult.SKIP; break;
default: default:
return result; return result;
} }
} }
// dump all that noise back into upstream // dump all that noise back into upstream
bufferedNoise.forEach(env.getChatter()); bufferedNoise.forEach(env.getChatter());
return allContinue ? PlaceResult.REJECT_CONTINUE : PlaceResult.REJECT; // TODO need reconsider to ensure this is the right course of action
return haveSkip ? PlaceResult.SKIP : PlaceResult.REJECT;
} }
} }
@@ -27,12 +27,12 @@ public interface IStructureElementCheckOnly<T> extends IStructureElement<T> {
@Override @Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, IItemSource s, default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, IItemSource s,
EntityPlayerMP actor, Consumer<IChatComponent> chatter) { EntityPlayerMP actor, Consumer<IChatComponent> chatter) {
return PlaceResult.REJECT_CONTINUE; return PlaceResult.SKIP;
} }
@Override @Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) { AutoPlaceEnvironment env) {
return PlaceResult.REJECT_CONTINUE; return PlaceResult.SKIP;
} }
} }
@@ -1,6 +1,5 @@
package com.gtnewhorizon.structurelib.structure; package com.gtnewhorizon.structurelib.structure;
import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
@@ -66,10 +65,4 @@ class LazyStructureElement<T> implements IStructureElementDeferred<T> {
AutoPlaceEnvironment env) { AutoPlaceEnvironment env) {
return get(t).survivalPlaceBlock(t, world, x, y, z, trigger, env); return get(t).survivalPlaceBlock(t, world, x, y, z, trigger, env);
} }
@Nullable
@Override
public List<String> getDescription(T context) {
return elem != null ? elem.getDescription(context) : null;
}
} }
@@ -4,33 +4,49 @@ import static com.gtnewhorizon.structurelib.structure.StructureUtility.isAir;
import static com.gtnewhorizon.structurelib.structure.StructureUtility.notAir; import static com.gtnewhorizon.structurelib.structure.StructureUtility.notAir;
import static com.gtnewhorizon.structurelib.structure.StructureUtility.step; import static com.gtnewhorizon.structurelib.structure.StructureUtility.step;
import java.util.Arrays; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MultimapBuilder;
import com.gtnewhorizon.structurelib.coords.Position;
import com.gtnewhorizon.structurelib.coords.StructureDefinitionCoords;
import com.gtnewhorizon.structurelib.util.Vec3Impl; import com.gtnewhorizon.structurelib.util.Vec3Impl;
import it.unimi.dsi.fastutil.chars.Char2CharOpenHashMap;
import it.unimi.dsi.fastutil.chars.CharOpenHashSet;
public class StructureDefinition<T> implements IStructureDefinition<T> { public class StructureDefinition<T> implements IStructureDefinition<T> {
private final Map<Character, IStructureElement<T>> elements; private final Map<Character, IStructureElement<T>> elements;
private final Map<String, String> shapes; private final Map<String, String> shapes;
private final Map<String, IStructureElement<T>[]> structures; private final Map<String, IStructureElement<T>[]> structures;
private final Map<String, Set<Vec3Impl>> occupiedSpaces; private final Map<String, Set<Vec3Impl>> occupiedSpaces;
private final Map<String, Position<StructureDefinitionCoords>> controllers;
private final Map<String, ListMultimap<Character, Position<StructureDefinitionCoords>>> socketLocations;
public static <B> Builder<B> builder() { public static <B> Builder<B> builder() {
return new Builder<>(); return new Builder<>();
} }
private StructureDefinition(Map<Character, IStructureElement<T>> elements, Map<String, String> shapes, private StructureDefinition(Map<Character, IStructureElement<T>> elements, Map<String, String> shapes,
Map<String, IStructureElement<T>[]> structures, Map<String, Set<Vec3Impl>> occupiedSpaces) { Map<String, IStructureElement<T>[]> structures, Map<String, Set<Vec3Impl>> occupiedSpaces,
Map<String, Position<StructureDefinitionCoords>> controllers,
Map<String, ListMultimap<Character, Position<StructureDefinitionCoords>>> socketLocations) {
this.elements = elements; this.elements = elements;
this.shapes = shapes; this.shapes = shapes;
this.structures = structures; this.structures = structures;
this.occupiedSpaces = occupiedSpaces; this.occupiedSpaces = occupiedSpaces;
this.controllers = controllers;
this.socketLocations = socketLocations;
} }
public static class Builder<T> { public static class Builder<T> {
@@ -41,12 +57,18 @@ public class StructureDefinition<T> implements IStructureDefinition<T> {
private char d = '\uD000'; private char d = '\uD000';
private final Map<Vec3Impl, Character> navigates; private final Map<Vec3Impl, Character> navigates;
private final Map<Character, IStructureElement<T>> elements; private final Map<Character, IStructureElement<T>> elements;
private final Map<String, String[][]> uncompiledShapes;
private final Map<String, String> shapes; private final Map<String, String> shapes;
private final Map<String, Set<Vec3Impl>> occupiedSpaces; private final Map<String, Set<Vec3Impl>> occupiedSpaces;
private final Map<String, Position<StructureDefinitionCoords>> controllers = new HashMap<>();
private final Char2CharOpenHashMap socketTranslations = new Char2CharOpenHashMap();
private final Map<String, ListMultimap<Character, Position<StructureDefinitionCoords>>> socketLocations = new HashMap<>();
private Builder() { private Builder() {
navigates = new HashMap<>(); navigates = new HashMap<>();
elements = new HashMap<>(); elements = new HashMap<>();
uncompiledShapes = new HashMap<>();
shapes = new HashMap<>(); shapes = new HashMap<>();
occupiedSpaces = new HashMap<>(); occupiedSpaces = new HashMap<>();
} }
@@ -82,7 +104,69 @@ public class StructureDefinition<T> implements IStructureDefinition<T> {
* @return this builder * @return this builder
*/ */
public Builder<T> addShape(String name, String[][] structurePiece) { public Builder<T> addShape(String name, String[][] structurePiece) {
uncompiledShapes.put(name, structurePiece);
return this;
}
/**
* @deprecated use the unboxed version
*/
@Deprecated
public Builder<T> addElement(Character name, IStructureElement<T> structurePiece) {
elements.putIfAbsent(name, structurePiece);
return this;
}
public Builder<T> addElement(char name, IStructureElement<T> structurePiece) {
elements.putIfAbsent(name, structurePiece);
return this;
}
/**
* Denotes {@code name} as a socket. Sockets are virtual structure elements that record their position in the
* structure for future retrieval. They are transformed into real structure elements and do not need their own
* element (see {@code replacement}).
*
* @param name The socket name character
* @param replacement The replacement character
* @see IStructureDefinition#getSocket(String, char)
* @see IStructureDefinition#getAllSockets(String, char)
*/
public Builder<T> addSocket(char name, char replacement) {
socketTranslations.put(name, replacement);
return this;
}
/**
* Like {@link #addSocket(char, char)} but without the replacement. The structure must have a structure element
* with the given character.
*
* @param name The socket name character
*/
public Builder<T> addSocket(char name) {
// Adding a name -> name entry like this isn't ideal but this is the cleanest solution
socketTranslations.put(name, name);
return this;
}
public IStructureDefinition<T> build() {
uncompiledShapes.forEach(this::compileShape);
Map<String, IStructureElement<T>[]> structures = compileStructureMap();
return new StructureDefinition<>(
new HashMap<>(elements),
new HashMap<>(shapes),
structures,
occupiedSpaces,
controllers,
socketLocations);
}
private void compileShape(String name, String[][] structurePiece) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
if (structurePiece.length > 0) { if (structurePiece.length > 0) {
for (String[] strings : structurePiece) { for (String[] strings : structurePiece) {
if (strings.length > 0) { if (strings.length > 0) {
@@ -95,6 +179,11 @@ public class StructureDefinition<T> implements IStructureDefinition<T> {
} }
builder.setLength(builder.length() - 1); builder.setLength(builder.length() - 1);
} }
// Always create a map for this piece, even if it doesn't have any sockets
// noinspection UnstableApiUsage
socketLocations.put(name, MultimapBuilder.hashKeys().arrayListValues().build());
Set<Vec3Impl> occupiedSpace = new HashSet<>(); Set<Vec3Impl> occupiedSpace = new HashSet<>();
// these track the global current location // these track the global current location
int aa = 0, bb = 0, cc = 0; int aa = 0, bb = 0, cc = 0;
@@ -103,6 +192,15 @@ public class StructureDefinition<T> implements IStructureDefinition<T> {
// I do know these are pretty bad variable naming, but I have no better idea // I do know these are pretty bad variable naming, but I have no better idea
for (int i = 0; i < builder.length(); i++) { for (int i = 0; i < builder.length(); i++) {
char ch = builder.charAt(i); char ch = builder.charAt(i);
// Translate the element char if it's a socket, and record the socket position
if (socketTranslations.containsKey(ch)) {
socketLocations.get(name).put(ch, new Position<>(aa, bb, cc));
ch = socketTranslations.get(ch);
builder.setCharAt(i, ch);
}
if (ch == ' ') { if (ch == ' ') {
builder.setCharAt(i, A); builder.setCharAt(i, A);
ch = A; ch = A;
@@ -110,6 +208,7 @@ public class StructureDefinition<T> implements IStructureDefinition<T> {
builder.setCharAt(i, A); builder.setCharAt(i, A);
ch = A; ch = A;
occupiedSpace.add(Vec3Impl.getFromPool(aa, bb, cc)); occupiedSpace.add(Vec3Impl.getFromPool(aa, bb, cc));
controllers.put(name, new Position<>(aa, bb, cc));
} }
if (ch == A) { if (ch == A) {
aa++; aa++;
@@ -148,93 +247,70 @@ public class StructureDefinition<T> implements IStructureDefinition<T> {
occupiedSpaces.put(name, occupiedSpace); occupiedSpaces.put(name, occupiedSpace);
boolean hasPlus = false; String built = builder.toString().replaceAll("[\\uA000\\uB000\\uC000]", "");
boolean hasMinus = false;
int write = 0; if (built.contains("+")) {
for (int read = 0; read < builder.length(); read++) {
char ch = builder.charAt(read);
if (ch == A || ch == B || ch == C) {
continue;
}
if (ch == '+') {
hasPlus = true;
} else if (ch == '-') {
hasMinus = true;
}
if (read != write) builder.setCharAt(write, ch);
write++;
}
builder.setLength(write);
if (hasPlus) {
addElement('+', notAir()); addElement('+', notAir());
} }
if (hasMinus) { if (built.contains("-")) {
addElement('-', isAir()); addElement('-', isAir());
} }
shapes.put(name, builder.toString());
return this;
}
/** shapes.put(name, built);
* @deprecated use the unboxed version
*/
@Deprecated
public Builder<T> addElement(Character name, IStructureElement<T> structurePiece) {
elements.putIfAbsent(name, structurePiece);
return this;
}
public Builder<T> addElement(char name, IStructureElement<T> structurePiece) {
elements.putIfAbsent(name, structurePiece);
return this;
}
public IStructureDefinition<T> build() {
Map<String, IStructureElement<T>[]> structures = compileStructureMap();
return new StructureDefinition<>(
new HashMap<>(elements),
new HashMap<>(shapes),
structures,
occupiedSpaces);
}
@SuppressWarnings("unchecked")
private Map<String, IStructureElement<T>[]> compileElementSetMap() {
Set<Integer> missing = findMissing();
if (missing.isEmpty()) {
return shapes.entrySet().stream().collect(
Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().chars().mapToObj(c -> (char) c).distinct().map(elements::get)
.toArray(IStructureElement[]::new)));
} else {
throw new RuntimeException(
"Missing Structure Element bindings for (chars as integers): "
+ Arrays.toString(missing.toArray()));
}
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Map<String, IStructureElement<T>[]> compileStructureMap() { private Map<String, IStructureElement<T>[]> compileStructureMap() {
Set<Integer> missing = findMissing(); CharOpenHashSet missing = findMissing();
if (missing.isEmpty()) {
return shapes.entrySet().stream().collect( if (!missing.isEmpty()) {
Collectors.toMap( throw new RuntimeException("Missing Structure Element bindings for: " + missing);
Map.Entry::getKey,
e -> e.getValue().chars().mapToObj(c -> elements.get((char) c))
.toArray(IStructureElement[]::new)));
} else {
throw new RuntimeException(
"Missing Structure Element bindings for (chars as integers): "
+ Arrays.toString(missing.toArray()));
} }
Map<String, IStructureElement<T>[]> map = new HashMap<>();
for (Entry<String, String> e : shapes.entrySet()) {
char[] chars = e.getValue().toCharArray();
IStructureElement<T>[] compiled = new IStructureElement[chars.length];
int a = 0, b = 0, c = 0;
for (int i = 0; i < chars.length; i++) {
char ch = chars[i];
IStructureElement<T> element = this.elements.get(ch);
compiled[i] = element;
if (element.isNavigating()) {
a = (element.resetA() ? 0 : a) + element.getStepA();
b = (element.resetB() ? 0 : b) + element.getStepB();
c = (element.resetC() ? 0 : c) + element.getStepC();
} else {
a++;
}
}
if (map.put(e.getKey(), compiled) != null) {
throw new IllegalStateException("Duplicate shape: " + e.getKey());
}
}
return map;
} }
private Set<Integer> findMissing() { private CharOpenHashSet findMissing() {
return shapes.values().stream().flatMapToInt(CharSequence::chars) CharOpenHashSet missing = new CharOpenHashSet();
.filter(i -> !elements.containsKey((char) i)).boxed().collect(Collectors.toSet());
for (String shape : shapes.values()) {
for (char c : shape.toCharArray()) {
if (!elements.containsKey(c)) {
missing.add(c);
}
}
}
return missing;
} }
} }
@@ -263,4 +339,61 @@ public class StructureDefinition<T> implements IStructureDefinition<T> {
if (occupiedSpace == null) throw new NoSuchElementException(name); if (occupiedSpace == null) throw new NoSuchElementException(name);
return occupiedSpace.contains(new Vec3Impl(offsetA, offsetB, offsetC)); return occupiedSpace.contains(new Vec3Impl(offsetA, offsetB, offsetC));
} }
@Override
public Position<StructureDefinitionCoords> getControllerPosition(String piece) {
return controllers.get(piece);
}
@Override
public StructureDefinitionCoords getCoordinateSystem(String piece) {
var controller = controllers.get(piece);
if (controller == null) {
throw new IllegalArgumentException("Invalid piece: " + piece);
}
return new StructureDefinitionCoords(controller.x, controller.y, controller.z);
}
@Override
public Position<StructureDefinitionCoords> getSocket(String piece, char socket) {
var piecePositions = socketLocations.get(piece);
if (piecePositions == null) {
throw new IllegalArgumentException("Invalid piece: " + piece);
}
var positions = piecePositions.get(socket);
if (positions.isEmpty()) {
throw new IllegalArgumentException("Socket " + socket + " for piece " + piece + " does not exist");
}
if (positions.size() > 1) {
throw new IllegalStateException(
"Socket " + socket
+ " for piece "
+ piece
+ " has several positions, but expected one and only one");
}
return positions.get(0).copy();
}
@Override
@Nonnull
public List<Position<StructureDefinitionCoords>> getAllSockets(String piece, char socket) {
var piecePositions = socketLocations.get(piece);
if (piecePositions == null) {
throw new IllegalArgumentException("Invalid piece: " + piece);
}
var list = new ArrayList<>(piecePositions.get(socket));
list.replaceAll(Position::copy);
return list;
}
} }
@@ -36,10 +36,7 @@ import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.ChatStyle;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent; import net.minecraft.util.IChatComponent;
import net.minecraft.util.IIcon; import net.minecraft.util.IIcon;
import net.minecraft.world.World; import net.minecraft.world.World;
@@ -341,7 +338,9 @@ public class StructureUtility {
ItemStack stack = new ItemStack(itemBlock, 1, itemMeta); ItemStack stack = new ItemStack(itemBlock, 1, itemMeta);
if (!s.takeOne(stack, true)) { if (!s.takeOne(stack, true)) {
if (chatter != null) chatter.accept( if (chatter != null) chatter.accept(
new ChatComponentTranslation("structurelib.autoplace.missing_block", stack.func_151000_E())); new ChatComponentTranslation(
"structurelib.autoplace.error.no_simple_block",
stack.func_151000_E()));
return PlaceResult.REJECT; return PlaceResult.REJECT;
} }
if (block instanceof ICustomBlockSetting) { if (block instanceof ICustomBlockSetting) {
@@ -448,7 +447,7 @@ public class StructureUtility {
if (!StructureLibAPI.isBlockTriviallyReplaceable(world, x, y, z, actor)) return PlaceResult.REJECT; if (!StructureLibAPI.isBlockTriviallyReplaceable(world, x, y, z, actor)) return PlaceResult.REJECT;
if (!assumeStackPresent && !s.takeOne(stack, true)) { if (!assumeStackPresent && !s.takeOne(stack, true)) {
if (chatter != null) chatter.accept( if (chatter != null) chatter.accept(
new ChatComponentTranslation("structurelib.autoplace.missing_block", stack.func_151000_E())); new ChatComponentTranslation("structurelib.autoplace.error.no_item_stack", stack.func_151000_E()));
return PlaceResult.REJECT; return PlaceResult.REJECT;
} }
if (!stack.copy().tryPlaceItemIntoWorld(actor, world, x, y, z, ForgeDirection.UP.ordinal(), 0.5f, 0.5f, 0.5f)) if (!stack.copy().tryPlaceItemIntoWorld(actor, world, x, y, z, ForgeDirection.UP.ordinal(), 0.5f, 0.5f, 0.5f))
@@ -707,29 +706,6 @@ public class StructureUtility {
public static <T, TIER> IStructureElement<T> ofBlocksTiered(ITierConverter<TIER> tierExtractor, public static <T, TIER> IStructureElement<T> ofBlocksTiered(ITierConverter<TIER> tierExtractor,
@Nullable List<Pair<Block, Integer>> allKnownTiers, @Nullable TIER notSet, BiConsumer<T, TIER> setter, @Nullable List<Pair<Block, Integer>> allKnownTiers, @Nullable TIER notSet, BiConsumer<T, TIER> setter,
Function<T, TIER> getter) { Function<T, TIER> getter) {
List<String> descriptions = null;
if (allKnownTiers != null) {
descriptions = new java.util.ArrayList<>();
for (Pair<Block, Integer> tier : allKnownTiers) {
Item item = Item.getItemFromBlock(tier.getLeft());
if (item != null) {
descriptions.add(new ItemStack(item, 1, tier.getRight()).getUnlocalizedName() + ".name");
}
}
}
return ofBlocksTiered(tierExtractor, allKnownTiers, notSet, setter, getter, descriptions);
}
/**
* Like {@link #ofBlocksTiered(ITierConverter, List, Object, BiConsumer, Function)}, but with an explicit
* description that will be returned by {@link IStructureElement#getDescription(Object)}.
*
* @param description the description lang keys to attach to this element, or null for no description
* @see #ofBlocksTiered(ITierConverter, List, Object, BiConsumer, Function)
*/
public static <T, TIER> IStructureElement<T> ofBlocksTiered(ITierConverter<TIER> tierExtractor,
@Nullable List<Pair<Block, Integer>> allKnownTiers, @Nullable TIER notSet, BiConsumer<T, TIER> setter,
Function<T, TIER> getter, @Nullable List<String> description) {
List<Pair<Block, Integer>> hints = allKnownTiers == null ? Collections.emptyList() : allKnownTiers; List<Pair<Block, Integer>> hints = allKnownTiers == null ? Collections.emptyList() : allKnownTiers;
if (hints.stream().anyMatch(Objects::isNull)) throw new IllegalArgumentException(); if (hints.stream().anyMatch(Objects::isNull)) throw new IllegalArgumentException();
IStructureElementCheckOnly<T> check = ofBlocksTiered(tierExtractor, notSet, setter, getter); IStructureElementCheckOnly<T> check = ofBlocksTiered(tierExtractor, notSet, setter, getter);
@@ -791,7 +767,7 @@ public class StructureUtility {
public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) { AutoPlaceEnvironment env) {
Pair<Block, Integer> hint = getHint(trigger); Pair<Block, Integer> hint = getHint(trigger);
if (hint == null) return PlaceResult.REJECT; if (hint == null) return PlaceResult.REJECT; // TODO or SKIP?
Block block = world.getBlock(x, y, z); Block block = world.getBlock(x, y, z);
int meta = world.getBlockMetadata(x, y, z); int meta = world.getBlockMetadata(x, y, z);
TIER tier = tierExtractor.convert(block, meta); TIER tier = tierExtractor.convert(block, meta);
@@ -808,24 +784,6 @@ public class StructureUtility {
env.getActor(), env.getActor(),
env.getChatter()); env.getChatter());
} }
@Nullable
@Override
public List<String> getDescription(T context) {
TIER currentTier = getter.apply(context);
if (Objects.equals(currentTier, notSet)) return description;
for (Pair<Block, Integer> pair : hints) {
TIER pairTier = tierExtractor.convert(pair.getKey(), pair.getValue());
if (!Objects.equals(pairTier, currentTier)) continue;
Item item = Item.getItemFromBlock(pair.getKey());
if (item == null) continue;
return Collections
.singletonList(new ItemStack(item, 1, pair.getValue()).getUnlocalizedName() + ".name");
}
return description;
}
}; };
} }
@@ -1449,65 +1407,10 @@ public class StructureUtility {
AutoPlaceEnvironment env) { AutoPlaceEnvironment env) {
return BlocksToPlace.create(block, meta); return BlocksToPlace.create(block, meta);
} }
@Nullable
@Override
public List<String> getDescription(T context) {
Item item = Item.getItemFromBlock(block);
if (item == null) return null;
return Collections.singletonList(new ItemStack(item, 1, meta).getUnlocalizedName() + ".name");
}
}; };
} else { } else {
return new IStructureElement<T>() { return new IStructureElement<T>() {
@Override
public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) {
BlocksToPlace e = getBlocksToPlace(t, world, x, y, z, trigger, env);
IItemSource source = env.getSource();
EntityPlayer actor = env.getActor();
Consumer<IChatComponent> chatter = env.getChatter();
if (check(t, world, x, y, z)) return PlaceResult.SKIP;
if (e.getStacks() == null) {
ItemStack taken = source.takeOne(e.getPredicate(), true);
return StructureUtility.survivalPlaceBlock(
taken,
NBTMode.EXACT,
taken.stackTagCompound,
false,
world,
x,
y,
z,
source,
actor,
chatter);
}
for (ItemStack stack : e.getStacks()) {
if (!source.takeOne(stack, true)) {
IChatComponent name = new ChatComponentText(stack.getDisplayName());
name.setChatStyle(new ChatStyle().setColor(EnumChatFormatting.YELLOW));
env.getChatter()
.accept(new ChatComponentTranslation("structurelib.autoplace.missing_block", name));
continue;
}
return StructureUtility.survivalPlaceBlock(
stack,
NBTMode.EXACT,
stack.stackTagCompound,
false,
world,
x,
y,
z,
source,
actor,
chatter);
}
return PlaceResult.REJECT;
}
@Override @Override
public boolean check(T t, World world, int x, int y, int z) { public boolean check(T t, World world, int x, int y, int z) {
Block worldBlock = world.getBlock(x, y, z); Block worldBlock = world.getBlock(x, y, z);
@@ -1536,14 +1439,6 @@ public class StructureUtility {
AutoPlaceEnvironment env) { AutoPlaceEnvironment env) {
return BlocksToPlace.create(block, meta); return BlocksToPlace.create(block, meta);
} }
@Nullable
@Override
public List<String> getDescription(T context) {
Item item = Item.getItemFromBlock(block);
if (item == null) return null;
return Collections.singletonList(new ItemStack(item, 1, meta).getUnlocalizedName() + ".name");
}
}; };
} }
} }
@@ -1586,14 +1481,6 @@ public class StructureUtility {
// there is getSubItems on ItemBlock, but it's client only // there is getSubItems on ItemBlock, but it's client only
return BlocksToPlace.create(defaultBlock, defaultMeta); return BlocksToPlace.create(defaultBlock, defaultMeta);
} }
@Nullable
@Override
public List<String> getDescription(T context) {
Item item = Item.getItemFromBlock(block);
if (item == null) return null;
return Collections.singletonList(new ItemStack(item, 1, 0).getUnlocalizedName() + ".name");
}
}; };
} else { } else {
return new IStructureElement<T>() { return new IStructureElement<T>() {
@@ -1626,14 +1513,6 @@ public class StructureUtility {
// there is getSubItems on ItemBlock, but it's client only // there is getSubItems on ItemBlock, but it's client only
return BlocksToPlace.create(defaultBlock, defaultMeta); return BlocksToPlace.create(defaultBlock, defaultMeta);
} }
@Nullable
@Override
public List<String> getDescription(T context) {
Item item = Item.getItemFromBlock(block);
if (item == null) return null;
return Collections.singletonList(new ItemStack(item, 1, 0).getUnlocalizedName() + ".name");
}
}; };
} }
} }
@@ -1897,71 +1776,6 @@ public class StructureUtility {
AutoPlaceEnvironment env) { AutoPlaceEnvironment env) {
return element.survivalPlaceBlock(t, world, x, y, z, trigger, env); return element.survivalPlaceBlock(t, world, x, y, z, trigger, env);
} }
@Nullable
@Override
public List<String> getDescription(T context) {
return element.getDescription(context);
}
};
}
/**
* Wraps an element and overrides its description. Useful for providing human-readable names to elements whose
* underlying implementation doesn't provide a description (e.g. tiered block elements).
*
* @param description the description to use, or null to clear any existing description
* @param element the element to wrap
*/
public static <B extends IStructureElement<T>, T> IStructureElement<T> withDescription(
@Nullable List<String> description, B element) {
return new IStructureElement<T>() {
@Override
public boolean check(T t, World world, int x, int y, int z) {
return element.check(t, world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return element.couldBeValid(t, world, x, y, z, trigger);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
return element.placeBlock(t, world, x, y, z, trigger);
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
return element.spawnHint(t, world, x, y, z, trigger);
}
@Nullable
@Override
public BlocksToPlace getBlocksToPlace(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) {
return element.getBlocksToPlace(t, world, x, y, z, trigger, env);
}
@Override
@Deprecated
public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
IItemSource s, EntityPlayerMP actor, Consumer<IChatComponent> chatter) {
return element.survivalPlaceBlock(t, world, x, y, z, trigger, s, actor, chatter);
}
@Override
public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) {
return element.survivalPlaceBlock(t, world, x, y, z, trigger, env);
}
@Nullable
@Override
public List<String> getDescription(T context) {
return description;
}
}; };
} }
@@ -2018,12 +1832,6 @@ public class StructureUtility {
AutoPlaceEnvironment env) { AutoPlaceEnvironment env) {
return element.survivalPlaceBlock(t, world, x, y, z, trigger, env); return element.survivalPlaceBlock(t, world, x, y, z, trigger, env);
} }
@Nullable
@Override
public List<String> getDescription(T context) {
return element.getDescription(context);
}
}; };
} }
@@ -2032,11 +1840,11 @@ public class StructureUtility {
/** /**
* Enable this structure element only if given predicate returns true. * Enable this structure element only if given predicate returns true.
* <p> * <p>
* Return REJECT_CONTINUE when survival auto place if given predicate returns false. * Return SKIP when survival auto place if given predicate returns false.
*/ */
public static <T> IStructureElement<T> onlyIf(Predicate<? super T> predicate, public static <T> IStructureElement<T> onlyIf(Predicate<? super T> predicate,
IStructureElement<? super T> downstream) { IStructureElement<? super T> downstream) {
return onlyIf(predicate, downstream, PlaceResult.REJECT_CONTINUE); return onlyIf(predicate, downstream, PlaceResult.SKIP);
} }
/** /**
@@ -2093,12 +1901,6 @@ public class StructureUtility {
if (predicate.test(t)) return downstream.survivalPlaceBlock(t, world, x, y, z, trigger, env); if (predicate.test(t)) return downstream.survivalPlaceBlock(t, world, x, y, z, trigger, env);
return placeResultWhenDisabled; return placeResultWhenDisabled;
} }
@Nullable
@Override
public List<String> getDescription(T context) {
return downstream.getDescription(context);
}
}; };
} }
@@ -2111,10 +1913,10 @@ public class StructureUtility {
* using {@link #isAir()}. It will not attempt to capture any errors though, so next one will not be tried if * using {@link #isAir()}. It will not attempt to capture any errors though, so next one will not be tried if
* previous one would crash. * previous one would crash.
* <p> * <p>
* (*): For survival auto place, it will: REJECT, if any structure element returns REJECT (and none returned ACCEPT, * (*): For survival auto place, it will * REJECT, if all structure element REJECT * SKIP, if 1 or more structure
* STOP, ACCEPT_STOP, or SKIP); REJECT_CONTINUE, if all structure elements return REJECT_CONTINUE (none returned * element SKIP and the rest structure element (0 or more) REJECT * any other result, **immediately** upon any
* REJECT); SKIP, as soon as any structure element returns SKIP; any other result, immediately upon any structure * structure element returns these other results. This behavior is not 100% fixed and might change later on, but we
* element returning those. * will send the notice on a best effort basis.
* <p> * <p>
* Take care while chaining, as it will try to call every structure element until it returns true. If none does it * Take care while chaining, as it will try to call every structure element until it returns true. If none does it
* will finally return false. * will finally return false.
@@ -2196,12 +1998,6 @@ public class StructureUtility {
AutoPlaceEnvironment env) { AutoPlaceEnvironment env) {
return elem.survivalPlaceBlock(t.getCurrentContext(), world, x, y, z, trigger, env); return elem.survivalPlaceBlock(t.getCurrentContext(), world, x, y, z, trigger, env);
} }
@Nullable
@Override
public List<String> getDescription(T context) {
return elem.getDescription(context.getCurrentContext());
}
}; };
} }
// endregion // endregion
@@ -3039,12 +2835,6 @@ public class StructureUtility {
warnNoExplicitSubChannel(env.getActor()); warnNoExplicitSubChannel(env.getActor());
return backing.survivalPlaceBlock(t, world, x, y, z, newTrigger, env); return backing.survivalPlaceBlock(t, world, x, y, z, newTrigger, env);
} }
@Nullable
@Override
public List<String> getDescription(T context) {
return backing.getDescription(context);
}
}; };
} }
// endregion // endregion
@@ -43,10 +43,9 @@ class SurvivalBuildStructureWalker<T> implements IStructureWalker<T> {
env.offsetABC[2] = c; env.offsetABC[2] = c;
env.setSource(params.getSource()); env.setSource(params.getSource());
PlaceResult placeResult = element.survivalPlaceBlock(object, world, x, y, z, trigger, env); PlaceResult placeResult = element.survivalPlaceBlock(object, world, x, y, z, trigger, env);
if (placeResult != PlaceResult.SKIP && placeResult != PlaceResult.REJECT_CONTINUE && built == -1) built = 0; if (placeResult != PlaceResult.SKIP && built == -1) built = 0;
switch (placeResult) { switch (placeResult) {
case SKIP: case SKIP:
case REJECT_CONTINUE:
return true; return true;
case ACCEPT: case ACCEPT:
if (check) element.check(object, world, x, y, z); if (check) element.check(object, world, x, y, z);
@@ -51,7 +51,6 @@ structurelib.autoplace.error.not_enabled=§cThis multiblock does not support aut
structurelib.autoplace.error.no_simple_block=§cSuggested to place §r%s§c but none was found structurelib.autoplace.error.no_simple_block=§cSuggested to place §r%s§c but none was found
structurelib.autoplace.error.no_item_stack=§cSuggested to place block by using §r%s§c but none was found structurelib.autoplace.error.no_item_stack=§cSuggested to place block by using §r%s§c but none was found
structurelib.autoplace.warning.no_explicit_channel=§6This structure depends on nonexistent sub channel §r%s§6. Using master channel instead. structurelib.autoplace.warning.no_explicit_channel=§6This structure depends on nonexistent sub channel §r%s§6. Using master channel instead.
structurelib.autoplace.missing_block=§cMissing block: %s
structurelib.blockhint.desc.0=Helps while building structurelib.blockhint.desc.0=Helps while building
structurelib.blockhint.0.name=Hint 1 dot structurelib.blockhint.0.name=Hint 1 dot
Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 B

After

Width:  |  Height:  |  Size: 176 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 154 B

After

Width:  |  Height:  |  Size: 208 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 B

After

Width:  |  Height:  |  Size: 212 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 160 B

After

Width:  |  Height:  |  Size: 234 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 137 B

After

Width:  |  Height:  |  Size: 196 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 B

After

Width:  |  Height:  |  Size: 186 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 131 B

After

Width:  |  Height:  |  Size: 186 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 141 B

After

Width:  |  Height:  |  Size: 204 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 132 B

After

Width:  |  Height:  |  Size: 184 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 B

After

Width:  |  Height:  |  Size: 198 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 139 B

After

Width:  |  Height:  |  Size: 204 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 143 B

After

Width:  |  Height:  |  Size: 225 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 99 B

After

Width:  |  Height:  |  Size: 133 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 132 B

After

Width:  |  Height:  |  Size: 183 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 146 B

After

Width:  |  Height:  |  Size: 197 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 115 B

After

Width:  |  Height:  |  Size: 164 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 276 B

After

Width:  |  Height:  |  Size: 367 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 606 B

After

Width:  |  Height:  |  Size: 667 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 361 B

After

Width:  |  Height:  |  Size: 439 B

@@ -0,0 +1,102 @@
package com.gtnewhorizon.structurelib.coords;
import java.util.Arrays;
import java.util.Collections;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.structure.IStructureDefinition;
import com.gtnewhorizon.structurelib.structure.StructureUtility;
// spotless:off
class CoordinateTests {
private IStructureDefinition<?> getDefinition() {
String[][] main = {
{ " ", " ", " ", " ", " " },
{ " ", " ", " ", " ", " " },
{ " ", " ", " X ", " ", " " },
{ " ", " ", " YY ", " ", " " },
{ " ~ ", " ", " ", " ", " " }
};
return IStructureDefinition.builder()
.addShape("main", StructureUtility.transpose(main))
.addSocket('X', ' ')
.addSocket('Y', ' ')
.build();
}
@Test
void testSocketAndCoordSystemTranslationToWorld() {
IStructureDefinition<?> def = getDefinition();
// Note: the position is the same object between all of these transforms, it is never copied, its generic just
// changes
var p = def.getSocket("main", 'X');
Assertions.assertEquals(new Position<>(2, 2, 2), p);
var p2 = def.getCoordinateSystem("main").translateInverse(p);
Assertions.assertEquals(new Position<>(0, -2, 2), p2);
var p3 = ExtendedFacing.NORTH_NORMAL_NONE.asCoordinateSystem().translateInverse(p2);
Assertions.assertEquals(new Position<>(0, 2, 2), p3);
var p4 = ControllerRelativeCoords.translateInverse(p3, 5, 5, 5);
Assertions.assertEquals(new Position<>(5, 7, 7), p4);
}
@Test
void testSocketAndCoordSystemTranslationToStructureDef() {
IStructureDefinition<?> def = getDefinition();
// Note: the position is the same object between all of these transforms, it is never copied, its generic just
// changes
var p = new Position<WorldCoords>(5, 7, 7);
var p2 = ControllerRelativeCoords.translate(p, 5, 5, 5);
Assertions.assertEquals(new Position<>(0, 2, 2), p2);
var p3 = ExtendedFacing.NORTH_NORMAL_NONE.asCoordinateSystem().translate(p2);
Assertions.assertEquals(new Position<>(0, -2, 2), p3);
var p4 = def.getCoordinateSystem("main").translate(p3);
Assertions.assertEquals(new Position<>(2, 2, 2), p4);
Assertions.assertEquals(def.getSocket("main", 'X'), p4);
}
@Test
void testSocketGetters() {
IStructureDefinition<?> def = getDefinition();
Assertions.assertThrows(
IllegalArgumentException.class,
() -> def.getSocket("invalid", 'X'));
Assertions.assertThrows(
IllegalStateException.class,
() -> def.getSocket("main", 'Y'));
Assertions.assertThrows(
IllegalArgumentException.class,
() -> def.getSocket("main", 'Z'));
Assertions.assertThrows(
IllegalArgumentException.class,
() -> def.getAllSockets("invalid", 'X'));
Assertions.assertEquals(
Collections.emptyList(),
def.getAllSockets("main", 'Z'));
Assertions.assertEquals(
Arrays.asList(new Position<>(2, 2, 2)),
def.getAllSockets("main", 'X'));
Assertions.assertEquals(
Arrays.asList(new Position<>(2, 3, 2), new Position<>(3, 3, 2)),
def.getAllSockets("main", 'Y'));
}
}
// spotless:on