diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/CommonProxy.java b/src/main/java/com/gtnewhorizon/gtnhlib/CommonProxy.java index 1b4bdc57..c08377a6 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/CommonProxy.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/CommonProxy.java @@ -9,6 +9,8 @@ import net.minecraftforge.common.util.FakePlayer; import com.gtnewhorizon.gtnhlib.block.BlockTest; import com.gtnewhorizon.gtnhlib.block.BlockTestTint; import com.gtnewhorizon.gtnhlib.block.BlockTestTintMul; +import com.gtnewhorizon.gtnhlib.blockstate.command.BlockStateCommand; +import com.gtnewhorizon.gtnhlib.blockstate.init.BlockPropertyInit; import com.gtnewhorizon.gtnhlib.brigadier.BrigadierApi; import com.gtnewhorizon.gtnhlib.config.ConfigurationManager; import com.gtnewhorizon.gtnhlib.eventbus.AutoEventBus; @@ -48,6 +50,8 @@ public class CommonProxy { GameRegistry.registerBlock(new BlockTestTint(), "model_test_tint"); GameRegistry.registerBlock(new BlockTestTintMul(), "model_test_tint_mul"); } + + BlockPropertyInit.init(); } public void init(FMLInitializationEvent event) { @@ -67,7 +71,9 @@ public class CommonProxy { BrigadierApi.init(); } - public void serverStarting(FMLServerStartingEvent event) {} + public void serverStarting(FMLServerStartingEvent event) { + event.registerServerCommand(new BlockStateCommand()); + } public void serverStarted(FMLServerStartedEvent event) {} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/command/BlockStateCommand.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/command/BlockStateCommand.java new file mode 100644 index 00000000..75ec6def --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/command/BlockStateCommand.java @@ -0,0 +1,140 @@ +package com.gtnewhorizon.gtnhlib.blockstate.command; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import net.minecraft.client.Minecraft; +import net.minecraft.command.CommandBase; +import net.minecraft.command.ICommandSender; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.MovingObjectPosition.MovingObjectType; +import net.minecraft.util.Vec3; + +import com.gtnewhorizon.gtnhlib.GTNHLib; +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.registry.BlockPropertyRegistry; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; + +public class BlockStateCommand extends CommandBase { + + @Override + public String getCommandName() { + return "blockstate"; + } + + @Override + public String getCommandUsage(ICommandSender sender) { + return "/blockstate [property name] [property value]"; + } + + @Override + public List getCommandAliases() { + return new ArrayList<>(); + } + + @Override + public void processCommand(ICommandSender sender, String[] args) { + if (!(sender instanceof EntityPlayer player)) return; + + String action = BlockProperty.getIndexSafe(args, 0); + String name = BlockProperty.getIndexSafe(args, 1); + String value = BlockProperty.getIndexSafe(args, 2); + + if (action == null || "set".equals(action) && name != null && value == null) { + sendErrorToPlayer(sender, getCommandUsage(sender)); + return; + } + + var hit = getHitResult(player); + + if (hit == null || hit.typeOfHit != MovingObjectType.BLOCK) { + sendErrorToPlayer(sender, "You must be looking at a block to use this command."); + return; + } + + Map> properties = new Object2ObjectOpenHashMap<>(); + BlockPropertyRegistry.getProperties(player.worldObj, hit.blockX, hit.blockY, hit.blockZ, properties); + + if ("get".equals(action)) { + if (name != null) { + @SuppressWarnings("unchecked") + BlockProperty prop = (BlockProperty) properties.get(name); + + if (prop != null) { + Object v = prop.getValue(player.worldObj, hit.blockX, hit.blockY, hit.blockZ); + + sendChatToPlayer(sender, prop.getName() + ": " + prop.stringify(v)); + return; + } + + sendErrorToPlayer(sender, "Property not found."); + } else { + sendChatToPlayer(player, "Properties:"); + + if (properties.isEmpty()) { + sendChatToPlayer(player, "None"); + return; + } + + for (var e : properties.entrySet()) { + @SuppressWarnings("unchecked") + BlockProperty prop = (BlockProperty) e.getValue(); + + Object v = prop.getValue(player.worldObj, hit.blockX, hit.blockY, hit.blockZ); + + sendChatToPlayer(player, prop.getName() + ": " + prop.stringify(v)); + } + } + } else { + @SuppressWarnings("unchecked") + BlockProperty prop = (BlockProperty) properties.get(name); + + if (prop != null) { + try { + Object v = prop.parse(value); + + prop.setValue(player.worldObj, hit.blockX, hit.blockY, hit.blockZ, v); + } catch (Throwable t) { + GTNHLib.LOG.error("Error setting property {}", name, t); + sendErrorToPlayer(player, "Error setting property: " + t.getMessage()); + } + + return; + } + + sendErrorToPlayer(sender, "Property not found."); + } + } + + private static MovingObjectPosition getHitResult(EntityPlayer player) { + double reachDistance = player instanceof EntityPlayerMP mp ? mp.theItemInWorldManager.getBlockReachDistance() + : Minecraft.getMinecraft().playerController.getBlockReachDistance(); + + Vec3 posVec = Vec3.createVectorHelper(player.posX, player.posY + player.getEyeHeight(), player.posZ); + + Vec3 lookVec = player.getLook(1); + + Vec3 modifiedPosVec = posVec.addVector( + lookVec.xCoord * reachDistance, + lookVec.yCoord * reachDistance, + lookVec.zCoord * reachDistance); + + MovingObjectPosition hit = player.worldObj.rayTraceBlocks(posVec, modifiedPosVec, true); + + return hit != null && hit.typeOfHit != MovingObjectType.BLOCK ? null : hit; + } + + private static void sendErrorToPlayer(ICommandSender sender, String aChatMessage) { + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + aChatMessage)); + } + + private static void sendChatToPlayer(ICommandSender sender, String aChatMessage) { + sender.addChatMessage(new ChatComponentText(aChatMessage)); + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/BlockProperty.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/BlockProperty.java new file mode 100644 index 00000000..423eed22 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/BlockProperty.java @@ -0,0 +1,118 @@ +package com.gtnewhorizon.gtnhlib.blockstate.core; + +import java.lang.reflect.Type; +import java.util.List; + +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; + +import org.jetbrains.annotations.ApiStatus.OverrideOnly; +import org.jetbrains.annotations.Nullable; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonSyntaxException; + +/// A property for a block. +/// +/// The property's type can be any java type, but it must be convertible to json and vice versa. +/// For any values with special serialization requirements, the {@link #serialize(Object)} and +/// {@link #deserialize(JsonElement)} methods must be overridden, along with {@link #stringify(Object)} and +/// {@link #parse(String)}. +/// +/// Consumers of this API must assume that the value is mutable. When mutating it in situations where the original +/// value must remain unmodified, the value must be first copied via {@link #copy(Object)}. If the value is immutable +/// (such as an enum variant or a property without an interface for modifying the value), implementations are free to +/// elide the copy. +/// +/// [TValue] must implement [Object#hashCode()] and [Object#equals(Object)] properly. +public interface BlockProperty { + + String getName(); + + Type getType(); + + boolean hasTrait(BlockPropertyTrait trait); + + default TValue copy(TValue value) { + return value; + } + + Gson GSON = new Gson(); + + @OverrideOnly + default Gson getGson() { + return GSON; + } + + /// Converts a json value into a java value. + /// It cannot be assumed that the json value is compatible with the string serialization methods. + /// @throws InvalidPropertyJsonException When the json is invalid + default TValue deserialize(JsonElement element) { + try { + return getGson().fromJson(element, getType()); + } catch (JsonSyntaxException e) { + throw new InvalidPropertyJsonException("Could not deserialize " + getType().getTypeName(), e); + } + } + + /// Converts a java value into a json value. + /// It cannot be assumed that the json value is compatible with the string serialization methods. + default JsonElement serialize(TValue value) { + return getGson().toJsonTree(value); + } + + /// Parses text into a java value. + /// It cannot be assumed that the text value is compatible with the json serialization methods. + /// @throws InvalidPropertyTextException When the text is invalid + default TValue parse(String text) throws InvalidPropertyTextException { + try { + return getGson().fromJson(text, getType()); + } catch (JsonSyntaxException e) { + throw new InvalidPropertyTextException("Could not parse " + getType().getTypeName(), e); + } + } + + /// Parses text into a java value. + /// It cannot be assumed that the text value is compatible with the json serialization methods. + default String stringify(TValue value) { + return getGson().toJson(value); + } + + default boolean appliesTo(IBlockAccess world, int x, int y, int z, Block block, int meta, + @Nullable TileEntity tile) { + return true; + } + + default TValue getValue(IBlockAccess world, int x, int y, int z) { + throw new UnsupportedOperationException(); + } + + default void setValue(World world, int x, int y, int z, TValue value) { + throw new UnsupportedOperationException(); + } + + default boolean appliesTo(ItemStack stack, Item item, int meta) { + return true; + } + + default TValue getValue(ItemStack stack) { + throw new UnsupportedOperationException(); + } + + default void setValue(ItemStack stack, TValue value) { + throw new UnsupportedOperationException(); + } + + static T getIndexSafe(T[] array, int index) { + return array == null || index < 0 || index >= array.length ? null : array[index]; + } + + static T getIndexSafe(List list, int index) { + return list == null || index < 0 || index >= list.size() ? null : list.get(index); + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/BlockPropertyTrait.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/BlockPropertyTrait.java new file mode 100644 index 00000000..da698729 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/BlockPropertyTrait.java @@ -0,0 +1,22 @@ +package com.gtnewhorizon.gtnhlib.blockstate.core; + +public enum BlockPropertyTrait { + /// If this property can interact with blocks in the world + SupportsWorld, + /// If this property can interact with blocks in ItemStacks. The Item must extend {@link ItemBlock}. + SupportsStacks, + /// If this property is exclusively derived from metadata (block and item) and implements {@link MetaBlockProperty}. + OnlyNeedsMeta, + /// If this property can be changed while the block exists in the world, regardless of whether this would spawn + /// items/etc into existence. + WorldMutable, + /// If this property can be changed while the block is in stack form, regardless of whether this would spawn + /// items/etc into existence. + StackMutable, + /// If this property can be treated like a 'setting' and will not give anything to the player when changed. + Config, + /// If this property can be transformed by a direction transform and implements {@link TransformableProperty}. + Transformable, + /// If this property can be transformed by a vector transform and implements {@link VectorTransformableProperty}. + VectorTransformable, +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/BlockState.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/BlockState.java new file mode 100644 index 00000000..4819dcf2 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/BlockState.java @@ -0,0 +1,40 @@ +package com.gtnewhorizon.gtnhlib.blockstate.core; + +import java.util.Map; + +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; + +import com.gtnewhorizon.gtnhlib.geometry.TransformLike; + +/// Represents the state of a block. Includes things like rotation, powered-ness, orientation, etc. Does not include +/// things like the inventory. +public interface BlockState extends AutoCloseable, Cloneable { + + BlockState clone(); + + /// Gets the 'original' block for this state. Note that any block-changing properties (such as the various 'lit' + /// properties) may change the actual block that gets placed by this BlockState. + Block getBlock(); + + T getPropertyValue(BlockProperty property); + + T getPropertyValue(String name); + + void setPropertyValue(BlockProperty property, T value); + + void setPropertyValue(String name, T value); + + /// Copies the properties stored in this BlockState into a map. Key=Property Name, Value=Property Value (as text). + Map toMap(); + + void transform(TransformLike transform); + + void place(World world, int x, int y, int z); + + ItemStack getItemStack(); + + @Override + void close(); +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/BlockStateImpl.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/BlockStateImpl.java new file mode 100644 index 00000000..fc2ffc5c --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/BlockStateImpl.java @@ -0,0 +1,221 @@ +package com.gtnewhorizon.gtnhlib.blockstate.core; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +import net.minecraft.block.Block; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; + +import org.jetbrains.annotations.ApiStatus; + +import com.gtnewhorizon.gtnhlib.GTNHLib; +import com.gtnewhorizon.gtnhlib.blockstate.registry.BlockPropertyRegistry; +import com.gtnewhorizon.gtnhlib.geometry.DirectionTransform; +import com.gtnewhorizon.gtnhlib.geometry.TransformLike; +import com.gtnewhorizon.gtnhlib.geometry.VectorTransform; +import com.gtnewhorizon.gtnhlib.util.ObjectPooler; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; + +@SuppressWarnings({ "resource", "unchecked" }) +@ApiStatus.Internal +public class BlockStateImpl implements BlockState { + + private Block block; + private int meta; + + private final Map> properties = new HashMap<>(4); + private final Map, Object> values = new HashMap<>(4); + + private static final ObjectPooler POOL = new ObjectPooler<>(BlockStateImpl::new); + + public static BlockStateImpl getInstance() { + return POOL.getInstance().assertIsDefault(); + } + + public BlockStateImpl assertIsDefault() { + if (block != null) throw new RuntimeException( + "BlockStateImpl reference was mutated while in the pool; block was set to " + block); + if (meta != 0) throw new RuntimeException( + "BlockStateImpl reference was mutated while in the pool; meta was set to " + meta); + if (!properties.isEmpty()) throw new RuntimeException( + "BlockStateImpl reference was mutated while in the pool; properties was set to " + properties); + if (!values.isEmpty()) throw new RuntimeException( + "BlockStateImpl reference was mutated while in the pool; values was set to " + values); + + return this; + } + + public BlockStateImpl reset() { + this.block = null; + this.meta = 0; + this.properties.clear(); + this.values.clear(); + + return this; + } + + public BlockStateImpl copy(BlockStateImpl other) { + reset(); + + this.block = other.block; + this.meta = other.meta; + this.properties.putAll(other.properties); + this.values.putAll(other.values); + + return this; + } + + public BlockStateImpl fromWorld(IBlockAccess world, int x, int y, int z) { + this.block = world.getBlock(x, y, z); + this.meta = world.getBlockMetadata(x, y, z); + + BlockPropertyRegistry.getProperties(world, x, y, z, this.properties); + + this.values.clear(); + + this.properties.forEach((name, property) -> { this.values.put(property, property.getValue(world, x, y, z)); }); + + return this; + } + + public BlockStateImpl fromStack(ItemStack stack) { + ItemBlock itemBlock = (ItemBlock) Objects.requireNonNull(stack.getItem(), "Item cannot be null"); + + this.block = itemBlock.field_150939_a; + this.meta = itemBlock.getMetadata(stack.getItemDamage()); + + BlockPropertyRegistry.getProperties(stack, this.properties); + + this.values.clear(); + + this.properties.forEach((name, property) -> { this.values.put(property, property.getValue(stack)); }); + + return this; + } + + @SuppressWarnings("MethodDoesntCallSuperMethod") + @Override + public BlockStateImpl clone() { + return POOL.getInstance().copy(this); + } + + @Override + public Block getBlock() { + return block; + } + + @Override + public T getPropertyValue(BlockProperty property) { + return (T) values.get(property); + } + + @Override + public T getPropertyValue(String name) { + BlockProperty property = (BlockProperty) properties.get(name); + + if (property == null) return null; + + return (T) values.get(property); + } + + @Override + public void setPropertyValue(BlockProperty property, T value) { + if (properties.containsValue(property)) { + values.put(property, value); + } + } + + @Override + public void setPropertyValue(String name, T value) { + BlockProperty property = (BlockProperty) properties.get(name); + + if (property == null) { + GTNHLib.LOG.warn( + "Tried to set invalid property on BlockState by name. Name={}, Value={}", + name, + value, + new Exception()); + return; + } + + if (property.getType() instanceof Classclazz) { + if (!clazz.isInstance(value)) { + GTNHLib.LOG.warn( + "Tried to set value for property on BlockState to an incompatible value. Name={}, Value={}", + name, + value, + new Exception()); + return; + } + } + + values.put(property, value); + } + + @Override + public Map toMap() { + Map out = new Object2ObjectOpenHashMap<>(values.size()); + + properties.forEach((name, prop) -> { + Object value = values.get(prop); + + if (value != null) { + out.put(name, ((BlockProperty) prop).stringify(value)); + } + }); + + return out; + } + + @Override + public void transform(TransformLike transform) { + values.replaceAll((property, value) -> { + if (property.hasTrait(BlockPropertyTrait.VectorTransformable) + && transform instanceof VectorTransform vector) { + return ((VectorTransformableProperty) property).transform(value, vector); + } + + if (property.hasTrait(BlockPropertyTrait.Transformable) && transform instanceof DirectionTransform dir) { + return ((TransformableProperty) property).transform(value, dir); + } + + return value; + }); + } + + @Override + public void place(World world, int x, int y, int z) { + world.setBlock(x, y, z, this.block, this.meta, 2); + + values.forEach((property, value) -> { + if (property.hasTrait(BlockPropertyTrait.SupportsWorld) + && property.hasTrait(BlockPropertyTrait.WorldMutable)) { + ((BlockProperty) property).setValue(world, x, y, z, value); + } + }); + } + + @Override + public ItemStack getItemStack() { + ItemStack stack = new ItemStack(this.block, 1, this.block.damageDropped(this.meta)); + + values.forEach((property, value) -> { + if (property.hasTrait(BlockPropertyTrait.SupportsStacks) + && property.hasTrait(BlockPropertyTrait.StackMutable)) { + ((BlockProperty) property).setValue(stack, value); + } + }); + + return stack; + } + + @Override + public void close() { + POOL.releaseInstance(this.reset()); + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/InvalidPropertyJsonException.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/InvalidPropertyJsonException.java new file mode 100644 index 00000000..742bb42b --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/InvalidPropertyJsonException.java @@ -0,0 +1,21 @@ +package com.gtnewhorizon.gtnhlib.blockstate.core; + +public class InvalidPropertyJsonException extends RuntimeException { + + public InvalidPropertyJsonException(String message) { + super(message); + } + + public InvalidPropertyJsonException(String message, Throwable cause) { + super(message, cause); + } + + public InvalidPropertyJsonException(Throwable cause) { + super(cause); + } + + public InvalidPropertyJsonException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/InvalidPropertyTextException.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/InvalidPropertyTextException.java new file mode 100644 index 00000000..68114ca3 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/InvalidPropertyTextException.java @@ -0,0 +1,21 @@ +package com.gtnewhorizon.gtnhlib.blockstate.core; + +public class InvalidPropertyTextException extends RuntimeException { + + public InvalidPropertyTextException(String message) { + super(message); + } + + public InvalidPropertyTextException(String message, Throwable cause) { + super(message, cause); + } + + public InvalidPropertyTextException(Throwable cause) { + super(cause); + } + + public InvalidPropertyTextException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/MetaBlockProperty.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/MetaBlockProperty.java new file mode 100644 index 00000000..3fde1bf3 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/MetaBlockProperty.java @@ -0,0 +1,84 @@ +package com.gtnewhorizon.gtnhlib.blockstate.core; + +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; + +import org.jetbrains.annotations.Nullable; + +/// A property whose value is solely determined by block metadata. +public interface MetaBlockProperty extends BlockProperty { + + int getMeta(T value, int existing); + + T getValue(int meta); + + @Override + default boolean appliesTo(IBlockAccess world, int x, int y, int z, Block block, int meta, + @Nullable TileEntity tile) { + return appliesTo(meta); + } + + @Override + default boolean appliesTo(ItemStack stack, Item item, int meta) { + return appliesTo(item.getMetadata(meta)); + } + + default boolean appliesTo(int meta) { + return true; + } + + /// Whether this property requires the existing meta value. When false, the parameter may be set to any value and + /// must be ignored by the implementation. + default boolean needsExisting() { + return true; + } + + @Override + default T getValue(IBlockAccess world, int x, int y, int z) { + if (!hasTrait(BlockPropertyTrait.SupportsWorld)) throw new UnsupportedOperationException(); + + return getValue(world.getBlockMetadata(x, y, z)); + } + + @Override + default void setValue(World world, int x, int y, int z, T value) { + if (!hasTrait(BlockPropertyTrait.SupportsWorld)) throw new UnsupportedOperationException(); + + boolean needsExisting = needsExisting(); + + int existing = needsExisting ? world.getBlockMetadata(x, y, z) : 0; + + int meta = getMeta(value, existing); + + if (!needsExisting || existing != meta) { + world.setBlockMetadataWithNotify(x, y, z, meta, 2); + } + } + + @Override + default T getValue(ItemStack stack) { + if (!hasTrait(BlockPropertyTrait.SupportsStacks)) throw new UnsupportedOperationException(); + + @SuppressWarnings("DataFlowIssue") + int meta = stack.getItem().getMetadata(stack.getItemDamage()); + + return getValue(meta); + } + + @SuppressWarnings("DataFlowIssue") + @Override + default void setValue(ItemStack stack, T t) { + if (!hasTrait(BlockPropertyTrait.SupportsStacks)) throw new UnsupportedOperationException(); + + int meta = needsExisting() ? stack.getItem().getMetadata(stack.getItemDamage()) : 0; + + meta = getMeta(t, meta); + + stack.setItemDamage(((ItemBlock) stack.getItem()).field_150939_a.damageDropped(meta)); + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/TransformableProperty.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/TransformableProperty.java new file mode 100644 index 00000000..dde9ff25 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/TransformableProperty.java @@ -0,0 +1,15 @@ +package com.gtnewhorizon.gtnhlib.blockstate.core; + +import org.jetbrains.annotations.NotNull; + +import com.gtnewhorizon.gtnhlib.geometry.DirectionTransform; + +/// This indicates that a property can be transformed in the world according to an arbitrary transform. +public interface TransformableProperty extends BlockProperty { + + /// The transform function may contain any transform, but there is no guarantee that this property has the degrees + /// of freedom to properly respect it. + /// See the header comment {@link BlockProperty} for this method's mutability semantics. + @NotNull + TValue transform(TValue value, DirectionTransform transform); +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/VectorTransformableProperty.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/VectorTransformableProperty.java new file mode 100644 index 00000000..2781bb86 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/core/VectorTransformableProperty.java @@ -0,0 +1,16 @@ +package com.gtnewhorizon.gtnhlib.blockstate.core; + +import org.jetbrains.annotations.NotNull; + +import com.gtnewhorizon.gtnhlib.geometry.VectorTransform; + +/// A version of {@link TransformableProperty} that supports arbitrary vector transformation, instead of explicitly +/// locking the vectors to a ForgeDirection. +public interface VectorTransformableProperty extends BlockProperty { + + /// The transform function may contain any transform, but there is no guarantee that this property has the degrees + /// of freedom to properly respect it. + /// See the header comment {@link BlockProperty} for this method's mutability semantics. + @NotNull + TValue transform(TValue value, VectorTransform transform); +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/init/BlockPropertyInit.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/init/BlockPropertyInit.java new file mode 100644 index 00000000..2e5f9dbd --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/init/BlockPropertyInit.java @@ -0,0 +1,65 @@ +package com.gtnewhorizon.gtnhlib.blockstate.init; + +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.IBlockAccess; + +import org.jetbrains.annotations.Nullable; + +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockPropertyTrait; +import com.gtnewhorizon.gtnhlib.blockstate.core.MetaBlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.properties.IntegerBlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.registry.BlockPropertyFactory; +import com.gtnewhorizon.gtnhlib.blockstate.registry.BlockPropertyRegistry; + +public class BlockPropertyInit { + + public static void init() { + MetaProperty metaProperty = new MetaProperty(); + + BlockPropertyRegistry.registerProperty(new BlockPropertyFactory() { + + @Override + public BlockProperty getProperty(IBlockAccess world, int x, int y, int z, Block block, int meta, + @Nullable TileEntity tile) { + return metaProperty; + } + + @Override + public BlockProperty getProperty(ItemStack stack, Item item, int meta) { + return metaProperty; + } + }); + + VanillaBlockProperties.initVanilla(); + } + + private static class MetaProperty implements IntegerBlockProperty, MetaBlockProperty { + + @Override + public String getName() { + return "meta"; + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, SupportsStacks, OnlyNeedsMeta, WorldMutable, StackMutable -> true; + default -> false; + }; + } + + @Override + public int getMeta(Integer value, int existing) { + return existing; + } + + @Override + public Integer getValue(int meta) { + return meta; + } + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/init/VanillaBlockProperties.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/init/VanillaBlockProperties.java new file mode 100644 index 00000000..ccca86a7 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/init/VanillaBlockProperties.java @@ -0,0 +1,731 @@ +package com.gtnewhorizon.gtnhlib.blockstate.init; + +import static com.gtnewhorizon.gtnhlib.blockstate.registry.BlockPropertyRegistry.registerProperty; +import static net.minecraftforge.common.util.ForgeDirection.DOWN; +import static net.minecraftforge.common.util.ForgeDirection.EAST; +import static net.minecraftforge.common.util.ForgeDirection.NORTH; +import static net.minecraftforge.common.util.ForgeDirection.SOUTH; +import static net.minecraftforge.common.util.ForgeDirection.UNKNOWN; +import static net.minecraftforge.common.util.ForgeDirection.UP; +import static net.minecraftforge.common.util.ForgeDirection.WEST; + +import java.lang.reflect.Type; +import java.util.Arrays; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockAnvil; +import net.minecraft.block.BlockBasePressurePlate; +import net.minecraft.block.BlockButton; +import net.minecraft.block.BlockChest; +import net.minecraft.block.BlockDispenser; +import net.minecraft.block.BlockDoor; +import net.minecraft.block.BlockFenceGate; +import net.minecraft.block.BlockFurnace; +import net.minecraft.block.BlockHopper; +import net.minecraft.block.BlockLadder; +import net.minecraft.block.BlockPistonBase; +import net.minecraft.block.BlockPistonExtension; +import net.minecraft.block.BlockPumpkin; +import net.minecraft.block.BlockQuartz; +import net.minecraft.block.BlockRedstoneLight; +import net.minecraft.block.BlockRotatedPillar; +import net.minecraft.block.BlockSlab; +import net.minecraft.block.BlockStairs; +import net.minecraft.block.BlockTorch; +import net.minecraft.block.BlockTrapDoor; +import net.minecraft.init.Blocks; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.tileentity.TileEntitySign; +import net.minecraft.tileentity.TileEntitySkull; +import net.minecraft.util.MathHelper; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockPropertyTrait; +import com.gtnewhorizon.gtnhlib.blockstate.core.InvalidPropertyTextException; +import com.gtnewhorizon.gtnhlib.blockstate.core.MetaBlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.core.TransformableProperty; +import com.gtnewhorizon.gtnhlib.blockstate.core.VectorTransformableProperty; +import com.gtnewhorizon.gtnhlib.blockstate.mixin.BlockSkullExt; +import com.gtnewhorizon.gtnhlib.blockstate.properties.AxisBlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.properties.AxisBlockProperty.AbstractAxisBlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.properties.AxisBlockProperty.Meta; +import com.gtnewhorizon.gtnhlib.blockstate.properties.BooleanBlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.properties.BooleanBlockProperty.FlagBooleanBlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.properties.DirectionBlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.properties.FloatBlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.properties.IntegerBlockProperty; +import com.gtnewhorizon.gtnhlib.geometry.Axis; +import com.gtnewhorizon.gtnhlib.geometry.DirectionTransform; +import com.gtnewhorizon.gtnhlib.geometry.VectorTransform; + +class VanillaBlockProperties { + + static void initVanilla() { + registerProperty(BlockRotatedPillar.class, AxisBlockProperty.axis(0b1100, axis -> switch (axis) { + case X -> 0b100; + case Z -> 0b1000; + default -> 0; + }, meta -> switch (meta) { + case 0b100 -> Axis.X; + case 0b1000 -> Axis.Z; + default -> Axis.Y; + })); + + registerProperty(BlockQuartz.class, new AbstractAxisBlockProperty("axis") { + + @Override + public boolean appliesTo(IBlockAccess world, int x, int y, int z, Block block, int meta, + @Nullable TileEntity tile) { + return meta >= 2 && meta <= 4; + } + + @Override + public int getMeta(Axis value, int existing) { + if (existing < 2 || existing > 4) return existing; + + return switch (value) { + case X -> 3; + case Y -> 2; + case Z -> 4; + case UNKNOWN -> 2; + }; + } + + @Override + public Axis getValue(int meta) { + return switch (meta) { + case 3 -> Axis.X; + case 2 -> Axis.Y; + case 4 -> Axis.Z; + default -> Axis.UNKNOWN; + }; + } + }); + + class RailModeProperty implements MetaBlockProperty { + + private final boolean canTurn; + + public RailModeProperty(boolean canTurn) { + this.canTurn = canTurn; + } + + @Override + public String getName() { + return "mode"; + } + + @Override + public Type getType() { + return RailMode.class; + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, OnlyNeedsMeta, WorldMutable, Config -> true; + default -> false; + }; + } + + @Override + public RailMode getValue(int meta) { + return getRailMode(meta, canTurn); + } + + public int getMeta(RailMode value, int existing) { + return getRailMeta(value, getRailDirection(existing, canTurn), canTurn, false); + } + + @Override + public String stringify(RailMode value) { + return value.toString(); + } + + @Override + public RailMode parse(String text) throws InvalidPropertyTextException { + return RailMode.parse(text); + } + } + + registerProperty(Blocks.rail, new RailModeProperty(true)); + + registerProperty( + Blocks.rail, + DirectionBlockProperty.facing( + (dir, existing) -> getRailMeta(getRailMode(existing, true), dir, true, false), + meta -> getRailDirection(meta, true))); + + registerProperty( + Arrays.asList(Blocks.golden_rail, Blocks.detector_rail, Blocks.activator_rail), + new RailModeProperty(false)); + + registerProperty( + Arrays.asList(Blocks.golden_rail, Blocks.detector_rail, Blocks.activator_rail), + DirectionBlockProperty.facing( + (dir, existing) -> getRailMeta( + getRailMode(existing, false), + dir, + false, + isRailPowered(existing)), + meta -> getRailDirection(meta, false))); + + BooleanBlockProperty powered = BooleanBlockProperty.flag("powered", 0b1000); + + registerProperty(Arrays.asList(Blocks.golden_rail, Blocks.detector_rail, Blocks.activator_rail), powered); + + registerProperty(BlockButton.class, powered); + registerProperty(BlockButton.class, DirectionBlockProperty.facing(0b111, 3, 4, 1, 2, 0, 5)); + + registerProperty(BlockTorch.class, DirectionBlockProperty.facing(-1, 3, 4, 1, 2, 0, 5)); + registerProperty( + Blocks.redstone_torch, + BooleanBlockProperty.blocks("powered", Blocks.unlit_redstone_torch, Blocks.redstone_torch)); + registerProperty( + Blocks.unlit_redstone_torch, + BooleanBlockProperty.blocks("powered", Blocks.unlit_redstone_torch, Blocks.redstone_torch)); + + registerProperty(Blocks.lever, powered); + registerProperty(Blocks.lever, new Meta() { + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, OnlyNeedsMeta, WorldMutable, Config -> true; + default -> false; + }; + } + + @Override + public boolean isValidAxis(Axis value) { + return value == Axis.X || value == Axis.Z; + } + + // 0 = on ceiling, X + // 7 = on ceiling, Z + // 6 = on floor, X + // 5 = on floor, Z + + private static final int CEILING_X = 0, CEILING_Z = 7, FLOOR_X = 6, FLOOR_Z = 5; + + @Override + public Axis getValue(int meta) { + return switch (meta & 0b111) { + case CEILING_X, FLOOR_X -> Axis.X; + case CEILING_Z, FLOOR_Z -> Axis.Z; + default -> Axis.UNKNOWN; + }; + } + + @Override + public int getMeta(Axis value, int meta) { + int power = meta & 0b1000; + meta &= 0b111; + + boolean ceiling = meta == CEILING_X || meta == CEILING_Z; + + switch (getValue(meta)) { + case X -> meta = ceiling ? CEILING_X : FLOOR_X; + case Z -> meta = ceiling ? CEILING_Z : FLOOR_Z; + } + + return meta | power; + } + }); + + registerProperty( + Blocks.lever, + DirectionBlockProperty.facing((dir, existing) -> (existing & 0b1000) | switch (dir) { + case NORTH -> 3; + case SOUTH -> 4; + case WEST -> 1; + case EAST -> 2; + case UP -> ((existing & 0b111) == 7) ? 7 : 0; + case DOWN -> ((existing & 0b111) == 6) ? 6 : 5; + default -> 0; + }, meta -> switch (meta & 0b111) { + case 3 -> NORTH; + case 4 -> SOUTH; + case 1 -> WEST; + case 2 -> EAST; + case 0, 7 -> UP; + case 5, 6 -> DOWN; + default -> UNKNOWN; + })); + + registerProperty(BlockPistonBase.class, powered); + registerProperty(BlockPistonBase.class, DirectionBlockProperty.facing(0b111, 3, 4, 1, 2, 0, 5)); + registerProperty(BlockPistonExtension.class, DirectionBlockProperty.facing(0b111, 3, 4, 1, 2, 0, 5)); + + class SlabTopProperty extends FlagBooleanBlockProperty implements TransformableProperty { + + public SlabTopProperty() { + super("top", 0b1000); + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, OnlyNeedsMeta, WorldMutable, Config, Transformable -> true; + default -> false; + }; + } + + @Override + public @NotNull Boolean transform(Boolean value, DirectionTransform transform) { + ForgeDirection dir = transform.apply(value ? UP : DOWN); + + if (dir == UP) return true; + if (dir == DOWN) return false; + + return value; + } + + @Override + public boolean appliesTo(IBlockAccess world, int x, int y, int z, Block block, int meta, + @Nullable TileEntity tile) { + return (block instanceof BlockSlab slab) && !slab.isOpaqueCube(); + } + } + + registerProperty(BlockSlab.class, new SlabTopProperty()); + + registerProperty(BlockStairs.class, DirectionBlockProperty.facing(0b11, dir -> switch (dir) { + case EAST -> 0; + case WEST -> 1; + case SOUTH -> 2; + case NORTH -> 3; + default -> 0; + }, meta -> switch (meta) { + case 0 -> EAST; + case 1 -> WEST; + case 2 -> SOUTH; + case 3 -> NORTH; + default -> NORTH; + })); + + registerProperty(BlockStairs.class, DirectionBlockProperty.facing(0b100, dir -> switch (dir) { + case UP -> 0; + case DOWN -> 0b100; + default -> 0; + }, meta -> switch (meta) { + case 0 -> UP; + case 0b100 -> DOWN; + default -> UP; + }).setName("up")); + + registerProperty(BlockChest.class, DirectionBlockProperty.facing(0b111, 2, 3, 4, 5, -1, -1)); + + registerProperty(BlockAnvil.class, DirectionBlockProperty.facing(0b11, dir -> switch (dir) { + case WEST -> 0; + case NORTH -> 1; + case EAST -> 2; + case SOUTH -> 3; + default -> 0; + }, meta -> switch (meta) { + case 0 -> WEST; + case 1 -> NORTH; + case 2 -> EAST; + case 3 -> SOUTH; + default -> NORTH; + })); + + registerProperty( + BlockAnvil.class, + IntegerBlockProperty.meta("damage", 0b1100, 2) + .map(Arrays.asList("undamaged", "slightly_damaged", "very_damaged", "broken"))); + + registerProperty(Blocks.redstone_wire, IntegerBlockProperty.meta("power", 0b1111, 0)); + + registerProperty(BlockFurnace.class, DirectionBlockProperty.facing()); + registerProperty(BlockFurnace.class, BooleanBlockProperty.blocks("lit", Blocks.furnace, Blocks.lit_furnace)); + + class StandingSignRotationProperty + implements FloatBlockProperty, MetaBlockProperty, VectorTransformableProperty { + + @Override + public String getName() { + return "rotation"; + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, OnlyNeedsMeta, WorldMutable, Config, VectorTransformable -> true; + default -> false; + }; + } + + @Override + public boolean needsExisting() { + return false; + } + + @Override + public int getMeta(Float value, int existing) { + return (Math.round(value * 16f / 360f) % 16 + 16) % 16; + } + + @Override + public Float getValue(int meta) { + return meta * 360f / 16f; + } + + @Override + public @NotNull Float transform(Float value, VectorTransform transform) { + Vector3f v = new Vector3f(0, 0, 1).rotateAxis(value * (float) Math.PI * 2f / 360f, 0, 1, 0); + + transform.transform(v); + + float rotation = MathHelper.floor_double(Math.atan2(v.x, v.z) * 360d / Math.PI / 2d + 0.5); + rotation = (rotation % 360 + 360) % 360; + + return rotation; + } + } + + registerProperty(Blocks.wall_sign, DirectionBlockProperty.facing()); + registerProperty(Blocks.standing_sign, new StandingSignRotationProperty()); + registerProperty(TileEntitySign.class, new BlockProperty() { + + @Override + public String getName() { + return "text"; + } + + @Override + public Type getType() { + return String.class; + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, WorldMutable, Config -> true; + default -> false; + }; + } + + @Override + public boolean appliesTo(IBlockAccess world, int x, int y, int z, Block block, int meta, + @Nullable TileEntity tile) { + return tile instanceof TileEntitySign; + } + + @Override + public String getValue(IBlockAccess world, int x, int y, int z) { + if (!(world.getTileEntity(x, y, z) instanceof TileEntitySign sign)) return ""; + + return String.join("\n", sign.signText); + } + + @Override + public void setValue(World world, int x, int y, int z, String value) { + if (!(world.getTileEntity(x, y, z) instanceof TileEntitySign sign)) return; + + String[] text = value.split("\n"); + sign.signText = new String[4]; + + for (int i = 0; i < 4; i++) { + String line = BlockProperty.getIndexSafe(text, i); + + if (line == null) line = ""; + if (line.length() > 15) line = line.substring(0, 15); + + sign.signText[i] = line; + } + + sign.markDirty(); + world.markBlockForUpdate(x, y, z); + } + + @Override + public String stringify(String value) { + return value; + } + + @Override + public String parse(String text) { + return text; + } + }); + + registerProperty(BlockDoor.class, new DirectionBlockProperty() { + + @Override + public String getName() { + return "facing"; + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, WorldMutable, Config, Transformable -> true; + default -> false; + }; + } + + @Override + public boolean isValidDirection(ForgeDirection value) { + return value.offsetY == 0; + } + + @Override + public ForgeDirection getValue(IBlockAccess world, int x, int y, int z) { + int meta = world.getBlockMetadata(x, y, z); + if (meta == 8) { + y--; + if (!(world.getBlock(x, y, z) instanceof BlockDoor)) return UNKNOWN; + meta = world.getBlockMetadata(x, y, z); + } + return switch (meta & 0b11) { + case 0 -> WEST; + case 1 -> NORTH; + case 2 -> EAST; + case 3 -> SOUTH; + default -> NORTH; + }; + } + + @Override + public void setValue(World world, int x, int y, int z, ForgeDirection value) { + int meta = world.getBlockMetadata(x, y, z); + if (meta == 8) { + y--; + if (!(world.getBlock(x, y, z) instanceof BlockDoor)) return; + meta = world.getBlockMetadata(x, y, z); + } + + meta &= ~0b11; + meta |= switch (value) { + case WEST -> 0; + case NORTH -> 1; + case EAST -> 2; + case SOUTH -> 3; + default -> 1; + }; + + world.setBlockMetadataWithNotify(x, y, z, meta, 2); + } + }); + registerProperty(BlockDoor.class, new BooleanBlockProperty() { + + @Override + public String getName() { + return "open"; + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, WorldMutable, Config -> true; + default -> false; + }; + } + + @Override + public Boolean getValue(IBlockAccess world, int x, int y, int z) { + int meta = world.getBlockMetadata(x, y, z); + if (meta == 8) { + y--; + if (!(world.getBlock(x, y, z) instanceof BlockDoor)) return false; + meta = world.getBlockMetadata(x, y, z); + } + return meta >= 4; + } + + @Override + public void setValue(World world, int x, int y, int z, Boolean value) { + int meta = world.getBlockMetadata(x, y, z); + if (meta == 8) { + y--; + if (!(world.getBlock(x, y, z) instanceof BlockDoor)) return; + meta = world.getBlockMetadata(x, y, z); + } + + meta &= ~0b100; + if (value) meta |= 0b100; + + world.setBlockMetadataWithNotify(x, y, z, meta, 2); + } + }); + + registerProperty(BlockLadder.class, DirectionBlockProperty.facing()); + + registerProperty(BlockBasePressurePlate.class, BooleanBlockProperty.flag("powered", 0b1)); + + registerProperty(BlockPumpkin.class, DirectionBlockProperty.facing(0b11, 2, 0, 1, 3, -1, -1)); + + registerProperty( + Arrays.asList(Blocks.unpowered_repeater, Blocks.powered_repeater), + BooleanBlockProperty.blocks("powered", Blocks.unpowered_repeater, Blocks.powered_repeater)); + registerProperty( + Arrays.asList(Blocks.unpowered_repeater, Blocks.powered_repeater), + DirectionBlockProperty.facing(0b11, 0, 2, 3, 1, -1, -1)); + registerProperty( + Arrays.asList(Blocks.unpowered_repeater, Blocks.powered_repeater), + IntegerBlockProperty.meta("delay", 0b1100, 2)); + + registerProperty(BlockTrapDoor.class, DirectionBlockProperty.facing(0b11, 0, 1, 2, 3, -1, -1)); + registerProperty(BlockTrapDoor.class, BooleanBlockProperty.flag("open", 0b100)); + registerProperty( + BlockTrapDoor.class, + DirectionBlockProperty.facing(0b1000, -1, -1, -1, -1, 0b1000, 0).setName("up")); + + registerProperty( + BlockRedstoneLight.class, + BooleanBlockProperty.blocks("powered", Blocks.redstone_lamp, Blocks.lit_redstone_lamp)); + + registerProperty(Blocks.tripwire_hook, DirectionBlockProperty.facing(0b11, 0, 2, 3, 1, -1, -1)); + registerProperty(Blocks.tripwire_hook, powered); + registerProperty(Blocks.tripwire_hook, BooleanBlockProperty.flag("connected", 0b100)); + + class SkullRotationProperty implements IntegerBlockProperty, VectorTransformableProperty { + + @Override + public String getName() { + return "rotation"; + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, WorldMutable, Config, VectorTransformable -> true; + default -> false; + }; + } + + @Override + public Integer getValue(IBlockAccess world, int x, int y, int z) { + if (!(world.getTileEntity(x, y, z) instanceof BlockSkullExt skull)) return 0; + + return skull.gtnhlib$getRotation() * 360 / 16; + } + + @Override + public void setValue(World world, int x, int y, int z, Integer value) { + if (!(world.getTileEntity(x, y, z) instanceof BlockSkullExt skull)) return; + + skull.gtnhlib$setRotation(value * 16 / 360); + + world.markBlockForUpdate(x, y, z); + } + + @Override + public @NotNull Integer transform(Integer value, VectorTransform transform) { + Vector3f v = new Vector3f(0, 0, 1).rotateAxis(value * (float) Math.PI * 2f / 360f, 0, 1, 0); + + transform.transform(v); + + int rotation = MathHelper.floor_double(Math.atan2(v.x, v.z) * 360d / Math.PI / 2d + 0.5); + + return (rotation % 360 + 360) % 360; + } + } + + registerProperty(TileEntitySkull.class, new SkullRotationProperty()); + + registerProperty(BlockDispenser.class, DirectionBlockProperty.facing()); + + registerProperty( + Arrays.asList(Blocks.unpowered_comparator, Blocks.powered_comparator), + BooleanBlockProperty.flag("powered", 0b1000)); + registerProperty( + Arrays.asList(Blocks.unpowered_comparator, Blocks.powered_comparator), + DirectionBlockProperty.facing(0b11, 0, 2, 3, 1, -1, -1)); + registerProperty( + Arrays.asList(Blocks.unpowered_comparator, Blocks.powered_comparator), + IntegerBlockProperty.meta("mode", 0b100, 2).map(Arrays.asList("comparator", "subtractor"))); + + registerProperty(BlockHopper.class, DirectionBlockProperty.facing()); + + registerProperty(BlockFenceGate.class, DirectionBlockProperty.facing(0b11, 2, 0, 1, 3, -1, -1)); + registerProperty(BlockFenceGate.class, BooleanBlockProperty.flag("open", 0b100)); + } + + public enum RailMode { + + NONE, + ASCENDING, + TURNED; + + public String toString() { + return switch (this) { + case NONE -> "none"; + case ASCENDING -> "ascending"; + case TURNED -> "turned"; + }; + } + + public static RailMode parse(String name) throws InvalidPropertyTextException { + if ("turned".equals(name)) return TURNED; + if ("ascending".equals(name)) return ASCENDING; + if ("none".equals(name)) return NONE; + throw new InvalidPropertyTextException("Illegal rail mode: '" + name + "'"); + } + } + + private static RailMode getRailMode(int meta, boolean canTurn) { + return canTurn && meta >= 6 ? RailMode.TURNED : meta >= 2 ? RailMode.ASCENDING : RailMode.NONE; + } + + private static ForgeDirection getRailDirection(int meta, boolean canTurn) { + if (canTurn) { + return switch (meta) { + case 0, 4, 6 -> NORTH; + case 1, 3, 9 -> WEST; + case 2, 7 -> EAST; + case 5, 8 -> SOUTH; + default -> NORTH; + }; + } else { + return switch (meta) { + case 0, 4 -> NORTH; + case 1, 3 -> WEST; + case 2 -> EAST; + case 5 -> SOUTH; + default -> NORTH; + }; + } + } + + private static boolean isRailPowered(int meta) { + return meta >= 8; + } + + private static int getRailMeta(RailMode mode, ForgeDirection dir, boolean canTurn, boolean powered) { + if (canTurn && mode == RailMode.TURNED) { + return switch (dir) { + case NORTH -> 6; + case WEST -> 9; + case EAST -> 7; + case SOUTH -> 8; + default -> 0; + }; + } + + if (mode == RailMode.ASCENDING) { + return switch (dir) { + case NORTH -> 4; + case WEST -> 3; + case EAST -> 2; + case SOUTH -> 5; + default -> 0; + }; + } + + return switch (dir) { + case NORTH, SOUTH -> 0; + case EAST, WEST -> 1; + default -> 0; + }; + } + +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/mixin/BlockSkullExt.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/mixin/BlockSkullExt.java new file mode 100644 index 00000000..1f158891 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/mixin/BlockSkullExt.java @@ -0,0 +1,11 @@ +package com.gtnewhorizon.gtnhlib.blockstate.mixin; + +import org.jetbrains.annotations.ApiStatus; + +@ApiStatus.Internal +public interface BlockSkullExt { + + int gtnhlib$getRotation(); + + void gtnhlib$setRotation(int rotation); +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/AxisBlockProperty.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/AxisBlockProperty.java new file mode 100644 index 00000000..460cca52 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/AxisBlockProperty.java @@ -0,0 +1,124 @@ +package com.gtnewhorizon.gtnhlib.blockstate.properties; + +import java.lang.reflect.Type; + +import org.jetbrains.annotations.NotNull; + +import com.google.gson.JsonElement; +import com.google.gson.JsonPrimitive; +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockPropertyTrait; +import com.gtnewhorizon.gtnhlib.blockstate.core.InvalidPropertyTextException; +import com.gtnewhorizon.gtnhlib.blockstate.core.MetaBlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.core.TransformableProperty; +import com.gtnewhorizon.gtnhlib.geometry.Axis; +import com.gtnewhorizon.gtnhlib.geometry.DirectionTransform; + +public interface AxisBlockProperty extends BlockProperty, TransformableProperty { + + @Override + default String getName() { + return "axis"; + } + + @Override + default Type getType() { + return Axis.class; + } + + @Override + default JsonElement serialize(Axis value) { + return new JsonPrimitive(stringify(value)); + } + + @Override + default Axis deserialize(JsonElement element) { + return element.isJsonPrimitive() && element.getAsJsonPrimitive().isString() ? parse(element.getAsString()) + : Axis.UNKNOWN; + } + + @Override + default String stringify(Axis value) { + return value.name().toLowerCase(); + } + + @Override + default Axis parse(String text) throws InvalidPropertyTextException { + try { + return Axis.valueOf(text.toUpperCase()); + } catch (IllegalArgumentException e) { + throw new InvalidPropertyTextException("Invalid Axis", e); + } + } + + default boolean isValidAxis(Axis value) { + return true; + } + + @Override + default @NotNull Axis transform(Axis value, DirectionTransform transform) { + Axis axis = Axis.fromDirection(transform.apply(value.positive())); + + return isValidAxis(axis) ? axis : value; + } + + interface Meta extends AxisBlockProperty, MetaBlockProperty { + + @Override + default boolean appliesTo(int meta) { + return isValidAxis(getValue(meta)); + } + } + + abstract class AbstractAxisBlockProperty implements Meta { + + private final String name; + + public AbstractAxisBlockProperty(String name) { + this.name = name; + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, WorldMutable, OnlyNeedsMeta, Config, Transformable -> true; + default -> false; + }; + } + } + + interface A2M { + + int getMeta(Axis axis); + } + + interface M2A { + + Axis getAxis(int meta); + } + + static AbstractAxisBlockProperty axis(int mask, A2M toMeta, M2A toAxis) { + return new AbstractAxisBlockProperty("axis") { + + @Override + public boolean needsExisting() { + return mask != -1; + } + + @Override + public int getMeta(Axis value, int existing) { + return toMeta.getMeta(value) | (existing & ~mask); + } + + @Override + public Axis getValue(int meta) { + return toAxis.getAxis(meta & mask); + } + }; + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/BooleanBlockProperty.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/BooleanBlockProperty.java new file mode 100644 index 00000000..747fed40 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/BooleanBlockProperty.java @@ -0,0 +1,107 @@ +package com.gtnewhorizon.gtnhlib.blockstate.properties; + +import java.lang.reflect.Type; + +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; + +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockPropertyTrait; +import com.gtnewhorizon.gtnhlib.blockstate.core.MetaBlockProperty; +import com.gtnewhorizon.gtnhlib.util.data.BlockSupplier; + +public interface BooleanBlockProperty extends BlockProperty { + + @Override + default Type getType() { + return boolean.class; + } + + static FlagBooleanBlockProperty flag(String name, int flag) { + return new FlagBooleanBlockProperty(name, flag); + } + + class FlagBooleanBlockProperty implements BooleanBlockProperty, MetaBlockProperty { + + public final String name; + public final int flag; + + public FlagBooleanBlockProperty(String name, int flag) { + this.name = name; + this.flag = flag; + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, SupportsStacks, OnlyNeedsMeta, WorldMutable, StackMutable -> true; + default -> false; + }; + } + + @Override + public int getMeta(Boolean value, int existing) { + existing &= ~flag; + if (value) existing |= flag; + + return existing; + } + + @Override + public Boolean getValue(int meta) { + return (meta & flag) == flag; + } + } + + static BooleanBlockProperty blocks(String name, Block falsey, Block truthy) { + return blocks(name, () -> falsey, () -> truthy); + } + + static BooleanBlockProperty blocks(String name, BlockSupplier falsey, BlockSupplier truthy) { + return new BooleanBlockProperty() { + + @Override + public String getName() { + return name; + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, SupportsStacks, WorldMutable, StackMutable -> true; + default -> false; + }; + } + + @Override + public Boolean getValue(IBlockAccess world, int x, int y, int z) { + return world.getBlock(x, y, z) == truthy.get(); + } + + @Override + public void setValue(World world, int x, int y, int z, Boolean value) { + world.setBlock(x, y, z, value ? truthy.get() : falsey.get(), world.getBlockMetadata(x, y, z), 2); + } + + @Override + public Boolean getValue(ItemStack stack) { + // noinspection DataFlowIssue + return ((ItemBlock) stack.getItem()).field_150939_a == truthy.get(); + } + + @Override + public void setValue(ItemStack stack, Boolean value) { + stack.func_150996_a(Item.getItemFromBlock(value ? truthy.get() : falsey.get())); + } + }; + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/DirectionBlockProperty.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/DirectionBlockProperty.java new file mode 100644 index 00000000..11d58435 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/DirectionBlockProperty.java @@ -0,0 +1,207 @@ +package com.gtnewhorizon.gtnhlib.blockstate.properties; + +import static net.minecraftforge.common.util.ForgeDirection.DOWN; +import static net.minecraftforge.common.util.ForgeDirection.EAST; +import static net.minecraftforge.common.util.ForgeDirection.NORTH; +import static net.minecraftforge.common.util.ForgeDirection.SOUTH; +import static net.minecraftforge.common.util.ForgeDirection.UNKNOWN; +import static net.minecraftforge.common.util.ForgeDirection.UP; +import static net.minecraftforge.common.util.ForgeDirection.WEST; + +import java.lang.reflect.Type; + +import net.minecraftforge.common.util.ForgeDirection; + +import org.jetbrains.annotations.NotNull; + +import com.google.gson.JsonElement; +import com.google.gson.JsonPrimitive; +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockPropertyTrait; +import com.gtnewhorizon.gtnhlib.blockstate.core.InvalidPropertyTextException; +import com.gtnewhorizon.gtnhlib.blockstate.core.MetaBlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.core.TransformableProperty; +import com.gtnewhorizon.gtnhlib.geometry.DirectionTransform; + +public interface DirectionBlockProperty extends BlockProperty, TransformableProperty { + + @Override + default String getName() { + return "direction"; + } + + @Override + default Type getType() { + return ForgeDirection.class; + } + + @Override + default @NotNull ForgeDirection transform(ForgeDirection value, DirectionTransform transform) { + ForgeDirection dir = transform.apply(value); + + return isValidDirection(dir) ? dir : value; + } + + @Override + default JsonElement serialize(ForgeDirection value) { + return new JsonPrimitive(stringify(value)); + } + + @Override + default ForgeDirection deserialize(JsonElement element) { + return element.isJsonPrimitive() && element.getAsJsonPrimitive().isString() ? parse(element.getAsString()) + : UNKNOWN; + } + + @Override + default String stringify(ForgeDirection value) { + return value.name().toLowerCase(); + } + + @Override + default ForgeDirection parse(String text) throws InvalidPropertyTextException { + try { + return ForgeDirection.valueOf(text.toUpperCase()); + } catch (IllegalArgumentException e) { + throw new InvalidPropertyTextException("Invalid ForgeDirection", e); + } + } + + default boolean isValidDirection(ForgeDirection value) { + return true; + } + + abstract class AbstractDirectionBlockProperty implements DirectionBlockProperty, MetaBlockProperty { + + private String name; + + public AbstractDirectionBlockProperty(String name) { + this.name = name; + } + + public AbstractDirectionBlockProperty setName(String name) { + this.name = name; + return this; + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, WorldMutable, OnlyNeedsMeta, Config, Transformable -> true; + default -> false; + }; + } + } + + static DirectionBlockProperty facing() { + return new AbstractDirectionBlockProperty("facing") { + + @Override + public int getMeta(ForgeDirection value, int existing) { + return value.ordinal(); + } + + @Override + public ForgeDirection getValue(int meta) { + return ForgeDirection.getOrientation(meta); + } + }; + } + + static AbstractDirectionBlockProperty facingVanilla(int mask) { + return facing(mask, dir -> switch (dir) { + case NORTH -> 3; + case SOUTH -> 4; + case WEST -> 1; + case EAST -> 2; + case UP -> 0; + case DOWN -> 5; + default -> 3; + }, meta -> switch (meta) { + case 3 -> NORTH; + case 4 -> SOUTH; + case 1 -> WEST; + case 2 -> EAST; + case 0 -> UP; + case 5 -> DOWN; + default -> NORTH; + }); + } + + interface D2M { + + int getMeta(ForgeDirection dir); + } + + interface M2D { + + ForgeDirection getDir(int meta); + } + + static AbstractDirectionBlockProperty facing(int mask, D2M toMeta, M2D toDir) { + return new AbstractDirectionBlockProperty("facing") { + + @Override + public boolean needsExisting() { + return mask != -1; + } + + @Override + public int getMeta(ForgeDirection value, int existing) { + // If the mask == -1, the right side of this | becomes 0 regardless of what existing is. + return toMeta.getMeta(value) | (existing & ~mask); + } + + @Override + public ForgeDirection getValue(int meta) { + return toDir.getDir(meta & mask); + } + }; + } + + interface D2M2 { + + int getMeta(ForgeDirection dir, int existing); + } + + static AbstractDirectionBlockProperty facing(D2M2 toMeta, M2D toDir) { + return new AbstractDirectionBlockProperty("facing") { + + @Override + public int getMeta(ForgeDirection value, int existing) { + return toMeta.getMeta(value, existing); + } + + @Override + public ForgeDirection getValue(int meta) { + return toDir.getDir(meta); + } + }; + } + + static AbstractDirectionBlockProperty facing(int mask, int north, int south, int west, int east, int up, int down) { + return facing(mask, dir -> switch (dir) { + case NORTH -> north == -1 ? 0 : north; + case SOUTH -> south == -1 ? 0 : south; + case WEST -> west == -1 ? 0 : west; + case EAST -> east == -1 ? 0 : east; + case UP -> up == -1 ? 0 : up; + case DOWN -> down == -1 ? 0 : down; + case UNKNOWN -> 0; + }, meta -> { + if (meta == north) return NORTH; + if (meta == south) return SOUTH; + if (meta == west) return WEST; + if (meta == east) return EAST; + if (meta == up) return UP; + if (meta == down) return DOWN; + + return UNKNOWN; + }); + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/FloatBlockProperty.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/FloatBlockProperty.java new file mode 100644 index 00000000..0a8fa236 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/FloatBlockProperty.java @@ -0,0 +1,13 @@ +package com.gtnewhorizon.gtnhlib.blockstate.properties; + +import java.lang.reflect.Type; + +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockProperty; + +public interface FloatBlockProperty extends BlockProperty { + + @Override + default Type getType() { + return float.class; + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/IntegerBlockProperty.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/IntegerBlockProperty.java new file mode 100644 index 00000000..5b189d20 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/IntegerBlockProperty.java @@ -0,0 +1,137 @@ +package com.gtnewhorizon.gtnhlib.blockstate.properties; + +import java.lang.reflect.Type; +import java.util.List; + +import net.minecraft.item.ItemStack; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; + +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockPropertyTrait; +import com.gtnewhorizon.gtnhlib.blockstate.core.MetaBlockProperty; + +public interface IntegerBlockProperty extends BlockProperty { + + @Override + default Type getType() { + return int.class; + } + + default BlockProperty map(List values) { + return new MappedBlockProperty(this, values); + } + + @SuppressWarnings("unchecked") + class MappedBlockProperty implements BlockProperty, MetaBlockProperty { + + private final IntegerBlockProperty base; + private final List values; + + public MappedBlockProperty(IntegerBlockProperty base, List values) { + this.base = base; + this.values = values; + } + + @Override + public String getName() { + return base.getName(); + } + + @Override + public Type getType() { + return String.class; + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + if (trait == BlockPropertyTrait.Transformable) return false; + + return base.hasTrait(trait); + } + + @Override + public String getValue(IBlockAccess world, int x, int y, int z) { + return BlockProperty.getIndexSafe(values, base.getValue(world, x, y, z)); + } + + @Override + public void setValue(World world, int x, int y, int z, String value) { + base.setValue(world, x, y, z, values.indexOf(value)); + } + + @Override + public String getValue(ItemStack stack) { + return BlockProperty.getIndexSafe(values, base.getValue(stack)); + } + + @Override + public void setValue(ItemStack stack, String value) { + base.setValue(stack, values.indexOf(value)); + } + + @Override + public boolean needsExisting() { + return ((MetaBlockProperty) base).needsExisting(); + } + + @Override + public int getMeta(String value, int existing) { + return ((MetaBlockProperty) base).getMeta(values.indexOf(value), existing); + } + + @Override + public String getValue(int meta) { + return values.get(((MetaBlockProperty) base).getValue(meta)); + } + } + + static IntegerBlockProperty meta(String name, int mask, int shift) { + return new MetaIntegerBlockProperty(name, mask, shift); + } + + class MetaIntegerBlockProperty implements IntegerBlockProperty, MetaBlockProperty { + + private final String name; + private final int mask; + private final int shift; + + public MetaIntegerBlockProperty(String name, int mask, int shift) { + this.name = name; + this.mask = mask; + this.shift = shift; + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, SupportsStacks, OnlyNeedsMeta, WorldMutable, StackMutable -> true; + default -> false; + }; + } + + @Override + public boolean needsExisting() { + return mask != -1; + } + + @Override + public int getMeta(Integer value, int existing) { + int meta = existing & ~mask; + + meta |= (value << shift) & mask; + + return meta; + } + + @Override + public Integer getValue(int meta) { + return (meta & mask) >> shift; + } + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/OrientationBlockProperty.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/OrientationBlockProperty.java new file mode 100644 index 00000000..6656f395 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/properties/OrientationBlockProperty.java @@ -0,0 +1,119 @@ +package com.gtnewhorizon.gtnhlib.blockstate.properties; + +import java.lang.reflect.Type; + +import net.minecraftforge.common.util.ForgeDirection; + +import org.jetbrains.annotations.NotNull; + +import com.google.gson.JsonElement; +import com.google.gson.JsonPrimitive; +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockPropertyTrait; +import com.gtnewhorizon.gtnhlib.blockstate.core.InvalidPropertyTextException; +import com.gtnewhorizon.gtnhlib.blockstate.core.MetaBlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.core.TransformableProperty; +import com.gtnewhorizon.gtnhlib.geometry.DirectionTransform; +import com.gtnewhorizon.gtnhlib.geometry.Orientation; + +public interface OrientationBlockProperty extends BlockProperty, TransformableProperty { + + @Override + default String getName() { + return "orientation"; + } + + @Override + default Type getType() { + return Orientation.class; + } + + @Override + default JsonElement serialize(Orientation value) { + return new JsonPrimitive(stringify(value)); + } + + @Override + default Orientation deserialize(JsonElement element) { + return element.isJsonPrimitive() && element.getAsJsonPrimitive().isString() ? parse(element.getAsString()) + : Orientation.UNKNOWN; + } + + @Override + default String stringify(Orientation value) { + return value.name().toLowerCase(); + } + + @Override + default Orientation parse(String text) throws InvalidPropertyTextException { + try { + return Orientation.valueOf(text.toUpperCase()); + } catch (IllegalArgumentException e) { + throw new InvalidPropertyTextException("Invalid Orientation", e); + } + } + + @Override + default @NotNull Orientation transform(Orientation value, DirectionTransform transform) { + ForgeDirection a = transform.apply(value.a); + ForgeDirection b = transform.apply(value.b); + + Orientation transformed = Orientation.getOrientation(a, b); + + return isValidOrientation(transformed) ? transformed : value; + } + + default boolean isValidOrientation(Orientation value) { + return true; + } + + interface O2M { + + int getMeta(Orientation dir); + } + + interface M2O { + + Orientation getDir(int meta); + } + + static OrientationBlockProperty orientation(int mask, O2M o2m, M2O m2o) { + return new MetaOrientationBlockProperty(m2o, mask, o2m); + } + + class MetaOrientationBlockProperty implements OrientationBlockProperty, MetaBlockProperty { + + private final M2O m2o; + private final int mask; + private final O2M o2m; + + public MetaOrientationBlockProperty(M2O m2o, int mask, O2M o2m) { + this.m2o = m2o; + this.mask = mask; + this.o2m = o2m; + } + + @Override + public boolean needsExisting() { + return mask != -1; + } + + @Override + public int getMeta(Orientation value, int existing) { + return o2m.getMeta(value) | (existing & ~mask); + } + + @Override + public Orientation getValue(int meta) { + return m2o.getDir(meta & mask); + } + + @Override + public boolean hasTrait(BlockPropertyTrait trait) { + return switch (trait) { + case SupportsWorld, OnlyNeedsMeta, WorldMutable, Config, Transformable -> true; + default -> false; + }; + } + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/registry/BlockPropertyFactory.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/registry/BlockPropertyFactory.java new file mode 100644 index 00000000..5aa32622 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/registry/BlockPropertyFactory.java @@ -0,0 +1,25 @@ +package com.gtnewhorizon.gtnhlib.blockstate.registry; + +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.IBlockAccess; + +import org.jetbrains.annotations.Nullable; + +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockProperty; + +public interface BlockPropertyFactory { + + @Nullable + default BlockProperty getProperty(IBlockAccess world, int x, int y, int z, Block block, int meta, + @Nullable TileEntity tile) { + return null; + } + + @Nullable + default BlockProperty getProperty(ItemStack stack, Item item, int meta) { + return null; + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/registry/BlockPropertyRegistry.java b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/registry/BlockPropertyRegistry.java new file mode 100644 index 00000000..3edc1817 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/blockstate/registry/BlockPropertyRegistry.java @@ -0,0 +1,246 @@ +package com.gtnewhorizon.gtnhlib.blockstate.registry; + +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; + +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.IBlockAccess; + +import org.jetbrains.annotations.NotNull; + +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockProperty; +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockPropertyTrait; +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockState; +import com.gtnewhorizon.gtnhlib.blockstate.core.BlockStateImpl; +import com.gtnewhorizon.gtnhlib.util.data.BlockMeta; +import com.gtnewhorizon.gtnhlib.util.data.ImmutableBlockMeta; +import com.gtnewhorizon.gtnhlib.util.data.ImmutableItemMeta; +import com.gtnewhorizon.gtnhlib.util.data.ItemMeta; + +import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; + +public class BlockPropertyRegistry { + + private BlockPropertyRegistry() {} + + private static class PropertyMap extends Object2ObjectOpenHashMap>> { + + public void add(K key, BlockProperty prop) { + this.computeIfAbsent(key, x -> new Object2ObjectArrayMap<>()).put(prop.getName(), prop); + } + + public void copyAll(K key, Map> out) { + var map = this.get(key); + + if (map != null) { + out.putAll(map); + } + } + } + + private static class CachedPropertyMap extends PropertyMap { + + private final Function>> fn; + + public CachedPropertyMap(Function>> fn) { + this.fn = fn; + } + + @SuppressWarnings("unchecked") + @Override + public Map> get(Object k) { + var map = super.get(k); + + if (map == null) { + map = fn.apply((K) k); + + this.put( + (K) k, + map == null || map.isEmpty() ? Collections.emptyMap() : Collections.unmodifiableMap(map)); + } + + return map; + } + } + + private static final PropertyMap BLOCK_PROPERTIES = new PropertyMap<>(); + private static final PropertyMap BLOCK_META_PROPERTIES = new PropertyMap<>(); + + private static final PropertyMap ITEM_PROPERTIES = new PropertyMap<>(); + private static final PropertyMap ITEM_META_PROPERTIES = new PropertyMap<>(); + + private static final PropertyMap IFACE_PROPERTIES = new PropertyMap<>(); + private static final CachedPropertyMap IFACE_CACHE = new CachedPropertyMap<>( + BlockPropertyRegistry::getInterfaceProperties); + + private static final ObjectArrayList> CUSTOM_PROPERTIES = new ObjectArrayList<>(); + + public static void registerProperty(Block block, BlockProperty property) { + BLOCK_PROPERTIES.add(block, property); + } + + public static void registerProperty(Collection blocks, BlockProperty property) { + for (Block block : blocks) { + BLOCK_PROPERTIES.add(block, property); + } + } + + public static void registerProperty(Block block, int blockMeta, BlockProperty property) { + registerProperty(new BlockMeta(block, blockMeta), property); + } + + public static void registerProperty(ImmutableBlockMeta bm, BlockProperty property) { + BLOCK_META_PROPERTIES.add(new BlockMeta(bm), property); + } + + public static void registerProperty(Item item, BlockProperty property) { + if (!(item instanceof ItemBlock)) throw new IllegalArgumentException("Item must be an ItemBlock: " + item); + + ITEM_PROPERTIES.add(item, property); + } + + public static void registerProperty(Item item, int itemMeta, BlockProperty property) { + registerProperty(new ItemMeta(item, itemMeta), property); + } + + public static void registerProperty(ImmutableItemMeta im, BlockProperty property) { + if (!(im.getItem() instanceof ItemBlock)) + throw new IllegalArgumentException("Item must be an ItemBlock: " + im); + + ITEM_META_PROPERTIES.add(new ItemMeta(im), property); + } + + public static void registerProperty(Type iface, BlockProperty property) { + IFACE_PROPERTIES.add(iface, property); + } + + public static void registerProperty(BlockPropertyFactory factory) { + CUSTOM_PROPERTIES.add(factory); + } + + @NotNull + private static Map> getInterfaceProperties(Type clazz) { + Map> cache = new Object2ObjectArrayMap<>(); + + ObjectLinkedOpenHashSet queue = new ObjectLinkedOpenHashSet<>(); + + queue.add(clazz); + + while (!queue.isEmpty()) { + Type curr = queue.removeFirst(); + + IFACE_PROPERTIES.copyAll(curr, cache); + + if (curr instanceof Classclazz2) { + for (Type iface : clazz2.getGenericInterfaces()) { + queue.addAndMoveToFirst(iface); + } + + for (Type iface : clazz2.getInterfaces()) { + queue.addAndMoveToFirst(iface); + } + + if (clazz2.getSuperclass() != null && clazz2.getSuperclass() != Object.class) { + queue.add(clazz2.getGenericSuperclass()); + queue.add(clazz2.getSuperclass()); + } + } + } + + return cache; + } + + private static final BlockMeta POOLED_BM = new BlockMeta(Blocks.air); + + public static void getProperties(IBlockAccess world, int x, int y, int z, + Map> properties) { + properties.clear(); + + Block block = world.getBlock(x, y, z); + int meta = world.getBlockMetadata(x, y, z); + + BLOCK_PROPERTIES.copyAll(block, properties); + BLOCK_META_PROPERTIES.copyAll(POOLED_BM.setBlock(block).setBlockMeta(meta), properties); + IFACE_CACHE.copyAll(block.getClass(), properties); + + TileEntity tile; + + if (block.hasTileEntity(meta)) { + tile = world.getTileEntity(x, y, z); + + if (tile != null) { + IFACE_CACHE.copyAll(tile.getClass(), properties); + } + } else { + tile = null; + } + + CUSTOM_PROPERTIES.forEach(factory -> { + BlockProperty property = factory.getProperty(world, x, y, z, block, meta, tile); + + if (property != null) { + properties.put(property.getName(), property); + } + }); + + properties.entrySet().removeIf(e -> { + if (!e.getValue().appliesTo(world, x, y, z, block, meta, tile)) return true; + return !e.getValue().hasTrait(BlockPropertyTrait.SupportsWorld); + }); + } + + private static final ItemMeta POOLED_IM = new ItemMeta(Items.feather); + + public static void getProperties(ItemStack stack, Map> properties) { + properties.clear(); + + Item item = Objects.requireNonNull(stack.getItem(), "Item cannot be null: " + stack); + int meta = Items.feather.getDamage(stack); + + ITEM_PROPERTIES.copyAll(item, properties); + ITEM_META_PROPERTIES.copyAll(POOLED_IM.setItem(item).setItemMeta(meta), properties); + IFACE_CACHE.copyAll(item.getClass(), properties); + + CUSTOM_PROPERTIES.forEach(factory -> { + BlockProperty property = factory.getProperty(stack, item, meta); + + if (property != null) { + properties.put(property.getName(), property); + } + }); + + properties.entrySet().removeIf(e -> { + if (!e.getValue().appliesTo(stack, item, meta)) return true; + return !e.getValue().hasTrait(BlockPropertyTrait.SupportsStacks); + }); + } + + public static BlockState getBlockState(IBlockAccess world, int x, int y, int z) { + BlockStateImpl state = BlockStateImpl.getInstance(); + + state.fromWorld(world, x, y, z); + + return state; + } + + public static BlockState getBlockState(ItemStack stack) { + BlockStateImpl state = BlockStateImpl.getInstance(); + + state.fromStack(stack); + + return state; + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/color/HSVColor.java b/src/main/java/com/gtnewhorizon/gtnhlib/color/HSVColor.java new file mode 100644 index 00000000..a9da93cb --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/color/HSVColor.java @@ -0,0 +1,75 @@ +package com.gtnewhorizon.gtnhlib.color; + +public class HSVColor implements ImmutableColor { + + public float hue, saturation, brightness; + + public HSVColor() {} + + public HSVColor(float hue, float saturation, float brightness) { + this.hue = hue; + this.saturation = saturation; + this.brightness = brightness; + } + + @Override + public int toIntRGB() { + return toIntARGB() & 0xFFFFFF; + } + + @Override + public int toIntARGB() { + return java.awt.Color.HSBtoRGB(hue, saturation, brightness); + } + + @Override + public int toIntRGBA() { + return toIntRGB() << 8 | 0xFF; + } + + @Override + public HSVColor toHSV() { + return new HSVColor(hue, saturation, brightness); + } + + @Override + public int getRed() { + return (toIntARGB() >> 16) & 0xFF; + } + + @Override + public int getGreen() { + return (toIntARGB() >> 8) & 0xFF; + } + + @Override + public int getBlue() { + return toIntARGB() & 0xFF; + } + + @Override + public int getAlpha() { + return 255; + } + + @Override + public final boolean equals(Object o) { + if (!(o instanceof HSVColor hsvColor)) return false; + + return Float.compare(hue, hsvColor.hue) == 0 && Float.compare(saturation, hsvColor.saturation) == 0 + && Float.compare(brightness, hsvColor.brightness) == 0; + } + + @Override + public int hashCode() { + int result = Float.hashCode(hue); + result = 31 * result + Float.hashCode(saturation); + result = 31 * result + Float.hashCode(brightness); + return result; + } + + @Override + public String toString() { + return "HSVColor{" + "hue=" + hue + ", saturation=" + saturation + ", brightness=" + brightness + '}'; + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/color/ImmutableColor.java b/src/main/java/com/gtnewhorizon/gtnhlib/color/ImmutableColor.java new file mode 100644 index 00000000..32383a4a --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/color/ImmutableColor.java @@ -0,0 +1,73 @@ +package com.gtnewhorizon.gtnhlib.color; + +import org.lwjgl.opengl.GL11; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +@SuppressWarnings("unused") +public interface ImmutableColor { + + int getRed(); + + int getGreen(); + + int getBlue(); + + int getAlpha(); + + default int toIntRGB() { + return ((getRed() & 0xFF) << 16) | ((getGreen() & 0xFF) << 8) | (getBlue() & 0xFF); + } + + default int toIntARGB() { + return ((getAlpha() & 0xFF) << 24) | ((getRed() & 0xFF) << 16) + | ((getGreen() & 0xFF) << 8) + | (getBlue() & 0xFF); + } + + default int toIntRGBA() { + return ((getRed() & 0xFF) << 24) | ((getGreen() & 0xFF) << 16) + | ((getBlue() & 0xFF) << 8) + | ((getAlpha() & 0xFF)); + } + + default int toIntABGR() { + return (getRed() & 0xFF) | ((getGreen() & 0xFF) << 8) + | ((getBlue() & 0xFF) << 16) + | ((getAlpha() & 0xFF) << 24); + } + + default RGBColor toRGB() { + return new RGBColor(getRed(), getGreen(), getBlue(), getAlpha()); + } + + default HSVColor toHSV() { + float[] hsv = java.awt.Color.RGBtoHSB(getRed(), getGreen(), getBlue(), null); + + return new HSVColor(hsv[0], hsv[1], hsv[2]); + } + + @SideOnly(Side.CLIENT) + default void makeActive() { + GL11.glColor4f(getRed() / 256f, getGreen() / 256f, getBlue() / 256f, getAlpha() / 256f); + } + + default short[] toShorts() { + return new short[] { (short) getRed(), (short) getGreen(), (short) getBlue(), (short) getAlpha() }; + } + + static HSVColor lerp(ImmutableColor a, ImmutableColor b, float k) { + HSVColor hsvA = a instanceof HSVColor hsv ? hsv : a.toHSV(); + HSVColor hsvB = b instanceof HSVColor hsv ? hsv : b.toHSV(); + + return new HSVColor( + lerp(hsvA.hue, hsvB.hue, k), + lerp(hsvA.saturation, hsvB.saturation, k), + lerp(hsvA.brightness, hsvB.brightness, k)); + } + + static float lerp(float a, float b, float k) { + return a * (1 - k) + b * k; + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/color/RGBColor.java b/src/main/java/com/gtnewhorizon/gtnhlib/color/RGBColor.java new file mode 100644 index 00000000..e9c8f119 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/color/RGBColor.java @@ -0,0 +1,97 @@ +package com.gtnewhorizon.gtnhlib.color; + +public class RGBColor implements ImmutableColor { + + public static final ImmutableColor WHITE = new RGBColor(255, 255, 255, 255); + + public int red, green, blue, alpha; + + public RGBColor() {} + + public RGBColor(int red, int green, int blue) { + this.red = red; + this.green = green; + this.blue = blue; + this.alpha = 255; + } + + public RGBColor(int red, int green, int blue, int alpha) { + this.red = red; + this.green = green; + this.blue = blue; + this.alpha = alpha; + } + + public RGBColor set(int red, int green, int blue) { + this.red = red; + this.green = green; + this.blue = blue; + this.alpha = 255; + return this; + } + + public RGBColor set(int red, int green, int blue, int alpha) { + this.red = red; + this.green = green; + this.blue = blue; + this.alpha = alpha; + return this; + } + + @Override + public int getRed() { + return red; + } + + @Override + public int getGreen() { + return green; + } + + @Override + public int getBlue() { + return blue; + } + + @Override + public int getAlpha() { + return alpha; + } + + public static RGBColor fromRGB(int value) { + return new RGBColor((value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF, 255); + } + + public static RGBColor fromARGB(int value) { + return new RGBColor((value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF, (value >> 24) & 0xFF); + } + + public static RGBColor fromRGBA(int value) { + return new RGBColor((value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF); + } + + public static RGBColor fromABGR(int value) { + return new RGBColor(value & 0xFF, (value >> 8) & 0xFF, (value >> 16) & 0xFF, (value >> 24) & 0xFF); + } + + @Override + public final boolean equals(Object o) { + if (!(o instanceof RGBColor RGBColor)) return false; + + return red == RGBColor.red && green == RGBColor.green && blue == RGBColor.blue && alpha == RGBColor.alpha; + } + + @Override + public int hashCode() { + int result = red; + result = 31 * result + green; + result = 31 * result + blue; + result = 31 * result + alpha; + return result; + } + + @Override + public String toString() { + return "Color{" + "red=" + red + ", green=" + green + ", blue=" + blue + ", alpha=" + alpha + '}'; + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/geometry/Axis.java b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/Axis.java new file mode 100644 index 00000000..15660e07 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/Axis.java @@ -0,0 +1,67 @@ +package com.gtnewhorizon.gtnhlib.geometry; + +import static net.minecraftforge.common.util.ForgeDirection.DOWN; +import static net.minecraftforge.common.util.ForgeDirection.EAST; +import static net.minecraftforge.common.util.ForgeDirection.NORTH; +import static net.minecraftforge.common.util.ForgeDirection.SOUTH; +import static net.minecraftforge.common.util.ForgeDirection.UP; +import static net.minecraftforge.common.util.ForgeDirection.WEST; + +import net.minecraftforge.common.util.ForgeDirection; + +public enum Axis { + + X, + Y, + Z, + UNKNOWN; + + public static Axis fromDirection(ForgeDirection dir) { + return switch (dir) { + case EAST, WEST -> Axis.X; + case UP, DOWN -> Axis.Y; + case NORTH, SOUTH -> Axis.Z; + case UNKNOWN -> UNKNOWN; + }; + } + + public ForgeDirection positive() { + return switch (this) { + case X -> EAST; + case Y -> UP; + case Z -> SOUTH; + case UNKNOWN -> ForgeDirection.UNKNOWN; + }; + } + + public ForgeDirection negative() { + return switch (this) { + case X -> WEST; + case Y -> DOWN; + case Z -> NORTH; + case UNKNOWN -> ForgeDirection.UNKNOWN; + }; + } + + public ForgeDirection flip(ForgeDirection dir) { + switch (this) { + case X -> { + if (dir == WEST) return EAST; + if (dir == EAST) return WEST; + } + case Y -> { + if (dir == DOWN) return UP; + if (dir == UP) return DOWN; + } + case Z -> { + if (dir == NORTH) return SOUTH; + if (dir == SOUTH) return NORTH; + } + case UNKNOWN -> { + return ForgeDirection.UNKNOWN; + } + } + + return dir; + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/geometry/DirectionTransform.java b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/DirectionTransform.java new file mode 100644 index 00000000..870f4cb4 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/DirectionTransform.java @@ -0,0 +1,53 @@ +package com.gtnewhorizon.gtnhlib.geometry; + +import java.util.function.Function; + +import net.minecraftforge.common.util.ForgeDirection; + +/// A transform that mutates ForgeDirections, represented as a pure function. +/// The transform function must map each direction onto one and only one other direction. It must never return the +/// same direction for two distinct input directions. +public interface DirectionTransform extends Function, TransformLike { + + DirectionTransform IDENTITY = dir -> dir; + + default > T transform(T value) { + return value.withA(apply(value.getA())); + } + + default > T transform(T value) { + return value.withAB(apply(value.getA()), apply(value.getB())); + } + + default > T transform(T value) { + return value.withABC(apply(value.getA()), apply(value.getB()), apply(value.getC())); + } + + default DirectionTransform precalculated() { + ForgeDirection[] transform = new ForgeDirection[6]; + + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + transform[dir.ordinal()] = this.apply(dir); + } + + return dir -> transform[dir.ordinal()]; + } + + default DirectionTransform inverse() { + ForgeDirection[] transform = new ForgeDirection[6]; + + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + transform[this.apply(dir).ordinal()] = dir; + } + + return dir -> transform[dir.ordinal()]; + } + + static DirectionTransform mirror(Axis axis) { + return axis::flip; + } + + static DirectionTransform rotate(ForgeDirection vector, int amount) { + return new Transform().rotate(vector, amount); + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/geometry/OneDegreeOfFreedom.java b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/OneDegreeOfFreedom.java new file mode 100644 index 00000000..915618ca --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/OneDegreeOfFreedom.java @@ -0,0 +1,15 @@ +package com.gtnewhorizon.gtnhlib.geometry; + +import net.minecraftforge.common.util.ForgeDirection; + +import org.jetbrains.annotations.Contract; + +public interface OneDegreeOfFreedom { + + ForgeDirection getA(); + + /// Sets the direction to the given value. May or may not mutate this, the returned value should always + /// replace the 'current' value. + @Contract(mutates = "this") + TSelf withA(ForgeDirection direction); +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/geometry/Orientation.java b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/Orientation.java new file mode 100644 index 00000000..668c8291 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/Orientation.java @@ -0,0 +1,99 @@ +package com.gtnewhorizon.gtnhlib.geometry; + +import static net.minecraftforge.common.util.ForgeDirection.DOWN; +import static net.minecraftforge.common.util.ForgeDirection.EAST; +import static net.minecraftforge.common.util.ForgeDirection.NORTH; +import static net.minecraftforge.common.util.ForgeDirection.SOUTH; +import static net.minecraftforge.common.util.ForgeDirection.UP; +import static net.minecraftforge.common.util.ForgeDirection.WEST; + +import java.util.EnumMap; + +import net.minecraftforge.common.util.ForgeDirection; + +import org.jetbrains.annotations.Contract; + +public enum Orientation implements TwoDegreesOfFreedom { + + UNKNOWN(ForgeDirection.UNKNOWN, ForgeDirection.UNKNOWN), + DOWN_DOWN(DOWN, DOWN), + UP_DOWN(UP, DOWN), + NORTH_DOWN(NORTH, DOWN), + SOUTH_DOWN(SOUTH, DOWN), + WEST_DOWN(WEST, DOWN), + EAST_DOWN(EAST, DOWN), + DOWN_UP(DOWN, UP), + UP_UP(UP, UP), + NORTH_UP(NORTH, UP), + SOUTH_UP(SOUTH, UP), + WEST_UP(WEST, UP), + EAST_UP(EAST, UP), + DOWN_NORTH(DOWN, NORTH), + UP_NORTH(UP, NORTH), + NORTH_NORTH(NORTH, NORTH), + SOUTH_NORTH(SOUTH, NORTH), + WEST_NORTH(WEST, NORTH), + EAST_NORTH(EAST, NORTH), + DOWN_SOUTH(DOWN, SOUTH), + UP_SOUTH(UP, SOUTH), + NORTH_SOUTH(NORTH, SOUTH), + SOUTH_SOUTH(SOUTH, SOUTH), + WEST_SOUTH(WEST, SOUTH), + EAST_SOUTH(EAST, SOUTH), + DOWN_WEST(DOWN, WEST), + UP_WEST(UP, WEST), + NORTH_WEST(NORTH, WEST), + SOUTH_WEST(SOUTH, WEST), + WEST_WEST(WEST, WEST), + EAST_WEST(EAST, WEST), + DOWN_EAST(DOWN, EAST), + UP_EAST(UP, EAST), + NORTH_EAST(NORTH, EAST), + SOUTH_EAST(SOUTH, EAST), + WEST_EAST(WEST, EAST), + EAST_EAST(EAST, EAST); + + public final ForgeDirection a, b; + + Orientation(ForgeDirection a, ForgeDirection b) { + this.a = a; + this.b = b; + } + + private static final EnumMap> ORIENTATIONS = new EnumMap<>( + ForgeDirection.class); + + static { + for (Orientation o : values()) { + ORIENTATIONS.computeIfAbsent(o.a, x -> new EnumMap<>(ForgeDirection.class)).put(o.b, o); + } + } + + public static Orientation getOrientation(ForgeDirection a, ForgeDirection b) { + if (a == null || a == ForgeDirection.UNKNOWN) { + return Orientation.UNKNOWN; + } + + if (b == null || b == ForgeDirection.UNKNOWN) { + return Orientation.UNKNOWN; + } + + return ORIENTATIONS.get(a).get(b); + } + + @Override + public ForgeDirection getA() { + return a; + } + + @Override + public ForgeDirection getB() { + return b; + } + + @Contract(mutates = "this") + @Override + public Orientation withAB(ForgeDirection a, ForgeDirection b) { + return getOrientation(a, b); + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/geometry/ThreeDegreesOfFreedom.java b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/ThreeDegreesOfFreedom.java new file mode 100644 index 00000000..e9975233 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/ThreeDegreesOfFreedom.java @@ -0,0 +1,19 @@ +package com.gtnewhorizon.gtnhlib.geometry; + +import net.minecraftforge.common.util.ForgeDirection; + +import org.jetbrains.annotations.Contract; + +public interface ThreeDegreesOfFreedom { + + ForgeDirection getA(); + + ForgeDirection getB(); + + ForgeDirection getC(); + + /// Sets the directions to the given values. May or may not mutate this, the returned value should always + /// replace the 'current' value. + @Contract(mutates = "this") + TSelf withABC(ForgeDirection a, ForgeDirection b, ForgeDirection c); +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/geometry/Transform.java b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/Transform.java new file mode 100644 index 00000000..cb8fcc2e --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/Transform.java @@ -0,0 +1,127 @@ +package com.gtnewhorizon.gtnhlib.geometry; + +import static net.minecraftforge.common.util.ForgeDirection.DOWN; +import static net.minecraftforge.common.util.ForgeDirection.EAST; +import static net.minecraftforge.common.util.ForgeDirection.NORTH; +import static net.minecraftforge.common.util.ForgeDirection.SOUTH; +import static net.minecraftforge.common.util.ForgeDirection.UNKNOWN; +import static net.minecraftforge.common.util.ForgeDirection.UP; +import static net.minecraftforge.common.util.ForgeDirection.WEST; + +import net.minecraftforge.common.util.ForgeDirection; + +import org.joml.Matrix4f; +import org.joml.Vector3f; +import org.joml.Vector3i; + +import lombok.EqualsAndHashCode; +import lombok.ToString; + +/// An arbitrary transform. +@SuppressWarnings("unused") +@EqualsAndHashCode +@ToString +public class Transform implements DirectionTransform, VectorTransform { + + public final Matrix4f matrix = new Matrix4f(); + + public Transform rotate(ForgeDirection vector, int amount) { + matrix.rotate((float) (Math.PI / 2 * amount), v(vector)); + + return this; + } + + public Transform flip(Axis axis) { + switch (axis) { + case X -> matrix.scale(-1, 1, 1); + case Y -> matrix.scale(1, -1, 1); + case Z -> matrix.scale(1, 1, -1); + } + + return this; + } + + public Axis transform(Axis axis) { + ForgeDirection out = transform(switch (axis) { + case X -> EAST; + case Y -> UP; + case Z -> SOUTH; + case UNKNOWN -> UNKNOWN; + }); + + return switch (out) { + case EAST, WEST -> Axis.X; + case UP, DOWN -> Axis.Y; + case NORTH, SOUTH -> Axis.Z; + case UNKNOWN -> Axis.UNKNOWN; + }; + } + + @Override + public ForgeDirection apply(ForgeDirection direction) { + return transform(direction); + } + + /// Transforms a ForgeDirection + public ForgeDirection transform(ForgeDirection dir) { + return transform(dir, matrix); + } + + /// Transforms a bitmask of ForgeDirections + public int transform(int bitmask) { + if (bitmask == 0) return 0; + + int out = 0; + + for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + if ((bitmask & dir.flag) != 0) { + out |= transform(dir).flag; + } + } + + return out; + } + + /// Transforms an int vector + public Vector3i transform(Vector3i v) { + Vector3f v2 = new Vector3f(v).mulTransposeDirection(matrix); + + v.x = Math.round(v2.x); + v.y = Math.round(v2.y); + v.z = Math.round(v2.z); + + return v; + } + + @Override + public Vector3f transform(Vector3f v) { + return v.mulTransposeDirection(matrix); + } + + @Override + public Vector3f inverse(Vector3f v) { + Matrix4f inverse = new Matrix4f(matrix).invert(); + + return v.mulTransposeDirection(inverse); + } + + private static Vector3f v(ForgeDirection dir) { + return new Vector3f(dir.offsetX, dir.offsetY, dir.offsetZ); + } + + private static ForgeDirection vprime(Vector3f dir) { + return switch (dir.maxComponent()) { + case 0 -> dir.x > 0 ? EAST : WEST; + case 1 -> dir.y > 0 ? UP : DOWN; + case 2 -> dir.z > 0 ? SOUTH : NORTH; + default -> throw new AssertionError(); + }; + } + + public static ForgeDirection transform(ForgeDirection dir, Matrix4f transform) { + if (dir == null) return null; + if (dir == UNKNOWN) return UNKNOWN; + + return vprime(v(dir).mulTransposeDirection(transform)); + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/geometry/TransformLike.java b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/TransformLike.java new file mode 100644 index 00000000..b45ab2b1 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/TransformLike.java @@ -0,0 +1,7 @@ +package com.gtnewhorizon.gtnhlib.geometry; + +/// Something that acts like a transform. This is just a marker interface to validate the usage of +/// {@link BlockState#transform(TransformLike)}. +public interface TransformLike { + +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/geometry/TwoDegreesOfFreedom.java b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/TwoDegreesOfFreedom.java new file mode 100644 index 00000000..c96c80a9 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/TwoDegreesOfFreedom.java @@ -0,0 +1,17 @@ +package com.gtnewhorizon.gtnhlib.geometry; + +import net.minecraftforge.common.util.ForgeDirection; + +import org.jetbrains.annotations.Contract; + +public interface TwoDegreesOfFreedom { + + ForgeDirection getA(); + + ForgeDirection getB(); + + /// Sets the directions to the given values. May or may not mutate this, the returned value should always + /// replace the 'current' value. + @Contract(mutates = "this") + TSelf withAB(ForgeDirection a, ForgeDirection b); +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/geometry/VectorTransform.java b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/VectorTransform.java new file mode 100644 index 00000000..d9613432 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/geometry/VectorTransform.java @@ -0,0 +1,13 @@ +package com.gtnewhorizon.gtnhlib.geometry; + +import org.joml.Vector3f; + +/// A version of {@link DirectionTransform} that can transform arbitrary vectors. +public interface VectorTransform extends TransformLike { + + /// Transforms the vector. Does not copy the parameter. + Vector3f transform(Vector3f v); + + /// Performs the inverse transform on the vector. Does not copy the parameter. + Vector3f inverse(Vector3f v); +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/mixins/Mixins.java b/src/main/java/com/gtnewhorizon/gtnhlib/mixins/Mixins.java index 5712e790..38022c23 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/mixins/Mixins.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/mixins/Mixins.java @@ -22,6 +22,7 @@ public enum Mixins implements IMixins { BRIGADIER(Side.COMMON, "MixinCommandHandler", "MixinCommandHelp"), FONT_RENDERER(new MixinBuilder("Font rendering replacements").addClientMixins("MixinFontRenderer") .setPhase(Phase.EARLY).setApplyIf(() -> GTNHLibConfig.enableFontRendererMixin)), + BLOCK_PROPERTIES_ACCESSORS(Side.COMMON, "MixinTileEntitySkull"), MODEL_TEXTURE_LOADING( new MixinBuilder("Automatically load model textures") .addClientMixins( diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/mixins/early/MixinTileEntitySkull.java b/src/main/java/com/gtnewhorizon/gtnhlib/mixins/early/MixinTileEntitySkull.java new file mode 100644 index 00000000..5c8fd9e6 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/mixins/early/MixinTileEntitySkull.java @@ -0,0 +1,27 @@ +package com.gtnewhorizon.gtnhlib.mixins.early; + +import net.minecraft.tileentity.TileEntity; +import net.minecraft.tileentity.TileEntitySkull; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +import com.gtnewhorizon.gtnhlib.blockstate.mixin.BlockSkullExt; + +@Mixin(TileEntitySkull.class) +public abstract class MixinTileEntitySkull implements BlockSkullExt { + + @Shadow + private int field_145910_i; + + @Override + public int gtnhlib$getRotation() { + return field_145910_i; + } + + @Override + public void gtnhlib$setRotation(int rotation) { + this.field_145910_i = rotation; + ((TileEntity) (Object) this).markDirty(); + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/util/data/BlockMeta.java b/src/main/java/com/gtnewhorizon/gtnhlib/util/data/BlockMeta.java index 0b8a654c..d05f53f0 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/util/data/BlockMeta.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/util/data/BlockMeta.java @@ -27,6 +27,10 @@ public class BlockMeta implements ImmutableBlockMeta { this(block, 0); } + public BlockMeta(ImmutableBlockMeta bm) { + this(bm.getBlock(), bm.getBlockMeta()); + } + @Override @Nonnull public Block getBlock() { diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/util/data/ItemMeta.java b/src/main/java/com/gtnewhorizon/gtnhlib/util/data/ItemMeta.java index 9c0fff11..a56f85e5 100644 --- a/src/main/java/com/gtnewhorizon/gtnhlib/util/data/ItemMeta.java +++ b/src/main/java/com/gtnewhorizon/gtnhlib/util/data/ItemMeta.java @@ -4,7 +4,9 @@ import java.util.Objects; import javax.annotation.Nonnull; +import net.minecraft.init.Items; import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; /** * A mutable implementation of {@link ImmutableItemMeta}. If your API should return a mutable pair, return this instead. @@ -26,6 +28,14 @@ public class ItemMeta implements ImmutableItemMeta { this(item, 0); } + public ItemMeta(ImmutableItemMeta im) { + this(im.getItem(), im.getItemMeta()); + } + + public ItemMeta(ItemStack stack) { + this(Objects.requireNonNull(stack.getItem(), "Item must not be null"), Items.feather.getDamage(stack)); + } + @Override @Nonnull public Item getItem() {