feat: 升级到1.21.1,neoforge代码还需修复错误

This commit is contained in:
叁玖领域 2026-05-07 00:02:08 +08:00
parent 5fb2c614db
commit 4a22bbe4a9
101 changed files with 1344 additions and 925 deletions

View File

@ -48,6 +48,9 @@ repositories {
name = 'BlameJared' name = 'BlameJared'
url = 'https://maven.blamejared.com' url = 'https://maven.blamejared.com'
} }
repositories {
maven { url 'https://maven.covers1624.net/' }
}
} }
// Declare capabilities on the outgoing configurations. // Declare capabilities on the outgoing configurations.
@ -101,24 +104,17 @@ processResources {
'mod_id' : mod_id, 'mod_id' : mod_id,
'license' : license, 'license' : license,
'description' : project.description, 'description' : project.description,
"forge_version" : forge_version, 'neoforge_version' : neoforge_version,
"forge_loader_version_range" : forge_loader_version_range, 'neoforge_loader_version_range': neoforge_loader_version_range,
"neoforge_version": neoforge_version,
"neoforge_loader_version_range": neoforge_loader_version_range,
'credits' : credits, 'credits' : credits,
'java_version' : java_version 'java_version' : java_version
] ]
var jsonExpandProps = expandProps.collectEntries { filesMatching(['pack.mcmeta', 'fabric.mod.json', 'META-INF/mods.toml', 'META-INF/neoforge.mods.toml', '*.mixins.json']) {
key, value -> [(key): value instanceof String ? value.replace("\n", "\\\\n") : value]
}
filesMatching(['META-INF/mods.toml']) {
expand expandProps expand expandProps
} }
filesMatching(['pack.mcmeta', 'fabric.mod.json', '*.mixins.json']) {
expand jsonExpandProps
}
inputs.properties(expandProps) inputs.properties(expandProps)
} }
@ -130,19 +126,18 @@ publishing {
pom { pom {
name = 'Lib39' name = 'Lib39'
description = 'Lib39 is a general-purpose dependency library for Minecraft mods.' description = 'Lib39 is a general-purpose dependency library for Minecraft mods.'
url = 'https://github.com/3944Realms/lib39' url = 'https://gitea.bot.leisuretimedock.top/R3944Realms/Lib39'
properties = [ properties = [
'minecraft.version': project.minecraft_version, 'minecraft.version': project.minecraft_version,
'mod.version': project.version, 'mod.version': project.version,
'forge.version': project.forge_version, 'java.version': project.java_version
'java.version': '17'
] ]
licenses { licenses {
license { license {
name = 'MIT' name = 'MIT'
url = 'https://raw.githubusercontent.com/3944Realms/lib39/refs/heads/main/LICENSE' url = 'https://gitea.bot.leisuretimedock.top/R3944Realms/Lib39/raw/branch/MultiLoader_1_21_1/LICENSE'
distribution = 'repo' distribution = 'repo'
} }
} }
@ -156,15 +151,15 @@ publishing {
} }
scm { scm {
connection = 'scm:git:https://github.com/3944Realms/lib39.git' connection = 'scm:git:git@bot.leisuretimedock.top:R3944Realms/Lib39.git'
developerConnection = 'scm:git:ssh://git@github.com:3944Realms/lib39.git' developerConnection = 'scm:git:ssh://git@bot.leisuretimedock.top:R3944Realms/Lib39.git'
url = 'https://github.com/3944Realms/lib39' url = 'https://gitea.bot.leisuretimedock.top/R3944Realms/Lib39'
tag = 'main' tag = 'main'
} }
issueManagement { issueManagement {
system = 'GitHub' system = 'Gitea'
url = 'https://github.com/3944Realms/lib39/issues' url = 'https://gitea.bot.leisuretimedock.top/R3944Realms/Lib39/issues'
} }
} }
} }

View File

@ -36,7 +36,7 @@ tasks.named('javadoc', Javadoc).configure {
source(configurations.commonJava) source(configurations.commonJava)
options.encoding = 'UTF-8' options.encoding = 'UTF-8'
options.charSet = 'UTF-8' options.charSet = 'UTF-8'
options.links("https://docs.oracle.com/en/java/javase/17/docs/api/") options.links("https://docs.oracle.com/en/java/javase/21/docs/api/")
options.memberLevel = JavadocMemberLevel.PUBLIC options.memberLevel = JavadocMemberLevel.PUBLIC
options.addBooleanOption('Xdoclint:none', true) options.addBooleanOption('Xdoclint:none', true)
options.addStringOption('doctitle', "${mod_id} ${minecraft_version} ${version} Javadoc") options.addStringOption('doctitle', "${mod_id} ${minecraft_version} ${version} Javadoc")

View File

@ -1,12 +1,14 @@
plugins { plugins {
id 'multiloader-common' id 'multiloader-common'
id 'net.neoforged.moddev.legacyforge' id 'net.neoforged.moddev'
} }
legacyForge { neoForge {
mcpVersion = minecraft_version neoFormVersion = neo_form_version
if (file("src/main/resources/META-INF/accesstransformer.cfg").exists()) { // Automatically enable AccessTransformers if the file exists
accessTransformers = ["src/main/resources/META-INF/accesstransformer.cfg"] def at = file('src/main/resources/META-INF/accesstransformer.cfg')
if (at.exists()) {
accessTransformers.from(at.absolutePath)
} }
parchment { parchment {
minecraftVersion = parchment_minecraft minecraftVersion = parchment_minecraft
@ -14,13 +16,16 @@ legacyForge {
} }
} }
dependencies { dependencies {
compileOnly(group: 'org.spongepowered', name: 'mixin', version: '0.8.5') compileOnly group: 'org.spongepowered', name: 'mixin', version: '0.8.5'
implementation(group: 'tschipp.carryon', name: 'carryon-common-1.20.1', version: '2.1.2') {
implementation(group: 'tschipp.carryon', name: 'carryon-common-1.21.1', version: '2.2.4') {
transitive = false transitive = false
} }
implementation(annotationProcessor("io.github.llamalad7:mixinextras-common:0.2.0")) // fabric and neoforge both bundle mixinextras, so it is safe to use it in common
implementation(group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.1') compileOnly group: 'io.github.llamalad7', name: 'mixinextras-common', version: '0.3.5'
annotationProcessor group: 'io.github.llamalad7', name: 'mixinextras-common', version: '0.3.5'
} }
configurations { configurations {
commonJava { commonJava {

View File

@ -49,7 +49,7 @@ public class Lib39 {
*/ */
@Contract("_ -> new") @Contract("_ -> new")
public static @NotNull ResourceLocation rl(String path) { public static @NotNull ResourceLocation rl(String path) {
return new ResourceLocation(Lib39.MOD_ID, path); return ResourceLocation.fromNamespaceAndPath(Lib39.MOD_ID, path);
} }
/** /**
@ -61,7 +61,7 @@ public class Lib39 {
*/ */
@Contract("_, _ -> new") @Contract("_, _ -> new")
public static @NotNull ResourceLocation rl(String modId, String path) { public static @NotNull ResourceLocation rl(String modId, String path) {
return new ResourceLocation(modId, path); return ResourceLocation.fromNamespaceAndPath(modId, path);
} }
/** /**
@ -72,7 +72,7 @@ public class Lib39 {
*/ */
@Contract("_ -> new") @Contract("_ -> new")
public static @NotNull ResourceLocation mrl(String path) { public static @NotNull ResourceLocation mrl(String path) {
return new ResourceLocation(path); return ResourceLocation.withDefaultNamespace(path);
} }
/** /**

View File

@ -1,16 +1,13 @@
package top.r3944realms.lib39.base.datagen.provider; package top.r3944realms.lib39.base.datagen.provider;
import net.minecraft.core.HolderLookup;
import net.minecraft.data.PackOutput; import net.minecraft.data.PackOutput;
import net.minecraft.data.recipes.FinishedRecipe; import net.minecraft.data.recipes.*;
import net.minecraft.data.recipes.RecipeCategory;
import net.minecraft.data.recipes.RecipeProvider;
import net.minecraft.data.recipes.ShapelessRecipeBuilder;
import net.minecraft.tags.ItemTags; import net.minecraft.tags.ItemTags;
import net.minecraft.world.item.Items; import net.minecraft.world.item.Items;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.lib39.core.register.Lib39Items; import top.r3944realms.lib39.core.register.Lib39Items;
import java.util.function.Consumer; import java.util.concurrent.CompletableFuture;
/** /**
* The type Lib 39 recipe provider. * The type Lib 39 recipe provider.
@ -19,18 +16,19 @@ public class Lib39RecipeProvider extends RecipeProvider {
/** /**
* Instantiates a new Lib 39 recipe provider. * Instantiates a new Lib 39 recipe provider.
* *
* @param output the output * @param output the output
* @param registries the registries
*/ */
public Lib39RecipeProvider(PackOutput output) { public Lib39RecipeProvider(PackOutput output, CompletableFuture<HolderLookup.Provider> registries) {
super(output); super(output, registries);
} }
@Override @Override
public void buildRecipes(@NotNull Consumer<FinishedRecipe> consumer) { protected void buildRecipes(RecipeOutput recipeOutput) {
ShapelessRecipeBuilder.shapeless(RecipeCategory.MISC, Lib39Items.DOLL.get()) ShapelessRecipeBuilder.shapeless(RecipeCategory.MISC, Lib39Items.DOLL.get())
.requires(ItemTags.WOOL) .requires(ItemTags.WOOL)
.requires(Items.ARMOR_STAND) .requires(Items.ARMOR_STAND)
.unlockedBy("has_armor_stand",has(Items.ARMOR_STAND)) .unlockedBy("has_armor_stand",has(Items.ARMOR_STAND))
.save(consumer); .save(recipeOutput);
} }
} }

View File

@ -78,6 +78,7 @@ public class WheelWidget extends AbstractWidget {
private Vector2f selectionEffectPos; private Vector2f selectionEffectPos;
private boolean animationStarted = false; private boolean animationStarted = false;
/** /**
* Sets closing animation started. * Sets closing animation started.
* *
@ -384,16 +385,15 @@ public class WheelWidget extends AbstractWidget {
return this.sections.size(); return this.sections.size();
} }
@Override @Override
public boolean mouseScrolled(double mouseX, double mouseY, double delta) { public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) {
if (delta > 0) { if (scrollY > 0) {
if (this.currentSectionIndex == this.getSectionSize() - 1) { if (this.currentSectionIndex == this.getSectionSize() - 1) {
this.currentSectionIndex = 0; this.currentSectionIndex = 0;
} else { } else {
this.currentSectionIndex++; this.currentSectionIndex++;
} }
} else if (delta < 0) { } else if (scrollY < 0) {
if (this.currentSectionIndex == 0) { if (this.currentSectionIndex == 0) {
this.currentSectionIndex = this.getSectionSize() - 1; this.currentSectionIndex = this.getSectionSize() - 1;
} else { } else {
@ -451,13 +451,8 @@ public class WheelWidget extends AbstractWidget {
} }
@Override @Override
public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) { protected void renderWidget(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
this.checkMousePos(mouseX, mouseY); checkMousePos(mouseX, mouseY);
this.renderWidget(guiGraphics, mouseX, mouseY, partialTick);
}
@Override
protected void renderWidget(GuiGraphics guiGraphics, int i, int i1, float v) {
RenderSystem.enableDepthTest(); RenderSystem.enableDepthTest();
RenderSystem.enableBlend(); RenderSystem.enableBlend();
this.renderClosingAnimation(guiGraphics); this.renderClosingAnimation(guiGraphics);
@ -597,7 +592,6 @@ public class WheelWidget extends AbstractWidget {
poseStack.pushPose(); poseStack.pushPose();
Tesselator tesselator = Tesselator.getInstance(); Tesselator tesselator = Tesselator.getInstance();
BufferBuilder buffer = tesselator.getBuilder();
// 计算足够大的绘制区域来覆盖整个环形基于外半径 // 计算足够大的绘制区域来覆盖整个环形基于外半径
float margin = outerRadius + 100f; // 使用半径计算边距 float margin = outerRadius + 100f; // 使用半径计算边距
@ -606,17 +600,17 @@ public class WheelWidget extends AbstractWidget {
float x2 = centerX + margin; float x2 = centerX + margin;
float y2 = centerY + margin; float y2 = centerY + margin;
buffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); BufferBuilder buffer = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);
Matrix4f matrix = poseStack.last().pose(); Matrix4f matrix = poseStack.last().pose();
buffer.vertex(matrix, x1, y1, -300).color(color).endVertex(); buffer.addVertex(matrix, x1, y1, -300).setColor(color);
buffer.vertex(matrix, x1, y2, -300).color(color).endVertex(); buffer.addVertex(matrix, x1, y2, -300).setColor(color);
buffer.vertex(matrix, x2, y2, -300).color(color).endVertex(); buffer.addVertex(matrix, x2, y2, -300).setColor(color);
buffer.vertex(matrix, x2, y1, -300).color(color).endVertex(); buffer.addVertex(matrix, x2, y1, -300).setColor(color);
setupRingShader(centerX, centerY, innerRadius, outerRadius); setupRingShader(centerX, centerY, innerRadius, outerRadius);
BufferUploader.drawWithShader(buffer.end()); BufferUploader.drawWithShader(buffer.build());
poseStack.popPose(); poseStack.popPose();
} }
@ -703,17 +697,16 @@ public class WheelWidget extends AbstractWidget {
PoseStack poseStack = guiGraphics.pose(); PoseStack poseStack = guiGraphics.pose();
Matrix4f matrix4f = poseStack.last().pose(); Matrix4f matrix4f = poseStack.last().pose();
Tesselator tesselator = Tesselator.getInstance(); Tesselator tesselator = Tesselator.getInstance();
BufferBuilder buffer = tesselator.getBuilder(); BufferBuilder buffer = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);
buffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);
float x1 = centerX - radius - 5; float x1 = centerX - radius - 5;
float y1 = centerY - radius - 5; float y1 = centerY - radius - 5;
float x2 = centerX + radius + 5; float x2 = centerX + radius + 5;
float y2 = centerY + radius + 5; float y2 = centerY + radius + 5;
buffer.vertex(matrix4f, x1, y1, -200).color(color).endVertex(); buffer.addVertex(matrix4f, x1, y1, -200).setColor(color);
buffer.vertex(matrix4f, x1, y2, -200).color(color).endVertex(); buffer.addVertex(matrix4f, x1, y2, -200).setColor(color);
buffer.vertex(matrix4f, x2, y2, -200).color(color).endVertex(); buffer.addVertex(matrix4f, x2, y2, -200).setColor(color);
buffer.vertex(matrix4f, x2, y1, -200).color(color).endVertex(); buffer.addVertex(matrix4f, x2, y1, -200).setColor(color);
Window window = Minecraft.getInstance().getWindow(); Window window = Minecraft.getInstance().getWindow();
float guiScale = (float) window.getGuiScale(); float guiScale = (float) window.getGuiScale();
@ -736,7 +729,7 @@ public class WheelWidget extends AbstractWidget {
.safeGetUniform("AntiAliasingRadius") .safeGetUniform("AntiAliasingRadius")
.set(guiScale); // 根据需要调整 .set(guiScale); // 根据需要调整
RenderSystem.setShaderColor(1, 1, 1, 1); RenderSystem.setShaderColor(1, 1, 1, 1);
BufferUploader.drawWithShader(Objects.requireNonNull(buffer.end())); BufferUploader.drawWithShader(Objects.requireNonNull(buffer.build()));
RenderSystem.enableDepthTest(); RenderSystem.enableDepthTest();
} }

View File

@ -5,10 +5,10 @@ import com.mojang.blaze3d.vertex.VertexConsumer;
import net.minecraft.client.model.Model; import net.minecraft.client.model.Model;
import net.minecraft.client.model.geom.ModelLayerLocation; import net.minecraft.client.model.geom.ModelLayerLocation;
import net.minecraft.client.model.geom.ModelPart; import net.minecraft.client.model.geom.ModelPart;
import net.minecraft.client.model.geom.PartPose;
import net.minecraft.client.model.geom.builders.*; import net.minecraft.client.model.geom.builders.*;
import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.RenderType;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
/** /**
@ -31,13 +31,42 @@ public class DollModel extends Model {
private final ModelPart rightArmSlim; private final ModelPart rightArmSlim;
private final ModelPart leftArmSlim; private final ModelPart leftArmSlim;
private final ModelPart leftLeg; private final ModelPart leftLeg;
@Nullable
private IDollPose currentPose;
@Nullable
public IDollPose getCurrentPose() {
return currentPose;
}
public void setDollPose(@NotNull IDollPose dollPose) {
this.currentPose = dollPose;
this.head.loadPose(dollPose.getHeadPose());
this.body.loadPose(dollPose.getBodyPose());
this.rightArm.loadPose(dollPose.getRightArmPose());
this.leftArm.loadPose(dollPose.getLeftArmPose());
this.rightArmSlim.loadPose(dollPose.getRightArmPose());
this.leftArmSlim.loadPose(dollPose.getLeftArmPose());
this.rightLeg.loadPose(dollPose.getRightLegPose());
this.leftLeg.loadPose(dollPose.getLeftLegPose());
}
public void resetPose() {
this.currentPose = DollPoses.DEFAULT;
this.head.resetPose();
this.body.resetPose();
this.rightArm.resetPose();
this.leftArm.resetPose();
this.rightArmSlim.resetPose();
this.leftArmSlim.resetPose();
this.rightLeg.resetPose();
this.leftLeg.resetPose();
}
/** /**
* Instantiates a new Doll model. * Instantiates a new Doll model.
* *
* @param root the root * @param root the root
*/ */
public DollModel(ModelPart root) { public DollModel(@NotNull ModelPart root) {
super(RenderType::entityTranslucent); super(RenderType::entityTranslucent);
this.head = root.getChild("head"); this.head = root.getChild("head");
this.body = root.getChild("body"); this.body = root.getChild("body");
@ -48,44 +77,123 @@ public class DollModel extends Model {
this.rightLeg = root.getChild("right_leg"); this.rightLeg = root.getChild("right_leg");
this.leftLeg = root.getChild("left_leg"); this.leftLeg = root.getChild("left_leg");
} }
/** /**
* Create body layer layer definition. * Create body layer layer definition.
* *
* @return the layer definition * @return the layer definition
*/ */
public static LayerDefinition createBodyLayer() { public static @NotNull LayerDefinition createBodyLayer() {
return createBodyLayer(DollPoses.DEFAULT);
}
private static @NotNull LayerDefinition createBodyLayer(@NotNull IDollPose dollPoses) {
MeshDefinition meshdefinition = new MeshDefinition(); MeshDefinition meshdefinition = new MeshDefinition();
PartDefinition partdefinition = meshdefinition.getRoot(); PartDefinition partdefinition = meshdefinition.getRoot();
partdefinition.addOrReplaceChild("head", CubeListBuilder.create().texOffs(0, 0).addBox(-4.0F, -8.0F, -4.0F, 8.0F, 8.0F, 8.0F, new CubeDeformation(0.0F)).texOffs(32, 0).addBox(-4.0F, -8.0F, -4.0F, 8.0F, 8.0F, 8.0F, new CubeDeformation(0.5F)), PartPose.offset(0.0F, 9.0F, 0.0F)); partdefinition.addOrReplaceChild(
partdefinition.addOrReplaceChild("body", CubeListBuilder.create().texOffs(16, 16).addBox(-4.0F, 0.0F, -2.0F, 8.0F, 12.0F, 4.0F, new CubeDeformation(0.0F)).texOffs(16, 32).addBox(-4.0F, 0.0F, -2.0F, 8.0F, 12.0F, 4.0F, new CubeDeformation(0.25F)), PartPose.offset(0.0F, 9.0F, 0.0F)); "head",
partdefinition.addOrReplaceChild("right_arm", CubeListBuilder.create().texOffs(40, 16).addBox(-3.0F, -2.0F, -2.0F, 4.0F, 12.0F, 4.0F, new CubeDeformation(0.0F)).texOffs(40, 32).addBox(-3.0F, -2.0F, -2.0F, 4.0F, 12.0F, 4.0F, new CubeDeformation(0.25F)), PartPose.offsetAndRotation(-5.0F, 11.0F, 0.0F, 0.0F, 0.0F, 0.3927F)); CubeListBuilder.create()
partdefinition.addOrReplaceChild("right_arm_slim", CubeListBuilder.create().texOffs(40, 16).addBox(-2.0F, -2.0F, -2.0F, 3.0F, 12.0F, 4.0F, new CubeDeformation(0.0F)).texOffs(40, 32).addBox(-2.0F, -2.0F, -2.0F, 3.0F, 12.0F, 4.0F, new CubeDeformation(0.25F)), PartPose.offsetAndRotation(-5.0F, 11.0F, 0.0F, 0.0F, 0.0F, 0.3927F)); .texOffs(0, 0)
partdefinition.addOrReplaceChild("left_arm_slim", CubeListBuilder.create().texOffs(32, 48).addBox(-1.0F, -2.0F, -2.0F, 3.0F, 12.0F, 4.0F, new CubeDeformation(0.0F)).texOffs(48, 48).addBox(-1.0F, -2.0F, -2.0F, 3.0F, 12.0F, 4.0F, new CubeDeformation(0.25F)), PartPose.offsetAndRotation(5.0F, 11.0F, 0.0F, 0.0F, 0.0F, -0.3927F)); .addBox(-4.0F, -8.0F, -4.0F, 8.0F, 8.0F, 8.0F, new CubeDeformation(0.0F))
partdefinition.addOrReplaceChild("left_arm", CubeListBuilder.create().texOffs(32, 48).addBox(-1.0F, -2.0F, -2.0F, 4.0F, 12.0F, 4.0F, new CubeDeformation(0.0F)).texOffs(48, 48).addBox(-1.0F, -2.0F, -2.0F, 4.0F, 12.0F, 4.0F, new CubeDeformation(0.25F)), PartPose.offsetAndRotation(5.0F, 11.0F, 0.0F, 0.0F, 0.0F, -0.3927F)); .texOffs(32, 0)
partdefinition.addOrReplaceChild("right_leg", CubeListBuilder.create().texOffs(0, 16).addBox(-2.0F, 0.0F, -2.0F, 4.0F, 12.0F, 4.0F, new CubeDeformation(0.0F)).texOffs(0, 32).addBox(-2.0F, 0.0F, -2.0F, 4.0F, 12.0F, 4.0F, new CubeDeformation(0.25F)), PartPose.offsetAndRotation(-2.0F, 19.0F, -2.0F, -1.5708F, 0.3927F, 0.0F)); .addBox(
partdefinition.addOrReplaceChild("left_leg", CubeListBuilder.create().texOffs(16, 48).addBox(-2.0F, 0.0F, -2.0F, 4.0F, 12.0F, 4.0F, new CubeDeformation(0.0F)).texOffs(0, 48).addBox(-2.0F, 0.0F, -2.0F, 4.0F, 12.0F, 4.0F, new CubeDeformation(0.25F)), PartPose.offsetAndRotation(2.0F, 19.0F, -2.0F, -1.5708F, -0.3927F, 0.0F)); -4.0F, -8.0F, -4.0F, 8.0F, 8.0F, 8.0F,
new CubeDeformation(0.5F)
), dollPoses.getHeadPose()
);
partdefinition.addOrReplaceChild(
"body",
CubeListBuilder.create()
.texOffs(16, 16)
.addBox(-4.0F, 0.0F, -2.0F, 8.0F, 12.0F, 4.0F, new CubeDeformation(0.0F))
.texOffs(16, 32)
.addBox(
-4.0F, 0.0F, -2.0F, 8.0F, 12.0F, 4.0F,
new CubeDeformation(0.25F)
), dollPoses.getBodyPose()
);
partdefinition.addOrReplaceChild(
"right_arm",
CubeListBuilder.create()
.texOffs(40, 16)
.addBox(-3.0F, -2.0F, -2.0F, 4.0F, 12.0F, 4.0F, new CubeDeformation(0.0F))
.texOffs(40, 32)
.addBox(
-3.0F, -2.0F, -2.0F, 4.0F, 12.0F, 4.0F,
new CubeDeformation(0.25F)
), dollPoses.getRightArmPose()
);
partdefinition.addOrReplaceChild(
"right_arm_slim",
CubeListBuilder.create()
.texOffs(40, 16)
.addBox(-2.0F, -2.0F, -2.0F, 3.0F, 12.0F, 4.0F, new CubeDeformation(0.0F))
.texOffs(40, 32)
.addBox(-2.0F, -2.0F, -2.0F, 3.0F, 12.0F, 4.0F,
new CubeDeformation(0.25F)
), dollPoses.getRightArmPose()
);
partdefinition.addOrReplaceChild(
"left_arm_slim",
CubeListBuilder.create()
.texOffs(32, 48)
.addBox(-1.0F, -2.0F, -2.0F, 3.0F, 12.0F, 4.0F, new CubeDeformation(0.0F))
.texOffs(48, 48)
.addBox(
-1.0F, -2.0F, -2.0F, 3.0F, 12.0F, 4.0F,
new CubeDeformation(0.25F)
), dollPoses.getLeftArmPose()
);
partdefinition.addOrReplaceChild(
"left_arm",
CubeListBuilder.create()
.texOffs(32, 48)
.addBox(-1.0F, -2.0F, -2.0F, 4.0F, 12.0F, 4.0F, new CubeDeformation(0.0F))
.texOffs(48, 48)
.addBox(
-1.0F, -2.0F, -2.0F, 4.0F, 12.0F, 4.0F,
new CubeDeformation(0.25F)
), dollPoses.getLeftArmPose()
);
partdefinition.addOrReplaceChild(
"right_leg",
CubeListBuilder.create()
.texOffs(0, 16)
.addBox(-2.0F, 0.0F, -2.0F, 4.0F, 12.0F, 4.0F, new CubeDeformation(0.0F))
.texOffs(0, 32)
.addBox(
-2.0F, 0.0F, -2.0F, 4.0F, 12.0F, 4.0F, new CubeDeformation(0.25F)
), dollPoses.getRightLegPose()
);
partdefinition.addOrReplaceChild(
"left_leg",
CubeListBuilder.create()
.texOffs(16, 48)
.addBox(-2.0F, 0.0F, -2.0F, 4.0F, 12.0F, 4.0F, new CubeDeformation(0.0F))
.texOffs(0, 48)
.addBox(
-2.0F, 0.0F, -2.0F, 4.0F, 12.0F, 4.0F,
new CubeDeformation(0.25F)
), dollPoses.getLeftLegPose()
);
return LayerDefinition.create(meshdefinition, 64, 64); return LayerDefinition.create(meshdefinition, 64, 64);
} }
@Override @Override
public void renderToBuffer(PoseStack poseStack, @NotNull VertexConsumer vertexConsumer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) { public void renderToBuffer(@NotNull PoseStack poseStack, VertexConsumer vertexConsumer, int packedLight, int packedOverlay, int color) {
poseStack.pushPose(); poseStack.pushPose();
poseStack.scale(0.5F, 0.5F, 0.5F); poseStack.scale(0.5F, 0.5F, 0.5F);
poseStack.translate(0.0, 1.5010000467300415, 0.0); poseStack.translate(0.0, 1.5010000467300415, 0.0);
this.head.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha); this.head.render(poseStack, vertexConsumer, packedLight, packedOverlay, color);
this.body.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha); this.body.render(poseStack, vertexConsumer, packedLight, packedOverlay, color);
if (this.slim) { if (this.slim) {
this.rightArmSlim.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha); this.rightArmSlim.render(poseStack, vertexConsumer, packedLight, packedOverlay, color);
this.leftArmSlim.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha); this.leftArmSlim.render(poseStack, vertexConsumer, packedLight, packedOverlay, color);
} else { } else {
this.rightArm.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha); this.rightArm.render(poseStack, vertexConsumer, packedLight, packedOverlay, color);
this.leftArm.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha); this.leftArm.render(poseStack, vertexConsumer, packedLight, packedOverlay, color);
} }
this.rightLeg.render(poseStack, vertexConsumer, packedLight, packedOverlay, color);
this.rightLeg.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha); this.leftLeg.render(poseStack, vertexConsumer, packedLight, packedOverlay, color);
this.leftLeg.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha);
poseStack.popPose(); poseStack.popPose();
} }
} }

View File

@ -0,0 +1,87 @@
package top.r3944realms.lib39.client.model;
import net.minecraft.client.model.geom.PartPose;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.lib39.Lib39;
public enum DollPoses implements IDollPose{
DEFAULT(
"default",
PartPose.offset(0.0F, 9.0F, 0.0F),
PartPose.offset(0.0F, 9.0F, 0.0F),
PartPose.offsetAndRotation(-5.0F, 11.0F, 0.0F, 0.0F, 0.0F, 0.3927F),
PartPose.offsetAndRotation(5.0F, 11.0F, 0.0F, 0.0F, 0.0F, -0.3927F),
PartPose.offsetAndRotation(-2.0F, 19.0F, -2.0F, -1.5708F, 0.3927F, 0.0F),
PartPose.offsetAndRotation(2.0F, 19.0F, -2.0F, -1.5708F, -0.3927F, 0.0F)
);
// 注册全局
private final ResourceLocation id;
private final Vec3 offset;
private final PartPose headPose;
private final PartPose bodyPose;
private final PartPose rightArmPose;
private final PartPose leftArmPose;
private final PartPose rightLegPose;
private final PartPose leftLegPose;
DollPoses(String name, PartPose headPose, PartPose bodyPose,
PartPose rightArmPose, PartPose leftArmPose,
PartPose rightLegPose, PartPose leftLegPose) {
this(name, Vec3.ZERO, headPose, bodyPose, rightArmPose, leftArmPose, rightLegPose, leftLegPose);
}
DollPoses(String name, Vec3 offset, PartPose headPose, PartPose bodyPose,
PartPose rightArmPose, PartPose leftArmPose,
PartPose rightLegPose, PartPose leftLegPose) {
this.id = Lib39.rl(name);
this.offset = offset;
this.headPose = headPose;
this.bodyPose = bodyPose;
this.rightArmPose = rightArmPose;
this.leftArmPose = leftArmPose;
this.rightLegPose = rightLegPose;
this.leftLegPose = leftLegPose;
}
@Override
public @NotNull ResourceLocation getId() {
return id;
}
@Override
public PartPose getHeadPose() {
return headPose;
}
@Override
public PartPose getBodyPose() {
return bodyPose;
}
@Override
public PartPose getRightArmPose() {
return rightArmPose;
}
@Override
public PartPose getLeftArmPose() {
return leftArmPose;
}
@Override
public PartPose getRightLegPose() {
return rightLegPose;
}
@Override
public PartPose getLeftLegPose() {
return leftLegPose;
}
@Override
public @NotNull Vec3 getTotalOffset() {
return offset;
}
}

View File

@ -0,0 +1,19 @@
package top.r3944realms.lib39.client.model;
import net.minecraft.client.model.geom.PartPose;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.NotNull;
public interface IDollPose {
@NotNull ResourceLocation getId();
@NotNull default Vec3 getTotalOffset() {
return Vec3.ZERO;
}
@NotNull PartPose getHeadPose();
@NotNull PartPose getBodyPose();
@NotNull PartPose getRightArmPose();
@NotNull PartPose getLeftArmPose();
@NotNull PartPose getRightLegPose();
@NotNull PartPose getLeftLegPose();
}

View File

@ -254,8 +254,8 @@ public class RadialMenuRenderer<T> {
*/ */
private void drawSector(GuiGraphics guiGraphics, float startAngle, float angleSize, private void drawSector(GuiGraphics guiGraphics, float startAngle, float angleSize,
float innerRadius, float outerRadius, float[] color) { float innerRadius, float outerRadius, float[] color) {
BufferBuilder buffer = Tesselator.getInstance().getBuilder(); Tesselator instance = Tesselator.getInstance();
buffer.begin(VertexFormat.Mode.TRIANGLE_STRIP, DefaultVertexFormat.POSITION_COLOR); BufferBuilder buffer = instance.begin(VertexFormat.Mode.TRIANGLE_STRIP, DefaultVertexFormat.POSITION_COLOR);
Matrix4f matrix = guiGraphics.pose().last().pose(); Matrix4f matrix = guiGraphics.pose().last().pose();
float segments = Math.max(8, this.segments * (angleSize / 360f)); float segments = Math.max(8, this.segments * (angleSize / 360f));
@ -269,14 +269,14 @@ public class RadialMenuRenderer<T> {
float sin = Mth.sin(rad); float sin = Mth.sin(rad);
// 外圈顶点 // 外圈顶点
buffer.vertex(matrix, outerRadius * cos, outerRadius * sin, 0) buffer.addVertex(matrix, outerRadius * cos, outerRadius * sin, 0)
.color(color[0], color[1], color[2], color[3]).endVertex(); .setColor(color[0], color[1], color[2], color[3]);
// 内圈顶点 // 内圈顶点
buffer.vertex(matrix, innerRadius * cos, innerRadius * sin, 0) buffer.addVertex(matrix, innerRadius * cos, innerRadius * sin, 0)
.color(color[0], color[1], color[2], color[3] * 0.6f).endVertex(); .setColor(color[0], color[1], color[2], color[3] * 0.6f);
} }
BufferUploader.drawWithShader(buffer.end()); BufferUploader.drawWithShader(buffer.build());
} }
/** /**

View File

@ -53,7 +53,7 @@ public class DollBlockEntityRenderer implements BlockEntityRenderer<DollBlockEnt
poseStack.mulPose(Axis.YP.rotationDegrees(rotation)); poseStack.mulPose(Axis.YP.rotationDegrees(rotation));
VertexConsumer vertexConsumer = buffer.getBuffer(RenderType.entityTranslucent(resourceLocationBooleanPair.first)); VertexConsumer vertexConsumer = buffer.getBuffer(RenderType.entityTranslucent(resourceLocationBooleanPair.first));
this.dollModel.slim = resourceLocationBooleanPair.second; this.dollModel.slim = resourceLocationBooleanPair.second;
this.dollModel.renderToBuffer(poseStack, vertexConsumer, packedLight, OverlayTexture.NO_OVERLAY, 1.0F, 1.0F, 1.0F, 1.0F); this.dollModel.renderToBuffer(poseStack, vertexConsumer, packedLight, OverlayTexture.NO_OVERLAY,-1);
poseStack.popPose(); poseStack.popPose();
} }
} }

View File

@ -9,6 +9,7 @@ import net.minecraft.client.renderer.BlockEntityWithoutLevelRenderer;
import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.resources.DefaultPlayerSkin; import net.minecraft.client.resources.DefaultPlayerSkin;
import net.minecraft.client.resources.PlayerSkin;
import net.minecraft.client.resources.SkinManager; import net.minecraft.client.resources.SkinManager;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemDisplayContext;
@ -86,7 +87,7 @@ public class DollItemRenderer extends BlockEntityWithoutLevelRenderer {
vertexConsumer, vertexConsumer,
packedLight, packedLight,
packedOverlay, packedOverlay,
1.0F, 1.0F, 1.0F, 1.0F -1
); );
poseStack.popPose(); poseStack.popPose();
@ -103,11 +104,12 @@ public class DollItemRenderer extends BlockEntityWithoutLevelRenderer {
ResourceLocation playerSkin; ResourceLocation playerSkin;
boolean isSlim; boolean isSlim;
if (profile != null) { if (profile != null) {
playerSkin = skinManager.getInsecureSkinLocation(profile); PlayerSkin insecureSkin = skinManager.getInsecureSkin(profile);
playerSkin = insecureSkin.texture();
isSlim = GameProfileHelper.isSlimArms(profile); isSlim = GameProfileHelper.isSlimArms(profile);
} else { } else {
playerSkin = DefaultPlayerSkin.getDefaultSkin(); //6 new SkinType("textures/entity/player/slim/steve.png", DefaultPlayerSkin.ModelType.SLIM), playerSkin = Lib39.mrl("textures/entity/player/wide/steve.png");
isSlim = true; isSlim = false;
} }
return Pair.of(playerSkin, isSlim); return Pair.of(playerSkin, isSlim);
} }

View File

@ -1,6 +1,7 @@
package top.r3944realms.lib39.content.block; package top.r3944realms.lib39.content.block;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import com.mojang.serialization.MapCodec;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.particles.ParticleTypes; import net.minecraft.core.particles.ParticleTypes;
@ -14,6 +15,7 @@ import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
@ -34,6 +36,7 @@ import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import top.r3944realms.lib39.client.model.IDollPose;
import top.r3944realms.lib39.content.block.blockentity.DollBlockEntity; import top.r3944realms.lib39.content.block.blockentity.DollBlockEntity;
import top.r3944realms.lib39.content.block.property.DollPose; import top.r3944realms.lib39.content.block.property.DollPose;
import top.r3944realms.lib39.core.register.Lib39BlockEntities; import top.r3944realms.lib39.core.register.Lib39BlockEntities;
@ -100,16 +103,16 @@ public abstract class AbstractDollBlock extends BaseEntityBlock implements Simpl
} }
@Override @Override
public @NotNull InteractionResult use(@NotNull BlockState blockState, @NotNull Level level, @NotNull BlockPos blockPos, @NotNull Player player, protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult) {
@NotNull InteractionHand hand, @NotNull BlockHitResult hitResult) {
if (level instanceof ServerLevel serverLevel) { if (level instanceof ServerLevel serverLevel) {
// 播放粒子效果 // 播放粒子效果
spawnNoteParticles(serverLevel, blockPos); spawnNoteParticles(serverLevel, pos);
// 播放音效 // 播放音效
playDollSound(serverLevel, blockPos); playDollSound(serverLevel, pos);
} }
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
/** /**
* 在玩偶位置生成音符粒子效果 * 在玩偶位置生成音符粒子效果
*/ */
@ -171,7 +174,7 @@ public abstract class AbstractDollBlock extends BaseEntityBlock implements Simpl
} }
@Override @Override
public @NotNull ItemStack getCloneItemStack(@NotNull BlockGetter level, @NotNull BlockPos pos, @NotNull BlockState state) { public ItemStack getCloneItemStack(LevelReader level, BlockPos pos, BlockState state) {
ItemStack stack = super.getCloneItemStack(level, pos, state); ItemStack stack = super.getCloneItemStack(level, pos, state);
BlockEntity blockEntity = level.getBlockEntity(pos); BlockEntity blockEntity = level.getBlockEntity(pos);
if (blockEntity instanceof DollBlockEntity doll) { if (blockEntity instanceof DollBlockEntity doll) {
@ -209,7 +212,7 @@ public abstract class AbstractDollBlock extends BaseEntityBlock implements Simpl
* 生成自定义掉落物 * 生成自定义掉落物
*/ */
@Nullable @Nullable
private List<ItemStack> getCustomDrops(DollBlockEntity dollEntity, LootParams.Builder params) { private List<ItemStack> getCustomDrops(DollBlockEntity dollEntity, LootParams.@NotNull Builder params) {
if (params.getOptionalParameter(LootContextParams.THIS_ENTITY) instanceof Player player) { if (params.getOptionalParameter(LootContextParams.THIS_ENTITY) instanceof Player player) {
if (player.isCreative()) { if (player.isCreative()) {
return List.of(); return List.of();

View File

@ -1,6 +1,8 @@
package top.r3944realms.lib39.content.block; package top.r3944realms.lib39.content.block;
import com.mojang.serialization.MapCodec;
import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.block.BaseEntityBlock;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Mirror; import net.minecraft.world.level.block.Mirror;
import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.Rotation;
@ -17,7 +19,7 @@ import top.r3944realms.lib39.content.block.property.DollPose;
* The type Doll block. * The type Doll block.
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class DollBlock extends AbstractDollBlock{ public class DollBlock extends AbstractDollBlock {
/** /**
* The constant MAX. * The constant MAX.
*/ */
@ -42,6 +44,10 @@ public class DollBlock extends AbstractDollBlock{
); );
} }
@Override @Override
protected MapCodec<? extends BaseEntityBlock> codec() {
return simpleCodec(p -> new DollBlock());
}
@Override
public @Nullable BlockState getStateForPlacement(@NotNull BlockPlaceContext context) { public @Nullable BlockState getStateForPlacement(@NotNull BlockPlaceContext context) {
BlockState stateForPlacement = super.getStateForPlacement(context); BlockState stateForPlacement = super.getStateForPlacement(context);
return stateForPlacement != null ? stateForPlacement.setValue(ROTATION, RotationSegment.convertToSegment((context.getRotation()+180) % 360)) : null; return stateForPlacement != null ? stateForPlacement.setValue(ROTATION, RotationSegment.convertToSegment((context.getRotation()+180) % 360)) : null;

View File

@ -1,11 +1,9 @@
package top.r3944realms.lib39.content.block; package top.r3944realms.lib39.content.block;
import com.mojang.serialization.MapCodec;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.HorizontalDirectionalBlock;
import net.minecraft.world.level.block.Mirror;
import net.minecraft.world.level.block.Rotation;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.DirectionProperty; import net.minecraft.world.level.block.state.properties.DirectionProperty;
@ -35,6 +33,12 @@ public class WallDollBlock extends AbstractDollBlock {
.setValue(FACING, Direction.NORTH) .setValue(FACING, Direction.NORTH)
); );
} }
@Override
protected MapCodec<? extends BaseEntityBlock> codec() {
return simpleCodec(p -> new WallDollBlock());
}
public @NotNull BlockState rotate(@NotNull BlockState state, @NotNull Rotation rotation) { public @NotNull BlockState rotate(@NotNull BlockState state, @NotNull Rotation rotation) {
return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); return state.setValue(FACING, rotation.rotate(state.getValue(FACING)));
} }

View File

@ -3,9 +3,11 @@ package top.r3944realms.lib39.content.block.blockentity;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import net.minecraft.Util; import net.minecraft.Util;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils; import net.minecraft.nbt.NbtUtils;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.world.item.component.ResolvableProfile;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.SkullBlockEntity; import net.minecraft.world.level.block.entity.SkullBlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
@ -21,7 +23,6 @@ import javax.annotation.Nullable;
* The type Doll block entity. * The type Doll block entity.
*/ */
public class DollBlockEntity extends BlockEntity { public class DollBlockEntity extends BlockEntity {
@Nullable @Nullable
private GameProfile owner; private GameProfile owner;
@ -35,16 +36,18 @@ public class DollBlockEntity extends BlockEntity {
super(Lib39BlockEntities.DOLL_BLOCK_ENTITY.get(), pos, blockState); super(Lib39BlockEntities.DOLL_BLOCK_ENTITY.get(), pos, blockState);
} }
protected void saveAdditional(@NotNull CompoundTag tag) { @Override
super.saveAdditional(tag); protected void saveAdditional(CompoundTag tag, HolderLookup.Provider registries) {
super.saveAdditional(tag, registries);
NBTWriter.of(tag) NBTWriter.of(tag)
.compoundIf(GameProfileHelper.TAG_OWN_PROFILE, owner != null, () -> NbtUtils.writeGameProfile(new CompoundTag(), this.owner)); .gameProfileIf(GameProfileHelper.TAG_OWN_PROFILE, owner != null, () -> owner);
} }
public void load(@NotNull CompoundTag tag) { @Override
super.load(tag); protected void loadAdditional(CompoundTag tag, HolderLookup.Provider registries) {
super.loadAdditional(tag, registries);
NBTReader.of(tag) NBTReader.of(tag)
.compound(GameProfileHelper.TAG_OWN_PROFILE, compoundTag -> setOwner(NbtUtils.readGameProfile(compoundTag))); .gameProfile(GameProfileHelper.TAG_OWN_PROFILE, this::setOwner);
} }
/** /**
@ -58,12 +61,14 @@ public class DollBlockEntity extends BlockEntity {
} }
@Override
public ClientboundBlockEntityDataPacket getUpdatePacket() { public ClientboundBlockEntityDataPacket getUpdatePacket() {
return ClientboundBlockEntityDataPacket.create(this); return ClientboundBlockEntityDataPacket.create(this);
} }
public @NotNull CompoundTag getUpdateTag() { @Override
return this.saveWithoutMetadata(); public CompoundTag getUpdateTag(HolderLookup.Provider registries) {
return super.getUpdateTag(registries);
} }
/** /**
@ -89,10 +94,21 @@ public class DollBlockEntity extends BlockEntity {
} }
private void updateOwnerProfile() { private void updateOwnerProfile() {
SkullBlockEntity.updateGameprofile(this.owner, gameProfile -> { if (this.owner != null) {
this.owner = gameProfile; // 使用 ResolvableProfile 进行异步解析
this.setChanged(); ResolvableProfile resolvableProfile = new ResolvableProfile(this.owner);
}); if (!resolvableProfile.isResolved()) {
resolvableProfile.resolve().thenAcceptAsync(resolved -> {
// ResolvableProfile 中获取 GameProfile
this.owner = resolved.gameProfile();
this.setChanged();
if (this.level != null) {
this.level.sendBlockUpdated(this.worldPosition, this.getBlockState(), this.getBlockState(), 3);
}
}, SkullBlockEntity.CHECKED_MAIN_THREAD_EXECUTOR);
}
}
this.setChanged();
} }
} }

View File

@ -29,16 +29,17 @@ public class DollItem extends StandingAndWallBlockItem implements Equipable {
super(Lib39Blocks.DOLL.get(), Lib39Blocks.WALL_DOLL.get(), properties, Direction.DOWN); super(Lib39Blocks.DOLL.get(), Lib39Blocks.WALL_DOLL.get(), properties, Direction.DOWN);
} }
@Override @Override
public void appendHoverText(@NotNull ItemStack stack, @Nullable Level level, @NotNull List<Component> tooltip, @NotNull TooltipFlag flag) { public void appendHoverText(ItemStack stack, TooltipContext context, List<Component> tooltipComponents, TooltipFlag tooltipFlag) {
super.appendHoverText(stack, context, tooltipComponents, tooltipFlag);
GameProfile profileFromItemStack = GameProfileHelper.getProfileFromItemStack(stack); GameProfile profileFromItemStack = GameProfileHelper.getProfileFromItemStack(stack);
if (profileFromItemStack != null && profileFromItemStack.getName() != null) { if (profileFromItemStack != null && profileFromItemStack.getName() != null) {
tooltip.add(Component.translatable("tooltip.lib39.content.doll.hover.1", profileFromItemStack.getName())); tooltipComponents.add(Component.translatable("tooltip.lib39.content.doll.hover.1", profileFromItemStack.getName()));
} }
tooltip.add(Component.translatable("tooltip.lib39.content.doll.hover.2")); tooltipComponents.add(Component.translatable("tooltip.lib39.content.doll.hover.2"));
} }
@Override @Override
public @NotNull EquipmentSlot getEquipmentSlot() { public @NotNull EquipmentSlot getEquipmentSlot() {
return EquipmentSlot.HEAD; return EquipmentSlot.HEAD;

View File

@ -11,14 +11,17 @@ import java.util.stream.Collectors;
/** /**
* The type Compat manager. * The type Compat manager.
*
* @param <C> the type parameter
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public abstract class CompatManager { public abstract class CompatManager<C extends ICompat> implements ICompatManager<C> {
/** /**
* Gets id. * Gets id.
* *
* @return the id * @return the id
*/ */
@Override
public ResourceLocation getId() { public ResourceLocation getId() {
return id; return id;
} }
@ -31,10 +34,7 @@ public abstract class CompatManager {
* The Id. * The Id.
*/ */
protected final ResourceLocation id; protected final ResourceLocation id;
/**
* The Compats.
*/
protected final Map<ResourceLocation, ICompat> compats = new HashMap<>();
/** /**
* The Initialized. * The Initialized.
*/ */
@ -47,6 +47,7 @@ public abstract class CompatManager {
/** /**
* Initialize. * Initialize.
*/ */
@Override
public void initialize() { public void initialize() {
initializeAllCompat(); initializeAllCompat();
onLoadComplete(); onLoadComplete();
@ -68,7 +69,8 @@ public abstract class CompatManager {
* @param id the id * @param id the id
* @param compat the compat * @param compat the compat
*/ */
public void registerCompat(ResourceLocation id, ICompat compat) { @Override
public void registerCompat(ResourceLocation id, C compat) {
if (initialized) { if (initialized) {
// 已初始化直接注册 // 已初始化直接注册
doRegisterCompat(id, compat); doRegisterCompat(id, compat);
@ -85,12 +87,12 @@ public abstract class CompatManager {
* @param id the id * @param id the id
* @param compat the compat * @param compat the compat
*/ */
protected void doRegisterCompat(ResourceLocation id, ICompat compat) { protected void doRegisterCompat(ResourceLocation id, C compat) {
if (compats.containsKey(id)) { if (getCompatMap().containsKey(id)) {
logger.warn("Compat with id {} is already registered!", id); logger.warn("Compat with id {} is already registered!", id);
return; return;
} }
compats.put(id, compat); getCompatMap().put(id, compat);
logger.debug("Registered compat: {}", id); logger.debug("Registered compat: {}", id);
} }
@ -101,7 +103,8 @@ public abstract class CompatManager {
* @param path the path * @param path the path
* @param compat the compat * @param compat the compat
*/ */
public void registerCompat(String namespace, String path, ICompat compat) { @Override
public void registerCompat(String namespace, String path, C compat) {
registerCompat(Lib39.rl(namespace, path), compat); registerCompat(Lib39.rl(namespace, path), compat);
} }
@ -112,14 +115,14 @@ public abstract class CompatManager {
* 初始化所有兼容模块并应用事件监听器 * 初始化所有兼容模块并应用事件监听器
*/ */
protected synchronized void initializeAllCompat() { protected synchronized void initializeAllCompat() {
logger.info("Initializing {} compatibility modules", compats.size()); logger.info("Initializing {} compatibility modules", getCompatMap().size());
// 先处理所有缓存的注册 // 先处理所有缓存的注册
pendingTasks.forEach(Runnable::run); pendingTasks.forEach(Runnable::run);
pendingTasks.clear(); pendingTasks.clear();
// 初始化所有兼容模块 // 初始化所有兼容模块
for (Map.Entry<ResourceLocation, ICompat> entry : compats.entrySet()) { for (Map.Entry<ResourceLocation, C> entry : getCompatMap().entrySet()) {
if (!entry.getValue().isInitialized() && entry.getValue().isModLoaded()) { if (!entry.getValue().isInitialized() && entry.getValue().isModLoaded()) {
try { try {
entry.getValue().initialize(); entry.getValue().initialize();
@ -139,8 +142,9 @@ public abstract class CompatManager {
* @param id the id * @param id the id
* @return the compat * @return the compat
*/ */
public Optional<ICompat> getCompat(ResourceLocation id) { @Override
return Optional.ofNullable(compats.get(id)); public Optional<C> getCompat(ResourceLocation id) {
return Optional.ofNullable(getCompatMap().get(id));
} }
/** /**
@ -149,8 +153,9 @@ public abstract class CompatManager {
* @param id the id * @param id the id
* @return the boolean * @return the boolean
*/ */
@Override
public boolean hasCompat(ResourceLocation id) { public boolean hasCompat(ResourceLocation id) {
return compats.containsKey(id); return getCompatMap().containsKey(id);
} }
/** /**
@ -158,8 +163,9 @@ public abstract class CompatManager {
* *
* @param id the id * @param id the id
*/ */
@Override
public void unregisterCompat(ResourceLocation id) { public void unregisterCompat(ResourceLocation id) {
ICompat removed = compats.remove(id); C removed = getCompatMap().remove(id);
if (removed != null) { if (removed != null) {
logger.debug("Unregistered compat: {}", id); logger.debug("Unregistered compat: {}", id);
} }
@ -170,9 +176,9 @@ public abstract class CompatManager {
* *
* @return the loaded compats * @return the loaded compats
*/ */
public List<ICompat> getLoadedCompats() { public List<C> getLoadedCompats() {
return compats.values().stream() return getCompatMap().values().stream()
.filter(ICompat::isModLoaded) .filter(C::isModLoaded)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@ -180,8 +186,8 @@ public abstract class CompatManager {
* On load complete. * On load complete.
*/ */
public void onLoadComplete() { public void onLoadComplete() {
logger.info("Calling onLoadComplete for {} compatibility modules", compats.size()); logger.info("Calling onLoadComplete for {} compatibility modules", getCompatMap().size());
for (Map.Entry<ResourceLocation, ICompat> entry : compats.entrySet()) { for (Map.Entry<ResourceLocation, C> entry : getCompatMap().entrySet()) {
try { try {
entry.getValue().onLoadComplete(); entry.getValue().onLoadComplete();
} catch (Exception e) { } catch (Exception e) {

View File

@ -0,0 +1,72 @@
package top.r3944realms.lib39.core.compat;
import net.minecraft.resources.ResourceLocation;
import java.util.Map;
import java.util.Optional;
/**
* The interface Compat manager.
*
* @param <C> the type parameter
*/
public interface ICompatManager<C extends ICompat> {
/**
* Gets id.
*
* @return the id
*/
ResourceLocation getId();
/**
* Gets compat map.
*
* @return the compat map
*/
Map<ResourceLocation, C> getCompatMap();
/**
* Initialize.
*/
void initialize();
/**
* Register compat.
*
* @param id the id
* @param compat the compat
*/
void registerCompat(ResourceLocation id, C compat);
/**
* Register compat.
*
* @param namespace the namespace
* @param path the path
* @param compat the compat
*/
void registerCompat(String namespace, String path, C compat);
/**
* Gets compat.
*
* @param id the id
* @return the compat
*/
Optional<C> getCompat(ResourceLocation id);
/**
* Has compat boolean.
*
* @param id the id
* @return the boolean
*/
boolean hasCompat(ResourceLocation id);
/**
* Unregister compat.
*
* @param id the id
*/
void unregisterCompat(ResourceLocation id);
}

View File

@ -0,0 +1,31 @@
package top.r3944realms.lib39.core.compat;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
/**
* The type Simple compat manager.
*/
public class SimpleCompatManager extends CompatManager<ICompat> {
/**
* The Compats.
*/
Map<ResourceLocation, ICompat> compats = new HashMap<>();
/**
* Instantiates a new Compat manager.
*
* @param id the id
*/
public SimpleCompatManager(@NotNull ResourceLocation id) {
super(id);
}
@Override
public Map<ResourceLocation, ICompat> getCompatMap() {
return compats;
}
}

View File

@ -123,26 +123,6 @@ public abstract class LanguageProvider implements DataProvider {
this.add(key.getDescriptionId(), name); this.add(key.getDescriptionId(), name);
} }
/**
* Add enchantment.
*
* @param key the key
* @param name the name
*/
public void addEnchantment(@NotNull Supplier<? extends Enchantment> key, String name) {
this.add(key.get(), name);
}
/**
* Add.
*
* @param key the key
* @param name the name
*/
public void add(@NotNull Enchantment key, String name) {
this.add(key.getDescriptionId(), name);
}
/** /**
* Add effect. * Add effect.
* *

View File

@ -530,29 +530,29 @@ public abstract class AbstractFabricItem extends Item {
} }
@Override @Override
public void appendHoverText(@NotNull ItemStack stack, @Nullable Level level, public void appendHoverText(ItemStack stack, TooltipContext context, List<Component> tooltipComponents, TooltipFlag tooltipFlag) {
@NotNull List<Component> tooltip, @NotNull TooltipFlag flag) { super.appendHoverText(stack, context, tooltipComponents, tooltipFlag);
super.appendHoverText(stack, level, tooltip, flag);
tooltip.add(Component.literal("§7右键点击在 3 秒后执行")); tooltipComponents.add(Component.literal("§7右键点击在 3 秒后执行"));
tooltip.add(Component.literal("§7§e准星瞄准生物§7的数据查询")); tooltipComponents.add(Component.literal("§7§e准星瞄准生物§7的数据查询"));
tooltip.add(Component.literal("§7§oShift + 右键§7进行§e客户端-服务器双端同步检查§7")); tooltipComponents.add(Component.literal("§7§oShift + 右键§7进行§e客户端-服务器双端同步检查§7"));
tooltip.add(Component.literal("")); tooltipComponents.add(Component.literal(""));
tooltip.add(Component.literal("§6查询延迟: §e3秒")); tooltipComponents.add(Component.literal("§6查询延迟: §e3秒"));
tooltip.add(Component.literal("§6瞄准距离: §e20格")); tooltipComponents.add(Component.literal("§6瞄准距离: §e20格"));
tooltip.add(Component.literal("§6冷却时间: §e1秒")); tooltipComponents.add(Component.literal("§6冷却时间: §e1秒"));
tooltip.add(Component.literal("")); tooltipComponents.add(Component.literal(""));
tooltip.add(Component.literal("§a单端查询内容:")); tooltipComponents.add(Component.literal("§a单端查询内容:"));
tooltip.add(Component.literal("§7- 基础数据字段")); tooltipComponents.add(Component.literal("§7- 基础数据字段"));
tooltip.add(Component.literal("§7- 自定义数据结构")); tooltipComponents.add(Component.literal("§7- 自定义数据结构"));
tooltip.add(Component.literal("§7- 数据验证状态")); tooltipComponents.add(Component.literal("§7- 数据验证状态"));
tooltip.add(Component.literal("§7- 同步状态信息")); tooltipComponents.add(Component.literal("§7- 同步状态信息"));
tooltip.add(Component.literal("")); tooltipComponents.add(Component.literal(""));
tooltip.add(Component.literal("§e双端同步检查:")); tooltipComponents.add(Component.literal("§e双端同步检查:"));
tooltip.add(Component.literal("§7- 客户端和服务器同时查询")); tooltipComponents.add(Component.literal("§7- 客户端和服务器同时查询"));
tooltip.add(Component.literal("§7- 字段级同步状态对比")); tooltipComponents.add(Component.literal("§7- 字段级同步状态对比"));
tooltip.add(Component.literal("§7- 总体同步率计算")); tooltipComponents.add(Component.literal("§7- 总体同步率计算"));
tooltip.add(Component.literal("§7- 双端数据状态差异")); tooltipComponents.add(Component.literal("§7- 双端数据状态差异"));
tooltip.add(Component.literal("§7- 同步建议")); tooltipComponents.add(Component.literal("§7- 同步建议"));
} }
} }

View File

@ -268,27 +268,27 @@ public abstract class AbstractNeoForgeItem extends Item {
} }
@Override @Override
public void appendHoverText(@NotNull ItemStack stack, @Nullable Level level, public void appendHoverText(ItemStack stack, TooltipContext context, List<Component> tooltipComponents, TooltipFlag tooltipFlag) {
@NotNull List<Component> tooltip, @NotNull TooltipFlag flag) { super.appendHoverText(stack, context, tooltipComponents, tooltipFlag);
super.appendHoverText(stack, level, tooltip, flag);
tooltip.add(Component.literal("§7右键点击触发§e准星瞄准生物§7的"));
tooltip.add(Component.literal("§7测试数据随机变换")); tooltipComponents.add(Component.literal("§7右键点击触发§e准星瞄准生物§7的"));
tooltip.add(Component.literal("§7§oShift + 右键§7操作§e自身§7数据")); tooltipComponents.add(Component.literal("§7测试数据随机变换"));
tooltip.add(Component.literal("")); tooltipComponents.add(Component.literal("§7§oShift + 右键§7操作§e自身§7数据"));
tooltip.add(Component.literal("§6冷却时间: §e1秒")); tooltipComponents.add(Component.literal(""));
tooltip.add(Component.literal("§6瞄准距离: §e20格")); tooltipComponents.add(Component.literal("§6冷却时间: §e1秒"));
tooltip.add(Component.literal("")); tooltipComponents.add(Component.literal("§6瞄准距离: §e20格"));
tooltip.add(Component.literal("§a变换类型:")); tooltipComponents.add(Component.literal(""));
tooltip.add(Component.literal("§7- 完全随机数据")); tooltipComponents.add(Component.literal("§a变换类型:"));
tooltip.add(Component.literal("§7- 字符串+计数器")); tooltipComponents.add(Component.literal("§7- 完全随机数据"));
tooltip.add(Component.literal("§7- 数值数据")); tooltipComponents.add(Component.literal("§7- 字符串+计数器"));
tooltip.add(Component.literal("§7- 自定义数据")); tooltipComponents.add(Component.literal("§7- 数值数据"));
tooltip.add(Component.literal("§7- 重置默认值")); tooltipComponents.add(Component.literal("§7- 自定义数据"));
tooltip.add(Component.literal("§7- 玩家专属数据")); tooltipComponents.add(Component.literal("§7- 重置默认值"));
tooltip.add(Component.literal("")); tooltipComponents.add(Component.literal("§7- 玩家专属数据"));
tooltip.add(Component.literal("§e自身操作特性:")); tooltipComponents.add(Component.literal(""));
tooltip.add(Component.literal("§7- 显示数据预览")); tooltipComponents.add(Component.literal("§e自身操作特性:"));
tooltip.add(Component.literal("§7- 玩家专属数据变换")); tooltipComponents.add(Component.literal("§7- 显示数据预览"));
tooltipComponents.add(Component.literal("§7- 玩家专属数据变换"));
} }
} }

View File

@ -1,6 +1,7 @@
package top.r3944realms.lib39.mixin.carryon; package top.r3944realms.lib39.mixin.carryon;
import com.llamalad7.mixinextras.sugar.Local; import com.llamalad7.mixinextras.sugar.Local;
import com.mojang.authlib.GameProfile;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
@ -8,11 +9,16 @@ import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.ModifyVariable;
import top.r3944realms.lib39.content.block.AbstractDollBlock;
import top.r3944realms.lib39.content.item.DollItem; import top.r3944realms.lib39.content.item.DollItem;
import top.r3944realms.lib39.util.GameProfileHelper; import top.r3944realms.lib39.util.GameProfileHelper;
import top.r3944realms.lib39.util.nbt.NBTReader;
import tschipp.carryon.client.render.CarriedObjectRender; import tschipp.carryon.client.render.CarriedObjectRender;
import tschipp.carryon.common.carry.CarryOnDataManager; import tschipp.carryon.common.carry.CarryOnDataManager;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/** /**
* The type Mixin carried object render. * The type Mixin carried object render.
*/ */
@ -28,8 +34,12 @@ public class MixinCarriedObjectRender {
) )
private static ItemStack warpDollItem$1(ItemStack stack, @Local(ordinal = 0, argsOnly = true) Player player) { private static ItemStack warpDollItem$1(ItemStack stack, @Local(ordinal = 0, argsOnly = true) Player player) {
if (stack.getItem() instanceof DollItem) { if (stack.getItem() instanceof DollItem) {
CompoundTag compound = CarryOnDataManager.getCarryData(player).getNbt().getCompound("tile").getCompound(GameProfileHelper.TAG_OWN_PROFILE); CompoundTag compound = CarryOnDataManager.getCarryData(player).getNbt().getCompound("tile");
stack.getOrCreateTag().put(GameProfileHelper.TAG_OWN_PROFILE, compound); AtomicReference<GameProfile> gameProfileAtomicReference = new AtomicReference<>();
NBTReader.of(compound).gameProfile(GameProfileHelper.TAG_OWN_PROFILE, gameProfileAtomicReference::set);
if (gameProfileAtomicReference.get() != null) {
GameProfileHelper.saveProfileToItemStack(stack, gameProfileAtomicReference.get());
}
} }
return stack; return stack;
} }
@ -42,8 +52,12 @@ public class MixinCarriedObjectRender {
) )
private static ItemStack warpDollItem$2(ItemStack stack, @Local(ordinal = 0) Player player) { private static ItemStack warpDollItem$2(ItemStack stack, @Local(ordinal = 0) Player player) {
if (stack.getItem() instanceof DollItem) { if (stack.getItem() instanceof DollItem) {
CompoundTag compound = CarryOnDataManager.getCarryData(player).getNbt().getCompound("tile").getCompound(GameProfileHelper.TAG_OWN_PROFILE); CompoundTag compound = CarryOnDataManager.getCarryData(player).getNbt().getCompound("tile");
stack.getOrCreateTag().put(GameProfileHelper.TAG_OWN_PROFILE, compound); AtomicReference<GameProfile> gameProfileAtomicReference = new AtomicReference<>();
NBTReader.of(compound).gameProfile(GameProfileHelper.TAG_OWN_PROFILE, gameProfileAtomicReference::set);
if (gameProfileAtomicReference.get() != null) {
GameProfileHelper.saveProfileToItemStack(stack, gameProfileAtomicReference.get());
}
} }
return stack; return stack;
} }

View File

@ -8,13 +8,16 @@ import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.PlayerInfo; import net.minecraft.client.multiplayer.PlayerInfo;
import net.minecraft.client.player.AbstractClientPlayer; import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.resources.DefaultPlayerSkin; import net.minecraft.client.resources.DefaultPlayerSkin;
import net.minecraft.core.component.DataComponents;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils; import net.minecraft.nbt.NbtUtils;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.component.ResolvableProfile;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.util.nbt.NBTReader; import top.r3944realms.lib39.util.nbt.NBTReader;
import top.r3944realms.lib39.util.nbt.NBTWriter; import top.r3944realms.lib39.util.nbt.NBTWriter;
@ -41,7 +44,7 @@ public class GameProfileHelper {
public static @NotNull ResourceLocation resolveSkinTexture(@NotNull GameProfile gameProfile) { public static @NotNull ResourceLocation resolveSkinTexture(@NotNull GameProfile gameProfile) {
return IClientOnly.check(() -> return IClientOnly.check(() ->
Minecraft.getInstance().getSkinManager() Minecraft.getInstance().getSkinManager()
.getInsecureSkinLocation(gameProfile)); .getInsecureSkin(gameProfile)).texture();
} }
/** /**
@ -53,7 +56,7 @@ public class GameProfileHelper {
public static ResourceLocation getSkinTexture(@Nullable GameProfile gameProfile) { public static ResourceLocation getSkinTexture(@Nullable GameProfile gameProfile) {
return IClientOnly.check(() -> { return IClientOnly.check(() -> {
if (gameProfile == null) { if (gameProfile == null) {
return DefaultPlayerSkin.getDefaultSkin(); return Lib39.mrl("textures/entity/player/wide/steve.png");
} }
return resolveSkinTexture(gameProfile); return resolveSkinTexture(gameProfile);
}); });
@ -71,7 +74,7 @@ public class GameProfileHelper {
PlayerInfo playerInfo = Objects.requireNonNull(Minecraft.getInstance() PlayerInfo playerInfo = Objects.requireNonNull(Minecraft.getInstance()
.getConnection()) .getConnection())
.getPlayerInfo(clientPlayer.getUUID()); .getPlayerInfo(clientPlayer.getUUID());
return playerInfo != null && "slim".equals(playerInfo.getModelName()); return playerInfo != null && "slim".equals(playerInfo.getSkin().model().id());
} }
return false; return false;
}); });
@ -88,18 +91,13 @@ public class GameProfileHelper {
if (player.level().isClientSide && player instanceof AbstractClientPlayer) { if (player.level().isClientSide && player instanceof AbstractClientPlayer) {
PlayerInfo info = Objects.requireNonNull(Minecraft.getInstance().getConnection()) PlayerInfo info = Objects.requireNonNull(Minecraft.getInstance().getConnection())
.getPlayerInfo(player.getUUID()); .getPlayerInfo(player.getUUID());
return info != null ? info.getModelName() : "default"; return info != null ? info.getSkin().model().id() : "default";
} }
return "default"; return "default";
}); });
} }
} }
/**
* The constant TAG_BE.
*/
public static final String TAG_BE = "BlockEntityTag";
/** /**
* The constant TAG_OWN_PROFILE. * The constant TAG_OWN_PROFILE.
*/ */
@ -150,7 +148,7 @@ public class GameProfileHelper {
GameProfile profile = player.getGameProfile(); GameProfile profile = player.getGameProfile();
for (Property property : profile.getProperties().get("textures")) { for (Property property : profile.getProperties().get("textures")) {
try { try {
String json = new String(Base64.getDecoder().decode(property.getValue())); String json = new String(Base64.getDecoder().decode(property.value()));
JsonObject obj = JsonParser.parseString(json).getAsJsonObject(); JsonObject obj = JsonParser.parseString(json).getAsJsonObject();
JsonObject textures = obj.getAsJsonObject("textures"); JsonObject textures = obj.getAsJsonObject("textures");
JsonObject skin = textures.getAsJsonObject("SKIN"); JsonObject skin = textures.getAsJsonObject("SKIN");
@ -197,7 +195,7 @@ public class GameProfileHelper {
// 获取第一个texture属性通常是皮肤 // 获取第一个texture属性通常是皮肤
Property textureProperty = textures.iterator().next(); Property textureProperty = textures.iterator().next();
String value = textureProperty.getValue(); String value = textureProperty.value();
try { try {
return isSlimFromTextureData(value); return isSlimFromTextureData(value);
@ -268,7 +266,7 @@ public class GameProfileHelper {
} }
Property textureProperty = textures.iterator().next(); Property textureProperty = textures.iterator().next();
String value = textureProperty.getValue(); String value = textureProperty.value();
try { try {
byte[] decodedBytes = Base64.getDecoder().decode(value); byte[] decodedBytes = Base64.getDecoder().decode(value);
@ -291,7 +289,7 @@ public class GameProfileHelper {
} }
/** /**
* 从ItemStack的NBT中读取GameProfile * 从ItemStack的组件中读取GameProfile
* *
* @param stack the stack * @param stack the stack
* @return the profile from item stack * @return the profile from item stack
@ -302,53 +300,26 @@ public class GameProfileHelper {
return null; return null;
} }
CompoundTag tag = stack.getTag(); if (stack.isEmpty()) return null;
if (tag == null) {
return null; ResolvableProfile profile = stack.get(DataComponents.PROFILE);
} return profile != null ? profile.gameProfile() : null;
AtomicReference<GameProfile> profileRef = new AtomicReference<>();
// 检查方块实体数据
NBTReader.of(tag)
.compound(TAG_BE, compoundTag ->
NBTReader.of(compoundTag)
.compound("OwnerProfile", ct -> profileRef.set(NbtUtils.readGameProfile(ct)))
)
.compound("OwnerProfile", ct -> {
if (profileRef.get() == null) { //兼容写法
profileRef.set(NbtUtils.readGameProfile(ct));
}
});
return profileRef.get();
} }
/** /**
* 将GameProfile保存到ItemStack的NBT * 将GameProfile保存到ItemStack的组件
* *
* @param stack the stack * @param stack the stack
* @param profile the profile * @param profile the profile
*/ */
public static void saveProfileToItemStack(@NotNull ItemStack stack, @Nullable GameProfile profile) { public static void saveProfileToItemStack(@NotNull ItemStack stack, @Nullable GameProfile profile) {
if (stack.isEmpty()) { if (stack.isEmpty()) return;
return;
}
CompoundTag tag = stack.getOrCreateTag();
if (profile == null) { if (profile == null) {
// 移除现有数据 stack.remove(DataComponents.PROFILE);
NBTReader.of(tag) } else {
.compound(TAG_BE, ct -> tag.remove(TAG_OWN_PROFILE)); stack.set(DataComponents.PROFILE, new ResolvableProfile(profile));
tag.remove(TAG_BE);
tag.remove(TAG_OWN_PROFILE);
return;
} }
// 创建方块实体数据
NBTWriter.of(tag)
.compound(TAG_BE, writer ->
writer
.compound(TAG_OWN_PROFILE, NbtUtils.writeGameProfile(new CompoundTag(), profile))
);
} }
/** /**
@ -362,17 +333,7 @@ public class GameProfileHelper {
return false; return false;
} }
CompoundTag tag = stack.getTag(); return !stack.isEmpty() && stack.has(DataComponents.PROFILE);
if (tag == null) {
return false;
}
if (tag.contains(TAG_BE)) {
CompoundTag blockEntityTag = tag.getCompound(TAG_BE);
return blockEntityTag.contains(TAG_OWN_PROFILE);
}
return tag.contains(TAG_OWN_PROFILE);
} }
} }

View File

@ -15,6 +15,8 @@
package top.r3944realms.lib39.util.nbt; package top.r3944realms.lib39.util.nbt;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag; import net.minecraft.nbt.ListTag;
import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.Vec3;
@ -378,6 +380,87 @@ public class NBTReader {
return this; return this;
} }
/**
* Game profile nbt reader.
*
* @param key the key
* @param setter the setter
* @return the nbt reader
*/
public NBTReader gameProfile(String key, Consumer<GameProfile> setter) {
if (nbt.contains(key, CompoundTag.TAG_COMPOUND)) {
CompoundTag tag = nbt.getCompound(key);
GameProfile profile = readGameProfileFromTag(tag);
if (profile != null) {
setter.accept(profile);
}
}
return this;
}
/**
* Game profile nbt reader with default value.
*
* @param key the key
* @param setter the setter
* @param defaultValue the default value
* @return the nbt reader
*/
public NBTReader gameProfile(String key, Consumer<GameProfile> setter, GameProfile defaultValue) {
if (nbt.contains(key, CompoundTag.TAG_COMPOUND)) {
CompoundTag tag = nbt.getCompound(key);
GameProfile profile = readGameProfileFromTag(tag);
if (profile != null) {
setter.accept(profile);
return this;
}
}
setter.accept(defaultValue);
return this;
}
/**
* Read GameProfile from CompoundTag.
*
* @param tag the tag
* @return the game profile, or null if invalid
*/
@Nullable
private static GameProfile readGameProfileFromTag(@NotNull CompoundTag tag) {
String name = null;
UUID uuid = null;
if (tag.contains("Name", CompoundTag.TAG_STRING)) {
name = tag.getString("Name");
}
if (tag.hasUUID("Id")) {
uuid = tag.getUUID("Id");
}
try {
GameProfile profile = new GameProfile(uuid, name);
if (tag.contains("Properties", CompoundTag.TAG_COMPOUND)) {
CompoundTag propertiesTag = tag.getCompound("Properties");
for (String key : propertiesTag.getAllKeys()) {
ListTag listTag = propertiesTag.getList(key, CompoundTag.TAG_COMPOUND);
for (int i = 0; i < listTag.size(); i++) {
CompoundTag propTag = listTag.getCompound(i);
String value = propTag.getString("Value");
if (propTag.contains("Signature", CompoundTag.TAG_STRING)) {
profile.getProperties().put(key, new Property(key, value, propTag.getString("Signature")));
} else {
profile.getProperties().put(key, new Property(key, value));
}
}
}
}
return profile;
} catch (Throwable e) {
return null;
}
}
/** /**
* Vec 3 nbt reader. * Vec 3 nbt reader.
* *
@ -469,6 +552,7 @@ public class NBTReader {
return this; return this;
} }
/** /**
* Nested nbt reader. * Nested nbt reader.
* *

View File

@ -1,5 +1,8 @@
package top.r3944realms.lib39.util.nbt; package top.r3944realms.lib39.util.nbt;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import io.netty.util.internal.StringUtil;
import net.minecraft.nbt.*; import net.minecraft.nbt.*;
import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.Contract;
@ -562,7 +565,6 @@ public class NBTWriter {
* @param tag the tag * @param tag the tag
* @return the nbt writer * @return the nbt writer
*/ */
// 直接操作Tag
public NBTWriter tag(String key, Tag tag) { public NBTWriter tag(String key, Tag tag) {
if (tag != null) { if (tag != null) {
root.put(key, tag); root.put(key, tag);
@ -570,6 +572,60 @@ public class NBTWriter {
return this; return this;
} }
/**
* Game profile nbt writer.
*
* @param key the key
* @param profile the profile
* @return the nbt writer
*/
public NBTWriter gameProfile(String key, @NotNull GameProfile profile) {
root.put(key, writeGameProfile(profile));
return this;
}
private CompoundTag writeGameProfile(@NotNull GameProfile profile) {
CompoundTag tag = new CompoundTag();
if (!StringUtil.isNullOrEmpty(profile.getName())) {
tag.putString("Name", profile.getName());
}
if (profile.getId() != null) {
tag.putUUID("Id", profile.getId());
}
if (!profile.getProperties().isEmpty()) {
CompoundTag compoundTag = new CompoundTag();
for(String keySet : profile.getProperties().keySet()) {
ListTag propListTag = new ListTag();
for(Property property : profile.getProperties().get(keySet)) {
CompoundTag propTag = new CompoundTag();
propTag.putString("Value", property.value());
if (property.hasSignature()) {
propTag.putString("Signature", property.signature());
}
propListTag.add(propTag);
}
compoundTag.put(keySet, propListTag);
}
tag.put("Properties", compoundTag);
}
return tag;
}
/**
* GameProfile if nbt writer.
*
* @param key the key
* @param condition the condition
* @param value the value
* @return the nbt writer
*/
public NBTWriter gameProfileIf(String key, boolean condition, Supplier<GameProfile> value) {
if (condition && value != null) {
root.put(key, writeGameProfile(value.get()));
}
return this;
}
/** /**
* String if nbt writer. * String if nbt writer.
* *
@ -578,7 +634,6 @@ public class NBTWriter {
* @param value the value * @param value the value
* @return the nbt writer * @return the nbt writer
*/ */
// 条件添加方法
public NBTWriter stringIf(String key, boolean condition, Supplier<String> value) { public NBTWriter stringIf(String key, boolean condition, Supplier<String> value) {
if (condition && value != null) { if (condition && value != null) {
root.putString(key, value.get()); root.putString(key, value.get());

View File

@ -2,9 +2,15 @@ package top.r3944realms.lib39.util.villager;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.core.component.DataComponents;
import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.tags.EnchantmentTags;
import net.minecraft.tags.ItemTags;
import net.minecraft.tags.TagKey; import net.minecraft.tags.TagKey;
import net.minecraft.util.Mth; import net.minecraft.util.Mth;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
@ -16,15 +22,18 @@ import net.minecraft.world.entity.npc.VillagerType;
import net.minecraft.world.item.*; import net.minecraft.world.item.*;
import net.minecraft.world.item.alchemy.Potion; import net.minecraft.world.item.alchemy.Potion;
import net.minecraft.world.item.alchemy.PotionBrewing; import net.minecraft.world.item.alchemy.PotionBrewing;
import net.minecraft.world.item.alchemy.PotionUtils; import net.minecraft.world.item.alchemy.PotionContents;
import net.minecraft.world.item.component.DyedItemColor;
import net.minecraft.world.item.component.SuspiciousStewEffects;
import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.item.enchantment.EnchantmentInstance; import net.minecraft.world.item.enchantment.EnchantmentInstance;
import net.minecraft.world.item.trading.ItemCost;
import net.minecraft.world.item.trading.MerchantOffer; import net.minecraft.world.item.trading.MerchantOffer;
import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.levelgen.structure.Structure; import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.saveddata.maps.MapDecoration; import net.minecraft.world.level.saveddata.maps.MapDecorationType;
import net.minecraft.world.level.saveddata.maps.MapItemSavedData; import net.minecraft.world.level.saveddata.maps.MapItemSavedData;
import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -32,6 +41,8 @@ import org.jetbrains.annotations.Nullable;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/** /**
* 村民交易构建器 * 村民交易构建器
@ -119,18 +130,19 @@ public class TradeBuilder {
* @param emeraldCost 绿宝石价格 * @param emeraldCost 绿宝石价格
* @param destination the destination * @param destination the destination
* @param displayName 显示名称 * @param displayName 显示名称
* @param destinationTyp the destination typ * @param destinationType the destination type
* @param maxUses 最大使用次数 * @param maxUses 最大使用次数
* @param villagerXp 村民获得的经验 * @param villagerXp 村民获得的经验
* @return 交易实例 treasure map for emeralds * @return 交易实例 treasure map for emeralds
*/ */
@Contract(pure = true) @Contract(pure = true)
public static @NotNull TreasureMapForEmeralds createTreasureMapTrade( public static @NotNull TreasureMapForEmeralds createTreasureMapTrade(
int emeraldCost, TagKey<Structure> destination, String displayName, MapDecoration.Type destinationTyp, int maxUses, int villagerXp) { int emeraldCost, TagKey<Structure> destination, String displayName,
Holder<MapDecorationType> destinationType, int maxUses, int villagerXp) {
return new TreasureMapForEmeralds(emeraldCost, destination, displayName, destinationTyp, maxUses, villagerXp); return new TreasureMapForEmeralds(emeraldCost, destination, displayName, destinationType, maxUses, villagerXp);
} }
/** /**
* 创建染色盔甲交易 * 创建染色盔甲交易
* *
@ -173,8 +185,8 @@ public class TradeBuilder {
} }
public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) { public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) {
ItemStack itemstack = new ItemStack(this.item, this.cost); ItemCost itemCost = new ItemCost(this.item, this.cost);
return new MerchantOffer(itemstack, new ItemStack(Items.EMERALD), this.maxUses, this.villagerXp, this.priceMultiplier); return new MerchantOffer(itemCost, new ItemStack(Items.EMERALD), this.maxUses, this.villagerXp, this.priceMultiplier);
} }
} }
@ -260,7 +272,7 @@ public class TradeBuilder {
} }
public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) { public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) {
return new MerchantOffer(new ItemStack(Items.EMERALD, this.emeraldCost), new ItemStack(this.itemStack.getItem(), this.numberOfItems), this.maxUses, this.villagerXp, this.priceMultiplier); return new MerchantOffer(new ItemCost(Items.EMERALD, this.emeraldCost), new ItemStack(this.itemStack.getItem(), this.numberOfItems), this.maxUses, this.villagerXp, this.priceMultiplier);
} }
} }
@ -271,7 +283,7 @@ public class TradeBuilder {
/** /**
* The Effect. * The Effect.
*/ */
final MobEffect effect; private final Holder<MobEffect> effect;
/** /**
* The Duration. * The Duration.
*/ */
@ -289,7 +301,7 @@ public class TradeBuilder {
* @param duration the duration * @param duration the duration
* @param xp the xp * @param xp the xp
*/ */
public SuspiciousStewForEmerald(MobEffect effect, int duration, int xp) { public SuspiciousStewForEmerald(Holder<MobEffect> effect, int duration, int xp) {
this.effect = effect; this.effect = effect;
this.duration = duration; this.duration = duration;
this.xp = xp; this.xp = xp;
@ -299,8 +311,9 @@ public class TradeBuilder {
@Nullable @Nullable
public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) { public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) {
ItemStack itemstack = new ItemStack(Items.SUSPICIOUS_STEW, 1); ItemStack itemstack = new ItemStack(Items.SUSPICIOUS_STEW, 1);
SuspiciousStewItem.saveMobEffect(itemstack, this.effect, this.duration); itemstack.set(DataComponents.SUSPICIOUS_STEW_EFFECTS,
return new MerchantOffer(new ItemStack(Items.EMERALD, 1), itemstack, 12, this.xp, this.priceMultiplier); new SuspiciousStewEffects(List.of(new SuspiciousStewEffects.Entry(effect, this.duration))));
return new MerchantOffer(new ItemCost(Items.EMERALD, 1), itemstack, 12, this.xp, this.priceMultiplier);
} }
} }
@ -355,7 +368,7 @@ public class TradeBuilder {
@Nullable @Nullable
public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) { public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) {
return new MerchantOffer(new ItemStack(Items.EMERALD, this.emeraldCost), new ItemStack(this.fromItem.getItem(), this.fromCount), new ItemStack(this.toItem.getItem(), this.toCount), this.maxUses, this.villagerXp, this.priceMultiplier); return new MerchantOffer(new ItemCost(Items.EMERALD, this.emeraldCost), Optional.of(new ItemCost(this.fromItem.getItem(), this.fromCount)), new ItemStack(this.toItem.getItem(), this.toCount), this.maxUses, this.villagerXp, this.priceMultiplier);
} }
} }
@ -400,9 +413,10 @@ public class TradeBuilder {
public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) { public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) {
int i = 5 + random.nextInt(15); int i = 5 + random.nextInt(15);
ItemStack itemstack = EnchantmentHelper.enchantItem(random, new ItemStack(this.itemStack.getItem()), i, false); ItemStack itemstack = EnchantmentHelper.enchantItem(random, new ItemStack(this.itemStack.getItem()), i ,
trader.level().registryAccess(), Optional.empty());
int j = Math.min(this.baseEmeraldCost + i, 64); int j = Math.min(this.baseEmeraldCost + i, 64);
ItemStack itemstack1 = new ItemStack(Items.EMERALD, j); ItemCost itemstack1 = new ItemCost(Items.EMERALD, j);
return new MerchantOffer(itemstack1, itemstack, this.maxUses, this.villagerXp, this.priceMultiplier); return new MerchantOffer(itemstack1, itemstack, this.maxUses, this.villagerXp, this.priceMultiplier);
} }
} }
@ -439,8 +453,8 @@ public class TradeBuilder {
@Nullable @Nullable
public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) { public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) {
if (trader instanceof VillagerDataHolder) { if (trader instanceof VillagerDataHolder) {
ItemStack itemstack = new ItemStack(this.trades.get(((VillagerDataHolder)trader).getVillagerData().getType()), this.cost); ItemCost itemCost = new ItemCost(this.trades.get(((VillagerDataHolder)trader).getVillagerData().getType()), this.cost);
return new MerchantOffer(itemstack, new ItemStack(Items.EMERALD), this.maxUses, this.villagerXp, 0.05F); return new MerchantOffer(itemCost, new ItemStack(Items.EMERALD), this.maxUses, this.villagerXp, 0.05F);
} else { } else {
return null; return null;
} }
@ -484,11 +498,15 @@ public class TradeBuilder {
} }
public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) { public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) {
ItemStack itemstack = new ItemStack(Items.EMERALD, this.emeraldCost); ItemCost itemcost = new ItemCost(Items.EMERALD, this.emeraldCost);
List<Potion> list = BuiltInRegistries.POTION.stream().filter((effects) -> !effects.getEffects().isEmpty() && PotionBrewing.isBrewablePotion(effects)).toList(); List<? extends Holder<Potion>> brewablePotions = BuiltInRegistries.POTION.holders()
Potion potion = list.get(random.nextInt(list.size())); .filter(potion -> !potion.value().getEffects().isEmpty())
ItemStack itemstack1 = PotionUtils.setPotion(new ItemStack(this.toItem.getItem(), this.toCount), potion); .filter(trader.level().potionBrewing()::isBrewablePotion)
return new MerchantOffer(itemstack, new ItemStack(this.fromItem, this.fromCount), itemstack1, this.maxUses, this.villagerXp, this.priceMultiplier); .toList();
Holder<Potion> potion = brewablePotions.get(random.nextInt(brewablePotions.size()));
ItemStack itemstack = new ItemStack(this.toItem.getItem(), this.toCount);
itemstack.set(DataComponents.POTION_CONTENTS, new PotionContents(potion));
return new MerchantOffer(itemcost, Optional.of(new ItemCost(this.fromItem, this.fromCount)), itemstack, this.maxUses, this.villagerXp, this.priceMultiplier);
} }
} }
@ -509,12 +527,17 @@ public class TradeBuilder {
} }
public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) { public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) {
List<Enchantment> list = BuiltInRegistries.ENCHANTMENT.stream().filter(Enchantment::isTradeable).toList(); Registry<Enchantment> registry = trader.level().registryAccess().registryOrThrow(Registries.ENCHANTMENT);
Enchantment enchantment = list.get(random.nextInt(list.size())); List<? extends Holder<Enchantment>> list = registry.holders()
.filter(holder -> holder.is(EnchantmentTags.TRADEABLE))
.toList();
Holder<Enchantment> holder = list.get(random.nextInt(list.size()));
Enchantment enchantment = holder.value();
int i = Mth.nextInt(random, enchantment.getMinLevel(), enchantment.getMaxLevel()); int i = Mth.nextInt(random, enchantment.getMinLevel(), enchantment.getMaxLevel());
ItemStack itemstack = EnchantedBookItem.createForEnchantment(new EnchantmentInstance(enchantment, i)); ItemStack itemstack = EnchantedBookItem.createForEnchantment(new EnchantmentInstance(holder, i));
int j = 2 + random.nextInt(5 + i * 10) + 3 * i; int j = 2 + random.nextInt(5 + i * 10) + 3 * i;
if (enchantment.isTreasureOnly()) {
if (holder.is(EnchantmentTags.DOUBLE_TRADE_PRICE)) {
j *= 2; j *= 2;
} }
@ -522,7 +545,7 @@ public class TradeBuilder {
j = 64; j = 64;
} }
return new MerchantOffer(new ItemStack(Items.EMERALD, j), new ItemStack(Items.BOOK), itemstack, 12, this.villagerXp, 0.2F); return new MerchantOffer(new ItemCost(Items.EMERALD, j), Optional.of(new ItemCost(Items.BOOK)), itemstack, 12, this.villagerXp, 0.2F);
} }
} }
@ -533,7 +556,7 @@ public class TradeBuilder {
private final int emeraldCost; private final int emeraldCost;
private final TagKey<Structure> destination; private final TagKey<Structure> destination;
private final String displayName; private final String displayName;
private final MapDecoration.Type destinationType; private final Holder<MapDecorationType> destinationType;
private final int maxUses; private final int maxUses;
private final int villagerXp; private final int villagerXp;
@ -547,7 +570,7 @@ public class TradeBuilder {
* @param maxUses the max uses * @param maxUses the max uses
* @param villagerXp the villager xp * @param villagerXp the villager xp
*/ */
public TreasureMapForEmeralds(int emeraldCost, TagKey<Structure> destination, String displayName, MapDecoration.Type destinationType, int maxUses, int villagerXp) { public TreasureMapForEmeralds(int emeraldCost, TagKey<Structure> destination, String displayName, Holder<MapDecorationType> destinationType, int maxUses, int villagerXp) {
this.emeraldCost = emeraldCost; this.emeraldCost = emeraldCost;
this.destination = destination; this.destination = destination;
this.displayName = displayName; this.displayName = displayName;
@ -566,8 +589,10 @@ public class TradeBuilder {
ItemStack itemstack = MapItem.create(serverlevel, blockpos.getX(), blockpos.getZ(), (byte)2, true, true); ItemStack itemstack = MapItem.create(serverlevel, blockpos.getX(), blockpos.getZ(), (byte)2, true, true);
MapItem.renderBiomePreviewMap(serverlevel, itemstack); MapItem.renderBiomePreviewMap(serverlevel, itemstack);
MapItemSavedData.addTargetDecoration(itemstack, blockpos, "+", this.destinationType); MapItemSavedData.addTargetDecoration(itemstack, blockpos, "+", this.destinationType);
itemstack.setHoverName(Component.translatable(this.displayName)); MapItemSavedData.addTargetDecoration(itemstack, blockpos, "+", this.destinationType);
return new MerchantOffer(new ItemStack(Items.EMERALD, this.emeraldCost), new ItemStack(Items.COMPASS), itemstack, this.maxUses, this.villagerXp, 0.2F); itemstack.set(DataComponents.ITEM_NAME, Component.translatable(this.displayName));
return new MerchantOffer(new ItemCost(Items.EMERALD, this.emeraldCost),
Optional.of(new ItemCost(Items.COMPASS)), itemstack, this.maxUses, this.villagerXp, 0.2F);
} else { } else {
return null; return null;
} }
@ -610,23 +635,23 @@ public class TradeBuilder {
} }
public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) { public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource random) {
ItemStack itemstack = new ItemStack(Items.EMERALD, this.value); ItemCost itemCost = new ItemCost(Items.EMERALD, this.value);
ItemStack itemstack1 = new ItemStack(this.item); ItemStack armorStack = new ItemStack(this.item);
if (this.item instanceof DyeableArmorItem) {
List<DyeItem> list = Lists.newArrayList(); if (armorStack.is(ItemTags.DYEABLE)) {
list.add(getRandomDye(random)); List<DyeItem> dyes = Lists.newArrayList();
dyes.add(getRandomDye(random));
if (random.nextFloat() > 0.7F) { if (random.nextFloat() > 0.7F) {
list.add(getRandomDye(random)); dyes.add(getRandomDye(random));
} }
if (random.nextFloat() > 0.8F) { if (random.nextFloat() > 0.8F) {
list.add(getRandomDye(random)); dyes.add(getRandomDye(random));
} }
// 1.21.1: 使用 DYED_COLOR 组件设置颜色
itemstack1 = DyeableLeatherItem.dyeArmor(itemstack1, list); armorStack = DyedItemColor.applyDyes(armorStack, dyes);
} }
return new MerchantOffer(itemstack, itemstack1, this.maxUses, this.villagerXp, 0.2F); return new MerchantOffer(itemCost, armorStack, this.maxUses, this.villagerXp, 0.2F);
} }
private static @NotNull DyeItem getRandomDye(@NotNull RandomSource random) { private static @NotNull DyeItem getRandomDye(@NotNull RandomSource random) {

View File

@ -3,7 +3,7 @@
"minVersion": "0.8", "minVersion": "0.8",
"package": "top.r3944realms.lib39.mixin", "package": "top.r3944realms.lib39.mixin",
"refmap": "${mod_id}.refmap.json", "refmap": "${mod_id}.refmap.json",
"compatibilityLevel": "JAVA_17", "compatibilityLevel": "JAVA_21",
"mixins": [ "mixins": [
"carryon.MixinCarriedObjectRender", "carryon.MixinCarriedObjectRender",
"minecraft.CreativeModeTabsAccessor" "minecraft.CreativeModeTabsAccessor"

View File

@ -4,23 +4,19 @@ plugins {
id 'multiloader-loader' id 'multiloader-loader'
id 'fabric-loom' id 'fabric-loom'
} }
repositories {
maven { url 'https://maven.covers1624.net/' }
}
dependencies { dependencies {
minecraft "com.mojang:minecraft:${minecraft_version}" minecraft "com.mojang:minecraft:${minecraft_version}"
mappings loom.layered { mappings loom.layered {
officialMojangMappings() officialMojangMappings()
parchment("org.parchmentmc.data:parchment-${parchment_minecraft}:${parchment_version}@zip") parchment("org.parchmentmc.data:parchment-${parchment_minecraft}:${parchment_version}@zip")
} }
modImplementation(group: 'tschipp.carryon', name: 'carryon-fabric-1.20.1', version: '2.1.2.7') { modImplementation(group: 'tschipp.carryon', name: 'carryon-fabric-1.21.1', version: '2.2.4.4') {
transitive = false transitive = false
} }
modImplementation "net.fabricmc:fabric-loader:${fabric_loader_version}" modImplementation "net.fabricmc:fabric-loader:${fabric_loader_version}"
modImplementation "net.fabricmc.fabric-api:fabric-api:${fabric_version}" modImplementation "net.fabricmc.fabric-api:fabric-api:${fabric_version}"
implementation group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.1' modImplementation "curse.maven:jade-324717:7545228"
implementation project(":common")
modImplementation "curse.maven:jade-324717:6291330"
testImplementation "net.fabricmc:fabric-loader-junit:${fabric_loader_version}" testImplementation "net.fabricmc:fabric-loader-junit:${fabric_loader_version}"
localRuntime 'net.covers1624:DevLogin:0.1.0.5' localRuntime 'net.covers1624:DevLogin:0.1.0.5'
} }
@ -102,7 +98,7 @@ tasks.named('javadoc', Javadoc) {
classpath += project(':common').sourceSets.main.compileClasspath classpath += project(':common').sourceSets.main.compileClasspath
options.encoding = 'UTF-8' options.encoding = 'UTF-8'
options.charSet = 'UTF-8' options.charSet = 'UTF-8'
options.links("https://docs.oracle.com/en/java/javase/17/docs/api/") options.links("https://docs.oracle.com/en/java/javase/21/docs/api/")
options.memberLevel = JavadocMemberLevel.PUBLIC options.memberLevel = JavadocMemberLevel.PUBLIC
options.addBooleanOption('Xdoclint:none', true) options.addBooleanOption('Xdoclint:none', true)
options.addStringOption('doctitle', "${mod_id} ${minecraft_version} ${version} Javadoc") options.addStringOption('doctitle', "${mod_id} ${minecraft_version} ${version} Javadoc")
@ -136,13 +132,6 @@ remapSourcesJar {
inputFile.set(tasks.named('sourcesJar').get().archiveFile) inputFile.set(tasks.named('sourcesJar').get().archiveFile)
} }
// javadocJar创建remap任务
tasks.register('remapJavadocJar', RemapJarTask) {
dependsOn tasks.named('javadocJar')
inputFile.set(tasks.named('javadocJar').get().archiveFile)
archiveClassifier.set('javadoc')
addNestedDependencies = false
}
// remapped artifacts添加到发布配置 // remapped artifacts添加到发布配置
publishing { publishing {
@ -159,61 +148,20 @@ publishing {
builtBy remapSourcesJar builtBy remapSourcesJar
classifier = 'sources' classifier = 'sources'
} }
artifact(remapJavadocJar) { artifact(javadocJar) {
builtBy remapJavadocJar builtBy javadocJar
classifier = 'javadoc' classifier = 'javadoc'
} }
pom {
name = 'Lib39'
description = 'Lib39 is a general-purpose dependency library for Minecraft mods.'
url = 'https://github.com/3944Realms/lib39'
properties = [
'minecraft.version': project.minecraft_version,
'mod.version': project.version,
'fabric.version': project.fabric_version,
'java.version': '17'
]
licenses {
license {
name = 'MIT'
url = 'https://raw.githubusercontent.com/3944Realms/lib39/refs/heads/main/LICENSE'
distribution = 'repo'
}
}
developers {
developer {
id = 'R3944Realms'
name = "${mod_author}"
email = 'f256198830@hotmail.com'
}
}
scm {
connection = 'scm:git:https://github.com/3944Realms/lib39.git'
developerConnection = 'scm:git:ssh://git@github.com:3944Realms/lib39.git'
url = 'https://github.com/3944Realms/lib39'
tag = 'main'
}
issueManagement {
system = 'GitHub'
url = 'https://github.com/3944Realms/lib39/issues'
}
}
} }
} }
} test {
test { useJUnitPlatform()
useJUnitPlatform() }
}
tasks.named('generateMetadataFileForMavenJavaPublication') { tasks.named('generateMetadataFileForMavenJavaPublication') {
dependsOn tasks.named('remapJavadocJar') dependsOn tasks.named('remapJar')
dependsOn tasks.named('remapJar') dependsOn tasks.named('remapSourcesJar')
dependsOn tasks.named('remapSourcesJar') dependsOn tasks.named('javadocJar')
} }
}

View File

@ -1,11 +1,13 @@
package top.r3944realms.lib39.base.compat.jade; package top.r3944realms.lib39.base.compat.jade;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
import snownee.jade.api.IWailaClientRegistration; import snownee.jade.api.IWailaClientRegistration;
import snownee.jade.api.IWailaPlugin; import snownee.jade.api.IWailaPlugin;
import snownee.jade.api.WailaPlugin; import snownee.jade.api.WailaPlugin;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.base.compat.jade.provider.FabricDollComponentProvider; import top.r3944realms.lib39.base.compat.jade.provider.FabricDollComponentProvider;
import top.r3944realms.lib39.content.block.AbstractDollBlock;
import top.r3944realms.lib39.content.block.DollBlock; import top.r3944realms.lib39.content.block.DollBlock;
/** /**
@ -19,7 +21,7 @@ public class FabricJadePlugin implements IWailaPlugin {
public static final ResourceLocation UID = Lib39.rl("lib39"); public static final ResourceLocation UID = Lib39.rl("lib39");
@Override @Override
public void registerClient(IWailaClientRegistration registration) { public void registerClient(@NotNull IWailaClientRegistration registration) {
registration.registerBlockComponent(new FabricDollComponentProvider(), DollBlock.class); registration.registerBlockComponent(new FabricDollComponentProvider(), AbstractDollBlock.class);
} }
} }

View File

@ -3,6 +3,7 @@ package top.r3944realms.lib39.base.compat.jade.provider;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
import snownee.jade.api.BlockAccessor; import snownee.jade.api.BlockAccessor;
import snownee.jade.api.IBlockComponentProvider; import snownee.jade.api.IBlockComponentProvider;
import snownee.jade.api.ITooltip; import snownee.jade.api.ITooltip;
@ -20,7 +21,7 @@ public class FabricDollComponentProvider implements IBlockComponentProvider {
} }
@Override @Override
public void appendTooltip(ITooltip iTooltip, BlockAccessor blockAccessor, IPluginConfig iPluginConfig) { public void appendTooltip(ITooltip iTooltip, @NotNull BlockAccessor blockAccessor, IPluginConfig iPluginConfig) {
if (blockAccessor.getBlockEntity() instanceof DollBlockEntity doll) { if (blockAccessor.getBlockEntity() instanceof DollBlockEntity doll) {
GameProfile ownerProfile = doll.getOwnerProfile(); GameProfile ownerProfile = doll.getOwnerProfile();
if (ownerProfile != null) { if (ownerProfile != null) {

View File

@ -9,6 +9,7 @@ import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents;
import net.fabricmc.fabric.api.lookup.v1.entity.EntityApiLookup; import net.fabricmc.fabric.api.lookup.v1.entity.EntityApiLookup;
import net.minecraft.Util; import net.minecraft.Util;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.component.DataComponents;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
@ -18,6 +19,7 @@ import net.minecraft.world.entity.Entity;
import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items; import net.minecraft.world.item.Items;
import net.minecraft.world.item.component.ResolvableProfile;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.SkullBlockEntity; import net.minecraft.world.level.block.entity.SkullBlockEntity;
@ -183,16 +185,28 @@ public class FabricCommonEventHandler {
} }
AnvilUpdateCallback.EVENT.register((left, right, outputSlot, name, baseCost, player) -> { AnvilUpdateCallback.EVENT.register((left, right, outputSlot, name, baseCost, player) -> {
if (left.getItem() instanceof DollItem && name != null && name.length() < 15) { if (left.getItem() instanceof DollItem && name != null && name.length() < 15) {
// 创建 GameProfile使用 NIL_UUID 临时占位
GameProfile profile = new GameProfile(Util.NIL_UUID, name); GameProfile profile = new GameProfile(Util.NIL_UUID, name);
ItemStack copied = Lib39Items.DOLL.get().getDefaultInstance(); ItemStack copied = Lib39Items.DOLL.get().getDefaultInstance();
SkullBlockEntity.updateGameprofile(profile,
profile1 -> GameProfileHelper.saveProfileToItemStack(copied, profile1)
);
copied.setCount(left.getCount()); copied.setCount(left.getCount());
// 使用 ResolvableProfile 进行异步解析
ResolvableProfile resolvableProfile = new ResolvableProfile(profile);
if (!resolvableProfile.isResolved()) {
resolvableProfile.resolve().thenAcceptAsync(resolved -> {
// 解析完成后保存到 ItemStack
GameProfile resolvedProfile = resolved.gameProfile();
GameProfileHelper.saveProfileToItemStack(copied, resolvedProfile);
}, player.getServer());
} else {
GameProfileHelper.saveProfileToItemStack(copied, profile);
}
return AnvilUpdateCallback.AnvilUpdateResult.withOutput(copied, 1, 1); return AnvilUpdateCallback.AnvilUpdateResult.withOutput(copied, 1, 1);
} else { } else {
ItemStack defaultInstance = Items.BARRIER.getDefaultInstance(); ItemStack defaultInstance = Items.BARRIER.getDefaultInstance();
defaultInstance.setHoverName(Component.translatable("invalid.player_name.too_long")); defaultInstance.set(DataComponents.CUSTOM_NAME,
Component.translatable("invalid.player_name.too_long"));
return AnvilUpdateCallback.AnvilUpdateResult.withOutput(defaultInstance, 0, 0); return AnvilUpdateCallback.AnvilUpdateResult.withOutput(defaultInstance, 0, 0);
} }
}); });

View File

@ -14,7 +14,7 @@ public class FabricNetworkHandler {
public static void registerClientReceivers() { public static void registerClientReceivers() {
ClientPlayNetworking.registerGlobalReceiver( ClientPlayNetworking.registerGlobalReceiver(
SyncNBTLookupDataEntityS2CPacket.TYPE, SyncNBTLookupDataEntityS2CPacket.TYPE,
SyncNBTLookupDataEntityS2CPacket::receive SyncNBTLookupDataEntityS2CPacket::handle
); );
} }

View File

@ -1,11 +1,14 @@
package top.r3944realms.lib39.core.network.toClient; package top.r3944realms.lib39.core.network.toClient;
import net.fabricmc.fabric.api.networking.v1.FabricPacket; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.fabricmc.fabric.api.networking.v1.PacketSender;
import net.fabricmc.fabric.api.networking.v1.PacketType;
import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.player.LocalPlayer;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.PacketType;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
@ -22,7 +25,7 @@ import java.util.Optional;
/** /**
* The type Sync nbt lookup data entity s 2 c packet. * The type Sync nbt lookup data entity s 2 c packet.
*/ */
public record SyncNBTLookupDataEntityS2CPacket(int entityId, ResourceLocation id, CompoundTag data) implements FabricPacket { public record SyncNBTLookupDataEntityS2CPacket(int entityId, ResourceLocation id, CompoundTag data) implements CustomPacketPayload {
/** /**
* The constant SYNC_NBT_LOOKUP_PACKET_ID. * The constant SYNC_NBT_LOOKUP_PACKET_ID.
*/ */
@ -31,10 +34,7 @@ public record SyncNBTLookupDataEntityS2CPacket(int entityId, ResourceLocation id
/** /**
* The constant TYPE. * The constant TYPE.
*/ */
public static final PacketType<SyncNBTLookupDataEntityS2CPacket> TYPE = PacketType.create( public static final Type<SyncNBTLookupDataEntityS2CPacket> TYPE = new Type<>(SYNC_NBT_LOOKUP_PACKET_ID);
SYNC_NBT_LOOKUP_PACKET_ID,
buf -> new SyncNBTLookupDataEntityS2CPacket(buf.readInt(), buf.readResourceLocation(), buf.readNbt())
);
/** /**
* Instantiates a new Sync nbt data s 2 c pack. * Instantiates a new Sync nbt data s 2 c pack.
@ -46,46 +46,60 @@ public record SyncNBTLookupDataEntityS2CPacket(int entityId, ResourceLocation id
this(entityId, data.id(), data.serializeNBT()); this(entityId, data.id(), data.serializeNBT());
} }
@Override /**
* Instantiates from buffer.
*
* @param buf the buffer
*/
public SyncNBTLookupDataEntityS2CPacket(RegistryFriendlyByteBuf buf) {
this(buf.readInt(), buf.readResourceLocation(), buf.readNbt());
}
public void write(@NotNull FriendlyByteBuf friendlyByteBuf) { public void write(@NotNull FriendlyByteBuf friendlyByteBuf) {
friendlyByteBuf.writeInt(entityId); friendlyByteBuf.writeInt(entityId);
friendlyByteBuf.writeResourceLocation(id); friendlyByteBuf.writeResourceLocation(id);
friendlyByteBuf.writeNbt(data); friendlyByteBuf.writeNbt(data);
} }
/**
@Contract(value = " -> new", pure = true) * Stream codec for serializing/deserializing the packet.
@Override */
public @NotNull PacketType<?> getType() { public static final StreamCodec<RegistryFriendlyByteBuf, SyncNBTLookupDataEntityS2CPacket> STREAM_CODEC =
return TYPE; StreamCodec.ofMember(SyncNBTLookupDataEntityS2CPacket::write, SyncNBTLookupDataEntityS2CPacket::new);
}
/** /**
* Receive. * Receive.
* *
* @param packet the packet * @param packet the packet
* @param localPlayer the local player * @param context the context
* @param packetSender the packet sender
*/ */
public static void receive(@NotNull SyncNBTLookupDataEntityS2CPacket packet, @NotNull LocalPlayer localPlayer, PacketSender packetSender) { public static void handle(@NotNull SyncNBTLookupDataEntityS2CPacket packet, ClientPlayNetworking.Context context) {
LocalPlayer localPlayer = context.player();
Level level = localPlayer.level(); Level level = localPlayer.level();
Entity entity = level.getEntity(packet.entityId); Entity entity = level.getEntity(packet.entityId);
if (entity != null) { if (entity != null) {
Optional<SyncData2Manager.DataProvider<Entity, ISyncData<?>>> lookupOpt = Optional<SyncData2Manager.DataProvider<Entity, ISyncData<?>>> lookupOpt =
FabricCommonEventHandler FabricCommonEventHandler
.getSyncData2Manager() .getSyncData2Manager()
.getDataProvider(packet.id); .getDataProvider(packet.id);
lookupOpt.flatMap(dataProvider -> dataProvider.getData(entity)) lookupOpt.flatMap(dataProvider -> dataProvider.getData(entity))
.ifPresent(lookup -> { .ifPresent(lookup -> {
if (lookup instanceof NBTEntitySyncData nbtLookup) { if (lookup instanceof NBTEntitySyncData nbtLookup) {
CompoundTag current = nbtLookup.serializeNBT(); CompoundTag current = nbtLookup.serializeNBT();
if (!current.equals(packet.data)) { if (!current.equals(packet.data)) {
nbtLookup.deserializeNBT(packet.data); nbtLookup.deserializeNBT(packet.data);
}
} else Lib39.LOGGER.debug("Unhandled sync data: {}", packet.data);
} }
); } else {
Lib39.LOGGER.debug("Unhandled sync data: {}", packet.data);
}
});
} }
} }
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
} }

View File

@ -1,6 +1,6 @@
package top.r3944realms.lib39.example; package top.r3944realms.lib39.example;
import top.r3944realms.lib39.core.compat.CompatManager; import top.r3944realms.lib39.core.compat.ICompatManager;
import top.r3944realms.lib39.example.core.compat.FabricLib39Compat; import top.r3944realms.lib39.example.core.compat.FabricLib39Compat;
import top.r3944realms.lib39.example.core.event.FabricExCommonEventHandler; import top.r3944realms.lib39.example.core.event.FabricExCommonEventHandler;
import top.r3944realms.lib39.example.core.network.FabricExNetworkHandler; import top.r3944realms.lib39.example.core.network.FabricExNetworkHandler;
@ -29,7 +29,7 @@ public class FabricLib39Example {
FabricExCommonEventHandler.init(); FabricExCommonEventHandler.init();
FabricExLib39Items.init(); FabricExLib39Items.init();
FabricExNetworkHandler.registerServerReceivers(); FabricExNetworkHandler.registerServerReceivers();
CompatManager orCreateCompatManager = FabricExCommonEventHandler.getOrCreateCompatManager(); ICompatManager orCreateCompatManager = FabricExCommonEventHandler.getOrCreateCompatManager();
orCreateCompatManager.registerCompat(FabricLib39Compat.ID, FabricLib39Compat.INSTANCE); orCreateCompatManager.registerCompat(FabricLib39Compat.ID, FabricLib39Compat.INSTANCE);
} }

View File

@ -1,12 +1,19 @@
package top.r3944realms.lib39.example.core.compat; package top.r3944realms.lib39.example.core.compat;
import net.minecraft.resources.ResourceLocation;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.core.compat.CompatManager; import top.r3944realms.lib39.core.compat.CompatManager;
import top.r3944realms.lib39.core.compat.ICompat;
import top.r3944realms.lib39.core.compat.SimpleCompatManager;
import java.util.HashMap;
import java.util.Map;
/** /**
* The type Fabric lib 39 compat manager. * The type Fabric lib 39 compat manager.
*/ */
public class FabricLib39CompatManager extends CompatManager { public class FabricLib39CompatManager extends SimpleCompatManager {
/** /**
* Instantiates a new Compat manager. * Instantiates a new Compat manager.
* *

View File

@ -4,7 +4,7 @@ import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.LivingEntity;
import top.r3944realms.lib39.api.callback.ActionResult; import top.r3944realms.lib39.api.callback.ActionResult;
import top.r3944realms.lib39.api.callback.SyncManagerRegisterCallback; import top.r3944realms.lib39.api.callback.SyncManagerRegisterCallback;
import top.r3944realms.lib39.core.compat.CompatManager; import top.r3944realms.lib39.core.compat.ICompatManager;
import top.r3944realms.lib39.core.event.FabricCommonEventHandler; import top.r3944realms.lib39.core.event.FabricCommonEventHandler;
import top.r3944realms.lib39.core.sync.CachedSyncManager; import top.r3944realms.lib39.core.sync.CachedSyncManager;
import top.r3944realms.lib39.example.content.data.AbstractedTestSyncData; import top.r3944realms.lib39.example.content.data.AbstractedTestSyncData;
@ -23,7 +23,7 @@ public class FabricExCommonEventHandler {
* *
* @return the compat manager * @return the compat manager
*/ */
public static CompatManager getOrCreateCompatManager() { public static ICompatManager getOrCreateCompatManager() {
if (compatManager == null) { if (compatManager == null) {
synchronized (FabricCommonEventHandler.class) { synchronized (FabricCommonEventHandler.class) {
if (compatManager == null) { if (compatManager == null) {
@ -37,7 +37,7 @@ public class FabricExCommonEventHandler {
/** /**
* The Compat manager. * The Compat manager.
*/ */
static volatile CompatManager compatManager; static volatile ICompatManager compatManager;
/** /**
* Init. * Init.

View File

@ -1,9 +1,9 @@
package top.r3944realms.lib39.example.core.network; package top.r3944realms.lib39.example.core.network;
import net.fabricmc.fabric.api.networking.v1.FabricPacket; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.minecraft.network.RegistryFriendlyByteBuf;
import net.fabricmc.fabric.api.networking.v1.PacketType; import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -15,63 +15,56 @@ import top.r3944realms.lib39.example.content.item.FabricFabricItem;
/** /**
* The type Client data packet. * The type Client data packet.
*/ */
public class FabricClientDataPacket implements FabricPacket { public record FabricClientDataPacket(AbstractedTestSyncData clientData, int targetEntityId) implements CustomPacketPayload {
/** /**
* The constant CLIENT_TEST_DATA. * The constant CLIENT_TEST_DATA.
*/ */
public static final ResourceLocation CLIENT_TEST_DATA = public static final ResourceLocation CLIENT_TEST_DATA =
Lib39.rl("client_test_data"); Lib39.rl("client_test_data");
/** /**
* The constant TYPE. * The constant TYPE.
*/ */
public static final PacketType<FabricClientDataPacket> TYPE = PacketType.create( public static final CustomPacketPayload.Type<FabricClientDataPacket> TYPE =
CLIENT_TEST_DATA, new CustomPacketPayload.Type<>(CLIENT_TEST_DATA);
FabricClientDataPacket::new
);
private final AbstractedTestSyncData clientData;
private final int targetEntityId;
/** /**
* Instantiates a new Client data packet. * Stream codec for serializing/deserializing the packet.
*
* @param clientData the client data
* @param targetEntityId the target entity id
*/ */
public FabricClientDataPacket(AbstractedTestSyncData clientData, int targetEntityId) { public static final StreamCodec<RegistryFriendlyByteBuf, FabricClientDataPacket> STREAM_CODEC =
this.clientData = clientData; StreamCodec.ofMember(FabricClientDataPacket::write, FabricClientDataPacket::new);
this.targetEntityId = targetEntityId;
/**
* Instantiates a new Client data packet from buffer.
*
* @param buf the buffer
*/
public FabricClientDataPacket(RegistryFriendlyByteBuf buf) {
this(FabricTestSyncData.staticFromBytes(buf), buf.readInt());
} }
/** /**
* Instantiates a new Client data packet. * Write packet data to buffer.
* *
* @param buf the buf * @param buf the buffer
*/ */
public FabricClientDataPacket(FriendlyByteBuf buf) { public void write(RegistryFriendlyByteBuf buf) {
this.clientData = FabricTestSyncData.staticFromBytes(buf);
this.targetEntityId = buf.readInt();
}
@Override
public void write(FriendlyByteBuf buf) {
clientData.toBytes(buf); clientData.toBytes(buf);
buf.writeInt(targetEntityId); buf.writeInt(targetEntityId);
} }
@Override @Override
public PacketType<?> getType() { public @NotNull Type<? extends CustomPacketPayload> type() {
return TYPE; return TYPE;
} }
/** /**
* Receive. * Handle packet on server side.
* * Register this with ServerPlayNetworking.registerGlobalReceiver
* @param packet the packet
* @param serverPlayer the server player
* @param packetSender the packet sender
*/ */
public static void receive(@NotNull FabricClientDataPacket packet, @NotNull ServerPlayer serverPlayer, PacketSender packetSender) { public static void handle(FabricClientDataPacket packet, ServerPlayNetworking.Context context) {
ServerPlayer serverPlayer = context.player();
// PacketSender is no longer needed, use context.responseSender() if needed
FabricFabricItem.handleClientDataFromPacket(serverPlayer, packet.clientData, packet.targetEntityId); FabricFabricItem.handleClientDataFromPacket(serverPlayer, packet.clientData, packet.targetEntityId);
} }
} }

View File

@ -12,7 +12,7 @@ public class FabricExNetworkHandler {
public static void registerServerReceivers() { public static void registerServerReceivers() {
ServerPlayNetworking.registerGlobalReceiver( ServerPlayNetworking.registerGlobalReceiver(
FabricClientDataPacket.TYPE, FabricClientDataPacket.TYPE,
FabricClientDataPacket::receive FabricClientDataPacket::handle
); );
} }
} }

View File

@ -5,12 +5,15 @@ import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.sugar.Local; import com.llamalad7.mixinextras.sugar.Local;
import com.mojang.blaze3d.platform.WindowEventHandler; import com.mojang.blaze3d.platform.WindowEventHandler;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.ReceivingLevelScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.server.Services; import net.minecraft.server.Services;
import net.minecraft.server.WorldStem; import net.minecraft.server.WorldStem;
import net.minecraft.server.packs.repository.PackRepository; import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.util.thread.ReentrantBlockableEventLoop; import net.minecraft.util.thread.ReentrantBlockableEventLoop;
import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.LevelStorageSource;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
@ -19,8 +22,6 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import top.r3944realms.lib39.api.callback.MinecraftSetUpServiceCallback; import top.r3944realms.lib39.api.callback.MinecraftSetUpServiceCallback;
import top.r3944realms.lib39.api.callback.client.ClientWorldCallback; import top.r3944realms.lib39.api.callback.client.ClientWorldCallback;
import javax.annotation.Nullable;
/** /**
* The type Mixin minecraft. * The type Mixin minecraft.
*/ */
@ -29,7 +30,8 @@ public abstract class MixinMinecraft extends ReentrantBlockableEventLoop<Runnabl
/** /**
* The Level. * The Level.
*/ */
@Shadow @Nullable public ClientLevel level; @Shadow @Nullable
public ClientLevel level;
/** /**
* Instantiates a new Mixin minecraft. * Instantiates a new Mixin minecraft.
@ -41,15 +43,15 @@ public abstract class MixinMinecraft extends ReentrantBlockableEventLoop<Runnabl
} }
/** /**
* Set level callback. * Set clientLevel callback.
* *
* @param levelClient the level client * @param clientLevel the clientLevel client
* @param original the original * @param original the original
*/ */
@WrapMethod(method = "setLevel") @WrapMethod(method = "setLevel")
public void setLevel$callback(ClientLevel levelClient, Operation<Void> original) { public void setLevel$callback(ClientLevel clientLevel, ReceivingLevelScreen.Reason reason, Operation<Void> original) {
if (levelClient != null) ClientWorldCallback.UNLOAD.invoker().onWorldUnload(levelClient); if (clientLevel != null) ClientWorldCallback.UNLOAD.invoker().onWorldUnload(clientLevel);
original.call(levelClient); original.call(clientLevel, reason);
} }
/** /**
@ -57,16 +59,16 @@ public abstract class MixinMinecraft extends ReentrantBlockableEventLoop<Runnabl
* *
* @param original the original * @param original the original
*/ */
@WrapMethod(method = "clearLevel()V") @WrapMethod(method = "clearClientLevel")
public void clearLevel$callback(Operation<Void> original) { public void clearLevel$callback(Screen nextScreen, Operation<Void> original) {
if (level != null) ClientWorldCallback.UNLOAD.invoker().onWorldUnload(level); if (level != null) ClientWorldCallback.UNLOAD.invoker().onWorldUnload(level);
original.call(); original.call(nextScreen);
} }
/** /**
* Set level setup. * Set level setup.
* *
* @param levelClient the level client * @param level the level client
* @param ci the ci * @param ci the ci
* @param services the services * @param services the services
*/ */
@ -78,16 +80,14 @@ public abstract class MixinMinecraft extends ReentrantBlockableEventLoop<Runnabl
shift = At.Shift.AFTER shift = At.Shift.AFTER
) )
) )
public void setLevel$setup(ClientLevel levelClient, CallbackInfo ci, public void setLevel$setup(ClientLevel level, ReceivingLevelScreen.Reason reason, CallbackInfo ci, @Local(ordinal = 0) Services services) {
@Local(ordinal = 0) Services services) {
MinecraftSetUpServiceCallback.EVENT.invoker().load(services,this); MinecraftSetUpServiceCallback.EVENT.invoker().load(services,this);
} }
/** /**
* Do world load setup. * Do world load setup.
* *
* @param levelId the level id * @param levelStorage the level id
* @param level the level
* @param packRepository the pack repository * @param packRepository the pack repository
* @param worldStem the world stem * @param worldStem the world stem
* @param newWorld the new world * @param newWorld the new world
@ -102,8 +102,7 @@ public abstract class MixinMinecraft extends ReentrantBlockableEventLoop<Runnabl
shift = At.Shift.AFTER shift = At.Shift.AFTER
) )
) )
public void doWorldLoad$setup(String levelId, LevelStorageSource.LevelStorageAccess level, PackRepository packRepository, WorldStem worldStem, boolean newWorld, CallbackInfo ci, public void doWorldLoad$setup(LevelStorageSource.LevelStorageAccess levelStorage, PackRepository packRepository, WorldStem worldStem, boolean newWorld, CallbackInfo ci, @Local(ordinal = 0) Services services) {
@Local(ordinal = 0) Services services) {
MinecraftSetUpServiceCallback.EVENT.invoker().load(services,this); MinecraftSetUpServiceCallback.EVENT.invoker().load(services,this);
} }
} }

View File

@ -8,8 +8,8 @@
"${mod_author}" "${mod_author}"
], ],
"contact": { "contact": {
"homepage": "https://github.com/3944Realms", "homepage": "https://gitea.bot.leisuretimedock.top/3944Realms",
"sources": "https://github.com/3944Realms/Lib39" "sources": "https://gitea.bot.leisuretimedock.top/3944Realms/Lib39"
}, },
"license": "${license}", "license": "${license}",
"icon": "lib39_logo.png", "icon": "lib39_logo.png",

View File

@ -2,19 +2,19 @@
"required": true, "required": true,
"minVersion": "0.8", "minVersion": "0.8",
"package": "top.r3944realms.lib39.mixin", "package": "top.r3944realms.lib39.mixin",
"refmap": "${mod_id}.fabric.refmap.json", "refmap": "${mod_id}.refmap.json",
"compatibilityLevel": "JAVA_17", "compatibilityLevel": "JAVA_18",
"mixins": [ "mixins": [
"MixinApiLookUpImpl", "MixinApiLookUpImpl",
"MixinEntity", "MixinEntity",
"callback.MixinAnvilMenu", "callback.MixinAnvilMenu"
"callback.MixinDedicateServer"
], ],
"client": [ "client": [
"callback.MixinMinecraft", "callback.MixinMinecraft",
"callback.client.MixinClientLevel" "callback.client.MixinClientLevel"
], ],
"server": [ "server": [
"callback.MixinDedicateServer"
], ],
"injectors": { "injectors": {
"defaultRequire": 1 "defaultRequire": 1

View File

@ -1,60 +0,0 @@
package top.r3944realms.lib39;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import top.r3944realms.lib39.core.network.NetworkHandler;
import top.r3944realms.lib39.core.register.ForgeLib39BlockEntities;
import top.r3944realms.lib39.core.register.ForgeLib39Blocks;
import top.r3944realms.lib39.core.register.ForgeLib39Items;
import top.r3944realms.lib39.core.register.ForgeLib39SoundEvents;
import top.r3944realms.lib39.example.ForgeLib39Example;
/**
* The type Lib 39.
*/
@Mod(Lib39.MOD_ID)
public class Lib39Forge {
/**
* Instantiates a new Lib 39.
*/
public Lib39Forge() {
Lib39.initialize();
initialize();
}
/**
* Initialize.
*/
public static void initialize() {
Lib39.LOGGER.info("[Lib39-Forge] Hello Forge");
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
ForgeLib39Blocks.register(modEventBus);
ForgeLib39Items.register(modEventBus);
ForgeLib39BlockEntities.register(modEventBus);
ForgeLib39SoundEvents.register(modEventBus);
NetworkHandler.register();
if (Lib39.shouldRegisterExamples()) {
Lib39.LOGGER.info("[Lib39-Forge] Registering Examples");
registerExamples();
}
Lib39.LOGGER.info("[Lib39-Forge] Finished Initializing.");
}
/**
* Register examples.
*/
static void registerExamples() {
Lib39.LOGGER.info("[Lib39-Forge] Starting example demonstrations");
try {
// 创建示例实例并演示功能
ForgeLib39Example example = new ForgeLib39Example();
example.demonstrateFeature();
Lib39.LOGGER.info("[Lib39-Forge] Example demonstrations completed successfully");
} catch (Exception e) {
Lib39.LOGGER.error("[Lib39-Forge] Failed to demonstrate examples", e);
}
}
}

View File

@ -1,32 +0,0 @@
package top.r3944realms.lib39.content.item;
import net.minecraft.client.renderer.BlockEntityWithoutLevelRenderer;
import net.minecraftforge.client.extensions.common.IClientItemExtensions;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.lib39.client.renderer.item.DollItemRenderer;
import java.util.function.Consumer;
/**
* The type Forge doll item.
*/
public class ForgeDollItem extends DollItem {
/**
* Instantiates a new Forge doll item.
*
* @param properties the properties
*/
public ForgeDollItem(Properties properties) {
super(properties);
}
@Override
public void initializeClient(@NotNull Consumer<IClientItemExtensions> consumer) {
consumer.accept(new IClientItemExtensions() {
@Override
public BlockEntityWithoutLevelRenderer getCustomRenderer() {
return DollItemRenderer.getInstance();
}
});
}
}

View File

@ -1 +0,0 @@
top.r3944realms.lib39.platform.ForgePlatformHelper

View File

@ -3,12 +3,12 @@
# Every field you add must be added to buildSrc/src/main/groovy/multiloader-common.gradle expandProps map. # Every field you add must be added to buildSrc/src/main/groovy/multiloader-common.gradle expandProps map.
# Project # Project
version=0.5.5 version=0.5.6
group=top.r3944realms.lib39 group=top.r3944realms.lib39
java_version=17 java_version=21
# Common # Common
minecraft_version=1.20.1 minecraft_version=1.21.1
mod_name=3944Realms 's Lib Mod mod_name=3944Realms 's Lib Mod
mod_author=R3944Realms mod_author=R3944Realms
mod_id=lib39 mod_id=lib39
@ -17,17 +17,18 @@ credits=Logo created by Shanyi43, edited by R3944Realms
description=Lib39 is a general-purpose dependency library that provides utility methods and core functionality for other mods. description=Lib39 is a general-purpose dependency library that provides utility methods and core functionality for other mods.
minecraft_version_range=[1.20.1, 1.22) minecraft_version_range=[1.20.1, 1.22)
# The version of ParchmentMC that is used, see https://parchmentmc.org/docs/getting-started#choose-a-version for new versions # The version of ParchmentMC that is used, see https://parchmentmc.org/docs/getting-started#choose-a-version for new versions
parchment_minecraft=1.20.1 parchment_minecraft=1.21
parchment_version=2023.09.03 parchment_version=2024.11.10
neo_form_version=1.21.1-20240808.144430
# NeoForge
neoforge_version=21.1.80
neoforge_loader_version_range=[4,)
# Fabric # Fabric
fabric_version=0.92.1+1.20.1 fabric_version=0.109.0+1.21.1
fabric_loader_version=0.16.9 fabric_loader_version=0.16.9
# Forge
forge_version=47.2.30
forge_loader_version_range=[47,)
# Gradle # Gradle
org.gradle.jvmargs=-Xmx3G org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false org.gradle.daemon=false
@ -40,9 +41,9 @@ publish_curseforge=true
modrinth_id=n65Vs1Vk modrinth_id=n65Vs1Vk
curseforge_id=1445917 curseforge_id=1445917
java_versions=21 17 java_versions=21
fabric_modrinth_dependencies= fabric_modrinth_dependencies=
forge_modrinth_dependencies= neoforge_modrinth_dependencies=
fabric_curseforge_dependencies= fabric_curseforge_dependencies=
forge_curseforge_dependencies= neoforge_curseforge_dependencies=

View File

@ -1,13 +1,6 @@
plugins { plugins {
id 'multiloader-loader' id 'multiloader-loader'
id 'net.neoforged.moddev.legacyforge' id 'net.neoforged.moddev'
}
mixin {
add(sourceSets.main, "${mod_id}.refmap.json")
config("${mod_id}.mixins.json")
config("${mod_id}.forge.mixins.json")
} }
def commonResources = project(':common').file('src/main/resources/').getAbsolutePath() def commonResources = project(':common').file('src/main/resources/').getAbsolutePath()
@ -16,8 +9,8 @@ def forgeBuildResources = file('build/resources/main/').getAbsolutePath()
def commonBuildResources = project(':common').file('build/resources/main/').getAbsolutePath() def commonBuildResources = project(':common').file('build/resources/main/').getAbsolutePath()
def generatedOutput = project(':common').file('src/generated/resources/').getAbsolutePath() def generatedOutput = project(':common').file('src/generated/resources/').getAbsolutePath()
legacyForge { neoForge {
version = "${minecraft_version}-${forge_version}" version = neoforge_version
validateAccessTransformers = true validateAccessTransformers = true
@ -74,20 +67,13 @@ dependencies {
compileOnly project(":common") compileOnly project(":common")
annotationProcessor("org.spongepowered:mixin:0.8.5-SNAPSHOT:processor") annotationProcessor("org.spongepowered:mixin:0.8.5-SNAPSHOT:processor")
implementation(annotationProcessor("io.github.llamalad7:mixinextras-common:0.2.0")) implementation(annotationProcessor("io.github.llamalad7:mixinextras-common:0.2.0"))
modImplementation(group: 'tschipp.carryon', name: 'carryon-forge-1.20.1', version: '2.1.2.7') { implementation(group: 'tschipp.carryon', name: 'carryon-neoforge-1.21.1', version: '2.2.4.4') {
transitive = false transitive = false
} }
modImplementation ("curse.maven:jade-324717:6855440") implementation "curse.maven:jade-324717:7545219"
implementation(jarJar("io.github.llamalad7:mixinextras-forge:0.2.0")) implementation(jarJar("io.github.llamalad7:mixinextras-forge:0.2.0"))
} }
jar {
finalizedBy('reobfJar')
manifest.attributes([
"MixinConfigs": "${mod_id}.mixins.json,${mod_id}.forge.mixins.json"
])
}
// sourceJar任务 // sourceJar任务
tasks.named('sourcesJar', Jar) { tasks.named('sourcesJar', Jar) {
dependsOn classes dependsOn classes
@ -106,7 +92,7 @@ tasks.named('javadoc', Javadoc) {
classpath += project(':common').sourceSets.main.compileClasspath classpath += project(':common').sourceSets.main.compileClasspath
options.encoding = 'UTF-8' options.encoding = 'UTF-8'
options.charSet = 'UTF-8' options.charSet = 'UTF-8'
options.links("https://docs.oracle.com/en/java/javase/17/docs/api/") options.links("https://docs.oracle.com/en/java/javase/21/docs/api/")
options.memberLevel = JavadocMemberLevel.PUBLIC options.memberLevel = JavadocMemberLevel.PUBLIC
options.addBooleanOption('Xdoclint:none', true) options.addBooleanOption('Xdoclint:none', true)
options.addStringOption('doctitle', "${mod_id} ${minecraft_version} ${version} Javadoc") options.addStringOption('doctitle', "${mod_id} ${minecraft_version} ${version} Javadoc")
@ -129,72 +115,6 @@ tasks.named('build') {
dependsOn tasks.named('javadocJar') dependsOn tasks.named('javadocJar')
} }
// reobf
tasks.named('reobfJar') {
dependsOn tasks.named('sourcesJar')
dependsOn tasks.named('javadocJar')
}
//
publishing {
publications {
mavenJava(MavenPublication) {
artifactId = "${mod_id}-forge-${minecraft_version}"
artifacts.clear()
artifact(tasks.named('reobfJar').get()) {
builtBy tasks.named('reobfJar')
}
artifact(tasks.named('sourcesJar').get()) {
builtBy tasks.named('sourcesJar')
classifier = 'sources'
}
artifact(tasks.named('javadocJar').get()) {
builtBy tasks.named('javadocJar')
classifier = 'javadoc'
}
pom {
name = 'Lib39'
description = 'Lib39 is a general-purpose dependency library for Minecraft mods.'
url = 'https://github.com/3944Realms/lib39'
properties = [
'minecraft.version': project.minecraft_version,
'mod.version': project.version,
'forge.version': project.forge_version,
'java.version': '17'
]
licenses {
license {
name = 'MIT'
url = 'https://raw.githubusercontent.com/3944Realms/lib39/refs/heads/main/LICENSE'
distribution = 'repo'
}
}
developers {
developer {
id = 'R3944Realms'
name = "${mod_author}"
email = 'f256198830@hotmail.com'
}
}
scm {
connection = 'scm:git:https://github.com/3944Realms/lib39.git'
developerConnection = 'scm:git:ssh://git@github.com:3944Realms/lib39.git'
url = 'https://github.com/3944Realms/lib39'
tag = 'main'
}
issueManagement {
system = 'GitHub'
url = 'https://github.com/3944Realms/lib39/issues'
}
}
}
}
}
test { test {
useJUnitPlatform() useJUnitPlatform()
} }
@ -205,21 +125,23 @@ processResources {
inputs.property "version", project.version inputs.property "version", project.version
inputs.property "minecraft_version", minecraft_version inputs.property "minecraft_version", minecraft_version
inputs.property "forge_version", forge_version inputs.property "neoforge_version", neoforge_version
inputs.property "mod_id", mod_id inputs.property "mod_id", mod_id
inputs.property "mod_name", mod_name inputs.property "mod_name", mod_name
inputs.property "description", description inputs.property "description", description
inputs.property "mod_author", mod_author inputs.property "mod_author", mod_author
inputs.property "credits", credits
filesMatching(['META-INF/mods.toml', 'pack.mcmeta', "*.mixins.json"]) { filesMatching(['META-INF/mods.toml', 'pack.mcmeta', "*.mixins.json"]) {
expand([ expand([
version: project.version, version: project.version,
minecraft_version: minecraft_version, minecraft_version: minecraft_version,
forge_version: forge_version, neoforge_version: neoforge_version,
mod_id: mod_id, mod_id: mod_id,
mod_name: mod_name, mod_name: mod_name,
description: description, description: description,
mod_author: mod_author mod_author: mod_author,
"credits": credits
]) ])
} }
duplicatesStrategy = DuplicatesStrategy.EXCLUDE duplicatesStrategy = DuplicatesStrategy.EXCLUDE

View File

@ -0,0 +1,62 @@
package top.r3944realms.lib39;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.common.Mod;
import top.r3944realms.lib39.core.network.NetworkHandler;
import top.r3944realms.lib39.core.register.NeoForgeLib39BlockEntities;
import top.r3944realms.lib39.core.register.NeoForgeLib39Blocks;
import top.r3944realms.lib39.core.register.NeoForgeLib39Items;
import top.r3944realms.lib39.core.register.NeoForgeLib39SoundEvents;
import top.r3944realms.lib39.example.NeoForgeLib39Example;
/**
* The type Lib 39.
*/
@Mod(Lib39.MOD_ID)
public class Lib39NeoForge {
public static IEventBus modEventBus;
/**
* Instantiates a new Lib 39.
*/
public Lib39NeoForge(IEventBus modEventBus) {
Lib39.initialize();
if(this.modEventBus == null) {
this.modEventBus = modEventBus;
}
initialize(modEventBus);
}
/**
* Initialize.
*/
public static void initialize(IEventBus modEventBus) {
Lib39.LOGGER.info("[Lib39-Forge] Hello Forge");
NeoForgeLib39Blocks.register(modEventBus);
NeoForgeLib39Items.register(modEventBus);
NeoForgeLib39BlockEntities.register(modEventBus);
NeoForgeLib39SoundEvents.register(modEventBus);
NetworkHandler.register();
if (Lib39.shouldRegisterExamples()) {
Lib39.LOGGER.info("[Lib39-Forge] Registering Examples");
registerExamples(modEventBus);
}
Lib39.LOGGER.info("[Lib39-Forge] Finished Initializing.");
}
/**
* Register examples.
*/
static void registerExamples(IEventBus modEventBus) {
Lib39.LOGGER.info("[Lib39-Forge] Starting example demonstrations");
try {
// 创建示例实例并演示功能
NeoForgeLib39Example example = new NeoForgeLib39Example(modEventBus);
example.demonstrateFeature();
Lib39.LOGGER.info("[Lib39-Forge] Example demonstrations completed successfully");
} catch (Exception e) {
Lib39.LOGGER.error("[Lib39-Forge] Failed to demonstrate examples", e);
}
}
}

View File

@ -1,7 +1,7 @@
package top.r3944realms.lib39.api.event; package top.r3944realms.lib39.api.event;
import net.minecraft.server.Services; import net.minecraft.server.Services;
import net.minecraftforge.eventbus.api.Event; import net.neoforged.bus.api.Event;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;

View File

@ -5,7 +5,7 @@ import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.MutableComponent;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.eventbus.api.Event; import net.neoforged.bus.api.Event;
import top.r3944realms.lib39.core.command.ICommandHelpManager; import top.r3944realms.lib39.core.command.ICommandHelpManager;
import top.r3944realms.lib39.core.command.model.CommandNode; import top.r3944realms.lib39.core.command.model.CommandNode;
import top.r3944realms.lib39.core.command.model.CommandPath; import top.r3944realms.lib39.core.command.model.CommandPath;

View File

@ -1,8 +1,7 @@
package top.r3944realms.lib39.api.event; package top.r3944realms.lib39.api.event;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.capabilities.Capability; import net.neoforged.bus.api.Event;
import net.minecraftforge.eventbus.api.Event;
import top.r3944realms.lib39.core.sync.ISyncData; import top.r3944realms.lib39.core.sync.ISyncData;
import top.r3944realms.lib39.core.sync.ISyncManager; import top.r3944realms.lib39.core.sync.ISyncManager;
import top.r3944realms.lib39.core.sync.SyncData2CapManager; import top.r3944realms.lib39.core.sync.SyncData2CapManager;

View File

@ -1,25 +1,26 @@
package top.r3944realms.lib39.base.compat.jade; package top.r3944realms.lib39.base.compat.jade;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
import snownee.jade.api.IWailaClientRegistration; import snownee.jade.api.IWailaClientRegistration;
import snownee.jade.api.IWailaPlugin; import snownee.jade.api.IWailaPlugin;
import snownee.jade.api.WailaPlugin; import snownee.jade.api.WailaPlugin;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.base.compat.jade.provider.ForgeDollComponentProvider; import top.r3944realms.lib39.base.compat.jade.provider.NeoForgeDollComponentProvider;
import top.r3944realms.lib39.content.block.DollBlock; import top.r3944realms.lib39.content.block.AbstractDollBlock;
/** /**
* The type Forge jade plugin. * The type Forge jade plugin.
*/ */
@WailaPlugin @WailaPlugin
public class ForgeJadePlugin implements IWailaPlugin { public class NeoForgeJadePlugin implements IWailaPlugin {
/** /**
* The constant UID. * The constant UID.
*/ */
public static final ResourceLocation UID = Lib39.rl("lib39"); public static final ResourceLocation UID = Lib39.rl("lib39");
@Override @Override
public void registerClient(IWailaClientRegistration registration) { public void registerClient(@NotNull IWailaClientRegistration registration) {
registration.registerBlockComponent(new ForgeDollComponentProvider(), DollBlock.class); registration.registerBlockComponent(new NeoForgeDollComponentProvider(), AbstractDollBlock.class);
} }
} }

View File

@ -3,25 +3,26 @@ package top.r3944realms.lib39.base.compat.jade.provider;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
import snownee.jade.api.BlockAccessor; import snownee.jade.api.BlockAccessor;
import snownee.jade.api.IBlockComponentProvider; import snownee.jade.api.IBlockComponentProvider;
import snownee.jade.api.ITooltip; import snownee.jade.api.ITooltip;
import snownee.jade.api.config.IPluginConfig; import snownee.jade.api.config.IPluginConfig;
import top.r3944realms.lib39.base.compat.jade.ForgeJadePlugin; import top.r3944realms.lib39.base.compat.jade.NeoForgeJadePlugin;
import top.r3944realms.lib39.content.block.blockentity.DollBlockEntity; import top.r3944realms.lib39.content.block.blockentity.DollBlockEntity;
/** /**
* The type Forge doll component provider. * The type Forge doll component provider.
*/ */
public class ForgeDollComponentProvider implements IBlockComponentProvider { public class NeoForgeDollComponentProvider implements IBlockComponentProvider {
@Override @Override
public ResourceLocation getUid() { public ResourceLocation getUid() {
return ForgeJadePlugin.UID; return NeoForgeJadePlugin.UID;
} }
@Override @Override
public void appendTooltip(ITooltip iTooltip, BlockAccessor blockAccessor, IPluginConfig iPluginConfig) { public void appendTooltip(ITooltip iTooltip, @NotNull BlockAccessor blockAccessor, IPluginConfig iPluginConfig) {
if (blockAccessor.getBlockEntity() instanceof DollBlockEntity doll) { if (blockAccessor.getBlockEntity() instanceof DollBlockEntity doll) {
GameProfile ownerProfile = doll.getOwnerProfile(); GameProfile ownerProfile = doll.getOwnerProfile();
if (ownerProfile != null) { if (ownerProfile != null) {

View File

@ -1,7 +1,7 @@
package top.r3944realms.lib39.base.datagen; package top.r3944realms.lib39.base.datagen;
import net.minecraft.data.DataProvider; import net.minecraft.data.DataProvider;
import net.minecraftforge.data.event.GatherDataEvent; import net.neoforged.neoforge.data.event.GatherDataEvent;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -79,7 +79,7 @@ public class Lib39BaseDataGenEvent {
private static void RecipeGenerator(@NotNull GatherDataEvent event) { private static void RecipeGenerator(@NotNull GatherDataEvent event) {
event.getGenerator().addProvider( event.getGenerator().addProvider(
event.includeServer(), event.includeServer(),
(DataProvider.Factory<Lib39RecipeProvider>) Lib39RecipeProvider::new (DataProvider.Factory<Lib39RecipeProvider>)pOutput -> new Lib39RecipeProvider(pOutput, event.getLookupProvider())
); );
} }
} }

View File

@ -1,6 +1,6 @@
package top.r3944realms.lib39.base.datagen.provider; package top.r3944realms.lib39.base.datagen.provider;
import top.r3944realms.lib39.core.register.ForgeLib39Blocks; import top.r3944realms.lib39.core.register.NeoForgeLib39Blocks;
import top.r3944realms.lib39.core.register.Lib39Blocks; import top.r3944realms.lib39.core.register.Lib39Blocks;
import top.r3944realms.lib39.datagen.provider.subprovider.BlockLootTables; import top.r3944realms.lib39.datagen.provider.subprovider.BlockLootTables;
@ -12,7 +12,7 @@ public class Lib39BlockLootTable extends BlockLootTables {
* Instantiates a new Lib 39 block loot table. * Instantiates a new Lib 39 block loot table.
*/ */
public Lib39BlockLootTable() { public Lib39BlockLootTable() {
super(ForgeLib39Blocks.BLOCKS); super(NeoForgeLib39Blocks.BLOCKS);
dropSelf(Lib39Blocks.DOLL, Lib39Blocks.WALL_DOLL); dropSelf(Lib39Blocks.DOLL, Lib39Blocks.WALL_DOLL);
} }
} }

View File

@ -2,8 +2,8 @@ package top.r3944realms.lib39.base.datagen.provider;
import net.minecraft.data.PackOutput; import net.minecraft.data.PackOutput;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.model.generators.BlockModelProvider; import net.neoforged.neoforge.client.model.generators.BlockModelProvider;
import net.minecraftforge.common.data.ExistingFileHelper; import net.neoforged.neoforge.common.data.ExistingFileHelper;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.util.PlantHelper; import top.r3944realms.lib39.util.PlantHelper;

View File

@ -3,10 +3,10 @@ package top.r3944realms.lib39.base.datagen.provider;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.data.PackOutput; import net.minecraft.data.PackOutput;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraftforge.client.model.generators.BlockStateProvider; import net.neoforged.neoforge.client.model.generators.BlockStateProvider;
import net.minecraftforge.client.model.generators.ConfiguredModel; import net.neoforged.neoforge.client.model.generators.ConfiguredModel;
import net.minecraftforge.client.model.generators.ModelFile; import net.neoforged.neoforge.client.model.generators.ModelFile;
import net.minecraftforge.common.data.ExistingFileHelper; import net.neoforged.neoforge.common.data.ExistingFileHelper;
import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;

View File

@ -15,11 +15,12 @@
package top.r3944realms.lib39.base.datagen.provider; package top.r3944realms.lib39.base.datagen.provider;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.data.PackOutput; import net.minecraft.data.PackOutput;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraftforge.common.data.ExistingFileHelper; import net.neoforged.neoforge.client.model.generators.ItemModelProvider;
import net.minecraftforge.registries.ForgeRegistries; import net.neoforged.neoforge.common.data.ExistingFileHelper;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.base.datagen.value.Lib39LangKey; import top.r3944realms.lib39.base.datagen.value.Lib39LangKey;
import top.r3944realms.lib39.datagen.value.LangKeyValue; import top.r3944realms.lib39.datagen.value.LangKeyValue;
@ -32,7 +33,7 @@ import java.util.Objects;
/** /**
* The type item model provider. * The type item model provider.
*/ */
public class Lib39ItemModelProvider extends net.minecraftforge.client.model.generators.ItemModelProvider { public class Lib39ItemModelProvider extends ItemModelProvider {
private static List<Item> objectList; private static List<Item> objectList;
/** /**
* The constant GENERATED. * The constant GENERATED.
@ -108,7 +109,7 @@ public class Lib39ItemModelProvider extends net.minecraftforge.client.model.gene
* @return the string * @return the string
*/ */
public String itemName(Item item){ public String itemName(Item item){
return Objects.requireNonNull(ForgeRegistries.ITEMS.getKey(item)).getPath(); return Objects.requireNonNull(BuiltInRegistries.ITEM.getKey(item)).getPath();
} }
/** /**

View File

@ -1,9 +1,9 @@
package top.r3944realms.lib39.base.datagen.provider; package top.r3944realms.lib39.base.datagen.provider;
import net.minecraft.data.PackOutput; import net.minecraft.data.PackOutput;
import net.minecraftforge.common.data.ExistingFileHelper; import net.neoforged.neoforge.common.data.ExistingFileHelper;
import net.minecraftforge.common.data.SoundDefinition; import net.neoforged.neoforge.common.data.SoundDefinition;
import net.minecraftforge.common.data.SoundDefinitionsProvider; import net.neoforged.neoforge.common.data.SoundDefinitionsProvider;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.core.register.Lib39SoundEvents; import top.r3944realms.lib39.core.register.Lib39SoundEvents;

View File

@ -0,0 +1,32 @@
package top.r3944realms.lib39.content.item;
import net.minecraft.client.renderer.BlockEntityWithoutLevelRenderer;
import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions;
import top.r3944realms.lib39.client.renderer.item.DollItemRenderer;
import top.r3944realms.lib39.util.IClientOnly;
/**
* The type Forge doll item.
*/
public class NeoForgeDollItem extends DollItem {
/**
* Instantiates a new Forge doll item.
*
* @param properties the properties
*/
public NeoForgeDollItem(Properties properties) {
super(properties);
}
public static class ClientOpt implements IClientOnly {
public static IClientItemExtensions getExtensions() {
return IClientOnly.check(() -> new IClientItemExtensions() {
@Override
public BlockEntityWithoutLevelRenderer getCustomRenderer() {
return DollItemRenderer.getInstance();
}
});
}
}
}

View File

@ -1,11 +1,12 @@
package top.r3944realms.lib39.core.compat; package top.r3944realms.lib39.core.compat;
import net.minecraftforge.eventbus.api.IEventBus;
import net.neoforged.bus.api.IEventBus;
/** /**
* The interface Compat. * The interface Compat.
*/ */
public interface IForgeCompat extends ICompat { public interface INeoForgeCompat extends ICompat {
/** /**
* Add common game listener. * Add common game listener.
* *

View File

@ -1,10 +1,10 @@
package top.r3944realms.lib39.core.compat; package top.r3944realms.lib39.core.compat;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist; import net.neoforged.api.distmarker.Dist;
import net.minecraftforge.eventbus.api.IEventBus; import net.neoforged.bus.api.IEventBus;
import net.minecraftforge.fml.DistExecutor; import net.neoforged.fml.common.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod; import net.neoforged.fml.loading.FMLEnvironment;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -18,24 +18,32 @@ import java.util.function.Consumer;
* The type Compat manager. * The type Compat manager.
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public abstract class ForgeCompatManager extends CompatManager { public abstract class NeoForgeCompatManager extends CompatManager<INeoForgeCompat> {
/** /**
* The Mod event bus. * The Mod event bus.
*/ */
protected final IEventBus modEventBus, /** protected final IEventBus modEventBus,
/**
* The Game event bus. * The Game event bus.
*/ */
gameEventBus; gameEventBus;
/** /**
* The Compats. * The Compats.
*/ */
protected final Map<ResourceLocation, IForgeCompat> compats = new HashMap<>(); protected final Map<ResourceLocation, INeoForgeCompat> compats = new HashMap<>();
/** /**
* <pre>
* 存储事件监听器配置
* The Listener configs. * The Listener configs.
* </pre>
*/ */
// 存储事件监听器配置
protected final List<ListenerConfig> listenerConfigs = new ArrayList<>(); protected final List<ListenerConfig> listenerConfigs = new ArrayList<>();
@Override
public Map<ResourceLocation, INeoForgeCompat> getCompatMap() {
return compats;
}
/** /**
* Instantiates a new Forge compat manager. * Instantiates a new Forge compat manager.
* *
@ -43,18 +51,16 @@ public abstract class ForgeCompatManager extends CompatManager {
* @param modEventBus the mod event bus * @param modEventBus the mod event bus
* @param gameEventBus the game event bus * @param gameEventBus the game event bus
*/ */
public ForgeCompatManager(ResourceLocation id, IEventBus modEventBus, IEventBus gameEventBus) { public NeoForgeCompatManager(ResourceLocation id, IEventBus modEventBus, IEventBus gameEventBus) {
super(id); super(id);
this.modEventBus = modEventBus; this.modEventBus = modEventBus;
this.gameEventBus = gameEventBus; this.gameEventBus = gameEventBus;
} }
@Override @Override
protected void doRegisterCompat(ResourceLocation id, ICompat compat) { protected void doRegisterCompat(ResourceLocation id, INeoForgeCompat compat) {
if (compat instanceof IForgeCompat) { super.doRegisterCompat(id, compat);
super.doRegisterCompat(id, compat); addListenerForCompat(id);
addListenerForCompat(id);
} else throw new IllegalArgumentException("Can't register compat " + id + " of type " + compat.getClass());
} }
/** /**
@ -63,7 +69,7 @@ public abstract class ForgeCompatManager extends CompatManager {
* @param dists the dists * @param dists the dists
* @param bus the bus * @param bus the bus
*/ */
public void addListenerForAll(@Nullable Dist dists, Mod.EventBusSubscriber.Bus bus) { public void addListenerForAll(@Nullable Dist dists, EventBusSubscriber.Bus bus) {
listenerConfigs.add(new ListenerConfig(null, dists, bus)); listenerConfigs.add(new ListenerConfig(null, dists, bus));
} }
@ -74,7 +80,7 @@ public abstract class ForgeCompatManager extends CompatManager {
* @param dists the dists * @param dists the dists
* @param bus the bus * @param bus the bus
*/ */
public void addListenerForCompat(ResourceLocation compatId, @Nullable Dist dists, Mod.EventBusSubscriber.Bus bus) { public void addListenerForCompat(ResourceLocation compatId, @Nullable Dist dists, EventBusSubscriber.Bus bus) {
listenerConfigs.add(new ListenerConfig(compatId, dists, bus)); listenerConfigs.add(new ListenerConfig(compatId, dists, bus));
} }
@ -84,14 +90,14 @@ public abstract class ForgeCompatManager extends CompatManager {
* @param compatId the compat id * @param compatId the compat id
*/ */
public void addListenerForCompat(ResourceLocation compatId) { public void addListenerForCompat(ResourceLocation compatId) {
addListenerForCompat(compatId, null, Mod.EventBusSubscriber.Bus.FORGE); addListenerForCompat(compatId, null, EventBusSubscriber.Bus.GAME);
addListenerForCompat(compatId, null, Mod.EventBusSubscriber.Bus.MOD); addListenerForCompat(compatId, null, EventBusSubscriber.Bus.MOD);
addListenerForCompat(compatId, Dist.CLIENT, Mod.EventBusSubscriber.Bus.FORGE); addListenerForCompat(compatId, Dist.CLIENT, EventBusSubscriber.Bus.GAME);
addListenerForCompat(compatId, Dist.CLIENT, Mod.EventBusSubscriber.Bus.MOD); addListenerForCompat(compatId, Dist.CLIENT, EventBusSubscriber.Bus.MOD);
addListenerForCompat(compatId, Dist.DEDICATED_SERVER, Mod.EventBusSubscriber.Bus.FORGE); addListenerForCompat(compatId, Dist.DEDICATED_SERVER, EventBusSubscriber.Bus.GAME);
addListenerForCompat(compatId, Dist.DEDICATED_SERVER, Mod.EventBusSubscriber.Bus.MOD); addListenerForCompat(compatId, Dist.DEDICATED_SERVER, EventBusSubscriber.Bus.MOD);
} }
/** /**
@ -101,10 +107,10 @@ public abstract class ForgeCompatManager extends CompatManager {
* @param bus the bus * @param bus the bus
* @param consumer the consumer * @param consumer the consumer
*/ */
public void addListenerForLoaded(@Nullable Dist dists, Mod.EventBusSubscriber.Bus bus, Consumer<IEventBus> consumer) { public void addListenerForLoaded(@Nullable Dist dists, EventBusSubscriber.Bus bus, Consumer<IEventBus> consumer) {
listenerConfigs.add(new ListenerConfig(null, dists, bus) { listenerConfigs.add(new ListenerConfig(null, dists, bus) {
@Override @Override
boolean shouldApply(@NotNull IForgeCompat compat) { boolean shouldApply(@NotNull INeoForgeCompat compat) {
return super.shouldApply(compat); return super.shouldApply(compat);
} }
}); });
@ -123,7 +129,7 @@ public abstract class ForgeCompatManager extends CompatManager {
pendingTasks.clear(); pendingTasks.clear();
// 初始化所有兼容模块 // 初始化所有兼容模块
for (Map.Entry<ResourceLocation, IForgeCompat> entry : compats.entrySet()) { for (Map.Entry<ResourceLocation, INeoForgeCompat> entry : compats.entrySet()) {
if (!entry.getValue().isInitialized() && entry.getValue().isModLoaded()) { if (!entry.getValue().isInitialized() && entry.getValue().isModLoaded()) {
try { try {
entry.getValue().initialize(); entry.getValue().initialize();
@ -160,7 +166,7 @@ public abstract class ForgeCompatManager extends CompatManager {
* 将监听器应用到所有兼容模块 * 将监听器应用到所有兼容模块
*/ */
private void applyListenerToAllCompats(ListenerConfig config) { private void applyListenerToAllCompats(ListenerConfig config) {
for (IForgeCompat compat : compats.values()) { for (INeoForgeCompat compat : compats.values()) {
if(!compat.isInitialized()) { if(!compat.isInitialized()) {
if (config.shouldApply(compat)) { if (config.shouldApply(compat)) {
applyListenerToCompat(compat, config); applyListenerToCompat(compat, config);
@ -173,7 +179,7 @@ public abstract class ForgeCompatManager extends CompatManager {
* 将监听器应用到特定兼容模块 * 将监听器应用到特定兼容模块
*/ */
private void applyListenerToCompat(ResourceLocation compatId, ListenerConfig config) { private void applyListenerToCompat(ResourceLocation compatId, ListenerConfig config) {
IForgeCompat compat = compats.get(compatId); INeoForgeCompat compat = compats.get(compatId);
if (compat != null && config.shouldApply(compat)) { if (compat != null && config.shouldApply(compat)) {
applyListenerToCompat(compat, config); applyListenerToCompat(compat, config);
} }
@ -182,33 +188,22 @@ public abstract class ForgeCompatManager extends CompatManager {
/** /**
* 将监听器应用到具体的 ICompat 实例 * 将监听器应用到具体的 ICompat 实例
*/ */
private void applyListenerToCompat(IForgeCompat compat, ListenerConfig config) { private void applyListenerToCompat(INeoForgeCompat compat, ListenerConfig config) {
try { try {
// 根据配置调用对应的 ICompat 方法 // 根据配置调用对应的 ICompat 方法
if (config.dists != null) { if (config.dists != null) {
switch (config.dists) { // 不再使用 DistExecutor改为在运行时判断环境
case CLIENT -> DistExecutor.unsafeRunWhenOn(Dist.CLIENT,() -> () -> { Dist currentDist = FMLEnvironment.dist;
if (config.bus == Mod.EventBusSubscriber.Bus.FORGE) {
compat.addClientGameListener(gameEventBus); if (config.dists == Dist.CLIENT && currentDist == Dist.CLIENT) {
} else { applyClientListener(compat, config);
compat.addClientModListener(modEventBus); } else if (config.dists == Dist.DEDICATED_SERVER && currentDist == Dist.DEDICATED_SERVER) {
} applyServerListener(compat, config);
});
case DEDICATED_SERVER -> DistExecutor.unsafeRunWhenOn(Dist.DEDICATED_SERVER,() -> () -> {
if (config.bus == Mod.EventBusSubscriber.Bus.FORGE) {
compat.addServerGameListener(gameEventBus);
} else {
compat.addServerModListener(modEventBus);
}
});
} }
// 如果环境不匹配什么都不做
} else { } else {
// 通用监听器 // 通用监听器两边都执行
if (config.bus == Mod.EventBusSubscriber.Bus.FORGE) { applyCommonListener(compat, config);
compat.addCommonGameListener(gameEventBus);
} else {
compat.addCommonModListener(modEventBus);
}
} }
logger.debug("Applied {} listener to compat: {}", logger.debug("Applied {} listener to compat: {}",
@ -219,15 +214,39 @@ public abstract class ForgeCompatManager extends CompatManager {
} }
} }
private void applyClientListener(INeoForgeCompat compat, @NotNull ListenerConfig config) {
if (config.bus == EventBusSubscriber.Bus.GAME) {
compat.addClientGameListener(gameEventBus);
} else {
compat.addClientModListener(modEventBus);
}
}
private void applyServerListener(INeoForgeCompat compat, @NotNull ListenerConfig config) {
if (config.bus == EventBusSubscriber.Bus.GAME) {
compat.addServerGameListener(gameEventBus);
} else {
compat.addServerModListener(modEventBus);
}
}
private void applyCommonListener(INeoForgeCompat compat, @NotNull ListenerConfig config) {
if (config.bus == EventBusSubscriber.Bus.GAME) {
compat.addCommonGameListener(gameEventBus);
} else {
compat.addCommonModListener(modEventBus);
}
}
/** /**
* 获取监听器类型名称用于日志 * 获取监听器类型名称用于日志
*/ */
private @NotNull String getListenerTypeName(@NotNull ListenerConfig config) { private @NotNull String getListenerTypeName(@NotNull ListenerConfig config) {
if (config.dists != null) { if (config.dists != null) {
return config.dists.name().toLowerCase() + " " + return config.dists.name().toLowerCase() + " " +
(config.bus == Mod.EventBusSubscriber.Bus.FORGE ? "game" : "mod"); (config.bus == EventBusSubscriber.Bus.GAME ? "game" : "mod");
} else { } else {
return "common " + (config.bus == Mod.EventBusSubscriber.Bus.FORGE ? "game" : "mod"); return "common " + (config.bus == EventBusSubscriber.Bus.GAME ? "game" : "mod");
} }
} }
@ -238,7 +257,7 @@ public abstract class ForgeCompatManager extends CompatManager {
* @param compatId the compat id * @param compatId the compat id
* @param bus the bus * @param bus the bus
*/ */
public void addListenerForCompat(ResourceLocation compatId, Mod.EventBusSubscriber.Bus bus) { public void addListenerForCompat(ResourceLocation compatId, EventBusSubscriber.Bus bus) {
addListenerForCompat(compatId, null, bus); addListenerForCompat(compatId, null, bus);
} }
@ -257,7 +276,7 @@ public abstract class ForgeCompatManager extends CompatManager {
/** /**
* The Bus. * The Bus.
*/ */
final Mod.EventBusSubscriber.Bus bus; final EventBusSubscriber.Bus bus;
/** /**
* Instantiates a new Listener config. * Instantiates a new Listener config.
@ -266,7 +285,7 @@ public abstract class ForgeCompatManager extends CompatManager {
* @param dists the dists * @param dists the dists
* @param bus the bus * @param bus the bus
*/ */
ListenerConfig(ResourceLocation compatId, Dist dists, Mod.EventBusSubscriber.Bus bus) { ListenerConfig(ResourceLocation compatId, Dist dists, EventBusSubscriber.Bus bus) {
this.compatId = compatId; this.compatId = compatId;
this.dists = dists; this.dists = dists;
this.bus = bus; this.bus = bus;
@ -278,7 +297,7 @@ public abstract class ForgeCompatManager extends CompatManager {
* @param compat the compat * @param compat the compat
* @return the boolean * @return the boolean
*/ */
boolean shouldApply(@NotNull IForgeCompat compat) { boolean shouldApply(@NotNull INeoForgeCompat compat) {
return compat.isModLoaded(); return compat.isModLoaded();
} }
} }

View File

@ -1,18 +1,28 @@
package top.r3944realms.lib39.core.event; package top.r3944realms.lib39.core.event;
import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.client.renderer.ShaderInstance;
import net.minecraftforge.api.distmarker.Dist; import net.minecraft.client.renderer.entity.ItemRenderer;
import net.minecraftforge.client.event.EntityRenderersEvent; import net.minecraft.client.renderer.item.ItemProperties;
import net.minecraftforge.client.event.RegisterShadersEvent; import net.neoforged.api.distmarker.Dist;
import net.minecraftforge.event.level.LevelEvent; import net.neoforged.bus.api.SubscribeEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent;
import net.neoforged.neoforge.client.event.EntityRenderersEvent;
import net.neoforged.neoforge.client.event.RegisterShadersEvent;
import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions;
import net.neoforged.neoforge.client.extensions.common.RegisterClientExtensionsEvent;
import net.neoforged.neoforge.event.level.LevelEvent;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.client.model.DollModel; import top.r3944realms.lib39.client.model.DollModel;
import top.r3944realms.lib39.client.renderer.block.DollBlockEntityRenderer; import top.r3944realms.lib39.client.renderer.block.DollBlockEntityRenderer;
import top.r3944realms.lib39.client.shader.Lib39Shaders; import top.r3944realms.lib39.client.shader.Lib39Shaders;
import top.r3944realms.lib39.content.item.NeoForgeDollItem;
import top.r3944realms.lib39.core.register.Lib39BlockEntities; import top.r3944realms.lib39.core.register.Lib39BlockEntities;
import top.r3944realms.lib39.core.register.Lib39Items;
import top.r3944realms.lib39.util.ILevelHelper; import top.r3944realms.lib39.util.ILevelHelper;
import java.io.IOException; import java.io.IOException;
@ -24,7 +34,7 @@ public class ClientEventHandler {
/** /**
* The type Mod. * The type Mod.
*/ */
@net.minecraftforge.fml.common.Mod.EventBusSubscriber(value = Dist.CLIENT, bus = net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus.MOD, modid = Lib39.MOD_ID) @EventBusSubscriber(value = Dist.CLIENT, bus = EventBusSubscriber.Bus.MOD, modid = Lib39.MOD_ID)
public static class Mod extends ClientEventHandler { public static class Mod extends ClientEventHandler {
/** /**
* On register shaders. * On register shaders.
@ -33,7 +43,7 @@ public class ClientEventHandler {
* @throws IOException the io exception * @throws IOException the io exception
*/ */
@SubscribeEvent @SubscribeEvent
public static void onRegisterShaders(RegisterShadersEvent event) throws IOException { public static void onRegisterShaders(@NotNull RegisterShadersEvent event) throws IOException {
event.registerShader(new ShaderInstance(event.getResourceProvider(), Lib39.rl("ring"), DefaultVertexFormat.POSITION_COLOR), Lib39Shaders::setRingShader); event.registerShader(new ShaderInstance(event.getResourceProvider(), Lib39.rl("ring"), DefaultVertexFormat.POSITION_COLOR), Lib39Shaders::setRingShader);
event.registerShader(new ShaderInstance(event.getResourceProvider(), Lib39.rl("selection"), DefaultVertexFormat.POSITION_COLOR), Lib39Shaders::setSelectionShader); event.registerShader(new ShaderInstance(event.getResourceProvider(), Lib39.rl("selection"), DefaultVertexFormat.POSITION_COLOR), Lib39Shaders::setSelectionShader);
} }
@ -44,7 +54,7 @@ public class ClientEventHandler {
* @param event the event * @param event the event
*/ */
@SubscribeEvent @SubscribeEvent
public static void onRegisterRenderer (EntityRenderersEvent.RegisterRenderers event) { public static void onRegisterRenderer (EntityRenderersEvent.@NotNull RegisterRenderers event) {
event.registerBlockEntityRenderer(Lib39BlockEntities.DOLL_BLOCK_ENTITY.get(),DollBlockEntityRenderer::new); event.registerBlockEntityRenderer(Lib39BlockEntities.DOLL_BLOCK_ENTITY.get(),DollBlockEntityRenderer::new);
} }
@ -54,16 +64,20 @@ public class ClientEventHandler {
* @param event the event * @param event the event
*/ */
@SubscribeEvent @SubscribeEvent
public static void registerLayerDefinitions(EntityRenderersEvent.RegisterLayerDefinitions event) { public static void registerLayerDefinitions(EntityRenderersEvent.@NotNull RegisterLayerDefinitions event) {
event.registerLayerDefinition(DollModel.LAYER_LOCATION, DollModel::createBodyLayer); event.registerLayerDefinition(DollModel.LAYER_LOCATION, DollModel::createBodyLayer);
} }
@SubscribeEvent
public static void onRegisterClientEx (@NotNull RegisterClientExtensionsEvent event) {
event.registerItem(NeoForgeDollItem.ClientOpt.getExtensions(), Lib39Items.DOLL.get());
}
} }
/** /**
* The type Game. * The type Game.
*/ */
@net.minecraftforge.fml.common.Mod.EventBusSubscriber(value = Dist.CLIENT, bus = net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus.FORGE, modid = Lib39.MOD_ID) @EventBusSubscriber(value = Dist.CLIENT, bus = EventBusSubscriber.Bus.GAME, modid = Lib39.MOD_ID)
public static class Game extends ClientEventHandler { public static class Game extends ClientEventHandler {
/** /**
* Register layer definitions. * Register layer definitions.
@ -71,7 +85,7 @@ public class ClientEventHandler {
* @param event the event * @param event the event
*/ */
@SubscribeEvent @SubscribeEvent
public static void obClientUnload(LevelEvent.Load event) { public static void obClientUnload(LevelEvent.@NotNull Load event) {
if (event.getLevel() != null && event.getLevel() instanceof ClientLevel level) { if (event.getLevel() != null && event.getLevel() instanceof ClientLevel level) {
ILevelHelper.LevelHelper.CLIENT.setLevel(level); ILevelHelper.LevelHelper.CLIENT.setLevel(level);
} }
@ -83,7 +97,7 @@ public class ClientEventHandler {
* @param event the event * @param event the event
*/ */
@SubscribeEvent @SubscribeEvent
public static void obClientUnload(LevelEvent.Unload event) { public static void obClientUnload(LevelEvent.@NotNull Unload event) {
if (event.getLevel() != null && event.getLevel() instanceof ClientLevel level) { if (event.getLevel() != null && event.getLevel() instanceof ClientLevel level) {
ILevelHelper.LevelHelper.CLIENT.setLevel(null); ILevelHelper.LevelHelper.CLIENT.setLevel(null);
} }

View File

@ -15,17 +15,17 @@ import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.SkullBlockEntity; import net.minecraft.world.level.block.entity.SkullBlockEntity;
import net.minecraftforge.common.MinecraftForge; import net.neoforged.bus.api.SubscribeEvent;
import net.minecraftforge.data.event.GatherDataEvent; import net.neoforged.fml.common.EventBusSubscriber;
import net.minecraftforge.event.AnvilUpdateEvent; import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent; import net.neoforged.neoforge.common.NeoForge;
import net.minecraftforge.event.RegisterCommandsEvent; import net.neoforged.neoforge.data.event.GatherDataEvent;
import net.minecraftforge.event.TickEvent; import net.neoforged.neoforge.event.AnvilUpdateEvent;
import net.minecraftforge.event.entity.EntityJoinLevelEvent; import net.neoforged.neoforge.event.BuildCreativeModeTabContentsEvent;
import net.minecraftforge.event.entity.EntityLeaveLevelEvent; import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.minecraftforge.event.level.LevelEvent; import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.neoforged.neoforge.event.entity.EntityLeaveLevelEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.neoforged.neoforge.event.level.LevelEvent;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.api.event.SyncManagerRegisterEvent; import top.r3944realms.lib39.api.event.SyncManagerRegisterEvent;
import top.r3944realms.lib39.base.command.Lib39HelpCommand; import top.r3944realms.lib39.base.command.Lib39HelpCommand;
@ -50,7 +50,7 @@ public class CommonEventHandler {
* The type Game. * The type Game.
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
@net.minecraftforge.fml.common.Mod.EventBusSubscriber(modid = Lib39.MOD_ID, bus = net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus.FORGE) @EventBusSubscriber(modid = Lib39.MOD_ID, bus = EventBusSubscriber.Bus.GAME)
public static class Game extends CommonEventHandler { public static class Game extends CommonEventHandler {
private static ServerLevel sl; private static ServerLevel sl;
@ -92,7 +92,7 @@ public class CommonEventHandler {
synchronized (Game.class) { synchronized (Game.class) {
if (!isSync2MInitialized) { if (!isSync2MInitialized) {
syncData2Manager = new SyncData2CapManager(); syncData2Manager = new SyncData2CapManager();
MinecraftForge.EVENT_BUS.post(new SyncManagerRegisterEvent(syncData2Manager)); NeoForge.EVENT_BUS.post(new SyncManagerRegisterEvent(syncData2Manager));
isSync2MInitialized = true; isSync2MInitialized = true;
sl = serverLevel; sl = serverLevel;
Lib39.LOGGER.info("SyncData2Manager initialized on Sever load"); Lib39.LOGGER.info("SyncData2Manager initialized on Sever load");
@ -104,7 +104,7 @@ public class CommonEventHandler {
if (!clientLevel.dimension().equals(Level.OVERWORLD)) return; if (!clientLevel.dimension().equals(Level.OVERWORLD)) return;
if (!isSync2MInitialized) { if (!isSync2MInitialized) {
syncData2Manager = new SyncData2CapManager(); syncData2Manager = new SyncData2CapManager();
MinecraftForge.EVENT_BUS.post(new SyncManagerRegisterEvent(syncData2Manager)); NeoForge.EVENT_BUS.post(new SyncManagerRegisterEvent(syncData2Manager));
Lib39.LOGGER.info("SyncData2Manager initialized on Client load"); Lib39.LOGGER.info("SyncData2Manager initialized on Client load");
} }
} }
@ -216,7 +216,7 @@ public class CommonEventHandler {
* The type Mod. * The type Mod.
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
@net.minecraftforge.fml.common.Mod.EventBusSubscriber(modid = Lib39.MOD_ID, bus = net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus.MOD) @EventBusSubscriber(modid = Lib39.MOD_ID, bus = EventBusSubscriber.Bus.MOD)
public static class Mod extends CommonEventHandler { public static class Mod extends CommonEventHandler {
private static final Map<Supplier<Block>, ResourceKey<CreativeModeTab>[]> itemAddMap = new ConcurrentHashMap<>(); private static final Map<Supplier<Block>, ResourceKey<CreativeModeTab>[]> itemAddMap = new ConcurrentHashMap<>();
private static final Map<ResourceKey<CreativeModeTab>, List<Supplier<Block>>> tabToItemsMap = new ConcurrentHashMap<>(); private static final Map<ResourceKey<CreativeModeTab>, List<Supplier<Block>>> tabToItemsMap = new ConcurrentHashMap<>();
@ -262,7 +262,7 @@ public class CommonEventHandler {
public static void onBuildCreativeTabContents(BuildCreativeModeTabContentsEvent event) { public static void onBuildCreativeTabContents(BuildCreativeModeTabContentsEvent event) {
List<Supplier<Block>> itemsForTab = tabToItemsMap.get(event.getTabKey()); List<Supplier<Block>> itemsForTab = tabToItemsMap.get(event.getTabKey());
if (itemsForTab != null) { if (itemsForTab != null) {
itemsForTab.forEach(event::accept); itemsForTab.forEach(i -> event.accept(i.get()));
} }
} }

View File

@ -1,20 +1,20 @@
package top.r3944realms.lib39.core.register; package top.r3944realms.lib39.core.register;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraftforge.eventbus.api.IEventBus; import net.neoforged.bus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister; import net.neoforged.neoforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.content.block.blockentity.DollBlockEntity; import top.r3944realms.lib39.content.block.blockentity.DollBlockEntity;
/** /**
* The type Lib 39 block entities. * The type Lib 39 block entities.
*/ */
public class ForgeLib39BlockEntities { public class NeoForgeLib39BlockEntities {
/** /**
* The constant BLOCK_ENTITY_TYPES. * The constant BLOCK_ENTITY_TYPES.
*/ */
public static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, Lib39.MOD_ID); public static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITY_TYPES = DeferredRegister.create(BuiltInRegistries.BLOCK_ENTITY_TYPE, Lib39.MOD_ID);
static { static {
//noinspection DataFlowIssue //noinspection DataFlowIssue

View File

@ -1,9 +1,9 @@
package top.r3944realms.lib39.core.register; package top.r3944realms.lib39.core.register;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraftforge.eventbus.api.IEventBus; import net.neoforged.bus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister; import net.neoforged.neoforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.content.block.DollBlock; import top.r3944realms.lib39.content.block.DollBlock;
import top.r3944realms.lib39.content.block.WallDollBlock; import top.r3944realms.lib39.content.block.WallDollBlock;
@ -12,11 +12,11 @@ import top.r3944realms.lib39.util.block.BlockRegistryBuilder;
/** /**
* The type Lib 39 blocks. * The type Lib 39 blocks.
*/ */
public class ForgeLib39Blocks { public class NeoForgeLib39Blocks {
/** /**
* The constant BLOCKS. * The constant BLOCKS.
*/ */
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, Lib39.MOD_ID); public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(BuiltInRegistries.BLOCK, Lib39.MOD_ID);
static { static {
Lib39Blocks.DOLL = BlockRegistryBuilder Lib39Blocks.DOLL = BlockRegistryBuilder

View File

@ -1,23 +1,23 @@
package top.r3944realms.lib39.core.register; package top.r3944realms.lib39.core.register;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraftforge.eventbus.api.IEventBus; import net.neoforged.bus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister; import net.neoforged.neoforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.content.item.ForgeDollItem; import top.r3944realms.lib39.content.item.NeoForgeDollItem;
/** /**
* The type Ex lib 39 items. * The type Ex lib 39 items.
*/ */
public class ForgeLib39Items { public class NeoForgeLib39Items {
/** /**
* The constant ITEMS. * The constant ITEMS.
*/ */
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Lib39.MOD_ID); public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(BuiltInRegistries.ITEM, Lib39.MOD_ID);
static { static {
Lib39Items.DOLL = ITEMS.register("doll", () -> new ForgeDollItem(new Item.Properties())); Lib39Items.DOLL = ITEMS.register("doll", () -> new NeoForgeDollItem(new Item.Properties()));
} }
/** /**

View File

@ -1,19 +1,19 @@
package top.r3944realms.lib39.core.register; package top.r3944realms.lib39.core.register;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvent;
import net.minecraftforge.eventbus.api.IEventBus; import net.neoforged.bus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister; import net.neoforged.neoforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
/** /**
* The type Lib 39 sound events. * The type Lib 39 sound events.
*/ */
public class ForgeLib39SoundEvents { public class NeoForgeLib39SoundEvents {
/** /**
* The constant SOUND_EVENTS. * The constant SOUND_EVENTS.
*/ */
public static final DeferredRegister<SoundEvent> SOUND_EVENTS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, Lib39.MOD_ID); public static final DeferredRegister<SoundEvent> SOUND_EVENTS = DeferredRegister.create(BuiltInRegistries.SOUND_EVENT, Lib39.MOD_ID);
static { static {
Lib39SoundEvents.DUCK_TOY = SOUND_EVENTS.register("duck_toy", Lib39SoundEvents.DUCK_TOY = SOUND_EVENTS.register("duck_toy",

View File

@ -4,9 +4,9 @@ import top.r3944realms.lib39.core.network.NetworkHandler;
import top.r3944realms.lib39.core.network.toClient.SyncNBTCapDataEntityS2CPacket; import top.r3944realms.lib39.core.network.toClient.SyncNBTCapDataEntityS2CPacket;
/** /**
* The interface Forge update. * The interface NeoForge update.
*/ */
public interface IForgeUpdate extends IUpdate { public interface INeoForgeUpdate extends IUpdate {
default void update() { default void update() {
NetworkHandler.sendToAllPlayer(new SyncNBTCapDataEntityS2CPacket(getSyncData().entityId(), getSyncData().id, getSyncData().serializeNBT())); NetworkHandler.sendToAllPlayer(new SyncNBTCapDataEntityS2CPacket(getSyncData().entityId(), getSyncData().id, getSyncData().serializeNBT()));
} }

View File

@ -1,25 +1,24 @@
package top.r3944realms.lib39.example; package top.r3944realms.lib39.example;
import net.minecraftforge.common.MinecraftForge; import net.neoforged.bus.api.IEventBus;
import net.minecraftforge.eventbus.api.IEventBus; import net.neoforged.neoforge.common.NeoForge;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import top.r3944realms.lib39.example.core.event.ExCommonEventHandler; import top.r3944realms.lib39.example.core.event.ExCommonEventHandler;
import top.r3944realms.lib39.example.core.network.ExNetworkHandler; import top.r3944realms.lib39.example.core.network.ExNetworkHandler;
import top.r3944realms.lib39.example.core.register.ForgeExLib39Items; import top.r3944realms.lib39.example.core.register.NeoForgeExLib39Items;
/** /**
* The type Forge lib 39 example. * The type Forge lib 39 example.
*/ */
public class ForgeLib39Example { public class NeoForgeLib39Example {
private static boolean registered = false; private static boolean registered = false;
/** /**
* Instantiates a new Lib 39 example. * Instantiates a new Lib 39 example.
*/ */
public ForgeLib39Example() { public NeoForgeLib39Example(IEventBus modEventBus) {
if (!registered) { if (!registered) {
init(); init(modEventBus);
registerToEventBus(); registerToEventBus(modEventBus);
registered = true; registered = true;
} }
} }
@ -27,15 +26,14 @@ public class ForgeLib39Example {
/** /**
* Init. * Init.
*/ */
public void init() { public void init(IEventBus modEventBus) {
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); NeoForgeExLib39Items.register(modEventBus);
ForgeExLib39Items.register(modEventBus);
ExNetworkHandler.register(); ExNetworkHandler.register();
} }
private void registerToEventBus() { private void registerToEventBus(IEventBus modEventBus) {
IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus(); IEventBus modBus = modEventBus;
IEventBus gameBus = MinecraftForge.EVENT_BUS; IEventBus gameBus = NeoForge.EVENT_BUS;
// DistExecutor.unsafeCallWhenOn(Dist.CLIENT, () -> { // DistExecutor.unsafeCallWhenOn(Dist.CLIENT, () -> {
// modBus.register(ExClientEventHandler.Mod.class); // modBus.register(ExClientEventHandler.Mod.class);
// gameBus.register(ExClientEventHandler.Game.class); // gameBus.register(ExClientEventHandler.Game.class);

View File

@ -1,17 +1,17 @@
package top.r3944realms.lib39.example.compat; package top.r3944realms.lib39.example.compat;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.eventbus.api.IEventBus; import net.neoforged.bus.api.IEventBus;
import net.minecraftforge.fml.ModList; import net.neoforged.fml.ModList;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.core.compat.IForgeCompat; import top.r3944realms.lib39.core.compat.INeoForgeCompat;
/** /**
* The type Lib 39 compat. * The type Lib 39 compat.
*/ */
public class Lib39Compat implements IForgeCompat { public class Lib39Compat implements INeoForgeCompat {
/** /**
* The Initialized. * The Initialized.
*/ */

View File

@ -1,13 +1,13 @@
package top.r3944realms.lib39.example.compat; package top.r3944realms.lib39.example.compat;
import net.minecraftforge.eventbus.api.IEventBus; import net.neoforged.bus.api.IEventBus;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.core.compat.ForgeCompatManager; import top.r3944realms.lib39.core.compat.NeoForgeCompatManager;
/** /**
* The type Lib 39 compat manager. * The type Lib 39 compat manager.
*/ */
public class Lib39CompatManager extends ForgeCompatManager { public class Lib39CompatManager extends NeoForgeCompatManager {
/** /**
* Instantiates a new Compat manager. * Instantiates a new Compat manager.
* *

View File

@ -6,7 +6,7 @@ import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.core.sync.IForgeUpdate; import top.r3944realms.lib39.core.sync.INeoForgeUpdate;
import top.r3944realms.lib39.util.nbt.NBTReader; import top.r3944realms.lib39.util.nbt.NBTReader;
import top.r3944realms.lib39.util.nbt.NBTWriter; import top.r3944realms.lib39.util.nbt.NBTWriter;
@ -18,7 +18,7 @@ import java.util.concurrent.atomic.AtomicReference;
* 测试同步数据实现 * 测试同步数据实现
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class TestSyncData extends AbstractedTestSyncData implements IForgeUpdate { public class TestSyncData extends AbstractedTestSyncData implements INeoForgeUpdate {
/** /**
* The constant ID. * The constant ID.
*/ */

View File

@ -16,14 +16,14 @@ import top.r3944realms.lib39.example.core.network.ExNetworkHandler;
/** /**
* The type Forge fabric item. * The type Forge fabric item.
*/ */
public class ForgeFabricItem extends AbstractFabricItem { public class NeoForgeFabricItem extends AbstractFabricItem {
/** /**
* Instantiates a new Forge fabric item. * Instantiates a new Forge fabric item.
* *
* @param properties the properties * @param properties the properties
*/ */
public ForgeFabricItem(Properties properties) { public NeoForgeFabricItem(Properties properties) {
super(properties); super(properties);
} }

View File

@ -10,14 +10,14 @@ import top.r3944realms.lib39.example.content.data.TestSyncData;
/** /**
* The type Forge neo forge item. * The type Forge neo forge item.
*/ */
public class ForgeNeoForgeItem extends AbstractNeoForgeItem{ public class NeoForgeNeoForgeItem extends AbstractNeoForgeItem{
/** /**
* Instantiates a new Forge neo forge item. * Instantiates a new Forge neo forge item.
* *
* @param properties the properties * @param properties the properties
*/ */
public ForgeNeoForgeItem(Properties properties) { public NeoForgeNeoForgeItem(Properties properties) {
super(properties); super(properties);
} }

View File

@ -1,16 +1,12 @@
package top.r3944realms.lib39.example.core.event; package top.r3944realms.lib39.example.core.event;
import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.LivingEntity;
import net.minecraftforge.common.MinecraftForge; import net.neoforged.bus.api.IEventBus;
import net.minecraftforge.common.capabilities.Capability; import net.neoforged.bus.api.SubscribeEvent;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent; import net.neoforged.fml.ModLoadingContext;
import net.minecraftforge.event.AttachCapabilitiesEvent; import net.neoforged.neoforge.common.NeoForge;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.event.lifecycle.FMLConstructModEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import top.r3944realms.lib39.api.event.SyncManagerRegisterEvent; import top.r3944realms.lib39.api.event.SyncManagerRegisterEvent;
import top.r3944realms.lib39.core.compat.CompatManager; import top.r3944realms.lib39.core.compat.ICompatManager;
import top.r3944realms.lib39.core.event.CommonEventHandler; import top.r3944realms.lib39.core.event.CommonEventHandler;
import top.r3944realms.lib39.core.sync.CachedSyncManager; import top.r3944realms.lib39.core.sync.CachedSyncManager;
import top.r3944realms.lib39.example.compat.Lib39Compat; import top.r3944realms.lib39.example.compat.Lib39Compat;
@ -71,21 +67,17 @@ public class ExCommonEventHandler {
* The type Mod. * The type Mod.
*/ */
public static class Mod extends ExCommonEventHandler { public static class Mod extends ExCommonEventHandler {
/**
* The constant EVENT_BUS.
*/
public static final IEventBus EVENT_BUS = FMLJavaModLoadingContext.get().getModEventBus();
/** /**
* Gets compat manager. * Gets compat manager.
* *
* @return the compat manager * @return the compat manager
*/ */
public static CompatManager getOrCreateCompatManager() { public static ICompatManager getOrCreateCompatManager() {
if (compatManager == null) { if (compatManager == null) {
synchronized (CommonEventHandler.Mod.class) { synchronized (CommonEventHandler.Mod.class) {
if (compatManager == null) { if (compatManager == null) {
compatManager = new Lib39CompatManager("compat", EVENT_BUS, MinecraftForge.EVENT_BUS); compatManager = new Lib39CompatManager("compat", EVENT_BUS, NeoForge.EVENT_BUS);
} }
} }
} }
@ -95,7 +87,7 @@ public class ExCommonEventHandler {
/** /**
* The Compat manager. * The Compat manager.
*/ */
static volatile CompatManager compatManager; static volatile ICompatManager compatManager;
/** /**
@ -106,7 +98,7 @@ public class ExCommonEventHandler {
@SubscribeEvent @SubscribeEvent
public static void onConstructMod(FMLConstructModEvent event) { public static void onConstructMod(FMLConstructModEvent event) {
event.enqueueWork(() -> { event.enqueueWork(() -> {
CompatManager orCreateCompatManager = Mod.getOrCreateCompatManager(); ICompatManager orCreateCompatManager = Mod.getOrCreateCompatManager();
orCreateCompatManager orCreateCompatManager
.registerCompat(Lib39Compat.ID, Lib39Compat.INSTANCE); .registerCompat(Lib39Compat.ID, Lib39Compat.INSTANCE);
orCreateCompatManager.initialize(); orCreateCompatManager.initialize();

View File

@ -5,7 +5,7 @@ import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkEvent;
import top.r3944realms.lib39.example.content.data.AbstractedTestSyncData; import top.r3944realms.lib39.example.content.data.AbstractedTestSyncData;
import top.r3944realms.lib39.example.content.data.TestSyncData; import top.r3944realms.lib39.example.content.data.TestSyncData;
import top.r3944realms.lib39.example.content.item.ForgeFabricItem; import top.r3944realms.lib39.example.content.item.NeoForgeFabricItem;
import java.util.function.Supplier; import java.util.function.Supplier;
@ -65,6 +65,6 @@ public class ClientDataPacket {
} }
private void handleClientData(ServerPlayer player, AbstractedTestSyncData clientData, int targetEntityId) { private void handleClientData(ServerPlayer player, AbstractedTestSyncData clientData, int targetEntityId) {
ForgeFabricItem.handleClientDataFromPacket(player, clientData, targetEntityId); NeoForgeFabricItem.handleClientDataFromPacket(player, clientData, targetEntityId);
} }
} }

View File

@ -1,27 +1,27 @@
package top.r3944realms.lib39.example.core.register; package top.r3944realms.lib39.example.core.register;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraftforge.eventbus.api.IEventBus; import net.neoforged.bus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister; import net.neoforged.neoforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.example.content.item.ForgeFabricItem; import top.r3944realms.lib39.example.content.item.NeoForgeFabricItem;
import top.r3944realms.lib39.example.content.item.ForgeItem; import top.r3944realms.lib39.example.content.item.ForgeItem;
import top.r3944realms.lib39.example.content.item.ForgeNeoForgeItem; import top.r3944realms.lib39.example.content.item.NeoForgeNeoForgeItem;
/** /**
* The type Ex lib 39 items. * The type Ex lib 39 items.
*/ */
public class ForgeExLib39Items { public class NeoForgeExLib39Items {
/** /**
* The constant ITEMS. * The constant ITEMS.
*/ */
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Lib39.MOD_ID); public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(BuiltInRegistries.ITEM, Lib39.MOD_ID);
static { static {
ExLib39Items.FABRIC = ITEMS.register( ExLib39Items.FABRIC = ITEMS.register(
"fabric", "fabric",
() -> new ForgeFabricItem( () -> new NeoForgeFabricItem(
new Item.Properties() new Item.Properties()
.stacksTo(1) .stacksTo(1)
.fireResistant() .fireResistant()
@ -29,7 +29,7 @@ public class ForgeExLib39Items {
); );
ExLib39Items.NEOFORGE = ExLib39Items.NEOFORGE =
ITEMS.register("neoforge", ITEMS.register("neoforge",
() -> new ForgeNeoForgeItem( () -> new NeoForgeNeoForgeItem(
new Item.Properties() new Item.Properties()
.stacksTo(1) .stacksTo(1)
.fireResistant() .fireResistant()

View File

@ -9,7 +9,7 @@ import net.minecraft.server.dedicated.DedicatedServer;
import net.minecraft.server.level.progress.ChunkProgressListenerFactory; import net.minecraft.server.level.progress.ChunkProgressListenerFactory;
import net.minecraft.server.packs.repository.PackRepository; import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraftforge.common.MinecraftForge; import net.neoforged.neoforge.common.NeoForge;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
@ -48,6 +48,6 @@ public abstract class MixinDedicateServer extends MinecraftServer implements Ser
) )
) )
private void initServer$setup(CallbackInfoReturnable<Boolean> cir) { private void initServer$setup(CallbackInfoReturnable<Boolean> cir) {
MinecraftForge.EVENT_BUS.post(new MinecraftSetUpServiceEvent(this.services,this)); NeoForge.EVENT_BUS.post(new MinecraftSetUpServiceEvent(this.services,this));
} }
} }

View File

@ -3,13 +3,14 @@ package top.r3944realms.lib39.mixin.init;
import com.llamalad7.mixinextras.sugar.Local; import com.llamalad7.mixinextras.sugar.Local;
import com.mojang.blaze3d.platform.WindowEventHandler; import com.mojang.blaze3d.platform.WindowEventHandler;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.ReceivingLevelScreen;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.server.Services; import net.minecraft.server.Services;
import net.minecraft.server.WorldStem; import net.minecraft.server.WorldStem;
import net.minecraft.server.packs.repository.PackRepository; import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.util.thread.ReentrantBlockableEventLoop; import net.minecraft.util.thread.ReentrantBlockableEventLoop;
import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraftforge.common.MinecraftForge; import net.neoforged.neoforge.common.NeoForge;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
@ -20,7 +21,7 @@ import top.r3944realms.lib39.api.event.MinecraftSetUpServiceEvent;
* The type Mixin minecraft. * The type Mixin minecraft.
*/ */
@Mixin(Minecraft.class) @Mixin(Minecraft.class)
public abstract class MixinMinecraft extends ReentrantBlockableEventLoop<Runnable> implements WindowEventHandler, net.minecraftforge.client.extensions.IForgeMinecraft { public abstract class MixinMinecraft extends ReentrantBlockableEventLoop<Runnable> implements WindowEventHandler {
/** /**
* Instantiates a new Mixin minecraft. * Instantiates a new Mixin minecraft.
* *
@ -33,7 +34,7 @@ public abstract class MixinMinecraft extends ReentrantBlockableEventLoop<Runnabl
/** /**
* Set level setup. * Set level setup.
* *
* @param levelClient the level client * @param level the level client
* @param ci the ci * @param ci the ci
* @param services the services * @param services the services
*/ */
@ -45,16 +46,14 @@ public abstract class MixinMinecraft extends ReentrantBlockableEventLoop<Runnabl
shift = At.Shift.AFTER shift = At.Shift.AFTER
) )
) )
public void setLevel$setup(ClientLevel levelClient, CallbackInfo ci, public void setLevel$setup(ClientLevel level, ReceivingLevelScreen.Reason reason, CallbackInfo ci, @Local(ordinal = 0) Services services) {
@Local(ordinal = 0) Services services) { NeoForge.EVENT_BUS.post(new MinecraftSetUpServiceEvent(services,this));
MinecraftForge.EVENT_BUS.post(new MinecraftSetUpServiceEvent(services,this));
} }
/** /**
* Do world load setup. * Do world load setup.
* *
* @param levelId the level id * @param levelStorage the level storage
* @param level the level
* @param packRepository the pack repository * @param packRepository the pack repository
* @param worldStem the world stem * @param worldStem the world stem
* @param newWorld the new world * @param newWorld the new world
@ -69,9 +68,8 @@ public abstract class MixinMinecraft extends ReentrantBlockableEventLoop<Runnabl
shift = At.Shift.AFTER shift = At.Shift.AFTER
) )
) )
public void doWorldLoad$setup(String levelId, LevelStorageSource.LevelStorageAccess level, PackRepository packRepository, WorldStem worldStem, boolean newWorld, CallbackInfo ci, public void doWorldLoad$setup(LevelStorageSource.LevelStorageAccess levelStorage, PackRepository packRepository, WorldStem worldStem, boolean newWorld, CallbackInfo ci, @Local(ordinal = 0) Services services) {
@Local(ordinal = 0) Services services) { NeoForge.EVENT_BUS.post(new MinecraftSetUpServiceEvent(services,this));
MinecraftForge.EVENT_BUS.post(new MinecraftSetUpServiceEvent(services,this));
} }
} }

View File

@ -4,6 +4,7 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.CommandSourceStack;
import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.MinecraftForge;
import net.neoforged.neoforge.common.NeoForge;
import top.r3944realms.lib39.api.event.RegisterCommandHelpEvent; import top.r3944realms.lib39.api.event.RegisterCommandHelpEvent;
import top.r3944realms.lib39.core.command.ICommandHelpManager; import top.r3944realms.lib39.core.command.ICommandHelpManager;
import top.r3944realms.lib39.platform.services.IHelpCommandHook; import top.r3944realms.lib39.platform.services.IHelpCommandHook;
@ -11,7 +12,7 @@ import top.r3944realms.lib39.platform.services.IHelpCommandHook;
/** /**
* The enum Forge help command hook. * The enum Forge help command hook.
*/ */
public enum ForgeHelpCommandHook implements IHelpCommandHook { public enum NeoForgeHelpCommandHook implements IHelpCommandHook {
/** /**
* Instance forge help command hook. * Instance forge help command hook.
*/ */
@ -20,6 +21,6 @@ public enum ForgeHelpCommandHook implements IHelpCommandHook {
@Override @Override
public void onRegister(LiteralArgumentBuilder<CommandSourceStack> tree, ICommandHelpManager manager, CommandBuildContext context) { public void onRegister(LiteralArgumentBuilder<CommandSourceStack> tree, ICommandHelpManager manager, CommandBuildContext context) {
RegisterCommandHelpEvent registerHelpCommandEvent = new RegisterCommandHelpEvent(tree, manager, context); RegisterCommandHelpEvent registerHelpCommandEvent = new RegisterCommandHelpEvent(tree, manager, context);
MinecraftForge.EVENT_BUS.post(registerHelpCommandEvent); NeoForge.EVENT_BUS.post(registerHelpCommandEvent);
} }
} }

View File

@ -1,8 +1,8 @@
package top.r3944realms.lib39.platform; package top.r3944realms.lib39.platform;
import net.minecraftforge.fml.ModList; import net.neoforged.fml.ModList;
import net.minecraftforge.fml.loading.FMLEnvironment; import net.neoforged.fml.loading.FMLEnvironment;
import net.minecraftforge.fml.loading.FMLLoader; import net.neoforged.fml.loading.FMLLoader;
import top.r3944realms.lib39.Lib39; import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.platform.services.IHelpCommandHook; import top.r3944realms.lib39.platform.services.IHelpCommandHook;
import top.r3944realms.lib39.platform.services.IPlatformHelper; import top.r3944realms.lib39.platform.services.IPlatformHelper;
@ -11,7 +11,7 @@ import top.r3944realms.lib39.platform.services.IUtilHelper;
/** /**
* The type Forge platform helper. * The type Forge platform helper.
*/ */
public class ForgePlatformHelper implements IPlatformHelper { public class NeoForgePlatformHelper implements IPlatformHelper {
@Override @Override
public String getPlatformName() { public String getPlatformName() {
@ -43,11 +43,11 @@ public class ForgePlatformHelper implements IPlatformHelper {
@Override @Override
public IUtilHelper getUtilHelper() { public IUtilHelper getUtilHelper() {
return ForgeUtilHelper.INSTANCE; return NeoForgeUtilHelper.INSTANCE;
} }
@Override @Override
public IHelpCommandHook getHelpCommandHook() { public IHelpCommandHook getHelpCommandHook() {
return ForgeHelpCommandHook.INSTANCE; return NeoForgeHelpCommandHook.INSTANCE;
} }
} }

View File

@ -7,7 +7,7 @@ import top.r3944realms.lib39.util.block.BlockRegistryBuilder;
/** /**
* The enum Forge util helper. * The enum Forge util helper.
*/ */
public enum ForgeUtilHelper implements IUtilHelper { public enum NeoForgeUtilHelper implements IUtilHelper {
/** /**
* Instance forge util helper. * Instance forge util helper.
*/ */

View File

@ -1,7 +1,7 @@
modLoader = "javafml" #mandatory modLoader = "javafml" #mandatory
loaderVersion = "${forge_loader_version_range}" #mandatory This is typically bumped every Minecraft version by Forge. See https://files.minecraftforge.net/ for a list of versions. loaderVersion = "${neoforge_loader_version_range}" #mandatory This is typically bumped every Minecraft version by Forge. See https://files.minecraftforge.net/ for a list of versions.
license = "${license}" # Review your options at https://choosealicense.com/. license = "${license}" # Review your options at https://choosealicense.com/.
issueTrackerURL="https://github.com/3944Realms/Lib39/issues" #optional issueTrackerURL="https://gitea.bot.leisuretimedock.top/3944Realms/Lib39/issues" #optional
[[mods]] #mandatory [[mods]] #mandatory
modId = "${mod_id}" #mandatory modId = "${mod_id}" #mandatory
version = "${version}" #mandatory version = "${version}" #mandatory
@ -9,13 +9,17 @@ displayName = "${mod_name}" #mandatory
#updateJSONURL="https://change.me.example.invalid/updates.json" #optional (see https://mcforge.readthedocs.io/en/latest/gettingstarted/autoupdate/) #updateJSONURL="https://change.me.example.invalid/updates.json" #optional (see https://mcforge.readthedocs.io/en/latest/gettingstarted/autoupdate/)
#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional (displayed in the mod UI) #displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional (displayed in the mod UI)
logoFile = "lib39_logo.png" #optional (needs to be in the root of your mod jar (root of your 'resources' folder)) logoFile = "lib39_logo.png" #optional (needs to be in the root of your mod jar (root of your 'resources' folder))
credits = "Thanks for this example mod goes to Java" #optional credits = "${credits}" #optional
authors = "${mod_author}" #optional authors = "${mod_author}" #optional
description = '''${description}''' #mandatory (Supports multiline text) description = '''${description}''' #mandatory (Supports multiline text)
[[mixins]]
config = "${mod_id}.mixins.json"
[[mixins]]
config = "${mod_id}.neoforge.mixins.json"
[[dependencies.${mod_id}]] #optional [[dependencies.${mod_id}]] #optional
modId = "forge" #mandatory modId = "neoforge" #mandatory
mandatory = true #mandatory mandatory = true #mandatory
versionRange = "[${forge_version},)" #mandatory versionRange = "[${neoforge_version},)" #mandatory
ordering = "NONE" # The order that this dependency should load in relation to your mod, required to be either 'BEFORE' or 'AFTER' if the dependency is not mandatory ordering = "NONE" # The order that this dependency should load in relation to your mod, required to be either 'BEFORE' or 'AFTER' if the dependency is not mandatory
side = "BOTH" # Side this dependency is applied on - 'BOTH', 'CLIENT' or 'SERVER' side = "BOTH" # Side this dependency is applied on - 'BOTH', 'CLIENT' or 'SERVER'
[[dependencies.${mod_id}]] [[dependencies.${mod_id}]]

View File

@ -0,0 +1 @@
top.r3944realms.lib39.platform.NeoForgePlatformHelper

View File

@ -2,15 +2,15 @@
"required": true, "required": true,
"minVersion": "0.8", "minVersion": "0.8",
"package": "top.r3944realms.lib39.mixin", "package": "top.r3944realms.lib39.mixin",
"refmap": "${mod_id}.forge.refmap.json", "refmap": "${mod_id}.refmap.json",
"compatibilityLevel": "JAVA_17", "compatibilityLevel": "JAVA_21",
"mixins": [ "mixins": [
"init.MixinDedicateServer"
], ],
"client": [ "client": [
"init.MixinMinecraft" "init.MixinMinecraft"
], ],
"server": [ "server": [
"init.MixinDedicateServer"
], ],
"injectors": { "injectors": {
"defaultRequire": 1 "defaultRequire": 1

Some files were not shown because too many files have changed in this diff Show More