This commit is contained in:
LordMZTE 2023-10-28 18:33:26 +02:00
commit 4368abcb2a
Signed by: LordMZTE
GPG key ID: B64802DC33A64FF6
33 changed files with 1734 additions and 0 deletions

129
.clang-format Normal file
View file

@ -0,0 +1,129 @@
---
AccessModifierOffset: 0
AlignAfterOpenBracket: BlockIndent
AlignArrayOfStructures: None
AlignConsecutiveAssignments: None
AlignConsecutiveMacros: None
AlignConsecutiveBitFields: None
AlignConsecutiveDeclarations: None
AlignEscapedNewlines: DontAlign
AlignOperands: DontAlign
AlignTrailingComments: false
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: Empty
AllowShortCaseLabelsOnASingleLine: false
AllowShortEnumsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: MultiLine
AttributeMacros: []
BinPackArguments: false
BinPackParameters: false
BitFieldColonSpacing: After
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: false
SplitEmptyRecord: false
SplitEmptyNamespace: false
BreakAfterJavaFieldAnnotations: true
#BreakArrays: false
BreakBeforeBinaryOperators: All
BreakBeforeBraces: Custom
BreakBeforeConceptDeclarations: true
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: AfterColon
BreakInheritanceList: AfterColon
BreakStringLiterals: true
ColumnLimit: 90
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DeriveLineEnding: false
DerivePointerAlignment: false
DisableFormat: false # wtf
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: Always
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: false
ForEachMacros: ["BOOST_FOREACH"]
IfMacros: []
IncludeBlocks: Regroup
IndentAccessModifiers: false
IndentCaseBlocks: false
IndentCaseLabels: true
IndentExternBlock: Indent
IndentGotoLabels: true
IndentPPDirectives: BeforeHash
#IndentRequiresClause: false
IndentWidth: 4
IndentWrappedFunctionNames: false
#InsertBraces: false
InsertTrailingCommas: Wrapped
JavaScriptQuotes: Double
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
LambdaBodyIndentation: OuterScope
MaxEmptyLinesToKeep: 1
NamespaceIndentation: All
PackConstructorInitializers: NextLine
PointerAlignment: Left
QualifierAlignment: Left
ReferenceAlignment: Left
ReflowComments: true
#RemoveSemicolon: true
#RequiresClausePosition: OwnLine
#RequiresExpressionIndentation: OuterScope
SeparateDefinitionBlocks: Always
SortIncludes: false
SortJavaStaticImport: Before
SortUsingDeclarations: true
SpaceAfterCStyleCast: true
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: false
SpaceAroundPointerQualifiers: After
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: false
SpaceBeforeInheritanceColon: false
SpaceBeforeParens: ControlStatementsExceptControlMacros
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesInAngles: Never
SpacesInCStyleCastParentheses: false
SpacesInConditionalStatement: false
SpacesInContainerLiterals: false
SpacesInLineCommentPrefix:
Minimum: 0
Maximum: -1
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: c++20
StatementAttributeLikeMacros: []
StatementMacros: []
TabWidth: 4
TypenameMacros: []
UseCRLF: false # wtf
UseTab: Never
WhitespaceSensitiveMacros: ["BOOST_PP_STRINGSIZE"]

34
.gitignore vendored Normal file
View file

@ -0,0 +1,34 @@
# gradle
.gradle/
build/
out/
classes/
.factorypath
# eclipse
*.launch
# idea
.idea/
*.iml
*.ipr
*.iws
# vscode
.settings/
.vscode/
bin/
.classpath
.project
# macos
*.DS_Store
# fabric
run/

8
LICENSE Normal file
View file

@ -0,0 +1,8 @@
Copyright (C) 2023 Anvilcraft
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
The above copyright notice, this permission notice and the word "ALEC" shall be included in all copies or substantial portions of the Software.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>

97
build.gradle Normal file
View file

@ -0,0 +1,97 @@
plugins {
id "dev.architectury.loom" version "1.1-SNAPSHOT"
id "maven-publish"
}
sourceCompatibility = targetCompatibility = JavaVersion.VERSION_17
archivesBaseName = project.archives_base_name
version = project.mod_version
group = project.maven_group
loom {
forge {
mixinConfigs = [
"anvillib.mixins.json"
]
}
}
repositories {
maven {
url "https://dl.cloudsmith.io/public/geckolib3/geckolib/maven/"
}
}
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"
forge "net.minecraftforge:forge:${project.forge_version}"
modImplementation "software.bernie.geckolib:geckolib-forge-1.18:3.0.57"
}
processResources {
// this will replace the property "${version}" in your mods.toml
// with the version you've defined in your gradle.properties
filesMatching("META-INF/mods.toml") {
expand "version": project.version
}
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
options.release = 17
}
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()
}
jar {
// add some additional metadata to the jar manifest
manifest {
attributes([
"Specification-Title" : project.mod_id,
"Specification-Vendor" : project.mod_author,
"Specification-Version" : "1",
"Implementation-Title" : project.name,
"Implementation-Version" : version,
"Implementation-Vendor" : project.mod_author,
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
])
}
}
sourcesJar {
archiveClassifier = "sources"
}
// configure the maven publication
publishing {
publications {
mavenJava(MavenPublication) {
from components.java
artifactId = project.archivesBaseName
}
}
repositories {
if (project.hasProperty("mvnURL")) {
maven {
credentials {
username findProperty("mvnUsername")
password findProperty("mvnPassword")
}
url = findProperty("mvnURL")
}
}
mavenLocal()
}
}

23
gradle.properties Normal file
View file

@ -0,0 +1,23 @@
# Done to increase the memory available to gradle.
org.gradle.jvmargs=-Xmx1G
# tell architectury loom that this project is a forge project.
# this will enable us to use the "forge" dependency.
# using archloom without this is possible and will give you a
# "standard" loom installation with some extra features.
loom.platform=forge
# Base properties
# minecraft version
minecraft_version=1.18.2
# forge version, latest version can be found on https://files.minecraftforge.net/
forge_version=1.18.2-40.2.1
# yarn, latest version can be found on https://fabricmc.net/develop/
yarn_mappings=1.18.2+build.4
# Mod Properties
mod_version=0.1.0
maven_group=net.anvilcraft
archives_base_name=anvillib-18
mod_id=anvillib
mod_author=LordMZTE

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Executable file
View file

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# 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"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# 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" "$@"

10
settings.gradle Normal file
View file

@ -0,0 +1,10 @@
pluginManagement {
// when using additional gradle plugins like shadow,
// add their repositories to this list!
repositories {
maven { url "https://maven.fabricmc.net/" }
maven { url "https://maven.architectury.dev/" }
maven { url "https://files.minecraftforge.net/maven/" }
gradlePluginPortal()
}
}

View file

@ -0,0 +1,17 @@
package net.anvilcraft.anvillib;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraftforge.fml.common.Mod;
import software.bernie.geckolib3.GeckoLib;
@Mod(AnvilLib.MODID)
public class AnvilLib {
public static final String MODID = "anvillib";
public static final Logger LOGGER = LogManager.getLogger();
public AnvilLib() {
GeckoLib.initialize();
}
}

View file

@ -0,0 +1,29 @@
package net.anvilcraft.anvillib;
import net.minecraft.item.ItemStack;
import net.minecraft.recipe.Ingredient;
import net.minecraft.tag.TagKey;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import net.minecraftforge.registries.ForgeRegistries;
public class Util {
public static ItemStack stackFromRegistry(Identifier id) {
if (ForgeRegistries.ITEMS.containsKey(id)) {
return new ItemStack(ForgeRegistries.ITEMS.getValue(id));
} else if (ForgeRegistries.BLOCKS.containsKey(id)) {
return new ItemStack(ForgeRegistries.BLOCKS.getValue(id));
} else {
throw new IllegalArgumentException("No block or item with ID " + id + "!");
}
}
public static Ingredient ingredientFromString(String s) {
if (s.charAt(0) == '#')
return Ingredient.fromTag(
TagKey.of(Registry.ITEM_KEY, new Identifier(s.substring(1)))
);
return Ingredient.ofStacks(stackFromRegistry(new Identifier(s)));
}
}

View file

@ -0,0 +1,19 @@
package net.anvilcraft.anvillib.cosmetics;
import net.anvilcraft.anvillib.AnvilLib;
import net.minecraft.client.render.entity.PlayerEntityRenderer;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.EntityRenderersEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
@EventBusSubscriber(modid = AnvilLib.MODID, bus = Bus.MOD, value = { Dist.CLIENT })
public class ClientEventHandler {
@SubscribeEvent
public static void clientSetup(EntityRenderersEvent.AddLayers event) {
for (String skin : event.getSkins())
if (event.getSkin(skin) instanceof PlayerEntityRenderer render)
render.addFeature(new CosmeticFeatureRenderer(render, skin));
}
}

View file

@ -0,0 +1,413 @@
package net.anvilcraft.anvillib.cosmetics;
import java.util.Arrays;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.jetbrains.annotations.ApiStatus.AvailableSince;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.AbstractClientPlayerEntity;
import net.minecraft.client.render.OverlayTexture;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.entity.model.BipedEntityModel;
import net.minecraft.client.render.entity.model.EntityModelLayers;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.Matrix4f;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.Vec3f;
import net.minecraftforge.fml.ModList;
import software.bernie.geckolib3.compat.PatchouliCompat;
import software.bernie.geckolib3.core.IAnimatable;
import software.bernie.geckolib3.core.IAnimatableModel;
import software.bernie.geckolib3.core.controller.AnimationController;
import software.bernie.geckolib3.core.controller.AnimationController.ModelFetcher;
import software.bernie.geckolib3.core.event.predicate.AnimationEvent;
import software.bernie.geckolib3.core.processor.IBone;
import software.bernie.geckolib3.core.util.Color;
import software.bernie.geckolib3.geo.render.built.GeoBone;
import software.bernie.geckolib3.geo.render.built.GeoModel;
import software.bernie.geckolib3.model.AnimatedGeoModel;
import software.bernie.geckolib3.renderers.geo.IGeoRenderer;
import software.bernie.geckolib3.util.EModelRenderCycle;
import software.bernie.geckolib3.util.GeoUtils;
import software.bernie.geckolib3.util.IRenderCycle;
import software.bernie.geckolib3.util.RenderUtils;
public class CosmeticArmorRenderer extends BipedEntityModel<PlayerEntity>
implements IGeoRenderer<CosmeticItem>, ModelFetcher<CosmeticItem> {
protected CosmeticItem currentArmorItem;
protected LivingEntity entityLiving;
protected float widthScale = 1;
protected float heightScale = 1;
protected Matrix4f dispatchedMat = new Matrix4f();
protected Matrix4f renderEarlyMat = new Matrix4f();
public String headBone = null;
public String bodyBone = null;
public String rightArmBone = null;
public String leftArmBone = null;
public String rightLegBone = null;
public String leftLegBone = null;
private final AnimatedGeoModel<CosmeticItem> modelProvider;
protected VertexConsumerProvider rtb = null;
private IRenderCycle currentModelRenderCycle = EModelRenderCycle.INITIAL;
{ AnimationController.addModelFetcher(this); }
@Override
@Nullable
public IAnimatableModel<CosmeticItem> apply(IAnimatable t) {
if (t instanceof CosmeticItem)
return this.getGeoModelProvider();
return null;
}
public CosmeticArmorRenderer() {
super(MinecraftClient.getInstance().getEntityModelLoader().getModelPart(
EntityModelLayers.PLAYER_INNER_ARMOR
));
this.modelProvider = new CosmeticModel();
}
@Override
public void render(
MatrixStack poseStack,
VertexConsumer buffer,
int packedLight,
int packedOverlay,
float red,
float green,
float blue,
float alpha
) {
this.render(0, poseStack, buffer, packedLight);
}
public void render(
float partialTick, MatrixStack poseStack, VertexConsumer buffer, int packedLight
) {
GeoModel model = this.modelProvider.getModel(
this.modelProvider.getModelLocation(this.currentArmorItem)
);
AnimationEvent<CosmeticItem> animationEvent = new AnimationEvent<>(
this.currentArmorItem,
0,
0,
MinecraftClient.getInstance().getTickDelta(),
false, // can also be getLastFrameDuration()
Arrays.asList(this.entityLiving)
);
poseStack.push();
poseStack.translate(0, 24 / 16F, 0);
poseStack.scale(-1, -1, 1);
//this.dispatchedMat = poseStack.last().pose().copy();
this.dispatchedMat = poseStack.peek().getPositionMatrix().copy();
this.modelProvider.setCustomAnimations(
this.currentArmorItem, getInstanceId(this.currentArmorItem), animationEvent
);
setCurrentModelRenderCycle(EModelRenderCycle.INITIAL);
fitToBiped();
RenderSystem.setShaderTexture(0, getTextureLocation(this.currentArmorItem));
Color renderColor = getRenderColor(
this.currentArmorItem, partialTick, poseStack, null, buffer, packedLight
);
RenderLayer renderType = getRenderType(
this.currentArmorItem,
partialTick,
poseStack,
null,
buffer,
packedLight,
getTextureLocation(this.currentArmorItem)
);
render(
model,
this.currentArmorItem,
partialTick,
renderType,
poseStack,
null,
buffer,
packedLight,
OverlayTexture.DEFAULT_UV,
renderColor.getRed() / 255f,
renderColor.getGreen() / 255f,
renderColor.getBlue() / 255f,
renderColor.getAlpha() / 255f
);
if (ModList.get().isLoaded("patchouli"))
PatchouliCompat.patchouliLoaded(poseStack);
poseStack.pop();
}
@Override
public void renderEarly(
CosmeticItem animatable,
MatrixStack poseStack,
float partialTick,
VertexConsumerProvider bufferSource,
VertexConsumer buffer,
int packedLight,
int packedOverlay,
float red,
float green,
float blue,
float alpha
) {
//this.renderEarlyMat = poseStack.last().pose().copy();
this.renderEarlyMat = poseStack.peek().getPositionMatrix().copy();
this.currentArmorItem = animatable;
IGeoRenderer.super.renderEarly(
animatable,
poseStack,
partialTick,
bufferSource,
buffer,
packedLight,
packedOverlay,
red,
green,
blue,
alpha
);
}
@Override
public void renderRecursively(
GeoBone bone,
MatrixStack poseStack,
VertexConsumer buffer,
int packedLight,
int packedOverlay,
float red,
float green,
float blue,
float alpha
) {
if (bone.isTrackingXform()) {
//Matrix4f poseState = poseStack.last().pose();
Matrix4f poseState = poseStack.peek().getPositionMatrix();
Vec3d renderOffset = getRenderOffset(this.currentArmorItem, 1);
Matrix4f localMatrix
= RenderUtils.invertAndMultiplyMatrices(poseState, this.dispatchedMat);
bone.setModelSpaceXform(
RenderUtils.invertAndMultiplyMatrices(poseState, this.renderEarlyMat)
);
//localMatrix.translate(new Vec3f(renderOffset));
localMatrix.addToLastColumn(new Vec3f(renderOffset));
bone.setLocalSpaceXform(localMatrix);
}
IGeoRenderer.super.renderRecursively(
bone, poseStack, buffer, packedLight, packedOverlay, red, green, blue, alpha
);
}
public Vec3d getRenderOffset(CosmeticItem entity, float partialTick) {
return Vec3d.ZERO;
}
protected void fitToBiped() {
if (this.headBone != null) {
IBone headBone = this.modelProvider.getBone(this.headBone);
GeoUtils.copyRotations(this.head, headBone);
headBone.setPositionX(this.head.pivotX);
headBone.setPositionY(-this.head.pivotY);
headBone.setPositionZ(this.head.pivotZ);
}
if (this.bodyBone != null) {
IBone bodyBone = this.modelProvider.getBone(this.bodyBone);
GeoUtils.copyRotations(this.body, bodyBone);
bodyBone.setPositionX(this.body.pivotX);
bodyBone.setPositionY(-this.body.pivotY);
bodyBone.setPositionZ(this.body.pivotZ);
}
if (this.rightArmBone != null) {
IBone rightArmBone = this.modelProvider.getBone(this.rightArmBone);
GeoUtils.copyRotations(this.rightArm, rightArmBone);
rightArmBone.setPositionX(this.rightArm.pivotX + 5);
rightArmBone.setPositionY(2 - this.rightArm.pivotY);
rightArmBone.setPositionZ(this.rightArm.pivotZ);
}
if (this.leftArmBone != null) {
IBone leftArmBone = this.modelProvider.getBone(this.leftArmBone);
GeoUtils.copyRotations(this.leftArm, leftArmBone);
leftArmBone.setPositionX(this.leftArm.pivotX - 5);
leftArmBone.setPositionY(2 - this.leftArm.pivotY);
leftArmBone.setPositionZ(this.leftArm.pivotZ);
}
if (this.rightLegBone != null) {
IBone rightLegBone = this.modelProvider.getBone(this.rightLegBone);
GeoUtils.copyRotations(this.rightLeg, rightLegBone);
rightLegBone.setPositionX(this.rightLeg.pivotX + 2);
rightLegBone.setPositionY(12 - this.rightLeg.pivotY);
rightLegBone.setPositionZ(this.rightLeg.pivotZ);
}
if (this.leftLegBone != null) {
IBone leftLegBone = this.modelProvider.getBone(this.leftLegBone);
GeoUtils.copyRotations(this.leftLeg, leftLegBone);
leftLegBone.setPositionX(this.leftLeg.pivotX - 2);
leftLegBone.setPositionY(12 - this.leftLeg.pivotY);
leftLegBone.setPositionZ(this.leftLeg.pivotZ);
}
}
@Override
public AnimatedGeoModel<CosmeticItem> getGeoModelProvider() {
return this.modelProvider;
}
@AvailableSince(value = "3.1.24")
@Override
@Nonnull
public IRenderCycle getCurrentModelRenderCycle() {
return this.currentModelRenderCycle;
}
@AvailableSince(value = "3.1.24")
@Override
public void setCurrentModelRenderCycle(IRenderCycle currentModelRenderCycle) {
this.currentModelRenderCycle = currentModelRenderCycle;
}
@AvailableSince(value = "3.1.24")
@Override
public float getWidthScale(CosmeticItem animatable) {
return this.widthScale;
}
@AvailableSince(value = "3.1.24")
@Override
public float getHeightScale(CosmeticItem entity) {
return this.heightScale;
}
@Override
public Identifier getTextureLocation(CosmeticItem animatable) {
return this.modelProvider.getTextureLocation(animatable);
}
/**
* Everything after this point needs to be called every frame before rendering
*/
public CosmeticArmorRenderer setCurrentItem(LivingEntity entity, CosmeticItem item) {
this.entityLiving = entity;
this.currentArmorItem = item;
return this;
}
public final CosmeticArmorRenderer
applyEntityStats(BipedEntityModel<AbstractClientPlayerEntity> defaultArmor) {
this.child = defaultArmor.child;
this.sneaking = defaultArmor.sneaking;
this.riding = defaultArmor.riding;
this.rightArmPose = defaultArmor.rightArmPose;
this.leftArmPose = defaultArmor.leftArmPose;
return this;
}
public void filterBones() {
this.headBone = getCurrentCosmetic().getHead();
this.bodyBone = getCurrentCosmetic().getBody();
this.leftArmBone = getCurrentCosmetic().getLeftArm();
this.rightArmBone = getCurrentCosmetic().getRightArm();
this.leftLegBone = getCurrentCosmetic().getLeftLeg();
this.rightLegBone = getCurrentCosmetic().getRightLeg();
getGeoModelProvider().getModel(getCurrentCosmetic().getModelLocation());
this.setBoneVisibility(this.headBone, getCurrentCosmetic().getHead() != null);
this.setBoneVisibility(this.bodyBone, getCurrentCosmetic().getBody() != null);
this.setBoneVisibility(
this.leftArmBone, getCurrentCosmetic().getLeftArm() != null
);
this.setBoneVisibility(
this.rightArmBone, getCurrentCosmetic().getRightArm() != null
);
this.setBoneVisibility(
this.leftLegBone, getCurrentCosmetic().getLeftLeg() != null
);
this.setBoneVisibility(
this.rightLegBone, getCurrentCosmetic().getRightLeg() != null
);
}
/**
* Sets a specific bone (and its child-bones) to visible or not
* @param boneName The name of the bone
* @param isVisible Whether the bone should be visible
*/
protected void setBoneVisibility(String boneName, boolean isVisible) {
if (boneName == null)
return;
this.modelProvider.getBone(boneName).setHidden(!isVisible);
}
/**
* Use {@link CosmeticArmorRenderer#setBoneVisibility(String, boolean)}
*/
@Deprecated(forRemoval = true)
protected IBone getAndHideBone(String boneName) {
setBoneVisibility(boneName, false);
return this.modelProvider.getBone(boneName);
}
@Override
public int getInstanceId(CosmeticItem animatable) {
return Objects.hash(
this.currentArmorItem.getCosmetic().getID(), this.entityLiving.getUuid()
);
}
@Override
public void setCurrentRTB(VertexConsumerProvider bufferSource) {
this.rtb = bufferSource;
}
@Override
public VertexConsumerProvider getCurrentRTB() {
return this.rtb;
}
public ICosmetic getCurrentCosmetic() {
return this.currentArmorItem.getCosmetic();
}
}

View file

@ -0,0 +1,92 @@
package net.anvilcraft.anvillib.cosmetics;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.client.model.ModelPart;
import net.minecraft.client.network.AbstractClientPlayerEntity;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.entity.PlayerEntityRenderer;
import net.minecraft.client.render.entity.feature.ArmorFeatureRenderer;
import net.minecraft.client.render.entity.model.BipedEntityModel;
import net.minecraft.client.render.entity.model.PlayerEntityModel;
import net.minecraft.client.render.item.ItemRenderer;
import net.minecraft.client.util.math.MatrixStack;
public class CosmeticFeatureRenderer extends ArmorFeatureRenderer<
AbstractClientPlayerEntity,
PlayerEntityModel<AbstractClientPlayerEntity>,
BipedEntityModel<AbstractClientPlayerEntity>> {
private static final Map<ICosmetic, CosmeticItem> modelCache = new HashMap<>();
private static CosmeticArmorRenderer cosmeticRenderer = null;
PlayerEntityRenderer renderer;
String skin;
public CosmeticFeatureRenderer(PlayerEntityRenderer renderer, String skin) {
super(renderer, null, null);
this.renderer = renderer;
this.skin = skin;
}
@Override
public void render(
MatrixStack matrix,
VertexConsumerProvider buffer,
int light,
AbstractClientPlayerEntity player,
float limbSwing,
float limbSwingAmount,
float partialTicks,
float ageInTicks,
float netHeadYaw,
float headPitch
) {
for (ICosmetic c : CosmeticsManager.getCosmeticsForPlayer(player.getUuid())) {
if (c.readyToRender())
this.renderCosmetic(matrix, buffer, player, light, c, partialTicks);
}
}
private void renderCosmetic(
MatrixStack matrix,
VertexConsumerProvider buffer,
AbstractClientPlayerEntity player,
int light,
ICosmetic cosmetic,
float partialTicks
) {
if (cosmeticRenderer == null)
cosmeticRenderer = new CosmeticArmorRenderer();
if (!modelCache.containsKey(cosmetic))
modelCache.put(cosmetic, new CosmeticItem(cosmetic));
CosmeticItem item = modelCache.get(cosmetic);
copyRotations(this.renderer.getModel(), cosmeticRenderer);
cosmeticRenderer.applyEntityStats(this.renderer.getModel());
cosmeticRenderer.setCurrentItem(player, item);
cosmeticRenderer.filterBones();
VertexConsumer vertex = ItemRenderer.getArmorGlintConsumer(
buffer,
RenderLayer.getArmorCutoutNoCull(cosmetic.getTextureLocation()),
false,
false
);
cosmeticRenderer.render(partialTicks, matrix, vertex, light);
}
private static void copyRotations(BipedEntityModel<?> from, BipedEntityModel<?> to) {
copyRotations(from.head, to.head);
copyRotations(from.hat, to.hat);
copyRotations(from.body, to.body);
copyRotations(from.leftArm, to.leftArm);
copyRotations(from.rightArm, to.rightArm);
copyRotations(from.rightLeg, to.rightLeg);
copyRotations(from.leftLeg, to.leftLeg);
}
private static void copyRotations(ModelPart from, ModelPart to) {
to.copyTransform(from);
}
}

View file

@ -0,0 +1,44 @@
package net.anvilcraft.anvillib.cosmetics;
import software.bernie.geckolib3.core.IAnimatable;
import software.bernie.geckolib3.core.PlayState;
import software.bernie.geckolib3.core.builder.AnimationBuilder;
import software.bernie.geckolib3.core.controller.AnimationController;
import software.bernie.geckolib3.core.event.predicate.AnimationEvent;
import software.bernie.geckolib3.core.manager.AnimationData;
import software.bernie.geckolib3.core.manager.AnimationFactory;
import software.bernie.geckolib3.util.GeckoLibUtil;
public class CosmeticItem implements IAnimatable {
private ICosmetic cosmetic = null;
private AnimationBuilder animationBuilder = new AnimationBuilder();
public CosmeticItem(ICosmetic cosmetic) {
this.cosmetic = cosmetic;
this.cosmetic.addAnimations(animationBuilder);
}
private <P extends IAnimatable> PlayState predicate(AnimationEvent<P> event) {
event.getController().transitionLengthTicks = 0;
event.getController().setAnimation(animationBuilder);
return PlayState.CONTINUE;
}
@Override
public void registerControllers(AnimationData data) {
data.addAnimationController(
new AnimationController<>(this, "controller", 20, this::predicate)
);
}
private final AnimationFactory factory = GeckoLibUtil.createFactory(this);
@Override
public AnimationFactory getFactory() {
return this.factory;
}
public ICosmetic getCosmetic() {
return this.cosmetic;
}
}

View file

@ -0,0 +1,21 @@
package net.anvilcraft.anvillib.cosmetics;
import net.minecraft.util.Identifier;
import software.bernie.geckolib3.model.AnimatedGeoModel;
public class CosmeticModel extends AnimatedGeoModel<CosmeticItem> {
@Override
public Identifier getAnimationFileLocation(CosmeticItem animatable) {
return animatable.getCosmetic().getAnimationFileLocation();
}
@Override
public Identifier getModelLocation(CosmeticItem animatable) {
return animatable.getCosmetic().getModelLocation();
}
@Override
public Identifier getTextureLocation(CosmeticItem animatable) {
return animatable.getCosmetic().getTextureLocation();
}
}

View file

@ -0,0 +1,51 @@
package net.anvilcraft.anvillib.cosmetics;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public class CosmeticsManager {
private static List<ICosmeticProvider> providers = new ArrayList<>();
private static Map<UUID, List<ICosmetic>> cosmeticCache = new HashMap<>();
private static Set<UUID> activePlayers = new HashSet<>();
private static void refresh() {
boolean doRefresh = false;
for (ICosmeticProvider provider : providers) {
doRefresh = doRefresh || provider.requestsRefresh();
}
if (!doRefresh)
return;
cosmeticCache.clear();
for (UUID uuid : activePlayers) {
loadPlayer(uuid);
}
}
private static void loadPlayer(UUID player) {
if (cosmeticCache.containsKey(player))
return;
cosmeticCache.put(player, new ArrayList<>());
List<ICosmetic> cosmetics = cosmeticCache.get(player);
for (ICosmeticProvider provider : providers) {
provider.addCosmetics(player, (cosmetic) -> cosmetics.add(cosmetic));
}
}
public static void registerProvider(ICosmeticProvider provider) {
providers.add(provider);
}
protected static List<ICosmetic> getCosmeticsForPlayer(UUID uuid) {
if (!activePlayers.contains(uuid)) {
activePlayers.add(uuid);
loadPlayer(uuid);
}
refresh();
return cosmeticCache.get(uuid);
}
}

View file

@ -0,0 +1,44 @@
package net.anvilcraft.anvillib.cosmetics;
import net.minecraft.util.Identifier;
import software.bernie.geckolib3.core.builder.AnimationBuilder;
public interface ICosmetic {
Identifier getAnimationFileLocation();
Identifier getModelLocation();
Identifier getTextureLocation();
default String getHead() {
return null; //head
}
default String getBody() {
return null; //body
}
default String getLeftArm() {
return null; //arm_left
}
default String getRightArm() {
return null; //arm_right
}
default String getLeftLeg() {
return null; //leg_left
}
default String getRightLeg() {
return null; //leg_right
}
void addAnimations(AnimationBuilder builder);
default boolean readyToRender() {
return true;
}
Identifier getID();
}

View file

@ -0,0 +1,10 @@
package net.anvilcraft.anvillib.cosmetics;
import java.util.UUID;
import java.util.function.Consumer;
public interface ICosmeticProvider {
boolean requestsRefresh();
void addCosmetics(UUID player, Consumer<ICosmetic> cosmeticAdder);
}

View file

@ -0,0 +1,48 @@
package net.anvilcraft.anvillib.mixin.common;
import java.util.HashMap;
import java.util.Map;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.google.gson.JsonElement;
import net.anvilcraft.anvillib.AnvilLib;
import net.anvilcraft.anvillib.recipe.RecipesEvent;
import net.minecraft.recipe.Recipe;
import net.minecraft.recipe.RecipeManager;
import net.minecraft.recipe.RecipeType;
import net.minecraft.resource.ResourceManager;
import net.minecraft.util.Identifier;
import net.minecraft.util.profiler.Profiler;
import net.minecraftforge.fml.ModLoader;
@Mixin(RecipeManager.class)
public class RecipeManagerMixin {
@Shadow
private Map<RecipeType<?>, Map<Identifier, Recipe<?>>> recipes;
@Shadow
private Map<Identifier, Recipe<?>> recipesById;
@Inject(method = "apply", at = @At("RETURN"))
private void afterLoad(
Map<Identifier, JsonElement> alec1,
ResourceManager alec2,
Profiler alec3,
CallbackInfo ci
) {
AnvilLib.LOGGER.info("Firing Recipe Event");
Map<RecipeType<?>, Map<Identifier, Recipe<?>>> recipes = new HashMap<>();
this.recipes.forEach((k, v) -> recipes.put(k, new HashMap<>(v)));
var ev = new RecipesEvent(recipes, new HashMap<>(this.recipesById));
ModLoader.get().postEvent(ev);
this.recipes = ev.recipes;
this.recipesById = ev.recipesById;
}
}

View file

@ -0,0 +1,23 @@
package net.anvilcraft.anvillib.recipe;
import java.util.Arrays;
import java.util.function.Predicate;
import net.anvilcraft.anvillib.Util;
import net.minecraft.recipe.Ingredient;
import net.minecraft.util.Identifier;
public abstract class AbstractIngredientCondition implements Predicate<Ingredient> {
public static AbstractIngredientCondition of(String s) {
return s.charAt(0) == '#'
? new TagIngredientCondition(new Identifier(s.substring(1)))
: new StackIngredientCondition(Util.stackFromRegistry(new Identifier(s)));
}
@Override
public boolean test(Ingredient i) {
return Arrays.stream(i.entries).anyMatch(this::entryMatches);
}
public abstract boolean entryMatches(Ingredient.Entry e);
}

View file

@ -0,0 +1,12 @@
package net.anvilcraft.anvillib.recipe;
import java.util.function.Function;
import net.minecraft.recipe.Recipe;
/**
* IRecipeMapper describes a class that knows how to conditionally replace recipes.
*/
public interface IRecipeMapper extends Function<Recipe<?>, Recipe<?>> {
public boolean shouldMap(Recipe<?> recipe);
}

View file

@ -0,0 +1,19 @@
package net.anvilcraft.anvillib.recipe;
import java.util.function.Predicate;
import net.minecraft.recipe.Ingredient;
import net.minecraft.recipe.Recipe;
public class IngredientsContainPredicate implements Predicate<Recipe<?>> {
public Predicate<Ingredient> pred;
public IngredientsContainPredicate(Predicate<Ingredient> pred) {
this.pred = pred;
}
@Override
public boolean test(Recipe<?> r) {
return r.getIngredients().stream().anyMatch(this.pred);
}
}

View file

@ -0,0 +1,54 @@
package net.anvilcraft.anvillib.recipe;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
import net.anvilcraft.anvillib.Util;
import net.minecraft.recipe.Ingredient;
import net.minecraft.recipe.Recipe;
public class InputReplaceRecipeMapper implements IRecipeMapper {
public Map<Predicate<Ingredient>, Ingredient> replacements = new HashMap<>();
public InputReplaceRecipeMapper replace(Predicate<Ingredient> p, Ingredient i) {
this.replacements.put(p, i);
return this;
}
public InputReplaceRecipeMapper replace(String p, Ingredient i) {
return this.replace(AbstractIngredientCondition.of(p), i);
}
public InputReplaceRecipeMapper replace(String p, String i) {
return this.replace(p, Util.ingredientFromString(i));
}
public InputReplaceRecipeMapper replace(Predicate<Ingredient> p, String i) {
return this.replace(p, Util.ingredientFromString(i));
}
@Override
public boolean shouldMap(Recipe<?> recipe) {
var ingredients = recipe.getIngredients();
if (ingredients == null)
return false;
for (var k : this.replacements.keySet())
if (ingredients.stream().anyMatch(k))
return true;
return false;
}
@Override
public Recipe<?> apply(Recipe<?> recipe) {
var ingredients = recipe.getIngredients();
for (int i = 0; i < ingredients.size(); i++) {
var ing = ingredients.get(i);
for (var entry : this.replacements.entrySet())
if (entry.getKey().test(ing))
ingredients.set(i, entry.getValue());
}
return recipe;
}
}

View file

@ -0,0 +1,22 @@
package net.anvilcraft.anvillib.recipe;
import java.util.function.Predicate;
import net.minecraft.item.ItemStack;
import net.minecraft.recipe.Recipe;
public class RecipeContainsPredicate implements Predicate<Recipe<?>> {
public ItemStack item;
public RecipeContainsPredicate(ItemStack item) {
this.item = item;
}
@Override
public boolean test(Recipe<?> r) {
return r.getIngredients() == null
? false
: r.getIngredients().stream().anyMatch(new StackIngredientCondition(this.item)
) || r.getOutput().isItemEqual(this.item);
}
}

View file

@ -0,0 +1,81 @@
package net.anvilcraft.anvillib.recipe;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import net.minecraft.recipe.Recipe;
import net.minecraft.recipe.RecipeType;
import net.minecraft.util.Identifier;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.event.IModBusEvent;
public class RecipesEvent extends Event implements IModBusEvent {
public Map<RecipeType<?>, Map<Identifier, Recipe<?>>> recipes;
public Map<Identifier, Recipe<?>> recipesById;
public RecipesEvent(
Map<RecipeType<?>, Map<Identifier, Recipe<?>>> recipes,
Map<Identifier, Recipe<?>> recipesById
) {
this.recipes = recipes;
this.recipesById = recipesById;
}
public void registerRecipe(Recipe<?> recipe) {
if (!this.recipes.containsKey(recipe.getType()))
this.recipes.put(recipe.getType(), new HashMap<>());
this.recipes.get(recipe.getType()).put(recipe.getId(), recipe);
this.recipesById.put(recipe.getId(), recipe);
}
public Optional<Recipe<?>> removeRecipeID(Identifier id) {
if (this.recipesById.containsKey(id)) {
return Optional.of(
this.recipes.get(this.recipesById.remove(id).getType()).remove(id)
);
}
return Optional.empty();
}
public void removeRecipesMatching(Predicate<Recipe<?>> p) {
var iter = this.recipesById.entrySet().iterator();
while (iter.hasNext()) {
var entry = iter.next();
if (p.test(entry.getValue())) {
iter.remove();
this.recipes.get(entry.getValue().getType()).remove(entry.getKey());
}
}
}
public void mapRecipes(IRecipeMapper mapper) {
var iter = this.recipesById.entrySet().iterator();
while (iter.hasNext()) {
var entry = iter.next();
if (mapper.shouldMap(entry.getValue())) {
var mapped = mapper.apply(entry.getValue());
if (mapped != entry.getValue()) {
iter.remove();
this.recipes.get(entry.getValue().getType()).remove(entry.getKey());
this.registerRecipe(mapped);
}
}
}
}
public void mapRecipeID(Identifier id, Function<Recipe<?>, Recipe<?>> func) {
var recipe = this.recipesById.get(id);
if (recipe != null) {
var mapped = func.apply(recipe);
if (recipe != mapped) {
this.removeRecipeID(id);
this.registerRecipe(mapped);
}
}
}
}

View file

@ -0,0 +1,95 @@
package net.anvilcraft.anvillib.recipe;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.recipe.Ingredient;
import net.minecraft.recipe.ShapedRecipe;
import net.minecraft.tag.TagKey;
import net.minecraft.util.Identifier;
import net.minecraft.util.collection.DefaultedList;
import net.minecraft.util.registry.Registry;
import net.minecraftforge.registries.ForgeRegistries;
public class ShapedRecipeBuilder {
public Identifier ident;
public String[] pattern;
public Map<Character, Ingredient> ingredients = new HashMap<>();
public ItemStack output;
public ShapedRecipeBuilder(Identifier ident, ItemStack output) {
this.ident = ident;
this.output = output;
}
public ShapedRecipeBuilder pattern(String... pat) {
this.pattern = pat;
return this;
}
public ShapedRecipeBuilder ingredient(char c, Ingredient i) {
this.ingredients.put(c, i);
return this;
}
public ShapedRecipeBuilder ingredient(char c, ItemStack... is) {
return this.ingredient(c, Ingredient.ofStacks(is));
}
public ShapedRecipeBuilder ingredient(char c, Item i) {
return this.ingredient(c, new ItemStack(i));
}
public ShapedRecipeBuilder ingredient(char c, Block b) {
return this.ingredient(c, new ItemStack(b));
}
public ShapedRecipeBuilder ingredient(char c, String s) {
if (s.charAt(0) == '#') {
return this.tagIngredient(c, new Identifier(s.substring(1)));
}
var ident = new Identifier(s);
var maybeItem = ForgeRegistries.ITEMS.getValue(ident);
if (maybeItem == null) {
var maybeBlock = ForgeRegistries.BLOCKS.getValue(ident);
if (maybeBlock == null)
throw new IllegalArgumentException(
"ID " + s + " not found in item or block registry!"
);
return this.ingredient(c, maybeBlock);
}
return this.ingredient(c, maybeItem);
}
public ShapedRecipeBuilder tagIngredient(char c, Identifier t) {
return this.ingredient(c, Ingredient.fromTag(TagKey.of(Registry.ITEM_KEY, t)));
}
public ShapedRecipe build() {
int width = -1;
for (String line : this.pattern) {
if (width != -1 && width != line.length())
throw new IllegalArgumentException(
"Lines in crafting pattern must be same width!"
);
width = line.length();
}
DefaultedList<Ingredient> ingredients = DefaultedList.of();
Arrays.stream(this.pattern)
.flatMap(s -> s.chars().mapToObj(c -> (char) c))
.map(this.ingredients::get)
.forEach(ingredients::add);
return new ShapedRecipe(
this.ident, "", width, this.pattern.length, ingredients, this.output
);
}
}

View file

@ -0,0 +1,18 @@
package net.anvilcraft.anvillib.recipe;
import net.minecraft.item.ItemStack;
import net.minecraft.recipe.Ingredient.Entry;
import net.minecraft.recipe.Ingredient.StackEntry;
public class StackIngredientCondition extends AbstractIngredientCondition {
public ItemStack stack;
public StackIngredientCondition(ItemStack stack) {
this.stack = stack;
}
@Override
public boolean entryMatches(Entry e) {
return e instanceof StackEntry se && se.stack.isItemEqual(this.stack);
}
}

View file

@ -0,0 +1,18 @@
package net.anvilcraft.anvillib.recipe;
import net.minecraft.recipe.Ingredient.Entry;
import net.minecraft.recipe.Ingredient.TagEntry;
import net.minecraft.util.Identifier;
public class TagIngredientCondition extends AbstractIngredientCondition {
public Identifier id;
public TagIngredientCondition(Identifier id) {
this.id = id;
}
@Override
public boolean entryMatches(Entry e) {
return e instanceof TagEntry te && te.tag.id().equals(this.id);
}
}

View file

@ -0,0 +1,3 @@
public net.minecraft.world.item.crafting.Ingredient f_43902_ # Ingredient.entries
public net.minecraft.world.item.crafting.Ingredient$TagValue f_43959_ # Ingredient$TagEntry.tag
public net.minecraft.world.item.crafting.Ingredient$ItemValue f_43951_ # Ingredient$StackEntry.stack

View file

@ -0,0 +1,41 @@
modLoader = "javafml"
loaderVersion = "[40,)"
license = "AGPL-3.0+ALEC"
issueTrackerURL = "https://git.tilera.org/Anvilcraft/anvillib/issues"
[[mods]]
modId = "anvillib"
version = "${version}"
displayName = "anvillib"
displayURL = "https://anvilcraft.net/"
#credits = ""
authors = "LordMZTE, (tilera)"
description = '''
Core for Notex 4.
Includes recipes and tweaks.
'''
[[dependencies.anvillib]]
modId = "forge"
mandatory = true
versionRange = "[40,)"
ordering = "NONE"
side = "BOTH"
[[dependencies.anvillib]]
modId = "minecraft"
mandatory = true
versionRange = "[1.18.2]"
ordering = "NONE"
side = "BOTH"
[[dependencies.anvillib]]
modId = "geckolib3"
mandatory = true
versionRange = "[3.0.57,)"
ordering = "NONE"
side = "BOTH"

View file

@ -0,0 +1,13 @@
{
"required": true,
"package": "net.anvilcraft.anvillib.mixin",
"compatibilityLevel": "JAVA_17",
"minVersion": "0.8",
"mixins": [
"common.RecipeManagerMixin"
],
"client": [],
"injectors": {
"defaultRequire": 1
}
}

View file

@ -0,0 +1,7 @@
{
"pack": {
"description": "Resources for anvillib",
"pack_format": 8,
"_comment": "pack_format 8 is the current format for Minecraft 1.18.2. Be aware may have changed by the time you use this template!"
}
}