English | 简体中文
A copy-and-rename starting point for FarmersDelight addons, with a fully commented example plugin.
A minimal, fully-commented starting point for building your own addon on top of the FarmersDelight (CraftEngine) plugin. Copy this folder, rename the namespace, and replace the example content.
CraftEngine ── defines custom items / blocks / furniture / models / recipes from YAML
FarmersDelight ── server-side gameplay + a stable public API (com.huidu.farmersdelight.api.**)
Your addon ── bundles CraftEngine YAML + Java glue that calls the FarmersDelight api
Three pieces, three responsibilities:
- CraftEngine YAML (
src/main/resources/craftengine/<namespace>/) — your items, blocks, food blocks, recipes, GUIs, images, translations.CraftEngineResourcescopies these intoplugins/CraftEngine/resources/<namespace>/on first load (install-if-missing). - FarmersDelight API (
FarmersDelightApi) — the things CraftEngine can't do alone: cooking-pot / cutting-board recipes, the in-game recipe book, Folia-safe scheduling, heat-source queries, crafting XP. - Your Java — gameplay glue. See
FDAddonTemplate.java.
FarmersDelight is not obfuscated: the plugin ships as a single open-source build, so the reason to stay
inside com.huidu.farmersdelight.api.** is the boundary itself, not renamed classes.
- Reference only
com.huidu.farmersdelight.api.**from your addon. Never import FD internals (managers, GUIs, util): the api jar you compile against contains nothing else, so an internal import does not even compile, and the internals are free to change in any release — nothing tests them for addons. - Audit with:
grep -rn "com.huidu.farmersdelight" src→ every hit must be…api…. - CraftEngine and Paper classes are fine to use directly (separate projects with their own stability rules).
-
The FarmersDelight API is a normal dependency declared in
settings.gradle.kts(com.huidu.farmersdelight:farmersdelight-plugin:<version>), with two channels:- Local checkout (preferred). Check out the FarmersDelight repository as a sibling directory
(
../FarmersDelight). The project is then a Gradle composite build:settings.gradle.ktsincludes it, sogradlewbuilds its:apiJarand substitutes it for the coordinate. No fetch, works offline. - No checkout. Without that sibling, Gradle falls back to a source dependency on
https://github.com/IOVEYOUMC0/Farmersdelight-Plugin.git, checked out at the pinned version, built in place and resolved the same way. This channel needs network access and a published version tag. - No checkout, no tag yet. Run
FarmersDelight/gradlew publishToMavenLocalonce and this build resolves the api jar from~/.m2;settings.gradle.ktsskips the Git source-dependency repository when that local jar exists. This is the bootstrap path while the pinned tag is not published.
Either way the artifact is the api-only jar: it contains ONLY
com.huidu.farmersdelight.api.**— no FD internals, not a runnable plugin — and the real FarmersDelight plugin provides the implementation at runtime. Nothing has to be vendored underlibs/any more. - Local checkout (preferred). Check out the FarmersDelight repository as a sibling directory
(
-
./gradlew build(orshadowJar) →build/libs/fdaddontemplate-1.2.0.jar. -
Drop the jar in
plugins/next to FarmersDelight + CraftEngine. This plugin usespaper-plugin.yml, whosedependencies.serverentries (CraftEngineandFarmersDelight, bothload: BEFORE,required: true,join-classpath: true) ensure load order and classpath access.
Compiling against a CraftEngine snapshot. 26.10 and 26.11 snapshots are not published to Maven, so point
the build at a local CraftEngine plugin jar instead of the ceVersion artifacts:
./gradlew build -PceJar=/path/to/craft-engine-paper-plugin-26.11-SNAPSHOT.jar
# plus this when that build keeps relocated libraries outside the jar:
# -PceLibraries=/path/to/plugins/CraftEngine/libsThe plugin jar already contains the bukkit and core classes, so it replaces both Maven artifacts. -PceVersion
still selects a Maven release for ordinary builds. Inside the FarmersDelight workspace the property also reaches
the sibling FarmersDelight composite build, which needs -PceLibraries as well (as shown above).
Current API/build checks: verification.
Get the singleton with FarmersDelightApi.get(). Guard every call with isAvailable().
| Method | Purpose |
|---|---|
isAvailable() / isFolia() |
FD present+enabled / running on Folia |
apiVersion() / hasFeature(String) |
version + feature gating (see Versioning) |
registerRecipeType(RecipeType) / unregisterRecipeType(id) |
add your recipes to FD's recipe book |
recipeTypes() / recipeType(id) |
query registered types |
registerCookingPotRecipe(id, ingredients, container, result, exp, cookTime, category) |
real cooking-pot recipe; survives /fd reload |
registerCuttingBoardRecipe(id, input, tool, results, sound) |
real cutting-board recipe |
unregisterCookingPotRecipe(id) / unregisterCuttingBoardRecipe(id) |
remove the above |
openRecipeBook(player) / openRecipeBook(player, filler) |
open FD's shared recipe book (filler adds a "Fill" button) |
openRecipeBook(player, typeId, filler) |
open an independent book for just your type (uses its own layout; never a shared menu) |
openRecipeEditor(player, typeId, recipeId) |
open the editor for an editable type |
isHeatSource(block) / isConductor(block) |
heat-source queries for your cooking blocks |
runAtLocation(loc, task) / runLaterAtLocation(loc, task, ticks) / runRepeating(task, delay, period) |
Folia-safe scheduling (repeating returns an ApiTask) |
awardCraftingExperience(player, loc, result, baseExp, source) |
Configured vanilla / CE Leveler XP + ProfessionCookingExperienceEvent |
isAvailable() answers "is FarmersDelight running". apiVersion() / hasFeature(String) answer "does this
FD build expose the surface I compiled against" — gate on these, not on the plugin's version string (the api
version tracks the addon-facing surface; the plugin version tracks content). apiVersion() is a monotonic
revision, bumped by +1 on every additive release and never decremented; nothing is ever removed, so an addon
compiled against revision N keeps linking against every later revision. hasFeature(id) is the direct probe
for a single capability ("station-query", "harvest-event", "cook-start-event", "buff-change-event",
"cooking-experience-location", "knife-drop-rules", "compat-util", "recipes", "item-displays",
"scheduler", "buffs", "debug-tools"); an unknown/null id returns false.
On a build older than the one that introduced these methods the call throws NoSuchMethodError — catch it and
treat it as revision 0. FDAddonTemplate.onEnable() shows the pattern:
int apiVersion;
try {
apiVersion = FarmersDelightApi.get().apiVersion();
} catch (NoSuchMethodError pre) {
apiVersion = 0; // pre-versioning FD build
}
boolean hasStationQuery = apiVersion >= 1 && FarmersDelightApi.get().hasFeature("station-query");Helper + event classes (also under api.**):
api.item.FarmersDelightItems—idOf/create/matchesId/matchesTag/displayNameOf/idsOf/tagIdsOf/isCustomItem/customIdOf/craftingRemainderOf/applyDisplay/buildIcon. CraftEngine-aware; use instead of rawMaterialchecks (the display helpers are covered under "More API surface").api.recipe.*—RecipeType,ViewableRecipe,RecipeFiller,RecipeEditor,EditableRecipe,NumericField,JumpTarget,IngredientMatching,RecipeBookLayout(give your type its own book layout — seeExampleRecipeType), and read-onlyFarmersDelightRecipes(query FD's own cooking-pot/cutting-board recipes).- Independent recipe book: override
RecipeType.listLayout()/detailLayout()to return aRecipeBookLayout(title + grid + decoration items, built from your own gui.yml; titles may carry CraftEngine<image:>/<shift:>for custom-texture backgrounds).ViewableRecipe.displaySlots()maps custom roles (e.g.fluid,tool) to extra detail slots, andjumpTargets()makes such a slot clickable. Open withopenRecipeBook(player, typeId, filler). Return null from the layouts to fall back to FD's shared book. - Editable type: override
RecipeType.editor()to return aRecipeEditor(item-slot labels +NumericFields) so admins edit recipes through FD's editor GUI — seerecipe/ExampleRecipeEditor. ARecipeFiller(seerecipe/ExampleRecipeFiller, matching withIngredientMatching) adds the "Fill" button. - Fill feedback: a
RecipeFillermay overridefillDetailed(player, recipe, fillAll)to return aFillOutcome(FILLED/MISSING_INGREDIENTS/INVENTORY_FULL/NOTHING) so the book mirrors the cooking pot's fill-button states;fillAlldistinguishes a shift-click (whole recipe) from a single-click (one of each). The default adapts the booleanfill(...), so a legacy filler still works — only without the richer states. OnlyFILLEDshould reopen the station GUI; the others stay on the book so the feedback stays visible.
- Independent recipe book: override
api.buff.*—CustomBuff+CustomBuffRegistry+BuffBossbar: a persistent addon buff that FD's milk-cure listener and its join/quit persistence lifecycle drive, with a per-player boss-bar readout on FD's channel. Seebuff/ExampleCustomBuff+buff/ExampleBuffBossbar.- Packet item displays —
FarmersDelightApi.createItemDisplay/updateItemDisplay/removeItemDisplay: floating items shown to nearby players with no real entity. Keep the returned int handles, recreate on chunk load, and report them onFarmersDelightCollectLiveDisplaysEventso/fd cleanupkeeps them. Seedisplay/ExampleItemDisplayManager. api.scheduler.ApiTask— cancel handle for repeating tasks.api.event.*—FarmersDelightReloadEvent,FarmersDelightProduceEvent,ProfessionCookingExperienceEvent, the gameplay notificationsFarmersDelightCookStartEvent(idle→cooking edge, counterpart to ProduceEvent),FarmersDelightHarvestEvent(mushroom-colony / rice Java harvests),FarmersDelightBuffChangeEvent(real custom-buff level transitions, not refreshes) andFarmersDelightRecipeDiscoveryEvent(per-player recipe lock/unlock transitions), plus the admin / lifecycle bridgesFarmersDelightCleanupEvent,FarmersDelightMigrateEvent,FarmersDelightWarmupEventandFarmersDelightCollectLiveDisplaysEvent— seelistener/ExampleFarmersDelightEventsListener(and the display manager for collect-live-displays). None are cancellable: they are notifications, and vetoing belongs upstream (harvest vetoes belong to the protection layer FarmersDelight already consults).api.util.*—PluginManagerGuard(blocks a live PlugMan reload/unload of your plugin; register it in onEnable),TooltipUtils.hideDurabilityLine(hide the durability line when an item's damage encodes a meter — seeutil/ExampleTooltipCustomizer), and the cross-version shimsCompatAttributes(resolvesMAX_HEALTH/ATTACK_SPEEDacross the 1.21.2 attribute-registry rename — null-check the constant beforegetAttribute) andCompatItemMeta(setItemModel/isSupported, applying theitem_modelcomponent on 1.21.5+, which is the supported floor). Use these shared shims instead of keeping your own copy.api.config.*—ConfigFileUpdater+ConfigUpdatePolicy+ConfigUpdateReport+ConfigKeyRename: keep theconfig.ymlan operator already has in step with the one your build ships (covered under "More API surface").
More API surface (text, items, effects, config updates, advancements, recipe queries, discovery, blocks, knife drops)
All under com.huidu.farmersdelight.api.**. Guard with FarmersDelightApi.get().isAvailable() (advancements also have their own FarmersDelightAdvancements.isAvailable()). FDAddonTemplate.java has runnable examples: foodEffects, advancements, recipeQueries, textAndMessages, recipeDiscovery.
render turns a template into a Component per viewer: {key} placeholders → <l10n:key> / <lang:key> translation tags (viewer locale) → CraftEngine <image:ns:id> / <shift:N> glyphs → MiniMessage + legacy & colors.
Component c = FarmersDelightText.render("<green>Hi {name}!", player, Map.of("name", player.getName()));
List<Component> lore = FarmersDelightText.buildLore(List.of("<gray>Line"), player, Map.of()); // italic stripped
Component glyph = FarmersDelightText.glyph("ns:icon_id"); // a single CraftEngine image glyph
FarmersDelightMessages.send(player, "<gold>Saved");
FarmersDelightMessages.actionBar(player, "<gray>{n} left", Map.of("n", "3"));
FarmersDelightMessages.title(player, "<aqua>Title", "<gray>Subtitle", 10, 40, 10, Map.of());Threading: messages and food effects touch the player — call them on the player's owning thread (main on Paper, the player's region thread on Folia), never from an async task.
isCustomItem / customIdOf / craftingRemainderOf, plus item-display builders that share FD's renderer (l10n tags + glyphs + colors, italic stripped):
FarmersDelightItems.applyDisplay(item, "<gold>Name", List.of("<gray>Lore"), player, Map.of());
ItemStack icon = FarmersDelightItems.buildIcon("ns:id", "<gold>Name", List.of("<gray>Lore"), player, Map.of());FarmersDelight's Comfort (slow regen while unsaturated) and Nourishment (suppress exhaustion):
FarmersDelightFoodEffects.applyComfort(player, 600); // seconds
FarmersDelightFoodEffects.registerComfortFood("ns:food", 600); // eating ns:food grants it; survives /fd reload
boolean has = FarmersDelightFoodEffects.hasNourishment(player);For more than a handful of foods, drive the mapping from your own config.yml instead of hard-coding ids
in Java — admins can tune it, your reload listener picks it up, and the pattern stays the same for any
addon. The template ships this helper:
util/ExampleFoodEffectRegistrar
(mirrors BrewinAndChewin's production FoodEffectRegistrar) — hold one per plugin, call
apply(getConfig().getConfigurationSection("food-effects")) on enable + reload, clear() on disable. It
parses each effect key as a list of id/duration entries (durations in seconds), matching the
shipped config.yml:
food-effects:
comfort:
- id: "myaddon:warm_tea"
duration: 60 # seconds
nourishment:
- id: "myaddon:hearty_stew"
duration: 300 # secondsBukkit's saveDefaultConfig() writes the bundled file only when none exists. It never adds a key to a
file that is already there, so every setting you add in a later version stays absent on a server that has
been running since before that version, and the feature behind it silently reads its hardcoded fallback
forever. Moving or dropping a setting is worse: the operator's tuned value is left sitting at a path
nothing reads.
ConfigFileUpdater fixes that. It renames paths that moved, deletes paths nothing reads any more, and
fills in settings a later version introduced — leaving every value the operator set exactly as it was. The
machinery is generic; what to rename, retire and protect is your data, supplied as a ConfigUpdatePolicy.
Use updateMainConfig(plugin, policy). It performs the whole ordered sequence and writes the file back,
and the order is load-bearing:
- Renames first. A rename is skipped when the new path is already set. Merging first would plant the bundled default at the new path, make every rename a no-op, and silently drop the value the operator had tuned under the old name.
- Retired keys next — after a rename has carried a value to its current path, and before the merge, so a setting nothing reads is not written back in.
- The additive merge last. Existing values are never overwritten; only genuinely absent keys are added, together with the comment that documents them.
Nothing is written when nothing changed, and a timestamped copy of the file is taken before the rewrite (the same pass that adds settings also deletes values the operator wrote).
Registry sections. A registry section is one whose children are content keyed by id rather than fixed
settings — a food list, a drop table, a per-item override map. Deleting an entry there is the operator's way
of disabling that item, so the merge must never add entries back one at a time or it silently undoes their
decision. Declare them with registrySection(...) and the merge will only create such a section when the
operator's file has none of it at all, never touching individual entries afterwards. Everything not declared
is treated as a plain setting and merged key by key.
The api never logs. It returns a ConfigUpdateReport and you say what happened, in your own wording and
your own language files. A backup that could not be written is reported on report.backupError() rather than
thrown — the update still goes ahead, and it is up to you whether the operator hears that they lost the
safety net.
The template ships this as util/ExampleConfigBootstrap,
modelled on BrewinAndChewin's production BrewinConfigBootstrap; FDAddonTemplate.onEnable() calls
configBootstrap.updateConfig() right after saveDefaultConfig() and before reading any value. The shape:
import com.huidu.farmersdelight.api.config.ConfigFileUpdater;
import com.huidu.farmersdelight.api.config.ConfigKeyRename;
import com.huidu.farmersdelight.api.config.ConfigUpdatePolicy;
import com.huidu.farmersdelight.api.config.ConfigUpdateReport;
import org.bukkit.plugin.java.JavaPlugin;
public final class MyAddonConfigBootstrap {
private static final ConfigUpdatePolicy POLICY = ConfigUpdatePolicy.builder()
// Old path -> new path, applied in the order added, so two entries can chain.
.migrate("tipsy.max-points", "tipsy.max-duration-seconds")
// Deleted from the operator's file because no code reads it any more.
.retire("legacy.fade-warning-ticks")
// Keyed by item id: a deleted entry means the operator turned that item off.
.registrySection("food-effects.comfort", "food-effects.nourishment")
.build();
private final JavaPlugin plugin;
public MyAddonConfigBootstrap(JavaPlugin plugin) {
this.plugin = plugin;
}
/** Call from onEnable, after saveDefaultConfig() and before reading any config value. */
public void updateConfig() {
ConfigUpdateReport report;
try {
report = ConfigFileUpdater.updateMainConfig(plugin, POLICY);
} catch (Exception e) {
plugin.getLogger().warning("config.yml could not be updated: " + e.getMessage());
return;
}
if (report.backupError() != null) {
plugin.getLogger().warning("config.yml was not backed up: " + report.backupError());
}
for (ConfigKeyRename rename : report.migratedKeys()) {
plugin.getLogger().info("Moved " + rename.oldPath() + " to " + rename.newPath() + ".");
}
if (!report.retiredKeys().isEmpty()) {
plugin.getLogger().info("Removed unread settings: " + String.join(", ", report.retiredKeys()));
}
if (report.addedKeys() > 0) {
plugin.getLogger().info("Added " + report.addedKeys() + " new settings to config.yml.");
}
}
}The report also has changed(), true when anything at all happened. addedKeys() counts value keys only,
not the sections around them.
For a plugin with more than one file, the class holds no state: build one policy per file and drive the
steps yourself with readBundledYaml / readYamlFile → applyTo(bundled, existing, policy) → backup →
tidy → save. Call tidy(config) immediately before any save — Bukkit's YAML dumper folds values
longer than 80 characters across several physical lines, which turns item-id lists and message templates
into multi-line blocks that are painful to edit by hand. tidy pins the width, the 2-space indent and
comment parsing; updateMainConfig already does it for you.
installBundledResource / writeStringAtomically / needsRestore round the package out: install a bundled
file through a temp file and an atomic move (a crash leaves the old file intact, not half a file), and
detect a config that no longer parses or was saved in the wrong encoding so you can restore it from the jar.
Needs the UltimateAdvancementAPI plugin. Grant/check FarmersDelight's own tab, or register your own tab from plain data — FD builds the real UAA tab and rebuilds it across /fd reload:
if (FarmersDelightAdvancements.isAvailable()) {
FarmersDelightAdvancements.tree("myaddon")
.root("root", icon, "Title", "Desc", "minecraft:textures/block/stone.png")
.advancement("step1", "root", icon, "Step 1", "Do a thing.", "task", 1, 0)
.register(); // unregister("myaddon") on disable
}
FarmersDelightAdvancements.award("myaddon", player, "step1");
FarmersDelightAdvancements.award(player, "master_chef"); // FD's own tab (no tabId)Titles/descriptions are client lang keys (resolved from the resource pack) or literal text.
Read-only views of FD's own cooking-pot / cutting-board recipes (Bukkit types only):
for (String id : FarmersDelightRecipes.cookingPotRecipeIds()) {
RecipeInfo r = FarmersDelightRecipes.cookingPotRecipe(id); // ingredients (id strings), results, cookTimeTicks, experience, category, container
}
// also: cuttingBoardRecipeIds(), cuttingBoardRecipe(id), matchesCookingPot(...), cookingPotResult(...)Per-player recipe lock/unlock in the recipe books (enable recipe-discovery in FD's config):
if (FarmersDelightRecipeDiscovery.isEnabled()) {
FarmersDelightRecipeDiscovery.unlock(player, "myaddon:type", "recipe_id");
boolean known = FarmersDelightRecipeDiscovery.isUnlocked(player,
FarmersDelightRecipeDiscovery.TYPE_COOKING_POT, "farmersdelight:beef_stew");
}Read-only identification of FarmersDelight's four workstations and what each currently holds. Every parameter
and return type is a Bukkit / java type (plus the snapshot records), so no CraftEngine dependency is needed.
See readCookingPot in FDAddonTemplate.java.
if (FarmersDelightBlocks.isStation(block)) {
FarmersDelightStation which = FarmersDelightBlocks.stationOf(block); // COOKING_POT / CUTTING_BOARD / SKILLET / STOVE
String blockId = FarmersDelightBlocks.blockIdOf(block); // any CE custom block id, or null
CookingPotSnapshot pot = FarmersDelightBlocks.cookingPot(block); // null unless it is a cooking pot
if (pot != null && pot.cooking()) {
double p = pot.progressFraction(); // 0..1
}
}
// also: cuttingBoard(block) -> CuttingBoardSnapshot, skillet(block) -> SkilletSnapshot, stove(block) -> StoveSnapshot,
// stationIdOf(block).Two hard rules from the API's own javadoc:
- Never identify a station by
Material. CraftEngine reports a configurable disguise material (the same one for every custom block by default), sogetType() == Material.Xidentifies nothing and changes silently when the server owner edits CraftEngine's disguise setting. Always go throughisStation/stationOf/stationIdOf, which resolve the real custom block state (detection is by the attached CraftEngine behavior, so a re-skinned or addon-provided station is still recognised).FarmersDelightStation.defaultBlockId()is the stock id FD ships each station under — not whatstationIdOfreturns for a re-skinned block. - Call on the region thread that owns the block (Folia / Luminol): every method reads world state, so call
from a listener for an event at that block, or a task scheduled with
runAtLocation. Calling from another region, the global region, or an async task hits Paper's thread check and throws. A snapshot is a copy taken at the instant of the call (the records are immutable and write nothing back) — treat it as a reading, not a live handle.nullmeans "not that station, or no block entity loaded".
Register extra mob drops harvested with a knife at runtime (the rule set behind FD's ham / leather / feather /
string drops), for an addon that ships its own butchering items or a quest plugin adding a conditional drop.
A rule fires when a player kills an adult entity of the matching type with a matching tool and a chance roll
passes; there is one rule per entity type. Rules registered here persist across /fd reload (the reload
re-applies them on top of config.yml), so unregister on your plugin's disable.
FarmersDelightKnifeDrops.register("pig", "myaddon:raw_ham", "myaddon:cooked_ham", 0.35, 0.05);
// full form adds per-rule tool matchers (item ids + "#tag" ids); empty/null falls back to the global knife list:
FarmersDelightKnifeDrops.register("cow", "myaddon:tallow", null, 0.20, 0.0,
List.of("myaddon:cleaver"), List.of("minecraft:swords"));
FarmersDelightKnifeDrops.unregister("pig"); // only removes rules this facade added
boolean has = FarmersDelightKnifeDrops.hasRule("cow"); // from any source (config / built-in / facade)Your addon needs no command of its own. FarmersDelight fires FarmersDelightReloadEvent on any
/fd reload <target>; listen for it and reload your config (see the example). Static cooking-pot /
cutting-board recipes declared in your CraftEngine pack are re-read by FarmersDelight on every reload.
Recipes you register at runtime should be (re)registered on FarmersDelightWarmupEvent, which fires once
CraftEngine has built its items — CraftEngineReloadEvent fires before that, so every recipe naming a custom
item is silently dropped.
- Organize by type, like FD:
items.yml,food_block.yml,blocks.yml,gui.yml,translations.yml. - Block style only — no inline
{ }flow maps. Leaveitem-name/modelunquoted; quote only when YAML requires it (a#-leading tag, or a trailing space). - No comments in shipping configs (this template comments for teaching). FD's own configs are clean.
- Native CE recipe types:
shaped,shapeless,smelting,smoking,blasting,campfire_cooking,stonecutting. - Cooking-pot / cutting-board recipes are not CE recipes, but they are still pack YAML: declare them under
configuration/farmersdelight/cooking_pot_recipes.yml(rootcooking_recipes) andconfiguration/farmersdelight/cutting_board_recipes.yml(rootcutting_recipes) — see the two example files in this template. CraftEngine hands those sections to FarmersDelight, so they need no addon code, show up in the recipe book, and are edited as data instead of Java. UseFarmersDelightApi.registerCookingPotRecipe/registerCuttingBoardRecipeWithChancesonly for recipes that must be decided at runtime. - Custom blocks get collision from their host state: a solid
auto-statehost (note_block,mushroom) gives full-cube collision; a transparent host (non_tintable_leaves) collides but renders cleanly for non-cube models;tripwireis non-colliding (flat food blocks). Block right-click/break logic can be pure CEevents(see FD'sfood_block.yml).
See configuration/items.yml for a
commented example (custom food + on-eat effect, a vanilla-item behavior override, a shaped recipe).
A custom block that does something and remembers state per position is split across three places —
all of it CraftEngine's own API. FarmersDelight publishes api.registry.ContentRegistration for callers
that want its id rules and its re-apply pass, but registering a block behaviour with CraftEngine directly is
equally valid; FD's own bridging covers recipes / scheduling / heat / XP. Compile against CE 26.9.1 and
verify symbols on 26.8.2–26.11 (26.11-SNAPSHOT was checked on 2026-11-28 and is a drop-in: FarmersDelight
compiles and boots against it without API changes). Stable class names alone do not guarantee API
compatibility; optional newer APIs need version checks and a fallback. Paper 1.21.5 is the compilation baseline.
- Block definition —
configuration/blocks.yml:blocks.fdaddon:example_blockwithbehavior: - type: fdaddon:example_block, ablock_itemso it can be placed, and a shaped recipe. Collision comes from the host state (auto-state: note_block→ solid). No block-entity declaration is needed — CraftEngine detects it from the behavior (see below). - Behavior —
ExampleBlockBehavior.java:extends BlockBehavior implements EntityBlock, overridesuseOnBlock(...)for right-click logic, exposes a staticFACTORY. Registered inonLoad()withBlockBehaviors.register(Key.of("fdaddon:example_block"), FACTORY)— do this before CraftEngine parsesblocks.yml, since the config references it by id. The behavior is a singleton shared by all placed blocks, so it holds no per-block state; on interaction it looks up the block entity at the clicked position and acts on that block's controller. - Per-block content —
ExampleBlockEntityController.java: because the behavior implementsEntityBlock, CraftEngine creates oneBlockEntityControllerper placed block and persists it inside the chunk. You serialize your state insaveCustomData(CompoundTag)and restore it inloadCustomData(CompoundTag)— that's the whole persistence story. Do not store block state in a side yml; there's no plugin-managed save/load lifecycle to write. This is exactly how FD's cooking pot / skillet / stove keep their inventories and progress. To mark a block changed so CraftEngine re-saves it, callblockEntity.world.blockEntityChanged(pos). For per-tick logic, overridecreateBlockEntityTicker(...)on the controller. - Storing items? Drop them safely. A drop call that did not throw is not proof of delivery: Paper returns
an entity wrapper even when another plugin cancels
ItemSpawnEvent. UseDropSafety.spawnVerified(...)and only clear the stored stack after it returns true. On a break path, keep the undelivered stacks and cancel the break; on a removal path that cannot be vetoed (explosion, another plugin replacing the block), persist the remaining stacks to a recovery file — FD'sStationDropRecovery/DropRecoveryArchiveare the reference implementations. For handing a stack to a player, use FD'sItemDelivery.giveOrDrop, which already verifies the overflow drop. Never clear a container before its contents are confirmed in the world. - Container example —
fdaddon:example_containerinblocks.yml, withExampleContainerBehavior,ExampleContainerControllerandExampleContainerBreakListener: two item slots persisted throughItemStackUtils, right-click with an item to store one and with an empty hand to take one back. It demonstrates the whole drop contract: the break listener asks the controller to drop and cancels the break when a spawn is refused;onRemove()(explosion, another plugin replacing the block) drops what it can and writes the rest toplugins/FDAddonTemplate/container-drop-recovery/*.nbt; the hand-back usesItemDelivery.giveOrDrop. The reusable pieces areStoredContents(slots + confirmed drop),DropSafety(verified spawn) andDropRecoveryArchive(compressed-NBT archive).StoredContentsTest/DropRecoveryArchiveTest/ExampleContainerWiringTestcover the failure paths.
The three parts above cover the block itself. A station with a container GUI, recipe book and editor composes the
api types instead of copying FarmersDelight's station classes; the wiring order (scheduler, ContainerGuiKernel,
RecipeType, editor, protection, tags, events) is documented in the wiki's
Building an addon station
page. Reference implementations to read: Brewin' And Chewin's keg (KegManager, KegRecipeType), Crabber's
Delight's crab trap (CrabTrapBlockEntityController) and Barbeque's Delight's grill (StationBlockEntity).
Register an extension with DebugToolRegistry in onEnable. FD must be built with -PdebugTools=true to expose these commands; /fd stats remains available in the normal build.
/fd debugtools place <target> [count] [spacing] [layers]
/fd debugtools activate <target>
/fd debugtools test <target|all> [count] [ticks]
/fd debugtools recipe place <target|all> <recipeId> [count]
/fd debugtools recipe random <target|all> [count]
/fd debugtools recipe validate
/fd debugtools undo
/fd stats addon <name>
See ExampleDebugExtension.java. Implement name(), declare supportsPlacement()/supportsActivation(), and provide only the callbacks the block needs:
- place(..., undo): capture the original state with undo.capture(loc) before modifying it. FD supplies one position per scheduled operation; keep the work on that position's owning region.
- activateAt(player, location): activate the supplied position in the player's latest debug batch. The overload with an item resolver is available for filling inputs. Do not scan every registered block; the old activate(player) callback is not used.
- recipeIds() and recipe(id, resolver): optional for processing stations. Resolve a complete valid setup before placement, preserve quantities and fluid requirements, and use the station's own rules for virtual fluid outputs. A functional block with no processing recipe can still support activation; leave recipeIds() empty.
- status(player): concise MiniMessage lines returned by /fd stats addon .
- cleanupBeforeUndo(location): release tracking for that position. FD handles block restoration; do not manually erase unrelated blocks or saved data.
all selects only targets supporting the requested operation. activate all still operates on the player's latest batch; it does not activate production blocks across the world. Activation does not independently undo already consumed or collected items.
test places, fills and activates, then verifies the outcome: built-in stations are read back through their controllers, addon targets are counted by the activateAt return value. A fill or activation that did not take effect counts as failed (activated N, M failed) and is logged instead of being reported as a success.
This template has no upstream mod: it is an original project by the FarmersDelight authors, written for addons that build on the FarmersDelight plugin.
- FarmersDelight plugin: https://github.com/IOVEYOUMC0/Farmersdelight-Plugin
- Addon-facing API docs (
api-docs/): https://github.com/IOVEYOUMC0/FarmersdelightPluginWiKi
The contract this template compiles against is com.huidu.farmersdelight.api; everything outside that
package is internal to the plugin and may change.
This template ships the GNU Affero General Public License v3.0 (LICENSE), the same licence as the
FarmersDelight plugin it builds against, and the FarmersDelight api artifact it compiles against (built from
the sibling checkout, or fetched as a Gradle source dependency from that same repository) is distributed
under that licence too.
AGPL-3.0 is strongly copyleft: an addon that links against the FarmersDelight API must itself be released under AGPL-3.0, and if you run a modified version as a network service you must offer the corresponding source to its users. If that does not suit your project, do not copy this template — get the addon licensed differently from the FarmersDelight authors first.
The template's own example code is a starting point only: delete the demo content and replace it with yours.