### Setup Forge Workspace for Eclipse Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/forgedev/index.md Run these Gradle commands in your cloned repository directory to set up your Eclipse workspace. ForgeGradle handles most of the setup. ```bash ./gradlew setup ./gradlew genEclipseRuns ``` -------------------------------- ### Top-Level Package Examples Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/gettingstarted/structuring.md Provides examples of deriving top-level packages from various unique identifiers like domains, subdomains, or email addresses. ```text Type | Value | Top-Level Package :---: | :---: | :---- Domain | example.com | `com.example` Subdomain | example.github.io | `io.github.example` Email | example@gmail.com | `com.gmail.example` ``` -------------------------------- ### Mod Lifecycle Events - FML Initialization Sequence Source: https://context7.com/minecraftforge/documentation/llms.txt Handles various Forge mod lifecycle events. Use `enqueueWork` for thread-safe operations within setup events. This example shows common setup, client-specific setup, inter-mod communication enqueueing, and processing inter-mod messages. ```java @Mod.EventBusSubscriber(modid = "mymod", bus = Bus.MOD) public class LifecycleHandler { @SubscribeEvent public static void onCommonSetup(FMLCommonSetupEvent event) { // Runs on all physical sides; parallel — use enqueueWork for thread-safety event.enqueueWork(() -> { ShapedRecipe.setCraftingSize(4, 4); // Expand crafting grid to 4x4 }); } @SubscribeEvent public static void onClientSetup(FMLClientSetupEvent event) { // Physical client only event.enqueueWork(() -> { ItemBlockRenderTypes.setRenderLayer( ModBlocks.EXAMPLE_BLOCK.get(), RenderType.cutout()); }); } @SubscribeEvent public static void onInterModEnqueue(InterModEnqueueEvent event) { // Send message to another mod InterModComms.sendTo("jei", "register_categories", () -> new MyJEIPlugin()); } @SubscribeEvent public static void onInterModProcess(InterModProcessEvent event) { // Process messages sent to this mod event.getIMCStream() .filter(msg -> msg.method().equals("register_thing")) .forEach(msg -> registerThing(msg.messageSupplier().get())); } private static void registerThing(Object thing) { /* ... */ } } ``` -------------------------------- ### Batch Game Tests with Setup and Teardown Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/misc/gametest.md Annotate methods with @BeforeBatch or @AfterBatch to perform setup and teardown for tests within a specified batch. The batch string must match the one supplied to the @GameTest annotation. Batch methods accept a ServerLevel parameter. ```java public class ExampleGameTests { @BeforeBatch(batch = "firstBatch") public static void beforeTest(ServerLevel level) { // Perform setup } @GameTest(batch = "firstBatch") public static void exampleTest2(GameTestHelper helper) { // Do stuff } } ``` -------------------------------- ### Access Transformer Syntax Examples Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/advanced/accesstransformers.md These examples demonstrate the syntax for Access Transformers, including targeting classes, fields, and methods with specific access modifiers and type descriptors. Comments are denoted by '#'. ```plaintext # Makes public the ByteArrayToKeyFunction interface in Crypt public net.minecraft.util.Crypt$ByteArrayToKeyFunction ``` ```plaintext # Makes protected and removes the final modifier from 'random' in MinecraftServer protected-f net.minecraft.server.MinecraftServer f_129758_ #random ``` ```plaintext # Makes public the 'makeExecutor' method in Util, # accepting a String and returns an ExecutorService public net.minecraft.Util m_137477_(Ljava/lang/String;)Ljava/util/concurrent/ExecutorService; #makeExecutor ``` ```plaintext # Makes public the 'leastMostToIntArray' method in UUIDUtil, # accepting two longs and returning an int[] public net.minecraft.core.UUIDUtil m_235872_(JJ)[I #leastMostToIntArray ``` -------------------------------- ### BlockLootSubProvider Constructor Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datagen/server/loottables.md Example of initializing a `BlockLootSubProvider`. It requires a set of explosion-resistant items and a `FeatureFlagSet` to determine block generation. ```java import net.minecraft.world.flag.FeatureFlagSet; import net.minecraft.world.level.storage.loot.BlockLootSubProvider; import java.util.Collections; // In some BlockLootSubProvider subclass public MyBlockLootSubProvider() { super(Collections.emptySet(), FeatureFlags.REGISTRY.allFlags()); } ``` -------------------------------- ### Dispatch Codec Setup Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datastorage/codecs.md Defines abstract and concrete classes for dispatchable objects, including methods to specify their type codec for registration. ```java // Define our object abstract class ExampleObject { // Define the method used to specify the object type for encoding public abstract Codec type(); } // Create simple object which stores a string public class StringObject extends ExampleObject { public StringObject(String s) { /* ... */ } public String s() { /* ... */ } public Codec type() { // A registered registry object // "string": // Codec.STRING.xmap(StringObject::new, StringObject::s) return STRING_OBJECT_CODEC.get(); } } // Create complex object which stores a string and integer public class ComplexObject extends ExampleObject { public ComplexObject(String s, int i) { /* ... */ } public String s() { /* ... */ } public int i() { /* ... */ } public Codec type() { // A registered registry object // "complex": // RecordCodecBuilder.create(instance -> // instance.group( // Codec.STRING.fieldOf("s").forGetter(ComplexObject::s), // Codec.INT.fieldOf("i").forGetter(ComplexObject::i) // ).apply(instance, ComplexObject::new) // ) return COMPLEX_OBJECT_CODEC.get(); } } // Assume there is an IForgeRegistry> DISPATCH public static final Codec = DISPATCH.getCodec() // Gets Codec> .dispatch( ExampleObject::type, // Get the codec from the specific object Function.identity() // Get the codec from the registry ); ``` -------------------------------- ### EntityLootSubProvider Constructor Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datagen/server/loottables.md Example of initializing an `EntityLootSubProvider`. It requires a `FeatureFlagSet` to determine entity type generation. ```java import net.minecraft.world.flag.FeatureFlagSet; import net.minecraft.world.level.storage.loot.EntityLootSubProvider; // In some EntityLootSubProvider subclass public MyEntityLootSubProvider() { super(FeatureFlags.REGISTRY.allFlags()); } ``` -------------------------------- ### Example Mod Configuration with Properties Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/gettingstarted/modfiles.md This TOML snippet demonstrates how to set various properties for a mod, including its ID, version, display name, description, and logo file. ```toml modId = "examplemod" namespace = "example" version = "1.21.1-1.0.0.0" displayName = "Example Mod" description = "This is an example." logoFile = "example_logo.png" logoBlur = false updateJSONURL = "https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json" features = { java_version = "17" } modproperties = { example = "value" } modUrl = "https://files.minecraftforge.net/" credits = "The person over here and there." authors = "Example Person" displayURL = "https://minecraftforge.net/" displayTest = "MATCH_VERSION" ``` -------------------------------- ### Class Naming Convention Examples Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/gettingstarted/structuring.md Demonstrates common suffixes used for class names to indicate their type, such as Item, Block, or Menu. ```text An `Item` called `PowerRing` -> `PowerRingItem`. * A `Block` called `NotDirt` -> `NotDirtBlock`. * A menu for an `Oven` -> `OvenMenu`. ``` -------------------------------- ### Example Recipe Implementation Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/resources/server/recipes/custom.md A basic record implementation of the Recipe interface. Ensure the Container passed to the recipe is treated as immutable; operate on a copy if modifications are needed. ```java public record ExampleRecipe(Ingredient input, int data, ItemStack output) implements Recipe { // Implement methods here } ``` -------------------------------- ### Define a Sound with Custom Properties Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datagen/client/sounds.md This example demonstrates how to define a sound using `this.add` and `definition()`. It shows how to set a subtitle, add multiple sounds with different weights and volumes, and stream a sound. The sound names are specified using `ResourceLocation`. ```java this.add(EXAMPLE_SOUND_EVENT, definition() .subtitle("sound.examplemod.example_sound") // Set translation key .with( sound(ResourceLocation.fromNamespaceAndPath(MODID, "example_sound_1")) // Set first sound .weight(4) // Has a 4 / 5 = 80% chance of playing .volume(0.5), // Scales all volumes called on this sound by half sound(ResourceLocation.fromNamespaceAndPath(MODID, "example_sound_2")) // Set second sound .stream() // Streams the sound ) ); ``` -------------------------------- ### Custom Tag Provider Constructor Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datagen/server/tags.md Example constructor for a custom tag provider, specifying the registry key for which tags will be generated. ```java import net.minecraft.core.registries.Registries; import net.minecraftforge.common.data.ExistingFileHelper; import net.minecraft.core.HolderLookup; import net.minecraft.data.PackOutput; public RecipeTypeTagsProvider(PackOutput output, CompletableFuture registries, ExistingFileHelper fileHelper) { super(output, Registries.RECIPE_TYPE, registries, MOD_ID, fileHelper); } ``` -------------------------------- ### Create a Custom Screen with Widgets Source: https://context7.com/minecraftforge/documentation/llms.txt Implement a custom screen by extending `Screen` or `AbstractContainerScreen`. Add widgets like `EditBox` and `Button` in the `init` method and handle rendering in the `render` method. This example shows a basic screen with a text input and a confirm button. ```java import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.components.EditBox; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.Component; public class MyScreen extends Screen { private EditBox nameField; public MyScreen() { super(Component.translatable("screen.mymod.my_screen")); } @Override protected void init() { super.init(); int centerX = this.width / 2; int centerY = this.height / 2; // Text input widget nameField = new EditBox(this.font, centerX - 75, centerY - 10, 150, 20, Component.translatable("label.mymod.name")); nameField.setMaxLength(32); this.addRenderableWidget(nameField); // Confirm button this.addRenderableWidget(Button.builder( Component.translatable("button.mymod.confirm"), btn -> onConfirm() ).bounds(centerX - 40, centerY + 20, 80, 20).build()); } private void onConfirm() { String name = nameField.getValue(); ModNetwork.CHANNEL.sendToServer(new SetNamePacket(name)); this.onClose(); } @Override public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) { this.renderBackground(graphics); // Dim background super.render(graphics, mouseX, mouseY, partialTick); // Widgets graphics.drawCenteredString(this.font, this.title, this.width / 2, this.height / 2 - 30, 0xFFFFFF); } @Override public boolean isPauseScreen() { return false; } } // Example of opening the screen from a key mapping handler (client side): // Minecraft.getInstance().setScreen(new MyScreen()); // Placeholder classes for compilation class ModNetwork { public static Object CHANNEL; } class SetNamePacket {} ``` -------------------------------- ### Package Naming Convention Example Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/gettingstarted/structuring.md Illustrates how unique top-level packages prevent class conflicts, especially in modular environments. Using a domain or subdomain ensures uniqueness. ```text a.jar - com.example.ExampleClass b.jar - com.example.ExampleClass // This class will not normally be loaded ``` ```text module A - package X - class I - class J module B - package X // This package will cause the mod loader to crash, as there already is a module with package X being exported - class R - class S - class T ``` -------------------------------- ### Implement Model Provider Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datagen/client/modelproviders.md Example of a model provider that generates all models and returns a CompletableFuture for writing files. This is useful for organizing complex datagen tasks. ```java public class ExampleModelConsumerProvider implements ModelProvider { private final ExampleMod example; public ExampleModelConsumerProvider(ExampleMod example) { this.example = example; } @Override public CompletableFuture run(CachedOutput cache) { // Populate the model provider CompletableFuture exampleFutures = this.example.generateAll(cache); // Generate the models // Run logic and create CompletableFuture(s) for writing files // ... // Assume we have a new CompletableFuture providerFuture return CompletableFuture.allOf(exampleFutures, providerFuture); } } ``` -------------------------------- ### Example Encoded SomeObject JSON Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datastorage/codecs.md Illustrates the JSON structure for an encoded SomeObject, showing both a complete object and one where an optional field is omitted. ```json { "s": "value", "i": 5, "b": false } ``` ```json { "s": "value2", // i is omitted, defaults to 0 "b": true } ``` -------------------------------- ### Legacy Metadata Example Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/blocks/states.md Illustrates the confusing nature of legacy metadata in Minecraft versions prior to 1.8, where block states were represented by raw numbers. ```Java switch (meta) { case 0: { ... } // south and on the lower half of the block case 1: { ... } // south on the upper side of the block case 2: { ... } // north and on the lower half of the block case 3: { ... } // north and on the upper half of the block // ... etc. ... } ``` -------------------------------- ### Specify Java Version Requirement Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/gettingstarted/modfiles.md Use the 'features' table to specify requirements, such as the Java version. This example requires Java version 17 or higher. ```toml features = { java_version = "[17,)" } ``` -------------------------------- ### Example Language File Structure Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/concepts/internationalization.md Define translations for your mod's elements in a JSON file. This structure maps translation keys to their corresponding displayable text. ```json { "item.examplemod.example_item": "Example Item Name", "block.examplemod.example_block": "Example Block Name", "commands.examplemod.examplecommand.error": "Example Command Errored!" } ``` -------------------------------- ### CompoundIngredient Example Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/resources/server/recipes/ingredients.md Compound ingredients function as an OR set, where the input stack must match at least one of the supplied ingredients. No type needs to be specified. ```js // For some input [ // At least one of these ingredients must match to succeed { // Ingredient }, { // Custom ingredient "type": "examplemod:example_ingredient" } ] ``` -------------------------------- ### Register Custom Display Test Extension Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/concepts/sides.md Register an `IExtensionPoint$DisplayTest` to define custom compatibility logic. This example allows the client to ignore the server version being absent, suitable for client- or server-only mods. ```java //Make sure the mod being absent on the other network side does not cause the client to display the server as incompatible ModLoadingContext.get().registerExtensionPoint(IExtensionPoint.DisplayTest.class, () -> new IExtensionPoint.DisplayTest(() -> NetworkConstants.IGNORESERVERONLY, (a, b) -> true)); ``` -------------------------------- ### Example mods.toml Configuration Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/gettingstarted/modfiles.md This TOML file defines the metadata for a Forge mod, including its ID, version, display name, update URL, and dependencies on Forge and Minecraft. It also specifies loader information and license. ```toml modLoader="javafml" loaderVersion="[52,)" license="All Rights Reserved" issueTrackerURL="https://github.com/MinecraftForge/MinecraftForge/issues" showAsResourcePack=false clientSideOnly=false [[mods]] modId="examplemod" version="1.0.0.0" displayName="Example Mod" updateJSONURL="https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json" displayURL="https://minecraftforge.net" logoFile="logo.png" credits="I'd like to thank my mother and father." authors="Author" description=''' Lets you craft dirt into diamonds. This is a traditional mod that has existed for eons. It is ancient. The holy Notch created it. Jeb rainbowfied it. Dinnerbone made it upside down. Etc. ''' displayTest="MATCH_VERSION" [[dependencies.examplemod]] modId="forge" mandatory=true versionRange="[52,)" ordering="NONE" side="BOTH" [[dependencies.examplemod]] modId="minecraft" mandatory=true versionRange="[1.21.1,)" ordering="NONE" side="BOTH" ``` -------------------------------- ### DistExecutor Usage Examples Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/concepts/sides.md Demonstrates how to use DistExecutor to run or call methods on specific physical sides. Use unsafe variants in development environments due to Java 9+ invokedynamic changes. ```java public static void unsafeRunMethodExample(Object param1, Object param2) { // ... } public static Object safeCallMethodExample() { // ... } // In some common class DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> ExampleClass.unsafeRunMethodExample(var1, var2)); DistExecutor.safeCallWhenOn(Dist.CLIENT, () -> ExampleClass::safeCallMethodExample); ``` -------------------------------- ### PartialNBTIngredient Example Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/resources/server/recipes/ingredients.md PartialNBTIngredients offer a looser NBT comparison, checking only specified keys within the share tag. Use type forge:partial_nbt and specify either 'item' or 'items'. ```js // For some input { "type": "forge:partial_nbt", // Either 'item' or 'items' must be specified // If both are specified, only 'item' will be read "item": "examplemod:example_item", "items": [ "examplemod:example_item", "examplemod:example_item2" // ... ], "nbt": { // Checks only for equivalency on 'key1' and 'key2' // All other keys in the stack will not be checked "key1": "data1", "key2": { // Data 2 } } } ``` -------------------------------- ### Run Client Configuration Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/gettingstarted/index.md Use gradlew run* commands for various configurations like runClient, runServer, runData, or runGameTestServer. ```gradle gradlew runClient ``` -------------------------------- ### Rotation Specification: Single Axis Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/rendering/modelextensions/transforms.md Example of specifying rotation around a single axis using a degree mapping. ```json { "x": 90 } ``` -------------------------------- ### Creating a KeyMapping with Keyboard Input Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/misc/keymappings.md Create a `KeyMapping` with a default keyboard input. Use `InputConstants.Type.KEYSYM` for broad compatibility and `GLFW` key tokens. ```java new KeyMapping( "key.examplemod.example1", // Will be localized using this translation key InputConstants.Type.KEYSYM, // Default mapping is on the keyboard GLFW.GLFW_KEY_P, // Default key is P "key.categories.misc" // Mapping will be in the misc category ) ``` -------------------------------- ### StrictNBTIngredient Example Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/resources/server/recipes/ingredients.md StrictNBTIngredients compare item, damage, and share tags for exact equivalency. Specify the type as forge:nbt. ```js // For some input { "type": "forge:nbt", "item": "examplemod:example_item", "nbt": { // Add nbt data (must match exactly what is on the stack) } } ``` -------------------------------- ### AttributeTagsProvider Constructor Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datagen/server/tags.md Example of a constructor for an AttributeTagsProvider, a subtype of IntrinsicHolderTagsProvider. It demonstrates how to provide a function to map an attribute object to its ResourceKey. ```java public AttributeTagsProvider(PackOutput output, CompletableFuture registries, ExistingFileHelper fileHelper) { super( output, ForgeRegistries.Keys.ATTRIBUTES, registries, attribute -> ForgeRegistries.ATTRIBUTES.getResourceKey(attribute).get(), MOD_ID, fileHelper ); } ``` -------------------------------- ### Configure ExampleConfig Class Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/misc/config.md This pattern is typically used with a `static` block and a class that accepts `ForgeConfigSpec.Builder` in its constructor to attach and hold config values. The `configure` method creates a pair of the config class and the spec. ```java static { Pair pair = new ForgeConfigSpec.Builder() .configure(ExampleConfig::new); // Store pair values in some constant field } ``` -------------------------------- ### DirectionProperty Creation (Cardinal) Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/blocks/states.md Provides an example of creating a `DirectionProperty` specifically for cardinal directions (North, South, East, West). ```Java DirectionProperty.create("", Direction.Plane.HORIZONTAL) ``` -------------------------------- ### Create a SimpleChannel Instance Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/networking/simpleimpl.md Instantiate a SimpleChannel for custom network communication. Ensure the protocol version and compatibility checkers are correctly defined. The compatibility checkers determine if the client and server versions are compatible. ```java private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel( ResourceLocation.fromNamespaceAndPath("mymodid", "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); ``` -------------------------------- ### IntersectionIngredient Example Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/resources/server/recipes/ingredients.md IntersectionIngredients function as an AND set, requiring the input stack to match all supplied ingredients. Requires at least two children. ```js // For some input { "type": "forge:intersection", // All of these ingredients must return true to succeed "children": [ { // Ingredient 1 }, { // Ingredient 2 } // ... ] } ``` -------------------------------- ### Rotation Specification: Quaternion Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/rendering/modelextensions/transforms.md Example of specifying rotation directly using a quaternion represented as an array of 4 floating point values. ```json [ 0.38268346, 0, 0, 0.9238795 ] ``` -------------------------------- ### Ambient Occlusion Override Example Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/rendering/modelextensions/facedata.md Illustrates that element-level 'ambient_occlusion: true' has no effect if the top-level 'ambientocclusion' flag in the model is set to false. ```js { "ambientocclusion": false, "elements": [ { "forge_data": { "ambient_occlusion": true // Has no effect } } ] } ``` -------------------------------- ### Encoded Pair JSON Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datastorage/codecs.md Example JSON structure for an encoded Pair object, showing how fieldOf maps keys. ```json // Encoded Pair { "left": 5, // fieldOf looks up 'left' key for left object "right": "value" // fieldOf looks up 'right' key for right object } ``` -------------------------------- ### Implement quickMoveStack for Menus Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/gui/menus.md Implement this method to handle shift-clicking or quick moving of item stacks within a menu. It manages moving stacks between the player inventory, hotbar, and the menu's slots. ```java @Override public ItemStack quickMoveStack(Player player, int quickMovedSlotIndex) { // The quick moved slot stack ItemStack quickMovedStack = ItemStack.EMPTY; // The quick moved slot Slot quickMovedSlot = this.slots.get(quickMovedSlotIndex) // If the slot is in the valid range and the slot is not empty if (quickMovedSlot != null && quickMovedSlot.hasItem()) { // Get the raw stack to move ItemStack rawStack = quickMovedSlot.getItem(); // Set the slot stack to a copy of the raw stack quickMovedStack = rawStack.copy(); /* The following quick move logic can be simplified to if in data inventory, try to move to player inventory/hotbar and vice versa for containers that cannot transform data (e.g. chests). */ // If the quick move was performed on the data inventory result slot if (quickMovedSlotIndex == 0) { // Try to move the result slot into the player inventory/hotbar if (!this.moveItemStackTo(rawStack, 5, 41, true)) { // If cannot move, no longer quick move return ItemStack.EMPTY; } // Perform logic on result slot quick move slot.onQuickCraft(rawStack, quickMovedStack); } // Else if the quick move was performed on the player inventory or hotbar slot else if (quickMovedSlotIndex >= 5 && quickMovedSlotIndex < 41) { // Try to move the inventory/hotbar slot into the data inventory input slots if (!this.moveItemStackTo(rawStack, 1, 5, false)) { // If cannot move and in player inventory slot, try to move to hotbar if (quickMovedSlotIndex < 32) { if (!this.moveItemStackTo(rawStack, 32, 41, false)) { // If cannot move, no longer quick move return ItemStack.EMPTY; } } // Else try to move hotbar into player inventory slot else if (!this.moveItemStackTo(rawStack, 5, 32, false)) { // If cannot move, no longer quick move return ItemStack.EMPTY; } } } // Else if the quick move was performed on the data inventory input slots, try to move to player inventory/hotbar else if (!this.moveItemStackTo(rawStack, 5, 41, false)) { // If cannot move, no longer quick move return ItemStack.EMPTY; } if (rawStack.isEmpty()) { // If the raw stack has completely moved out of the slot, set the slot to the empty stack quickMovedSlot.set(ItemStack.EMPTY); } else { // Otherwise, notify the slot that that the stack count has changed quickMovedSlot.setChanged(); } /* The following if statement and Slot#onTake call can be removed if the menu does not represent a container that can transform stacks (e.g. chests). */ if (rawStack.getCount() == quickMovedStack.getCount()) { // If the raw stack was not able to be moved to another slot, no longer quick move return ItemStack.EMPTY; } // Execute logic on what to do post move with the remaining stack quickMovedSlot.onTake(player, rawStack); } return quickMovedStack; // Return the slot stack } ``` -------------------------------- ### Creating a KeyMapping with Mouse Input and GUI Context Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/misc/keymappings.md Create a `KeyMapping` that is only active within GUI screens and uses a default mouse input. Custom categories can be defined using translation keys that include the mod ID. ```java new KeyMapping( "key.examplemod.example2", KeyConflictContext.GUI, // Mapping can only be used when a screen is open InputConstants.Type.MOUSE, // Default mapping is on the mouse GLFW.GLFW_MOUSE_BUTTON_LEFT, // Default mouse input is the left mouse button "key.categories.examplemod.examplecategory" // Mapping will be in the new example category ) ``` -------------------------------- ### Rotation Specification: Multiple Axes Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/rendering/modelextensions/transforms.md Example of specifying multiple rotations around different axes in an array. Rotations are applied in the order they appear. ```json [ { "x": 90 }, { "y": 45 }, { "x": -22.5 } ] ``` -------------------------------- ### Screen Initialization Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/gui/screens.md The init method is called upon screen initialization and re-initialization (e.g., on window resize). Use it to add widgets and precompute values. ```java @Override protected void init() { super.init(); // Add widgets and precomputed values this.addRenderableWidget(new EditBox(/* ... */)); } ``` -------------------------------- ### Create Shapeless Recipe with ShapelessRecipeBuilder Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datagen/server/recipes.md Use `ShapelessRecipeBuilder` to define shapeless recipes. Add required ingredients, specify unlock criteria, and save the recipe. ```java ShapelessRecipeBuilder builder = ShapelessRecipeBuilder.shapeless(RecipeCategory.MISC, result) .requires(item) // Add item to the recipe .unlockedBy("criteria", criteria) // How the recipe is unlocked .save(writer); // Add data to builder ``` -------------------------------- ### Using RecipeWrapper with IItemHandler Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/resources/server/recipes/index.md Demonstrates how to wrap an IItemHandler with RecipeWrapper to pass it to RecipeManager methods that expect a Container. This is useful for integrating custom inventory systems with the vanilla recipe system. ```java // Within some method with IItemHandlerModifiable handler recipeManger.getRecipeFor(RecipeType.CRAFTING, new RecipeWrapper(handler), level); ``` -------------------------------- ### Implementing a Custom LootTableSubProvider Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datagen/server/loottables.md This is a basic implementation of a LootTableSubProvider. The `generate` method is where you will define your loot tables by calling the provided writer. ```java import java.util.function.BiConsumer; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.storage.loot.LootTable; import net.minecraft.world.level.storage.loot.LootContext; public class ExampleSubProvider implements LootTableSubProvider { // Used to create a factory method for the wrapping Supplier public ExampleSubProvider() {} // The method used to generate the loot tables @Override public void generate(BiConsumer writer) { // Generate loot tables here by calling writer#accept } } ``` -------------------------------- ### Encoded Either JSON Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datastorage/codecs.md Example JSON structures for encoded Either objects, showing distinct representations for Left and Right types. ```json // Encoded Either$Left 5 // Encoded Either$Right "value" ``` -------------------------------- ### ParticleDescription JSON Example Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/gameeffects/particles.md Defines the textures used by a particle. The 'textures' array lists ResourceLocations pointing to PNG files in assets//textures/particle/. ```json { "textures": [ // Will point to a texture located in // assets/mymod/textures/particle/particle_texture.png "mymod:particle_texture", // Textures should by ordered by drawing order // e.g. particle_texture will render first, then particle_texture2 // after some time "mymod:particle_texture2" ] } ``` -------------------------------- ### Registering an ExampleConditionSerializer Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/resources/server/conditional.md Declare a static instance of your serializer and register it using CraftingHelper#register. This can be done during the RegisterEvent for RecipeSerializers or during FMLCommonSetupEvent. ```java public static final ExampleConditionSerializer INSTANCE = new ExampleConditionSerializer(); ``` ```java public void registerSerializers(RegisterEvent event) { event.register(ForgeRegistries.Keys.RECIPE_SERIALIZERS, helper -> CraftingHelper.register(INSTANCE) ); } ``` -------------------------------- ### Register a BlockEntityType with Builder Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/concepts/registries.md Register BlockEntityType objects using their respective Builder classes. This example shows how to create a BlockEntityType for a custom block entity. ```java public static final RegistryObject> EXAMPLE_BLOCK_ENTITY = REGISTER.register( "example_block_entity", () -> BlockEntityType.Builder.of(ExampleBlockEntity::new, EXAMPLE_BLOCK.get()).build(null) ); ``` -------------------------------- ### Registering and Looking Up Datapack Registry Objects Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datagen/server/datapackregistries.md This snippet demonstrates how to define resource keys for registry objects and then use `BootstrapContext#lookup` to retrieve a `HolderGetter`. This is useful when one registry object depends on another, such as a `PlacedFeature` depending on a `ConfiguredFeature`. ```java public static final ResourceKey> EXAMPLE_CONFIGURED_FEATURE = ResourceKey.create( Registries.CONFIGURED_FEATURE, ResourceLocation.fromNamespaceAndPath(MOD_ID, "example_configured_feature") ); public static final ResourceKey EXAMPLE_PLACED_FEATURE = ResourceKey.create( Registries.PLACED_FEATURE, ResourceLocation.fromNamespaceAndPath(MOD_ID, "example_placed_feature") ); // In some constant location or argument new RegistrySetBuilder() // Create configured features .add(Registries.CONFIGURED_FEATURE, bootstrap -> { // Register configured features here bootstrap.register( // The resource key for the configured feature EXAMPLE_CONFIGURED_FEATURE, new ConfiguredFeature(/* ... */) ); }) // Create placed features .add(Registries.PLACED_FEATURE, bootstrap -> { // Register placed features here // Get configured feature registry HolderGetter> configured = bootstrap.lookup(Registries.CONFIGURED_FEATURE); bootstrap.register( // The resource key for the placed feature EXAMPLE_PLACED_FEATURE, new PlacedFeature( configured.getOrThrow(EXAMPLE_CONFIGURED_FEATURE), // Get the configured feature List.of() // and do nothing to the placement location ) ) }); ``` -------------------------------- ### Open Menu with SimpleMenuProvider Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/gui/menus.md Use `SimpleMenuProvider` to easily create a `MenuProvider` for opening a custom menu. This is typically called on the server side. ```java serverPlayer.openMenu(new SimpleMenuProvider( (containerId, playerInventory, player) -> new MyMenu(containerId, playerInventory), Component.translatable("menu.title.examplemod.mymenu") )); ``` -------------------------------- ### Add a Global Loot Modifier Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datagen/server/glm.md Implement the start method in your GlobalLootModifierProvider to add GLMs. Specify the modifier name, conditions, and the modifier instance to be serialized. ```java // In some GlobalLootModifierProvider#start this.add("example_modifier", new ExampleModifier( new LootItemCondition[] { WeatherCheck.weather().setRaining(true).build() // Executes when raining }, "val1", 10, Items.DIRT )); ``` -------------------------------- ### Create and Load Saved Data Instance Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datastorage/saveddata.md Demonstrates how to create and load a custom SavedData instance using `computeIfAbsent`. The `create` method supplies a new instance, and `load` populates it with NBT data. This is typically called on a `DimensionDataStorage`. ```java public ExampleSavedData create() { return new ExampleSavedData(); } public ExampleSavedData load(CompoundTag tag) { ExampleSavedData data = this.create(); // Load saved data return data; } // In some method within the class netherDataStorage.computeIfAbsent(this::load, this::create, "example"); ``` -------------------------------- ### Item Translation Key Example Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/concepts/internationalization.md Specify the translation key for an item's name. This key is used in language files to provide the localized display name. ```json { "item.examplemod.example_item": "Example Item Name" } ``` -------------------------------- ### Getting Relative Position Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/misc/gametest.md Use the /test pos command to obtain the relative coordinates of a block within a structure template. This is useful for precise placement in tests. ```bash /test pos # Exports 'final BlockPos = new BlockPos(...);' ``` -------------------------------- ### IntegerProperty Creation Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/blocks/states.md Demonstrates how to create an `IntegerProperty` for blocks that require an integer value within a specified range. ```Java IntegerProperty.create("property_name", minimum, maximum) ``` -------------------------------- ### DifferenceIngredient Example Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/resources/server/recipes/ingredients.md DifferenceIngredients implement set subtraction (SUB), where the input stack must match the base ingredient but not the subtracted ingredient. Use type forge:difference. ```js // For some input { "type": "forge:difference", "base": { // Ingredient the stack is in }, "subtracted": { // Ingredient the stack is NOT in } } ``` -------------------------------- ### Create Cooking Recipe with SimpleCookingRecipeBuilder Source: https://github.com/minecraftforge/documentation/blob/1.21.x/docs/datagen/server/recipes.md Use `SimpleCookingRecipeBuilder` to generate smelting, blasting, smoking, or campfire cooking recipes. Specify input, output, experience, cooking time, unlock criteria, and save. ```java SimpleCookingRecipeBuilder builder = SimpleCookingRecipeBuilder.smelting(input, RecipeCategory.MISC, result, experience, cookingTime) .unlockedBy("criteria", criteria) // How the recipe is unlocked .save(writer); // Add data to builder ```