Move RebornCore into a sub project

Update gradle and build against java 16
This commit is contained in:
modmuss50 2021-05-28 14:51:01 +01:00
parent 44a0313361
commit b0c7a733c7
242 changed files with 23176 additions and 97 deletions

View file

@ -4,7 +4,7 @@ jobs:
build: build:
runs-on: ubuntu-20.04 runs-on: ubuntu-20.04
container: container:
image: openjdk:15-jdk image: openjdk:16-jdk
options: --user root options: --user root
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
@ -17,14 +17,14 @@ jobs:
token: ${{ secrets.github_token }} token: ${{ secrets.github_token }}
prefix: ${{ github.ref }} prefix: ${{ github.ref }}
- run: ./gradlew build publish --stacktrace # - run: ./gradlew build publish --stacktrace
env: # env:
MAVEN_URL: ${{ secrets.MAVEN_URL }} # MAVEN_URL: ${{ secrets.MAVEN_URL }}
MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} # MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} # MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
SIGNING_KEY: ${{ secrets.SIGNING_KEY }} # SIGNING_KEY: ${{ secrets.SIGNING_KEY }}
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }} # SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
CROWDIN_KEY: ${{ secrets.CROWDIN_KEY }} # CROWDIN_KEY: ${{ secrets.CROWDIN_KEY }}
- name: Upload artifacts - name: Upload artifacts
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2

View file

@ -4,7 +4,7 @@ jobs:
build: build:
runs-on: ubuntu-20.04 runs-on: ubuntu-20.04
container: container:
image: openjdk:15-jdk image: openjdk:16-jdk
options: --user root options: --user root
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2

View file

@ -10,7 +10,7 @@ jobs:
build: build:
runs-on: ubuntu-20.04 runs-on: ubuntu-20.04
container: container:
image: openjdk:15-jdk image: openjdk:16-jdk
options: --user root options: --user root
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2

3
.gitignore vendored
View file

@ -30,3 +30,6 @@ java_pid2412.hprof
/buildSrc/build/ /buildSrc/build/
/src/main/resources/package-lock.json /src/main/resources/package-lock.json
/src/main/resources/node_modules/ /src/main/resources/node_modules/
/RebornCore/.gradle
/RebornCore/build

1
RebornCore/build.gradle Normal file
View file

@ -0,0 +1 @@
group = 'RebornCore'

View file

@ -0,0 +1,37 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.cottonmc.libcd.api;
import net.minecraft.item.Item;
import java.util.Collection;
/**
* A recipe that has output behavior that cannot be described by just the Recipe#getOutput() method.
* Used for RecipeTweaker remove-by-output code.
*/
public interface CustomOutputRecipe {
Collection<Item> getOutputItems();
}

View file

@ -0,0 +1,40 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore;
import net.fabricmc.api.EnvType;
public enum Distribution {
UNIVERSAL,
CLIENT,
SERVER;
public boolean isInvalid() {
if (this == UNIVERSAL) {
return false;
}
return RebornCore.getSide() == EnvType.CLIENT && this == CLIENT;
}
}

View file

@ -0,0 +1,129 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerBlockEntityEvents;
import net.fabricmc.fabric.api.event.world.WorldTickCallback;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.util.Identifier;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import reborncore.api.ToolManager;
import reborncore.api.blockentity.UnloadHandler;
import reborncore.common.RebornCoreCommands;
import reborncore.common.RebornCoreConfig;
import reborncore.common.blocks.BlockWrenchEventHandler;
import reborncore.common.config.Configuration;
import reborncore.common.crafting.ingredient.IngredientManager;
import reborncore.common.fluid.RebornFluidManager;
import reborncore.common.misc.ModSounds;
import reborncore.common.misc.RebornCoreTags;
import reborncore.common.multiblock.MultiblockRegistry;
import reborncore.common.network.ServerBoundPackets;
import reborncore.common.powerSystem.PowerSystem;
import reborncore.common.util.CalenderUtils;
import reborncore.common.util.GenericWrenchHelper;
import java.io.File;
import java.util.function.Supplier;
public class RebornCore implements ModInitializer {
public static final String MOD_NAME = "Reborn Core";
public static final String MOD_ID = "reborncore";
public static final String MOD_VERSION = "@MODVERSION@";
public static final String WEB_URL = "https://files.modmuss50.me/";
public static final Logger LOGGER = LogManager.getFormatterLogger(MOD_ID);
public static File configDir;
public static boolean LOADED = false;
public RebornCore() {
}
@Override
public void onInitialize() {
new Configuration(RebornCoreConfig.class, MOD_ID);
PowerSystem.init();
CalenderUtils.loadCalender(); //Done early as some features need this
ToolManager.INSTANCE.customToolHandlerList.add(new GenericWrenchHelper(new Identifier("ic2:wrench"), true));
ToolManager.INSTANCE.customToolHandlerList.add(new GenericWrenchHelper(new Identifier("forestry:wrench"), false));
ToolManager.INSTANCE.customToolHandlerList.add(new GenericWrenchHelper(new Identifier("actuallyadditions:item_laser_wrench"), false));
ToolManager.INSTANCE.customToolHandlerList.add(new GenericWrenchHelper(new Identifier("thermalfoundation:wrench"), false));
ToolManager.INSTANCE.customToolHandlerList.add(new GenericWrenchHelper(new Identifier("charset:wrench"), false));
ToolManager.INSTANCE.customToolHandlerList.add(new GenericWrenchHelper(new Identifier("teslacorelib:wrench"), false));
ToolManager.INSTANCE.customToolHandlerList.add(new GenericWrenchHelper(new Identifier("rftools:smartwrench"), false));
ToolManager.INSTANCE.customToolHandlerList.add(new GenericWrenchHelper(new Identifier("intergrateddynamics:smartwrench"), false));
ToolManager.INSTANCE.customToolHandlerList.add(new GenericWrenchHelper(new Identifier("correlated:weldthrower"), false));
ToolManager.INSTANCE.customToolHandlerList.add(new GenericWrenchHelper(new Identifier("chiselsandbits:wrench_wood"), false));
ToolManager.INSTANCE.customToolHandlerList.add(new GenericWrenchHelper(new Identifier("redstonearsenal:tool.wrench_flux"), false));
ModSounds.setup();
BlockWrenchEventHandler.setup();
/*
This is a generic multiblock tick handler. If you are using this code on your
own, you will need to register this with the Forge TickRegistry on both the
client AND server sides. Note that different types of ticks run on different
parts of the system. CLIENT ticks only run on the client, at the start/end of
each game loop. SERVER and WORLD ticks only run on the server. WORLDLOAD
ticks run only on the server, and only when worlds are loaded.
*/
WorldTickCallback.EVENT.register(MultiblockRegistry::tickStart);
// packets
ServerBoundPackets.init();
IngredientManager.setup();
RebornFluidManager.setupBucketMap();
RebornCoreCommands.setup();
RebornCoreTags.WATER_EXPLOSION_ITEM.toString();
/* register UnloadHandler */
ServerBlockEntityEvents.BLOCK_ENTITY_UNLOAD.register((blockEntity, world) -> {
if (blockEntity instanceof UnloadHandler) ((UnloadHandler) blockEntity).onUnload();
});
LOGGER.info("Reborn core is done for now, now to let other mods have their turn...");
LOADED = true;
}
public static EnvType getSide() {
return FabricLoader.getInstance().getEnvironmentType();
}
public static void clientOnly(Supplier<Runnable> runnable){
if(FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT){
runnable.get().run();
}
}
}

View file

@ -0,0 +1,57 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientBlockEntityEvents;
import net.fabricmc.fabric.api.client.item.v1.ItemTooltipCallback;
import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback;
import net.fabricmc.fabric.api.event.client.ClientSpriteRegistryCallback;
import net.minecraft.client.texture.SpriteAtlasTexture;
import reborncore.api.blockentity.UnloadHandler;
import reborncore.client.HolidayRenderManager;
import reborncore.client.IconSupplier;
import reborncore.client.ItemStackRenderer;
import reborncore.client.StackToolTipHandler;
import reborncore.common.fluid.RebornFluidRenderManager;
import reborncore.common.network.ClientBoundPacketHandlers;
public class RebornCoreClient implements ClientModInitializer {
@Override
public void onInitializeClient() {
RebornFluidRenderManager.setupClient();
HolidayRenderManager.setupClient();
ClientSpriteRegistryCallback.event(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE).register(IconSupplier::registerSprites);
ClientBoundPacketHandlers.init();
HudRenderCallback.EVENT.register(new ItemStackRenderer());
ItemTooltipCallback.EVENT.register(new StackToolTipHandler());
/* register UnloadHandler */
ClientBlockEntityEvents.BLOCK_ENTITY_UNLOAD.register((blockEntity, world) -> {
if (blockEntity instanceof UnloadHandler) ((UnloadHandler) blockEntity).onUnload();
});
}
}

View file

@ -0,0 +1,135 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore;
import net.minecraft.block.Block;
import net.minecraft.item.BlockItem;
import net.minecraft.item.Item;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import org.apache.commons.lang3.Validate;
import java.util.HashMap;
import java.util.function.Function;
/**
* Created by Gigabit101 on 16/08/2016.
*/
public class RebornRegistry {
//public static LootManager.InnerPool lp = new LootManager.InnerPool();
//Yeah, this is horrible
private static final HashMap<Object, Identifier> objIdentMap = new HashMap<>();
/**
* Registers Block and BlockItem in vanilla registries
*
* @param block Block Block to register
* @param builder Item.Settings Settings builder for BlockItem
* @param name Identifier Registry name for block and item
*/
public static void registerBlock(Block block, Item.Settings builder, Identifier name) {
Registry.register(Registry.BLOCK, name, block);
BlockItem itemBlock = new BlockItem(block, builder);
Registry.register(Registry.ITEM, name, itemBlock);
}
public static void registerBlock(Block block, Function<Block, BlockItem> blockItemFunction, Identifier name) {
Registry.register(Registry.BLOCK, name, block);
BlockItem itemBlock = blockItemFunction.apply(block);
Registry.register(Registry.ITEM, name, itemBlock);
}
/**
* Registers Block and BlockItem in vanilla registries.
* Block should have registered identifier in RebornRegistry via {@link #registerIdent registerIdent} method
*
* @param block Block Block to register
* @param itemGroup Item.Settings Settings builder for BlockItem
*/
public static void registerBlock(Block block, Item.Settings itemGroup) {
Validate.isTrue(objIdentMap.containsKey(block));
registerBlock(block, itemGroup, objIdentMap.get(block));
}
public static void registerBlock(Block block, Function<Block, BlockItem> blockItemFunction){
Validate.isTrue(objIdentMap.containsKey(block));
registerBlock(block, blockItemFunction, objIdentMap.get(block));
}
/**
* Register only Block, without BlockItem in vanilla registries
* Block should have registered identifier in RebornRegistry via {@link #registerIdent registerIdent} method
* @param block Block Block to register
*/
public static void registerBlockNoItem(Block block) {
Validate.isTrue(objIdentMap.containsKey(block));
Registry.register(Registry.BLOCK, objIdentMap.get(block), block);
}
/**
* Register Item in vanilla registries
*
* @param item Item Item to register
* @param name Identifier Registry name for item
*/
public static void registerItem(Item item, Identifier name) {
Registry.register(Registry.ITEM, name, item);
}
/**
* Register Item in vanilla registries
* Item should have registered identifier in RebornRegistry via {@link #registerIdent registerIdent} method
*
* @param item Item Item to register
*/
public static void registerItem(Item item){
Validate.isTrue(objIdentMap.containsKey(item));
registerItem(item, objIdentMap.get(item));
}
/**
* Registers Identifier in internal RebornCore map
*
* @param object Object Item, Block or whatever to be put into map
* @param identifier Identifier Registry name for object
*/
public static void registerIdent(Object object, Identifier identifier){
objIdentMap.put(object, identifier);
}
//eg: RebornRegistry.addLoot(Items.NETHER_STAR, 0.95, LootTableList.CHESTS_VILLAGE_BLACKSMITH);
//eg: RebornRegistry.addLoot(Items.DIAMOND, 1.95, LootTableList.ENTITIES_COW);
public static void addLoot(Item item, double chance, Identifier list) {
// lp.addItem(LootManager.createLootEntry(item, chance, list));
}
public static void addLoot(Item item, int minSize, int maxSize, double chance, Identifier list) {
// lp.addItem(LootManager.createLootEntry(item, minSize, maxSize, chance, list));
}
}

View file

@ -0,0 +1,33 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api;
import net.minecraft.item.ItemStack;
public interface ICustomToolHandler extends IToolHandler {
boolean canHandleTool(ItemStack stack);
}

View file

@ -0,0 +1,35 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api;
import net.minecraft.text.Text;
import java.util.List;
public interface IListInfoProvider {
void addInfo(List<Text> info, boolean isReal, boolean hasData);
}

View file

@ -0,0 +1,33 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
public interface IToolDrop {
ItemStack getToolDrop(PlayerEntity p0);
}

View file

@ -0,0 +1,51 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.World;
/**
* Added onto an item
*/
public interface IToolHandler {
/**
* Called when a machine is actived with the item that has IToolHandler on it
*
* @param stack the held itemstack
* @param pos the pos of the block
* @param world the world of the block
* @param player the player that actived the block
* @param side the side that the player actived
* @param damage if the tool should be damged, or power taken
* @return If the tool can handle being actived on the block, return false when the tool is broken or out of power for example.
*/
boolean handleTool(ItemStack stack, BlockPos pos, World world, PlayerEntity player, Direction side, boolean damage);
}

View file

@ -0,0 +1,72 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.World;
import java.util.ArrayList;
import java.util.List;
public class ToolManager implements ICustomToolHandler {
public static final ToolManager INSTANCE = new ToolManager();
public List<ICustomToolHandler> customToolHandlerList = new ArrayList<>();
@Override
public boolean handleTool(ItemStack stack, BlockPos pos, World world, PlayerEntity player, Direction side, boolean damage) {
if (stack == null || stack.isEmpty()) {
return false;
}
if (stack.getItem() instanceof IToolHandler) {
return ((IToolHandler) stack.getItem()).handleTool(stack, pos, world, player, side, damage);
}
for (ICustomToolHandler customToolHandler : customToolHandlerList) {
if (customToolHandler.canHandleTool(stack)) {
return customToolHandler.handleTool(stack, pos, world, player, side, damage);
}
}
return false;
}
@Override
public boolean canHandleTool(ItemStack stack) {
if (stack == null || stack.isEmpty()) {
return false;
}
if (stack.getItem() instanceof IToolHandler) {
return true;
}
for (ICustomToolHandler customToolHandler : customToolHandlerList) {
if (customToolHandler.canHandleTool(stack)) {
return true;
}
}
return false;
}
}

View file

@ -0,0 +1,35 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api.blockentity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public interface IMachineGuiHandler {
void open(PlayerEntity player, BlockPos pos, World world);
}

View file

@ -0,0 +1,48 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api.blockentity;
import net.minecraft.item.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import reborncore.common.recipes.IUpgradeHandler;
/**
* Added to an item to say that it is a valid behavior
*/
public interface IUpgrade {
void process(
@NotNull MachineBaseBlockEntity machineBase,
@Nullable
IUpgradeHandler handler,
@NotNull
ItemStack stack);
default boolean isValidForInventory(IUpgradeable upgradeable, ItemStack stack) {
return true;
}
}

View file

@ -0,0 +1,44 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api.blockentity;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
public interface IUpgradeable {
default boolean canBeUpgraded() {
return true;
}
Inventory getUpgradeInvetory();
int getUpgradeSlotCount();
default boolean isUpgradeValid(IUpgrade upgrade, ItemStack stack) {
return true;
}
}

View file

@ -0,0 +1,33 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api.blockentity;
import net.minecraft.inventory.Inventory;
public interface InventoryProvider {
Inventory getInventory();
}

View file

@ -0,0 +1,31 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api.blockentity;
public interface UnloadHandler {
void onUnload();
}

View file

@ -0,0 +1,53 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api.events;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.player.PlayerEntity;
public interface ApplyArmorToDamageCallback {
Event<ApplyArmorToDamageCallback> EVENT = EventFactory.createArrayBacked(ApplyArmorToDamageCallback.class,
(listeners) -> (player, damageSource, amount) -> {
float damageAmount = amount;
for (ApplyArmorToDamageCallback listener : listeners){
damageAmount = listener.applyArmorToDamage(player, damageSource, damageAmount);
}
return damageAmount;
});
/**
* Apply armor to amount of damage inflicted. Decreases it in most cases unless armor should increase damage inflicted.
* Event is called after damage is being reduced by armor already and before damage reduction from enchants.
*
* @param player PlayerEntity Player being damaged
* @param source DamageSource Type of damage
* @param amount float Current amount of damage
* @return float Amount of damage after reduction
*/
float applyArmorToDamage(PlayerEntity player, DamageSource source, float amount);
}

View file

@ -0,0 +1,44 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api.events;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.CraftingInventory;
import net.minecraft.item.ItemStack;
public interface ItemCraftCallback {
Event<ItemCraftCallback> EVENT = EventFactory.createArrayBacked(ItemCraftCallback.class, (listeners) -> (stack, craftingInventory, playerEntity) -> {
for (ItemCraftCallback callback : listeners) {
callback.onCraft(stack, craftingInventory, playerEntity);
}
});
void onCraft(ItemStack stack, CraftingInventory craftingInventory, PlayerEntity playerEntity);
}

View file

@ -0,0 +1,33 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api.items;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
public interface ArmorFovHandler {
float changeFov(float old, ItemStack stack, PlayerEntity playerEntity);
}

View file

@ -0,0 +1,33 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api.items;
import net.minecraft.entity.player.PlayerEntity;
public interface ArmorRemoveHandler {
void onRemoved(PlayerEntity playerEntity);
}

View file

@ -0,0 +1,33 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api.items;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
public interface ArmorTickable {
void tickArmor(ItemStack stack, PlayerEntity playerEntity);
}

View file

@ -0,0 +1,113 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api.items;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.Inventories;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.util.collection.DefaultedList;
public abstract class InventoryBase implements Inventory {
private final int size;
private DefaultedList<ItemStack> stacks;
public InventoryBase(int size) {
this.size = size;
stacks = DefaultedList.ofSize(size, ItemStack.EMPTY);
}
public Tag serializeNBT() {
CompoundTag tag = new CompoundTag();
Inventories.toTag(tag, stacks);
return tag;
}
public void deserializeNBT(CompoundTag tag) {
stacks = DefaultedList.ofSize(size, ItemStack.EMPTY);
Inventories.fromTag(tag, stacks);
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return stacks.stream().allMatch(ItemStack::isEmpty);
}
@Override
public ItemStack getStack(int i) {
return stacks.get(i);
}
@Override
public ItemStack removeStack(int i, int i1) {
ItemStack stack = Inventories.splitStack(stacks, i, i1);
if (!stack.isEmpty()) {
this.markDirty();
}
return stack;
}
@Override
public ItemStack removeStack(int i) {
return Inventories.removeStack(stacks, i);
}
@Override
public void setStack(int i, ItemStack itemStack) {
stacks.set(i, itemStack);
if (itemStack.getCount() > this.getMaxCountPerStack()) {
itemStack.setCount(this.getMaxCountPerStack());
}
this.markDirty();
}
@Override
public void markDirty() {
//Stuff happens in the super methods
}
@Override
public boolean canPlayerUse(PlayerEntity playerEntity) {
return true;
}
@Override
public void clear() {
stacks.clear();
}
public DefaultedList<ItemStack> getStacks() {
return stacks;
}
}

View file

@ -0,0 +1,129 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api.items;
import net.minecraft.block.*;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.entity.ChestBlockEntity;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.SidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.World;
import reborncore.common.util.ItemUtils;
import org.jetbrains.annotations.Nullable;
public class InventoryUtils {
public static ItemStack insertItemStacked(Inventory inventory, ItemStack input, boolean simulate) {
ItemStack stack = input.copy();
for (int i = 0; i < inventory.size(); i++) {
ItemStack targetStack = inventory.getStack(i);
//Nice and simple, insert the item into a blank slot
if (targetStack.isEmpty()) {
if (!simulate) {
inventory.setStack(i, stack);
}
return ItemStack.EMPTY;
} else if (ItemUtils.isItemEqual(stack, targetStack, true, false)) {
int freeStackSpace = targetStack.getMaxCount() - targetStack.getCount();
if (freeStackSpace > 0) {
int transferAmount = Math.min(freeStackSpace, input.getCount());
if (!simulate) {
targetStack.increment(transferAmount);
}
stack.decrement(transferAmount);
}
}
}
return stack;
}
public static ItemStack insertItem(ItemStack input, Inventory inventory, Direction direction) {
ItemStack stack = input.copy();
if (inventory instanceof SidedInventory) {
SidedInventory sidedInventory = (SidedInventory) inventory;
for (int slot : sidedInventory.getAvailableSlots(direction)) {
if (sidedInventory.canInsert(slot, stack, direction)) {
stack = insertIntoInv(sidedInventory, slot, stack);
if (stack.isEmpty()) {
break;
}
}
}
return stack;
} else {
for (int i = 0; i < inventory.size() & !stack.isEmpty(); i++) {
if (inventory.isValid(i, stack)) {
stack = insertIntoInv(inventory, i, stack);
}
}
}
return stack;
}
@Nullable
public static Inventory getInventoryAt(World world, BlockPos blockPos) {
Inventory inventory = null;
BlockState blockState = world.getBlockState(blockPos);
Block block = blockState.getBlock();
if (block instanceof InventoryProvider) {
inventory = ((InventoryProvider) block).getInventory(blockState, world, blockPos);
} else if (block instanceof BlockEntityProvider) {
BlockEntity blockEntity = world.getBlockEntity(blockPos);
if (blockEntity instanceof Inventory) {
inventory = (Inventory) blockEntity;
if (inventory instanceof ChestBlockEntity && block instanceof ChestBlock) {
inventory = ChestBlock.getInventory((ChestBlock) block, blockState, world, blockPos, true);
}
}
}
return inventory;
}
private static ItemStack insertIntoInv(Inventory inventory, int slot, ItemStack input) {
ItemStack targetStack = inventory.getStack(slot);
ItemStack stack = input.copy();
//Nice and simple, insert the item into a blank slot
if (targetStack.isEmpty()) {
inventory.setStack(slot, stack);
return ItemStack.EMPTY;
} else if (ItemUtils.isItemEqual(stack, targetStack, true, false)) {
int freeStackSpace = targetStack.getMaxCount() - targetStack.getCount();
if (freeStackSpace > 0) {
int transferAmount = Math.min(freeStackSpace, stack.getCount());
targetStack.increment(transferAmount);
stack.decrement(transferAmount);
}
}
return stack;
}
}

View file

@ -0,0 +1,37 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api.items;
import com.google.common.collect.Multimap;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.attribute.EntityAttribute;
import net.minecraft.entity.attribute.EntityAttributeModifier;
import net.minecraft.item.ItemStack;
public interface ItemStackModifiers {
void getAttributeModifiers(EquipmentSlot slot, ItemStack stack, Multimap<EntityAttribute, EntityAttributeModifier> builder);
}

View file

@ -0,0 +1,58 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.api.recipe;
import net.minecraft.item.ItemStack;
import reborncore.common.blockentity.SlotConfiguration;
import reborncore.common.crafting.RebornRecipe;
import reborncore.common.recipes.RecipeCrafter;
/**
* Created by modmuss50 on 11/04/2016.
*/
public interface IRecipeCrafterProvider extends SlotConfiguration.SlotFilter {
RecipeCrafter getRecipeCrafter();
default boolean canCraft(RebornRecipe rebornRecipe) {
return true;
}
@Override
default boolean isStackValid(int slotID, ItemStack stack) {
if (getRecipeCrafter() == null) {
return false;
}
return getRecipeCrafter().isStackValidInput(stack);
}
@Override
default int[] getInputSlots() {
if (getRecipeCrafter() == null) {
return new int[]{};
}
return getRecipeCrafter().inputSlots;
}
}

View file

@ -0,0 +1,106 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client;
import com.mojang.blaze3d.systems.RenderSystem;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.render.BufferBuilder;
import net.minecraft.client.render.Tessellator;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.VertexFormats;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.util.math.BlockPos;
import reborncore.common.chunkloading.ChunkLoaderManager;
import reborncore.common.network.NetworkManager;
import reborncore.common.network.ServerBoundPackets;
import java.util.ArrayList;
import java.util.List;
@Environment(EnvType.CLIENT)
public class ClientChunkManager {
private static final List<ChunkLoaderManager.LoadedChunk> loadedChunks = new ArrayList<>();
public static void setLoadedChunks(List<ChunkLoaderManager.LoadedChunk> chunks) {
loadedChunks.clear();
loadedChunks.addAll(chunks);
}
public static void toggleLoadedChunks(BlockPos chunkLoader) {
if (loadedChunks.size() == 0) {
NetworkManager.sendToServer(ServerBoundPackets.requestChunkloaderChunks(chunkLoader));
} else {
loadedChunks.clear();
}
}
public static boolean hasChunksForLoader(BlockPos pos) {
return loadedChunks.stream()
.filter(loadedChunk -> loadedChunk.getChunkLoader().equals(pos))
.anyMatch(loadedChunk -> loadedChunk.getWorld().equals(ChunkLoaderManager.getWorldName(MinecraftClient.getInstance().world)));
}
public static void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, double x, double y, double z) {
if (loadedChunks.size() == 0) {
return;
}
final MinecraftClient minecraftClient = MinecraftClient.getInstance();
RenderSystem.enableDepthTest();
RenderSystem.shadeModel(7425);
RenderSystem.enableAlphaTest();
RenderSystem.defaultAlphaFunc();
final Tessellator tessellator = Tessellator.getInstance();
final BufferBuilder bufferBuilder = tessellator.getBuffer();
RenderSystem.disableTexture();
RenderSystem.disableBlend();
RenderSystem.lineWidth(5.0F);
bufferBuilder.begin(3, VertexFormats.POSITION_COLOR);
loadedChunks.stream()
.filter(loadedChunk -> loadedChunk.getWorld().equals(ChunkLoaderManager.getWorldName(minecraftClient.world)))
.forEach(loadedChunk -> {
double chunkX = (double) loadedChunk.getChunk().getStartX() - x;
double chunkY = (double) loadedChunk.getChunk().getStartZ() - z;
bufferBuilder.vertex(chunkX + 8, 0.0D - y, chunkY + 8).color(1.0F, 0.0F, 0.0F, 0.0F).next();
bufferBuilder.vertex(chunkX + 8, 0.0D - y, chunkY + 8).color(1.0F, 0.0F, 0.0F, 0.5F).next();
bufferBuilder.vertex(chunkX + 8, 256.0D - y, chunkY + 8).color(1.0F, 0.0F, 0.0F, 0.5F).next();
bufferBuilder.vertex(chunkX + 8, 256.0D - y, chunkY + 8).color(1.0F, 0.0F, 0.0F, 0.0F).next();
});
tessellator.draw();
RenderSystem.lineWidth(1.0F);
RenderSystem.enableBlend();
RenderSystem.enableTexture();
}
}

View file

@ -0,0 +1,84 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client;
import net.fabricmc.fabric.api.client.rendereregistry.v1.LivingEntityFeatureRendererRegistrationCallback;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.entity.LivingEntityRenderer;
import net.minecraft.client.render.entity.feature.FeatureRenderer;
import net.minecraft.client.render.entity.feature.FeatureRendererContext;
import net.minecraft.client.render.entity.model.EntityModel;
import net.minecraft.client.render.entity.model.PlayerEntityModel;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.client.util.math.Vector3f;
import net.minecraft.entity.LivingEntity;
import net.minecraft.util.Identifier;
import reborncore.common.RebornCoreConfig;
import reborncore.common.util.CalenderUtils;
/**
* Created by Mark on 27/11/2016.
*/
public class HolidayRenderManager {
public static void setupClient() {
if (CalenderUtils.christmas && RebornCoreConfig.easterEggs) {
LivingEntityFeatureRendererRegistrationCallback.EVENT.register((entityType, entityRenderer, registrationHelper) -> {
if (entityRenderer.getModel() instanceof PlayerEntityModel) {
registrationHelper.register(new LayerRender(entityRenderer));
}
});
}
}
private static final ModelSantaHat santaHat = new ModelSantaHat();
private static final Identifier TEXTURE = new Identifier("reborncore", "textures/models/santa_hat.png");
public static class LayerRender <T extends LivingEntity, M extends EntityModel<T>> extends FeatureRenderer<T, M> {
public LayerRender(FeatureRendererContext<T, M> context) {
super(context);
}
@Override
public void render(MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int i, T player, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) {
MinecraftClient.getInstance().getTextureManager().bindTexture(TEXTURE);
VertexConsumer vertexConsumer = vertexConsumerProvider.getBuffer(RenderLayer.getEntitySolid(TEXTURE));
matrixStack.push();
float yaw = player.prevYaw + (player.yaw - player.prevYaw) * tickDelta - (player.prevBodyYaw + (player.bodyYaw - player.prevBodyYaw) * tickDelta);
float pitch = player.prevPitch + (player.pitch - player.prevPitch) * tickDelta;
matrixStack.multiply(Vector3f.POSITIVE_Y.getDegreesQuaternion(yaw));
matrixStack.multiply(Vector3f.POSITIVE_X.getDegreesQuaternion(pitch));
santaHat.render(matrixStack, vertexConsumer, i, LivingEntityRenderer.getOverlay(player, 0.0F), 1F, 1F, 1F, 1F);
matrixStack.pop();
}
}
}

View file

@ -0,0 +1,48 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.event.client.ClientSpriteRegistryCallback;
import net.minecraft.client.texture.SpriteAtlasTexture;
import net.minecraft.util.Identifier;
import reborncore.RebornCore;
public class IconSupplier {
public static Identifier armour_head_id = new Identifier(RebornCore.MOD_ID, "gui/slot_sprites/armour_head");
public static Identifier armour_chest_id = new Identifier(RebornCore.MOD_ID, "gui/slot_sprites/armour_chest");
public static Identifier armour_legs_id = new Identifier(RebornCore.MOD_ID, "gui/slot_sprites/armour_legs");
public static Identifier armour_feet_id = new Identifier(RebornCore.MOD_ID, "gui/slot_sprites/armour_feet");
@Environment(EnvType.CLIENT)
public static void registerSprites(SpriteAtlasTexture atlasTexture, ClientSpriteRegistryCallback.Registry registry) {
registry.register(IconSupplier.armour_head_id);
registry.register(IconSupplier.armour_chest_id);
registry.register(IconSupplier.armour_legs_id);
registry.register(IconSupplier.armour_feet_id);
}
}

View file

@ -0,0 +1,34 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client;
import net.minecraft.item.ItemStack;
import java.util.LinkedList;
import java.util.Queue;
public class ItemStackRenderManager {
public static final Queue<ItemStack> RENDER_QUEUE = new LinkedList<>();
}

View file

@ -0,0 +1,159 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gl.Framebuffer;
import net.minecraft.client.render.DiffuseLighting;
import net.minecraft.client.render.OverlayTexture;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.item.ItemRenderer;
import net.minecraft.client.render.model.BakedModel;
import net.minecraft.client.render.model.json.ModelTransformation;
import net.minecraft.client.texture.NativeImage;
import net.minecraft.client.texture.SpriteAtlasTexture;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import org.apache.commons.io.FileUtils;
import org.lwjgl.opengl.GL11;
import java.io.File;
/**
* Initially take from https://github.com/JamiesWhiteShirt/developer-mode/tree/experimental-item-render and then ported to 1.15
* Thanks 2xsaiko for fixing the lighting + odd issues above
*/
public class ItemStackRenderer implements HudRenderCallback {
@Override
public void onHudRender(MatrixStack matrixStack, float v) {
if (!ItemStackRenderManager.RENDER_QUEUE.isEmpty()) {
MinecraftClient.getInstance().textRenderer.draw(matrixStack, "Rendering " + ItemStackRenderManager.RENDER_QUEUE.size() + " items left", 5, 5, -1);
ItemStack itemStack = ItemStackRenderManager.RENDER_QUEUE.poll();
export(itemStack, 512, Registry.ITEM.getId(itemStack.getItem()));
}
}
private void export(ItemStack stack, int size, Identifier identifier) {
File dir = new File(FabricLoader.getInstance().getGameDirectory(), "item_renderer/" + identifier.getNamespace());
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(dir, identifier.getPath() + ".png");
if (file.exists()) {
file.delete();
}
MinecraftClient minecraft = MinecraftClient.getInstance();
if (minecraft.getItemRenderer() == null || minecraft.world == null) {
return;
}
final Framebuffer framebuffer = new Framebuffer(size, size, true, MinecraftClient.IS_SYSTEM_MAC);
framebuffer.setClearColor(0.0F, 0.0F, 0.0F, 0.0F);
framebuffer.clear(MinecraftClient.IS_SYSTEM_MAC);
framebuffer.beginWrite(true);
final ItemRenderer itemRenderer = MinecraftClient.getInstance().getItemRenderer();
final BakedModel model = itemRenderer.getHeldItemModel(stack, minecraft.world, minecraft.player);
RenderSystem.matrixMode(GL11.GL_PROJECTION);
RenderSystem.pushMatrix();
RenderSystem.loadIdentity();
RenderSystem.ortho(-1, 1, 1, -1, -100.0, 100.0);
RenderSystem.matrixMode(GL11.GL_MODELVIEW);
RenderSystem.pushMatrix();
RenderSystem.loadIdentity();
{
minecraft.getTextureManager().bindTexture(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE);
minecraft.getTextureManager().getTexture(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE).setFilter(false, false);
RenderSystem.enableRescaleNormal();
RenderSystem.enableAlphaTest();
RenderSystem.defaultAlphaFunc();
RenderSystem.enableBlend();
RenderSystem.enableDepthTest();
RenderSystem.blendFunc(GlStateManager.SrcFactor.SRC_ALPHA, GlStateManager.DstFactor.ONE_MINUS_SRC_ALPHA);
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
MatrixStack matrixStack = new MatrixStack();
matrixStack.scale(2F, -2F, 1F);
boolean frontLit = !model.isSideLit();
if (frontLit) {
DiffuseLighting.disableGuiDepthLighting();
}
VertexConsumerProvider.Immediate immediate = MinecraftClient.getInstance().getBufferBuilders().getEntityVertexConsumers();
itemRenderer.renderItem(stack, ModelTransformation.Mode.GUI, false, matrixStack, immediate, 15728880, OverlayTexture.DEFAULT_UV, model);
immediate.draw();
RenderSystem.enableDepthTest();
if (frontLit) {
DiffuseLighting.enableGuiDepthLighting();
}
RenderSystem.disableAlphaTest();
RenderSystem.disableRescaleNormal();
}
RenderSystem.popMatrix();
RenderSystem.matrixMode(GL11.GL_PROJECTION);
RenderSystem.popMatrix();
RenderSystem.matrixMode(GL11.GL_MODELVIEW);
framebuffer.endWrite();
try (NativeImage nativeImage = new NativeImage(size, size, false)) {
GlStateManager.bindTexture(framebuffer.getColorAttachment());
nativeImage.loadFromTextureImage(0, false);
nativeImage.mirrorVertically();
try {
byte[] bytes = nativeImage.getBytes();
FileUtils.writeByteArrayToFile(file, bytes);
System.out.println("Wrote " + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
framebuffer.delete();
}
}

View file

@ -0,0 +1,211 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Date: 27/11/2016 17:33:21
// Template version 1.1
// Java generated by Techne
// Keep in mind that you still need to fill in some blanks
// - ZeuX
package reborncore.client;
import net.minecraft.client.model.ModelPart;
import net.minecraft.client.network.AbstractClientPlayerEntity;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.render.entity.model.EntityModel;
import net.minecraft.client.util.math.MatrixStack;
public class ModelSantaHat extends EntityModel<AbstractClientPlayerEntity> {
private final ModelPart hatband1;
private final ModelPart hatband2;
private final ModelPart hatband3;
private final ModelPart hatband4;
private final ModelPart hatbase1;
private final ModelPart hatband5;
private final ModelPart hatband6;
private final ModelPart hatbase2;
private final ModelPart hatextension1;
private final ModelPart hatextension2;
private final ModelPart hatextension3;
private final ModelPart hatextension4;
private final ModelPart hatball1;
private final ModelPart hatball2;
private final ModelPart hatball3;
private final ModelPart hatball4;
private final ModelPart hatball5;
private final ModelPart hatball6;
public ModelSantaHat() {
textureWidth = 64;
textureHeight = 64;
hatband1 = new ModelPart(this, 0, 32);
hatband1.addCuboid(-4F, -8F, -5F, 8, 1, 1);
hatband1.setPivot(0F, 0F, 0F);
hatband1.setTextureSize(64, 64);
hatband1.mirror = true;
setRotation(hatband1, 0F, 0F, 0F);
hatband2 = new ModelPart(this, 0, 32);
hatband2.addCuboid(-4F, -8F, 4F, 8, 1, 1);
hatband2.setPivot(0F, 0F, 0F);
hatband2.setTextureSize(64, 64);
hatband2.mirror = true;
setRotation(hatband2, 0F, 0F, 0F);
hatband3 = new ModelPart(this, 0, 34);
hatband3.addCuboid(-5F, -8F, -4F, 1, 1, 8);
hatband3.setPivot(0F, 0F, 0F);
hatband3.setTextureSize(64, 64);
hatband3.mirror = true;
setRotation(hatband3, 0F, 0F, 0F);
hatband4 = new ModelPart(this, 0, 34);
hatband4.addCuboid(4F, -8F, -4F, 1, 1, 8);
hatband4.setPivot(0F, 0F, 0F);
hatband4.setTextureSize(64, 64);
hatband4.mirror = true;
setRotation(hatband4, 0F, 0F, 0F);
hatbase1 = new ModelPart(this, 0, 43);
hatbase1.addCuboid(-4F, -9F, -4F, 8, 1, 8);
hatbase1.setPivot(0F, 0F, 0F);
hatbase1.setTextureSize(64, 64);
hatbase1.mirror = true;
setRotation(hatbase1, 0F, 0F, 0F);
hatband5 = new ModelPart(this, 18, 41);
hatband5.addCuboid(0F, -7F, -5F, 4, 1, 1);
hatband5.setPivot(0F, 0F, 0F);
hatband5.setTextureSize(64, 64);
hatband5.mirror = true;
setRotation(hatband5, 0F, 0F, 0F);
hatband6 = new ModelPart(this, 18, 41);
hatband6.addCuboid(-4F, -7F, 0F, 4, 1, 1);
hatband6.setPivot(0F, 0F, 4F);
hatband6.setTextureSize(64, 64);
hatband6.mirror = true;
setRotation(hatband6, 0F, 0F, 0F);
hatbase2 = new ModelPart(this, 18, 34);
hatbase2.addCuboid(-3F, -10F, -3F, 6, 1, 6);
hatbase2.setPivot(0F, 0F, 0F);
hatbase2.setTextureSize(64, 64);
hatbase2.mirror = true;
setRotation(hatbase2, 0F, 0.1115358F, 0F);
hatextension1 = new ModelPart(this, 0, 52);
hatextension1.addCuboid(-3F, -11F, -2F, 4, 2, 4);
hatextension1.setPivot(0F, 0F, 0F);
hatextension1.setTextureSize(64, 64);
hatextension1.mirror = true;
setRotation(hatextension1, 0F, -0.0371786F, 0.0743572F);
hatextension2 = new ModelPart(this, 16, 52);
hatextension2.addCuboid(-2.4F, -12F, -1.5F, 3, 2, 3);
hatextension2.setPivot(0F, 0F, 0F);
hatextension2.setTextureSize(64, 64);
hatextension2.mirror = true;
setRotation(hatextension2, 0F, 0.0743572F, 0.0743572F);
hatextension3 = new ModelPart(this, 28, 52);
hatextension3.addCuboid(-3.5F, -13F, -1F, 2, 2, 2);
hatextension3.setPivot(0F, 0F, 0F);
hatextension3.setTextureSize(64, 64);
hatextension3.mirror = true;
setRotation(hatextension3, 0F, 0F, 0.2230717F);
hatextension4 = new ModelPart(this, 0, 58);
hatextension4.addCuboid(-13F, -6.6F, -1F, 2, 3, 2);
hatextension4.setPivot(0F, 0F, 0F);
hatextension4.setTextureSize(64, 64);
hatextension4.mirror = true;
setRotation(hatextension4, 0F, 0F, 1.264073F);
hatball1 = new ModelPart(this, 8, 58);
hatball1.addCuboid(2F, -14.4F, -1.001F, 2, 2, 2);
hatball1.setPivot(0F, 0F, 0F);
hatball1.setTextureSize(64, 64);
hatball1.mirror = true;
setRotation(hatball1, 0F, 0F, 0F);
hatball2 = new ModelPart(this, 16, 57);
hatball2.addCuboid(2.5F, -14.8F, -0.5F, 1, 1, 1);
hatball2.setPivot(0F, 0F, 0F);
hatball2.setTextureSize(64, 64);
hatball2.mirror = true;
setRotation(hatball2, 0F, 0F, 0F);
hatball3 = new ModelPart(this, 16, 57);
hatball3.addCuboid(2.5F, -13F, -0.5F, 1, 1, 1);
hatball3.setPivot(0F, 0F, 0F);
hatball3.setTextureSize(64, 64);
hatball3.mirror = true;
setRotation(hatball3, 0F, 0F, 0F);
hatball4 = new ModelPart(this, 16, 57);
hatball4.addCuboid(3.4F, -14F, -0.5F, 1, 1, 1);
hatball4.setPivot(0F, 0F, 0F);
hatball4.setTextureSize(64, 64);
hatball4.mirror = true;
setRotation(hatball4, 0F, 0F, 0F);
hatball5 = new ModelPart(this, 16, 57);
hatball5.addCuboid(2.5F, -14F, 0.4F, 1, 1, 1);
hatball5.setPivot(0F, 0F, 0F);
hatball5.setTextureSize(64, 64);
hatball5.mirror = true;
setRotation(hatball5, 0F, 0F, 0F);
hatball6 = new ModelPart(this, 16, 57);
hatball6.addCuboid(2.5F, -14F, -1.4F, 1, 1, 1);
hatball6.setPivot(0F, 0F, 0F);
hatball6.setTextureSize(64, 64);
hatball6.mirror = true;
setRotation(hatball6, 0F, 0F, 0F);
}
@Override
public void setAngles(AbstractClientPlayerEntity entity, float limbAngle, float limbDistance, float age, float headYaw, float headPitch) {
}
@Override
public void render(MatrixStack matrixStack, VertexConsumer vertexConsumer, int light, int overlay, float r, float g, float b, float f) {
hatband1.render(matrixStack, vertexConsumer, light, overlay);
hatband2.render(matrixStack, vertexConsumer, light, overlay);
hatband3.render(matrixStack, vertexConsumer, light, overlay);
hatband4.render(matrixStack, vertexConsumer, light, overlay);
hatbase1.render(matrixStack, vertexConsumer, light, overlay);
hatband5.render(matrixStack, vertexConsumer, light, overlay);
hatband6.render(matrixStack, vertexConsumer, light, overlay);
hatbase2.render(matrixStack, vertexConsumer, light, overlay);
hatextension1.render(matrixStack, vertexConsumer, light, overlay);
hatextension2.render(matrixStack, vertexConsumer, light, overlay);
hatextension3.render(matrixStack, vertexConsumer, light, overlay);
hatextension4.render(matrixStack, vertexConsumer, light, overlay);
hatball1.render(matrixStack, vertexConsumer, light, overlay);
hatball2.render(matrixStack, vertexConsumer, light, overlay);
hatball3.render(matrixStack, vertexConsumer, light, overlay);
hatball4.render(matrixStack, vertexConsumer, light, overlay);
hatball5.render(matrixStack, vertexConsumer, light, overlay);
hatball6.render(matrixStack, vertexConsumer, light, overlay);
}
private void setRotation(ModelPart model, float x, float y, float z) {
model.pitch = x;
model.yaw = y;
model.roll = z;
}
@Override
public void accept(ModelPart modelPart) {
}
}

View file

@ -0,0 +1,158 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import net.fabricmc.fabric.api.client.render.fluid.v1.FluidRenderHandler;
import net.fabricmc.fabric.api.client.render.fluid.v1.FluidRenderHandlerRegistry;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.render.BufferBuilder;
import net.minecraft.client.render.Tessellator;
import net.minecraft.client.render.VertexFormats;
import net.minecraft.client.texture.Sprite;
import net.minecraft.client.texture.SpriteAtlasTexture;
import net.minecraft.client.texture.TextureManager;
import net.minecraft.fluid.Fluid;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import org.lwjgl.opengl.GL11;
import reborncore.common.fluid.FluidValue;
import reborncore.common.fluid.container.FluidInstance;
import reborncore.common.util.Tank;
/**
* Created by Gigabit101 on 08/08/2016.
*/
public class RenderUtil {
public static final Identifier BLOCK_TEX = SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE;
public static TextureManager engine() {
return MinecraftClient.getInstance().getTextureManager();
}
public static void bindBlockTexture() {
engine().bindTexture(BLOCK_TEX);
}
public static Sprite getStillTexture(FluidInstance fluid) {
if (fluid == null || fluid.getFluid() == null) {
return null;
}
return getStillTexture(fluid.getFluid());
}
public static Sprite getSprite(Identifier identifier) {
return MinecraftClient.getInstance().getSpriteAtlas(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE).apply(identifier);
}
public static Sprite getStillTexture(Fluid fluid) {
FluidRenderHandler fluidRenderHandler = FluidRenderHandlerRegistry.INSTANCE.get(fluid);
if (fluidRenderHandler != null) {
return fluidRenderHandler.getFluidSprites(MinecraftClient.getInstance().world, BlockPos.ORIGIN, fluid.getDefaultState())[0];
}
return null;
}
public static void renderGuiTank(Tank tank, double x, double y, double zLevel, double width, double height) {
renderGuiTank(tank.getFluidInstance(), tank.getCapacity(), tank.getFluidAmount(), x, y, zLevel, width, height);
}
public static void renderGuiTank(FluidInstance fluid, FluidValue capacity, FluidValue amount, double x, double y, double zLevel,
double width, double height) {
if (fluid == null || fluid.getFluid() == null || fluid.getAmount().lessThanOrEqual(FluidValue.EMPTY)) {
return;
}
Sprite icon = getStillTexture(fluid);
if (icon == null) {
return;
}
int renderAmount = (int) Math.max(Math.min(height, amount.getRawValue() * height / capacity.getRawValue()), 1);
int posY = (int) (y + height - renderAmount);
RenderUtil.bindBlockTexture();
int color = 0;
GL11.glColor3ub((byte) (color >> 16 & 0xFF), (byte) (color >> 8 & 0xFF), (byte) (color & 0xFF));
RenderSystem.enableBlend();
for (int i = 0; i < width; i += 16) {
for (int j = 0; j < renderAmount; j += 16) {
int drawWidth = (int) Math.min(width - i, 16);
int drawHeight = Math.min(renderAmount - j, 16);
int drawX = (int) (x + i);
int drawY = posY + j;
float minU = icon.getMinU();
float maxU = icon.getMaxU();
float minV = icon.getMinV();
float maxV = icon.getMaxV();
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder tes = tessellator.getBuffer();
tes.begin(GL11.GL_QUADS, VertexFormats.POSITION_TEXTURE_COLOR);
tes.vertex(drawX, drawY + drawHeight, 0).texture(minU, minV + (maxV - minV) * drawHeight / 16F).next();
tes.vertex(drawX + drawWidth, drawY + drawHeight, 0)
.texture(minU + (maxU - minU) * drawWidth / 16F, minV + (maxV - minV) * drawHeight / 16F)
.next();
tes.vertex(drawX + drawWidth, drawY, 0).texture(minU + (maxU - minU) * drawWidth / 16F, minV).next();
tes.vertex(drawX, drawY, 0).texture(minU, minV).next();
tessellator.draw();
}
}
RenderSystem.disableBlend();
}
public static void drawGradientRect(int zLevel, int left, int top, int right, int bottom, int startColor, int endColor) {
float f = (float) (startColor >> 24 & 255) / 255.0F;
float f1 = (float) (startColor >> 16 & 255) / 255.0F;
float f2 = (float) (startColor >> 8 & 255) / 255.0F;
float f3 = (float) (startColor & 255) / 255.0F;
float f4 = (float) (endColor >> 24 & 255) / 255.0F;
float f5 = (float) (endColor >> 16 & 255) / 255.0F;
float f6 = (float) (endColor >> 8 & 255) / 255.0F;
float f7 = (float) (endColor & 255) / 255.0F;
RenderSystem.disableTexture();
RenderSystem.enableBlend();
RenderSystem.disableAlphaTest();
RenderSystem.blendFuncSeparate(GlStateManager.SrcFactor.SRC_ALPHA, GlStateManager.DstFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SrcFactor.ONE, GlStateManager.DstFactor.ZERO);
RenderSystem.shadeModel(7425);
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder vertexbuffer = tessellator.getBuffer();
vertexbuffer.begin(7, VertexFormats.POSITION_COLOR);
vertexbuffer.vertex(right, top, 0).color(f1, f2, f3, f).next();
vertexbuffer.vertex(left, top, 0).color(f1, f2, f3, f).next();
vertexbuffer.vertex(left, bottom, 0).color(f5, f6, f7, f4).next();
vertexbuffer.vertex(right, bottom, 0).color(f5, f6, f7, f4).next();
tessellator.draw();
RenderSystem.shadeModel(7424);
RenderSystem.disableBlend();
RenderSystem.enableAlphaTest();
RenderSystem.enableTexture();
}
}

View file

@ -0,0 +1,134 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client;
import net.fabricmc.fabric.api.client.item.v1.ItemTooltipCallback;
import net.minecraft.block.Block;
import net.minecraft.block.BlockEntityProvider;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.client.resource.language.I18n;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.text.LiteralText;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import reborncore.RebornCore;
import reborncore.api.IListInfoProvider;
import reborncore.common.BaseBlockEntityProvider;
import reborncore.common.powerSystem.PowerSystem;
import reborncore.common.util.StringUtils;
import team.reborn.energy.Energy;
import team.reborn.energy.EnergyHolder;
import team.reborn.energy.EnergySide;
import java.util.List;
public class StackToolTipHandler implements ItemTooltipCallback {
@Override
public void getTooltip(ItemStack itemStack, TooltipContext tooltipContext, List<Text> tooltipLines) {
Item item = itemStack.getItem();
Block block = Block.getBlockFromItem(item);
if (item instanceof IListInfoProvider) {
((IListInfoProvider) item).addInfo(tooltipLines, false, false);
}
else if (item instanceof EnergyHolder) {
LiteralText line1 = new LiteralText(PowerSystem.getLocalizedPowerNoSuffix(Energy.of(itemStack).getEnergy()));
line1.append("/");
line1.append(PowerSystem.getLocalizedPower(Energy.of(itemStack).getMaxStored()));
line1.formatted(Formatting.GOLD);
tooltipLines.add(1, line1);
if (Screen.hasShiftDown()) {
int percentage = percentage(Energy.of(itemStack).getEnergy(), Energy.of(itemStack).getMaxStored());
MutableText line2 = StringUtils.getPercentageText(percentage);
line2.append(" ");
line2.formatted(Formatting.GRAY);
line2.append(I18n.translate("reborncore.gui.tooltip.power_charged"));
tooltipLines.add(2, line2);
double inputRate = ((EnergyHolder) item).getMaxInput(EnergySide.UNKNOWN);
double outputRate = ((EnergyHolder) item).getMaxOutput(EnergySide.UNKNOWN);
LiteralText line3 = new LiteralText("");
if (inputRate != 0 && inputRate == outputRate){
line3.append(I18n.translate("techreborn.tooltip.transferRate"));
line3.append(" : ");
line3.formatted(Formatting.GRAY);
line3.append(PowerSystem.getLocalizedPower(inputRate));
line3.formatted(Formatting.GOLD);
}
else if(inputRate != 0){
line3.append(I18n.translate("reborncore.tooltip.energy.inputRate"));
line3.append(" : ");
line3.formatted(Formatting.GRAY);
line3.append(PowerSystem.getLocalizedPower(inputRate));
line3.formatted(Formatting.GOLD);
}
else if (outputRate !=0){
line3.append(I18n.translate("reborncore.tooltip.energy.outputRate"));
line3.append(" : ");
line3.formatted(Formatting.GRAY);
line3.append(PowerSystem.getLocalizedPower(outputRate));
line3.formatted(Formatting.GOLD);
}
tooltipLines.add(3, line3);
}
}
else {
try {
if ((block instanceof BaseBlockEntityProvider)) {
BlockEntity blockEntity = ((BlockEntityProvider) block).createBlockEntity(MinecraftClient.getInstance().world);
boolean hasData = false;
if (itemStack.hasTag() && itemStack.getOrCreateTag().contains("blockEntity_data")) {
CompoundTag blockEntityData = itemStack.getOrCreateTag().getCompound("blockEntity_data");
if (blockEntity != null) {
blockEntity.fromTag(block.getDefaultState(), blockEntityData);
hasData = true;
tooltipLines.add(new LiteralText(I18n.translate("reborncore.tooltip.has_data")).formatted(Formatting.DARK_GREEN));
}
}
if (blockEntity instanceof IListInfoProvider) {
((IListInfoProvider) blockEntity).addInfo(tooltipLines, false, hasData);
}
}
} catch (NullPointerException e) {
RebornCore.LOGGER.debug("Failed to load info for " + itemStack.getName());
}
}
}
private int percentage(double CurrentValue, double MaxValue) {
if (CurrentValue == 0)
return 0;
return (int) ((CurrentValue * 100.0f) / MaxValue);
}
}

View file

@ -0,0 +1,103 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.render.DiffuseLighting;
import net.minecraft.client.texture.TextureManager;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import org.lwjgl.opengl.GL11;
import reborncore.common.util.Color;
public class GuiButtonCustomTexture extends ButtonWidget {
public int textureU;
public int textureV;
public String texturename;
public String linkedPage;
public Text name;
public String imageprefix = "techreborn:textures/manual/elements/";
public int buttonHeight;
public int buttonWidth;
public int buttonU;
public int buttonV;
public int textureH;
public int textureW;
public GuiButtonCustomTexture(int xPos, int yPos, int u, int v, int buttonWidth, int buttonHeight,
String texturename, String linkedPage, Text name, int buttonU, int buttonV, int textureH, int textureW, ButtonWidget.PressAction pressAction) {
super(xPos, yPos, buttonWidth, buttonHeight, LiteralText.EMPTY, pressAction);
this.textureU = u;
this.textureV = v;
this.texturename = texturename;
this.name = name;
this.linkedPage = linkedPage;
this.buttonHeight = height;
this.buttonWidth = width;
this.buttonU = buttonU;
this.buttonV = buttonV;
this.textureH = textureH;
this.textureW = textureW;
}
public void drawButton(MatrixStack matrixStack, MinecraftClient mc, int mouseX, int mouseY) {
if (this.visible) {
boolean flag = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width
&& mouseY < this.y + this.height;
mc.getTextureManager().bindTexture(WIDGETS_LOCATION);
int u = textureU;
int v = textureV;
if (flag) {
u += width;
GL11.glPushMatrix();
GL11.glColor4f(0f, 0f, 0f, 1f);
this.drawTexture(matrixStack, this.x, this.y, u, v, width, height);
GL11.glPopMatrix();
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(32826);
DiffuseLighting.enable();
renderImage(matrixStack, this.x, this.y);
this.drawTextWithShadow(matrixStack, mc.textRenderer, this.name, this.x + 20, this.y + 3,
Color.WHITE.getColor());
}
}
public void renderImage(MatrixStack matrixStack, int offsetX, int offsetY) {
TextureManager render = MinecraftClient.getInstance().getTextureManager();
render.bindTexture(new Identifier(imageprefix + this.texturename + ".png"));
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(1F, 1F, 1F, 1F);
drawTexture(matrixStack, offsetX, offsetY, this.buttonU, this.buttonV, this.textureW, this.textureH);
GL11.glDisable(GL11.GL_BLEND);
}
}

View file

@ -0,0 +1,83 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.render.DiffuseLighting;
import net.minecraft.client.render.item.ItemRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.item.ItemStack;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Text;
import org.lwjgl.opengl.GL11;
import reborncore.common.util.Color;
public class GuiButtonItemTexture extends ButtonWidget {
public int textureU;
public int textureV;
public ItemStack itemstack;
public String LINKED_PAGE;
public Text NAME;
public GuiButtonItemTexture(int xPos, int yPos, int u, int v, int width, int height, ItemStack stack,
String linkedPage, Text name, ButtonWidget.PressAction pressAction) {
super(xPos, yPos, width, height, LiteralText.EMPTY, pressAction);
textureU = u;
textureV = v;
itemstack = stack;
NAME = name;
this.LINKED_PAGE = linkedPage;
}
@Override
public void render(MatrixStack matrixStack, int mouseX, int mouseY, float ticks) {
if (this.visible) {
MinecraftClient mc = MinecraftClient.getInstance();
boolean flag = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width
&& mouseY < this.y + this.height;
mc.getTextureManager().bindTexture(WIDGETS_LOCATION);
int u = textureU;
int v = textureV;
if (flag) {
u += mc.textRenderer.getWidth(this.NAME) + 25;
v += mc.textRenderer.getWidth(this.NAME) + 25;
GL11.glPushMatrix();
GL11.glColor4f(0f, 0f, 0f, 1f);
this.drawTexture(matrixStack, this.x, this.y, u, v, mc.textRenderer.getWidth(this.NAME) + 25, height);
GL11.glPopMatrix();
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(32826);
DiffuseLighting.enable();
ItemRenderer itemRenderer = MinecraftClient.getInstance().getItemRenderer();
itemRenderer.renderGuiItemIcon(itemstack, this.x, this.y);
this.drawTextWithShadow(matrixStack, mc.textRenderer, this.NAME, this.x + 20, this.y + 3,
Color.WHITE.getColor());
}
}
}

View file

@ -0,0 +1,50 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui;
import reborncore.client.RenderUtil;
public class GuiUtil {
public static void drawTooltipBox(int x, int y, int w, int h) {
int bg = 0xf0100010;
drawGradientRect(x + 1, y, w - 1, 1, bg, bg);
drawGradientRect(x + 1, y + h, w - 1, 1, bg, bg);
drawGradientRect(x + 1, y + 1, w - 1, h - 1, bg, bg);// center
drawGradientRect(x, y + 1, 1, h - 1, bg, bg);
drawGradientRect(x + w, y + 1, 1, h - 1, bg, bg);
int grad1 = 0x505000ff;
int grad2 = 0x5028007F;
drawGradientRect(x + 1, y + 2, 1, h - 3, grad1, grad2);
drawGradientRect(x + w - 1, y + 2, 1, h - 3, grad1, grad2);
drawGradientRect(x + 1, y + 1, w - 1, 1, grad1, grad1);
drawGradientRect(x + 1, y + h - 1, w - 1, 1, grad2, grad2);
}
public static void drawGradientRect(int x, int y, int w, int h, int colour1, int colour2) {
RenderUtil.drawGradientRect(0, x, y, x + w, y + h, colour1, colour2);
}
}

View file

@ -0,0 +1,459 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder;
import com.mojang.blaze3d.systems.RenderSystem;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.screen.ingame.HandledScreen;
import net.minecraft.client.gui.widget.AbstractButtonWidget;
import net.minecraft.client.resource.language.I18n;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.fluid.Fluid;
import net.minecraft.fluid.Fluids;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.screen.slot.Slot;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.Util;
import org.lwjgl.glfw.GLFW;
import reborncore.api.blockentity.IUpgradeable;
import reborncore.client.gui.builder.slot.FluidConfigGui;
import reborncore.client.gui.builder.slot.GuiTab;
import reborncore.client.gui.builder.slot.SlotConfigGui;
import reborncore.client.gui.builder.widget.GuiButtonHologram;
import reborncore.client.gui.guibuilder.GuiBuilder;
import reborncore.client.screen.builder.BuiltScreenHandler;
import reborncore.client.screen.builder.slot.PlayerInventorySlot;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Created by Prospector
*/
public class GuiBase<T extends ScreenHandler> extends HandledScreen<T> {
public static FluidCellProvider fluidCellProvider = fluid -> ItemStack.EMPTY;
public static ItemStack wrenchStack = ItemStack.EMPTY;
private final List<GuiTab.Builder> tabBuilders = Util.make(new ArrayList<>(), builders -> {
builders.add(GuiTab.Builder.builder()
.name("reborncore.gui.tooltip.config_slots")
.enabled(guiTab -> guiTab.machine().hasSlotConfig())
.stack(guiTab -> wrenchStack)
.draw(SlotConfigGui::draw)
.click(SlotConfigGui::mouseClicked)
.mouseReleased(SlotConfigGui::mouseReleased)
.hideGuiElements()
.keyPressed((guiBase, keyCode, scanCode, modifiers) -> {
if (hasControlDown() && keyCode == GLFW.GLFW_KEY_C) {
SlotConfigGui.copyToClipboard();
return true;
} else if (hasControlDown() && keyCode == GLFW.GLFW_KEY_V) {
SlotConfigGui.pasteFromClipboard();
return true;
} else if (keyCode == GLFW.GLFW_KEY_ESCAPE && SlotConfigGui.selectedSlot != -1) {
SlotConfigGui.reset();
return true;
}
return false;
})
.tips(tips -> {
tips.add("reborncore.gui.slotconfigtip.slot");
tips.add("reborncore.gui.slotconfigtip.side1");
tips.add("reborncore.gui.slotconfigtip.side2");
tips.add("reborncore.gui.slotconfigtip.side3");
tips.add("reborncore.gui.slotconfigtip.copy1");
tips.add("reborncore.gui.slotconfigtip.copy2");
})
);
builders.add(GuiTab.Builder.builder()
.name("reborncore.gui.tooltip.config_fluids")
.enabled(guiTab -> guiTab.machine().showTankConfig())
.stack(guiTab -> GuiBase.fluidCellProvider.provide(Fluids.LAVA))
.draw(FluidConfigGui::draw)
.click(FluidConfigGui::mouseClicked)
.mouseReleased(FluidConfigGui::mouseReleased)
.hideGuiElements()
);
builders.add(GuiTab.Builder.builder()
.name("reborncore.gui.tooltip.config_redstone")
.stack(guiTab -> new ItemStack(Items.REDSTONE))
.draw(RedstoneConfigGui::draw)
.click(RedstoneConfigGui::mouseClicked)
);
});
public GuiBuilder builder = new GuiBuilder();
public BlockEntity be;
@Nullable
public BuiltScreenHandler builtScreenHandler;
private final int xSize = 176;
private final int ySize = 176;
private GuiTab selectedTab;
private List<GuiTab> tabs;
public boolean upgrades;
public GuiBase(PlayerEntity player, BlockEntity blockEntity, T screenHandler) {
super(screenHandler, player.inventory, new LiteralText(I18n.translate(blockEntity.getCachedState().getBlock().getTranslationKey())));
this.be = blockEntity;
this.builtScreenHandler = (BuiltScreenHandler) screenHandler;
selectedTab = null;
populateSlots();
}
private void populateSlots() {
tabs = tabBuilders.stream()
.map(builder -> builder.build(getMachine(), this))
.filter(GuiTab::enabled)
.collect(Collectors.toList());
}
public int getScreenWidth() {
return backgroundWidth;
}
public void drawSlot(MatrixStack matrixStack, int x, int y, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += this.x;
y += this.y;
}
builder.drawSlot(matrixStack, this, x - 1, y - 1);
}
public void drawOutputSlotBar(MatrixStack matrixStack, int x, int y, int count, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += this.x;
y += this.y;
}
builder.drawOutputSlotBar(matrixStack, this, x - 4, y - 4, count);
}
public void drawArmourSlots(MatrixStack matrixStack, int x, int y, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += this.x;
y += this.y;
}
builder.drawSlot(matrixStack, this, x - 1, y - 1);
builder.drawSlot(matrixStack, this, x - 1, y - 1 + 18);
builder.drawSlot(matrixStack, this, x - 1, y - 1 + 18 + 18);
builder.drawSlot(matrixStack, this, x - 1, y - 1 + 18 + 18 + 18);
}
public void drawOutputSlot(MatrixStack matrixStack, int x, int y, Layer layer) {
if (layer == Layer.BACKGROUND) {
x += this.x;
y += this.y;
}
builder.drawOutputSlot(matrixStack, this, x - 5, y - 5);
}
@Override
public void init() {
super.init();
if (isConfigEnabled()) {
SlotConfigGui.init(this);
}
if (isConfigEnabled() && getMachine().getTank() != null && getMachine().showTankConfig()) {
FluidConfigGui.init(this);
}
}
@Override
protected void drawBackground(MatrixStack matrixStack, float lastFrameDuration, int mouseX, int mouseY) {
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
renderBackground(matrixStack);
boolean drawPlayerSlots = selectedTab == null && drawPlayerSlots();
updateSlotDraw(drawPlayerSlots);
builder.drawDefaultBackground(matrixStack, this, x, y, xSize, ySize);
if (drawPlayerSlots) {
builder.drawPlayerSlots(matrixStack, this, x + backgroundWidth / 2, y + 93, true);
}
if (tryAddUpgrades() && be instanceof IUpgradeable) {
IUpgradeable upgradeable = (IUpgradeable) be;
if (upgradeable.canBeUpgraded()) {
builder.drawUpgrades(matrixStack, this, x - 24, y + 6);
upgrades = true;
}
}
int offset = upgrades ? 86 : 6;
for (GuiTab slot : tabs) {
if (slot.enabled()) {
builder.drawSlotTab(matrixStack, this, x - 24, y + offset, slot.stack());
offset += 24;
}
}
final GuiBase<T> gui = this;
getTab().ifPresent(guiTab -> builder.drawSlotConfigTips(matrixStack, gui, x + backgroundWidth / 2, y + 93, mouseX, mouseY, guiTab));
}
private void updateSlotDraw(boolean doDraw) {
if (builtScreenHandler == null) {
return;
}
for (Slot slot : builtScreenHandler.slots) {
if (slot instanceof PlayerInventorySlot) {
((PlayerInventorySlot) slot).doDraw = doDraw;
}
}
}
public boolean drawPlayerSlots() {
return true;
}
public boolean tryAddUpgrades() {
return true;
}
@Environment(EnvType.CLIENT)
@Override
protected void drawForeground(MatrixStack matrixStack, int mouseX, int mouseY) {
drawTitle(matrixStack);
getTab().ifPresent(guiTab -> guiTab.draw(matrixStack, mouseX, mouseY));
}
@Override
public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
super.render(matrixStack, mouseX, mouseY, partialTicks);
this.drawMouseoverTooltip(matrixStack, mouseX, mouseY);
}
@Override
protected void drawMouseoverTooltip(MatrixStack matrixStack, int mouseX, int mouseY) {
if (isPointWithinBounds(-25, 6, 24, 80, mouseX, mouseY) && upgrades
&& this.focusedSlot != null && !this.focusedSlot.hasStack()) {
List<Text> list = new ArrayList<>();
list.add(new TranslatableText("reborncore.gui.tooltip.upgrades"));
renderTooltip(matrixStack, list, mouseX, mouseY);
}
int offset = upgrades ? 82 : 0;
for (GuiTab tab : tabs) {
if (isPointWithinBounds(-26, 6 + offset, 24, 23, mouseX, mouseY)) {
renderTooltip(matrixStack, Collections.singletonList(new TranslatableText(tab.name())), mouseX, mouseY);
}
offset += 24;
}
for (AbstractButtonWidget abstractButtonWidget : buttons) {
if (abstractButtonWidget.isHovered()) {
abstractButtonWidget.renderToolTip(matrixStack, mouseX, mouseY);
break;
}
}
super.drawMouseoverTooltip(matrixStack, mouseX, mouseY);
}
protected void drawTitle(MatrixStack matrixStack) {
drawCentredText(matrixStack, new TranslatableText(be.getCachedState().getBlock().getTranslationKey()), 6, 4210752, Layer.FOREGROUND);
}
public void drawCentredText(MatrixStack matrixStack, Text text, int y, int colour, Layer layer) {
drawText(matrixStack, text, (backgroundWidth / 2 - getTextRenderer().getWidth(text) / 2), y, colour, layer);
}
protected void drawCentredText(MatrixStack matrixStack, Text text, int y, int colour, int modifier, Layer layer) {
drawText(matrixStack, text, (backgroundWidth / 2 - (getTextRenderer().getWidth(text)) / 2) + modifier, y, colour, layer);
}
public void drawText(MatrixStack matrixStack, Text text, int x, int y, int colour, Layer layer) {
int factorX = 0;
int factorY = 0;
if (layer == Layer.BACKGROUND) {
factorX = this.x;
factorY = this.y;
}
getTextRenderer().draw(matrixStack, text, x + factorX, y + factorY, colour);
RenderSystem.color4f(1, 1, 1, 1);
}
public GuiButtonHologram addHologramButton(int x, int y, int id, Layer layer) {
GuiButtonHologram buttonHologram = new GuiButtonHologram(x + this.x, y + this.y, this, layer, var1 -> {
});
addButton(buttonHologram);
return buttonHologram;
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) {
if (getTab().map(guiTab -> guiTab.click(mouseX, mouseY, mouseButton)).orElse(false)) {
return true;
}
return super.mouseClicked(mouseX, mouseY, mouseButton);
}
// @Override
// protected void mouseClickMove(double mouseX, double mouseY, int clickedMouseButton, long timeSinceLastClick) {
// if (isConfigEnabled() && slotConfigType == SlotConfigType.ITEMS && getMachine().hasSlotConfig()) {
// GuiSlotConfiguration.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick, this);
// }
// if (isConfigEnabled() && slotConfigType == SlotConfigType.FLUIDS && getMachine().showTankConfig()) {
// GuiFluidConfiguration.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick, this);
// }
// super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick);
// }
@Override
public boolean mouseReleased(double mouseX, double mouseY, int state) {
int offset = 0;
if (!upgrades) {
offset = 80;
}
for (GuiTab tab : tabs) {
if (isPointWithinBounds(-26, 84 - offset, 30, 23, mouseX, mouseY)) {
if (selectedTab == tab) {
closeSelectedTab();
} else {
selectedTab = tab;
}
SlotConfigGui.reset();
break;
}
offset -= 24;
}
if (getTab().map(guiTab -> guiTab.mouseReleased(mouseX, mouseY, state)).orElse(false)) {
return true;
}
return super.mouseReleased(mouseX, mouseY, state);
}
@Override
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
if (getTab().map(guiTab -> guiTab.keyPress(keyCode, scanCode, modifiers)).orElse(false)) {
return true;
}
if (selectedTab != null && keyCode == GLFW.GLFW_KEY_ESCAPE) {
closeSelectedTab();
return true;
}
return super.keyPressed(keyCode, scanCode, modifiers);
}
@Override
public void onClose() {
closeSelectedTab();
super.onClose();
}
@Nullable
public MachineBaseBlockEntity getMachine() {
return (MachineBaseBlockEntity) be;
}
/**
* @param rectX int Top left corner of region
* @param rectY int Top left corner of region
* @param rectWidth int Width of region
* @param rectHeight int Height of region
* @param pointX int Mouse pointer
* @param pointY int Mouse pointer
* @return boolean Returns true if mouse pointer is in region specified
*/
public boolean isPointInRect(int rectX, int rectY, int rectWidth, int rectHeight, double pointX, double pointY) {
return super.isPointWithinBounds(rectX, rectY, rectWidth, rectHeight, pointX, pointY);
}
public enum Layer {
BACKGROUND, FOREGROUND
}
public interface FluidCellProvider {
ItemStack provide(Fluid fluid);
}
public boolean isConfigEnabled() {
return be instanceof MachineBaseBlockEntity && builtScreenHandler != null;
}
public int getGuiLeft() {
return x;
}
public int getGuiTop() {
return y;
}
public MinecraftClient getMinecraft() {
// Just to stop complains from IDEA
if (client == null) {
throw new NullPointerException("Minecraft client is null.");
}
return this.client;
}
public TextRenderer getTextRenderer() {
return this.textRenderer;
}
public Optional<GuiTab> getTab() {
if (!isConfigEnabled()) {
return Optional.empty();
}
return Optional.ofNullable(selectedTab);
}
public boolean isTabOpen() {
return selectedTab != null;
}
public boolean hideGuiElements() {
return selectedTab != null && selectedTab.hideGuiElements();
}
public void closeSelectedTab() {
selectedTab = null;
}
@Override
protected boolean isClickOutsideBounds(double mouseX, double mouseY, int left, int top, int mouseButton) {
//Expanded the width to allow for the upgrades
return super.isClickOutsideBounds(mouseX + 40, mouseY, left + 40, top, mouseButton);
}
public List<GuiTab> getTabs() {
return tabs;
}
}

View file

@ -0,0 +1,103 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder;
import net.minecraft.client.render.item.ItemRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.network.Packet;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import reborncore.client.RenderUtil;
import reborncore.client.gui.guibuilder.GuiBuilder;
import reborncore.common.blockentity.RedstoneConfiguration;
import reborncore.common.network.IdentifiedPacket;
import reborncore.common.network.NetworkManager;
import reborncore.common.network.ServerBoundPackets;
import java.util.Locale;
public class RedstoneConfigGui {
public static void draw(MatrixStack matrixStack, GuiBase<?> guiBase, int mouseX, int mouseY) {
if (guiBase.getMachine() == null) return;
RedstoneConfiguration configuration = guiBase.getMachine().getRedstoneConfiguration();
GuiBuilder builder = guiBase.builder;
ItemRenderer itemRenderer = guiBase.getMinecraft().getItemRenderer();
int x = 10;
int y = 100;
int i = 0;
int spread = configuration.getElements().size() == 3 ? 27 : 18;
for (RedstoneConfiguration.Element element : configuration.getElements()) {
itemRenderer.renderInGuiWithOverrides(element.getIcon(), x - 3, y + (i * spread) - 5);
guiBase.getTextRenderer().draw(matrixStack, new TranslatableText("reborncore.gui.fluidconfig." + element.getName()), x + 15, y + (i * spread), -1);
boolean hovered = withinBounds(guiBase, mouseX, mouseY, x + 92, y + (i * spread) - 2, 63, 15);
int color = hovered ? 0xFF8b8b8b : 0x668b8b8b;
RenderUtil.drawGradientRect(0, x + 91, y + (i * spread) - 2, x + 93 + 65, y + (i * spread) + 10, color, color);
Text name = new TranslatableText("reborncore.gui.fluidconfig." + configuration.getState(element).name().toLowerCase(Locale.ROOT));
guiBase.drawCentredText(matrixStack, name, y + (i * spread), -1, x + 37, GuiBase.Layer.FOREGROUND);
//guiBase.getTextRenderer().drawWithShadow(name, x + 92, y + (i * spread), -1);
i++;
}
}
public static boolean mouseClicked(GuiBase<?> guiBase, double mouseX, double mouseY, int mouseButton) {
if (guiBase.getMachine() == null) return false;
RedstoneConfiguration configuration = guiBase.getMachine().getRedstoneConfiguration();
int x = 10;
int y = 100;
int i = 0;
int spread = configuration.getElements().size() == 3 ? 27 : 18;
for (RedstoneConfiguration.Element element : configuration.getElements()) {
if (withinBounds(guiBase, (int) mouseX, (int) mouseY, x + 91, y + (i * spread) - 2, 63, 15)) {
RedstoneConfiguration.State currentState = configuration.getState(element);
int ns = currentState.ordinal() + 1;
if (ns >= RedstoneConfiguration.State.values().length) {
ns = 0;
}
RedstoneConfiguration.State nextState = RedstoneConfiguration.State.values()[ns];
IdentifiedPacket packet = ServerBoundPackets.createPacketSetRedstoneSate(guiBase.getMachine().getPos(), element, nextState);
NetworkManager.sendToServer(packet);
return true;
}
i++;
}
return false;
}
private static boolean withinBounds(GuiBase<?> guiBase, int mouseX, int mouseY, int x, int y, int width, int height) {
mouseX -= guiBase.getGuiLeft();
mouseY -= guiBase.getGuiTop();
return (mouseX > x && mouseX < x + width) && (mouseY > y && mouseY < y + height);
}
}

View file

@ -0,0 +1,145 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot;
import com.google.common.collect.Lists;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.util.math.MatrixStack;
import reborncore.client.gui.builder.GuiBase;
import reborncore.client.gui.builder.slot.elements.ConfigFluidElement;
import reborncore.client.gui.builder.slot.elements.ElementBase;
import reborncore.client.gui.builder.slot.elements.SlotType;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
public class FluidConfigGui {
static ConfigFluidElement fluidConfigElement;
public static void init(GuiBase<?> guiBase) {
fluidConfigElement = new ConfigFluidElement(guiBase.getMachine().getTank(), SlotType.NORMAL, 35 - guiBase.getGuiLeft() + 50, 35 - guiBase.getGuiTop() - 25, guiBase);
}
public static void draw(MatrixStack matrixStack, GuiBase<?> guiBase, int mouseX, int mouseY) {
fluidConfigElement.draw(matrixStack, guiBase);
}
public static List<ConfigFluidElement> getVisibleElements() {
return Collections.singletonList(fluidConfigElement);
}
public static boolean mouseClicked(GuiBase<?> guiBase, double mouseX, double mouseY, int mouseButton) {
if (mouseButton == 0) {
for (ConfigFluidElement configFluidElement : getVisibleElements()) {
for (ElementBase element : configFluidElement.elements) {
if (element.isInRect(guiBase, element.x, element.y, element.getWidth(guiBase.getMachine()), element.getHeight(guiBase.getMachine()), mouseX, mouseY)) {
element.isPressing = true;
boolean action = element.onStartPress(guiBase.getMachine(), guiBase, mouseX, mouseY);
for (ElementBase e : getVisibleElements()) {
if (e != element) {
e.isPressing = false;
}
}
if (action) {
break;
}
} else {
element.isPressing = false;
}
}
}
}
return !getVisibleElements().isEmpty();
}
public static void mouseClickMove(double mouseX, double mouseY, int mouseButton, long timeSinceLastClick, GuiBase<?> guiBase) {
if (mouseButton == 0) {
for (ConfigFluidElement configFluidElement : getVisibleElements()) {
for (ElementBase element : configFluidElement.elements) {
if (element.isInRect(guiBase, element.x, element.y, element.getWidth(guiBase.getMachine()), element.getHeight(guiBase.getMachine()), mouseX, mouseY)) {
element.isDragging = true;
boolean action = element.onDrag(guiBase.getMachine(), guiBase, mouseX, mouseY);
for (ElementBase e : getVisibleElements()) {
if (e != element) {
e.isDragging = false;
}
}
if (action) {
break;
}
} else {
element.isDragging = false;
}
}
}
}
}
public static boolean mouseReleased(GuiBase<?> guiBase, double mouseX, double mouseY, int mouseButton) {
boolean clicked = false;
if (mouseButton == 0) {
for (ConfigFluidElement configFluidElement : getVisibleElements()) {
if (configFluidElement.isInRect(guiBase, configFluidElement.x, configFluidElement.y, configFluidElement.getWidth(guiBase.getMachine()), configFluidElement.getHeight(guiBase.getMachine()), mouseX, mouseY)) {
clicked = true;
}
for (ElementBase element : Lists.reverse(configFluidElement.elements)) {
if (element.isInRect(guiBase, element.x, element.y, element.getWidth(guiBase.getMachine()), element.getHeight(guiBase.getMachine()), mouseX, mouseY)) {
element.isReleasing = true;
boolean action = element.onRelease(guiBase.getMachine(), guiBase, mouseX, mouseY);
for (ElementBase e : getVisibleElements()) {
if (e != element) {
e.isReleasing = false;
}
}
if (action) {
clicked = true;
}
break;
} else {
element.isReleasing = false;
}
}
}
}
return clicked;
}
@Nullable
private static MachineBaseBlockEntity getMachine() {
if (!(MinecraftClient.getInstance().currentScreen instanceof GuiBase)) {
return null;
}
GuiBase<?> base = (GuiBase<?>) MinecraftClient.getInstance().currentScreen;
if (!(base.be instanceof MachineBaseBlockEntity)) {
return null;
}
MachineBaseBlockEntity machineBase = (MachineBaseBlockEntity) base.be;
return machineBase;
}
}

View file

@ -0,0 +1,181 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.item.ItemStack;
import org.apache.commons.lang3.Validate;
import reborncore.client.gui.builder.GuiBase;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
public class GuiTab {
private final Builder builder;
private final MachineBaseBlockEntity machineBaseBlockEntity;
private final GuiBase<?> guiBase;
private GuiTab(Builder builder, MachineBaseBlockEntity machineBaseBlockEntity, GuiBase<?> guiBase) {
this.builder = builder;
this.machineBaseBlockEntity = machineBaseBlockEntity;
this.guiBase = guiBase;
}
public String name() {
return builder.name;
}
public boolean enabled() {
return builder.enabled.apply(this);
}
public ItemStack stack() {
return builder.stack.apply(this);
}
public MachineBaseBlockEntity machine() {
return machineBaseBlockEntity;
}
public void draw(MatrixStack matrixStack, int x, int y) {
builder.draw.draw(matrixStack, guiBase, x, y);
}
public boolean click(double mouseX, double mouseY, int mouseButton) {
return builder.click.click(guiBase, mouseX, mouseY, mouseButton);
}
public boolean mouseReleased(double mouseX, double mouseY, int mouseButton) {
return builder.mouseReleased.mouseReleased(guiBase, mouseX, mouseY, mouseButton);
}
public boolean keyPress(int keyCode, int scanCode, int modifiers) {
return builder.keyPressed.keyPress(guiBase, keyCode, scanCode, modifiers);
}
public List<String> getTips() {
List<String> tips = new LinkedList<>();
builder.tips.accept(tips);
return tips;
}
public boolean hideGuiElements() {
return builder.hideGuiElements;
}
public GuiBase<?> gui() {
return guiBase;
}
public static class Builder {
private String name;
private Function<GuiTab, Boolean> enabled = (tab) -> true;
private Function<GuiTab, ItemStack> stack = (tab) -> ItemStack.EMPTY;
private Draw draw = (matrixStack, gui, x, y) -> {
};
private Click click = (guiBase, mouseX, mouseY, mouseButton) -> false;
private MouseReleased mouseReleased = (guiBase, mouseX, mouseY, state) -> false;
private KeyPressed keyPressed = (guiBase, keyCode, scanCode, modifiers) -> false;
private Consumer<List<String>> tips = strings -> {
};
private boolean hideGuiElements = false;
public static Builder builder() {
return new Builder();
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder stack(Function<GuiTab, ItemStack> function) {
this.stack = function;
return this;
}
public Builder enabled(Function<GuiTab, Boolean> function) {
this.enabled = function;
return this;
}
public Builder draw(Draw draw) {
this.draw = draw;
return this;
}
public Builder click(Click click) {
this.click = click;
return this;
}
public Builder mouseReleased(MouseReleased mouseReleased) {
this.mouseReleased = mouseReleased;
return this;
}
public Builder keyPressed(KeyPressed keyPressed) {
this.keyPressed = keyPressed;
return this;
}
public Builder tips(Consumer<List<String>> listConsumer) {
this.tips = listConsumer;
return this;
}
public Builder hideGuiElements() {
hideGuiElements = true;
return this;
}
public GuiTab build(MachineBaseBlockEntity blockEntity, GuiBase<?> guiBase) {
Validate.notBlank(name, "No name provided");
return new GuiTab(this, blockEntity, guiBase);
}
public interface Draw {
void draw(MatrixStack matrixStack, GuiBase<?> guiBase, int mouseX, int mouseY);
}
public interface Click {
boolean click(GuiBase<?> guiBase, double mouseX, double mouseY, int mouseButton);
}
public interface MouseReleased {
boolean mouseReleased(GuiBase<?> guiBase, double mouseX, double mouseY, int state);
}
public interface KeyPressed {
boolean keyPress(GuiBase<?> guiBase, int keyCode, int scanCode, int modifiers);
}
}
}

View file

@ -0,0 +1,233 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot;
import com.google.common.collect.Lists;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.screen.slot.Slot;
import net.minecraft.text.LiteralText;
import net.minecraft.util.Util;
import reborncore.client.gui.GuiUtil;
import reborncore.client.gui.builder.GuiBase;
import reborncore.client.gui.builder.slot.elements.ConfigSlotElement;
import reborncore.client.gui.builder.slot.elements.ElementBase;
import reborncore.client.gui.builder.slot.elements.SlotType;
import reborncore.client.screen.builder.BuiltScreenHandler;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import reborncore.common.network.NetworkManager;
import reborncore.common.network.ServerBoundPackets;
import reborncore.common.util.Color;
import reborncore.mixin.common.AccessorSlot;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
public class SlotConfigGui {
static HashMap<Integer, ConfigSlotElement> slotElementMap = new HashMap<>();
public static int selectedSlot = 0;
public static void reset() {
selectedSlot = -1;
}
public static void init(GuiBase<?> guiBase) {
reset();
slotElementMap.clear();
BuiltScreenHandler container = guiBase.builtScreenHandler;
for (Slot slot : container.slots) {
if (guiBase.be != slot.inventory) {
continue;
}
AccessorSlot accessorSlot = (AccessorSlot) slot;
ConfigSlotElement slotElement = new ConfigSlotElement(guiBase.getMachine().getOptionalInventory().get(), accessorSlot.getIndex(), SlotType.NORMAL, slot.x - guiBase.getGuiLeft() + 50, slot.y - guiBase.getGuiTop() - 25, guiBase);
slotElementMap.put(accessorSlot.getIndex(), slotElement);
}
}
public static void draw(MatrixStack matrixStack, GuiBase<?> guiBase, int mouseX, int mouseY) {
BuiltScreenHandler container = guiBase.builtScreenHandler;
for (Slot slot : container.slots) {
if (guiBase.be != slot.inventory) {
continue;
}
RenderSystem.color3f(255, 0, 0);
Color color = new Color(255, 0, 0, 128);
GuiUtil.drawGradientRect(slot.x - 1, slot.y - 1, 18, 18, color.getColor(), color.getColor());
RenderSystem.color3f(255, 255, 255);
}
if (selectedSlot != -1) {
slotElementMap.get(selectedSlot).draw(matrixStack, guiBase);
}
}
public static List<ConfigSlotElement> getVisibleElements() {
if (selectedSlot == -1) {
return Collections.emptyList();
}
return slotElementMap.values().stream()
.filter(configSlotElement -> configSlotElement.getId() == selectedSlot)
.collect(Collectors.toList());
}
public static void copyToClipboard() {
MachineBaseBlockEntity machine = getMachine();
if (machine == null || machine.getSlotConfiguration() == null) {
return;
}
String json = machine.getSlotConfiguration().toJson(machine.getClass().getCanonicalName());
MinecraftClient.getInstance().keyboard.setClipboard(json);
MinecraftClient.getInstance().player.sendSystemMessage(new LiteralText("Slot configuration copyied to clipboard"), Util.NIL_UUID);
}
public static void pasteFromClipboard() {
MachineBaseBlockEntity machine = getMachine();
if (machine == null || machine.getSlotConfiguration() == null) {
return;
}
String json = MinecraftClient.getInstance().keyboard.getClipboard();
try {
machine.getSlotConfiguration().readJson(json, machine.getClass().getCanonicalName());
NetworkManager.sendToServer(ServerBoundPackets.createPacketConfigSave(machine.getPos(), machine.getSlotConfiguration()));
MinecraftClient.getInstance().player.sendSystemMessage(new LiteralText("Slot configuration loaded from clipboard"), Util.NIL_UUID);
} catch (UnsupportedOperationException e) {
MinecraftClient.getInstance().player.sendSystemMessage(new LiteralText(e.getMessage()), Util.NIL_UUID);
}
}
@Nullable
private static MachineBaseBlockEntity getMachine() {
if (!(MinecraftClient.getInstance().currentScreen instanceof GuiBase)) {
return null;
}
GuiBase<?> base = (GuiBase<?>) MinecraftClient.getInstance().currentScreen;
if (!(base.be instanceof MachineBaseBlockEntity)) {
return null;
}
MachineBaseBlockEntity machineBase = (MachineBaseBlockEntity) base.be;
return machineBase;
}
public static boolean mouseClicked(GuiBase<?> guiBase, double mouseX, double mouseY, int mouseButton) {
if (mouseButton == 0) {
for (ConfigSlotElement configSlotElement : getVisibleElements()) {
for (ElementBase element : configSlotElement.elements) {
if (element.isInRect(guiBase, element.x, element.y, element.getWidth(guiBase.getMachine()), element.getHeight(guiBase.getMachine()), mouseX, mouseY)) {
element.isPressing = true;
boolean action = element.onStartPress(guiBase.getMachine(), guiBase, mouseX, mouseY);
for (ElementBase e : getVisibleElements()) {
if (e != element) {
e.isPressing = false;
}
}
if (action) {
break;
}
} else {
element.isPressing = false;
}
}
}
}
BuiltScreenHandler screenHandler = guiBase.builtScreenHandler;
if (getVisibleElements().isEmpty()) {
for (Slot slot : screenHandler.slots) {
if (guiBase.be != slot.inventory) {
continue;
}
if (guiBase.isPointInRect(slot.x, slot.y, 18, 18, mouseX, mouseY)) {
AccessorSlot accessorSlot = (AccessorSlot) slot;
selectedSlot = accessorSlot.getIndex();
return true;
}
}
}
return !getVisibleElements().isEmpty();
}
public static void mouseClickMove(double mouseX, double mouseY, int mouseButton, long timeSinceLastClick, GuiBase<?> guiBase) {
if (mouseButton == 0) {
for (ConfigSlotElement configSlotElement : getVisibleElements()) {
for (ElementBase element : configSlotElement.elements) {
if (element.isInRect(guiBase, element.x, element.y, element.getWidth(guiBase.getMachine()), element.getHeight(guiBase.getMachine()), mouseX, mouseY)) {
element.isDragging = true;
boolean action = element.onDrag(guiBase.getMachine(), guiBase, mouseX, mouseY);
for (ElementBase e : getVisibleElements()) {
if (e != element) {
e.isDragging = false;
}
}
if (action) {
break;
}
} else {
element.isDragging = false;
}
}
}
}
}
public static boolean mouseReleased(GuiBase<?> guiBase, double mouseX, double mouseY, int mouseButton) {
boolean clicked = false;
if (mouseButton == 0) {
for (ConfigSlotElement configSlotElement : getVisibleElements()) {
if (configSlotElement.isInRect(guiBase, configSlotElement.x, configSlotElement.y, configSlotElement.getWidth(guiBase.getMachine()), configSlotElement.getHeight(guiBase.getMachine()), mouseX, mouseY)) {
clicked = true;
}
for (ElementBase element : Lists.reverse(configSlotElement.elements)) {
if (element.isInRect(guiBase, element.x, element.y, element.getWidth(guiBase.getMachine()), element.getHeight(guiBase.getMachine()), mouseX, mouseY)) {
element.isReleasing = true;
boolean action = element.onRelease(guiBase.getMachine(), guiBase, mouseX, mouseY);
for (ElementBase e : getVisibleElements()) {
if (e != element) {
e.isReleasing = false;
}
}
if (action) {
clicked = true;
}
break;
} else {
element.isReleasing = false;
}
}
}
}
return clicked;
}
}

View file

@ -0,0 +1,42 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot.elements;
public class ButtonElement extends ElementBase {
@SuppressWarnings("unused")
private final Sprite.Button buttonSprite;
public ButtonElement(int x, int y, Sprite.Button buttonSprite) {
super(x, y, buttonSprite.getNormal());
this.buttonSprite = buttonSprite;
this.addUpdateAction((gui, element) -> {
if (isHovering) {
element.container.setSprite(0, buttonSprite.getHovered());
} else {
element.container.setSprite(0, buttonSprite.getNormal());
}
});
}
}

View file

@ -0,0 +1,78 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot.elements;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.Text;
import reborncore.client.gui.builder.GuiBase;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import java.util.function.Predicate;
public class CheckBoxElement extends ElementBase {
public Text label;
public String type;
public int labelColor, slotID;
public MachineBaseBlockEntity machineBase;
Predicate<CheckBoxElement> ticked;
private final Sprite.CheckBox checkBoxSprite;
public CheckBoxElement(Text label, int labelColor, int x, int y, String type, int slotID, Sprite.CheckBox checkBoxSprite, MachineBaseBlockEntity machineBase, Predicate<CheckBoxElement> ticked) {
super(x, y, checkBoxSprite.getNormal());
this.checkBoxSprite = checkBoxSprite;
this.type = type;
this.slotID = slotID;
this.machineBase = machineBase;
this.label = label;
this.labelColor = labelColor;
this.ticked = ticked;
if (ticked.test(this)) {
container.setSprite(0, checkBoxSprite.getTicked());
} else {
container.setSprite(0, checkBoxSprite.getNormal());
}
this.addPressAction((element, gui, provider, mouseX, mouseY) -> {
if (ticked.test(this)) {
element.container.setSprite(0, checkBoxSprite.getTicked());
} else {
element.container.setSprite(0, checkBoxSprite.getNormal());
}
return true;
});
}
@Override
public void draw(MatrixStack matrixStack, GuiBase<?> gui) {
// super.draw(gui);
ISprite sprite = checkBoxSprite.getNormal();
if (ticked.test(this)) {
sprite = checkBoxSprite.getTicked();
}
drawSprite(matrixStack, gui, sprite, x, y);
drawText(matrixStack, gui, label, x + checkBoxSprite.getNormal().width + 5, ((y + getHeight(gui.getMachine()) / 2) - (gui.getTextRenderer().fontHeight / 2)), labelColor);
}
}

View file

@ -0,0 +1,81 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot.elements;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.TranslatableText;
import reborncore.client.gui.builder.GuiBase;
import reborncore.common.util.Tank;
import java.util.ArrayList;
import java.util.List;
public class ConfigFluidElement extends ElementBase {
SlotType type;
Tank tank;
public List<ElementBase> elements = new ArrayList<>();
boolean filter = false;
public ConfigFluidElement(Tank tank, SlotType type, int x, int y, GuiBase<?> gui) {
super(x, y, type.getButtonSprite());
this.type = type;
this.tank = tank;
FluidConfigPopupElement popupElement;
elements.add(popupElement = new FluidConfigPopupElement(x - 22, y - 22, this));
elements.add(new ButtonElement(x + 37, y - 25, Sprite.EXIT_BUTTON).addReleaseAction((element, gui1, provider, mouseX, mouseY) -> {
gui.closeSelectedTab();
return true;
}));
elements.add(new CheckBoxElement(new TranslatableText("reborncore.gui.fluidconfig.pullin"), 0xFFFFFFFF, x - 26, y + 42, "input", 0, Sprite.LIGHT_CHECK_BOX, gui.getMachine(),
checkBoxElement -> checkBoxElement.machineBase.fluidConfiguration.autoInput()).addPressAction((element, gui12, provider, mouseX, mouseY) -> {
popupElement.updateCheckBox((CheckBoxElement) element, "input", gui12);
return true;
}));
elements.add(new CheckBoxElement(new TranslatableText("reborncore.gui.fluidconfig.pumpout"), 0xFFFFFFFF, x - 26, y + 57, "output", 0, Sprite.LIGHT_CHECK_BOX, gui.getMachine(),
checkBoxElement -> checkBoxElement.machineBase.fluidConfiguration.autoOutput()).addPressAction((element, gui13, provider, mouseX, mouseY) -> {
popupElement.updateCheckBox((CheckBoxElement) element, "output", gui13);
return true;
}));
setWidth(85);
setHeight(105 + (filter ? 15 : 0));
}
@Override
public void draw(MatrixStack matrixStack, GuiBase<?> gui) {
super.draw(matrixStack, gui);
if (isHovering) {
drawSprite(matrixStack, gui, type.getButtonHoverOverlay(), x, y);
}
elements.forEach(elementBase -> elementBase.draw(matrixStack, gui));
}
public SlotType getType() {
return type;
}
}

View file

@ -0,0 +1,136 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot.elements;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.render.item.ItemRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.text.TranslatableText;
import reborncore.client.gui.builder.GuiBase;
import reborncore.client.gui.builder.slot.SlotConfigGui;
import reborncore.client.gui.slots.BaseSlot;
import reborncore.common.blockentity.SlotConfiguration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class ConfigSlotElement extends ElementBase {
SlotType type;
Inventory inventory;
int id;
public List<ElementBase> elements = new ArrayList<>();
boolean filter = false;
public ConfigSlotElement(Inventory slotInventory, int slotId, SlotType type, int x, int y, GuiBase<?> gui) {
super(x, y, type.getButtonSprite());
this.type = type;
this.inventory = slotInventory;
this.id = slotId;
SlotConfigPopupElement popupElement;
boolean inputEnabled = gui.builtScreenHandler.slots.stream()
.filter(Objects::nonNull)
.filter(slot -> slot.inventory == inventory)
.filter(slot -> slot instanceof BaseSlot)
.map(slot -> (BaseSlot) slot)
.filter(baseSlot -> baseSlot.getSlotID() == slotId)
.allMatch(BaseSlot::canWorldBlockInsert);
elements.add(popupElement = new SlotConfigPopupElement(this.id, x - 22, y - 22, this, inputEnabled));
elements.add(new ButtonElement(x + 37, y - 25, Sprite.EXIT_BUTTON).addReleaseAction((element, gui1, provider, mouseX, mouseY) -> {
SlotConfigGui.selectedSlot = -1;
gui.closeSelectedTab();
return true;
}));
if (inputEnabled) {
elements.add(new CheckBoxElement(new TranslatableText("reborncore.gui.slotconfig.autoinput"), 0xFFFFFFFF, x - 26, y + 42, "input", slotId, Sprite.LIGHT_CHECK_BOX, gui.getMachine(),
checkBoxElement -> checkBoxElement.machineBase.getSlotConfiguration().getSlotDetails(checkBoxElement.slotID).autoInput()).addPressAction((element, gui12, provider, mouseX, mouseY) -> {
popupElement.updateCheckBox((CheckBoxElement) element, "input", gui12);
return true;
}));
}
elements.add(new CheckBoxElement(new TranslatableText("reborncore.gui.slotconfig.autooutput"), 0xFFFFFFFF, x - 26, y + 57, "output", slotId, Sprite.LIGHT_CHECK_BOX, gui.getMachine(),
checkBoxElement -> checkBoxElement.machineBase.getSlotConfiguration().getSlotDetails(checkBoxElement.slotID).autoOutput()).addPressAction((element, gui13, provider, mouseX, mouseY) -> {
popupElement.updateCheckBox((CheckBoxElement) element, "output", gui13);
return true;
}));
if (gui.getMachine() instanceof SlotConfiguration.SlotFilter) {
SlotConfiguration.SlotFilter slotFilter = (SlotConfiguration.SlotFilter) gui.getMachine();
if (Arrays.stream(slotFilter.getInputSlots()).anyMatch(value -> value == slotId)) {
elements.add(new CheckBoxElement(new TranslatableText("reborncore.gui.slotconfig.filter_input"), 0xFFFFFFFF, x - 26, y + 72, "filter", slotId, Sprite.LIGHT_CHECK_BOX, gui.getMachine(),
checkBoxElement -> checkBoxElement.machineBase.getSlotConfiguration().getSlotDetails(checkBoxElement.slotID).filter()).addPressAction((element, gui13, provider, mouseX, mouseY) -> {
popupElement.updateCheckBox((CheckBoxElement) element, "filter", gui13);
return true;
}));
filter = true;
popupElement.filter = true;
}
}
setWidth(85);
setHeight(105 + (filter ? 15 : 0));
}
@Override
public void draw(MatrixStack matrixStack, GuiBase<?> gui) {
super.draw(matrixStack, gui);
ItemStack stack = inventory.getStack(id);
int xPos = x + 1 + gui.getGuiLeft();
int yPos = y + 1 + gui.getGuiTop();
RenderSystem.enableDepthTest();
matrixStack.push();
RenderSystem.enableBlend();
RenderSystem.blendFunc(GlStateManager.SrcFactor.SRC_ALPHA, GlStateManager.DstFactor.ONE_MINUS_SRC_ALPHA);
ItemRenderer renderItem = MinecraftClient.getInstance().getItemRenderer();
renderItem.renderInGuiWithOverrides(stack, xPos, yPos);
renderItem.renderGuiItemOverlay(gui.getTextRenderer(), stack, xPos, yPos, null);
RenderSystem.disableDepthTest();
RenderSystem.disableLighting();
matrixStack.pop();
if (isHovering) {
drawSprite(matrixStack, gui, type.getButtonHoverOverlay(), x, y);
}
elements.forEach(elementBase -> elementBase.draw(matrixStack, gui));
}
public SlotType getType() {
return type;
}
public int getId() {
return id;
}
}

View file

@ -0,0 +1,348 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot.elements;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.render.item.ItemRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import reborncore.client.RenderUtil;
import reborncore.client.gui.builder.GuiBase;
import reborncore.client.gui.guibuilder.GuiBuilder;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import java.util.ArrayList;
import java.util.List;
public class ElementBase {
public int x;
public int y;
public boolean isHovering = false;
public boolean isDragging = false;
public boolean isPressing = false;
public boolean isReleasing = false;
public boolean startPressLast = false;
public boolean isHoveringLast = false;
public boolean isDraggingLast = false;
public boolean isPressingLast = false;
public boolean isReleasingLast = false;
public List<ElementBase.Action> hoverActions = new ArrayList<>();
public List<ElementBase.Action> dragActions = new ArrayList<>();
public List<ElementBase.Action> startPressActions = new ArrayList<>();
public List<ElementBase.Action> pressActions = new ArrayList<>();
public List<ElementBase.Action> releaseActions = new ArrayList<>();
public SpriteContainer container;
public List<UpdateAction> updateActions = new ArrayList<>();
public List<UpdateAction> buttonUpdate = new ArrayList<>();
private int width;
private int height;
public static final Identifier MECH_ELEMENTS = new Identifier("reborncore", "textures/gui/elements.png");
public ElementBase(int x, int y, SpriteContainer container) {
this.container = container;
this.x = x;
this.y = y;
}
public ElementBase(int x, int y, ISprite... sprites) {
this.container = new SpriteContainer();
for (ISprite sprite : sprites) {
container.addSprite(sprite);
}
this.x = x;
this.y = y;
}
public ElementBase(int x, int y, int width, int height) {
this.container = new SpriteContainer();
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public ElementBase(int x, int y, int width, int height, SpriteContainer container) {
this.container = container;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public ElementBase(int x, int y, int width, int height, ISprite... sprites) {
this.container = new SpriteContainer();
for (ISprite sprite : sprites) {
container.addSprite(sprite);
}
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public SpriteContainer getSpriteContainer() {
return container;
}
public void adjustDimensions(MachineBaseBlockEntity provider) {
if (container.offsetSprites != null) {
for (OffsetSprite offsetSprite : container.offsetSprites) {
if (offsetSprite.getSprite().getSprite(provider).width + offsetSprite.getOffsetX(provider) > this.width) {
this.width = offsetSprite.getSprite().getSprite(provider).width + offsetSprite.getOffsetX(provider);
}
if (offsetSprite.getSprite().getSprite(provider).height + offsetSprite.getOffsetY(provider) > this.height) {
this.height = offsetSprite.getSprite().getSprite(provider).height + offsetSprite.getOffsetY(provider);
}
}
}
}
public void draw(MatrixStack matrixStack, GuiBase<?> gui) {
for (OffsetSprite sprite : getSpriteContainer().offsetSprites) {
drawSprite(matrixStack, gui, sprite.getSprite(), x + sprite.getOffsetX(gui.getMachine()), y + sprite.getOffsetY(gui.getMachine()));
}
}
public void renderUpdate(GuiBase<?> gui) {
isHoveringLast = isHovering;
isPressingLast = isPressing;
isDraggingLast = isDragging;
isReleasingLast = isReleasing;
}
public void update(GuiBase<?> gui) {
for (UpdateAction action : updateActions) {
action.update(gui, this);
}
}
public ElementBase addUpdateAction(UpdateAction action) {
updateActions.add(action);
return this;
}
public ElementBase setWidth(int width) {
this.width = width;
return this;
}
public ElementBase setHeight(int height) {
this.height = height;
return this;
}
public int getX() {
return x;
}
public ElementBase setX(int x) {
this.x = x;
return this;
}
public int getY() {
return y;
}
public ElementBase setY(int y) {
this.y = y;
return this;
}
public int getWidth(MachineBaseBlockEntity provider) {
adjustDimensions(provider);
return width;
}
public int getHeight(MachineBaseBlockEntity provider) {
adjustDimensions(provider);
return height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public ElementBase addHoverAction(ElementBase.Action action) {
this.hoverActions.add(action);
return this;
}
public ElementBase addDragAction(ElementBase.Action action) {
this.dragActions.add(action);
return this;
}
public ElementBase addStartPressAction(ElementBase.Action action) {
this.startPressActions.add(action);
return this;
}
public ElementBase addPressAction(ElementBase.Action action) {
this.pressActions.add(action);
return this;
}
public ElementBase addReleaseAction(ElementBase.Action action) {
this.releaseActions.add(action);
return this;
}
public boolean onHover(MachineBaseBlockEntity provider, GuiBase<?> gui, double mouseX, double mouseY) {
for (ElementBase.Action action : hoverActions) {
action.execute(this, gui, provider, mouseX, mouseY);
}
return !hoverActions.isEmpty();
}
public boolean onDrag(MachineBaseBlockEntity provider, GuiBase<?> gui, double mouseX, double mouseY) {
for (ElementBase.Action action : dragActions) {
action.execute(this, gui, provider, mouseX, mouseY);
}
return !dragActions.isEmpty();
}
public boolean onStartPress(MachineBaseBlockEntity provider, GuiBase<?> gui, double mouseX, double mouseY) {
for (ElementBase.Action action : startPressActions) {
action.execute(this, gui, provider, mouseX, mouseY);
}
return !startPressActions.isEmpty();
}
public boolean onRelease(MachineBaseBlockEntity provider, GuiBase<?> gui, double mouseX, double mouseY) {
for (ElementBase.Action action : releaseActions) {
if (action.execute(this, gui, provider, mouseX, mouseY)) {
return true;
}
}
if (isPressing) {
for (ElementBase.Action action : pressActions) {
action.execute(this, gui, provider, mouseX, mouseY);
}
}
return !releaseActions.isEmpty() || !pressActions.isEmpty();
}
public interface Action {
boolean execute(ElementBase element, GuiBase<?> gui, MachineBaseBlockEntity provider, double mouseX, double mouseY);
}
public interface UpdateAction {
void update(GuiBase<?> gui, ElementBase element);
}
public void drawRect(GuiBase<?> gui, int x, int y, int width, int height, int colour) {
drawGradientRect(gui, x, y, width, height, colour, colour);
}
/*
Taken from Gui
*/
public void drawGradientRect(GuiBase<?> gui, int x, int y, int width, int height, int startColor, int endColor) {
x = adjustX(gui, x);
y = adjustY(gui, y);
int left = x;
int top = y;
int right = x + width;
int bottom = y + height;
RenderUtil.drawGradientRect(0, left, top, right, bottom, startColor, endColor);
}
public int adjustX(GuiBase<?> gui, int x) {
return gui.getGuiLeft() + x;
}
public int adjustY(GuiBase<?> gui, int y) {
return gui.getGuiTop() + y;
}
public boolean isInRect(GuiBase<?> gui, int x, int y, int xSize, int ySize, double mouseX, double mouseY) {
return gui.isPointInRect(x + gui.getGuiLeft(), y + gui.getGuiTop(), xSize, ySize, mouseX, mouseY);
}
public void drawText(MatrixStack matrixStack, GuiBase<?> gui, Text text, int x, int y, int color) {
x = adjustX(gui, x);
y = adjustY(gui, y);
gui.getTextRenderer().draw(matrixStack, text, x, y, color);
}
public void setTextureSheet(Identifier textureLocation) {
MinecraftClient.getInstance().getTextureManager().bindTexture(textureLocation);
}
public void drawSprite(MatrixStack matrixStack, GuiBase<?> gui, ISprite iSprite, int x, int y) {
Sprite sprite = iSprite.getSprite(gui.getMachine());
if (sprite != null) {
if (sprite.hasTextureInfo()) {
RenderSystem.color3f(1F, 1F, 1F);
setTextureSheet(sprite.textureLocation);
gui.drawTexture(matrixStack, x + gui.getGuiLeft(), y + gui.getGuiTop(), sprite.x, sprite.y, sprite.width, sprite.height);
}
if (sprite.hasStack()) {
RenderSystem.pushMatrix();
RenderSystem.enableBlend();
RenderSystem.blendFunc(GlStateManager.SrcFactor.SRC_ALPHA, GlStateManager.DstFactor.ONE_MINUS_SRC_ALPHA);
ItemRenderer itemRenderer = MinecraftClient.getInstance().getItemRenderer();
itemRenderer.renderInGuiWithOverrides(sprite.itemStack, x + gui.getGuiLeft(), y + gui.getGuiTop());
RenderSystem.disableLighting();
RenderSystem.popMatrix();
}
}
}
public int getScaledBurnTime(int scale, int burnTime, int totalBurnTime) {
return (int) (((float) burnTime / (float) totalBurnTime) * scale);
}
public int getPercentage(int MaxValue, int CurrentValue) {
if (CurrentValue == 0) {
return 0;
}
return (int) ((CurrentValue * 100.0f) / MaxValue);
}
public void drawDefaultBackground(MatrixStack matrixStack, Screen gui, int x, int y, int width, int height) {
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
MinecraftClient.getInstance().getTextureManager().bindTexture(GuiBuilder.defaultTextureSheet);
gui.drawTexture(matrixStack, x, y, 0, 0, width / 2, height / 2);
gui.drawTexture(matrixStack, x + width / 2, y, 150 - width / 2, 0, width / 2, height / 2);
gui.drawTexture(matrixStack, x, y + height / 2, 0, 150 - height / 2, width / 2, height / 2);
gui.drawTexture(matrixStack, x + width / 2, y + height / 2, 150 - width / 2, 150 - height / 2, width / 2, height / 2);
}
}

View file

@ -0,0 +1,213 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot.elements;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.block.BlockState;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.render.OverlayTexture;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.Tessellator;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.block.BlockRenderManager;
import net.minecraft.client.render.model.BakedModel;
import net.minecraft.client.texture.SpriteAtlasTexture;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.client.util.math.Vector3f;
import net.minecraft.network.Packet;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Quaternion;
import net.minecraft.world.World;
import reborncore.RebornCore;
import reborncore.client.gui.GuiUtil;
import reborncore.client.gui.builder.GuiBase;
import reborncore.common.blockentity.FluidConfiguration;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import reborncore.common.network.IdentifiedPacket;
import reborncore.common.network.NetworkManager;
import reborncore.common.network.ServerBoundPackets;
import reborncore.common.util.Color;
import reborncore.common.util.MachineFacing;
public class FluidConfigPopupElement extends ElementBase {
public boolean filter = false;
ConfigFluidElement fluidElement;
double lastMousex, lastMousey;
public FluidConfigPopupElement(int x, int y, ConfigFluidElement fluidElement) {
super(x, y, Sprite.SLOT_CONFIG_POPUP);
this.fluidElement = fluidElement;
}
@Override
public void draw(MatrixStack matrixStack, GuiBase<?> gui) {
drawDefaultBackground(matrixStack, gui, adjustX(gui, getX() - 8), adjustY(gui, getY() - 7), 84, 105 + (filter ? 15 : 0));
super.draw(matrixStack, gui);
MachineBaseBlockEntity machine = ((MachineBaseBlockEntity) gui.be);
World world = machine.getWorld();
BlockPos pos = machine.getPos();
BlockState state = world.getBlockState(pos);
BlockState actualState = state.getBlock().getDefaultState();
BlockRenderManager dispatcher = MinecraftClient.getInstance().getBlockRenderManager();
BakedModel model = dispatcher.getModels().getModel(state.getBlock().getDefaultState());
MinecraftClient.getInstance().getTextureManager().bindTexture(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE);
drawState(gui, world, model, actualState, pos, dispatcher, 4, 23, Vector3f.POSITIVE_Y.getDegreesQuaternion(90F)); //left
drawState(gui, world, model, actualState, pos, dispatcher, 23, 4, Vector3f.NEGATIVE_X.getDegreesQuaternion(90F)); //top
drawState(gui, world, model, actualState, pos, dispatcher, 23, 23, null); //centre
drawState(gui, world, model, actualState, pos, dispatcher, 23, 26, Vector3f.POSITIVE_X.getDegreesQuaternion(90F)); //bottom
drawState(gui, world, model, actualState, pos, dispatcher, 42, 23, Vector3f.POSITIVE_Y.getDegreesQuaternion(90F)); //right
drawState(gui, world, model, actualState, pos, dispatcher, 26, 42, Vector3f.POSITIVE_Y.getDegreesQuaternion(180F)); //back
drawSateColor(gui.getMachine(), MachineFacing.UP.getFacing(machine), 22, -1, gui);
drawSateColor(gui.getMachine(), MachineFacing.FRONT.getFacing(machine), 22, 18, gui);
drawSateColor(gui.getMachine(), MachineFacing.DOWN.getFacing(machine), 22, 37, gui);
drawSateColor(gui.getMachine(), MachineFacing.RIGHT.getFacing(machine), 41, 18, gui);
drawSateColor(gui.getMachine(), MachineFacing.BACK.getFacing(machine), 41, 37, gui);
drawSateColor(gui.getMachine(), MachineFacing.LEFT.getFacing(machine), 3, 18, gui);
}
@Override
public boolean onRelease(MachineBaseBlockEntity provider, GuiBase<?> gui, double mouseX, double mouseY) {
if (isInBox(23, 4, 16, 16, mouseX, mouseY, gui)) {
cyleConfig(MachineFacing.UP.getFacing(provider), gui);
} else if (isInBox(23, 23, 16, 16, mouseX, mouseY, gui)) {
cyleConfig(MachineFacing.FRONT.getFacing(provider), gui);
} else if (isInBox(42, 23, 16, 16, mouseX, mouseY, gui)) {
cyleConfig(MachineFacing.RIGHT.getFacing(provider), gui);
} else if (isInBox(4, 23, 16, 16, mouseX, mouseY, gui)) {
cyleConfig(MachineFacing.LEFT.getFacing(provider), gui);
} else if (isInBox(23, 42, 16, 16, mouseX, mouseY, gui)) {
cyleConfig(MachineFacing.DOWN.getFacing(provider), gui);
} else if (isInBox(42, 42, 16, 16, mouseX, mouseY, gui)) {
cyleConfig(MachineFacing.BACK.getFacing(provider), gui);
} else {
return false;
}
return true;
}
public void cyleConfig(Direction side, GuiBase<?> guiBase) {
FluidConfiguration.FluidConfig config = guiBase.getMachine().fluidConfiguration.getSideDetail(side);
FluidConfiguration.ExtractConfig fluidIO = config.getIoConfig().getNext();
FluidConfiguration.FluidConfig newConfig = new FluidConfiguration.FluidConfig(side, fluidIO);
IdentifiedPacket packetSave = ServerBoundPackets.createPacketFluidConfigSave(guiBase.be.getPos(), newConfig);
NetworkManager.sendToServer(packetSave);
}
public void updateCheckBox(CheckBoxElement checkBoxElement, String type, GuiBase<?> guiBase) {
FluidConfiguration configHolder = guiBase.getMachine().fluidConfiguration;
boolean input = configHolder.autoInput();
boolean output = configHolder.autoOutput();
if (type.equalsIgnoreCase("input")) {
input = !configHolder.autoInput();
}
if (type.equalsIgnoreCase("output")) {
output = !configHolder.autoOutput();
}
IdentifiedPacket packetFluidIOSave = ServerBoundPackets.createPacketFluidIOSave(guiBase.be.getPos(), input, output);
NetworkManager.sendToServer(packetFluidIOSave);
}
@Override
public boolean onHover(MachineBaseBlockEntity provider, GuiBase<?> gui, double mouseX, double mouseY) {
lastMousex = mouseX;
lastMousey = mouseY;
return super.onHover(provider, gui, mouseX, mouseY);
}
private void drawSateColor(MachineBaseBlockEntity machineBase, Direction side, int inx, int iny, GuiBase<?> gui) {
iny += 4;
int sx = inx + getX() + gui.getGuiLeft();
int sy = iny + getY() + gui.getGuiTop();
FluidConfiguration fluidConfiguration = machineBase.fluidConfiguration;
if (fluidConfiguration == null) {
RebornCore.LOGGER.debug("Humm, this isnt suppoed to happen");
return;
}
FluidConfiguration.FluidConfig fluidConfig = fluidConfiguration.getSideDetail(side);
Color color;
switch (fluidConfig.getIoConfig()) {
case NONE:
color = new Color(0, 0, 0, 0);
break;
case INPUT:
color = new Color(0, 0, 255, 128);
break;
case OUTPUT:
color = new Color(255, 69, 0, 128);
break;
case ALL:
color = new Color(52, 255, 30, 128);
break;
default:
color = new Color(0, 0, 0, 0);
break;
}
RenderSystem.color3f(255, 255, 255);
GuiUtil.drawGradientRect(sx, sy, 18, 18, color.getColor(), color.getColor());
RenderSystem.color3f(255, 255, 255);
}
private boolean isInBox(int rectX, int rectY, int rectWidth, int rectHeight, double pointX, double pointY, GuiBase<?> guiBase) {
rectX += getX();
rectY += getY();
return isInRect(guiBase, rectX, rectY, rectWidth, rectHeight, pointX, pointY);
//return (pointX - guiBase.getGuiLeft()) >= rectX - 1 && (pointX - guiBase.getGuiLeft()) < rectX + rectWidth + 1 && (pointY - guiBase.getGuiTop()) >= rectY - 1 && (pointY - guiBase.getGuiTop()) < rectY + rectHeight + 1;
}
public void drawState(GuiBase<?> gui,
World world,
BakedModel model,
BlockState actualState,
BlockPos pos,
BlockRenderManager dispatcher,
int x,
int y,
Quaternion quaternion) {
MatrixStack matrixStack = new MatrixStack();
matrixStack.push();
matrixStack.translate(8 + gui.getGuiLeft() + this.x + x, 8 + gui.getGuiTop() + this.y + y, 512);
matrixStack.scale(16F, 16F, 16F);
matrixStack.translate(0.5F, 0.5F, 0.5F);
matrixStack.scale(-1, -1, -1);
if (quaternion != null) {
matrixStack.multiply(quaternion);
}
VertexConsumerProvider.Immediate immediate = VertexConsumerProvider.immediate(Tessellator.getInstance().getBuffer());
dispatcher.getModelRenderer().render(matrixStack.peek(), immediate.getBuffer(RenderLayer.getSolid()), actualState, model, 1F, 1F, 1F, OverlayTexture.getU(15F), OverlayTexture.DEFAULT_UV);
immediate.draw();
matrixStack.pop();
}
}

View file

@ -0,0 +1,31 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot.elements;
import reborncore.common.blockentity.MachineBaseBlockEntity;
public interface ISprite {
Sprite getSprite(MachineBaseBlockEntity provider);
}

View file

@ -0,0 +1,69 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot.elements;
import reborncore.common.blockentity.MachineBaseBlockEntity;
public class OffsetSprite {
public ISprite sprite;
public int offsetX = 0;
public int offsetY = 0;
public OffsetSprite(ISprite sprite, int offsetX, int offsetY) {
this.sprite = sprite;
this.offsetX = offsetX;
this.offsetY = offsetY;
}
public OffsetSprite(ISprite sprite) {
this.sprite = sprite;
}
public OffsetSprite(Sprite sprite, MachineBaseBlockEntity provider) {
this.sprite = sprite;
}
public ISprite getSprite() {
return sprite;
}
public int getOffsetX(MachineBaseBlockEntity provider) {
return offsetX + sprite.getSprite(provider).offsetX;
}
public OffsetSprite setOffsetX(int offsetX) {
this.offsetX = offsetX;
return this;
}
public int getOffsetY(MachineBaseBlockEntity provider) {
return offsetY + sprite.getSprite(provider).offsetY;
}
public OffsetSprite setOffsetY(int offsetY) {
this.offsetY = offsetY;
return this;
}
}

View file

@ -0,0 +1,220 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot.elements;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.block.BlockState;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.render.OverlayTexture;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.Tessellator;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.block.BlockRenderManager;
import net.minecraft.client.render.model.BakedModel;
import net.minecraft.client.texture.SpriteAtlasTexture;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.client.util.math.Vector3f;
import net.minecraft.network.Packet;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Quaternion;
import net.minecraft.world.World;
import reborncore.RebornCore;
import reborncore.client.gui.GuiUtil;
import reborncore.client.gui.builder.GuiBase;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import reborncore.common.blockentity.SlotConfiguration;
import reborncore.common.network.IdentifiedPacket;
import reborncore.common.network.NetworkManager;
import reborncore.common.network.ServerBoundPackets;
import reborncore.common.util.Color;
import reborncore.common.util.MachineFacing;
public class SlotConfigPopupElement extends ElementBase {
int id;
public boolean filter = false;
ConfigSlotElement slotElement;
boolean allowInput = true;
public SlotConfigPopupElement(int slotId, int x, int y, ConfigSlotElement slotElement, boolean allowInput) {
super(x, y, Sprite.SLOT_CONFIG_POPUP);
this.id = slotId;
this.slotElement = slotElement;
this.allowInput = allowInput;
}
@Override
public void draw(MatrixStack matrixStack, GuiBase<?> gui) {
drawDefaultBackground(matrixStack, gui, adjustX(gui, getX() - 8), adjustY(gui, getY() - 7), 84, 105 + (filter ? 15 : 0));
super.draw(matrixStack, gui);
MachineBaseBlockEntity machine = ((MachineBaseBlockEntity) gui.be);
World world = machine.getWorld();
BlockPos pos = machine.getPos();
BlockState state = world.getBlockState(pos);
BlockState actualState = state.getBlock().getDefaultState();
BlockRenderManager dispatcher = MinecraftClient.getInstance().getBlockRenderManager();
BakedModel model = dispatcher.getModels().getModel(state.getBlock().getDefaultState());
MinecraftClient.getInstance().getTextureManager().bindTexture(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE);
drawState(gui, world, model, actualState, pos, dispatcher, 4, 23, Vector3f.POSITIVE_Y.getDegreesQuaternion(90F)); //left
drawState(gui, world, model, actualState, pos, dispatcher, 23, 4, Vector3f.NEGATIVE_X.getDegreesQuaternion(90F)); //top
drawState(gui, world, model, actualState, pos, dispatcher, 23, 23, null); //centre
drawState(gui, world, model, actualState, pos, dispatcher, 23, 26, Vector3f.POSITIVE_X.getDegreesQuaternion(90F)); //bottom
drawState(gui, world, model, actualState, pos, dispatcher, 42, 23, Vector3f.POSITIVE_Y.getDegreesQuaternion(90F)); //right
drawState(gui, world, model, actualState, pos, dispatcher, 26, 42, Vector3f.POSITIVE_Y.getDegreesQuaternion(180F)); //back
drawSlotSateColor(gui.getMachine(), MachineFacing.UP.getFacing(machine), id, 22, -1, gui);
drawSlotSateColor(gui.getMachine(), MachineFacing.FRONT.getFacing(machine), id, 22, 18, gui);
drawSlotSateColor(gui.getMachine(), MachineFacing.DOWN.getFacing(machine), id, 22, 37, gui);
drawSlotSateColor(gui.getMachine(), MachineFacing.RIGHT.getFacing(machine), id, 41, 18, gui);
drawSlotSateColor(gui.getMachine(), MachineFacing.BACK.getFacing(machine), id, 41, 37, gui);
drawSlotSateColor(gui.getMachine(), MachineFacing.LEFT.getFacing(machine), id, 3, 18, gui);
}
@Override
public boolean onRelease(MachineBaseBlockEntity provider, GuiBase<?> gui, double mouseX, double mouseY) {
if (isInBox(23, 4, 16, 16, mouseX, mouseY, gui)) {
cyleSlotConfig(MachineFacing.UP.getFacing(provider), gui);
} else if (isInBox(23, 23, 16, 16, mouseX, mouseY, gui)) {
cyleSlotConfig(MachineFacing.FRONT.getFacing(provider), gui);
} else if (isInBox(42, 23, 16, 16, mouseX, mouseY, gui)) {
cyleSlotConfig(MachineFacing.RIGHT.getFacing(provider), gui);
} else if (isInBox(4, 23, 16, 16, mouseX, mouseY, gui)) {
cyleSlotConfig(MachineFacing.LEFT.getFacing(provider), gui);
} else if (isInBox(23, 42, 16, 16, mouseX, mouseY, gui)) {
cyleSlotConfig(MachineFacing.DOWN.getFacing(provider), gui);
} else if (isInBox(42, 42, 16, 16, mouseX, mouseY, gui)) {
cyleSlotConfig(MachineFacing.BACK.getFacing(provider), gui);
} else {
return false;
}
return true;
}
public void cyleSlotConfig(Direction side, GuiBase<?> guiBase) {
SlotConfiguration.SlotConfig currentSlot = guiBase.getMachine().getSlotConfiguration().getSlotDetails(id).getSideDetail(side);
//Bit of a mess, in the future have a way to remove config options from this list
SlotConfiguration.ExtractConfig nextConfig = currentSlot.getSlotIO().getIoConfig().getNext();
if (!allowInput && nextConfig == SlotConfiguration.ExtractConfig.INPUT) {
nextConfig = SlotConfiguration.ExtractConfig.OUTPUT;
}
SlotConfiguration.SlotIO slotIO = new SlotConfiguration.SlotIO(nextConfig);
SlotConfiguration.SlotConfig newConfig = new SlotConfiguration.SlotConfig(side, slotIO, id);
IdentifiedPacket packetSlotSave = ServerBoundPackets.createPacketSlotSave(guiBase.be.getPos(), newConfig);
NetworkManager.sendToServer(packetSlotSave);
}
public void updateCheckBox(CheckBoxElement checkBoxElement, String type, GuiBase<?> guiBase) {
SlotConfiguration.SlotConfigHolder configHolder = guiBase.getMachine().getSlotConfiguration().getSlotDetails(id);
boolean input = configHolder.autoInput();
boolean output = configHolder.autoOutput();
boolean filter = configHolder.filter();
if (type.equalsIgnoreCase("input")) {
input = !configHolder.autoInput();
}
if (type.equalsIgnoreCase("output")) {
output = !configHolder.autoOutput();
}
if (type.equalsIgnoreCase("filter")) {
filter = !configHolder.filter();
}
IdentifiedPacket packetSlotSave = ServerBoundPackets.createPacketIOSave(guiBase.be.getPos(), id, input, output, filter);
NetworkManager.sendToServer(packetSlotSave);
}
private void drawSlotSateColor(MachineBaseBlockEntity machineBase, Direction side, int slotID, int inx, int iny, GuiBase<?> gui) {
iny += 4;
int sx = inx + getX() + gui.getGuiLeft();
int sy = iny + getY() + gui.getGuiTop();
SlotConfiguration.SlotConfigHolder slotConfigHolder = machineBase.getSlotConfiguration().getSlotDetails(slotID);
if (slotConfigHolder == null) {
RebornCore.LOGGER.debug("Humm, this isnt suppoed to happen");
return;
}
SlotConfiguration.SlotConfig slotConfig = slotConfigHolder.getSideDetail(side);
Color color;
switch (slotConfig.getSlotIO().getIoConfig()) {
case NONE:
color = new Color(0, 0, 0, 0);
break;
case INPUT:
color = new Color(0, 0, 255, 128);
break;
case OUTPUT:
color = new Color(255, 69, 0, 128);
break;
default:
color = new Color(0, 0, 0, 0);
break;
}
RenderSystem.color3f(255, 255, 255);
GuiUtil.drawGradientRect(sx, sy, 18, 18, color.getColor(), color.getColor());
RenderSystem.color3f(255, 255, 255);
}
private boolean isInBox(int rectX, int rectY, int rectWidth, int rectHeight, double pointX, double pointY, GuiBase<?> guiBase) {
rectX += getX();
rectY += getY();
return isInRect(guiBase, rectX, rectY, rectWidth, rectHeight, pointX, pointY);
//return (pointX - guiBase.getGuiLeft()) >= rectX - 1 && (pointX - guiBase.getGuiLeft()) < rectX + rectWidth + 1 && (pointY - guiBase.getGuiTop()) >= rectY - 1 && (pointY - guiBase.getGuiTop()) < rectY + rectHeight + 1;
}
public void drawState(GuiBase<?> gui,
World world,
BakedModel model,
BlockState actualState,
BlockPos pos,
BlockRenderManager dispatcher,
int x,
int y,
Quaternion quaternion) {
MatrixStack matrixStack = new MatrixStack();
matrixStack.push();
matrixStack.translate(8 + gui.getGuiLeft() + this.x + x, 8 + gui.getGuiTop() + this.y + y, 512);
matrixStack.scale(16F, 16F, 16F);
matrixStack.translate(0.5F, 0.5F, 0.5F);
matrixStack.scale(-1, -1, -1);
if (quaternion != null) {
matrixStack.multiply(quaternion);
}
VertexConsumerProvider.Immediate immediate = VertexConsumerProvider.immediate(Tessellator.getInstance().getBuffer());
dispatcher.getModelRenderer().render(matrixStack.peek(), immediate.getBuffer(RenderLayer.getSolid()), actualState, model, 1F, 1F, 1F, OverlayTexture.getU(15F), OverlayTexture.DEFAULT_UV);
immediate.draw();
matrixStack.pop();
}
public void drawState(GuiBase<?> gui, World world, BakedModel model, BlockState actualState, BlockPos pos, BlockRenderManager dispatcher, int x, int y) {
drawState(gui, world, model, actualState, pos, dispatcher, x, y, null);
}
}

View file

@ -0,0 +1,62 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot.elements;
import net.minecraft.inventory.Inventory;
public class SlotElement extends ElementBase {
protected Inventory slotInventory;
protected SlotType type;
int slotId, slotX, slotY;
public SlotElement(Inventory slotInventory, int slotId, int slotX, int slotY, SlotType type, int x, int y) {
super(x, y, type.getSprite());
this.type = type;
this.slotInventory = slotInventory;
this.slotId = slotId;
this.slotX = slotX;
this.slotY = slotY;
}
public SlotType getType() {
return type;
}
public Inventory getSlotInventory() {
return slotInventory;
}
public int getSlotId() {
return slotId;
}
public int getSlotX() {
return slotX;
}
public int getSlotY() {
return slotY;
}
}

View file

@ -0,0 +1,69 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot.elements;
public enum SlotType {
NORMAL(1, 1, Sprite.SLOT_NORMAL, Sprite.BUTTON_SLOT_NORMAL, Sprite.BUTTON_HOVER_OVERLAY_SLOT_NORMAL);
int slotOffsetX;
int slotOffsetY;
Sprite sprite;
Sprite buttonSprite;
Sprite buttonHoverOverlay;
SlotType(int slotOffsetX, int slotOffsetY, Sprite sprite, Sprite buttonSprite, Sprite buttonHoverOverlay) {
this.slotOffsetX = slotOffsetX;
this.slotOffsetY = slotOffsetY;
this.sprite = sprite;
this.buttonSprite = buttonSprite;
this.buttonHoverOverlay = buttonHoverOverlay;
}
SlotType(int slotOffset, Sprite sprite) {
this.slotOffsetX = slotOffset;
this.slotOffsetY = slotOffset;
this.sprite = sprite;
}
public int getSlotOffsetX() {
return slotOffsetX;
}
public int getSlotOffsetY() {
return slotOffsetY;
}
public Sprite getSprite() {
return sprite;
}
public Sprite getButtonSprite() {
return buttonSprite;
}
public Sprite getButtonHoverOverlay() {
return buttonHoverOverlay;
}
}

View file

@ -0,0 +1,169 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot.elements;
import net.minecraft.block.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.Identifier;
import reborncore.common.blockentity.MachineBaseBlockEntity;
public class Sprite implements ISprite {
public static final Sprite EMPTY = new Sprite(ElementBase.MECH_ELEMENTS, 0, 0, 0, 0);
public static final Sprite SLOT_NORMAL = new Sprite(ElementBase.MECH_ELEMENTS, 0, 0, 18, 18);
public static final Sprite CHARGE_SLOT_ICON = new Sprite(ElementBase.MECH_ELEMENTS, 18, 0, 18, 18);
public static final Sprite DISCHARGE_SLOT_ICON = new Sprite(ElementBase.MECH_ELEMENTS, 36, 0, 18, 18);
public static final Sprite ENERGY_BAR = new Sprite(ElementBase.MECH_ELEMENTS, 0, 18, 12, 40);
public static final Sprite ENERGY_BAR_BACKGROUND = new Sprite(ElementBase.MECH_ELEMENTS, 12, 18, 14, 42);
public static final Sprite TOP_ENERGY_BAR = new Sprite(ElementBase.MECH_ELEMENTS, 0, 215, 167, 2);
public static final Sprite TOP_ENERGY_BAR_BACKGROUND = new Sprite(ElementBase.MECH_ELEMENTS, 0, 217, 169, 3);
public static final Sprite LEFT_TAB = new Sprite(ElementBase.MECH_ELEMENTS, 0, 86, 23, 26);
public static final Sprite LEFT_TAB_SELECTED = new Sprite(ElementBase.MECH_ELEMENTS, 0, 60, 29, 26);
public static final Sprite CONFIGURE_ICON = new Sprite(ElementBase.MECH_ELEMENTS, 26, 18, 16, 16);
public static final Sprite REDSTONE_DISABLED_ICON = new Sprite(new ItemStack(Items.GUNPOWDER));
public static final Sprite REDSTONE_LOW_ICON = new Sprite(new ItemStack(Items.REDSTONE));
public static final Sprite REDSTONE_HIGH_ICON = new Sprite(new ItemStack(Blocks.REDSTONE_TORCH));
public static final Sprite UPGRADE_ICON = new Sprite(ElementBase.MECH_ELEMENTS, 26, 34, 16, 16);
public static final Sprite ENERGY_ICON = new Sprite(ElementBase.MECH_ELEMENTS, 46, 19, 9, 13);
public static final Sprite ENERGY_ICON_EMPTY = new Sprite(ElementBase.MECH_ELEMENTS, 62, 19, 9, 13);
public static final Sprite JEI_ICON = new Sprite(ElementBase.MECH_ELEMENTS, 42, 34, 16, 16);
public static final Sprite BUTTON_SLOT_NORMAL = new Sprite(ElementBase.MECH_ELEMENTS, 54, 0, 18, 18);
public static final Sprite FAKE_SLOT = new Sprite(ElementBase.MECH_ELEMENTS, 72, 0, 18, 18);
public static final Sprite BUTTON_HOVER_OVERLAY_SLOT_NORMAL = new Sprite(ElementBase.MECH_ELEMENTS, 90, 0, 18, 18);
public static final Sprite SLOT_CONFIG_POPUP = new Sprite(ElementBase.MECH_ELEMENTS, 29, 60, 62, 62);
public static final Sprite.Button EXIT_BUTTON = new Sprite.Button(new Sprite(ElementBase.MECH_ELEMENTS, 26, 122, 13, 13), new Sprite(ElementBase.MECH_ELEMENTS, 39, 122, 13, 13));
public static final Sprite.CheckBox DARK_CHECK_BOX = new Sprite.CheckBox(new Sprite(ElementBase.MECH_ELEMENTS, 74, 18, 13, 13), new Sprite(ElementBase.MECH_ELEMENTS, 87, 18, 16, 13));
public static final Sprite.CheckBox LIGHT_CHECK_BOX = new Sprite.CheckBox(new Sprite(ElementBase.MECH_ELEMENTS, 74, 31, 13, 13), new Sprite(ElementBase.MECH_ELEMENTS, 87, 31, 16, 13));
public final Identifier textureLocation;
public final int x;
public final int y;
public final int width;
public final int height;
public int offsetX = 0;
public int offsetY = 0;
public ItemStack itemStack;
public Sprite(Identifier textureLocation, int x, int y, int width, int height) {
this.textureLocation = textureLocation;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.itemStack = null;
}
public Sprite(ItemStack stack) {
this.textureLocation = null;
this.x = -1;
this.y = -1;
this.width = -1;
this.height = -1;
this.itemStack = stack;
}
public boolean hasStack() {
return itemStack != null;
}
public boolean hasTextureInfo() {
return x >= 0 && y >= 0 && width >= 0 && height >= 0;
}
public Sprite setOffsetX(int offsetX) {
this.offsetX = offsetX;
return this;
}
public Sprite setOffsetY(int offsetY) {
this.offsetY = offsetY;
return this;
}
@Override
public Sprite getSprite(MachineBaseBlockEntity provider) {
return this;
}
public static class Button {
private final Sprite normal;
private final Sprite hovered;
public Button(Sprite normal, Sprite hovered) {
this.normal = normal;
this.hovered = hovered;
}
public Sprite getNormal() {
return normal;
}
public Sprite getHovered() {
return hovered;
}
}
public static class ToggleButton {
private final Sprite normal;
private final Sprite hovered;
private final Sprite pressed;
public ToggleButton(Sprite normal, Sprite hovered, Sprite pressed) {
this.normal = normal;
this.hovered = hovered;
this.pressed = pressed;
}
public Sprite getNormal() {
return normal;
}
public Sprite getHovered() {
return hovered;
}
public Sprite getPressed() {
return pressed;
}
}
public static class CheckBox {
private final Sprite normal;
private final Sprite ticked;
public CheckBox(Sprite normal, Sprite ticked) {
this.normal = normal;
this.ticked = ticked;
}
public Sprite getNormal() {
return normal;
}
public Sprite getTicked() {
return ticked;
}
}
}

View file

@ -0,0 +1,78 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.slot.elements;
import java.util.ArrayList;
import java.util.List;
public class SpriteContainer {
public List<OffsetSprite> offsetSprites = new ArrayList<>();
public SpriteContainer setSprite(int index, OffsetSprite sprite) {
offsetSprites.set(index, sprite);
return this;
}
public SpriteContainer setSprite(int index, ISprite sprite, int offsetX, int offsetY) {
if (sprite instanceof Sprite) {
offsetSprites.set(index, new OffsetSprite(sprite).setOffsetX(((Sprite) sprite).offsetX + offsetX).setOffsetY(((Sprite) sprite).offsetY + offsetY));
} else {
offsetSprites.set(index, new OffsetSprite(sprite, offsetX, offsetY));
}
return this;
}
public SpriteContainer setSprite(int index, ISprite sprite) {
if (sprite instanceof Sprite) {
offsetSprites.set(index, new OffsetSprite(sprite).setOffsetX(((Sprite) sprite).offsetX).setOffsetY(((Sprite) sprite).offsetY));
} else {
offsetSprites.add(index, new OffsetSprite(sprite));
}
return this;
}
public SpriteContainer addSprite(OffsetSprite sprite) {
offsetSprites.add(sprite);
return this;
}
public SpriteContainer addSprite(ISprite sprite, int offsetX, int offsetY) {
if (sprite instanceof Sprite) {
offsetSprites.add(new OffsetSprite(sprite).setOffsetX(((Sprite) sprite).offsetX + offsetX).setOffsetY(((Sprite) sprite).offsetY + offsetY));
} else {
offsetSprites.add(new OffsetSprite(sprite, offsetX, offsetY));
}
return this;
}
public SpriteContainer addSprite(ISprite sprite) {
if (sprite instanceof Sprite) {
offsetSprites.add(new OffsetSprite(sprite).setOffsetX(((Sprite) sprite).offsetX).setOffsetY(((Sprite) sprite).offsetY));
} else {
offsetSprites.add(new OffsetSprite(sprite));
}
return this;
}
}

View file

@ -0,0 +1,56 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.widget;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.text.Text;
import org.apache.logging.log4j.util.TriConsumer;
public class GuiButtonExtended extends GuiButtonSimple {
private TriConsumer<GuiButtonExtended, Double, Double> clickHandler;
public GuiButtonExtended(int x, int y, Text buttonText, ButtonWidget.PressAction pressAction) {
super(x, y, 20, 200, buttonText, pressAction);
}
public GuiButtonExtended(int x, int y, int widthIn, int heightIn, Text buttonText, ButtonWidget.PressAction pressAction) {
super(x, y, widthIn, heightIn, buttonText, pressAction);
}
public GuiButtonExtended clickHandler(TriConsumer<GuiButtonExtended, Double, Double> consumer) {
clickHandler = consumer;
return this;
}
@Override
public void onClick(double mouseX, double mouseY) {
if (clickHandler != null) {
clickHandler.accept(this, mouseX, mouseY);
}
super.onClick(mouseY, mouseY);
}
}

View file

@ -0,0 +1,50 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.widget;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.LiteralText;
import reborncore.client.gui.builder.GuiBase;
/**
* Created by Prospector
*/
public class GuiButtonHologram extends GuiButtonExtended {
GuiBase.Layer layer;
GuiBase<?> gui;
public GuiButtonHologram(int x, int y, GuiBase<?> gui, GuiBase.Layer layer, ButtonWidget.PressAction pressAction) {
super(x, y, 20, 12, LiteralText.EMPTY, pressAction);
this.layer = layer;
this.gui = gui;
}
@Override
public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
}
}

View file

@ -0,0 +1,38 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.widget;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.text.Text;
public class GuiButtonSimple extends ButtonWidget {
public GuiButtonSimple(int x, int y, Text buttonText, ButtonWidget.PressAction pressAction) {
super(x, y, 20, 200, buttonText, pressAction);
}
public GuiButtonSimple(int x, int y, int widthIn, int heightIn, Text buttonText, ButtonWidget.PressAction pressAction) {
super(x, y, widthIn, heightIn, buttonText, pressAction);
}
}

View file

@ -0,0 +1,74 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.builder.widget;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.LiteralText;
import reborncore.client.gui.builder.GuiBase;
/**
* @author drcrazy
*/
public class GuiButtonUpDown extends GuiButtonExtended {
GuiBase<?> gui;
UpDownButtonType type;
public GuiButtonUpDown(int x, int y, GuiBase<?> gui, ButtonWidget.PressAction pressAction, UpDownButtonType type) {
super(x, y, 12, 12, LiteralText.EMPTY, pressAction);
this.gui = gui;
this.type = type;
}
@Override
public void renderButton(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
if (gui.hideGuiElements()) return;
gui.getMinecraft().getTextureManager().bindTexture(gui.builder.getResourceLocation());
switch (type) {
case FASTFORWARD:
gui.drawTexture(matrixStack, x, y, 174, 74, 12, 12);
break;
case FORWARD:
gui.drawTexture(matrixStack, x, y, 174, 86, 12, 12);
break;
case REWIND:
gui.drawTexture(matrixStack, x, y, 174, 98, 12, 12);
break;
case FASTREWIND:
gui.drawTexture(matrixStack, x, y, 174, 110, 12, 12);
break;
default:
break;
}
}
public enum UpDownButtonType {
FASTFORWARD,
FORWARD,
REWIND,
FASTREWIND
}
}

View file

@ -0,0 +1,61 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.componets;
public class BaseTextures {
//
// private static final ResourceLocation baseTexture = new ResourceLocation("reborncore", "textures/gui/base.png");
//
// public GuiTexture background;
// public GuiTexture slot;
// public GuiTexture burnBase;
// public GuiTexture burnOverlay;
// public GuiTexture powerBase;
// public GuiTexture powerOverlay;
// public GuiTexture progressBase;
// public GuiTexture progressOverlay;
// public GuiTexture tank;
// public GuiTexture tankBase;
// public GuiTexture tankScale;
// public GuiTexture powerBaseOld;
// public GuiTexture powerOverlayOld;
//
// public BaseTextures()
// {
// background = new GuiTexture(baseTexture, 176, 166, 0, 0);
// slot = new GuiTexture(baseTexture, 18, 18, 176, 31);
// burnBase = new GuiTexture(baseTexture, 14, 14, 176, 0);
// burnOverlay = new GuiTexture(baseTexture, 13, 13, 176, 50);
// powerBase = new GuiTexture(baseTexture, 7, 13, 190, 0);
// powerOverlay = new GuiTexture(baseTexture, 7, 13, 197, 0);
// progressBase = new GuiTexture(baseTexture, 22, 15, 200, 14);
// progressOverlay = new GuiTexture(baseTexture, 22, 16, 177, 14);
// tank = new GuiTexture(baseTexture, 20, 55, 176, 63);
// tankBase = new GuiTexture(baseTexture, 20, 55, 196, 63);
// tankScale = new GuiTexture(baseTexture, 20, 55, 216, 63);
// powerBaseOld = new GuiTexture(baseTexture, 32, 17, 224, 13);
// powerOverlayOld = new GuiTexture(baseTexture, 32, 17, 224, 30);
// }
}

View file

@ -0,0 +1,70 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.componets;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.Text;
import org.lwjgl.opengl.GL11;
public class GuiHiddenButton extends ButtonWidget {
public GuiHiddenButton(int xPosition, int yPosition, Text displayString) {
super(xPosition, yPosition, 0, 0, displayString, var1 -> {
});
}
public GuiHiddenButton(int id, int xPosition, int yPosition, int width, int height, Text displayString) {
super(xPosition, yPosition, width, height, displayString, var1 -> {
});
}
@Override
public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
if (this.visible) {
TextRenderer fontrenderer = MinecraftClient.getInstance().textRenderer;
MinecraftClient.getInstance().getTextureManager().bindTexture(WIDGETS_LOCATION);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.hovered = mouseX >= this.x && mouseY >= this.y
&& mouseX < this.x + this.width && mouseY < this.y + this.height;
GL11.glEnable(GL11.GL_BLEND);
RenderSystem.blendFuncSeparate(770, 771, 1, 0);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
int l = 14737632;
if (!this.active) {
l = 10526880;
} else if (this.isHovered()) {
l = 16777120;
}
this.drawTextWithShadow(matrixStack, fontrenderer, this.getMessage(), this.x + this.width / 2,
this.y + (this.height - 8) / 2, l);
}
}
}

View file

@ -0,0 +1,825 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.guibuilder;
import com.google.common.collect.Lists;
import com.mojang.blaze3d.systems.RenderSystem;
import net.fabricmc.fabric.api.client.render.fluid.v1.FluidRenderHandlerRegistry;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawableHelper;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.EntryListWidget;
import net.minecraft.client.render.BufferBuilder;
import net.minecraft.client.render.Tessellator;
import net.minecraft.client.render.VertexFormats;
import net.minecraft.client.texture.Sprite;
import net.minecraft.client.texture.SpriteAtlasTexture;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.fluid.Fluids;
import net.minecraft.item.ItemStack;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import reborncore.api.IListInfoProvider;
import reborncore.client.RenderUtil;
import reborncore.client.gui.builder.GuiBase;
import reborncore.client.gui.builder.slot.GuiTab;
import reborncore.common.fluid.FluidUtil;
import reborncore.common.fluid.FluidValue;
import reborncore.common.fluid.container.FluidInstance;
import reborncore.common.powerSystem.PowerSystem;
import reborncore.common.powerSystem.PowerSystem.EnergySystem;
import reborncore.common.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by Gigabit101 on 08/08/2016.
*/
public class GuiBuilder {
public static final Identifier defaultTextureSheet = new Identifier("reborncore", "textures/gui/guielements.png");
private static final Text SPACE_TEXT = new LiteralText(" ");
static Identifier resourceLocation;
public GuiBuilder() {
GuiBuilder.resourceLocation = defaultTextureSheet;
}
public GuiBuilder(Identifier resourceLocation) {
GuiBuilder.resourceLocation = resourceLocation;
}
public Identifier getResourceLocation() {
return resourceLocation;
}
public void drawDefaultBackground(MatrixStack matrixStack, Screen gui, int x, int y, int width, int height) {
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
MinecraftClient.getInstance().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, x, y, 0, 0, width / 2, height / 2);
gui.drawTexture(matrixStack, x + width / 2, y, 150 - width / 2, 0, width / 2, height / 2);
gui.drawTexture(matrixStack, x, y + height / 2, 0, 150 - height / 2, width / 2, height / 2);
gui.drawTexture(matrixStack, x + width / 2, y + height / 2, 150 - width / 2, 150 - height / 2, width / 2,
height / 2);
}
public void drawPlayerSlots(MatrixStack matrixStack, Screen gui, int posX, int posY, boolean center) {
MinecraftClient.getInstance().getTextureManager().bindTexture(resourceLocation);
if (center) {
posX -= 81;
}
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 9; x++) {
gui.drawTexture(matrixStack, posX + x * 18, posY + y * 18, 150, 0, 18, 18);
}
}
for (int x = 0; x < 9; x++) {
gui.drawTexture(matrixStack, posX + x * 18, posY + 58, 150, 0, 18, 18);
}
}
public void drawSlot(MatrixStack matrixStack, Screen gui, int posX, int posY) {
MinecraftClient.getInstance().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, posX, posY, 150, 0, 18, 18);
}
public void drawText(MatrixStack matrixStack, GuiBase<?> gui, Text text, int x, int y, int color) {
gui.getTextRenderer().draw(matrixStack, text, x, y, color);
}
public void drawProgressBar(MatrixStack matrixStack, GuiBase<?> gui, double progress, int x, int y) {
gui.getMinecraft().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, x, y, 150, 18, 22, 15);
int j = (int) (progress);
if (j > 0) {
gui.drawTexture(matrixStack, x, y, 150, 34, j + 1, 15);
}
}
public void drawOutputSlot(MatrixStack matrixStack, GuiBase<?> gui, int x, int y) {
gui.getMinecraft().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, x, y, 174, 0, 26, 26);
}
/**
* Draws button with JEI icon in the given coords.
*
* @param gui GuiBase GUI to draw on
* @param x int Top left corner where to place button
* @param y int Top left corner where to place button
* @param layer Layer Layer to draw on
*/
public void drawJEIButton(MatrixStack matrixStack, GuiBase<?> gui, int x, int y, GuiBase.Layer layer) {
if (gui.hideGuiElements()) return;
if (FabricLoader.getInstance().isModLoaded("jei")) {
if (layer == GuiBase.Layer.BACKGROUND) {
x += gui.getGuiLeft();
y += gui.getGuiTop();
}
gui.getMinecraft().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, x, y, 202, 0, 12, 12);
}
}
/**
* Draws lock button in either locked or unlocked state
*
* @param gui GuiBase GUI to draw on
* @param x int Top left corner where to place button
* @param y int Top left corner where to place button
* @param mouseX int Mouse cursor position to check for tooltip
* @param mouseY int Mouse cursor position to check for tooltip
* @param layer Layer Layer to draw on
* @param locked boolean Set to true if it is in locked state
*/
public void drawLockButton(MatrixStack matrixStack, GuiBase<?> gui, int x, int y, int mouseX, int mouseY, GuiBase.Layer layer, boolean locked) {
if (gui.hideGuiElements()) return;
if (layer == GuiBase.Layer.BACKGROUND) {
x += gui.getGuiLeft();
y += gui.getGuiTop();
}
gui.getMinecraft().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, x, y, 174, 26 + (locked ? 12 : 0), 20, 12);
if (gui.isPointInRect(x, y, 20, 12, mouseX, mouseY)) {
List<Text> list = new ArrayList<>();
if (locked) {
list.add(new TranslatableText("reborncore.gui.tooltip.unlock_items"));
} else {
list.add(new TranslatableText("reborncore.gui.tooltip.lock_items"));
}
RenderSystem.pushMatrix();
gui.renderTooltip(matrixStack, list, mouseX, mouseY);
RenderSystem.popMatrix();
}
}
/**
* Draws hologram toggle button
*
* @param gui GuiBase GUI to draw on
* @param x int Top left corner where to place button
* @param y int Top left corner where to place button
* @param mouseX int Mouse cursor position to check for tooltip
* @param mouseY int Mouse cursor position to check for tooltip
* @param layer Layer Layer to draw on
*/
public void drawHologramButton(MatrixStack matrixStack, GuiBase<?> gui, int x, int y, int mouseX, int mouseY, GuiBase.Layer layer) {
if (gui.isTabOpen()) return;
if (layer == GuiBase.Layer.BACKGROUND) {
x += gui.getGuiLeft();
y += gui.getGuiTop();
}
gui.getMinecraft().getTextureManager().bindTexture(resourceLocation);
if (gui.getMachine().renderMultiblock) {
gui.drawTexture(matrixStack, x, y, 174, 62, 20, 12);
} else {
gui.drawTexture(matrixStack, x, y, 174, 50, 20, 12);
}
if (gui.isPointInRect(x, y, 20, 12, mouseX, mouseY)) {
List<Text> list = new ArrayList<>();
list.add(new TranslatableText("reborncore.gui.tooltip.hologram"));
RenderSystem.pushMatrix();
if (layer == GuiBase.Layer.FOREGROUND) {
mouseX -= gui.getGuiLeft();
mouseY -= gui.getGuiTop();
}
gui.renderTooltip(matrixStack, list, mouseX, mouseY);
RenderSystem.popMatrix();
}
}
/**
* Draws big horizontal bar for heat value
*
* @param gui GuiBase GUI to draw on
* @param x int Top left corner where to place bar
* @param y int Top left corner where to place bar
* @param value int Current heat value
* @param max int Maximum heat value
* @param layer Layer Layer to draw on
*/
public void drawBigHeatBar(MatrixStack matrixStack, GuiBase<?> gui, int x, int y, int value, int max, GuiBase.Layer layer) {
if (gui.hideGuiElements()) return;
if (layer == GuiBase.Layer.BACKGROUND) {
x += gui.getGuiLeft();
y += gui.getGuiTop();
}
gui.getMinecraft().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, x, y, 26, 218, 114, 18);
if (value != 0) {
int j = (int) ((double) value / (double) max * 106);
if (j < 0) {
j = 0;
}
gui.drawTexture(matrixStack, x + 4, y + 4, 26, 246, j, 10);
Text text = new LiteralText(String.valueOf(value))
.append(new TranslatableText("reborncore.gui.heat"));
gui.drawCentredText(matrixStack, text, y + 5, 0xFFFFFF, layer);
}
}
/**
* Draws big horizontal blue bar
*
* @param gui GuiBase GUI to draw on
* @param x int Top left corner where to place bar
* @param y int Top left corner where to place bar
* @param value int Current value
* @param max int Maximum value
* @param mouseX int Mouse cursor position to check for tooltip
* @param mouseY int Mouse cursor position to check for tooltip
* @param suffix String String to put on the bar and tooltip after percentage value
* @param line2 String String to put into tooltip as a second line
* @param format String Formatted value to put on the bar
* @param layer Layer Layer to draw on
*/
public void drawBigBlueBar(MatrixStack matrixStack, GuiBase<?> gui, int x, int y, int value, int max, int mouseX, int mouseY, String suffix, Text line2, String format, GuiBase.Layer layer) {
if (gui.hideGuiElements()) return;
if (layer == GuiBase.Layer.BACKGROUND) {
x += gui.getGuiLeft();
y += gui.getGuiTop();
}
gui.getMinecraft().getTextureManager().bindTexture(resourceLocation);
int j = (int) ((double) value / (double) max * 106);
if (j < 0) {
j = 0;
}
gui.drawTexture(matrixStack, x + 4, y + 4, 0, 236, j, 10);
if (!suffix.equals("")) {
suffix = " " + suffix;
}
gui.drawCentredText(matrixStack, new LiteralText(format).append(suffix), y + 5, 0xFFFFFF, layer);
if (gui.isPointInRect(x, y, 114, 18, mouseX, mouseY)) {
int percentage = percentage(max, value);
List<Text> list = new ArrayList<>();
list.add(
new LiteralText(String.valueOf(value))
.formatted(Formatting.GOLD)
.append("/")
.append(String.valueOf(max))
.append(suffix)
);
list.add(
new LiteralText(String.valueOf(percentage))
.formatted(StringUtils.getPercentageColour(percentage))
.append("%")
.append(
new TranslatableText("reborncore.gui.tooltip.dsu_fullness")
.formatted(Formatting.GRAY)
)
);
list.add(line2);
if (value > max) {
list.add(
new LiteralText("Yo this is storing more than it should be able to")
.formatted(Formatting.GRAY)
);
list.add(
new LiteralText("prolly a bug")
.formatted(Formatting.GRAY)
);
list.add(
new LiteralText("pls report and tell how tf you did this")
.formatted(Formatting.GRAY)
);
}
if (layer == GuiBase.Layer.FOREGROUND) {
mouseX -= gui.getGuiLeft();
mouseY -= gui.getGuiTop();
}
gui.renderTooltip(matrixStack, list, mouseX, mouseY);
RenderSystem.disableLighting();
RenderSystem.color4f(1, 1, 1, 1);
}
}
public void drawBigBlueBar(MatrixStack matrixStack, GuiBase<?> gui, int x, int y, int value, int max, int mouseX, int mouseY, String suffix, GuiBase.Layer layer) {
drawBigBlueBar(matrixStack, gui, x, y, value, max, mouseX, mouseY, suffix, LiteralText.EMPTY, Integer.toString(value), layer);
}
public void drawBigBlueBar(MatrixStack matrixStack, GuiBase<?> gui, int x, int y, int value, int max, int mouseX, int mouseY, GuiBase.Layer layer) {
drawBigBlueBar(matrixStack, gui, x, y, value, max, mouseX, mouseY, "", LiteralText.EMPTY, "", layer);
}
/**
* Shades GUI and draw gray bar on top of GUI
*
* @param gui GuiBase GUI to draw on
* @param layer Layer Layer to draw on
*/
public void drawMultiblockMissingBar(MatrixStack matrixStack, GuiBase<?> gui, GuiBase.Layer layer) {
if (gui.hideGuiElements()) return;
int x = 0;
int y = 4;
if (layer == GuiBase.Layer.BACKGROUND) {
x += gui.getGuiLeft();
y += gui.getGuiTop();
}
RenderSystem.disableLighting();
RenderSystem.enableDepthTest();
RenderSystem.colorMask(true, true, true, false);
RenderUtil.drawGradientRect(0, x, y, x + 176, y + 20, 0x000000, 0xC0000000);
RenderUtil.drawGradientRect(0, x, y + 20, x + 176, y + 20 + 48, 0xC0000000, 0xC0000000);
RenderUtil.drawGradientRect(0, x, y + 68, x + 176, y + 70 + 20, 0xC0000000, 0x00000000);
RenderSystem.colorMask(true, true, true, true);
RenderSystem.disableDepthTest();
gui.drawCentredText(matrixStack, new TranslatableText("reborncore.gui.missingmultiblock"), 43, 0xFFFFFF, layer);
}
/**
* Draws upgrade slots on the left side of machine GUI. Draws on the background
* level.
*
* @param gui GuiBase GUI to draw on
* @param x int Top left corner where to place slots
* @param y int Top left corner where to place slots
*/
public void drawUpgrades(MatrixStack matrixStack, GuiBase<?> gui, int x, int y) {
gui.getMinecraft().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, x, y, 217, 0, 24, 81);
}
/**
* Draws tab on the left side of machine GUI. Draws on the background level.
*
* @param gui GuiBase GUI to draw on
* @param x int Top left corner where to place tab
* @param y int Top left corner where to place tab
* @param stack ItemStack Item to show as tab icon
*/
public void drawSlotTab(MatrixStack matrixStack, GuiBase<?> gui, int x, int y, ItemStack stack) {
gui.getMinecraft().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, x, y, 217, 82, 24, 24);
gui.getMinecraft().getItemRenderer().renderInGuiWithOverrides(stack, x + 5, y + 4);
}
/**
* Draws Slot Configuration tips instead of player inventory
*
* @param gui GuiBase GUI to draw on
* @param x int Top left corner where to place tips list
* @param y int Top left corner where to place tips list
* @param mouseX int Mouse cursor position
* @param mouseY int Mouse cursor position
*/
public void drawSlotConfigTips(MatrixStack matrixStack, GuiBase<?> gui, int x, int y, int mouseX, int mouseY, GuiTab guiTab) {
List<Text> tips = guiTab.getTips().stream()
.map(TranslatableText::new)
.collect(Collectors.toList());
TipsListWidget explanation = new TipsListWidget(gui, gui.getScreenWidth() - 14, 54, y, y + 76, 9 + 2, tips);
explanation.setLeftPos(x - 81);
explanation.render(matrixStack, mouseX, mouseY, 1.0f);
RenderSystem.color4f(1, 1, 1, 1);
}
private class TipsListWidget extends EntryListWidget<TipsListWidget.TipsListEntry> {
public TipsListWidget(GuiBase<?> gui, int width, int height, int top, int bottom, int entryHeight, List<Text> tips) {
super(gui.getMinecraft(), width, height, top, bottom, entryHeight);
for (Text tip : tips) {
this.addEntry(new TipsListEntry(tip));
}
}
@Override
public int getRowWidth() {
return 162;
}
@Override
protected void renderBackground(MatrixStack matrixStack) {
}
@Override
public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) {
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder bufferBuilder = tessellator.getBuffer();
this.client.getTextureManager().bindTexture(DrawableHelper.OPTIONS_BACKGROUND_TEXTURE);
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
bufferBuilder.begin(7, VertexFormats.POSITION_TEXTURE_COLOR);
bufferBuilder.vertex(this.left, this.bottom, 0.0D).texture((float) this.left / 32.0F, (float) (this.bottom + (int) this.getScrollAmount()) / 32.0F).color(32, 32, 32, 255).next();
bufferBuilder.vertex(this.right, this.bottom, 0.0D).texture((float) this.right / 32.0F, (float) (this.bottom + (int) this.getScrollAmount()) / 32.0F).color(32, 32, 32, 255).next();
bufferBuilder.vertex(this.right, this.top, 0.0D).texture((float) this.right / 32.0F, (float) (this.top + (int) this.getScrollAmount()) / 32.0F).color(32, 32, 32, 255).next();
bufferBuilder.vertex(this.left, this.top, 0.0D).texture((float) this.left / 32.0F, (float) (this.top + (int) this.getScrollAmount()) / 32.0F).color(32, 32, 32, 255).next();
tessellator.draw();
super.renderList(matrices, this.getRowLeft(), this.top, mouseX, mouseY, delta);
}
private class TipsListEntry extends EntryListWidget.Entry<TipsListWidget.TipsListEntry> {
private final Text tip;
public TipsListEntry(Text tip) {
this.tip = tip;
}
@Override
public void render(MatrixStack matrixStack, int index, int y, int x, int width, int height, int mouseX, int mouseY, boolean hovering, float delta) {
MinecraftClient.getInstance().textRenderer.drawTrimmed(tip, x, y, width, 11184810);
}
}
}
//TODO: change to double
/**
* Draws energy output value and icon
*
* @param gui GuiBase GUI to draw on
* @param x int Top left corner where to place energy output
* @param y int Top left corner where to place energy output
* @param maxOutput int Energy output value
* @param layer Layer Layer to draw on
*/
public void drawEnergyOutput(MatrixStack matrixStack, GuiBase<?> gui, int x, int y, int maxOutput, GuiBase.Layer layer) {
if (gui.hideGuiElements()) return;
Text text = new LiteralText(PowerSystem.getLocalizedPowerNoSuffix(maxOutput))
.append(SPACE_TEXT)
.append(PowerSystem.getDisplayPower().abbreviation)
.append("\t");
int width = gui.getTextRenderer().getWidth(text);
gui.drawText(matrixStack, text, x - width - 2, y + 5, 0, layer);
if (layer == GuiBase.Layer.BACKGROUND) {
x += gui.getGuiLeft();
y += gui.getGuiTop();
}
gui.getMinecraft().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, x, y, 150, 91, 16, 16);
}
/**
* Draws progress arrow in direction specified.
*
* @param gui GuiBase GUI to draw on
* @param progress int Current progress
* @param maxProgress int Maximum progress
* @param x int Top left corner where to place progress arrow
* @param y int Top left corner where to place progress arrow
* @param mouseX int Mouse cursor position to check for tooltip
* @param mouseY int Mouse cursor position to check for tooltip
* @param direction ProgressDirection Direction of progress arrow
* @param layer Layer Layer to draw on
*/
public void drawProgressBar(MatrixStack matrixStack, GuiBase<?> gui, int progress, int maxProgress, int x, int y, int mouseX, int mouseY, ProgressDirection direction, GuiBase.Layer layer) {
if (gui.hideGuiElements()) return;
if (layer == GuiBase.Layer.BACKGROUND) {
x += gui.getGuiLeft();
y += gui.getGuiTop();
}
gui.getMinecraft().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, x, y, direction.x, direction.y, direction.width, direction.height);
int j = (int) ((double) progress / (double) maxProgress * 16);
if (j < 0) {
j = 0;
}
switch (direction) {
case RIGHT:
gui.drawTexture(matrixStack, x, y, direction.xActive, direction.yActive, j, 10);
break;
case LEFT:
gui.drawTexture(matrixStack, x + 16 - j, y, direction.xActive + 16 - j, direction.yActive, j, 10);
break;
case UP:
gui.drawTexture(matrixStack, x, y + 16 - j, direction.xActive, direction.yActive + 16 - j, 10, j);
break;
case DOWN:
gui.drawTexture(matrixStack, x, y, direction.xActive, direction.yActive, 10, j);
break;
default:
return;
}
if (gui.isPointInRect(x, y, direction.width, direction.height, mouseX, mouseY)) {
int percentage = percentage(maxProgress, progress);
List<Text> list = new ArrayList<>();
list.add(
new LiteralText(String.valueOf(percentage))
.formatted(StringUtils.getPercentageColour(percentage))
.append("%")
);
if (layer == GuiBase.Layer.FOREGROUND) {
mouseX -= gui.getGuiLeft();
mouseY -= gui.getGuiTop();
}
gui.renderTooltip(matrixStack, list, mouseX, mouseY);
RenderSystem.disableLighting();
RenderSystem.color4f(1, 1, 1, 1);
}
}
/**
* Draws multi-energy bar
*
* @param gui GuiBase GUI to draw on
* @param x int Top left corner where to place energy bar
* @param y int Top left corner where to place energy bar
* @param energyStored int Current amount of energy
* @param maxEnergyStored int Maximum amount of energy
* @param mouseX int Mouse cursor position to check for tooltip
* @param mouseY int Mouse cursor position to check for tooltip
* @param buttonID int Button ID used to switch energy systems
* @param layer Layer Layer to draw on
*/
public void drawMultiEnergyBar(MatrixStack matrixStack, GuiBase<?> gui, int x, int y, int energyStored, int maxEnergyStored, int mouseX,
int mouseY, int buttonID, GuiBase.Layer layer) {
if (gui.hideGuiElements()) return;
if (layer == GuiBase.Layer.BACKGROUND) {
x += gui.getGuiLeft();
y += gui.getGuiTop();
}
EnergySystem displayPower = PowerSystem.getDisplayPower();
MinecraftClient.getInstance().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, x, y, displayPower.xBar - 15, displayPower.yBar - 1, 14, 50);
int draw = (int) ((double) energyStored / (double) maxEnergyStored * (48));
if (energyStored > maxEnergyStored) {
draw = 48;
}
gui.drawTexture(matrixStack, x + 1, y + 49 - draw, displayPower.xBar, 48 + displayPower.yBar - draw, 12, draw);
int percentage = percentage(maxEnergyStored, energyStored);
if (gui.isPointInRect(x + 1, y + 1, 11, 48, mouseX, mouseY)) {
List<Text> list = Lists.newArrayList();
if (Screen.hasShiftDown()) {
list.add(
new LiteralText(PowerSystem.getLocalizedPowerFullNoSuffix(energyStored))
.formatted(Formatting.GOLD)
.append("/")
.append(PowerSystem.getLocalizedPowerFull(maxEnergyStored))
);
} else {
list.add(
new LiteralText(PowerSystem.getLocalizedPowerNoSuffix(energyStored))
.formatted(Formatting.GOLD)
.append("/")
.append(PowerSystem.getLocalizedPower(maxEnergyStored))
);
}
list.add(
StringUtils.getPercentageText(percentage)
.append(SPACE_TEXT)
.append(
new TranslatableText("reborncore.gui.tooltip.power_charged")
.formatted(Formatting.GRAY)
)
);
if (gui.be instanceof IListInfoProvider) {
if (Screen.hasShiftDown()) {
((IListInfoProvider) gui.be).addInfo(list, true, true);
} else {
list.add(LiteralText.EMPTY);
list.add(
new LiteralText("Shift")
.formatted(Formatting.BLUE)
.append(SPACE_TEXT)
.formatted(Formatting.GRAY)
.append(new TranslatableText("reborncore.gui.tooltip.power_moreinfo"))
);
}
}
if (layer == GuiBase.Layer.FOREGROUND) {
mouseX -= gui.getGuiLeft();
mouseY -= gui.getGuiTop();
}
gui.renderTooltip(matrixStack, list, mouseX, mouseY);
RenderSystem.disableLighting();
RenderSystem.color4f(1, 1, 1, 1);
}
}
/**
* Draws tank and fluid inside it
*
* @param gui GuiBase GUI to draw on
* @param x int Top left corner of tank
* @param y int Top left corner of tank
* @param mouseX int Mouse cursor position to check for tooltip
* @param mouseY int Mouse cursor position to check for tooltip
* @param fluid FluidStack Fluid to draw in tank
* @param maxCapacity int Maximum tank capacity
* @param isTankEmpty boolean True if tank is empty
* @param layer Layer Layer to draw on
*/
public void drawTank(MatrixStack matrixStack, GuiBase<?> gui, int x, int y, int mouseX, int mouseY, FluidInstance fluid, FluidValue maxCapacity, boolean isTankEmpty, GuiBase.Layer layer) {
if (gui.hideGuiElements()) return;
if (layer == GuiBase.Layer.BACKGROUND) {
x += gui.getGuiLeft();
y += gui.getGuiTop();
}
int percentage = 0;
FluidValue amount = FluidValue.EMPTY;
if (!isTankEmpty) {
amount = fluid.getAmount();
percentage = percentage(maxCapacity.getRawValue(), amount.getRawValue());
}
gui.getMinecraft().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, x, y, 194, 26, 22, 56);
if (!isTankEmpty) {
drawFluid(matrixStack, gui, fluid, x + 4, y + 4, 14, 48, maxCapacity.getRawValue());
}
gui.drawTexture(matrixStack, x + 3, y + 3, 194, 82, 16, 50);
if (gui.isPointInRect(x, y, 22, 56, mouseX, mouseY)) {
List<Text> list = new ArrayList<>();
if (isTankEmpty) {
list.add(new TranslatableText("reborncore.gui.tooltip.tank_empty").formatted(Formatting.GOLD));
} else {
list.add(
new LiteralText(String.format("%s / %s", amount, maxCapacity))
.formatted(Formatting.GOLD)
.append(SPACE_TEXT)
.append(FluidUtil.getFluidName(fluid))
);
}
list.add(
StringUtils.getPercentageText(percentage)
.formatted(Formatting.GRAY)
.append(SPACE_TEXT)
.append(new TranslatableText("reborncore.gui.tooltip.tank_fullness"))
);
if (layer == GuiBase.Layer.FOREGROUND) {
mouseX -= gui.getGuiLeft();
mouseY -= gui.getGuiTop();
}
gui.renderTooltip(matrixStack, list, mouseX, mouseY);
RenderSystem.disableLighting();
RenderSystem.color4f(1, 1, 1, 1);
}
}
/**
* Draws fluid in tank
*
* @param gui GuiBase GUI to draw on
* @param fluid FluidStack Fluid to draw
* @param x int Top left corner of fluid
* @param y int Top left corner of fluid
* @param width int Width of fluid to draw
* @param height int Height of fluid to draw
* @param maxCapacity int Maximum capacity of tank
*/
public void drawFluid(MatrixStack matrixStack, GuiBase<?> gui, FluidInstance fluid, int x, int y, int width, int height, int maxCapacity) {
if (fluid.getFluid() == Fluids.EMPTY) {
return;
}
gui.getMinecraft().getTextureManager().bindTexture(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE);
y += height;
final Sprite sprite = FluidRenderHandlerRegistry.INSTANCE.get(fluid.getFluid()).getFluidSprites(gui.getMachine().getWorld(), gui.getMachine().getPos(), fluid.getFluid().getDefaultState())[0];
int color = FluidRenderHandlerRegistry.INSTANCE.get(fluid.getFluid()).getFluidColor(gui.getMachine().getWorld(), gui.getMachine().getPos(), fluid.getFluid().getDefaultState());
final int drawHeight = (int) (fluid.getAmount().getRawValue() / (maxCapacity * 1F) * height);
final int iconHeight = sprite.getHeight();
int offsetHeight = drawHeight;
RenderSystem.color3f((color >> 16 & 255) / 255.0F, (float) (color >> 8 & 255) / 255.0F, (float) (color & 255) / 255.0F);
int iteration = 0;
while (offsetHeight != 0) {
final int curHeight = offsetHeight < iconHeight ? offsetHeight : iconHeight;
DrawableHelper.drawSprite(matrixStack, x, y - offsetHeight, 0, width, curHeight, sprite);
offsetHeight -= curHeight;
iteration++;
if (iteration > 50) {
break;
}
}
RenderSystem.color3f(1F, 1F, 1F);
gui.getMinecraft().getTextureManager().bindTexture(resourceLocation);
}
/**
* Draws burning progress, similar to vanilla furnace
*
* @param gui GuiBase GUI to draw on
* @param progress int Current progress
* @param maxProgress int Maximum progress
* @param x int Top left corner where to place burn bar
* @param y int Top left corner where to place burn bar
* @param mouseX int Mouse cursor position to check for tooltip
* @param mouseY int Mouse cursor position to check for tooltip
* @param layer Layer Layer to draw on
*/
public void drawBurnBar(MatrixStack matrixStack, GuiBase<?> gui, int progress, int maxProgress, int x, int y, int mouseX, int mouseY, GuiBase.Layer layer) {
if (gui.hideGuiElements()) return;
if (layer == GuiBase.Layer.BACKGROUND) {
x += gui.getGuiLeft();
y += gui.getGuiTop();
}
gui.getMinecraft().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, x, y, 150, 64, 13, 13);
int j = 13 - (int) ((double) progress / (double) maxProgress * 13);
if (j > 0) {
gui.drawTexture(matrixStack, x, y + j, 150, 51 + j, 13, 13 - j);
}
if (gui.isPointInRect(x, y, 12, 12, mouseX, mouseY)) {
int percentage = percentage(maxProgress, progress);
List<Text> list = new ArrayList<>();
list.add(StringUtils.getPercentageText(percentage));
if (layer == GuiBase.Layer.FOREGROUND) {
mouseX -= gui.getGuiLeft();
mouseY -= gui.getGuiTop();
}
gui.renderTooltip(matrixStack, list, mouseX, mouseY);
RenderSystem.disableLighting();
RenderSystem.color4f(1, 1, 1, 1);
}
}
/**
* Draws bar containing output slots
*
* @param gui GuiBase GUI to draw on
* @param x int Top left corner where to place slots bar
* @param y int Top left corner where to place slots bar
* @param count int Number of output slots
*/
public void drawOutputSlotBar(MatrixStack matrixStack, GuiBase<?> gui, int x, int y, int count) {
MinecraftClient.getInstance().getTextureManager().bindTexture(resourceLocation);
gui.drawTexture(matrixStack, x, y, 150, 122, 3, 26);
x += 3;
for (int i = 1; i <= count; i++) {
gui.drawTexture(matrixStack, x, y, 150 + 3, 122, 20, 26);
x += 20;
}
gui.drawTexture(matrixStack, x, y, 150 + 23, 122, 3, 26);
}
protected int percentage(int MaxValue, int CurrentValue) {
if (CurrentValue == 0) {
return 0;
}
return (int) ((CurrentValue * 100.0f) / MaxValue);
}
public enum ProgressDirection {
RIGHT(58, 150, 74, 150, 16, 10),
LEFT(74, 160, 58, 160, 16, 10),
DOWN(78, 170, 88, 170, 10, 16),
UP(58, 170, 68, 170, 10, 16);
public int x;
public int y;
public int xActive;
public int yActive;
public int width;
public int height;
ProgressDirection(int x, int y, int xActive, int yActive, int width, int height) {
this.x = x;
this.y = y;
this.xActive = xActive;
this.yActive = yActive;
this.width = width;
this.height = height;
}
}
}

View file

@ -0,0 +1,66 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.slots;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.screen.slot.Slot;
import reborncore.mixin.common.AccessorSlot;
import java.util.function.Predicate;
/**
* Created by modmuss50 on 11/04/2016.
*/
public class BaseSlot extends Slot {
private Predicate<ItemStack> filter = (stack) -> true;
public BaseSlot(Inventory inventoryIn, int index, int xPosition, int yPosition) {
super(inventoryIn, index, xPosition, yPosition);
}
public BaseSlot(Inventory inventoryIn, int index, int xPosition, int yPosition, Predicate<ItemStack> filter) {
super(inventoryIn, index, xPosition, yPosition);
this.filter = filter;
}
public boolean canWorldBlockRemove() {
return true;
}
@Override
public boolean canInsert(ItemStack stack) {
return filter.test(stack);
}
public boolean canWorldBlockInsert() {
return true;
}
public int getSlotID() {
return ((AccessorSlot) this).getIndex();
}
}

View file

@ -0,0 +1,48 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.slots;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import team.reborn.energy.Energy;
/**
* Created by Rushmead
*/
public class SlotCharge extends BaseSlot {
public SlotCharge(Inventory inventoryIn, int index, int xPosition, int yPosition) {
super(inventoryIn, index, xPosition, yPosition);
}
@Override
public boolean canInsert(ItemStack stack) {
return Energy.valid(stack);
}
@Override
public boolean canWorldBlockRemove() {
return false;
}
}

View file

@ -0,0 +1,68 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.slots;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
public class SlotFake extends BaseSlot {
public boolean mCanInsertItem;
public boolean mCanStackItem;
public int mMaxStacksize = 127;
public SlotFake(Inventory itemHandler, int par2, int par3, int par4, boolean aCanInsertItem,
boolean aCanStackItem, int aMaxStacksize) {
super(itemHandler, par2, par3, par4);
this.mCanInsertItem = aCanInsertItem;
this.mCanStackItem = aCanStackItem;
this.mMaxStacksize = aMaxStacksize;
}
@Override
public boolean canInsert(ItemStack par1ItemStack) {
return this.mCanInsertItem;
}
@Override
public int getMaxItemCount() {
return this.mMaxStacksize;
}
@Override
public boolean hasStack() {
return false;
}
@Override
public ItemStack takeStack(int par1) {
return !this.mCanStackItem ? ItemStack.EMPTY : super.takeStack(par1);
}
@Override
public boolean canWorldBlockRemove() {
return false;
}
}

View file

@ -0,0 +1,63 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.slots;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import java.util.ArrayList;
import java.util.List;
public class SlotFilteredVoid extends BaseSlot {
private final List<ItemStack> filter = new ArrayList<ItemStack>();
public SlotFilteredVoid(Inventory itemHandler, int id, int x, int y) {
super(itemHandler, id, x, y);
}
public SlotFilteredVoid(Inventory itemHandler, int id, int x, int y, ItemStack[] filterList) {
super(itemHandler, id, x, y);
for (ItemStack itemStack : filterList) {
this.filter.add(itemStack);
}
}
@Override
public boolean canInsert(ItemStack stack) {
for (ItemStack itemStack : filter) {
if (itemStack.getItem().equals(stack.getItem())) {
return false;
}
}
return super.canInsert(stack);
}
@Override
public void setStack(ItemStack arg0) {
}
}

View file

@ -0,0 +1,42 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.slots;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import reborncore.common.fluid.FluidUtil;
public class SlotFluid extends BaseSlot {
public SlotFluid(Inventory p_i1824_1_, int p_i1824_2_, int p_i1824_3_, int p_i1824_4_) {
super(p_i1824_1_, p_i1824_2_, p_i1824_3_, p_i1824_4_);
}
@Override
public boolean canInsert(ItemStack stack) {
return FluidUtil.getFluidHandler(stack) != null;
}
}

View file

@ -0,0 +1,50 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.slots;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
public class SlotInput extends BaseSlot {
public SlotInput(Inventory itemHandler, int par2, int par3, int par4) {
super(itemHandler, par2, par3, par4);
}
@Override
public boolean canInsert(ItemStack par1ItemStack) {
return true;
}
@Override
public int getMaxItemCount() {
return 64;
}
@Override
public boolean canWorldBlockRemove() {
return false;
}
}

View file

@ -0,0 +1,55 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.slots;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
public class SlotOutput extends BaseSlot {
public SlotOutput(Inventory itemHandler, int par2, int par3, int par4) {
super(itemHandler, par2, par3, par4);
}
@Override
public boolean canInsert(ItemStack par1ItemStack) {
return false;
}
@Override
public int getMaxItemCount() {
return 64;
}
@Override
public boolean canWorldBlockRemove() {
return true;
}
@Override
public boolean canWorldBlockInsert() {
return false;
}
}

View file

@ -0,0 +1,65 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* This class was created by <Vazkii>. It's distributed as
* part of the Botania Mod. Get the Source Code in github:
* https://github.com/Vazkii/Botania
* <p>
* Botania is Open Source and distributed under the
* Botania License: http://botaniamod.net/license.php
*/
package reborncore.client.multiblock;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos;
public class MultiblockComponent {
public BlockPos relPos;
public final BlockState state;
public MultiblockComponent(BlockPos relPos, BlockState state) {
this.relPos = relPos;
this.state = state;
}
public BlockPos getRelativePosition() {
return relPos;
}
public Block getBlock() {
return state.getBlock();
}
public BlockState getState() {
return state;
}
public MultiblockComponent copy() {
return new MultiblockComponent(relPos, state);
}
}

View file

@ -0,0 +1,46 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.multiblock;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.block.entity.BlockEntityRenderDispatcher;
import net.minecraft.client.render.block.entity.BlockEntityRenderer;
import net.minecraft.client.util.math.MatrixStack;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import reborncore.common.blockentity.MultiblockWriter;
public class MultiblockRenderer<T extends MachineBaseBlockEntity> extends BlockEntityRenderer<T> {
public MultiblockRenderer(BlockEntityRenderDispatcher blockEntityRenderDispatcher) {
super(blockEntityRenderDispatcher);
}
@Override
public void render(T blockEntity, float partialTicks, MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int light, int overlay) {
if (blockEntity.renderMultiblock) {
blockEntity.writeMultiblock(new MultiblockWriter.HologramRenderer(blockEntity.getWorld(), matrixStack, vertexConsumerProvider, 0.4F).rotate(blockEntity.getFacing().getOpposite()));
}
}
}

View file

@ -0,0 +1,32 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.screen;
import net.minecraft.entity.player.PlayerEntity;
import reborncore.client.screen.builder.BuiltScreenHandler;
public interface BuiltScreenHandlerProvider {
BuiltScreenHandler createScreenHandler(int syncID, PlayerEntity player);
}

View file

@ -0,0 +1,206 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.screen.builder;
import com.mojang.serialization.Codec;
import com.mojang.serialization.DataResult;
import net.minecraft.block.entity.AbstractFurnaceBlockEntity;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.inventory.CraftingInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtOps;
import net.minecraft.nbt.Tag;
import org.apache.commons.lang3.Range;
import org.apache.commons.lang3.tuple.Pair;
import reborncore.RebornCore;
import reborncore.api.blockentity.IUpgrade;
import reborncore.api.blockentity.IUpgradeable;
import reborncore.api.recipe.IRecipeCrafterProvider;
import reborncore.client.gui.slots.BaseSlot;
import reborncore.client.gui.slots.SlotFake;
import reborncore.client.gui.slots.SlotOutput;
import reborncore.client.screen.builder.slot.FilteredSlot;
import reborncore.client.screen.builder.slot.UpgradeSlot;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import reborncore.common.fluid.container.ItemFluidInfo;
import reborncore.common.powerSystem.PowerAcceptorBlockEntity;
import team.reborn.energy.Energy;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class BlockEntityScreenHandlerBuilder {
private final Inventory inventory;
private final BlockEntity blockEntity;
private final ScreenHandlerBuilder parent;
private final int rangeStart;
BlockEntityScreenHandlerBuilder(final ScreenHandlerBuilder parent, final BlockEntity blockEntity) {
if (blockEntity instanceof Inventory) {
this.inventory = (Inventory) blockEntity;
} else {
throw new RuntimeException(blockEntity.getClass().getName() + " is not an inventory");
}
this.blockEntity = blockEntity;
this.parent = parent;
this.rangeStart = parent.slots.size();
if (inventory instanceof IUpgradeable) {
upgradeSlots((IUpgradeable) inventory);
}
if (blockEntity instanceof MachineBaseBlockEntity) {
sync(((MachineBaseBlockEntity) blockEntity).getRedstoneConfiguration());
}
}
public BlockEntityScreenHandlerBuilder slot(final int index, final int x, final int y) {
this.parent.slots.add(new BaseSlot(this.inventory, index, x, y));
return this;
}
public BlockEntityScreenHandlerBuilder slot(final int index, final int x, final int y, Predicate<ItemStack> filter) {
this.parent.slots.add(new BaseSlot(this.inventory, index, x, y, filter));
return this;
}
public BlockEntityScreenHandlerBuilder outputSlot(final int index, final int x, final int y) {
this.parent.slots.add(new SlotOutput(this.inventory, index, x, y));
return this;
}
public BlockEntityScreenHandlerBuilder fakeSlot(final int index, final int x, final int y) {
this.parent.slots.add(new SlotFake(this.inventory, index, x, y, false, false, Integer.MAX_VALUE));
return this;
}
public BlockEntityScreenHandlerBuilder filterSlot(final int index, final int x, final int y,
final Predicate<ItemStack> filter) {
this.parent.slots.add(new FilteredSlot(this.inventory, index, x, y).setFilter(filter));
return this;
}
public BlockEntityScreenHandlerBuilder energySlot(final int index, final int x, final int y) {
this.parent.slots.add(new FilteredSlot(this.inventory, index, x, y)
.setFilter(Energy::valid));
return this;
}
public BlockEntityScreenHandlerBuilder fluidSlot(final int index, final int x, final int y) {
this.parent.slots.add(new FilteredSlot(this.inventory, index, x, y).setFilter(
stack -> stack.getItem() instanceof ItemFluidInfo));
return this;
}
public BlockEntityScreenHandlerBuilder fuelSlot(final int index, final int x, final int y) {
this.parent.slots.add(new FilteredSlot(this.inventory, index, x, y).setFilter(AbstractFurnaceBlockEntity::canUseAsFuel));
return this;
}
@Deprecated
public BlockEntityScreenHandlerBuilder upgradeSlot(final int index, final int x, final int y) {
this.parent.slots.add(new FilteredSlot(this.inventory, index, x, y)
.setFilter(stack -> stack.getItem() instanceof IUpgrade));
return this;
}
private BlockEntityScreenHandlerBuilder upgradeSlots(IUpgradeable upgradeable) {
if (upgradeable.canBeUpgraded()) {
for (int i = 0; i < upgradeable.getUpgradeSlotCount(); i++) {
this.parent.slots.add(new UpgradeSlot(upgradeable.getUpgradeInvetory(), i, -18, i * 18 + 12));
}
}
return this;
}
/**
* @param supplier The supplier it can supply a variable holding in an Object it
* will be synced with a custom packet
* @param setter The setter to call when the variable has been updated.
* @return ContainerTileInventoryBuilder Inventory which will do the sync
*/
public <T> BlockEntityScreenHandlerBuilder sync(final Supplier<T> supplier, final Consumer<T> setter) {
this.parent.objectValues.add(Pair.of(supplier, setter));
return this;
}
public BlockEntityScreenHandlerBuilder sync(Syncable syncable) {
syncable.getSyncPair(this.parent.objectValues);
return this;
}
public <T> BlockEntityScreenHandlerBuilder sync(Codec<T> codec) {
return sync(() -> {
DataResult<Tag> dataResult = codec.encodeStart(NbtOps.INSTANCE, (T) blockEntity);
if (dataResult.error().isPresent()) {
throw new RuntimeException("Failed to encode: " + dataResult.error().get().message() + " " + blockEntity);
} else {
return (CompoundTag) dataResult.result().get();
}
}, compoundTag -> {
DataResult<T> dataResult = codec.parse(NbtOps.INSTANCE, compoundTag);
if (dataResult.error().isPresent()) {
throw new RuntimeException("Failed to encode: " + dataResult.error().get().message() + " " + blockEntity);
}
});
}
public BlockEntityScreenHandlerBuilder syncEnergyValue() {
if (this.blockEntity instanceof PowerAcceptorBlockEntity) {
PowerAcceptorBlockEntity powerAcceptor = ((PowerAcceptorBlockEntity) this.blockEntity);
return this.sync(powerAcceptor::getEnergy, powerAcceptor::setEnergy)
.sync(powerAcceptor::getExtraPowerStorage, powerAcceptor::setExtraPowerStorage)
.sync(powerAcceptor::getPowerChange, powerAcceptor::setPowerChange);
}
RebornCore.LOGGER.error(this.inventory + " is not an instance of TilePowerAcceptor! Energy cannot be synced.");
return this;
}
public BlockEntityScreenHandlerBuilder syncCrafterValue() {
if (this.blockEntity instanceof IRecipeCrafterProvider) {
IRecipeCrafterProvider recipeCrafter = ((IRecipeCrafterProvider) this.blockEntity);
return this
.sync(() -> recipeCrafter.getRecipeCrafter().currentTickTime, (time) -> recipeCrafter.getRecipeCrafter().currentTickTime = time)
.sync(() -> recipeCrafter.getRecipeCrafter().currentNeededTicks, (ticks) -> recipeCrafter.getRecipeCrafter().currentNeededTicks = ticks);
}
RebornCore.LOGGER.error(this.inventory + " is not an instance of IRecipeCrafterProvider! Craft progress cannot be synced.");
return this;
}
public BlockEntityScreenHandlerBuilder onCraft(final Consumer<CraftingInventory> onCraft) {
this.parent.craftEvents.add(onCraft);
return this;
}
public ScreenHandlerBuilder addInventory() {
this.parent.blockEntityInventoryRanges.add(Range.between(this.rangeStart, this.parent.slots.size() - 1));
return this.parent;
}
}

View file

@ -0,0 +1,373 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.screen.builder;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.CraftingInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.screen.ScreenHandlerListener;
import net.minecraft.screen.ScreenHandlerType;
import net.minecraft.screen.slot.Slot;
import net.minecraft.util.math.BlockPos;
import org.apache.commons.lang3.Range;
import org.apache.commons.lang3.tuple.MutableTriple;
import org.apache.commons.lang3.tuple.Pair;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import reborncore.common.util.ItemUtils;
import reborncore.mixin.common.AccessorScreenHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.function.*;
public class BuiltScreenHandler extends ScreenHandler implements ExtendedScreenHandlerListener {
private final String name;
private final Predicate<PlayerEntity> canInteract;
private final List<Range<Integer>> playerSlotRanges;
private final List<Range<Integer>> blockEntitySlotRanges;
private final ArrayList<MutableTriple<IntSupplier, IntConsumer, Short>> shortValues;
private final ArrayList<MutableTriple<IntSupplier, IntConsumer, Integer>> integerValues;
private final ArrayList<MutableTriple<Supplier, Consumer, Object>> objectValues;
private List<Consumer<CraftingInventory>> craftEvents;
private Integer[] integerParts;
private final MachineBaseBlockEntity blockEntity;
public BuiltScreenHandler(int syncID, final String name, final Predicate<PlayerEntity> canInteract,
final List<Range<Integer>> playerSlotRange,
final List<Range<Integer>> blockEntitySlotRange, MachineBaseBlockEntity blockEntity) {
super(null, syncID);
this.name = name;
this.canInteract = canInteract;
this.playerSlotRanges = playerSlotRange;
this.blockEntitySlotRanges = blockEntitySlotRange;
this.shortValues = new ArrayList<>();
this.integerValues = new ArrayList<>();
this.objectValues = new ArrayList<>();
this.blockEntity = blockEntity;
}
public void addShortSync(final List<Pair<IntSupplier, IntConsumer>> syncables) {
for (final Pair<IntSupplier, IntConsumer> syncable : syncables) {
this.shortValues.add(MutableTriple.of(syncable.getLeft(), syncable.getRight(), (short) 0));
}
this.shortValues.trimToSize();
}
public void addIntegerSync(final List<Pair<IntSupplier, IntConsumer>> syncables) {
for (final Pair<IntSupplier, IntConsumer> syncable : syncables) {
this.integerValues.add(MutableTriple.of(syncable.getLeft(), syncable.getRight(), 0));
}
this.integerValues.trimToSize();
this.integerParts = new Integer[this.integerValues.size()];
}
public void addObjectSync(final List<Pair<Supplier, Consumer>> syncables) {
for (final Pair<Supplier, Consumer> syncable : syncables) {
this.objectValues.add(MutableTriple.of(syncable.getLeft(), syncable.getRight(), null));
}
this.objectValues.trimToSize();
}
public void addCraftEvents(final List<Consumer<CraftingInventory>> craftEvents) {
this.craftEvents = craftEvents;
}
@Override
public boolean canUse(final PlayerEntity playerIn) {
return this.canInteract.test(playerIn);
}
@Override
public final void onContentChanged(final Inventory inv) {
if (!this.craftEvents.isEmpty()) {
this.craftEvents.forEach(consumer -> consumer.accept((CraftingInventory) inv));
}
}
@Override
public void sendContentUpdates() {
super.sendContentUpdates();
for (final ScreenHandlerListener listener : ((AccessorScreenHandler) (this)).getListeners()) {
int i = 0;
if (!this.shortValues.isEmpty()) {
for (final MutableTriple<IntSupplier, IntConsumer, Short> value : this.shortValues) {
final short supplied = (short) value.getLeft().getAsInt();
if (supplied != value.getRight()) {
listener.onPropertyUpdate(this, i, supplied);
value.setRight(supplied);
}
i++;
}
}
if (!this.integerValues.isEmpty()) {
for (final MutableTriple<IntSupplier, IntConsumer, Integer> value : this.integerValues) {
final int supplied = value.getLeft().getAsInt();
if (supplied != value.getRight()) {
listener.onPropertyUpdate(this, i, supplied >> 16);
listener.onPropertyUpdate(this, i + 1, (short) (supplied & 0xFFFF));
value.setRight(supplied);
}
i += 2;
}
}
if (!this.objectValues.isEmpty()) {
int objects = 0;
for (final MutableTriple<Supplier, Consumer, Object> value : this.objectValues) {
final Object supplied = value.getLeft().get();
if (supplied != value.getRight()) {
sendObject(listener, this, objects, supplied);
value.setRight(supplied);
}
objects++;
}
}
}
}
@Override
public void addListener(final ScreenHandlerListener listener) {
super.addListener(listener);
int i = 0;
if (!this.shortValues.isEmpty()) {
for (final MutableTriple<IntSupplier, IntConsumer, Short> value : this.shortValues) {
final short supplied = (short) value.getLeft().getAsInt();
listener.onPropertyUpdate(this, i, supplied);
value.setRight(supplied);
i++;
}
}
if (!this.integerValues.isEmpty()) {
for (final MutableTriple<IntSupplier, IntConsumer, Integer> value : this.integerValues) {
final int supplied = value.getLeft().getAsInt();
listener.onPropertyUpdate(this, i, supplied >> 16);
listener.onPropertyUpdate(this, i + 1, (short) (supplied & 0xFFFF));
value.setRight(supplied);
i += 2;
}
}
if (!this.objectValues.isEmpty()) {
int objects = 0;
for (final MutableTriple<Supplier, Consumer, Object> value : this.objectValues) {
final Object supplied = value.getLeft();
sendObject(listener, this, objects, ((Supplier) supplied).get());
value.setRight(supplied);
objects++;
}
}
}
@Override
public void handleObject(int var, Object value) {
this.objectValues.get(var).getMiddle().accept(value);
}
@Override
public void setProperty(int id, int value) {
if (id < this.shortValues.size()) {
this.shortValues.get(id).getMiddle().accept((short) value);
this.shortValues.get(id).setRight((short) value);
} else if (id - this.shortValues.size() < this.integerValues.size() * 2) {
if ((id - this.shortValues.size()) % 2 == 0) {
this.integerParts[(id - this.shortValues.size()) / 2] = value;
} else {
this.integerValues.get((id - this.shortValues.size()) / 2).getMiddle().accept(
(this.integerParts[(id - this.shortValues.size()) / 2] & 0xFFFF) << 16 | value & 0xFFFF);
}
}
}
@Override
public ItemStack transferSlot(final PlayerEntity player, final int index) {
ItemStack originalStack = ItemStack.EMPTY;
final Slot slot = this.slots.get(index);
if (slot != null && slot.hasStack()) {
final ItemStack stackInSlot = slot.getStack();
originalStack = stackInSlot.copy();
boolean shifted = false;
for (final Range<Integer> range : this.playerSlotRanges) {
if (range.contains(index)) {
if (this.shiftToBlockEntity(stackInSlot)) {
shifted = true;
}
break;
}
}
if (!shifted) {
for (final Range<Integer> range : this.blockEntitySlotRanges) {
if (range.contains(index)) {
if (this.shiftToPlayer(stackInSlot)) {
shifted = true;
}
break;
}
}
}
slot.onStackChanged(stackInSlot, originalStack);
if (stackInSlot.getCount() <= 0) {
slot.setStack(ItemStack.EMPTY);
} else {
slot.markDirty();
}
if (stackInSlot.getCount() == originalStack.getCount()) {
return ItemStack.EMPTY;
}
slot.onTakeItem(player, stackInSlot);
}
return originalStack;
}
protected boolean shiftItemStack(final ItemStack stackToShift, final int start, final int end) {
if (stackToShift.isEmpty()) {
return false;
}
int inCount = stackToShift.getCount();
// First lets see if we have the same item in a slot to merge with
for (int slotIndex = start; stackToShift.getCount() > 0 && slotIndex < end; slotIndex++) {
final Slot slot = this.slots.get(slotIndex);
final ItemStack stackInSlot = slot.getStack();
int maxCount = Math.min(stackToShift.getMaxCount(), slot.getMaxItemCount());
if (!stackToShift.isEmpty() && slot.canInsert(stackToShift)) {
if (ItemUtils.isItemEqual(stackInSlot, stackToShift, true, false)) {
// Got 2 stacks that need merging
int freeStackSpace = maxCount - stackInSlot.getCount();
if (freeStackSpace > 0) {
int transferAmount = Math.min(freeStackSpace, stackToShift.getCount());
stackInSlot.increment(transferAmount);
stackToShift.decrement(transferAmount);
}
}
}
}
// If not lets go find the next free slot to insert our remaining stack
for (int slotIndex = start; stackToShift.getCount() > 0 && slotIndex < end; slotIndex++) {
final Slot slot = this.slots.get(slotIndex);
final ItemStack stackInSlot = slot.getStack();
if (stackInSlot.isEmpty() && slot.canInsert(stackToShift)) {
int maxCount = Math.min(stackToShift.getMaxCount(), slot.getMaxItemCount());
int moveCount = Math.min(maxCount, stackToShift.getCount());
ItemStack moveStack = stackToShift.copy();
moveStack.setCount(moveCount);
slot.setStack(moveStack);
stackToShift.decrement(moveCount);
}
}
//If we moved some, but still have more left over lets try again
if (!stackToShift.isEmpty() && stackToShift.getCount() != inCount) {
shiftItemStack(stackToShift, start, end);
}
return stackToShift.getCount() != inCount;
}
private boolean shiftToBlockEntity(final ItemStack stackToShift) {
if (!blockEntity.getOptionalInventory().isPresent()) {
return false;
}
for (final Range<Integer> range : this.blockEntitySlotRanges) {
if (this.shiftItemStack(stackToShift, range.getMinimum(), range.getMaximum() + 1)) {
return true;
}
}
return false;
}
private boolean shiftToPlayer(final ItemStack stackToShift) {
for (final Range<Integer> range : this.playerSlotRanges) {
if (this.shiftItemStack(stackToShift, range.getMinimum(), range.getMaximum() + 1)) {
return true;
}
}
return false;
}
public String getName() {
return this.name;
}
@Override
public Slot addSlot(Slot slotIn) {
return super.addSlot(slotIn);
}
public MachineBaseBlockEntity getBlockEntity() {
return blockEntity;
}
public BlockPos getPos() {
return getBlockEntity().getPos();
}
ScreenHandlerType<BuiltScreenHandler> type = null;
public void setType(ScreenHandlerType<BuiltScreenHandler> type) {
this.type = type;
}
@Override
public ScreenHandlerType<BuiltScreenHandler> getType() {
return type;
}
}

View file

@ -0,0 +1,44 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.screen.builder;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.screen.ScreenHandlerListener;
import net.minecraft.server.network.ServerPlayerEntity;
import reborncore.common.network.ClientBoundPackets;
import reborncore.common.network.NetworkManager;
public interface ExtendedScreenHandlerListener {
default void sendObject(ScreenHandlerListener screenHandlerListener, ScreenHandler screenHandler, int var, Object value) {
if (screenHandlerListener instanceof ServerPlayerEntity) {
NetworkManager.sendToPlayer(ClientBoundPackets.createPacketSendObject(var, value, screenHandler), (ServerPlayerEntity) screenHandlerListener);
}
}
default void handleObject(int var, Object value) {
}
}

View file

@ -0,0 +1,142 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.screen.builder;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.ArmorItem;
import net.minecraft.util.Identifier;
import org.apache.commons.lang3.Range;
import reborncore.client.IconSupplier;
import reborncore.client.screen.builder.slot.PlayerInventorySlot;
import reborncore.client.screen.builder.slot.SpriteSlot;
public final class PlayerScreenHandlerBuilder {
private final PlayerInventory player;
private final ScreenHandlerBuilder parent;
private Range<Integer> main;
private Range<Integer> hotbar;
private Range<Integer> armor;
PlayerScreenHandlerBuilder(final ScreenHandlerBuilder parent, final PlayerInventory player) {
this.player = player;
this.parent = parent;
}
public PlayerScreenHandlerBuilder inventory(final int xStart, final int yStart) {
final int startIndex = this.parent.slots.size();
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 9; ++j) {
this.parent.slots.add(new PlayerInventorySlot(this.player, j + i * 9 + 9, xStart + j * 18, yStart + i * 18));
}
}
this.main = Range.between(startIndex, this.parent.slots.size() - 1);
return this;
}
public PlayerScreenHandlerBuilder hotbar(final int xStart, final int yStart) {
final int startIndex = this.parent.slots.size();
for (int i = 0; i < 9; ++i) {
this.parent.slots.add(new PlayerInventorySlot(this.player, i, xStart + i * 18, yStart));
}
this.hotbar = Range.between(startIndex, this.parent.slots.size() - 1);
return this;
}
public PlayerScreenHandlerBuilder inventory() {
return this.inventory(8, 94);
}
public PlayerScreenHandlerBuilder hotbar() {
return this.hotbar(8, 152);
}
public PlayerArmorScreenHandlerBuilder armor() {
return new PlayerArmorScreenHandlerBuilder(this);
}
public ScreenHandlerBuilder addInventory() {
if (this.hotbar != null) {
this.parent.addPlayerInventoryRange(this.hotbar);
}
if (this.main != null) {
this.parent.addPlayerInventoryRange(this.main);
}
if (this.armor != null) {
this.parent.addBlockEnityInventoryRange(this.armor);
}
return this.parent;
}
public static final class PlayerArmorScreenHandlerBuilder {
private final PlayerScreenHandlerBuilder parent;
private final int startIndex;
public PlayerArmorScreenHandlerBuilder(final PlayerScreenHandlerBuilder parent) {
this.parent = parent;
this.startIndex = parent.parent.slots.size();
}
private PlayerArmorScreenHandlerBuilder armor(final int index, final int xStart, final int yStart,
final EquipmentSlot slotType, final Identifier sprite) {
this.parent.parent.slots.add(new SpriteSlot(this.parent.player, index, xStart, yStart, sprite, 1)
.setFilter(stack -> {
if (stack.getItem() instanceof ArmorItem) {
return ((ArmorItem) stack.getItem()).getSlotType() == slotType;
}
return false;
}));
return this;
}
public PlayerArmorScreenHandlerBuilder helmet(final int xStart, final int yStart) {
return this.armor(this.parent.player.size() - 2, xStart, yStart, EquipmentSlot.HEAD, IconSupplier.armour_head_id);
}
public PlayerArmorScreenHandlerBuilder chestplate(final int xStart, final int yStart) {
return this.armor(this.parent.player.size() - 3, xStart, yStart, EquipmentSlot.CHEST, IconSupplier.armour_chest_id);
}
public PlayerArmorScreenHandlerBuilder leggings(final int xStart, final int yStart) {
return this.armor(this.parent.player.size() - 4, xStart, yStart, EquipmentSlot.LEGS, IconSupplier.armour_legs_id);
}
public PlayerArmorScreenHandlerBuilder boots(final int xStart, final int yStart) {
return this.armor(this.parent.player.size() - 5, xStart, yStart, EquipmentSlot.FEET, IconSupplier.armour_feet_id);
}
public PlayerArmorScreenHandlerBuilder complete(final int xStart, final int yStart) {
return this.helmet(xStart, yStart).chestplate(xStart, yStart + 18).leggings(xStart, yStart + 18 + 18)
.boots(xStart, yStart + 18 + 18 + 18);
}
public PlayerScreenHandlerBuilder addArmor() {
this.parent.armor = Range.between(this.startIndex - 1, this.parent.parent.slots.size() - 2);
return this.parent;
}
}
}

View file

@ -0,0 +1,103 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.screen.builder;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.CraftingInventory;
import net.minecraft.screen.slot.Slot;
import net.minecraft.util.math.Vec3d;
import org.apache.commons.lang3.Range;
import org.apache.commons.lang3.tuple.Pair;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class ScreenHandlerBuilder {
private final String name;
final List<Slot> slots;
final List<Range<Integer>> playerInventoryRanges, blockEntityInventoryRanges;
final List<Pair<Supplier, Consumer>> objectValues;
final List<Consumer<CraftingInventory>> craftEvents;
public ScreenHandlerBuilder(final String name) {
this.name = name;
this.slots = new ArrayList<>();
this.playerInventoryRanges = new ArrayList<>();
this.blockEntityInventoryRanges = new ArrayList<>();
this.objectValues = new ArrayList<>();
this.craftEvents = new ArrayList<>();
}
public PlayerScreenHandlerBuilder player(final PlayerInventory player) {
return new PlayerScreenHandlerBuilder(this, player);
}
public BlockEntityScreenHandlerBuilder blockEntity(final BlockEntity blockEntity) {
return new BlockEntityScreenHandlerBuilder(this, blockEntity);
}
void addPlayerInventoryRange(final Range<Integer> range) {
this.playerInventoryRanges.add(range);
}
void addBlockEnityInventoryRange(final Range<Integer> range) {
this.blockEntityInventoryRanges.add(range);
}
private Predicate<PlayerEntity> isUsable(MachineBaseBlockEntity blockEntity) {
return playerEntity -> blockEntity.getWorld().getBlockEntity(blockEntity.getPos()) == blockEntity
&& playerEntity.getPos().distanceTo(Vec3d.of(blockEntity.getPos())) < 16;
}
public BuiltScreenHandler create(final MachineBaseBlockEntity blockEntity, int syncID) {
final BuiltScreenHandler built = new BuiltScreenHandler(syncID, this.name, isUsable(blockEntity),
this.playerInventoryRanges,
this.blockEntityInventoryRanges, blockEntity);
if (!this.objectValues.isEmpty())
built.addObjectSync(objectValues);
if (!this.craftEvents.isEmpty()) {
built.addCraftEvents(this.craftEvents);
}
this.slots.forEach(built::addSlot);
this.slots.clear();
return built;
}
}

View file

@ -0,0 +1,37 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.screen.builder;
import org.apache.commons.lang3.tuple.Pair;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
public interface Syncable {
void getSyncPair(List<Pair<Supplier, Consumer>> pairList);
}

View file

@ -0,0 +1,65 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.screen.builder.slot;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import reborncore.client.gui.slots.BaseSlot;
import java.util.function.Predicate;
public class FilteredSlot extends BaseSlot {
private Predicate<ItemStack> filter;
private int stackLimit = 64;
public FilteredSlot(final Inventory inventory, final int index, final int xPosition, final int yPosition) {
super(inventory, index, xPosition, yPosition);
}
public FilteredSlot(final Inventory inventory, final int index, final int xPosition, final int yPosition, int stackLimit) {
super(inventory, index, xPosition, yPosition);
this.stackLimit = stackLimit;
}
public FilteredSlot setFilter(final Predicate<ItemStack> filter) {
this.filter = filter;
return this;
}
@Override
public boolean canInsert(final ItemStack stack) {
try {
return this.filter.test(stack);
} catch (NullPointerException e) {
return true;
}
}
@Override
public int getMaxItemCount() {
return stackLimit;
}
}

View file

@ -0,0 +1,46 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.screen.builder.slot;
import net.minecraft.inventory.Inventory;
import net.minecraft.screen.slot.Slot;
/**
* Created by drcrazy on 31-Dec-19 for TechReborn-1.15.
*/
public class PlayerInventorySlot extends Slot {
public boolean doDraw;
public PlayerInventorySlot(Inventory inventory, int index, int xPosition, int yPosition) {
super(inventory, index, xPosition, yPosition);
this.doDraw = true;
}
@Override
public boolean doDrawHoveringEffect() {
return doDraw;
}
}

View file

@ -0,0 +1,62 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.screen.builder.slot;
import com.mojang.datafixers.util.Pair;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.texture.SpriteAtlasTexture;
import net.minecraft.inventory.Inventory;
import net.minecraft.util.Identifier;
import org.jetbrains.annotations.Nullable;
public class SpriteSlot extends FilteredSlot {
private final Identifier spriteName;
int stacksize;
public SpriteSlot(final Inventory inventory, final int index, final int xPosition, final int yPosition, final Identifier sprite, final int stacksize) {
super(inventory, index, xPosition, yPosition);
this.spriteName = sprite;
this.stacksize = stacksize;
}
public SpriteSlot(final Inventory inventory, final int index, final int xPosition, final int yPosition, final Identifier sprite) {
this(inventory, index, xPosition, yPosition, sprite, 64);
}
@Override
public int getMaxItemCount() {
return this.stacksize;
}
@Override
@Nullable
@Environment(EnvType.CLIENT)
public Pair<Identifier, Identifier> getBackgroundSprite() {
return Pair.of(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, spriteName);
}
}

View file

@ -0,0 +1,60 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.screen.builder.slot;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.item.ItemStack;
import reborncore.api.blockentity.IUpgrade;
import reborncore.api.blockentity.IUpgradeable;
import reborncore.client.gui.slots.BaseSlot;
import reborncore.common.util.RebornInventory;
public class UpgradeSlot extends BaseSlot {
public UpgradeSlot(final net.minecraft.inventory.Inventory inventory, final int index, final int xPosition, final int yPosition) {
super(inventory, index, xPosition, yPosition);
}
@Override
public boolean canInsert(final ItemStack stack) {
if (!(stack.getItem() instanceof IUpgrade)) {
return false;
}
IUpgrade upgrade = (IUpgrade) stack.getItem();
IUpgradeable upgradeable = null;
RebornInventory inv = (RebornInventory) inventory;
BlockEntity blockEntity = inv.getBlockEntity();
if (blockEntity instanceof IUpgradeable) {
upgradeable = (IUpgradeable) blockEntity;
}
return upgrade.isValidForInventory(upgradeable, stack) && (upgradeable == null || upgradeable.isUpgradeValid(upgrade, stack));
}
@Override
public int getMaxItemCount() {
return 1;
}
}

View file

@ -0,0 +1,96 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.texture;
import net.minecraft.client.texture.AbstractTexture;
import net.minecraft.client.texture.NativeImage;
import net.minecraft.client.texture.TextureUtil;
import net.minecraft.resource.Resource;
import net.minecraft.resource.ResourceManager;
import net.minecraft.resource.metadata.ResourceMetadataReader;
import net.minecraft.util.Identifier;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by modmuss50 on 23/05/2016.
*/
public class InputStreamTexture extends AbstractTexture {
protected final InputStream textureLocation;
NativeImage image;
String name;
public InputStreamTexture(InputStream textureResourceLocation, String name) {
this.textureLocation = textureResourceLocation;
this.name = name;
}
@Override
public void load(ResourceManager resourceManager) throws IOException {
this.clearGlId();
if (image == null) {
Resource iresource = null;
try {
iresource = new Resource() {
@Override
public Identifier getId() {
return new Identifier("reborncore:loaded/" + name);
}
@Override
public InputStream getInputStream() {
return textureLocation;
}
@Nullable
@Override
public <T> T getMetadata(ResourceMetadataReader<T> iMetadataSectionSerializer) {
return null;
}
@Override
public String getResourcePackName() {
return "reborncore";
}
@Override
public void close() {
}
};
image = NativeImage.read(iresource.getInputStream());
} finally {
IOUtils.closeQuietly(iresource);
}
}
this.bindTexture();
TextureUtil.allocate(this.getGlId(), 0, image.getWidth(), image.getHeight());
image.upload(0, 0, 0, true);
}
}

View file

@ -0,0 +1,38 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.common;
import net.minecraft.block.Block;
public abstract class BaseBlock extends Block {
public BaseBlock(Settings builder) {
super(builder);
}
public int getRenderType() {
return 3;
}
}

View file

@ -0,0 +1,86 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.common;
import net.minecraft.block.Block;
import net.minecraft.block.BlockEntityProvider;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.util.collection.DefaultedList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import java.util.Optional;
public abstract class BaseBlockEntityProvider extends Block implements BlockEntityProvider {
protected BaseBlockEntityProvider(Settings builder) {
super(builder);
}
public Optional<ItemStack> getDropWithContents(World world, BlockPos pos, ItemStack stack) {
BlockEntity blockEntity = world.getBlockEntity(pos);
if (blockEntity == null) {
return Optional.empty();
}
ItemStack newStack = stack.copy();
CompoundTag blockEntityData = blockEntity.toTag(new CompoundTag());
stripLocationData(blockEntityData);
if (!newStack.hasTag()) {
newStack.setTag(new CompoundTag());
}
newStack.getTag().put("blockEntity_data", blockEntityData);
return Optional.of(newStack);
}
@Override
public void onPlaced(World worldIn, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {
if (stack.hasTag() && stack.getTag().contains("blockEntity_data")) {
BlockEntity blockEntity = worldIn.getBlockEntity(pos);
CompoundTag nbt = stack.getTag().getCompound("blockEntity_data");
injectLocationData(nbt, pos);
blockEntity.fromTag(state, nbt);
blockEntity.markDirty();
}
}
private void stripLocationData(CompoundTag compound) {
compound.remove("x");
compound.remove("y");
compound.remove("z");
}
private void injectLocationData(CompoundTag compound, BlockPos pos) {
compound.putInt("x", pos.getX());
compound.putInt("y", pos.getY());
compound.putInt("z", pos.getZ());
}
public void getDrops(BlockState state, DefaultedList<ItemStack> drops, World world, BlockPos pos, int fortune){
}
}

View file

@ -0,0 +1,206 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.common;
import com.google.common.collect.ImmutableList;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import net.fabricmc.api.EnvType;
import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.command.argument.EntityArgumentType;
import net.minecraft.command.argument.ItemStackArgumentType;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.server.command.CommandManager;
import net.minecraft.command.CommandSource;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerChunkManager;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.LiteralText;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.chunk.ChunkStatus;
import reborncore.client.ItemStackRenderManager;
import reborncore.common.crafting.RecipeManager;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static com.mojang.brigadier.arguments.IntegerArgumentType.getInteger;
import static com.mojang.brigadier.arguments.IntegerArgumentType.integer;
import static com.mojang.brigadier.arguments.StringArgumentType.word;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
public class RebornCoreCommands {
private final static ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();
private final static SuggestionProvider<ServerCommandSource> MOD_SUGGESTIONS = (context, builder) ->
CommandSource.suggestMatching(FabricLoader.getInstance().getAllMods().stream().map(modContainer -> modContainer.getMetadata().getId()), builder);
public static void setup() {
CommandRegistrationCallback.EVENT.register(((dispatcher, isDedicated) -> RebornCoreCommands.addCommands(dispatcher)));
}
private static void addCommands(CommandDispatcher<ServerCommandSource> dispatcher) {
dispatcher.register(
literal("reborncore")
.then(
literal("recipes")
.then(literal("validate")
.requires(source -> source.hasPermissionLevel(3))
.executes(ctx -> {
RecipeManager.validateRecipes(ctx.getSource().getWorld());
return Command.SINGLE_SUCCESS;
})
)
)
.then(
literal("generate")
.requires(source -> source.hasPermissionLevel(3))
.then(argument("size", integer())
.executes(RebornCoreCommands::generate)
)
)
.then(
literal("flyspeed")
.requires(source -> source.hasPermissionLevel(3))
.then(argument("speed", integer(1, 10))
.executes(ctx -> flySpeed(ctx, ImmutableList.of(ctx.getSource().getPlayer())))
.then(CommandManager.argument("players", EntityArgumentType.players())
.executes(ctx -> flySpeed(ctx, EntityArgumentType.getPlayers(ctx, "players")))
)
)
)
.then(
literal("render")
.then(
literal("mod")
.then(
argument("modid", word())
.suggests(MOD_SUGGESTIONS)
.executes(RebornCoreCommands::renderMod)
)
)
.then(
literal("item")
.then(
argument("item", ItemStackArgumentType.itemStack())
.executes(RebornCoreCommands::itemRenderer)
)
)
.then(
literal("hand")
.executes(RebornCoreCommands::handRenderer)
)
)
);
}
private static int generate(CommandContext<ServerCommandSource> ctx) {
final int size = getInteger(ctx, "size");
final ServerWorld world = ctx.getSource().getWorld();
final ServerChunkManager serverChunkManager = world.getChunkManager();
final AtomicInteger completed = new AtomicInteger(0);
for (int x = -(size / 2); x < size / 2; x++) {
for (int z = -(size / 2); z < size / 2; z++) {
final int chunkPosX = x;
final int chunkPosZ = z;
CompletableFuture.supplyAsync(() -> serverChunkManager.getChunk(chunkPosX, chunkPosZ, ChunkStatus.FULL, true), EXECUTOR_SERVICE)
.whenComplete((chunk, throwable) -> {
int max = (int) Math.pow(size, 2);
ctx.getSource().sendFeedback(new LiteralText(String.format("Finished generating %d:%d (%d/%d %d%%)", chunk.getPos().x, chunk.getPos().z, completed.getAndIncrement(), max, completed.get() == 0 ? 0 : (int) ((completed.get() * 100.0f) / max))), true);
}
);
}
}
return Command.SINGLE_SUCCESS;
}
private static int flySpeed(CommandContext<ServerCommandSource> ctx, Collection<ServerPlayerEntity> players) {
final int speed = getInteger(ctx, "speed");
players.stream()
.peek(player -> player.abilities.setFlySpeed(speed / 20F))
.forEach(ServerPlayerEntity::sendAbilitiesUpdate);
return Command.SINGLE_SUCCESS;
}
private static int renderMod(CommandContext<ServerCommandSource> ctx) {
String modid = StringArgumentType.getString(ctx, "modid");
List<ItemStack> list = Registry.ITEM.getIds().stream()
.filter(identifier -> identifier.getNamespace().equals(modid))
.map(Registry.ITEM::get)
.map(ItemStack::new)
.collect(Collectors.toList());
queueRender(list);
return Command.SINGLE_SUCCESS;
}
private static int itemRenderer(CommandContext<ServerCommandSource> ctx) {
Item item = ItemStackArgumentType.getItemStackArgument(ctx, "item").getItem();
queueRender(Collections.singletonList(new ItemStack(item)));
return Command.SINGLE_SUCCESS;
}
private static int handRenderer(CommandContext<ServerCommandSource> ctx) {
try {
queueRender(Collections.singletonList(ctx.getSource().getPlayer().inventory.getMainHandStack()));
} catch (CommandSyntaxException e) {
e.printStackTrace();
return 0;
}
return Command.SINGLE_SUCCESS;
}
private static void queueRender(List<ItemStack> stacks) {
if (FabricLoader.getInstance().getEnvironmentType() == EnvType.SERVER) {
System.out.println("Render item only works on the client!");
return;
}
ItemStackRenderManager.RENDER_QUEUE.addAll(stacks);
}
}

View file

@ -0,0 +1,35 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.common;
import reborncore.common.config.Config;
public class RebornCoreConfig {
@Config(config = "misc", key = "Enable Seasonal Easter Eggs", comment = "Disable this is you don't want seasonal easter eggs")
public static boolean easterEggs = true;
@Config(config = "misc", key = "Selected Energy system", comment = "Possible values are: E (was FE, EU)")
public static String selectedSystem = "E";
}

View file

@ -0,0 +1,218 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.common.blockentity;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import reborncore.common.fluid.FluidUtil;
import reborncore.common.util.NBTSerializable;
import reborncore.common.util.Tank;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class FluidConfiguration implements NBTSerializable {
HashMap<Direction, FluidConfig> sideMap;
boolean input, output;
public FluidConfiguration() {
sideMap = new HashMap<>();
Arrays.stream(Direction.values()).forEach(facing -> sideMap.put(facing, new FluidConfig(facing)));
}
public FluidConfiguration(CompoundTag tagCompound) {
sideMap = new HashMap<>();
read(tagCompound);
}
public FluidConfig getSideDetail(Direction side) {
if (side == null) {
return sideMap.get(Direction.NORTH);
}
return sideMap.get(side);
}
public List<FluidConfig> getAllSides() {
return new ArrayList<>(sideMap.values());
}
public void updateFluidConfig(FluidConfig config) {
FluidConfig toEdit = sideMap.get(config.side);
toEdit.ioConfig = config.ioConfig;
}
public void update(MachineBaseBlockEntity machineBase) {
if (!input && !output) {
return;
}
if (machineBase.getTank() == null || machineBase.getWorld().getTime() % machineBase.slotTransferSpeed() != 0) {
return;
}
for (Direction facing : Direction.values()) {
FluidConfig fluidConfig = getSideDetail(facing);
if (fluidConfig == null || !fluidConfig.getIoConfig().isEnabled()) {
continue;
}
Tank tank = getTank(machineBase, facing);
if (autoInput() && fluidConfig.getIoConfig().isInsert()) {
FluidUtil.transferFluid(tank, machineBase.getTank(), machineBase.fluidTransferAmount());
}
if (autoOutput() && fluidConfig.getIoConfig().isExtact()) {
FluidUtil.transferFluid(machineBase.getTank(), tank, machineBase.fluidTransferAmount());
}
}
}
private Tank getTank(MachineBaseBlockEntity machine, Direction facing) {
BlockPos pos = machine.getPos().offset(facing);
BlockEntity blockEntity = machine.getWorld().getBlockEntity(pos);
if (blockEntity instanceof MachineBaseBlockEntity) {
return ((MachineBaseBlockEntity) blockEntity).getTank();
}
return null;
}
public boolean autoInput() {
return input;
}
public boolean autoOutput() {
return output;
}
public void setInput(boolean input) {
this.input = input;
}
public void setOutput(boolean output) {
this.output = output;
}
@NotNull
@Override
public CompoundTag write() {
CompoundTag compound = new CompoundTag();
Arrays.stream(Direction.values()).forEach(facing -> compound.put("side_" + facing.ordinal(), sideMap.get(facing).write()));
compound.putBoolean("input", input);
compound.putBoolean("output", output);
return compound;
}
@Override
public void read(@NotNull CompoundTag nbt) {
sideMap.clear();
Arrays.stream(Direction.values()).forEach(facing -> {
CompoundTag compound = nbt.getCompound("side_" + facing.ordinal());
FluidConfig config = new FluidConfig(compound);
sideMap.put(facing, config);
});
input = nbt.getBoolean("input");
output = nbt.getBoolean("output");
}
public static class FluidConfig implements NBTSerializable {
Direction side;
FluidConfiguration.ExtractConfig ioConfig;
public FluidConfig(Direction side) {
this.side = side;
this.ioConfig = ExtractConfig.ALL;
}
public FluidConfig(Direction side, FluidConfiguration.ExtractConfig ioConfig) {
this.side = side;
this.ioConfig = ioConfig;
}
public FluidConfig(CompoundTag tagCompound) {
read(tagCompound);
}
public Direction getSide() {
return side;
}
public ExtractConfig getIoConfig() {
return ioConfig;
}
@NotNull
@Override
public CompoundTag write() {
CompoundTag tagCompound = new CompoundTag();
tagCompound.putInt("side", side.ordinal());
tagCompound.putInt("config", ioConfig.ordinal());
return tagCompound;
}
@Override
public void read(@NotNull CompoundTag nbt) {
side = Direction.values()[nbt.getInt("side")];
ioConfig = FluidConfiguration.ExtractConfig.values()[nbt.getInt("config")];
}
}
public enum ExtractConfig {
NONE(false, false),
INPUT(false, true),
OUTPUT(true, false),
ALL(true, true);
boolean extact;
boolean insert;
ExtractConfig(boolean extact, boolean insert) {
this.extact = extact;
this.insert = insert;
}
public boolean isExtact() {
return extact;
}
public boolean isInsert() {
return insert;
}
public boolean isEnabled() {
return extact || insert;
}
public FluidConfiguration.ExtractConfig getNext() {
int i = this.ordinal() + 1;
if (i >= FluidConfiguration.ExtractConfig.values().length) {
i = 0;
}
return FluidConfiguration.ExtractConfig.values()[i];
}
}
}

View file

@ -0,0 +1,518 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.common.blockentity;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.entity.BlockEntityType;
import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.SidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.packet.s2c.play.BlockEntityUpdateS2CPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Text;
import net.minecraft.util.BlockRotation;
import net.minecraft.util.Formatting;
import net.minecraft.util.Tickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.World;
import org.apache.commons.lang3.Validate;
import reborncore.api.IListInfoProvider;
import reborncore.api.blockentity.IUpgrade;
import reborncore.api.blockentity.IUpgradeable;
import reborncore.api.blockentity.InventoryProvider;
import reborncore.api.recipe.IRecipeCrafterProvider;
import reborncore.common.blocks.BlockMachineBase;
import reborncore.common.fluid.FluidValue;
import reborncore.common.network.ClientBoundPackets;
import reborncore.common.network.NetworkManager;
import reborncore.common.recipes.IUpgradeHandler;
import reborncore.common.recipes.RecipeCrafter;
import reborncore.common.util.RebornInventory;
import reborncore.common.util.Tank;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* Created by modmuss50 on 04/11/2016.
*/
public class MachineBaseBlockEntity extends BlockEntity implements Tickable, IUpgradeable, IUpgradeHandler, IListInfoProvider, Inventory, SidedInventory {
public RebornInventory<MachineBaseBlockEntity> upgradeInventory = new RebornInventory<>(getUpgradeSlotCount(), "upgrades", 1, this, (slotID, stack, face, direction, blockEntity) -> true);
private SlotConfiguration slotConfiguration;
public FluidConfiguration fluidConfiguration;
private RedstoneConfiguration redstoneConfiguration;
public boolean renderMultiblock = false;
private int ticktime = 0;
/**
* This is used to change the speed of the crafting operation.
* <p/>
* 0 = none; 0.2 = 20% speed increase 0.75 = 75% increase
*/
double speedMultiplier = 0;
/**
* This is used to change the power of the crafting operation.
* <p/>
* 1 = none; 1.2 = 20% speed increase 1.75 = 75% increase 5 = uses 5 times
* more power
*/
double powerMultiplier = 1;
public MachineBaseBlockEntity(BlockEntityType<?> blockEntityTypeIn) {
super(blockEntityTypeIn);
redstoneConfiguration = new RedstoneConfiguration(this);
}
public boolean isMultiblockValid() {
MultiblockWriter.MultiblockVerifier verifier = new MultiblockWriter.MultiblockVerifier(getPos(), getWorld());
writeMultiblock(verifier.rotate(getFacing().getOpposite()));
return verifier.isValid();
}
public void writeMultiblock(MultiblockWriter writer) {}
public void syncWithAll() {
if (world == null || world.isClient) { return; }
NetworkManager.sendToTracking(ClientBoundPackets.createCustomDescriptionPacket(this), this);
}
public void onLoad() {
if (slotConfiguration == null) {
if (getOptionalInventory().isPresent()) {
slotConfiguration = new SlotConfiguration(getOptionalInventory().get());
}
}
if (getTank() != null) {
if (fluidConfiguration == null) {
fluidConfiguration = new FluidConfiguration();
}
}
redstoneConfiguration.refreshCache();
}
@Nullable
@Override
public BlockEntityUpdateS2CPacket toUpdatePacket() {
return new BlockEntityUpdateS2CPacket(getPos(), 0, toInitialChunkDataTag());
}
@Override
public CompoundTag toInitialChunkDataTag() {
CompoundTag compound = super.toTag(new CompoundTag());
toTag(compound);
return compound;
}
@Override
public void tick() {
if (ticktime == 0) {
onLoad();
}
ticktime++;
@Nullable
RecipeCrafter crafter = null;
if (getOptionalCrafter().isPresent()) {
crafter = getOptionalCrafter().get();
}
if (canBeUpgraded()) {
resetUpgrades();
for (int i = 0; i < getUpgradeSlotCount(); i++) {
ItemStack stack = getUpgradeInvetory().getStack(i);
if (!stack.isEmpty() && stack.getItem() instanceof IUpgrade) {
((IUpgrade) stack.getItem()).process(this, this, stack);
}
}
}
if (world == null || world.isClient) {
return;
}
if (crafter != null && isActive(RedstoneConfiguration.RECIPE_PROCESSING)) {
crafter.updateEntity();
}
if (slotConfiguration != null && isActive(RedstoneConfiguration.ITEM_IO)) {
slotConfiguration.update(this);
}
if (fluidConfiguration != null && isActive(RedstoneConfiguration.FLUID_IO)) {
fluidConfiguration.update(this);
}
}
public void resetUpgrades() {
resetPowerMulti();
resetSpeedMulti();
}
public int getFacingInt() {
Block block = world.getBlockState(pos).getBlock();
if (block instanceof BlockMachineBase) {
return ((BlockMachineBase) block).getFacing(world.getBlockState(pos)).getId();
}
return 0;
}
public Direction getFacingEnum() {
Block block = world.getBlockState(pos).getBlock();
if (block instanceof BlockMachineBase) {
return ((BlockMachineBase) block).getFacing(world.getBlockState(pos));
}
return Direction.NORTH;
}
public void setFacing(Direction enumFacing) {
Block block = world.getBlockState(pos).getBlock();
if (block instanceof BlockMachineBase) {
((BlockMachineBase) block).setFacing(enumFacing, world, pos);
}
}
public boolean isActive() {
Block block = world.getBlockState(pos).getBlock();
if (block instanceof BlockMachineBase) {
return world.getBlockState(pos).get(BlockMachineBase.ACTIVE);
}
return false;
}
public Optional<RebornInventory<?>> getOptionalInventory() {
if (this instanceof InventoryProvider) {
InventoryProvider inventory = (InventoryProvider) this;
if (inventory.getInventory() == null) {
return Optional.empty();
}
return Optional.of((RebornInventory<?>) inventory.getInventory());
}
return Optional.empty();
}
protected Optional<RecipeCrafter> getOptionalCrafter() {
if (this instanceof IRecipeCrafterProvider) {
IRecipeCrafterProvider crafterProvider = (IRecipeCrafterProvider) this;
if (crafterProvider.getRecipeCrafter() == null) {
return Optional.empty();
}
return Optional.of(crafterProvider.getRecipeCrafter());
}
return Optional.empty();
}
@Override
public void fromTag(BlockState blockState, CompoundTag tagCompound) {
super.fromTag(blockState, tagCompound);
if (getOptionalInventory().isPresent()) {
getOptionalInventory().get().read(tagCompound);
}
if (getOptionalCrafter().isPresent()) {
getOptionalCrafter().get().read(tagCompound);
}
if (tagCompound.contains("slotConfig")) {
slotConfiguration = new SlotConfiguration(tagCompound.getCompound("slotConfig"));
} else {
if (getOptionalInventory().isPresent()) {
slotConfiguration = new SlotConfiguration(getOptionalInventory().get());
}
}
if (tagCompound.contains("fluidConfig")) {
fluidConfiguration = new FluidConfiguration(tagCompound.getCompound("fluidConfig"));
}
if (tagCompound.contains("redstoneConfig")) {
redstoneConfiguration.refreshCache();
redstoneConfiguration.read(tagCompound.getCompound("redstoneConfig"));
}
upgradeInventory.read(tagCompound, "Upgrades");
}
@Override
public CompoundTag toTag(CompoundTag tagCompound) {
super.toTag(tagCompound);
if (getOptionalInventory().isPresent()) {
getOptionalInventory().get().write(tagCompound);
}
if (getOptionalCrafter().isPresent()) {
getOptionalCrafter().get().write(tagCompound);
}
if (slotConfiguration != null) {
tagCompound.put("slotConfig", slotConfiguration.write());
}
if (fluidConfiguration != null) {
tagCompound.put("fluidConfig", fluidConfiguration.write());
}
upgradeInventory.write(tagCompound, "Upgrades");
tagCompound.put("redstoneConfig", redstoneConfiguration.write());
return tagCompound;
}
private boolean isItemValidForSlot(int index, ItemStack stack) {
if (slotConfiguration == null) {
return false;
}
SlotConfiguration.SlotConfigHolder slotConfigHolder = slotConfiguration.getSlotDetails(index);
if (slotConfigHolder.filter() && getOptionalCrafter().isPresent()) {
RecipeCrafter crafter = getOptionalCrafter().get();
if (!crafter.isStackValidInput(stack)) {
return false;
}
}
return true;
}
//Inventory end
@Override
public Inventory getUpgradeInvetory() {
return upgradeInventory;
}
@Override
public int getUpgradeSlotCount() {
return 4;
}
public Direction getFacing() {
return getFacingEnum();
}
@Override
public void applyRotation(BlockRotation rotationIn) {
setFacing(rotationIn.rotate(getFacing()));
}
@Override
public void resetSpeedMulti() {
speedMultiplier = 0;
}
@Override
public double getSpeedMultiplier() {
return speedMultiplier;
}
@Override
public void addPowerMulti(double amount) {
powerMultiplier = powerMultiplier * (1f + amount);
}
@Override
public void resetPowerMulti() {
powerMultiplier = 1;
}
@Override
public double getPowerMultiplier() {
return powerMultiplier;
}
@Override
public double getEuPerTick(double baseEu) {
return baseEu * powerMultiplier;
}
@Override
public void addSpeedMulti(double amount) {
if (speedMultiplier + amount <= 0.99) {
speedMultiplier += amount;
} else {
speedMultiplier = 0.99;
}
}
public boolean hasSlotConfig() {
return true;
}
@Nullable
public Tank getTank() {
return null;
}
public boolean showTankConfig() {
return getTank() != null;
}
//The amount of ticks between a slot tranfer atempt, less is faster
public int slotTransferSpeed() {
return 4;
}
//The amount of fluid transfured each tick buy the fluid config
public FluidValue fluidTransferAmount() {
return FluidValue.BUCKET_QUARTER;
}
@Override
public void addInfo(List<Text> info, boolean isReal, boolean hasData) {
if (hasData) {
if (getOptionalInventory().isPresent()) {
info.add(new LiteralText(Formatting.GOLD + "" + getOptionalInventory().get().getContents() + Formatting.GRAY + " items"));
}
if (!upgradeInventory.isEmpty()) {
info.add(new LiteralText(Formatting .GOLD + "" + upgradeInventory.getContents() + Formatting .GRAY + " upgrades"));
}
}
}
public Block getBlockType(){
return world.getBlockState(pos).getBlock();
}
@Override
public int size() {
if(getOptionalInventory().isPresent()){
return getOptionalInventory().get().size();
}
return 0;
}
@Override
public boolean isEmpty() {
if(getOptionalInventory().isPresent()){
return getOptionalInventory().get().isEmpty();
}
return true;
}
@Override
public ItemStack getStack(int i) {
if(getOptionalInventory().isPresent()){
return getOptionalInventory().get().getStack(i);
}
return ItemStack.EMPTY;
}
@Override
public ItemStack removeStack(int i, int i1) {
if(getOptionalInventory().isPresent()){
return getOptionalInventory().get().removeStack(i, i1);
}
return ItemStack.EMPTY;
}
@Override
public ItemStack removeStack(int i) {
if(getOptionalInventory().isPresent()){
return getOptionalInventory().get().removeStack(i);
}
return ItemStack.EMPTY;
}
@Override
public void setStack(int i, ItemStack itemStack) {
if(getOptionalInventory().isPresent()){
getOptionalInventory().get().setStack(i, itemStack);
}
}
@Override
public boolean canPlayerUse(PlayerEntity playerEntity) {
if(getOptionalInventory().isPresent()){
return getOptionalInventory().get().canPlayerUse(playerEntity);
}
return false;
}
@Override
public boolean isValid(int slot, ItemStack stack) {
return isItemValidForSlot(slot, stack);
}
@Override
public void clear() {
if(getOptionalInventory().isPresent()){
getOptionalInventory().get().clear();
}
}
@NotNull
public SlotConfiguration getSlotConfiguration() {
Validate.notNull(slotConfiguration, "slotConfiguration cannot be null");
return slotConfiguration;
}
@Override
public int[] getAvailableSlots(Direction side) {
if(slotConfiguration == null){
return new int[]{}; //I think should be ok, if needed this can return all the slots
}
return slotConfiguration.getSlotsForSide(side).stream()
.filter(Objects::nonNull)
.filter(slotConfig -> slotConfig.getSlotIO().ioConfig != SlotConfiguration.ExtractConfig.NONE)
.mapToInt(SlotConfiguration.SlotConfig::getSlotID).toArray();
}
@Override
public boolean canInsert(int index, ItemStack stack, @Nullable Direction direction) {
if(direction == null || slotConfiguration == null){
return false;
}
SlotConfiguration.SlotConfigHolder slotConfigHolder = slotConfiguration.getSlotDetails(index);
SlotConfiguration.SlotConfig slotConfig = slotConfigHolder.getSideDetail(direction);
if (slotConfig.getSlotIO().ioConfig.isInsert()) {
if (slotConfigHolder.filter() && getOptionalCrafter().isPresent()) {
RecipeCrafter crafter = getOptionalCrafter().get();
return crafter.isStackValidInput(stack);
}
return slotConfig.getSlotIO().getIoConfig().isInsert();
}
return false;
}
@Override
public boolean canExtract(int index, ItemStack stack, Direction direction) {
if (slotConfiguration == null) {
return false;
}
SlotConfiguration.SlotConfigHolder slotConfigHolder = slotConfiguration.getSlotDetails(index);
SlotConfiguration.SlotConfig slotConfig = slotConfigHolder.getSideDetail(direction);
return slotConfig.getSlotIO().ioConfig.isExtact();
}
public void onBreak(World world, PlayerEntity playerEntity, BlockPos blockPos, BlockState blockState){
}
public void onPlace(World worldIn, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack){
}
public RedstoneConfiguration getRedstoneConfiguration() {
return redstoneConfiguration;
}
public boolean isActive(RedstoneConfiguration.Element element) {
return redstoneConfiguration.isActive(element);
}
}

View file

@ -0,0 +1,286 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.common.blockentity;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.FluidBlock;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.render.*;
import net.minecraft.client.render.block.BlockRenderManager;
import net.minecraft.client.render.model.json.ModelTransformation;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.fluid.FluidState;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.BlockRenderView;
import net.minecraft.world.BlockView;
import java.util.Random;
import java.util.function.BiPredicate;
/**
* Writes a multiblock for either verification or hologram rendering
*
* @see MultiblockVerifier
* @see HologramRenderer
* @author ramidzkh
*/
public interface MultiblockWriter {
/**
* Adds a block to the multiblock
*
* @param x X
* @param y Y
* @param z Z
* @param predicate Predicate of the position
* @param state The state for the hologram
* @return This. Useful for chaining
*/
MultiblockWriter add(int x, int y, int z, BiPredicate<BlockView, BlockPos> predicate, BlockState state);
/**
* Fills a section between (ax, ay, az) to (bx, by, bz)
*
* @param ax X of the first point
* @param ay Y of the first point
* @param az Z of the first point
* @param bx X of the second point
* @param by X of the second point
* @param bz Z of the second point
* @param predicate Predicate of the position
* @param state The state for the hologram
* @return This. Useful for chaining
*/
default MultiblockWriter fill(int ax, int ay, int az, int bx, int by, int bz, BiPredicate<BlockView, BlockPos> predicate, BlockState state) {
for (int x = ax; x < bx; x++) {
for (int y = ay; y < by; y++) {
for (int z = az; z < bz; z++) {
add(x, y, z, predicate, state);
}
}
}
return this;
}
/**
* Fills the outer ring of (0, 0, 0) to (pX, pY, pZ) through the axis, using the <code>predicate</code> and
* <code>state</code>. The inside of the ring uses <code>holePredicate</code> and <code>holeHologramState</code>
*
* @param through The axis to go through
* @param pX Size on the X axis
* @param pY Size on the Y axis
* @param pZ Size on the Z axis
* @param predicate Predicate for the ring
* @param state The ring state for the hologram
* @param holePredicate Predicate for the hole
* @param holeHologramState The hole state for the hologram
* @return This. Useful for chaining
*/
default MultiblockWriter ring(Direction.Axis through, int pX, int pY, int pZ, BiPredicate<BlockView, BlockPos> predicate, BlockState state, BiPredicate<BlockView, BlockPos> holePredicate, BlockState holeHologramState) {
if (holePredicate == null) {
holePredicate = predicate.negate();
}
if (holeHologramState == null) {
holeHologramState = Blocks.AIR.getDefaultState();
}
if (through == Direction.Axis.X) {
for (int y = 0; y < pY; y++) {
for (int z = 0; z < pZ; z++) {
if ((y == 0 || y == (pY - 1)) || (z == 0 || z == (pZ - 1))) {
add(pX, y, z, predicate, state);
} else {
add(pX, y, z, holePredicate, holeHologramState);
}
}
}
} else if (through == Direction.Axis.Y) {
for (int x = 0; x < pX; x++) {
for (int z = 0; z < pZ; z++) {
if ((x == 0 || x == (pX - 1)) || (z == 0 || z == (pZ - 1))) {
add(x, pY, z, predicate, state);
} else {
add(x, pY, z, holePredicate, holeHologramState);
}
}
}
} else if (through == Direction.Axis.Z) {
for (int x = 0; x < pX; x++) {
for (int y = 0; y < pY; y++) {
if ((x == 0 || x == (pX - 1)) || (y == 0 || y == (pY - 1))) {
add(x, y, pZ, predicate, state);
} else {
add(x, y, pZ, holePredicate, holeHologramState);
}
}
}
}
return this;
}
default MultiblockWriter ringWithAir(Direction.Axis through, int x, int y, int z, BiPredicate<BlockView, BlockPos> predicate, BlockState state) {
return ring(through, x, y, z, predicate, state, (view, pos) -> view.getBlockState(pos).getBlock() == Blocks.AIR, Blocks.AIR.getDefaultState());
}
default MultiblockWriter add(int x, int y, int z, BlockState state) {
return this.add(x, y, z, (view, pos) -> view.getBlockState(pos) == state, state);
}
default MultiblockWriter fill(int ax, int ay, int az, int bx, int by, int bz, BlockState state) {
return fill(ax, ay, az, bx, by, bz, (view, pos) -> view.getBlockState(pos) == state, state);
}
default MultiblockWriter ring(Direction.Axis through, int x, int y, int z, BlockState state, BlockState holeState) {
return ring(through, x, y, z, (view, pos) -> view.getBlockState(pos) == state, state, (view, pos) -> view.getBlockState(pos) == holeState, holeState);
}
default MultiblockWriter ringWithAir(Direction.Axis through, int x, int y, int z, BlockState state) {
return ringWithAir(through, x, y, z, (view, pos) -> view.getBlockState(pos) == state, state);
}
default MultiblockWriter translate(int offsetX, int offsetY, int offsetZ) {
return (x, y, z, predicate, state) -> add(offsetX + x, offsetY + y, offsetZ + z, predicate, state);
}
default MultiblockWriter rotate() {
return (x, y, z, predicate, state) -> add(-z, y, x, predicate, state);
}
default MultiblockWriter rotate(Direction direction) {
MultiblockWriter w = this;
switch (direction) {
case NORTH:
w = w.rotate();
case WEST:
w = w.rotate();
case SOUTH:
w = w.rotate();
}
return w;
}
/**
* A writer which prints the hologram to {@link System#out}
*/
class DebugWriter implements MultiblockWriter {
private final MultiblockWriter writer;
public DebugWriter(MultiblockWriter writer) {
this.writer = writer;
}
@Override
public MultiblockWriter add(int x, int y, int z, BiPredicate<BlockView, BlockPos> predicate, BlockState state) {
System.out.printf("\t%d\t%d\t%d\t%s\n", x, y, z, state.getBlock());
if (writer != null) {
writer.add(x, y, z, predicate, state);
}
return this;
}
}
/**
* A writer which verifies the positions of each block
*/
class MultiblockVerifier implements MultiblockWriter {
private final BlockPos relative;
private final BlockView view;
private boolean valid = true;
public MultiblockVerifier(BlockPos relative, BlockView view) {
this.relative = relative;
this.view = view;
}
public boolean isValid() {
return valid;
}
@Override
public MultiblockWriter add(int x, int y, int z, BiPredicate<BlockView, BlockPos> predicate, BlockState state) {
if (valid) {
valid = predicate.test(view, relative.add(x, y, z));
}
return this;
}
}
/**
* Renders a hologram
*/
@Environment(EnvType.CLIENT)
class HologramRenderer implements MultiblockWriter {
private static final BlockPos OUT_OF_WORLD_POS = new BlockPos(0, 260, 0); // Bad hack; disables lighting
private final BlockRenderView view;
private final MatrixStack matrix;
private final VertexConsumerProvider vertexConsumerProvider;
private final float scale;
public HologramRenderer(BlockRenderView view, MatrixStack matrix, VertexConsumerProvider vertexConsumerProvider, float scale) {
this.view = view;
this.matrix = matrix;
this.vertexConsumerProvider = vertexConsumerProvider;
this.scale = scale;
}
@Override
public MultiblockWriter add(int x, int y, int z, BiPredicate<BlockView, BlockPos> predicate, BlockState state) {
final BlockRenderManager blockRenderManager = MinecraftClient.getInstance().getBlockRenderManager();
matrix.push();
matrix.translate(x, y, z);
matrix.translate(0.5, 0.5, 0.5);
matrix.scale(scale, scale, scale);
if (state.getBlock() instanceof FluidBlock) {
FluidState fluidState = ((FluidBlock) state.getBlock()).getFluidState(state);
MinecraftClient.getInstance().getItemRenderer().renderItem(new ItemStack(fluidState.getFluid().getBucketItem()), ModelTransformation.Mode.FIXED, 15728880, OverlayTexture.DEFAULT_UV, matrix, vertexConsumerProvider);
} else {
matrix.translate(-0.5, -0.5, -0.5);
VertexConsumer consumer = vertexConsumerProvider.getBuffer(RenderLayers.getBlockLayer(state));
blockRenderManager.renderBlock(state, OUT_OF_WORLD_POS, view, matrix, consumer, false, new Random());
}
matrix.pop();
return this;
}
}
}

View file

@ -0,0 +1,252 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.common.blockentity;
import net.minecraft.block.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.nbt.CompoundTag;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.tuple.Pair;
import reborncore.api.recipe.IRecipeCrafterProvider;
import reborncore.client.screen.builder.Syncable;
import reborncore.common.util.BooleanFunction;
import reborncore.common.util.NBTSerializable;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class RedstoneConfiguration implements NBTSerializable, Syncable {
//Set in TR to be a better item such as a battery or a cell
public static ItemStack powerStack = new ItemStack(Items.CARROT_ON_A_STICK);
public static ItemStack fluidStack = new ItemStack(Items.BUCKET);
private static List<Element> ELEMENTS = new ArrayList<>();
private static Map<String, Element> ELEMENT_MAP = new HashMap<>();
public static Element ITEM_IO = newBuilder()
.name("item_io")
.icon(() -> new ItemStack(Blocks.HOPPER))
.build();
public static Element POWER_IO = newBuilder()
.name("power_io")
.icon(() -> powerStack)
.build();
public static Element FLUID_IO = newBuilder()
.name("fluid_io")
.canApply(type -> type.getTank() != null)
.icon(() -> fluidStack)
.build();
public static Element RECIPE_PROCESSING = newBuilder()
.name("recipe_processing")
.canApply(type -> type instanceof IRecipeCrafterProvider)
.icon(() -> new ItemStack(Blocks.CRAFTING_TABLE))
.build();
private static Element.Builder newBuilder() {
return Element.Builder.getInstance();
}
private final MachineBaseBlockEntity blockEntity;
private List<Element> activeElements;
private Map<Element, State> stateMap;
public RedstoneConfiguration(MachineBaseBlockEntity blockEntity) {
this.blockEntity = blockEntity;
}
public List<Element> getElements() {
if (activeElements != null) {
return activeElements;
}
return activeElements = ELEMENTS.stream()
.filter(element -> element.isApplicable(blockEntity))
.collect(Collectors.toList());
}
public void refreshCache() {
activeElements = null;
if (stateMap != null) {
for (Element element : getElements()) {
if (!stateMap.containsKey(element)) {
stateMap.put(element, State.IGNORED);
}
}
}
}
public State getState(Element element) {
if (stateMap == null) {
populateStateMap();
}
State state = stateMap.get(element);
Validate.notNull(state, "Unsupported element " + element.getName() + " for machine: " + blockEntity.getClass().getName());
return state;
}
public void setState(Element element, State state) {
if (stateMap == null) {
populateStateMap();
}
Validate.isTrue(stateMap.containsKey(element));
stateMap.replace(element, state);
}
public boolean isActive(Element element) {
State state = getState(element);
if (state == State.IGNORED) {
return true;
}
boolean hasRedstonePower = blockEntity.getWorld().isReceivingRedstonePower(blockEntity.getPos());
boolean enabledState = state == State.ENABLED_ON;
return enabledState == hasRedstonePower;
}
private void populateStateMap() {
Validate.isTrue(stateMap == null);
stateMap = new HashMap<>();
for (Element element : getElements()) {
stateMap.put(element, State.IGNORED);
}
}
@NotNull
@Override
public CompoundTag write() {
CompoundTag tag = new CompoundTag();
for (Element element : getElements()) {
tag.putInt(element.getName(), getState(element).ordinal());
}
return tag;
}
@Override
public void read(@NotNull CompoundTag tag) {
stateMap = new HashMap<>();
for (String key : tag.getKeys()) {
Element element = ELEMENT_MAP.get(key);
if (element == null) {
System.out.println("Unknown element type: " + key);
continue;
}
State state = State.values()[tag.getInt(key)];
stateMap.put(element, state);
}
//Ensure all active states are in the map, will happen if a new state is added when the world is upgraded
for (Element element : getElements()) {
if (!stateMap.containsKey(element)) {
stateMap.put(element, State.IGNORED);
}
}
}
@Override
public void getSyncPair(List<Pair<Supplier, Consumer>> pairList) {
pairList.add(Pair.of(this::write, (Consumer<CompoundTag>) this::read));
}
public static Element getElementByName(String name) {
return ELEMENT_MAP.get(name);
}
//Could be power input/output, item/fluid io, machine processing
public static class Element {
private final String name;
private final BooleanFunction<MachineBaseBlockEntity> isApplicable;
private final Supplier<ItemStack> icon;
public Element(String name, BooleanFunction<MachineBaseBlockEntity> isApplicable, Supplier<ItemStack> icon) {
this.name = name;
this.isApplicable = isApplicable;
this.icon = icon;
}
public boolean isApplicable(MachineBaseBlockEntity blockEntity) {
return isApplicable.get(blockEntity);
}
public String getName() {
return name;
}
public ItemStack getIcon() {
return icon.get();
}
public static class Builder {
private String name;
private BooleanFunction<MachineBaseBlockEntity> isApplicable = (be) -> true;
private Supplier<ItemStack> icon = () -> ItemStack.EMPTY;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder canApply(BooleanFunction<MachineBaseBlockEntity> isApplicable) {
this.isApplicable = isApplicable;
return this;
}
public Builder icon(Supplier<ItemStack> stack) {
this.icon = stack;
return this;
}
public Element build() {
Validate.isTrue(!StringUtils.isEmpty(name));
Element element = new Element(name, isApplicable, icon);
ELEMENTS.add(element);
ELEMENT_MAP.put(element.getName(), element);
return element;
}
public static Builder getInstance() {
return new Builder();
}
}
}
public enum State {
IGNORED,
ENABLED_ON,
ENABLED_OFF
}
}

View file

@ -0,0 +1,490 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.common.blockentity;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import it.unimi.dsi.fastutil.ints.IntLists;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.SidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.StringNbtReader;
import net.minecraft.util.math.Direction;
import org.apache.commons.lang3.Validate;
import reborncore.RebornCore;
import reborncore.api.items.InventoryUtils;
import reborncore.common.util.ItemUtils;
import reborncore.common.util.NBTSerializable;
import reborncore.common.util.RebornInventory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.stream.Collectors;
public class SlotConfiguration implements NBTSerializable {
List<SlotConfigHolder> slotDetails = new ArrayList<>();
@Nullable
Inventory inventory;
public SlotConfiguration(RebornInventory<?> inventory) {
this.inventory = inventory;
for (int i = 0; i < inventory.size(); i++) {
updateSlotDetails(new SlotConfigHolder(i));
}
}
public void update(MachineBaseBlockEntity machineBase) {
if (inventory == null && machineBase.getOptionalInventory().isPresent()) {
inventory = machineBase.getOptionalInventory().get();
}
if (inventory != null && slotDetails.size() != inventory.size()) {
for (int i = 0; i < inventory.size(); i++) {
SlotConfigHolder holder = getSlotDetails(i);
if (holder == null) {
RebornCore.LOGGER.debug("Fixed slot " + i + " in " + machineBase);
//humm somthing has gone wrong
updateSlotDetails(new SlotConfigHolder(i));
}
}
}
if (!machineBase.getWorld().isClient && machineBase.getWorld().getTime() % machineBase.slotTransferSpeed() == 0) {
getSlotDetails().forEach(slotConfigHolder -> slotConfigHolder.handleItemIO(machineBase));
}
}
public SlotConfiguration(CompoundTag tagCompound) {
read(tagCompound);
}
public List<SlotConfigHolder> getSlotDetails() {
return slotDetails;
}
/**
* Replaces or adds a slot detail for the slot id
*
* @param slotConfigHolder
* @return SlotConfigHolder
*/
public SlotConfigHolder updateSlotDetails(SlotConfigHolder slotConfigHolder) {
SlotConfigHolder lookup = getSlotDetails(slotConfigHolder.slotID);
if (lookup != null) {
slotDetails.remove(lookup);
}
slotDetails.add(slotConfigHolder);
return slotConfigHolder;
}
@Nullable
public SlotConfigHolder getSlotDetails(int id) {
for (SlotConfigHolder detail : slotDetails) {
if (detail.slotID == id) {
return detail;
}
}
return null;
}
public List<SlotConfig> getSlotsForSide(Direction facing) {
return slotDetails.stream().map(slotConfigHolder -> slotConfigHolder.getSideDetail(facing)).collect(Collectors.toList());
}
@NotNull
@Override
public CompoundTag write() {
CompoundTag tagCompound = new CompoundTag();
tagCompound.putInt("size", slotDetails.size());
for (int i = 0; i < slotDetails.size(); i++) {
tagCompound.put("slot_" + i, slotDetails.get(i).write());
}
return tagCompound;
}
@Override
public void read(@NotNull CompoundTag nbt) {
int size = nbt.getInt("size");
for (int i = 0; i < size; i++) {
CompoundTag tagCompound = nbt.getCompound("slot_" + i);
SlotConfigHolder slotConfigHolder = new SlotConfigHolder(tagCompound);
updateSlotDetails(slotConfigHolder);
}
}
public static class SlotConfigHolder implements NBTSerializable {
int slotID;
HashMap<Direction, SlotConfig> sideMap;
boolean input, output, filter;
public SlotConfigHolder(int slotID) {
this.slotID = slotID;
sideMap = new HashMap<>();
Arrays.stream(Direction.values()).forEach(facing -> sideMap.put(facing, new SlotConfig(facing, slotID)));
}
public SlotConfigHolder(CompoundTag tagCompound) {
sideMap = new HashMap<>();
read(tagCompound);
Validate.isTrue(Arrays.stream(Direction.values())
.map(enumFacing -> sideMap.get(enumFacing))
.noneMatch(Objects::isNull),
"sideMap failed to load from nbt"
);
}
public SlotConfig getSideDetail(Direction side) {
Validate.notNull(side, "A none null side must be used");
SlotConfig slotConfig = sideMap.get(side);
Validate.notNull(slotConfig, "slotConfig was null for side " + side);
return slotConfig;
}
public List<SlotConfig> getAllSides() {
return new ArrayList<>(sideMap.values());
}
public void updateSlotConfig(SlotConfig config) {
SlotConfig toEdit = sideMap.get(config.side);
toEdit.slotIO = config.slotIO;
}
private void handleItemIO(MachineBaseBlockEntity machineBase) {
if (!input && !output) {
return;
}
getAllSides().stream()
.filter(config -> config.getSlotIO().getIoConfig() != ExtractConfig.NONE)
.forEach(config -> {
if (input && config.getSlotIO().getIoConfig() == ExtractConfig.INPUT) {
config.handleItemInput(machineBase);
}
if (output && config.getSlotIO().getIoConfig() == ExtractConfig.OUTPUT) {
config.handleItemOutput(machineBase);
}
});
}
public boolean autoInput() {
return input;
}
public boolean autoOutput() {
return output;
}
public boolean filter() {
return filter;
}
public void setInput(boolean input) {
this.input = input;
}
public void setOutput(boolean output) {
this.output = output;
}
public void setfilter(boolean filter) {
this.filter = filter;
}
@NotNull
@Override
public CompoundTag write() {
CompoundTag compound = new CompoundTag();
compound.putInt("slotID", slotID);
Arrays.stream(Direction.values()).forEach(facing -> compound.put("side_" + facing.ordinal(), sideMap.get(facing).write()));
compound.putBoolean("input", input);
compound.putBoolean("output", output);
compound.putBoolean("filter", filter);
return compound;
}
@Override
public void read(@NotNull CompoundTag nbt) {
sideMap.clear();
slotID = nbt.getInt("slotID");
Arrays.stream(Direction.values()).forEach(facing -> {
CompoundTag compound = nbt.getCompound("side_" + facing.ordinal());
SlotConfig config = new SlotConfig(compound);
sideMap.put(facing, config);
});
input = nbt.getBoolean("input");
output = nbt.getBoolean("output");
if (nbt.contains("filter")) { //Was added later, this allows old saves to be upgraded
filter = nbt.getBoolean("filter");
}
}
}
public static class SlotConfig implements NBTSerializable {
@NotNull
private Direction side;
@NotNull
private SlotIO slotIO;
private int slotID;
public SlotConfig(@NotNull Direction side, int slotID) {
this.side = side;
this.slotID = slotID;
this.slotIO = new SlotIO(ExtractConfig.NONE);
}
public SlotConfig(@NotNull Direction side, @NotNull SlotIO slotIO, int slotID) {
this.side = side;
this.slotIO = slotIO;
this.slotID = slotID;
}
public SlotConfig(CompoundTag tagCompound) {
read(tagCompound);
Validate.notNull(side, "error when loading slot config");
Validate.notNull(slotIO, "error when loading slot config");
}
@NotNull
public Direction getSide() {
Validate.notNull(side);
return side;
}
@NotNull
public SlotIO getSlotIO() {
Validate.notNull(slotIO);
return slotIO;
}
public int getSlotID() {
return slotID;
}
private void handleItemInput(MachineBaseBlockEntity machineBase) {
RebornInventory<?> inventory = machineBase.getOptionalInventory().get();
ItemStack targetStack = inventory.getStack(slotID);
if (targetStack.getMaxCount() == targetStack.getCount()) {
return;
}
Inventory sourceInv = InventoryUtils.getInventoryAt(machineBase.getWorld(), machineBase.getPos().offset(side));
if (sourceInv == null) {
return;
}
IntList availableSlots = null;
if (sourceInv instanceof SidedInventory) {
availableSlots = IntArrayList.wrap(((SidedInventory) sourceInv).getAvailableSlots(side.getOpposite()));
}
for (int i = 0; i < sourceInv.size(); i++) {
if (availableSlots != null && !availableSlots.contains(i)) {
continue;
}
ItemStack sourceStack = sourceInv.getStack(i);
if (sourceStack.isEmpty()) {
continue;
}
if(!canInsertItem(slotID, sourceStack, side, machineBase)){
continue;
}
if (sourceInv instanceof SidedInventory && !((SidedInventory) sourceInv).canExtract(i, sourceStack, side.getOpposite())) {
continue;
}
//Checks if we are going to merge stacks that the items are the same
if (!targetStack.isEmpty()) {
if (!ItemUtils.isItemEqual(sourceStack, targetStack, true, false)) {
continue;
}
}
int extract = 4;
if (!targetStack.isEmpty()) {
extract = Math.min(targetStack.getMaxCount() - targetStack.getCount(), extract);
}
ItemStack extractedStack = sourceInv.removeStack(i, extract);
if (targetStack.isEmpty()) {
inventory.setStack(slotID, extractedStack);
} else {
inventory.getStack(slotID).increment(extractedStack.getCount());
}
inventory.setChanged();
break;
}
}
private void handleItemOutput(MachineBaseBlockEntity machineBase) {
RebornInventory<?> inventory = machineBase.getOptionalInventory().get();
ItemStack sourceStack = inventory.getStack(slotID);
if (sourceStack.isEmpty()) {
return;
}
Inventory destInventory = InventoryUtils.getInventoryAt(machineBase.getWorld(), machineBase.getPos().offset(side));
if (destInventory == null) {
return;
}
ItemStack stack = InventoryUtils.insertItem(sourceStack, destInventory, side.getOpposite());
inventory.setStack(slotID, stack);
}
@NotNull
@Override
public CompoundTag write() {
CompoundTag tagCompound = new CompoundTag();
tagCompound.putInt("side", side.ordinal());
tagCompound.put("config", slotIO.write());
tagCompound.putInt("slot", slotID);
return tagCompound;
}
@Override
public void read(@NotNull CompoundTag nbt) {
side = Direction.values()[nbt.getInt("side")];
slotIO = new SlotIO(nbt.getCompound("config"));
slotID = nbt.getInt("slot");
}
}
public static class SlotIO implements NBTSerializable {
ExtractConfig ioConfig;
public SlotIO(CompoundTag tagCompound) {
read(tagCompound);
}
public SlotIO(ExtractConfig ioConfig) {
this.ioConfig = ioConfig;
}
public ExtractConfig getIoConfig() {
return ioConfig;
}
@NotNull
@Override
public CompoundTag write() {
CompoundTag compound = new CompoundTag();
compound.putInt("config", ioConfig.ordinal());
return compound;
}
@Override
public void read(@NotNull CompoundTag nbt) {
ioConfig = ExtractConfig.values()[nbt.getInt("config")];
}
}
public enum ExtractConfig {
NONE(false, false),
INPUT(false, true),
OUTPUT(true, false);
boolean extact;
boolean insert;
ExtractConfig(boolean extact, boolean insert) {
this.extact = extact;
this.insert = insert;
}
public boolean isExtact() {
return extact;
}
public boolean isInsert() {
return insert;
}
public ExtractConfig getNext() {
int i = this.ordinal() + 1;
if (i >= ExtractConfig.values().length) {
i = 0;
}
return ExtractConfig.values()[i];
}
}
public String toJson(String machineIdent) {
CompoundTag tagCompound = new CompoundTag();
tagCompound.put("data", write());
tagCompound.putString("machine", machineIdent);
return tagCompound.toString();
}
public void readJson(String json, String machineIdent) throws UnsupportedOperationException {
CompoundTag compound;
try {
compound = StringNbtReader.parse(json);
} catch (CommandSyntaxException e) {
throw new UnsupportedOperationException("Clipboard conetents isnt a valid slot configuation");
}
if (!compound.contains("machine") || !compound.getString("machine").equals(machineIdent)) {
throw new UnsupportedOperationException("Machine config is not for this machine.");
}
read(compound.getCompound("data"));
}
//DO NOT CALL THIS, use the inventory access on the inventory
public static boolean canInsertItem(int index, ItemStack itemStackIn, Direction direction, MachineBaseBlockEntity blockEntity) {
if(itemStackIn.isEmpty()){
return false;
}
SlotConfiguration.SlotConfigHolder slotConfigHolder = blockEntity.getSlotConfiguration().getSlotDetails(index);
SlotConfiguration.SlotConfig slotConfig = slotConfigHolder.getSideDetail(direction);
if (slotConfig.getSlotIO().getIoConfig().isInsert()) {
if (slotConfigHolder.filter()) {
if(blockEntity instanceof SlotFilter){
return ((SlotFilter) blockEntity).isStackValid(index, itemStackIn);
}
}
return blockEntity.isValid(index, itemStackIn);
}
return false;
}
//DO NOT CALL THIS, use the inventory access on the inventory
public static boolean canExtractItem(int index, ItemStack stack, Direction direction, MachineBaseBlockEntity blockEntity) {
SlotConfiguration.SlotConfigHolder slotConfigHolder = blockEntity.getSlotConfiguration().getSlotDetails(index);
SlotConfiguration.SlotConfig slotConfig = slotConfigHolder.getSideDetail(direction);
if (slotConfig.getSlotIO().getIoConfig().isExtact()) {
return true;
}
return false;
}
public interface SlotFilter {
boolean isStackValid(int slotID, ItemStack stack);
int[] getInputSlots();
}
}

View file

@ -0,0 +1,234 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.common.blocks;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.InventoryProvider;
import net.minecraft.block.Material;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.SidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.state.StateManager;
import net.minecraft.state.property.BooleanProperty;
import net.minecraft.state.property.DirectionProperty;
import net.minecraft.state.property.Properties;
import net.minecraft.util.ActionResult;
import net.minecraft.util.BlockRotation;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.BlockView;
import net.minecraft.world.World;
import net.minecraft.world.WorldAccess;
import reborncore.api.ToolManager;
import reborncore.api.blockentity.IMachineGuiHandler;
import reborncore.api.blockentity.IUpgrade;
import reborncore.api.blockentity.IUpgradeable;
import reborncore.api.items.InventoryUtils;
import reborncore.common.BaseBlockEntityProvider;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import reborncore.common.fluid.FluidUtil;
import reborncore.common.util.ItemHandlerUtils;
import reborncore.common.util.Tank;
import reborncore.common.util.WrenchUtils;
public abstract class BlockMachineBase extends BaseBlockEntityProvider implements InventoryProvider {
public static final DirectionProperty FACING = Properties.HORIZONTAL_FACING;
public static final BooleanProperty ACTIVE = BooleanProperty.of("active");
boolean hasCustomStates;
public BlockMachineBase() {
this(Block.Settings.of(Material.METAL).strength(2F, 2F));
}
public BlockMachineBase(Block.Settings builder) {
this(builder, false);
}
public BlockMachineBase(Block.Settings builder, boolean hasCustomStates) {
super(builder);
this.hasCustomStates = hasCustomStates;
if (!hasCustomStates) {
this.setDefaultState(
this.getStateManager().getDefaultState().with(FACING, Direction.NORTH).with(ACTIVE, false));
}
BlockWrenchEventHandler.wrenableBlocks.add(this);
}
public void setFacing(Direction facing, World world, BlockPos pos) {
if (hasCustomStates) {
return;
}
world.setBlockState(pos, world.getBlockState(pos).with(FACING, facing));
}
public Direction getFacing(BlockState state) {
return state.get(FACING);
}
public void setActive(Boolean active, World world, BlockPos pos) {
if (hasCustomStates) {
return;
}
Direction facing = world.getBlockState(pos).get(FACING);
BlockState state = world.getBlockState(pos).with(ACTIVE, active).with(FACING, facing);
world.setBlockState(pos, state, 3);
}
public boolean isActive(BlockState state) {
return state.get(ACTIVE);
}
public boolean isAdvanced() {
return false;
}
public abstract IMachineGuiHandler getGui();
// BaseBlockEntityProvider
@Override
public void onPlaced(World worldIn, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {
super.onPlaced(worldIn, pos, state, placer, stack);
setFacing(placer.getHorizontalFacing().getOpposite(), worldIn, pos);
BlockEntity blockEntity = worldIn.getBlockEntity(pos);
if (blockEntity instanceof MachineBaseBlockEntity) {
((MachineBaseBlockEntity) blockEntity).onPlace(worldIn, pos, state, placer, stack);
}
}
@Override
public BlockEntity createBlockEntity(BlockView worldIn) {
return null;
}
// Block
@Override
protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {
builder.add(FACING, ACTIVE);
}
@SuppressWarnings("deprecation")
@Override
public void onStateReplaced(BlockState state, World worldIn, BlockPos pos, BlockState newState, boolean isMoving) {
if (state.getBlock() != newState.getBlock()) {
ItemHandlerUtils.dropContainedItems(worldIn, pos);
super.onStateReplaced(state, worldIn, pos, newState, isMoving);
}
}
@Override
public void onBreak(World world, BlockPos blockPos, BlockState blockState, PlayerEntity playerEntity) {
BlockEntity blockEntity = world.getBlockEntity(blockPos);
if (blockEntity instanceof MachineBaseBlockEntity) {
((MachineBaseBlockEntity) blockEntity).onBreak(world, playerEntity, blockPos, blockState);
}
super.onBreak(world, blockPos, blockState, playerEntity);
}
@SuppressWarnings("deprecation")
@Override
public boolean hasComparatorOutput(BlockState state) {
return true;
}
@SuppressWarnings("deprecation")
@Override
public int getComparatorOutput(BlockState state, World world, BlockPos pos) {
return ScreenHandler.calculateComparatorOutput(getInventory(state, world, pos));
}
/*
* Right-click should open GUI for all non-wrench items
* Shift-Right-click should apply special action, like fill\drain bucket, install behavior, etc.
*/
@SuppressWarnings("deprecation")
@Override
public ActionResult onUse(BlockState state, World worldIn, BlockPos pos, PlayerEntity playerIn, Hand hand, BlockHitResult hitResult) {
ItemStack stack = playerIn.getStackInHand(hand);
BlockEntity blockEntity = worldIn.getBlockEntity(pos);
// We extended BlockTileBase. Thus we should always have blockEntity entity. I hope.
if (blockEntity == null) {
return ActionResult.PASS;
}
if (blockEntity instanceof MachineBaseBlockEntity) {
Tank tank = ((MachineBaseBlockEntity) blockEntity).getTank();
if (tank != null && FluidUtil.interactWithFluidHandler(playerIn, hand, tank)) {
return ActionResult.SUCCESS;
}
}
if (!stack.isEmpty()) {
if (ToolManager.INSTANCE.canHandleTool(stack)) {
if (WrenchUtils.handleWrench(stack, worldIn, pos, playerIn, hitResult.getSide())) {
return ActionResult.SUCCESS;
}
} else if (stack.getItem() instanceof IUpgrade && blockEntity instanceof IUpgradeable) {
IUpgradeable upgradeableEntity = (IUpgradeable) blockEntity;
if (upgradeableEntity.canBeUpgraded()) {
if (InventoryUtils.insertItemStacked(upgradeableEntity.getUpgradeInvetory(), stack,
true).getCount() > 0) {
stack = InventoryUtils.insertItemStacked(upgradeableEntity.getUpgradeInvetory(), stack, false);
playerIn.setStackInHand(Hand.MAIN_HAND, stack);
return ActionResult.SUCCESS;
}
}
}
}
if (getGui() != null && !playerIn.isSneaking()) {
getGui().open(playerIn, pos, worldIn);
return ActionResult.SUCCESS;
}
return super.onUse(state, worldIn, pos, playerIn, hand, hitResult);
}
@SuppressWarnings("deprecation")
@Override
public BlockState rotate(BlockState state, BlockRotation rotation) {
return state.with(FACING, rotation.rotate(state.get(FACING)));
}
// InventoryProvider
@Override
public SidedInventory getInventory(BlockState blockState, WorldAccess world, BlockPos blockPos) {
BlockEntity blockEntity = world.getBlockEntity(blockPos);
if (blockEntity instanceof MachineBaseBlockEntity) {
return (MachineBaseBlockEntity) blockEntity;
}
return null;
}
}

View file

@ -0,0 +1,61 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.common.blocks;
import net.fabricmc.fabric.api.event.player.UseBlockCallback;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import reborncore.api.ToolManager;
import java.util.ArrayList;
import java.util.List;
public class BlockWrenchEventHandler {
public static List<Block> wrenableBlocks = new ArrayList<>();
public static void setup() {
UseBlockCallback.EVENT.register((playerEntity, world, hand, blockHitResult) -> {
if (hand == Hand.OFF_HAND) {
// Wrench should be in main hand
return ActionResult.PASS;
}
if (ToolManager.INSTANCE.canHandleTool(playerEntity.getStackInHand(Hand.MAIN_HAND))) {
BlockState state = world.getBlockState(blockHitResult.getBlockPos());
if (wrenableBlocks.contains(state.getBlock())) {
Block block = state.getBlock();
block.onUse(state, world, blockHitResult.getBlockPos(), playerEntity, hand, blockHitResult);
return ActionResult.SUCCESS;
}
}
return ActionResult.PASS;
});
}
}

View file

@ -0,0 +1,221 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.common.chunkloading;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtOps;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ChunkTicketType;
import net.minecraft.server.world.ServerChunkManager;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryKey;
import net.minecraft.world.PersistentState;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import reborncore.common.network.ClientBoundPackets;
import reborncore.common.network.NetworkManager;
import java.util.*;
import java.util.stream.Collectors;
//This does not do the actual chunk loading, just keeps track of what chunks the chunk loader has loaded
public class ChunkLoaderManager extends PersistentState {
public static Codec<List<LoadedChunk>> CODEC = Codec.list(LoadedChunk.CODEC);
private static final ChunkTicketType<ChunkPos> CHUNK_LOADER = ChunkTicketType.create("reborncore:chunk_loader", Comparator.comparingLong(ChunkPos::toLong));
private static final String KEY = "reborncore_chunk_loader";
public ChunkLoaderManager() {
super(KEY);
}
public static ChunkLoaderManager get(World world){
ServerWorld serverWorld = (ServerWorld) world;
return serverWorld.getPersistentStateManager().getOrCreate(ChunkLoaderManager::new, KEY);
}
private final List<LoadedChunk> loadedChunks = new ArrayList<>();
@Override
public void fromTag(CompoundTag tag) {
loadedChunks.clear();
List<LoadedChunk> chunks = CODEC.parse(NbtOps.INSTANCE, tag.getCompound("loadedchunks"))
.result()
.orElse(Collections.emptyList());
loadedChunks.addAll(chunks);
}
@Override
public CompoundTag toTag(CompoundTag compoundTag) {
CODEC.encodeStart(NbtOps.INSTANCE, loadedChunks)
.result()
.ifPresent(tag -> compoundTag.put("loadedchunks", tag));
return compoundTag;
}
public Optional<LoadedChunk> getLoadedChunk(World world, ChunkPos chunkPos, BlockPos chunkLoader){
return loadedChunks.stream()
.filter(loadedChunk -> loadedChunk.getWorld().equals(getWorldName(world)))
.filter(loadedChunk -> loadedChunk.getChunk().equals(chunkPos))
.filter(loadedChunk -> loadedChunk.getChunkLoader().equals(chunkLoader))
.findFirst();
}
public Optional<LoadedChunk> getLoadedChunk(World world, ChunkPos chunkPos){
return loadedChunks.stream()
.filter(loadedChunk -> loadedChunk.getWorld().equals(getWorldName(world)))
.filter(loadedChunk -> loadedChunk.getChunk().equals(chunkPos))
.findFirst();
}
public List<LoadedChunk> getLoadedChunks(World world, BlockPos chunkloader){
return loadedChunks.stream()
.filter(loadedChunk -> loadedChunk.getWorld().equals(getWorldName(world)))
.filter(loadedChunk -> loadedChunk.getChunkLoader().equals(chunkloader))
.collect(Collectors.toList());
}
public boolean isChunkLoaded(World world, ChunkPos chunkPos, BlockPos chunkLoader){
return getLoadedChunk(world, chunkPos, chunkLoader).isPresent();
}
public boolean isChunkLoaded(World world, ChunkPos chunkPos){
return getLoadedChunk(world, chunkPos).isPresent();
}
public void loadChunk(World world, ChunkPos chunkPos, BlockPos chunkLoader, String player){
Validate.isTrue(!isChunkLoaded(world, chunkPos, chunkLoader), "chunk is already loaded");
LoadedChunk loadedChunk = new LoadedChunk(chunkPos, getWorldName(world), player, chunkLoader);
loadedChunks.add(loadedChunk);
final ServerChunkManager serverChunkManager = ((ServerWorld) world).getChunkManager();
serverChunkManager.addTicket(ChunkLoaderManager.CHUNK_LOADER, loadedChunk.getChunk(), 31, loadedChunk.getChunk());
markDirty();
}
public void unloadChunkLoader(World world, BlockPos chunkLoader){
getLoadedChunks(world, chunkLoader).forEach(loadedChunk -> unloadChunk(world, loadedChunk.getChunk(), chunkLoader));
}
public void unloadChunk(World world, ChunkPos chunkPos, BlockPos chunkLoader){
Optional<LoadedChunk> optionalLoadedChunk = getLoadedChunk(world, chunkPos, chunkLoader);
Validate.isTrue(optionalLoadedChunk.isPresent(), "chunk is not loaded");
LoadedChunk loadedChunk = optionalLoadedChunk.get();
loadedChunks.remove(loadedChunk);
if(!isChunkLoaded(world, loadedChunk.getChunk())){
final ServerChunkManager serverChunkManager = ((ServerWorld) world).getChunkManager();
serverChunkManager.removeTicket(ChunkLoaderManager.CHUNK_LOADER, loadedChunk.getChunk(), 31, loadedChunk.getChunk());
}
markDirty();
}
public static Identifier getWorldName(World world){
return world.getRegistryKey().getValue();
}
public static RegistryKey<World> getDimensionRegistryKey(World world){
return world.getRegistryKey();
}
public void syncChunkLoaderToClient(ServerPlayerEntity serverPlayerEntity, BlockPos chunkLoader){
syncToClient(serverPlayerEntity, loadedChunks.stream().filter(loadedChunk -> loadedChunk.getChunkLoader().equals(chunkLoader)).collect(Collectors.toList()));
}
public void syncAllToClient(ServerPlayerEntity serverPlayerEntity) {
syncToClient(serverPlayerEntity, loadedChunks);
}
public void clearClient(ServerPlayerEntity serverPlayerEntity) {
syncToClient(serverPlayerEntity, Collections.emptyList());
}
public void syncToClient(ServerPlayerEntity serverPlayerEntity, List<LoadedChunk> chunks) {
NetworkManager.sendToPlayer(ClientBoundPackets.createPacketSyncLoadedChunks(chunks), serverPlayerEntity);
}
public static class LoadedChunk {
public static Codec<ChunkPos> CHUNK_POS_CODEC = RecordCodecBuilder.create(instance ->
instance.group(
Codec.INT.fieldOf("x").forGetter(p -> p.x),
Codec.INT.fieldOf("z").forGetter(p -> p.z)
)
.apply(instance, ChunkPos::new));
public static Codec<LoadedChunk> CODEC = RecordCodecBuilder.create(instance ->
instance.group(
CHUNK_POS_CODEC.fieldOf("chunk").forGetter(LoadedChunk::getChunk),
Identifier.CODEC.fieldOf("world").forGetter(LoadedChunk::getWorld),
Codec.STRING.fieldOf("player").forGetter(LoadedChunk::getPlayer),
BlockPos.CODEC.fieldOf("chunkLoader").forGetter(LoadedChunk::getChunkLoader)
)
.apply(instance, LoadedChunk::new));
private ChunkPos chunk;
private Identifier world;
private String player;
private BlockPos chunkLoader;
public LoadedChunk(ChunkPos chunk, Identifier world, String player, BlockPos chunkLoader) {
this.chunk = chunk;
this.world = world;
this.player = player;
this.chunkLoader = chunkLoader;
Validate.isTrue(!StringUtils.isBlank(player), "Player cannot be blank");
}
public ChunkPos getChunk() {
return chunk;
}
public Identifier getWorld() {
return world;
}
public String getPlayer() {
return player;
}
public BlockPos getChunkLoader() {
return chunkLoader;
}
}
}

View file

@ -0,0 +1,64 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.common.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Config {
/**
* This the category of the config
*
* @return
*/
String category() default "config";
/**
* This is the key for the config, the default is the field name.
*
* @return
*/
String key() default "";
/**
* This is a comment that will be supplied along with the config, use this to explain what the config does
*
* @return
*/
String comment() default "";
/**
* this is the config file name, the default is just config.cgf, use this is you whish to split the config into more than one file.
*
* @return
*/
String config() default "config";
}

View file

@ -0,0 +1,188 @@
/*
* This file is part of RebornCore, licensed under the MIT License (MIT).
*
* Copyright (c) 2021 TeamReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.common.config;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.fabricmc.loader.api.FabricLoader;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class Configuration {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private final Class clazz;
private final String modId;
public Configuration(Class clazz, String modId) {
this.clazz = clazz;
this.modId = modId;
setup();
}
private void setup() {
final File configDir = new File(FabricLoader.getInstance().getConfigDir().toFile(), modId);
if (!configDir.exists()) {
configDir.mkdirs();
}
final File[] configFiles = configDir.listFiles();
if (configFiles != null) {
final HashMap<String, JsonObject> configs = new HashMap<>();
for (File file : configFiles) {
final String name = file.getName().substring(0, file.getName().length() - (".json".length()));
try {
final String fileContents = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
final JsonObject jsonObject = GSON.fromJson(fileContents, JsonObject.class);
configs.put(name, jsonObject);
} catch (IOException e) {
System.err.println("Failed to read config file: " + file.getAbsolutePath());
e.printStackTrace();
}
}
readFromJson(configs);
}
//Save the configs
for (Map.Entry<String, JsonObject> entry : toJson().entrySet()) {
final File configFile = new File(configDir, entry.getKey() + ".json");
final String jsonStr = GSON.toJson(entry.getValue());
try {
FileUtils.writeStringToFile(configFile, jsonStr, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Failed to write config file: " + configFile.getAbsolutePath(), e);
}
}
}
private HashMap<Field, Config> getConfigFields() {
final HashMap<Field, Config> fieldMap = new HashMap<>();
for (Field field : clazz.getDeclaredFields()) {
if (!field.isAnnotationPresent(Config.class)) {
continue;
}
if (!Modifier.isStatic(field.getModifiers())) {
throw new UnsupportedOperationException("Config field must be static");
}
Config annotation = field.getAnnotation(Config.class);
fieldMap.put(field, annotation);
}
return fieldMap;
}
public HashMap<String, JsonObject> toJson() {
final HashMap<Field, Config> fieldMap = getConfigFields();
final HashMap<String, JsonObject> configs = new HashMap<>();
for (Map.Entry<Field, Config> entry : fieldMap.entrySet()) {
Field field = entry.getKey();
Config annotation = entry.getValue();
final JsonObject config = configs.computeIfAbsent(annotation.config(), s -> new JsonObject());
JsonObject categoryObject;
if (config.has(annotation.category())) {
categoryObject = config.getAsJsonObject(annotation.category());
} else {
categoryObject = new JsonObject();
config.add(annotation.category(), categoryObject);
}
String key = annotation.key().isEmpty() ? field.getName() : annotation.key();
if (categoryObject.has(key)) {
throw new UnsupportedOperationException("Some bad happened, duplicate key found: " + key);
}
JsonObject fieldObject = new JsonObject();
fieldObject.addProperty("comment", annotation.comment());
Object value;
try {
value = field.get(null);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
JsonElement jsonElement = GSON.toJsonTree(value);
fieldObject.add("value", jsonElement);
categoryObject.add(key, fieldObject);
}
return configs;
}
public void readFromJson(HashMap<String, JsonObject> configs) {
final HashMap<Field, Config> fieldMap = getConfigFields();
for (Map.Entry<Field, Config> entry : fieldMap.entrySet()) {
Field field = entry.getKey();
Config annotation = entry.getValue();
final JsonObject config = configs.get(annotation.config());
if (config == null) {
continue; //Could be possible if a new config is added
}
JsonObject categoryObject = config.getAsJsonObject(annotation.category());
if (categoryObject == null) {
continue;
}
String key = annotation.key().isEmpty() ? field.getName() : annotation.key();
if (!categoryObject.has(key)) {
continue;
}
JsonObject fieldObject = categoryObject.get(key).getAsJsonObject();
if (!fieldObject.has("value")) {
continue;
}
JsonElement jsonValue = fieldObject.get("value");
Class<?> fieldType = field.getType();
Object fieldValue = GSON.fromJson(jsonValue, fieldType);
try {
field.set(null, fieldValue);
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to set field value", e);
}
}
}
}

Some files were not shown because too many files have changed in this diff Show more