Skip to content

Commit

Permalink
feat: support ingredient notation in item recipe results
Browse files Browse the repository at this point in the history
  • Loading branch information
klikli-dev committed Aug 21, 2024
1 parent ab178e5 commit 09e9713
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
package com.klikli_dev.occultism.crafting.recipe.result;

import com.klikli_dev.occultism.registry.OccultismRecipeResults;
import com.klikli_dev.occultism.util.OccultismExtraCodecs;
import com.mojang.serialization.Codec;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.component.DataComponentPatch;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.world.item.ItemStack;
Expand All @@ -16,7 +20,18 @@
*/
public class ItemRecipeResult extends RecipeResult {

public static final MapCodec<ItemRecipeResult> CODEC = MapCodec.assumeMapUnsafe(ItemStack.STRICT_CODEC.xmap(ItemRecipeResult::new, ItemRecipeResult::getStack));
public static final MapCodec<ItemRecipeResult> INGREDIENT_COMPAT_CODEC = RecordCodecBuilder.mapCodec((builder) -> builder.group(
ItemStack.ITEM_NON_AIR_CODEC.fieldOf("item").forGetter(t -> t.stack.getItemHolder()),
Codec.INT.fieldOf("count").forGetter(t -> t.stack.getCount()),
DataComponentPatch.CODEC.optionalFieldOf("components", DataComponentPatch.EMPTY).forGetter(t -> t.stack.getComponentsPatch())
).apply(builder, (item, count, components) -> new ItemRecipeResult(new ItemStack(item, count, components))));

public static final MapCodec<ItemRecipeResult> ITEM_STACK_COMPAT_CODEC = MapCodec.assumeMapUnsafe(ItemStack.STRICT_CODEC.xmap(ItemRecipeResult::new, ItemRecipeResult::getStack));

public static final MapCodec<ItemRecipeResult> CODEC = OccultismExtraCodecs.mapWithAlternative(
ITEM_STACK_COMPAT_CODEC,
INGREDIENT_COMPAT_CODEC
);

public static final StreamCodec<RegistryFriendlyByteBuf, ItemRecipeResult> STREAM_CODEC = StreamCodec.composite(
ItemStack.OPTIONAL_STREAM_CODEC,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
package com.klikli_dev.occultism.util;

import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Codec;
import com.mojang.serialization.MapCodec;

import java.util.UUID;

public class OccultismExtraCodecs {
public static final Codec<java.util.UUID> UUID = Codec.STRING.xmap(java.util.UUID::fromString, java.util.UUID::toString);

public static <T> MapCodec<T> mapWithAlternative(final MapCodec<T> primary, final MapCodec<? extends T> alternative) {
return Codec.mapEither(
primary,
alternative
).xmap(
Either::unwrap,
Either::left
);
}
}

0 comments on commit 09e9713

Please sign in to comment.