Skip to content

Commit

Permalink
Merge pull request #3 from HeChuQIU/feat/infrastructure
Browse files Browse the repository at this point in the history
添加一系列方便开发的工具方法
  • Loading branch information
HeChuQIU authored Apr 20, 2024
2 parents 0ca278b + b8fda76 commit 6cb6349
Show file tree
Hide file tree
Showing 9 changed files with 156 additions and 60 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ gradle-app.setting

# Common working directory
run/
run-data/
src/generated/

# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
32 changes: 26 additions & 6 deletions src/main/java/com/gensokyo/nucleardelight/NuclearDelight.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package com.gensokyo.nucleardelight;

import com.gensokyo.nucleardelight.register.AutoRegistryObject;
import com.gensokyo.nucleardelight.world.effect.MobEffects;
import com.gensokyo.nucleardelight.world.food.Foods;
import com.mojang.logging.LogUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.core.registries.Registries;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.food.FoodProperties;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.CreativeModeTab;
Expand All @@ -30,6 +33,10 @@
import net.minecraftforge.registries.RegistryObject;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

// The value here should match an entry in the META-INF/mods.toml file
@Mod(NuclearDelight.MODID)
public class NuclearDelight {
Expand All @@ -42,6 +49,7 @@ public class NuclearDelight {
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
// Create a Deferred Register to hold Items which will all be registered under the "nucleardelight" namespace
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
public static final DeferredRegister<MobEffect> MOB_EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, MODID);
// Create a Deferred Register to hold CreativeModeTabs which will all be registered under the "examplemod" namespace
public static final DeferredRegister<CreativeModeTab> CREATIVE_MODE_TABS = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, MODID);

Expand All @@ -59,21 +67,34 @@ public class NuclearDelight {
.withTabsBefore(CreativeModeTabs.COMBAT)
.icon(() -> EXAMPLE_ITEM.get().getDefaultInstance())
.displayItems((parameters, output) -> {
output.accept(EXAMPLE_ITEM.get()); // Add the example item to the tab. For your own tabs, this method is preferred over the event
output.accept(EXAMPLE_ITEM.get()); // Add the example item to the tab. For your own tabs, this method is preferred over the event
}).build());

public static List<RegistryObject<Item>> RegisteredItems = new ArrayList<>();

public NuclearDelight() {
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();

// Register the commonSetup method for modloading
modEventBus.addListener(this::commonSetup);

Foods.Initializing();
List<RegistryObject<Item>> registeredFoods = Utils.registryObjects(ITEMS,
Utils.getStaticFinalFieldsNameAndValue(Foods.class, FoodProperties.class).entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey().toLowerCase(),
entry -> () -> new Item(new Item.Properties().food(entry.getValue()))
)));

Utils.getStaticFinalFieldsNameAndValue(MobEffects.class, AutoRegistryObject.class)
.forEach((key, value) -> value.register(MOB_EFFECTS, key.toLowerCase()));

RegisteredItems.addAll(registeredFoods);

// Register the Deferred Register to the mod event bus so blocks get registered
BLOCKS.register(modEventBus);
// Register the Deferred Register to the mod event bus so items get registered
ITEMS.register(modEventBus);
MOB_EFFECTS.register(modEventBus);
// Register the Deferred Register to the mod event bus so tabs get registered
CREATIVE_MODE_TABS.register(modEventBus);

Expand Down Expand Up @@ -101,11 +122,11 @@ private void commonSetup(final FMLCommonSetupEvent event) {
}

// Add the example block item to the building blocks tab
private void addCreative(BuildCreativeModeTabContentsEvent event)
{
private void addCreative(BuildCreativeModeTabContentsEvent event) {
if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS)
event.accept(EXAMPLE_BLOCK_ITEM);
}

// You can use SubscribeEvent and let the Event Bus discover methods to call
@SubscribeEvent
public void onServerStarting(ServerStartingEvent event) {
Expand All @@ -118,8 +139,7 @@ public void onServerStarting(ServerStartingEvent event) {
public static class ClientModEvents {

@SubscribeEvent
public static void onClientSetup(FMLClientSetupEvent event)
{
public static void onClientSetup(FMLClientSetupEvent event) {
// Some client setup code
LOGGER.info("HELLO FROM CLIENT SETUP");
LOGGER.info("MINECRAFT NAME >> {}", Minecraft.getInstance().getUser().getName());
Expand Down
42 changes: 42 additions & 0 deletions src/main/java/com/gensokyo/nucleardelight/Utils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.gensokyo.nucleardelight;

import com.mojang.logging.LogUtils;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.RegistryObject;
import org.slf4j.Logger;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

public class Utils {
private static final Logger LOGGER = LogUtils.getLogger();

public static <T> Map<String, T> getStaticFinalFieldsNameAndValue(Class<?> clazz, Class<T> valueType) {
Map<String, T> staticFinalFieldsNameAndValue = new HashMap<>();
try {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers) && field.getType() == valueType) {
boolean accessible = field.canAccess(null);
field.setAccessible(true);
T value = (T) field.get(null);
field.setAccessible(accessible);

staticFinalFieldsNameAndValue.put(field.getName(), value);
}
}
} catch (IllegalAccessException e) {
LOGGER.error("Failed to access field", e);
}
return staticFinalFieldsNameAndValue;
}

public static <T> List<RegistryObject<T>> registryObjects(DeferredRegister<T> register, Map<String, Supplier<T>> idAndObjectPairs) {
return idAndObjectPairs.entrySet().stream().map(entry -> register.register(entry.getKey(), entry.getValue())).toList();
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
package com.gensokyo.nucleardelight.datagenerator;

import com.gensokyo.nucleardelight.NuclearDelight;
import net.minecraft.data.PackOutput;
import net.minecraft.world.item.Item;
import net.minecraftforge.common.data.ExistingFileHelper;
import net.minecraftforge.data.event.GatherDataEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.registries.RegistryObject;

import java.util.List;

@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)
public class DataGenerator {
@SubscribeEvent
public static void dataGen(GatherDataEvent event) {
// event.getGenerator().addProvider();
PackOutput packOutput = event.getGenerator().getPackOutput();
ExistingFileHelper existingFileHelper = event.getExistingFileHelper();

List<Item> items = NuclearDelight.RegisteredItems.stream().map(RegistryObject::get).toList();
event.getGenerator().addProvider(true, new SingleTextureItemModelGenerator(items, packOutput, existingFileHelper));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.gensokyo.nucleardelight.NuclearDelight;
import net.minecraft.data.PackOutput;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraftforge.client.model.generators.ItemModelProvider;
import net.minecraftforge.common.data.ExistingFileHelper;
Expand All @@ -19,7 +20,16 @@ public SingleTextureItemModelGenerator(Collection<Item> items, PackOutput output

@Override
protected void registerModels() {
items.forEach(item ->
singleTexture(item.getDescriptionId(), mcLoc("item/handheld"), "layer0", modLoc("item/" + item.getDescriptionId())));
items.stream().map(SingleTextureItemModelGenerator::getNameFromItem).forEach(itemName ->
singleTexture(itemName, new ResourceLocation("item/generated"), "layer0", modLoc("item/" + itemName)));
}

private static String getNameFromItem(Item item) {
return getNameFromDescriptionId(item.getDescriptionId());
}

private static String getNameFromDescriptionId(String descriptionId) {
String[] strings = descriptionId.split("\\.");
return strings[strings.length - 1];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.gensokyo.nucleardelight.register;

import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.RegistryObject;

import java.util.function.Supplier;

public class AutoRegistryObject<T> {
private final Supplier<T> supplier;
private RegistryObject<T> object;

public AutoRegistryObject(Supplier<T> supplier) {
this.supplier = supplier;
}

public void register(DeferredRegister<T> register, String name) {
object = register.register(name, supplier);
}

public T get() {
return object.get();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.gensokyo.nucleardelight.world.effect;

import com.gensokyo.nucleardelight.register.AutoRegistryObject;
import net.minecraft.world.effect.MobEffect;

public class MobEffects {
public static final AutoRegistryObject<MobEffect> VOMITING = new AutoRegistryObject<>(VomitingMobEffect::new);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.gensokyo.nucleardelight.world.effect;

import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectCategory;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.LivingEntity;
import org.jetbrains.annotations.NotNull;

public class VomitingMobEffect extends MobEffect {

protected VomitingMobEffect() {
super(MobEffectCategory.HARMFUL, 0xA6A03A);
}

@Override
public void applyEffectTick(@NotNull LivingEntity entity, int level) {
if (!entity.hasEffect(MobEffects.CONFUSION)) {
entity.addEffect(new MobEffectInstance(MobEffects.CONFUSION,
entity.getEffect(com.gensokyo.nucleardelight.world.effect.MobEffects.VOMITING.get()).getDuration(), 1));
}
}

@Override
public boolean isDurationEffectTick(int p_19455_, int p_19456_) {
return true;
}
}
54 changes: 3 additions & 51 deletions src/main/java/com/gensokyo/nucleardelight/world/food/Foods.java
Original file line number Diff line number Diff line change
@@ -1,64 +1,16 @@
package com.gensokyo.nucleardelight.world.food;

import com.gensokyo.nucleardelight.NuclearDelight;
import com.gensokyo.nucleardelight.world.effect.MobEffects;
import com.mojang.logging.LogUtils;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.food.FoodProperties;
import net.minecraft.world.item.Item;
import org.slf4j.Logger;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

public class Foods {
private static final Logger LOGGER = LogUtils.getLogger();

// public static List<Item> FOODS = List.of();
//
// public static List<Item> getFoods() {
// return FOODS;
// }

public static final FoodProperties EXAMPLE_FOOD = new FoodProperties.Builder().alwaysEat()
.effect(() -> new MobEffectInstance(MobEffects.REGENERATION, 100, 1), 1.0F)
public static final FoodProperties APPLE_JAM_JAR = new FoodProperties.Builder().alwaysEat()
.effect(() -> new MobEffectInstance(MobEffects.VOMITING.get(), 1000, 1), 1.0F)
.nutrition(1)
.saturationMod(2f).build();

public static void Initializing() {
LOGGER.debug("Initializing Foods");
try {
Class<?> clazz = Foods.class;
Field[] fields = clazz.getDeclaredFields();

Map<String, FoodProperties> staticFinalFoodProperties = new HashMap<>();

for (Field field : fields) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers) && field.getType() == FoodProperties.class) {
boolean accessible = field.canAccess(null);
field.setAccessible(true);
FoodProperties value = (FoodProperties) field.get(null);
field.setAccessible(accessible);

staticFinalFoodProperties.put(field.getName(), value);
}
}

// Print the names and values of the static final FoodProperties fields
for (Map.Entry<String, FoodProperties> entry : staticFinalFoodProperties.entrySet()) {
LOGGER.debug("Name: {}, Value: {}", entry.getKey(), entry.getValue());
String id = entry.getKey().toLowerCase();
Supplier<Item> getFoodItem = (()-> new Item((new Item.Properties()).food(entry.getValue())));

NuclearDelight.ITEMS.register(id, getFoodItem);
}
} catch (IllegalAccessException e) {
LOGGER.error("Failed to access field", e);
}
}
}

0 comments on commit 6cb6349

Please sign in to comment.