Fixed structure features and code style

This commit is contained in:
paulevsGitch 2021-07-10 16:07:44 +03:00
parent d431f2555c
commit 5a9365e2bb
153 changed files with 2304 additions and 2459 deletions

View file

@ -8,7 +8,7 @@ yarn_mappings= 6
loader_version= 0.11.6 loader_version= 0.11.6
# Mod Properties # Mod Properties
mod_version = 0.2.0 mod_version = 0.2.1
maven_group = ru.bclib maven_group = ru.bclib
archives_base_name = bclib archives_base_name = bclib

View file

@ -33,7 +33,7 @@ public class BCLib implements ModInitializer {
public static boolean isClient() { public static boolean isClient() {
return FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT; return FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT;
} }
public static ResourceLocation makeID(String path) { public static ResourceLocation makeID(String path) {
return new ResourceLocation(MOD_ID, path); return new ResourceLocation(MOD_ID, path);
} }

View file

@ -1,10 +1,6 @@
package ru.bclib.api; package ru.bclib.api;
import java.util.HashMap;
import java.util.Random;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.impl.biome.InternalBiomeData; import net.fabricmc.fabric.impl.biome.InternalBiomeData;
@ -20,6 +16,9 @@ import net.minecraft.world.level.biome.Biomes;
import ru.bclib.util.MHelper; import ru.bclib.util.MHelper;
import ru.bclib.world.biomes.BCLBiome; import ru.bclib.world.biomes.BCLBiome;
import java.util.HashMap;
import java.util.Random;
public class BiomeAPI { public class BiomeAPI {
/** /**
* Empty biome used as default value if requested biome doesn't exist or linked. Shouldn't be registered anywhere to prevent bugs. * Empty biome used as default value if requested biome doesn't exist or linked. Shouldn't be registered anywhere to prevent bugs.
@ -33,6 +32,7 @@ public class BiomeAPI {
/** /**
* Initialize registry for current server. * Initialize registry for current server.
*
* @param server - {@link MinecraftServer} * @param server - {@link MinecraftServer}
*/ */
public static void initRegistry(MinecraftServer server) { public static void initRegistry(MinecraftServer server) {
@ -49,23 +49,19 @@ public class BiomeAPI {
/** /**
* Adds {@link BCLBiome} to FabricAPI biomes as the Nether biome (with random {@link ClimateParameters}). * Adds {@link BCLBiome} to FabricAPI biomes as the Nether biome (with random {@link ClimateParameters}).
*
* @param biome - {@link BCLBiome}. * @param biome - {@link BCLBiome}.
*/ */
public static void addNetherBiomeToFabricApi(BCLBiome biome) { public static void addNetherBiomeToFabricApi(BCLBiome biome) {
ResourceKey<Biome> key = BuiltinRegistries.BIOME.getResourceKey(biome.getBiome()).get(); ResourceKey<Biome> key = BuiltinRegistries.BIOME.getResourceKey(biome.getBiome()).get();
Random random = new Random(biome.getID().toString().hashCode()); Random random = new Random(biome.getID().toString().hashCode());
ClimateParameters parameters = new ClimateParameters( ClimateParameters parameters = new ClimateParameters(MHelper.randRange(-2F, 2F, random), MHelper.randRange(-2F, 2F, random), MHelper.randRange(-2F, 2F, random), MHelper.randRange(-2F, 2F, random), MHelper.randRange(-2F, 2F, random));
MHelper.randRange(-2F, 2F, random),
MHelper.randRange(-2F, 2F, random),
MHelper.randRange(-2F, 2F, random),
MHelper.randRange(-2F, 2F, random),
MHelper.randRange(-2F, 2F, random)
);
InternalBiomeData.addNetherBiome(key, parameters); InternalBiomeData.addNetherBiome(key, parameters);
} }
/** /**
* Adds {@link BCLBiome} to FabricAPI biomes as an End land biome (generating on islands). * Adds {@link BCLBiome} to FabricAPI biomes as an End land biome (generating on islands).
*
* @param biome - {@link BCLBiome}. * @param biome - {@link BCLBiome}.
*/ */
public static void addEndLandBiomeToFabricApi(BCLBiome biome) { public static void addEndLandBiomeToFabricApi(BCLBiome biome) {
@ -77,6 +73,7 @@ public class BiomeAPI {
/** /**
* Adds {@link BCLBiome} to FabricAPI biomes as an End void biome (generating between islands in the void). * Adds {@link BCLBiome} to FabricAPI biomes as an End void biome (generating between islands in the void).
*
* @param biome - {@link BCLBiome}. * @param biome - {@link BCLBiome}.
*/ */
public static void addEndVoidBiomeToFabricApi(BCLBiome biome) { public static void addEndVoidBiomeToFabricApi(BCLBiome biome) {
@ -87,6 +84,7 @@ public class BiomeAPI {
/** /**
* Get {@link BCLBiome} from {@link Biome} instance on server. Used to convert world biomes to BCLBiomes. * Get {@link BCLBiome} from {@link Biome} instance on server. Used to convert world biomes to BCLBiomes.
*
* @param biome - {@link Biome} from world. * @param biome - {@link Biome} from world.
* @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}. * @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}.
*/ */
@ -99,6 +97,7 @@ public class BiomeAPI {
/** /**
* Get {@link BCLBiome} from biome on client. Used in fog rendering. * Get {@link BCLBiome} from biome on client. Used in fog rendering.
*
* @param biome - {@link Biome} from client world. * @param biome - {@link Biome} from client world.
* @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}. * @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}.
*/ */
@ -116,6 +115,7 @@ public class BiomeAPI {
/** /**
* Get biome {@link ResourceLocation} from given {@link Biome}. * Get biome {@link ResourceLocation} from given {@link Biome}.
*
* @param biome - {@link Biome} from server world. * @param biome - {@link Biome} from server world.
* @return biome {@link ResourceLocation}. * @return biome {@link ResourceLocation}.
*/ */
@ -123,9 +123,10 @@ public class BiomeAPI {
ResourceLocation id = biomeRegistry.getKey(biome); ResourceLocation id = biomeRegistry.getKey(biome);
return id == null ? EMPTY_BIOME.getID() : id; return id == null ? EMPTY_BIOME.getID() : id;
} }
/** /**
* Get {@link BCLBiome} from given {@link ResourceLocation}. * Get {@link BCLBiome} from given {@link ResourceLocation}.
*
* @param biomeID - biome {@link ResourceLocation}. * @param biomeID - biome {@link ResourceLocation}.
* @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}. * @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}.
*/ */
@ -135,6 +136,7 @@ public class BiomeAPI {
/** /**
* Get actual {@link Biome} from given {@link BCLBiome}. If it is null it will request it from current {@link Registry}. * Get actual {@link Biome} from given {@link BCLBiome}. If it is null it will request it from current {@link Registry}.
*
* @param biome - {@link BCLBiome}. * @param biome - {@link BCLBiome}.
* @return {@link Biome}. * @return {@link Biome}.
*/ */
@ -149,6 +151,7 @@ public class BiomeAPI {
/** /**
* Check if biome with {@link ResourceLocation} exists in API registry. * Check if biome with {@link ResourceLocation} exists in API registry.
*
* @param biomeID - biome {@link ResourceLocation}. * @param biomeID - biome {@link ResourceLocation}.
* @return {@code true} if biome exists in API registry and {@code false} if not. * @return {@code true} if biome exists in API registry and {@code false} if not.
*/ */

View file

@ -1,16 +1,15 @@
package ru.bclib.api; package ru.bclib.api;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.block.Block;
import ru.bclib.util.WeightedList;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;
import java.util.Set; import java.util.Set;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.block.Block;
import ru.bclib.util.WeightedList;
public class BonemealAPI { public class BonemealAPI {
private static final Map<ResourceLocation, Map<Block, WeightedList<Block>>> WATER_GRASS_BIOMES = Maps.newHashMap(); private static final Map<ResourceLocation, Map<Block, WeightedList<Block>>> WATER_GRASS_BIOMES = Maps.newHashMap();
private static final Map<ResourceLocation, Map<Block, WeightedList<Block>>> LAND_GRASS_BIOMES = Maps.newHashMap(); private static final Map<ResourceLocation, Map<Block, WeightedList<Block>>> LAND_GRASS_BIOMES = Maps.newHashMap();
@ -27,13 +26,13 @@ public class BonemealAPI {
} }
public static void addLandGrass(Block plant, Block... terrain) { public static void addLandGrass(Block plant, Block... terrain) {
for (Block block: terrain) { for (Block block : terrain) {
addLandGrass(block, plant, 1F); addLandGrass(block, plant, 1F);
} }
} }
public static void addLandGrass(ResourceLocation biome, Block plant, Block... terrain) { public static void addLandGrass(ResourceLocation biome, Block plant, Block... terrain) {
for (Block block: terrain) { for (Block block : terrain) {
addLandGrass(biome, block, plant, 1F); addLandGrass(biome, block, plant, 1F);
} }
} }
@ -62,13 +61,13 @@ public class BonemealAPI {
} }
public static void addWaterGrass(Block plant, Block... terrain) { public static void addWaterGrass(Block plant, Block... terrain) {
for (Block block: terrain) { for (Block block : terrain) {
addWaterGrass(block, plant, 1F); addWaterGrass(block, plant, 1F);
} }
} }
public static void addWaterGrass(ResourceLocation biome, Block plant, Block... terrain) { public static void addWaterGrass(ResourceLocation biome, Block plant, Block... terrain) {
for (Block block: terrain) { for (Block block : terrain) {
addWaterGrass(biome, block, plant, 1F); addWaterGrass(biome, block, plant, 1F);
} }
} }

View file

@ -1,5 +1,15 @@
package ru.bclib.api; package ru.bclib.api;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtIo;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.chunk.storage.RegionFile;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.File; import java.io.File;
@ -8,17 +18,6 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtIo;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.chunk.storage.RegionFile;
public class DataFixerAPI { public class DataFixerAPI {
private static final Map<String, String> REPLACEMENT = Maps.newHashMap(); private static final Map<String, String> REPLACEMENT = Maps.newHashMap();
private static final Map<String, Integer> FIX_VERSIONS = Maps.newHashMap(); private static final Map<String, Integer> FIX_VERSIONS = Maps.newHashMap();
@ -31,7 +30,7 @@ public class DataFixerAPI {
boolean shoudFix = false; boolean shoudFix = false;
Collection<ModContainer> mods = FabricLoader.getInstance().getAllMods(); Collection<ModContainer> mods = FabricLoader.getInstance().getAllMods();
for (ModContainer mod: mods) { for (ModContainer mod : mods) {
String name = mod.getMetadata().getId(); String name = mod.getMetadata().getId();
int preVersion = WorldDataAPI.getIntModVersion(name); int preVersion = WorldDataAPI.getIntModVersion(name);
int version = getModVersion(mod.getMetadata().getVersion().toString()); int version = getModVersion(mod.getMetadata().getVersion().toString());
@ -39,7 +38,8 @@ public class DataFixerAPI {
int fixVersion = FIX_VERSIONS.getOrDefault(name, version); int fixVersion = FIX_VERSIONS.getOrDefault(name, version);
shoudFix |= fixVersion < version && fixVersion >= preVersion; shoudFix |= fixVersion < version && fixVersion >= preVersion;
} }
}; }
;
if (!shoudFix) { if (!shoudFix) {
return; return;
} }
@ -90,14 +90,15 @@ public class DataFixerAPI {
/** /**
* Register block data fix. Fix will be applied on world load if current mod version will be newer than specified one. * Register block data fix. Fix will be applied on world load if current mod version will be newer than specified one.
* @param modID - {@link String} mod id; *
* @param modID - {@link String} mod id;
* @param modVersion - {@link String} mod version, should be in format: %d.%d.%d * @param modVersion - {@link String} mod version, should be in format: %d.%d.%d
* @param result - {@link String} new block name; * @param result - {@link String} new block name;
* @param names - array of {@link String}, old block names to convert. * @param names - array of {@link String}, old block names to convert.
*/ */
protected static void addFix(String modID, String modVersion, String result, String... names) { protected static void addFix(String modID, String modVersion, String result, String... names) {
FIX_VERSIONS.put(modID, getModVersion(modVersion)); FIX_VERSIONS.put(modID, getModVersion(modVersion));
for (String name: names) { for (String name : names) {
REPLACEMENT.put(name, result); REPLACEMENT.put(name, result);
} }
} }
@ -106,7 +107,7 @@ public class DataFixerAPI {
if (list == null) { if (list == null) {
list = Lists.newArrayList(); list = Lists.newArrayList();
} }
for (File file: dir.listFiles()) { for (File file : dir.listFiles()) {
if (file.isDirectory()) { if (file.isDirectory()) {
getAllRegions(file, list); getAllRegions(file, list);
} }
@ -119,6 +120,7 @@ public class DataFixerAPI {
/** /**
* Get mod version from string. String should be in format: %d.%d.%d * Get mod version from string. String should be in format: %d.%d.%d
*
* @param version - {@link String} mod version. * @param version - {@link String} mod version.
* @return int mod version. * @return int mod version.
*/ */
@ -137,6 +139,7 @@ public class DataFixerAPI {
/** /**
* Get mod version from integer. String will be in format %d.%d.%d * Get mod version from integer. String will be in format %d.%d.%d
*
* @param version - mod version in integer form. * @param version - mod version in integer form.
* @return {@link String} mod version. * @return {@link String} mod version.
*/ */

View file

@ -1,16 +1,16 @@
package ru.bclib.api; package ru.bclib.api;
import java.util.List;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import ru.bclib.integration.ModIntegration; import ru.bclib.integration.ModIntegration;
import java.util.List;
public class ModIntegrationAPI { public class ModIntegrationAPI {
private static final List<ModIntegration> INTEGRATIONS = Lists.newArrayList(); private static final List<ModIntegration> INTEGRATIONS = Lists.newArrayList();
/** /**
* Registers mod integration * Registers mod integration
*
* @param integration * @param integration
* @return * @return
*/ */
@ -21,6 +21,7 @@ public class ModIntegrationAPI {
/** /**
* Get all registered mod integrations. * Get all registered mod integrations.
*
* @return {@link List} of {@link ModIntegration}. * @return {@link List} of {@link ModIntegration}.
*/ */
public static List<ModIntegration> getIntegrations() { public static List<ModIntegration> getIntegrations() {

View file

@ -1,7 +1,5 @@
package ru.bclib.api; package ru.bclib.api;
import java.util.function.Supplier;
import net.fabricmc.fabric.api.tag.TagRegistry; import net.fabricmc.fabric.api.tag.TagRegistry;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.BlockTags; import net.minecraft.tags.BlockTags;
@ -16,6 +14,8 @@ import net.minecraft.world.level.block.Blocks;
import ru.bclib.BCLib; import ru.bclib.BCLib;
import ru.bclib.util.TagHelper; import ru.bclib.util.TagHelper;
import java.util.function.Supplier;
public class TagAPI { public class TagAPI {
// Block Tags // Block Tags
public static final Tag.Named<Block> BOOKSHELVES = makeCommonBlockTag("bookshelves"); public static final Tag.Named<Block> BOOKSHELVES = makeCommonBlockTag("bookshelves");
@ -34,22 +34,24 @@ public class TagAPI {
public static final Tag.Named<Item> IRON_INGOTS = makeCommonItemTag("iron_ingots"); public static final Tag.Named<Item> IRON_INGOTS = makeCommonItemTag("iron_ingots");
public static final Tag.Named<Item> FURNACES = makeCommonItemTag("furnaces"); public static final Tag.Named<Item> FURNACES = makeCommonItemTag("furnaces");
public final static Tag.Named<Item> HAMMERS = makeItemTag("fabric", "hammers"); public final static Tag.Named<Item> HAMMERS = makeItemTag("fabric", "hammers");
/** /**
* Get or create {@link Tag.Named}. * Get or create {@link Tag.Named}.
*
* @param containerSupplier - {@link TagCollection} {@link Supplier} tag collection; * @param containerSupplier - {@link TagCollection} {@link Supplier} tag collection;
* @param id - {@link ResourceLocation} tag id. * @param id - {@link ResourceLocation} tag id.
* @return {@link Tag.Named}. * @return {@link Tag.Named}.
*/ */
public static <T> Tag.Named<T> makeTag(Supplier<TagCollection<T>> containerSupplier, ResourceLocation id) { public static <T> Tag.Named<T> makeTag(Supplier<TagCollection<T>> containerSupplier, ResourceLocation id) {
Tag<T> tag = containerSupplier.get().getTag(id); Tag<T> tag = containerSupplier.get().getTag(id);
return tag == null ? TagRegistry.create(id, containerSupplier) : (Named<T>) tag; return tag == null ? TagRegistry.create(id, containerSupplier) : (Named<T>) tag;
} }
/** /**
* Get or create {@link Block} {@link Tag.Named} with mod namespace. * Get or create {@link Block} {@link Tag.Named} with mod namespace.
*
* @param modID - {@link String} mod namespace (mod id); * @param modID - {@link String} mod namespace (mod id);
* @param name - {@link String} tag name. * @param name - {@link String} tag name.
* @return {@link Block} {@link Tag.Named}. * @return {@link Block} {@link Tag.Named}.
*/ */
public static Tag.Named<Block> makeBlockTag(String modID, String name) { public static Tag.Named<Block> makeBlockTag(String modID, String name) {
@ -58,8 +60,9 @@ public class TagAPI {
/** /**
* Get or create {@link Item} {@link Tag.Named} with mod namespace. * Get or create {@link Item} {@link Tag.Named} with mod namespace.
*
* @param modID - {@link String} mod namespace (mod id); * @param modID - {@link String} mod namespace (mod id);
* @param name - {@link String} tag name. * @param name - {@link String} tag name.
* @return {@link Item} {@link Tag.Named}. * @return {@link Item} {@link Tag.Named}.
*/ */
public static Tag.Named<Item> makeItemTag(String modID, String name) { public static Tag.Named<Item> makeItemTag(String modID, String name) {
@ -68,9 +71,10 @@ public class TagAPI {
/** /**
* Get or create {@link Block} {@link Tag.Named}. * Get or create {@link Block} {@link Tag.Named}.
* @see <a href="https://fabricmc.net/wiki/tutorial:tags">Fabric Wiki (Tags)</a> *
* @param name - {@link String} tag name. * @param name - {@link String} tag name.
* @return {@link Block} {@link Tag.Named}. * @return {@link Block} {@link Tag.Named}.
* @see <a href="https://fabricmc.net/wiki/tutorial:tags">Fabric Wiki (Tags)</a>
*/ */
public static Tag.Named<Block> makeCommonBlockTag(String name) { public static Tag.Named<Block> makeCommonBlockTag(String name) {
return makeTag(BlockTags::getAllTags, new ResourceLocation("c", name)); return makeTag(BlockTags::getAllTags, new ResourceLocation("c", name));
@ -78,9 +82,10 @@ public class TagAPI {
/** /**
* Get or create {@link Item} {@link Tag.Named}. * Get or create {@link Item} {@link Tag.Named}.
* @see <a href="https://fabricmc.net/wiki/tutorial:tags">Fabric Wiki (Tags)</a> *
* @param name - {@link String} tag name. * @param name - {@link String} tag name.
* @return {@link Item} {@link Tag.Named}. * @return {@link Item} {@link Tag.Named}.
* @see <a href="https://fabricmc.net/wiki/tutorial:tags">Fabric Wiki (Tags)</a>
*/ */
public static Tag.Named<Item> makeCommonItemTag(String name) { public static Tag.Named<Item> makeCommonItemTag(String name) {
return makeTag(ItemTags::getAllTags, new ResourceLocation("c", name)); return makeTag(ItemTags::getAllTags, new ResourceLocation("c", name));
@ -88,6 +93,7 @@ public class TagAPI {
/** /**
* Get or create Minecraft {@link Block} {@link Tag.Named}. * Get or create Minecraft {@link Block} {@link Tag.Named}.
*
* @param name - {@link String} tag name. * @param name - {@link String} tag name.
* @return {@link Block} {@link Tag.Named}. * @return {@link Block} {@link Tag.Named}.
*/ */
@ -99,6 +105,7 @@ public class TagAPI {
/** /**
* Adds {@link Block} to NETHER_GROUND and GEN_TERRAIN tags to process it properly in terrain generators and block logic. * Adds {@link Block} to NETHER_GROUND and GEN_TERRAIN tags to process it properly in terrain generators and block logic.
*
* @param block - {@link Block}. * @param block - {@link Block}.
*/ */
public static void addNetherGround(Block block) { public static void addNetherGround(Block block) {
@ -108,6 +115,7 @@ public class TagAPI {
/** /**
* Adds {@link Block} to END_GROUND and GEN_TERRAIN tags to process it properly in terrain generators and block logic. * Adds {@link Block} to END_GROUND and GEN_TERRAIN tags to process it properly in terrain generators and block logic.
*
* @param block - {@link Block}. * @param block - {@link Block}.
*/ */
public static void addEndGround(Block block) { public static void addEndGround(Block block) {

View file

@ -1,20 +1,19 @@
package ru.bclib.api; package ru.bclib.api;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtIo;
import ru.bclib.BCLib;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtIo;
import ru.bclib.BCLib;
public class WorldDataAPI { public class WorldDataAPI {
private static final Map<String, CompoundTag> TAGS = Maps.newHashMap(); private static final Map<String, CompoundTag> TAGS = Maps.newHashMap();
private static final List<String> MODS = Lists.newArrayList(); private static final List<String> MODS = Lists.newArrayList();
@ -52,6 +51,7 @@ public class WorldDataAPI {
/** /**
* Register mod cache, world cache is located in world data folder. * Register mod cache, world cache is located in world data folder.
*
* @param modID - {@link String} modID. * @param modID - {@link String} modID.
*/ */
public static void registerModCache(String modID) { public static void registerModCache(String modID) {
@ -60,6 +60,7 @@ public class WorldDataAPI {
/** /**
* Get root {@link CompoundTag} for mod cache in world data folder. * Get root {@link CompoundTag} for mod cache in world data folder.
*
* @param modID - {@link String} modID. * @param modID - {@link String} modID.
* @return {@link CompoundTag} * @return {@link CompoundTag}
*/ */
@ -74,13 +75,14 @@ public class WorldDataAPI {
/** /**
* Get {@link CompoundTag} with specified path from mod cache in world data folder. * Get {@link CompoundTag} with specified path from mod cache in world data folder.
*
* @param modID - {@link String} path to tag, dot-separated. * @param modID - {@link String} path to tag, dot-separated.
* @return {@link CompoundTag} * @return {@link CompoundTag}
*/ */
public static CompoundTag getCompoundTag(String modID, String path) { public static CompoundTag getCompoundTag(String modID, String path) {
String[] parts = path.split("\\."); String[] parts = path.split("\\.");
CompoundTag tag = getRootTag(modID); CompoundTag tag = getRootTag(modID);
for (String part: parts) { for (String part : parts) {
if (tag.contains(part)) { if (tag.contains(part)) {
tag = tag.getCompound(part); tag = tag.getCompound(part);
} }
@ -95,6 +97,7 @@ public class WorldDataAPI {
/** /**
* Forces mod cache file to be saved. * Forces mod cache file to be saved.
*
* @param modID {@link String} mod ID. * @param modID {@link String} mod ID.
*/ */
public static void saveFile(String modID) { public static void saveFile(String modID) {
@ -108,6 +111,7 @@ public class WorldDataAPI {
/** /**
* Get stored mod version (only for mods with registered cache). * Get stored mod version (only for mods with registered cache).
*
* @return {@link String} mod version. * @return {@link String} mod version.
*/ */
public static String getModVersion(String modID) { public static String getModVersion(String modID) {
@ -116,6 +120,7 @@ public class WorldDataAPI {
/** /**
* Get stored mod version as integer (only for mods with registered cache). * Get stored mod version as integer (only for mods with registered cache).
*
* @return {@code int} mod version. * @return {@code int} mod version.
*/ */
public static int getIntModVersion(String modID) { public static int getIntModVersion(String modID) {

View file

@ -26,25 +26,25 @@ import ru.bclib.registry.BaseBlockEntities;
public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity { public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity {
private NonNullList<ItemStack> inventory; private NonNullList<ItemStack> inventory;
private int viewerCount; private int viewerCount;
private BaseBarrelBlockEntity(BlockEntityType<?> type, BlockPos blockPos, BlockState blockState) { private BaseBarrelBlockEntity(BlockEntityType<?> type, BlockPos blockPos, BlockState blockState) {
super(type, blockPos, blockState); super(type, blockPos, blockState);
this.inventory = NonNullList.withSize(27, ItemStack.EMPTY); this.inventory = NonNullList.withSize(27, ItemStack.EMPTY);
} }
public BaseBarrelBlockEntity(BlockPos blockPos, BlockState blockState) { public BaseBarrelBlockEntity(BlockPos blockPos, BlockState blockState) {
this(BaseBlockEntities.BARREL, blockPos, blockState); this(BaseBlockEntities.BARREL, blockPos, blockState);
} }
public CompoundTag save(CompoundTag tag) { public CompoundTag save(CompoundTag tag) {
super.save(tag); super.save(tag);
if (!this.trySaveLootTable(tag)) { if (!this.trySaveLootTable(tag)) {
ContainerHelper.saveAllItems(tag, this.inventory); ContainerHelper.saveAllItems(tag, this.inventory);
} }
return tag; return tag;
} }
public void load(CompoundTag tag) { public void load(CompoundTag tag) {
super.load(tag); super.load(tag);
this.inventory = NonNullList.withSize(this.getContainerSize(), ItemStack.EMPTY); this.inventory = NonNullList.withSize(this.getContainerSize(), ItemStack.EMPTY);
@ -52,56 +52,57 @@ public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity {
ContainerHelper.loadAllItems(tag, this.inventory); ContainerHelper.loadAllItems(tag, this.inventory);
} }
} }
public int getContainerSize() { public int getContainerSize() {
return 27; return 27;
} }
protected NonNullList<ItemStack> getItems() { protected NonNullList<ItemStack> getItems() {
return this.inventory; return this.inventory;
} }
protected void setItems(NonNullList<ItemStack> list) { protected void setItems(NonNullList<ItemStack> list) {
this.inventory = list; this.inventory = list;
} }
protected Component getDefaultName() { protected Component getDefaultName() {
return new TranslatableComponent("container.barrel"); return new TranslatableComponent("container.barrel");
} }
protected AbstractContainerMenu createMenu(int syncId, Inventory playerInventory) { protected AbstractContainerMenu createMenu(int syncId, Inventory playerInventory) {
return ChestMenu.threeRows(syncId, playerInventory, this); return ChestMenu.threeRows(syncId, playerInventory, this);
} }
public void startOpen(Player player) { public void startOpen(Player player) {
if (!player.isSpectator()) { if (!player.isSpectator()) {
if (viewerCount < 0) { if (viewerCount < 0) {
viewerCount = 0; viewerCount = 0;
} }
++viewerCount; ++viewerCount;
BlockState blockState = this.getBlockState(); BlockState blockState = this.getBlockState();
if (!blockState.getValue(BarrelBlock.OPEN)) { if (!blockState.getValue(BarrelBlock.OPEN)) {
playSound(blockState, SoundEvents.BARREL_OPEN); playSound(blockState, SoundEvents.BARREL_OPEN);
setOpen(blockState, true); setOpen(blockState, true);
} }
if (level != null) { if (level != null) {
scheduleUpdate(); scheduleUpdate();
} }
} }
} }
private void scheduleUpdate() { private void scheduleUpdate() {
level.getBlockTicks().scheduleTick(getBlockPos(), getBlockState().getBlock(), 5); level.getBlockTicks().scheduleTick(getBlockPos(), getBlockState().getBlock(), 5);
} }
public void tick() { public void tick() {
if (level != null) { if (level != null) {
viewerCount = ChestBlockEntity.getOpenCount(level, worldPosition); viewerCount = ChestBlockEntity.getOpenCount(level, worldPosition);
if (viewerCount > 0) { if (viewerCount > 0) {
scheduleUpdate(); scheduleUpdate();
} else { }
else {
BlockState blockState = getBlockState(); BlockState blockState = getBlockState();
if (!(blockState.getBlock() instanceof BaseBarrelBlock)) { if (!(blockState.getBlock() instanceof BaseBarrelBlock)) {
setRemoved(); setRemoved();
@ -114,27 +115,26 @@ public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity {
} }
} }
} }
public void stopOpen(Player player) { public void stopOpen(Player player) {
if (!player.isSpectator()) { if (!player.isSpectator()) {
--this.viewerCount; --this.viewerCount;
} }
} }
private void setOpen(BlockState state, boolean open) { private void setOpen(BlockState state, boolean open) {
if (level != null) { if (level != null) {
level.setBlock(this.getBlockPos(), state.setValue(BarrelBlock.OPEN, open), 3); level.setBlock(this.getBlockPos(), state.setValue(BarrelBlock.OPEN, open), 3);
} }
} }
private void playSound(BlockState blockState, SoundEvent soundEvent) { private void playSound(BlockState blockState, SoundEvent soundEvent) {
if (level != null) { if (level != null) {
Vec3i vec3i = blockState.getValue(BarrelBlock.FACING).getNormal(); Vec3i vec3i = blockState.getValue(BarrelBlock.FACING).getNormal();
double d = (double) this.worldPosition.getX() + 0.5D + (double) vec3i.getX() / 2.0D; double d = (double) this.worldPosition.getX() + 0.5D + (double) vec3i.getX() / 2.0D;
double e = (double) this.worldPosition.getY() + 0.5D + (double) vec3i.getY() / 2.0D; double e = (double) this.worldPosition.getY() + 0.5D + (double) vec3i.getY() / 2.0D;
double f = (double) this.worldPosition.getZ() + 0.5D + (double) vec3i.getZ() / 2.0D; double f = (double) this.worldPosition.getZ() + 0.5D + (double) vec3i.getZ() / 2.0D;
level.playSound(null, d, e, f, soundEvent, SoundSource.BLOCKS, 0.5F, level.playSound(null, d, e, f, soundEvent, SoundSource.BLOCKS, 0.5F, this.level.random.nextFloat() * 0.1F + 0.9F);
this.level.random.nextFloat() * 0.1F + 0.9F);
} }
} }
} }

View file

@ -15,11 +15,11 @@ public class BaseFurnaceBlockEntity extends AbstractFurnaceBlockEntity {
public BaseFurnaceBlockEntity(BlockPos blockPos, BlockState blockState) { public BaseFurnaceBlockEntity(BlockPos blockPos, BlockState blockState) {
super(BaseBlockEntities.FURNACE, blockPos, blockState, RecipeType.SMELTING); super(BaseBlockEntities.FURNACE, blockPos, blockState, RecipeType.SMELTING);
} }
protected Component getDefaultName() { protected Component getDefaultName() {
return new TranslatableComponent("container.furnace"); return new TranslatableComponent("container.furnace");
} }
protected AbstractContainerMenu createMenu(int syncId, Inventory playerInventory) { protected AbstractContainerMenu createMenu(int syncId, Inventory playerInventory) {
return new FurnaceMenu(syncId, playerInventory, this, this.dataAccess); return new FurnaceMenu(syncId, playerInventory, this, this.dataAccess);
} }

View file

@ -10,7 +10,7 @@ public class BaseSignBlockEntity extends SignBlockEntity {
public BaseSignBlockEntity(BlockPos blockPos, BlockState blockState) { public BaseSignBlockEntity(BlockPos blockPos, BlockState blockState) {
super(blockPos, blockState); super(blockPos, blockState);
} }
@Override @Override
public BlockEntityType<?> getType() { public BlockEntityType<?> getType() {
return BaseBlockEntities.SIGN; return BaseBlockEntities.SIGN;

View file

@ -1,11 +1,6 @@
package ru.bclib.blockentities; package ru.bclib.blockentities;
import java.util.Collections;
import java.util.Set;
import java.util.function.Supplier;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
@ -13,33 +8,36 @@ import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public class DynamicBlockEntityType<T extends BlockEntity> extends BlockEntityType<T> { import java.util.Collections;
import java.util.Set;
public class DynamicBlockEntityType<T extends BlockEntity> extends BlockEntityType<T> {
private final Set<Block> validBlocks = Sets.newHashSet(); private final Set<Block> validBlocks = Sets.newHashSet();
private final BlockEntitySupplier<? extends T> factory; private final BlockEntitySupplier<? extends T> factory;
public DynamicBlockEntityType(BlockEntitySupplier<? extends T> supplier) { public DynamicBlockEntityType(BlockEntitySupplier<? extends T> supplier) {
super(null, Collections.emptySet(), null); super(null, Collections.emptySet(), null);
this.factory = supplier; this.factory = supplier;
} }
@Override @Override
@Nullable public T create(BlockPos blockPos, BlockState blockState) { @Nullable
public T create(BlockPos blockPos, BlockState blockState) {
return factory.create(blockPos, blockState); return factory.create(blockPos, blockState);
} }
@Override @Override
public boolean isValid(BlockState blockState) { public boolean isValid(BlockState blockState) {
return validBlocks.contains(blockState.getBlock()); return validBlocks.contains(blockState.getBlock());
} }
public void registerBlock(Block block) { public void registerBlock(Block block) {
validBlocks.add(block); validBlocks.add(block);
} }
@FunctionalInterface @FunctionalInterface
public public interface BlockEntitySupplier<T extends BlockEntity> {
interface BlockEntitySupplier<T extends BlockEntity> {
T create(BlockPos blockPos, BlockState blockState); T create(BlockPos blockPos, BlockState blockState);
} }
} }

View file

@ -1,14 +1,7 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -25,15 +18,20 @@ import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.block.state.properties.IntegerProperty;
import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.material.MaterialColor;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import ru.bclib.items.BaseAnvilItem; import ru.bclib.items.BaseAnvilItem;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelProvider { public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelProvider {
public static final IntegerProperty DESTRUCTION = BlockProperties.DESTRUCTION; public static final IntegerProperty DESTRUCTION = BlockProperties.DESTRUCTION;
public BaseAnvilBlock(MaterialColor color) { public BaseAnvilBlock(MaterialColor color) {
super(FabricBlockSettings.copyOf(Blocks.ANVIL).mapColor(color)); super(FabricBlockSettings.copyOf(Blocks.ANVIL).mapColor(color));
} }
@ -43,7 +41,7 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro
super.createBlockStateDefinition(builder); super.createBlockStateDefinition(builder);
builder.add(DESTRUCTION); builder.add(DESTRUCTION);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
@ -52,7 +50,7 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro
dropStack.getOrCreateTag().putInt(BaseAnvilItem.DESTRUCTION, destruction); dropStack.getOrCreateTag().putInt(BaseAnvilItem.DESTRUCTION, destruction);
return Lists.newArrayList(dropStack); return Lists.newArrayList(dropStack);
} }
protected String getTop(ResourceLocation blockId, String block) { protected String getTop(ResourceLocation blockId, String block) {
if (block.contains("item")) { if (block.contains("item")) {
return blockId.getPath() + "_top_0"; return blockId.getPath() + "_top_0";
@ -60,16 +58,16 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro
char last = block.charAt(block.length() - 1); char last = block.charAt(block.length() - 1);
return blockId.getPath() + "_top_" + last; return blockId.getPath() + "_top_" + last;
} }
@Override @Override
public abstract Item asItem(); public abstract Item asItem();
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation blockId) { public BlockModel getItemModel(ResourceLocation blockId) {
return getBlockModel(blockId, defaultBlockState()); return getBlockModel(blockId, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
@ -82,7 +80,7 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_ANVIL, textures); Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_ANVIL, textures);
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {

View file

@ -45,14 +45,14 @@ public abstract class BaseAttachedBlock extends BaseBlockNotFull {
} }
return null; return null;
} }
@Override @Override
public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) {
Direction direction = state.getValue(FACING); Direction direction = state.getValue(FACING);
BlockPos blockPos = pos.relative(direction.getOpposite()); BlockPos blockPos = pos.relative(direction.getOpposite());
return canSupportCenter(world, blockPos, direction) || world.getBlockState(blockPos).is(BlockTags.LEAVES); return canSupportCenter(world, blockPos, direction) || world.getBlockState(blockPos).is(BlockTags.LEAVES);
} }
@Override @Override
public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) {
if (!canSurvive(state, world, pos)) { if (!canSurvive(state, world, pos)) {
@ -62,13 +62,13 @@ public abstract class BaseAttachedBlock extends BaseBlockNotFull {
return state; return state;
} }
} }
@Override @Override
public BlockState rotate(BlockState state, Rotation rotation) { public BlockState rotate(BlockState state, Rotation rotation) {
return BlocksHelper.rotateHorizontal(state, rotation, FACING); return BlocksHelper.rotateHorizontal(state, rotation, FACING);
} }
@Override @Override
public BlockState mirror(BlockState state, Mirror mirror) { public BlockState mirror(BlockState state, Mirror mirror) {
return BlocksHelper.mirrorHorizontal(state, mirror, FACING); return BlocksHelper.mirrorHorizontal(state, mirror, FACING);

View file

@ -1,23 +1,23 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Optional;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Optional;
public class BaseBarkBlock extends BaseRotatedPillarBlock { public class BaseBarkBlock extends BaseRotatedPillarBlock {
public BaseBarkBlock(Properties settings) { public BaseBarkBlock(Properties settings) {
super(settings); super(settings);
} }
@Override @Override
protected Optional<String> createBlockPattern(ResourceLocation blockId) { protected Optional<String> createBlockPattern(ResourceLocation blockId) {
blockId = Registry.BLOCK.getKey(this); blockId = Registry.BLOCK.getKey(this);
return PatternsHelper.createJson(BasePatterns.BLOCK_BASE, replacePath(blockId)); return PatternsHelper.createJson(BasePatterns.BLOCK_BASE, replacePath(blockId));
} }
private ResourceLocation replacePath(ResourceLocation blockId) { private ResourceLocation replacePath(ResourceLocation blockId) {
String newPath = blockId.getPath().replace("_bark", "_log_side"); String newPath = blockId.getPath().replace("_bark", "_log_side");
return new ResourceLocation(blockId.getNamespace(), newPath); return new ResourceLocation(blockId.getNamespace(), newPath);

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -24,7 +17,6 @@ import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.monster.piglin.PiglinAi; import net.minecraft.world.entity.monster.piglin.PiglinAi;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.BarrelBlock; import net.minecraft.world.level.block.BarrelBlock;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
@ -33,6 +25,7 @@ import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.BlockHitResult;
import org.jetbrains.annotations.Nullable;
import ru.bclib.blockentities.BaseBarrelBlockEntity; import ru.bclib.blockentities.BaseBarrelBlockEntity;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
@ -40,16 +33,21 @@ import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import ru.bclib.registry.BaseBlockEntities; import ru.bclib.registry.BaseBlockEntities;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider { public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider {
public BaseBarrelBlock(Block source) { public BaseBarrelBlock(Block source) {
super(FabricBlockSettings.copyOf(source).noOcclusion()); super(FabricBlockSettings.copyOf(source).noOcclusion());
} }
@Override @Override
public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) {
return BaseBlockEntities.BARREL.create(blockPos, blockState); return BaseBlockEntities.BARREL.create(blockPos, blockState);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
@ -57,24 +55,24 @@ public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider {
drop.add(new ItemStack(this.asItem())); drop.add(new ItemStack(this.asItem()));
return drop; return drop;
} }
@Override @Override
public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) {
BlockHitResult hit) {
if (world.isClientSide) { if (world.isClientSide) {
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} else { }
else {
BlockEntity blockEntity = world.getBlockEntity(pos); BlockEntity blockEntity = world.getBlockEntity(pos);
if (blockEntity instanceof BaseBarrelBlockEntity) { if (blockEntity instanceof BaseBarrelBlockEntity) {
player.openMenu((BaseBarrelBlockEntity) blockEntity); player.openMenu((BaseBarrelBlockEntity) blockEntity);
player.awardStat(Stats.OPEN_BARREL); player.awardStat(Stats.OPEN_BARREL);
PiglinAi.angerNearbyPiglins(player, true); PiglinAi.angerNearbyPiglins(player, true);
} }
return InteractionResult.CONSUME; return InteractionResult.CONSUME;
} }
} }
@Override @Override
public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) {
BlockEntity blockEntity = world.getBlockEntity(pos); BlockEntity blockEntity = world.getBlockEntity(pos);
@ -82,15 +80,14 @@ public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider {
((BaseBarrelBlockEntity) blockEntity).tick(); ((BaseBarrelBlockEntity) blockEntity).tick();
} }
} }
@Override @Override
public RenderShape getRenderShape(BlockState state) { public RenderShape getRenderShape(BlockState state) {
return RenderShape.MODEL; return RenderShape.MODEL;
} }
@Override @Override
public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) {
ItemStack itemStack) {
if (itemStack.hasCustomHoverName()) { if (itemStack.hasCustomHoverName()) {
BlockEntity blockEntity = world.getBlockEntity(pos); BlockEntity blockEntity = world.getBlockEntity(pos);
if (blockEntity instanceof BaseBarrelBlockEntity) { if (blockEntity instanceof BaseBarrelBlockEntity) {
@ -98,41 +95,52 @@ public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider {
} }
} }
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation blockId) { public BlockModel getItemModel(ResourceLocation blockId) {
return getBlockModel(blockId, defaultBlockState()); return getBlockModel(blockId, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
Optional<String> pattern; Optional<String> pattern;
if (blockState.getValue(OPEN)) { if (blockState.getValue(OPEN)) {
pattern = PatternsHelper.createJson(BasePatterns.BLOCK_BARREL_OPEN, blockId); pattern = PatternsHelper.createJson(BasePatterns.BLOCK_BARREL_OPEN, blockId);
} else { }
else {
pattern = PatternsHelper.createJson(BasePatterns.BLOCK_BOTTOM_TOP, blockId); pattern = PatternsHelper.createJson(BasePatterns.BLOCK_BOTTOM_TOP, blockId);
} }
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
String open = blockState.getValue(OPEN) ? "_open" : ""; String open = blockState.getValue(OPEN) ? "_open" : "";
ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + open);
"block/" + stateId.getPath() + open);
registerBlockModel(stateId, modelId, blockState, modelCache); registerBlockModel(stateId, modelId, blockState, modelCache);
Direction facing = blockState.getValue(FACING); Direction facing = blockState.getValue(FACING);
BlockModelRotation rotation = BlockModelRotation.X0_Y0; BlockModelRotation rotation = BlockModelRotation.X0_Y0;
switch (facing) { switch (facing) {
case NORTH: rotation = BlockModelRotation.X90_Y0; break; case NORTH:
case EAST: rotation = BlockModelRotation.X90_Y90; break; rotation = BlockModelRotation.X90_Y0;
case SOUTH: rotation = BlockModelRotation.X90_Y180; break; break;
case WEST: rotation = BlockModelRotation.X90_Y270; break; case EAST:
case DOWN: rotation = BlockModelRotation.X180_Y0; break; rotation = BlockModelRotation.X90_Y90;
default: break; break;
case SOUTH:
rotation = BlockModelRotation.X90_Y180;
break;
case WEST:
rotation = BlockModelRotation.X90_Y270;
break;
case DOWN:
rotation = BlockModelRotation.X180_Y0;
break;
default:
break;
} }
return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false);
} }

View file

@ -1,8 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.renderer.block.model.BlockModel;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
@ -11,17 +8,20 @@ import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import java.util.Collections;
import java.util.List;
public class BaseBlock extends Block implements BlockModelProvider { public class BaseBlock extends Block implements BlockModelProvider {
public BaseBlock(Properties settings) { public BaseBlock(Properties settings) {
super(settings); super(settings);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this)); return Collections.singletonList(new ItemStack(this));
} }
@Override @Override
public BlockModel getItemModel(ResourceLocation blockId) { public BlockModel getItemModel(ResourceLocation blockId) {
return getBlockModel(blockId, defaultBlockState()); return getBlockModel(blockId, defaultBlockState());

View file

@ -6,19 +6,19 @@ import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
public class BaseBlockNotFull extends BaseBlock { public class BaseBlockNotFull extends BaseBlock {
public BaseBlockNotFull(Properties settings) { public BaseBlockNotFull(Properties settings) {
super(settings); super(settings);
} }
public boolean canSuffocate(BlockState state, BlockGetter view, BlockPos pos) { public boolean canSuffocate(BlockState state, BlockGetter view, BlockPos pos) {
return false; return false;
} }
public boolean isSimpleFullBlock(BlockState state, BlockGetter view, BlockPos pos) { public boolean isSimpleFullBlock(BlockState state, BlockGetter view, BlockPos pos) {
return false; return false;
} }
public boolean allowsSpawning(BlockState state, BlockGetter view, BlockPos pos, EntityType<?> type) { public boolean allowsSpawning(BlockState state, BlockGetter view, BlockPos pos, EntityType<?> type) {
return false; return false;
} }

View file

@ -1,26 +1,25 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.BaseEntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import java.util.Collections;
import java.util.List;
public class BaseBlockWithEntity extends BaseEntityBlock { public class BaseBlockWithEntity extends BaseEntityBlock {
public BaseBlockWithEntity(Properties settings) { public BaseBlockWithEntity(Properties settings) {
super(settings); super(settings);
} }
@Override @Override
public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) {
return null; return null;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {

View file

@ -1,11 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -19,10 +13,15 @@ import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
public class BaseBookshelfBlock extends BaseBlock { public class BaseBookshelfBlock extends BaseBlock {
public BaseBookshelfBlock(Block source) { public BaseBookshelfBlock(Block source) {
super(FabricBlockSettings.copyOf(source)); super(FabricBlockSettings.copyOf(source));
@ -39,14 +38,14 @@ public class BaseBookshelfBlock extends BaseBlock {
} }
return Collections.singletonList(new ItemStack(Items.BOOK, 3)); return Collections.singletonList(new ItemStack(Items.BOOK, 3));
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_BOOKSHELF, replacePath(blockId)); Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_BOOKSHELF, replacePath(blockId));
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
private ResourceLocation replacePath(ResourceLocation blockId) { private ResourceLocation replacePath(ResourceLocation blockId) {
String newPath = blockId.getPath().replace("_bookshelf", ""); String newPath = blockId.getPath().replace("_bookshelf", "");
return new ResourceLocation(blockId.getNamespace(), newPath); return new ResourceLocation(blockId.getNamespace(), newPath);

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.renderer.block.model.BlockModel;
@ -20,26 +13,32 @@ import net.minecraft.world.level.block.ButtonBlock;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.AttachFace; import net.minecraft.world.level.block.state.properties.AttachFace;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public abstract class BaseButtonBlock extends ButtonBlock implements BlockModelProvider { public abstract class BaseButtonBlock extends ButtonBlock implements BlockModelProvider {
private final Block parent; private final Block parent;
protected BaseButtonBlock(Block parent, Properties properties, boolean sensitive) { protected BaseButtonBlock(Block parent, Properties properties, boolean sensitive) {
super(sensitive, properties); super(sensitive, properties);
this.parent = parent; this.parent = parent;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this)); return Collections.singletonList(new ItemStack(this));
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation blockId) { public BlockModel getItemModel(ResourceLocation blockId) {
@ -47,38 +46,53 @@ public abstract class BaseButtonBlock extends ButtonBlock implements BlockModelP
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.ITEM_BUTTON, parentId); Optional<String> pattern = PatternsHelper.createJson(BasePatterns.ITEM_BUTTON, parentId);
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) {
ResourceLocation parentId = Registry.BLOCK.getKey(parent); ResourceLocation parentId = Registry.BLOCK.getKey(parent);
Optional<String> pattern = blockState.getValue(POWERED) ? Optional<String> pattern = blockState.getValue(POWERED) ? PatternsHelper.createJson(BasePatterns.BLOCK_BUTTON_PRESSED, parentId) : PatternsHelper.createJson(BasePatterns.BLOCK_BUTTON, parentId);
PatternsHelper.createJson(BasePatterns.BLOCK_BUTTON_PRESSED, parentId) :
PatternsHelper.createJson(BasePatterns.BLOCK_BUTTON, parentId);
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
String powered = blockState.getValue(POWERED) ? "_powered" : ""; String powered = blockState.getValue(POWERED) ? "_powered" : "";
ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + powered);
"block/" + stateId.getPath() + powered);
registerBlockModel(stateId, modelId, blockState, modelCache); registerBlockModel(stateId, modelId, blockState, modelCache);
AttachFace face = blockState.getValue(FACE); AttachFace face = blockState.getValue(FACE);
boolean isCeiling = face == AttachFace.CEILING; boolean isCeiling = face == AttachFace.CEILING;
int x = 0, y = 0; int x = 0, y = 0;
switch (face) { switch (face) {
case CEILING: x = 180; break; case CEILING:
case WALL: x = 90; break; x = 180;
default: break; break;
case WALL:
x = 90;
break;
default:
break;
} }
switch (blockState.getValue(FACING)) { switch (blockState.getValue(FACING)) {
case NORTH: if (isCeiling) { y = 180; } break; case NORTH:
case EAST: y = isCeiling ? 270 : 90; break; if (isCeiling) {
case SOUTH: if(!isCeiling) { y = 180; } break; y = 180;
case WEST: y = isCeiling ? 90 : 270; break; }
default: break; break;
case EAST:
y = isCeiling ? 270 : 90;
break;
case SOUTH:
if (!isCeiling) {
y = 180;
}
break;
case WEST:
y = isCeiling ? 90 : 270;
break;
default:
break;
} }
BlockModelRotation rotation = BlockModelRotation.by(x, y); BlockModelRotation rotation = BlockModelRotation.by(x, y);
return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), face == AttachFace.WALL); return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), face == AttachFace.WALL);

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -20,6 +13,7 @@ import net.minecraft.world.level.block.ChainBlock;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.material.MaterialColor;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
@ -27,40 +21,44 @@ import ru.bclib.client.models.PatternsHelper;
import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.client.render.BCLRenderLayer;
import ru.bclib.interfaces.IRenderTyped; import ru.bclib.interfaces.IRenderTyped;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class BaseChainBlock extends ChainBlock implements BlockModelProvider, IRenderTyped { public class BaseChainBlock extends ChainBlock implements BlockModelProvider, IRenderTyped {
public BaseChainBlock(MaterialColor color) { public BaseChainBlock(MaterialColor color) {
super(FabricBlockSettings.copyOf(Blocks.CHAIN).mapColor(color)); super(FabricBlockSettings.copyOf(Blocks.CHAIN).mapColor(color));
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this)); return Collections.singletonList(new ItemStack(this));
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation blockId) { public BlockModel getItemModel(ResourceLocation blockId) {
return ModelsHelper.createItemModel(blockId); return ModelsHelper.createItemModel(blockId);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_CHAIN, blockId); Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_CHAIN, blockId);
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
Direction.Axis axis = blockState.getValue(AXIS); Direction.Axis axis = blockState.getValue(AXIS);
ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath());
"block/" + stateId.getPath());
registerBlockModel(stateId, modelId, blockState, modelCache); registerBlockModel(stateId, modelId, blockState, modelCache);
return ModelsHelper.createRotatedModel(modelId, axis); return ModelsHelper.createRotatedModel(modelId, axis);
} }
@Override @Override
public BCLRenderLayer getRenderLayer() { public BCLRenderLayer getRenderLayer() {
return BCLRenderLayer.CUTOUT; return BCLRenderLayer.CUTOUT;

View file

@ -1,30 +1,28 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.List;
import java.util.Optional;
import net.minecraft.core.BlockPos;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.renderer.block.model.BlockModel;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.ChestBlock; import net.minecraft.world.level.block.ChestBlock;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import ru.bclib.registry.BaseBlockEntities; import ru.bclib.registry.BaseBlockEntities;
import java.util.List;
import java.util.Optional;
public class BaseChestBlock extends ChestBlock implements BlockModelProvider { public class BaseChestBlock extends ChestBlock implements BlockModelProvider {
private final Block parent; private final Block parent;
@ -37,23 +35,22 @@ public class BaseChestBlock extends ChestBlock implements BlockModelProvider {
public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) {
return BaseBlockEntities.CHEST.create(blockPos, blockState); return BaseBlockEntities.CHEST.create(blockPos, blockState);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
{
List<ItemStack> drop = super.getDrops(state, builder); List<ItemStack> drop = super.getDrops(state, builder);
drop.add(new ItemStack(this.asItem())); drop.add(new ItemStack(this.asItem()));
return drop; return drop;
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation blockId) { public BlockModel getItemModel(ResourceLocation blockId) {
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.ITEM_CHEST, blockId); Optional<String> pattern = PatternsHelper.createJson(BasePatterns.ITEM_CHEST, blockId);
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) {

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -18,56 +11,63 @@ import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.ComposterBlock; import net.minecraft.world.level.block.ComposterBlock;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.ModelsHelper.MultiPartBuilder; import ru.bclib.client.models.ModelsHelper.MultiPartBuilder;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class BaseComposterBlock extends ComposterBlock implements BlockModelProvider { public class BaseComposterBlock extends ComposterBlock implements BlockModelProvider {
public BaseComposterBlock(Block source) { public BaseComposterBlock(Block source) {
super(FabricBlockSettings.copyOf(source)); super(FabricBlockSettings.copyOf(source));
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this.asItem())); return Collections.singletonList(new ItemStack(this.asItem()));
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation resourceLocation) { public BlockModel getItemModel(ResourceLocation resourceLocation) {
return getBlockModel(resourceLocation, defaultBlockState()); return getBlockModel(resourceLocation, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_COMPOSTER, blockId); Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_COMPOSTER, blockId);
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath()); ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath());
registerBlockModel(stateId, modelId, blockState, modelCache); registerBlockModel(stateId, modelId, blockState, modelCache);
MultiPartBuilder builder = MultiPartBuilder.create(stateDefinition); MultiPartBuilder builder = MultiPartBuilder.create(stateDefinition);
LEVEL.getPossibleValues().forEach(level -> { LEVEL.getPossibleValues().forEach(level -> {
if (level > 0) { if (level > 0) {
ResourceLocation contentId; ResourceLocation contentId;
if (level > 7) { if (level > 7) {
contentId = new ResourceLocation("block/composter_contents_ready"); contentId = new ResourceLocation("block/composter_contents_ready");
} else { }
else {
contentId = new ResourceLocation("block/composter_contents" + level); contentId = new ResourceLocation("block/composter_contents" + level);
} }
builder.part(contentId).setCondition(state -> state.getValue(LEVEL).equals(level)).add(); builder.part(contentId).setCondition(state -> state.getValue(LEVEL).equals(level)).add();
} }
}); });
builder.part(modelId).add(); builder.part(modelId).add();
return builder.build(); return builder.build();
} }
} }

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -17,34 +10,41 @@ import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.CraftingTableBlock; import net.minecraft.world.level.block.CraftingTableBlock;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
public class BaseCraftingTableBlock extends CraftingTableBlock implements BlockModelProvider { public class BaseCraftingTableBlock extends CraftingTableBlock implements BlockModelProvider {
public BaseCraftingTableBlock(Block source) { public BaseCraftingTableBlock(Block source) {
super(FabricBlockSettings.copyOf(source)); super(FabricBlockSettings.copyOf(source));
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this.asItem())); return Collections.singletonList(new ItemStack(this.asItem()));
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation resourceLocation) { public BlockModel getItemModel(ResourceLocation resourceLocation) {
return getBlockModel(resourceLocation, defaultBlockState()); return getBlockModel(resourceLocation, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
String blockName = blockId.getPath(); String blockName = blockId.getPath();
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_SIDED, new HashMap<String, String>() { Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_SIDED, new HashMap<String, String>() {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
{ {
put("%modid%", blockId.getNamespace()); put("%modid%", blockId.getNamespace());
put("%particle%", blockName + "_front"); put("%particle%", blockName + "_front");

View file

@ -1,11 +1,6 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
@ -31,6 +26,10 @@ import net.minecraft.world.phys.shapes.VoxelShape;
import ru.bclib.util.BlocksHelper; import ru.bclib.util.BlocksHelper;
import ru.bclib.util.MHelper; import ru.bclib.util.MHelper;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class BaseCropBlock extends BasePlantBlock { public class BaseCropBlock extends BasePlantBlock {
private static final VoxelShape SHAPE = Block.box(2, 0, 2, 14, 14, 14); private static final VoxelShape SHAPE = Block.box(2, 0, 2, 14, 14, 14);
public static final IntegerProperty AGE = IntegerProperty.create("age", 0, 3); public static final IntegerProperty AGE = IntegerProperty.create("age", 0, 3);
@ -39,12 +38,7 @@ public class BaseCropBlock extends BasePlantBlock {
private final Item drop; private final Item drop;
public BaseCropBlock(Item drop, Block... terrain) { public BaseCropBlock(Item drop, Block... terrain) {
super(FabricBlockSettings.of(Material.PLANT) super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.HOES).breakByHand(true).sound(SoundType.GRASS).randomTicks().noCollission());
.breakByTool(FabricToolTags.HOES)
.breakByHand(true)
.sound(SoundType.GRASS)
.randomTicks()
.noCollission());
this.drop = drop; this.drop = drop;
this.terrain = terrain; this.terrain = terrain;
this.registerDefaultState(defaultBlockState().setValue(AGE, 0)); this.registerDefaultState(defaultBlockState().setValue(AGE, 0));
@ -57,7 +51,7 @@ public class BaseCropBlock extends BasePlantBlock {
@Override @Override
protected boolean isTerrain(BlockState state) { protected boolean isTerrain(BlockState state) {
for (Block block: terrain) { for (Block block : terrain) {
if (state.is(block)) { if (state.is(block)) {
return true; return true;
} }
@ -106,7 +100,7 @@ public class BaseCropBlock extends BasePlantBlock {
public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) {
return state.getValue(AGE) < 3; return state.getValue(AGE) < 3;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) {

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -23,6 +16,7 @@ import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.DoorHingeSide; import net.minecraft.world.level.block.state.properties.DoorHingeSide;
import net.minecraft.world.level.block.state.properties.DoubleBlockHalf; import net.minecraft.world.level.block.state.properties.DoubleBlockHalf;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
@ -30,25 +24,29 @@ import ru.bclib.client.models.PatternsHelper;
import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.client.render.BCLRenderLayer;
import ru.bclib.interfaces.IRenderTyped; import ru.bclib.interfaces.IRenderTyped;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModelProvider { public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModelProvider {
public BaseDoorBlock(Block source) { public BaseDoorBlock(Block source) {
super(FabricBlockSettings.copyOf(source).strength(3F, 3F).noOcclusion()); super(FabricBlockSettings.copyOf(source).strength(3F, 3F).noOcclusion());
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
if (state.getValue(HALF) == DoubleBlockHalf.LOWER) if (state.getValue(HALF) == DoubleBlockHalf.LOWER)
return Collections.singletonList(new ItemStack(this.asItem())); return Collections.singletonList(new ItemStack(this.asItem()));
else else return Collections.emptyList();
return Collections.emptyList();
} }
@Override @Override
public BCLRenderLayer getRenderLayer() { public BCLRenderLayer getRenderLayer() {
return BCLRenderLayer.CUTOUT; return BCLRenderLayer.CUTOUT;
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) {
@ -64,11 +62,12 @@ public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModel
case TOP: case TOP:
pattern = PatternsHelper.createJson(BasePatterns.BLOCK_DOOR_TOP, resourceLocation); pattern = PatternsHelper.createJson(BasePatterns.BLOCK_DOOR_TOP, resourceLocation);
break; break;
default: break; default:
break;
} }
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
@ -81,23 +80,27 @@ public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModel
case EAST: case EAST:
if (hinge && open) { if (hinge && open) {
rotation = BlockModelRotation.X0_Y90; rotation = BlockModelRotation.X0_Y90;
} else if (open) { }
else if (open) {
rotation = BlockModelRotation.X0_Y270; rotation = BlockModelRotation.X0_Y270;
} }
break; break;
case SOUTH: case SOUTH:
if (!hinge && !open || hinge && !open) { if (!hinge && !open || hinge && !open) {
rotation = BlockModelRotation.X0_Y90; rotation = BlockModelRotation.X0_Y90;
} else if (hinge) { }
else if (hinge) {
rotation = BlockModelRotation.X0_Y180; rotation = BlockModelRotation.X0_Y180;
} }
break; break;
case WEST: case WEST:
if (!hinge && !open || hinge && !open) { if (!hinge && !open || hinge && !open) {
rotation = BlockModelRotation.X0_Y180; rotation = BlockModelRotation.X0_Y180;
} else if (hinge) { }
else if (hinge) {
rotation = BlockModelRotation.X0_Y270; rotation = BlockModelRotation.X0_Y270;
} else { }
else {
rotation = BlockModelRotation.X0_Y90; rotation = BlockModelRotation.X0_Y90;
} }
break; break;
@ -105,17 +108,17 @@ public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModel
default: default:
if (!hinge && !open || hinge && !open) { if (!hinge && !open || hinge && !open) {
rotation = BlockModelRotation.X0_Y270; rotation = BlockModelRotation.X0_Y270;
} else if (!hinge) { }
else if (!hinge) {
rotation = BlockModelRotation.X0_Y180; rotation = BlockModelRotation.X0_Y180;
} }
break; break;
} }
ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_" + doorType);
"block/" + stateId.getPath() + "_" + doorType);
registerBlockModel(stateId, modelId, blockState, modelCache); registerBlockModel(stateId, modelId, blockState, modelCache);
return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false);
} }
protected DoorType getDoorType(BlockState blockState) { protected DoorType getDoorType(BlockState blockState) {
boolean isHinge = isHinge(blockState.getValue(HINGE), blockState.getValue(OPEN)); boolean isHinge = isHinge(blockState.getValue(HINGE), blockState.getValue(OPEN));
switch (blockState.getValue(HALF)) { switch (blockState.getValue(HALF)) {
@ -128,34 +131,30 @@ public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModel
} }
return DoorType.BOTTOM; return DoorType.BOTTOM;
} }
private boolean isHinge(DoorHingeSide hingeSide, boolean open) { private boolean isHinge(DoorHingeSide hingeSide, boolean open) {
boolean isHinge = hingeSide == DoorHingeSide.RIGHT; boolean isHinge = hingeSide == DoorHingeSide.RIGHT;
return isHinge && !open || !isHinge && open; return isHinge && !open || !isHinge && open;
} }
protected enum DoorType implements StringRepresentable { protected enum DoorType implements StringRepresentable {
BOTTOM_HINGE("bottom_hinge"), BOTTOM_HINGE("bottom_hinge"), TOP_HINGE("top_hinge"), BOTTOM("bottom"), TOP("top");
TOP_HINGE("top_hinge"),
BOTTOM("bottom"),
TOP("top");
private final String name; private final String name;
DoorType(String name) { DoorType(String name) {
this.name = name; this.name = name;
} }
public boolean isHinge() { public boolean isHinge() {
return this == BOTTOM_HINGE || return this == BOTTOM_HINGE || this == TOP_HINGE;
this == TOP_HINGE;
} }
@Override @Override
public String toString() { public String toString() {
return getSerializedName(); return getSerializedName();
} }
@Override @Override
public String getSerializedName() { public String getSerializedName() {
return name; return name;

View file

@ -1,10 +1,6 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.List;
import java.util.Random;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
@ -38,6 +34,9 @@ import ru.bclib.client.render.BCLRenderLayer;
import ru.bclib.interfaces.IRenderTyped; import ru.bclib.interfaces.IRenderTyped;
import ru.bclib.util.BlocksHelper; import ru.bclib.util.BlocksHelper;
import java.util.List;
import java.util.Random;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock {
private static final VoxelShape SHAPE = Block.box(4, 2, 4, 12, 16, 12); private static final VoxelShape SHAPE = Block.box(4, 2, 4, 12, 16, 12);
@ -45,21 +44,12 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements I
public static final BooleanProperty TOP = BooleanProperty.create("top"); public static final BooleanProperty TOP = BooleanProperty.create("top");
public BaseDoublePlantBlock() { public BaseDoublePlantBlock() {
super(FabricBlockSettings.of(Material.PLANT) super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).noCollission());
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.sound(SoundType.WET_GRASS)
.noCollission());
this.registerDefaultState(this.stateDefinition.any().setValue(TOP, false)); this.registerDefaultState(this.stateDefinition.any().setValue(TOP, false));
} }
public BaseDoublePlantBlock(int light) { public BaseDoublePlantBlock(int light) {
super(FabricBlockSettings.of(Material.PLANT) super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).lightLevel((state) -> state.getValue(TOP) ? light : 0).noCollission());
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.sound(SoundType.WET_GRASS)
.lightLevel((state) -> state.getValue(TOP) ? light : 0)
.noCollission());
this.registerDefaultState(this.stateDefinition.any().setValue(TOP, false)); this.registerDefaultState(this.stateDefinition.any().setValue(TOP, false));
} }
@ -67,18 +57,18 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements I
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> stateManager) { protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> stateManager) {
stateManager.add(TOP, ROTATION); stateManager.add(TOP, ROTATION);
} }
@Override @Override
public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) {
Vec3 vec3d = state.getOffset(view, pos); Vec3 vec3d = state.getOffset(view, pos);
return SHAPE.move(vec3d.x, vec3d.y, vec3d.z); return SHAPE.move(vec3d.x, vec3d.y, vec3d.z);
} }
@Override @Override
public BlockBehaviour.OffsetType getOffsetType() { public BlockBehaviour.OffsetType getOffsetType() {
return BlockBehaviour.OffsetType.XZ; return BlockBehaviour.OffsetType.XZ;
} }
@Override @Override
public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) {
BlockState down = world.getBlockState(pos.below()); BlockState down = world.getBlockState(pos.below());
@ -91,7 +81,7 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements I
BlockState up = world.getBlockState(pos.above()); BlockState up = world.getBlockState(pos.above());
return state.getValue(TOP) ? down.getBlock() == this : isTerrain(down) && (up.getBlock() == this); return state.getValue(TOP) ? down.getBlock() == this : isTerrain(down) && (up.getBlock() == this);
} }
protected abstract boolean isTerrain(BlockState state); protected abstract boolean isTerrain(BlockState state);
@Override @Override
@ -123,17 +113,17 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements I
public BCLRenderLayer getRenderLayer() { public BCLRenderLayer getRenderLayer() {
return BCLRenderLayer.CUTOUT; return BCLRenderLayer.CUTOUT;
} }
@Override @Override
public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) { public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) {
return true; return true;
} }
@Override @Override
public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) {
return true; return true;
} }
@Override @Override
public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) {
ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this)); ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this));

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -20,12 +13,18 @@ import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.FenceBlock; import net.minecraft.world.level.block.FenceBlock;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.ModelsHelper.MultiPartBuilder; import ru.bclib.client.models.ModelsHelper.MultiPartBuilder;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class BaseFenceBlock extends FenceBlock implements BlockModelProvider { public class BaseFenceBlock extends FenceBlock implements BlockModelProvider {
private final Block parent; private final Block parent;
@ -33,13 +32,13 @@ public class BaseFenceBlock extends FenceBlock implements BlockModelProvider {
super(FabricBlockSettings.copyOf(source).noOcclusion()); super(FabricBlockSettings.copyOf(source).noOcclusion());
this.parent = source; this.parent = source;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this)); return Collections.singletonList(new ItemStack(this));
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation blockId) { public BlockModel getItemModel(ResourceLocation blockId) {
@ -47,7 +46,7 @@ public class BaseFenceBlock extends FenceBlock implements BlockModelProvider {
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.ITEM_FENCE, parentId); Optional<String> pattern = PatternsHelper.createJson(BasePatterns.ITEM_FENCE, parentId);
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
@ -62,27 +61,22 @@ public class BaseFenceBlock extends FenceBlock implements BlockModelProvider {
} }
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_post");
"block/" + stateId.getPath() + "_post"); ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_side");
ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(),
"block/" + stateId.getPath() + "_side");
registerBlockModel(postId, postId, blockState, modelCache); registerBlockModel(postId, postId, blockState, modelCache);
registerBlockModel(sideId, sideId, blockState, modelCache); registerBlockModel(sideId, sideId, blockState, modelCache);
MultiPartBuilder builder = MultiPartBuilder.create(stateDefinition); MultiPartBuilder builder = MultiPartBuilder.create(stateDefinition);
builder.part(sideId).setCondition(state -> state.getValue(NORTH)).setUVLock(true).add(); builder.part(sideId).setCondition(state -> state.getValue(NORTH)).setUVLock(true).add();
builder.part(sideId).setCondition(state -> state.getValue(EAST)) builder.part(sideId).setCondition(state -> state.getValue(EAST)).setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add();
.setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); builder.part(sideId).setCondition(state -> state.getValue(SOUTH)).setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add();
builder.part(sideId).setCondition(state -> state.getValue(SOUTH)) builder.part(sideId).setCondition(state -> state.getValue(WEST)).setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add();
.setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add();
builder.part(sideId).setCondition(state -> state.getValue(WEST))
.setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add();
builder.part(postId).add(); builder.part(postId).add();
return builder.build(); return builder.build();
} }
} }

View file

@ -41,7 +41,7 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider
public BaseFurnaceBlock(Block source) { public BaseFurnaceBlock(Block source) {
super(FabricBlockSettings.copyOf(source).luminance(state -> state.getValue(LIT) ? 13 : 0)); super(FabricBlockSettings.copyOf(source).luminance(state -> state.getValue(LIT) ? 13 : 0));
} }
@Override @Override
public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) {
return new BaseFurnaceBlockEntity(blockPos, blockState); return new BaseFurnaceBlockEntity(blockPos, blockState);
@ -55,7 +55,7 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider
player.awardStat(Stats.INTERACT_WITH_FURNACE); player.awardStat(Stats.INTERACT_WITH_FURNACE);
} }
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
@ -69,34 +69,34 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider
textures.put("%front%", blockName + "_front_on"); textures.put("%front%", blockName + "_front_on");
textures.put("%glow%", blockName + "_glow"); textures.put("%glow%", blockName + "_glow");
pattern = PatternsHelper.createJson(BasePatterns.BLOCK_FURNACE_LIT, textures); pattern = PatternsHelper.createJson(BasePatterns.BLOCK_FURNACE_LIT, textures);
} else { }
else {
textures.put("%front%", blockName + "_front"); textures.put("%front%", blockName + "_front");
pattern = PatternsHelper.createJson(BasePatterns.BLOCK_FURNACE, textures); pattern = PatternsHelper.createJson(BasePatterns.BLOCK_FURNACE, textures);
} }
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation resourceLocation) { public BlockModel getItemModel(ResourceLocation resourceLocation) {
return getBlockModel(resourceLocation, defaultBlockState()); return getBlockModel(resourceLocation, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
String lit = blockState.getValue(LIT) ? "_lit" : ""; String lit = blockState.getValue(LIT) ? "_lit" : "";
ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + lit);
"block/" + stateId.getPath() + lit);
registerBlockModel(stateId, modelId, blockState, modelCache); registerBlockModel(stateId, modelId, blockState, modelCache);
return ModelsHelper.createFacingModel(modelId, blockState.getValue(FACING), false, true); return ModelsHelper.createFacingModel(modelId, blockState.getValue(FACING), false, true);
} }
@Override @Override
public BCLRenderLayer getRenderLayer() { public BCLRenderLayer getRenderLayer() {
return BCLRenderLayer.CUTOUT; return BCLRenderLayer.CUTOUT;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
@ -110,13 +110,13 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider
} }
return drop; return drop;
} }
@Override @Override
@Nullable @Nullable
public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState blockState, BlockEntityType<T> blockEntityType) { public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState blockState, BlockEntityType<T> blockEntityType) {
return createFurnaceTicker(level, blockEntityType, BaseBlockEntities.FURNACE); return createFurnaceTicker(level, blockEntityType, BaseBlockEntities.FURNACE);
} }
@Nullable @Nullable
protected static <T extends BlockEntity> BlockEntityTicker<T> createFurnaceTicker(Level level, BlockEntityType<T> blockEntityType, BlockEntityType<? extends AbstractFurnaceBlockEntity> blockEntityType2) { protected static <T extends BlockEntity> BlockEntityTicker<T> createFurnaceTicker(Level level, BlockEntityType<T> blockEntityType, BlockEntityType<? extends AbstractFurnaceBlockEntity> blockEntityType2) {
return level.isClientSide ? null : createTickerHelper(blockEntityType, blockEntityType2, AbstractFurnaceBlockEntity::serverTick); return level.isClientSide ? null : createTickerHelper(blockEntityType, blockEntityType2, AbstractFurnaceBlockEntity::serverTick);

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -19,11 +12,17 @@ import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.FenceGateBlock; import net.minecraft.world.level.block.FenceGateBlock;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider { public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider {
private final Block parent; private final Block parent;
@ -31,19 +30,19 @@ public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider
super(FabricBlockSettings.copyOf(source).noOcclusion()); super(FabricBlockSettings.copyOf(source).noOcclusion());
this.parent = source; this.parent = source;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this)); return Collections.singletonList(new ItemStack(this));
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation resourceLocation) { public BlockModel getItemModel(ResourceLocation resourceLocation) {
return getBlockModel(resourceLocation, defaultBlockState()); return getBlockModel(resourceLocation, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
@ -52,23 +51,21 @@ public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider
ResourceLocation parentId = Registry.BLOCK.getKey(parent); ResourceLocation parentId = Registry.BLOCK.getKey(parent);
Optional<String> pattern; Optional<String> pattern;
if (inWall) { if (inWall) {
pattern = isOpen ? PatternsHelper.createJson(BasePatterns.BLOCK_GATE_OPEN_WALL, parentId) : pattern = isOpen ? PatternsHelper.createJson(BasePatterns.BLOCK_GATE_OPEN_WALL, parentId) : PatternsHelper.createJson(BasePatterns.BLOCK_GATE_CLOSED_WALL, parentId);
PatternsHelper.createJson(BasePatterns.BLOCK_GATE_CLOSED_WALL, parentId); }
} else { else {
pattern = isOpen ? PatternsHelper.createJson(BasePatterns.BLOCK_GATE_OPEN, parentId) : pattern = isOpen ? PatternsHelper.createJson(BasePatterns.BLOCK_GATE_OPEN, parentId) : PatternsHelper.createJson(BasePatterns.BLOCK_GATE_CLOSED, parentId);
PatternsHelper.createJson(BasePatterns.BLOCK_GATE_CLOSED, parentId);
} }
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
boolean inWall = blockState.getValue(IN_WALL); boolean inWall = blockState.getValue(IN_WALL);
boolean isOpen = blockState.getValue(OPEN); boolean isOpen = blockState.getValue(OPEN);
String state = "" + (inWall ? "_wall" : "") + (isOpen ? "_open" : "_closed"); String state = "" + (inWall ? "_wall" : "") + (isOpen ? "_open" : "_closed");
ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + state);
"block/" + stateId.getPath() + state);
registerBlockModel(stateId, modelId, blockState, modelCache); registerBlockModel(stateId, modelId, blockState, modelCache);
return ModelsHelper.createFacingModel(modelId, blockState.getValue(FACING), true, false); return ModelsHelper.createFacingModel(modelId, blockState.getValue(FACING), true, false);
} }

View file

@ -1,10 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -31,6 +26,7 @@ import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids; import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
@ -39,6 +35,9 @@ import ru.bclib.client.render.BCLRenderLayer;
import ru.bclib.interfaces.IRenderTyped; import ru.bclib.interfaces.IRenderTyped;
import ru.bclib.util.BlocksHelper; import ru.bclib.util.BlocksHelper;
import java.util.Map;
import java.util.Optional;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, BlockModelProvider { public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, BlockModelProvider {
public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING; public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING;
@ -47,17 +46,17 @@ public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, B
protected static final VoxelShape WEST_SHAPE = Block.box(13.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); protected static final VoxelShape WEST_SHAPE = Block.box(13.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D);
protected static final VoxelShape SOUTH_SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 3.0D); protected static final VoxelShape SOUTH_SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 3.0D);
protected static final VoxelShape NORTH_SHAPE = Block.box(0.0D, 0.0D, 13.0D, 16.0D, 16.0D, 16.0D); protected static final VoxelShape NORTH_SHAPE = Block.box(0.0D, 0.0D, 13.0D, 16.0D, 16.0D, 16.0D);
public BaseLadderBlock(Block block) { public BaseLadderBlock(Block block) {
super(FabricBlockSettings.copyOf(block).noOcclusion()); super(FabricBlockSettings.copyOf(block).noOcclusion());
} }
@Override @Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> stateManager) { protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> stateManager) {
stateManager.add(FACING); stateManager.add(FACING);
stateManager.add(WATERLOGGED); stateManager.add(WATERLOGGED);
} }
@Override @Override
public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) {
return switch (state.getValue(FACING)) { return switch (state.getValue(FACING)) {
@ -67,32 +66,32 @@ public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, B
default -> NORTH_SHAPE; default -> NORTH_SHAPE;
}; };
} }
private boolean canPlaceOn(BlockGetter world, BlockPos pos, Direction side) { private boolean canPlaceOn(BlockGetter world, BlockPos pos, Direction side) {
BlockState blockState = world.getBlockState(pos); BlockState blockState = world.getBlockState(pos);
return !blockState.isSignalSource() && blockState.isFaceSturdy(world, pos, side); return !blockState.isSignalSource() && blockState.isFaceSturdy(world, pos, side);
} }
@Override @Override
public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) {
Direction direction = state.getValue(FACING); Direction direction = state.getValue(FACING);
return canPlaceOn(world, pos.relative(direction.getOpposite()), direction); return canPlaceOn(world, pos.relative(direction.getOpposite()), direction);
} }
@Override @Override
public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) {
LevelAccessor world, BlockPos pos, BlockPos neighborPos) {
if (facing.getOpposite() == state.getValue(FACING) && !state.canSurvive(world, pos)) { if (facing.getOpposite() == state.getValue(FACING) && !state.canSurvive(world, pos)) {
return Blocks.AIR.defaultBlockState(); return Blocks.AIR.defaultBlockState();
} else { }
else {
if (state.getValue(WATERLOGGED)) { if (state.getValue(WATERLOGGED)) {
world.getLiquidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world)); world.getLiquidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world));
} }
return super.updateShape(state, facing, neighborState, world, pos, neighborPos); return super.updateShape(state, facing, neighborState, world, pos, neighborPos);
} }
} }
@Override @Override
public BlockState getStateForPlacement(BlockPlaceContext ctx) { public BlockState getStateForPlacement(BlockPlaceContext ctx) {
BlockState blockState; BlockState blockState;
@ -102,13 +101,13 @@ public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, B
return null; return null;
} }
} }
blockState = defaultBlockState(); blockState = defaultBlockState();
LevelReader worldView = ctx.getLevel(); LevelReader worldView = ctx.getLevel();
BlockPos blockPos = ctx.getClickedPos(); BlockPos blockPos = ctx.getClickedPos();
FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos()); FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos());
Direction[] directions = ctx.getNearestLookingDirections(); Direction[] directions = ctx.getNearestLookingDirections();
for (Direction direction : directions) { for (Direction direction : directions) {
if (direction.getAxis().isHorizontal()) { if (direction.getAxis().isHorizontal()) {
blockState = blockState.setValue(FACING, direction.getOpposite()); blockState = blockState.setValue(FACING, direction.getOpposite());
@ -117,43 +116,43 @@ public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, B
} }
} }
} }
return null; return null;
} }
@Override @Override
public BlockState rotate(BlockState state, Rotation rotation) { public BlockState rotate(BlockState state, Rotation rotation) {
return BlocksHelper.rotateHorizontal(state, rotation, FACING); return BlocksHelper.rotateHorizontal(state, rotation, FACING);
} }
@Override @Override
public BlockState mirror(BlockState state, Mirror mirror) { public BlockState mirror(BlockState state, Mirror mirror) {
return BlocksHelper.mirrorHorizontal(state, mirror, FACING); return BlocksHelper.mirrorHorizontal(state, mirror, FACING);
} }
@Override @Override
public FluidState getFluidState(BlockState state) { public FluidState getFluidState(BlockState state) {
return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state);
} }
@Override @Override
public BCLRenderLayer getRenderLayer() { public BCLRenderLayer getRenderLayer() {
return BCLRenderLayer.CUTOUT; return BCLRenderLayer.CUTOUT;
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation blockId) { public BlockModel getItemModel(ResourceLocation blockId) {
return ModelsHelper.createBlockItem(blockId); return ModelsHelper.createBlockItem(blockId);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_LADDER, blockId); Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_LADDER, blockId);
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {

View file

@ -1,10 +1,6 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags;
import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.renderer.block.model.BlockModel;
@ -24,38 +20,27 @@ import ru.bclib.client.render.BCLRenderLayer;
import ru.bclib.interfaces.IRenderTyped; import ru.bclib.interfaces.IRenderTyped;
import ru.bclib.util.MHelper; import ru.bclib.util.MHelper;
import java.util.Collections;
import java.util.List;
public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, IRenderTyped { public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, IRenderTyped {
private final Block sapling; private final Block sapling;
public BaseLeavesBlock(Block sapling, MaterialColor color) { public BaseLeavesBlock(Block sapling, MaterialColor color) {
super(FabricBlockSettings.copyOf(Blocks.OAK_LEAVES) super(FabricBlockSettings.copyOf(Blocks.OAK_LEAVES).mapColor(color).breakByTool(FabricToolTags.HOES).breakByTool(FabricToolTags.SHEARS).breakByHand(true).isValidSpawn((state, world, pos, type) -> false).isSuffocating((state, world, pos) -> false).isViewBlocking((state, world, pos) -> false));
.mapColor(color)
.breakByTool(FabricToolTags.HOES)
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.isValidSpawn((state, world, pos, type) -> false)
.isSuffocating((state, world, pos) -> false)
.isViewBlocking((state, world, pos) -> false));
this.sapling = sapling; this.sapling = sapling;
} }
public BaseLeavesBlock(Block sapling, MaterialColor color, int light) { public BaseLeavesBlock(Block sapling, MaterialColor color, int light) {
super(FabricBlockSettings.copyOf(Blocks.OAK_LEAVES) super(FabricBlockSettings.copyOf(Blocks.OAK_LEAVES).mapColor(color).luminance(light).breakByTool(FabricToolTags.HOES).breakByTool(FabricToolTags.SHEARS).isValidSpawn((state, world, pos, type) -> false).isSuffocating((state, world, pos) -> false).isViewBlocking((state, world, pos) -> false));
.mapColor(color)
.luminance(light)
.breakByTool(FabricToolTags.HOES)
.breakByTool(FabricToolTags.SHEARS)
.isValidSpawn((state, world, pos, type) -> false)
.isSuffocating((state, world, pos) -> false)
.isViewBlocking((state, world, pos) -> false));
this.sapling = sapling; this.sapling = sapling;
} }
@Override @Override
public BCLRenderLayer getRenderLayer() { public BCLRenderLayer getRenderLayer() {
return BCLRenderLayer.CUTOUT; return BCLRenderLayer.CUTOUT;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
@ -72,7 +57,7 @@ public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider,
} }
return MHelper.RANDOM.nextInt(16) == 0 ? Lists.newArrayList(new ItemStack(sapling)) : Lists.newArrayList(); return MHelper.RANDOM.nextInt(16) == 0 ? Lists.newArrayList(new ItemStack(sapling)) : Lists.newArrayList();
} }
@Override @Override
public BlockModel getItemModel(ResourceLocation resourceLocation) { public BlockModel getItemModel(ResourceLocation resourceLocation) {
return getBlockModel(resourceLocation, defaultBlockState()); return getBlockModel(resourceLocation, defaultBlockState());

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -21,6 +14,7 @@ import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.IronBarsBlock; import net.minecraft.world.level.block.IronBarsBlock;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
@ -28,17 +22,22 @@ import ru.bclib.client.models.PatternsHelper;
import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.client.render.BCLRenderLayer;
import ru.bclib.interfaces.IRenderTyped; import ru.bclib.interfaces.IRenderTyped;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvider, IRenderTyped { public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvider, IRenderTyped {
public BaseMetalBarsBlock(Block source) { public BaseMetalBarsBlock(Block source) {
super(FabricBlockSettings.copyOf(source).strength(5.0F, 6.0F).noOcclusion()); super(FabricBlockSettings.copyOf(source).strength(5.0F, 6.0F).noOcclusion());
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this)); return Collections.singletonList(new ItemStack(this));
} }
public Optional<String> getModelString(String block) { public Optional<String> getModelString(String block) {
ResourceLocation blockId = Registry.BLOCK.getKey(this); ResourceLocation blockId = Registry.BLOCK.getKey(this);
if (block.contains("item")) { if (block.contains("item")) {
@ -51,13 +50,13 @@ public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvi
return PatternsHelper.createJson(BasePatterns.BLOCK_BARS_SIDE, blockId); return PatternsHelper.createJson(BasePatterns.BLOCK_BARS_SIDE, blockId);
} }
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation resourceLocation) { public BlockModel getItemModel(ResourceLocation resourceLocation) {
return ModelsHelper.createBlockItem(resourceLocation); return ModelsHelper.createBlockItem(resourceLocation);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
@ -72,32 +71,25 @@ public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvi
} }
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_post");
"block/" + stateId.getPath() + "_post"); ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_side");
ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(),
"block/" + stateId.getPath() + "_side");
registerBlockModel(postId, postId, blockState, modelCache); registerBlockModel(postId, postId, blockState, modelCache);
registerBlockModel(sideId, sideId, blockState, modelCache); registerBlockModel(sideId, sideId, blockState, modelCache);
ModelsHelper.MultiPartBuilder builder = ModelsHelper.MultiPartBuilder.create(stateDefinition); ModelsHelper.MultiPartBuilder builder = ModelsHelper.MultiPartBuilder.create(stateDefinition);
builder.part(postId).setCondition(state -> builder.part(postId).setCondition(state -> !state.getValue(NORTH) && !state.getValue(EAST) && !state.getValue(SOUTH) && !state.getValue(WEST)).add();
!state.getValue(NORTH) && !state.getValue(EAST) &&
!state.getValue(SOUTH) && !state.getValue(WEST)).add();
builder.part(sideId).setCondition(state -> state.getValue(NORTH)).setUVLock(true).add(); builder.part(sideId).setCondition(state -> state.getValue(NORTH)).setUVLock(true).add();
builder.part(sideId).setCondition(state -> state.getValue(EAST)) builder.part(sideId).setCondition(state -> state.getValue(EAST)).setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add();
.setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); builder.part(sideId).setCondition(state -> state.getValue(SOUTH)).setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add();
builder.part(sideId).setCondition(state -> state.getValue(SOUTH)) builder.part(sideId).setCondition(state -> state.getValue(WEST)).setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add();
.setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add();
builder.part(sideId).setCondition(state -> state.getValue(WEST))
.setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add();
return builder.build(); return builder.build();
} }
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) { public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) {
if (direction.getAxis().isVertical() && stateFrom.getBlock() == this && !stateFrom.equals(state)) { if (direction.getAxis().isVertical() && stateFrom.getBlock() == this && !stateFrom.equals(state)) {
@ -105,7 +97,7 @@ public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvi
} }
return super.skipRendering(state, stateFrom, direction); return super.skipRendering(state, stateFrom, direction);
} }
@Override @Override
public BCLRenderLayer getRenderLayer() { public BCLRenderLayer getRenderLayer() {
return BCLRenderLayer.CUTOUT; return BCLRenderLayer.CUTOUT;

View file

@ -1,9 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.renderer.block.model.BlockModel;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
@ -23,22 +19,21 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.util.MHelper; import ru.bclib.util.MHelper;
import java.util.Collections;
import java.util.List;
public class BaseOreBlock extends OreBlock implements BlockModelProvider { public class BaseOreBlock extends OreBlock implements BlockModelProvider {
private final Item dropItem; private final Item dropItem;
private final int minCount; private final int minCount;
private final int maxCount; private final int maxCount;
public BaseOreBlock(Item drop, int minCount, int maxCount, int experience) { public BaseOreBlock(Item drop, int minCount, int maxCount, int experience) {
super(FabricBlockSettings.of(Material.STONE, MaterialColor.SAND) super(FabricBlockSettings.of(Material.STONE, MaterialColor.SAND).hardness(3F).resistance(9F).requiresCorrectToolForDrops().sound(SoundType.STONE), UniformInt.of(1, experience));
.hardness(3F)
.resistance(9F)
.requiresCorrectToolForDrops()
.sound(SoundType.STONE), UniformInt.of(1, experience));
this.dropItem = drop; this.dropItem = drop;
this.minCount = minCount; this.minCount = minCount;
this.maxCount = maxCount; this.maxCount = maxCount;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
@ -56,14 +51,15 @@ public class BaseOreBlock extends OreBlock implements BlockModelProvider {
return Collections.singletonList(new ItemStack(dropItem, max)); return Collections.singletonList(new ItemStack(dropItem, max));
} }
count = MHelper.randRange(min, max, MHelper.RANDOM); count = MHelper.randRange(min, max, MHelper.RANDOM);
} else { }
else {
count = MHelper.randRange(minCount, maxCount, MHelper.RANDOM); count = MHelper.randRange(minCount, maxCount, MHelper.RANDOM);
} }
return Collections.singletonList(new ItemStack(dropItem, count)); return Collections.singletonList(new ItemStack(dropItem, count));
} }
return Collections.emptyList(); return Collections.emptyList();
} }
@Override @Override
public BlockModel getItemModel(ResourceLocation resourceLocation) { public BlockModel getItemModel(ResourceLocation resourceLocation) {
return getBlockModel(resourceLocation, defaultBlockState()); return getBlockModel(resourceLocation, defaultBlockState());

View file

@ -1,14 +1,6 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -28,16 +20,22 @@ import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class BasePathBlock extends BaseBlockNotFull { public class BasePathBlock extends BaseBlockNotFull {
private static final VoxelShape SHAPE = Block.box(0, 0, 0, 16, 15, 16); private static final VoxelShape SHAPE = Block.box(0, 0, 0, 16, 15, 16);
private Block baseBlock; private Block baseBlock;
public BasePathBlock(Block source) { public BasePathBlock(Block source) {
super(FabricBlockSettings.copyOf(source).isValidSpawn((state, world, pos, type) -> false)); super(FabricBlockSettings.copyOf(source).isValidSpawn((state, world, pos, type) -> false));
this.baseBlock = Blocks.DIRT; this.baseBlock = Blocks.DIRT;
@ -72,7 +70,7 @@ public class BasePathBlock extends BaseBlockNotFull {
public BlockModel getItemModel(ResourceLocation blockId) { public BlockModel getItemModel(ResourceLocation blockId) {
return getBlockModel(blockId, defaultBlockState()); return getBlockModel(blockId, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
@ -87,7 +85,7 @@ public class BasePathBlock extends BaseBlockNotFull {
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PATH, textures); Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PATH, textures);
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {

View file

@ -1,10 +1,6 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.List;
import java.util.Random;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
@ -33,6 +29,9 @@ import net.minecraft.world.phys.shapes.VoxelShape;
import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.client.render.BCLRenderLayer;
import ru.bclib.interfaces.IRenderTyped; import ru.bclib.interfaces.IRenderTyped;
import java.util.List;
import java.util.Random;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public abstract class BasePlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { public abstract class BasePlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock {
private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12);
@ -46,45 +45,36 @@ public abstract class BasePlantBlock extends BaseBlockNotFull implements IRender
} }
public BasePlantBlock(boolean replaceable) { public BasePlantBlock(boolean replaceable) {
super(FabricBlockSettings.of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT) super(FabricBlockSettings.of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).noCollission());
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.sound(SoundType.GRASS)
.noCollission());
} }
public BasePlantBlock(boolean replaceable, int light) { public BasePlantBlock(boolean replaceable, int light) {
super(FabricBlockSettings.of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT) super(FabricBlockSettings.of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).luminance(light).sound(SoundType.GRASS).noCollission());
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.luminance(light)
.sound(SoundType.GRASS)
.noCollission());
} }
public BasePlantBlock(Properties settings) { public BasePlantBlock(Properties settings) {
super(settings); super(settings);
} }
protected abstract boolean isTerrain(BlockState state); protected abstract boolean isTerrain(BlockState state);
@Override @Override
public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) {
Vec3 vec3d = state.getOffset(view, pos); Vec3 vec3d = state.getOffset(view, pos);
return SHAPE.move(vec3d.x, vec3d.y, vec3d.z); return SHAPE.move(vec3d.x, vec3d.y, vec3d.z);
} }
@Override @Override
public BlockBehaviour.OffsetType getOffsetType() { public BlockBehaviour.OffsetType getOffsetType() {
return BlockBehaviour.OffsetType.XZ; return BlockBehaviour.OffsetType.XZ;
} }
@Override @Override
public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) {
BlockState down = world.getBlockState(pos.below()); BlockState down = world.getBlockState(pos.below());
return isTerrain(down); return isTerrain(down);
} }
@Override @Override
public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) {
if (!canSurvive(state, world, pos)) { if (!canSurvive(state, world, pos)) {
@ -110,17 +100,17 @@ public abstract class BasePlantBlock extends BaseBlockNotFull implements IRender
public BCLRenderLayer getRenderLayer() { public BCLRenderLayer getRenderLayer() {
return BCLRenderLayer.CUTOUT; return BCLRenderLayer.CUTOUT;
} }
@Override @Override
public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) { public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) {
return true; return true;
} }
@Override @Override
public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) {
return true; return true;
} }
@Override @Override
public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) {
ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this)); ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this));

View file

@ -1,7 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Random;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
@ -15,16 +13,13 @@ import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.block.state.properties.IntegerProperty;
import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.Material;
import java.util.Random;
public abstract class BasePlantWithAgeBlock extends BasePlantBlock { public abstract class BasePlantWithAgeBlock extends BasePlantBlock {
public static final IntegerProperty AGE = BlockProperties.AGE; public static final IntegerProperty AGE = BlockProperties.AGE;
public BasePlantWithAgeBlock() { public BasePlantWithAgeBlock() {
this(FabricBlockSettings.of(Material.PLANT) this(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).randomTicks().noCollission());
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.sound(SoundType.GRASS)
.randomTicks()
.noCollission());
} }
public BasePlantWithAgeBlock(Properties settings) { public BasePlantWithAgeBlock(Properties settings) {
@ -53,7 +48,7 @@ public abstract class BasePlantWithAgeBlock extends BasePlantBlock {
public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) {
return true; return true;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) {

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -19,11 +12,17 @@ import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.PressurePlateBlock; import net.minecraft.world.level.block.PressurePlateBlock;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class BasePressurePlateBlock extends PressurePlateBlock implements BlockModelProvider { public class BasePressurePlateBlock extends PressurePlateBlock implements BlockModelProvider {
private final Block parent; private final Block parent;
@ -31,19 +30,19 @@ public class BasePressurePlateBlock extends PressurePlateBlock implements BlockM
super(rule, FabricBlockSettings.copyOf(source).noCollission().noOcclusion().strength(0.5F)); super(rule, FabricBlockSettings.copyOf(source).noCollission().noOcclusion().strength(0.5F));
this.parent = source; this.parent = source;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this)); return Collections.singletonList(new ItemStack(this));
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation resourceLocation) { public BlockModel getItemModel(ResourceLocation resourceLocation) {
return getBlockModel(resourceLocation, defaultBlockState()); return getBlockModel(resourceLocation, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) {
@ -51,18 +50,18 @@ public class BasePressurePlateBlock extends PressurePlateBlock implements BlockM
Optional<String> pattern; Optional<String> pattern;
if (blockState.getValue(POWERED)) { if (blockState.getValue(POWERED)) {
pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_DOWN, parentId); pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_DOWN, parentId);
} else { }
else {
pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_UP, parentId); pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_UP, parentId);
} }
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
String state = blockState.getValue(POWERED) ? "_down" : "_up"; String state = blockState.getValue(POWERED) ? "_down" : "_up";
ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + state);
"block/" + stateId.getPath() + state);
registerBlockModel(stateId, modelId, blockState, modelCache); registerBlockModel(stateId, modelId, blockState, modelCache);
return ModelsHelper.createBlockSimple(modelId); return ModelsHelper.createBlockSimple(modelId);
} }

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -18,10 +11,16 @@ import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.RotatedPillarBlock; import net.minecraft.world.level.block.RotatedPillarBlock;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockModelProvider { public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockModelProvider {
public BaseRotatedPillarBlock(Properties settings) { public BaseRotatedPillarBlock(Properties settings) {
super(settings); super(settings);
@ -30,26 +29,26 @@ public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockM
public BaseRotatedPillarBlock(Block block) { public BaseRotatedPillarBlock(Block block) {
super(FabricBlockSettings.copyOf(block)); super(FabricBlockSettings.copyOf(block));
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this)); return Collections.singletonList(new ItemStack(this));
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation blockId) { public BlockModel getItemModel(ResourceLocation blockId) {
return getBlockModel(blockId, defaultBlockState()); return getBlockModel(blockId, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
Optional<String> pattern = createBlockPattern(blockId); Optional<String> pattern = createBlockPattern(blockId);
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
@ -57,7 +56,7 @@ public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockM
registerBlockModel(stateId, modelId, blockState, modelCache); registerBlockModel(stateId, modelId, blockState, modelCache);
return ModelsHelper.createRotatedModel(modelId, blockState.getValue(AXIS)); return ModelsHelper.createRotatedModel(modelId, blockState.getValue(AXIS));
} }
protected Optional<String> createBlockPattern(ResourceLocation blockId) { protected Optional<String> createBlockPattern(ResourceLocation blockId) {
return PatternsHelper.createBlockPillar(blockId); return PatternsHelper.createBlockPillar(blockId);
} }

View file

@ -1,10 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -42,23 +37,22 @@ import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.Nullable;
import ru.bclib.blockentities.BaseSignBlockEntity; import ru.bclib.blockentities.BaseSignBlockEntity;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.interfaces.ISpetialItem; import ru.bclib.interfaces.ISpetialItem;
import ru.bclib.util.BlocksHelper; import ru.bclib.util.BlocksHelper;
import java.util.Collections;
import java.util.List;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpetialItem { public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpetialItem {
public static final IntegerProperty ROTATION = BlockStateProperties.ROTATION_16; public static final IntegerProperty ROTATION = BlockStateProperties.ROTATION_16;
public static final BooleanProperty FLOOR = BooleanProperty.create("floor"); public static final BooleanProperty FLOOR = BooleanProperty.create("floor");
private static final VoxelShape[] WALL_SHAPES = new VoxelShape[] { private static final VoxelShape[] WALL_SHAPES = new VoxelShape[] {Block.box(0.0D, 4.5D, 14.0D, 16.0D, 12.5D, 16.0D), Block.box(0.0D, 4.5D, 0.0D, 2.0D, 12.5D, 16.0D), Block.box(0.0D, 4.5D, 0.0D, 16.0D, 12.5D, 2.0D), Block.box(14.0D, 4.5D, 0.0D, 16.0D, 12.5D, 16.0D)};
Block.box(0.0D, 4.5D, 14.0D, 16.0D, 12.5D, 16.0D),
Block.box(0.0D, 4.5D, 0.0D, 2.0D, 12.5D, 16.0D),
Block.box(0.0D, 4.5D, 0.0D, 16.0D, 12.5D, 2.0D),
Block.box(14.0D, 4.5D, 0.0D, 16.0D, 12.5D, 16.0D)
};
private final Block parent; private final Block parent;
public BaseSignBlock(Block source) { public BaseSignBlock(Block source) {
@ -66,17 +60,17 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe
this.registerDefaultState(this.stateDefinition.any().setValue(ROTATION, 0).setValue(FLOOR, false).setValue(WATERLOGGED, false)); this.registerDefaultState(this.stateDefinition.any().setValue(ROTATION, 0).setValue(FLOOR, false).setValue(WATERLOGGED, false));
this.parent = source; this.parent = source;
} }
@Override @Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(ROTATION, FLOOR, WATERLOGGED); builder.add(ROTATION, FLOOR, WATERLOGGED);
} }
@Override @Override
public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) {
return state.getValue(FLOOR) ? SHAPE : WALL_SHAPES[state.getValue(ROTATION) >> 2]; return state.getValue(FLOOR) ? SHAPE : WALL_SHAPES[state.getValue(ROTATION) >> 2];
} }
@Override @Override
public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) {
return new BaseSignBlockEntity(blockPos, blockState); return new BaseSignBlockEntity(blockPos, blockState);
@ -90,13 +84,14 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe
if (!world.isClientSide) { if (!world.isClientSide) {
sign.setAllowedPlayerEditor(placer.getUUID()); sign.setAllowedPlayerEditor(placer.getUUID());
((ServerPlayer) placer).connection.send(new ClientboundOpenSignEditorPacket(pos)); ((ServerPlayer) placer).connection.send(new ClientboundOpenSignEditorPacket(pos));
} else { }
else {
sign.setEditable(true); sign.setEditable(true);
} }
} }
} }
} }
@Override @Override
public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) {
if (state.getValue(WATERLOGGED)) { if (state.getValue(WATERLOGGED)) {
@ -107,7 +102,7 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe
} }
return super.updateShape(state, facing, neighborState, world, pos, neighborPos); return super.updateShape(state, facing, neighborState, world, pos, neighborPos);
} }
@Override @Override
public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) {
if (!state.getValue(FLOOR)) { if (!state.getValue(FLOOR)) {
@ -118,21 +113,20 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe
return world.getBlockState(pos.below()).getMaterial().isSolid(); return world.getBlockState(pos.below()).getMaterial().isSolid();
} }
} }
@Override @Override
public BlockState getStateForPlacement(BlockPlaceContext ctx) { public BlockState getStateForPlacement(BlockPlaceContext ctx) {
if (ctx.getClickedFace() == Direction.UP) { if (ctx.getClickedFace() == Direction.UP) {
FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos()); FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos());
return this.defaultBlockState().setValue(FLOOR, true) return this.defaultBlockState().setValue(FLOOR, true).setValue(ROTATION, Mth.floor((180.0 + ctx.getRotation() * 16.0 / 360.0) + 0.5 - 12) & 15).setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER);
.setValue(ROTATION, Mth.floor((180.0 + ctx.getRotation() * 16.0 / 360.0) + 0.5 - 12) & 15) }
.setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); else if (ctx.getClickedFace() != Direction.DOWN) {
} else if (ctx.getClickedFace() != Direction.DOWN) {
BlockState blockState = this.defaultBlockState(); BlockState blockState = this.defaultBlockState();
FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos()); FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos());
LevelReader worldView = ctx.getLevel(); LevelReader worldView = ctx.getLevel();
BlockPos blockPos = ctx.getClickedPos(); BlockPos blockPos = ctx.getClickedPos();
Direction[] directions = ctx.getNearestLookingDirections(); Direction[] directions = ctx.getNearestLookingDirections();
for (Direction direction : directions) { for (Direction direction : directions) {
if (direction.getAxis().isHorizontal()) { if (direction.getAxis().isHorizontal()) {
Direction dir = direction.getOpposite(); Direction dir = direction.getOpposite();
@ -144,22 +138,22 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe
} }
} }
} }
return null; return null;
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) {
ResourceLocation parentId = Registry.BLOCK.getKey(parent); ResourceLocation parentId = Registry.BLOCK.getKey(parent);
return ModelsHelper.createBlockEmpty(parentId); return ModelsHelper.createBlockEmpty(parentId);
} }
@Override @Override
public BlockState rotate(BlockState state, Rotation rotation) { public BlockState rotate(BlockState state, Rotation rotation) {
return state.setValue(ROTATION, rotation.rotate((Integer) state.getValue(ROTATION), 16)); return state.setValue(ROTATION, rotation.rotate((Integer) state.getValue(ROTATION), 16));
} }
@Override @Override
public BlockState mirror(BlockState state, Mirror mirror) { public BlockState mirror(BlockState state, Mirror mirror) {
return state.setValue(ROTATION, mirror.mirror((Integer) state.getValue(ROTATION), 16)); return state.setValue(ROTATION, mirror.mirror((Integer) state.getValue(ROTATION), 16));
@ -169,24 +163,24 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this)); return Collections.singletonList(new ItemStack(this));
} }
@Override @Override
public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) { public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return super.canPlaceLiquid(world, pos, state, fluid); return super.canPlaceLiquid(world, pos, state, fluid);
} }
@Override @Override
public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) { public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return super.placeLiquid(world, pos, state, fluidState); return super.placeLiquid(world, pos, state, fluidState);
} }
@Override @Override
public int getStackSize() { public int getStackSize() {
return 16; return 16;
} }
@Override @Override
public boolean canPlaceOnWater() { public boolean canPlaceOnWater() {
return false; return false;

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -21,11 +14,17 @@ import net.minecraft.world.level.block.SlabBlock;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.SlabType; import net.minecraft.world.level.block.state.properties.SlabType;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class BaseSlabBlock extends SlabBlock implements BlockModelProvider { public class BaseSlabBlock extends SlabBlock implements BlockModelProvider {
private final Block parent; private final Block parent;
@ -33,19 +32,19 @@ public class BaseSlabBlock extends SlabBlock implements BlockModelProvider {
super(FabricBlockSettings.copyOf(source)); super(FabricBlockSettings.copyOf(source));
this.parent = source; this.parent = source;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this)); return Collections.singletonList(new ItemStack(this));
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation resourceLocation) { public BlockModel getItemModel(ResourceLocation resourceLocation) {
return getBlockModel(resourceLocation, defaultBlockState()); return getBlockModel(resourceLocation, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
@ -53,18 +52,18 @@ public class BaseSlabBlock extends SlabBlock implements BlockModelProvider {
Optional<String> pattern; Optional<String> pattern;
if (blockState.getValue(TYPE) == SlabType.DOUBLE) { if (blockState.getValue(TYPE) == SlabType.DOUBLE) {
pattern = PatternsHelper.createBlockSimple(parentId); pattern = PatternsHelper.createBlockSimple(parentId);
} else { }
else {
pattern = PatternsHelper.createJson(BasePatterns.BLOCK_SLAB, parentId); pattern = PatternsHelper.createJson(BasePatterns.BLOCK_SLAB, parentId);
} }
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
SlabType type = blockState.getValue(TYPE); SlabType type = blockState.getValue(TYPE);
ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_" + type);
"block/" + stateId.getPath() + "_" + type);
registerBlockModel(stateId, modelId, blockState, modelCache); registerBlockModel(stateId, modelId, blockState, modelCache);
if (type == SlabType.TOP) { if (type == SlabType.TOP) {
return ModelsHelper.createMultiVariant(modelId, BlockModelRotation.X180_Y0.getRotation(), true); return ModelsHelper.createMultiVariant(modelId, BlockModelRotation.X180_Y0.getRotation(), true);

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -22,11 +15,17 @@ import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.Half; import net.minecraft.world.level.block.state.properties.Half;
import net.minecraft.world.level.block.state.properties.StairsShape; import net.minecraft.world.level.block.state.properties.StairsShape;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class BaseStairsBlock extends StairBlock implements BlockModelProvider { public class BaseStairsBlock extends StairBlock implements BlockModelProvider {
private final Block parent; private final Block parent;
@ -41,13 +40,13 @@ public class BaseStairsBlock extends StairBlock implements BlockModelProvider {
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this)); return Collections.singletonList(new ItemStack(this));
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation resourceLocation) { public BlockModel getItemModel(ResourceLocation resourceLocation) {
return getBlockModel(resourceLocation, defaultBlockState()); return getBlockModel(resourceLocation, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
@ -68,7 +67,7 @@ public class BaseStairsBlock extends StairBlock implements BlockModelProvider {
} }
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
@ -77,21 +76,21 @@ public class BaseStairsBlock extends StairBlock implements BlockModelProvider {
switch (shape) { switch (shape) {
case INNER_LEFT: case INNER_LEFT:
case INNER_RIGHT: case INNER_RIGHT:
state = "_inner"; break; state = "_inner";
break;
case OUTER_LEFT: case OUTER_LEFT:
case OUTER_RIGHT: case OUTER_RIGHT:
state = "_outer"; break; state = "_outer";
break;
default: default:
state = ""; state = "";
} }
ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + state); ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + state);
registerBlockModel(stateId, modelId, blockState, modelCache); registerBlockModel(stateId, modelId, blockState, modelCache);
boolean isTop = blockState.getValue(HALF) == Half.TOP; boolean isTop = blockState.getValue(HALF) == Half.TOP;
boolean isLeft = shape == StairsShape.INNER_LEFT || boolean isLeft = shape == StairsShape.INNER_LEFT || shape == StairsShape.OUTER_LEFT;
shape == StairsShape.OUTER_LEFT; boolean isRight = shape == StairsShape.INNER_RIGHT || shape == StairsShape.OUTER_RIGHT;
boolean isRight = shape == StairsShape.INNER_RIGHT ||
shape == StairsShape.OUTER_RIGHT;
int y = 0; int y = 0;
int x = isTop ? 180 : 0; int x = isTop ? 180 : 0;
switch (blockState.getValue(FACING)) { switch (blockState.getValue(FACING)) {

View file

@ -6,11 +6,11 @@ import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
public class BaseStoneButtonBlock extends BaseButtonBlock { public class BaseStoneButtonBlock extends BaseButtonBlock {
public BaseStoneButtonBlock(Block source) { public BaseStoneButtonBlock(Block source) {
super(source, FabricBlockSettings.copyOf(source).noOcclusion(), false); super(source, FabricBlockSettings.copyOf(source).noOcclusion(), false);
} }
@Override @Override
protected SoundEvent getSound(boolean clicked) { protected SoundEvent getSound(boolean clicked) {
return clicked ? SoundEvents.STONE_BUTTON_CLICK_ON : SoundEvents.STONE_BUTTON_CLICK_OFF; return clicked ? SoundEvents.STONE_BUTTON_CLICK_ON : SoundEvents.STONE_BUTTON_CLICK_OFF;

View file

@ -1,15 +1,6 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import org.jetbrains.annotations.Nullable;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -41,14 +32,21 @@ import net.minecraft.world.level.material.MaterialColor;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.BlockHitResult;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import ru.bclib.client.sound.BlockSounds; import ru.bclib.client.sound.BlockSounds;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class BaseTerrainBlock extends BaseBlock { public class BaseTerrainBlock extends BaseBlock {
private final Block baseBlock; private final Block baseBlock;
private Block pathBlock; private Block pathBlock;
@ -60,11 +58,11 @@ public class BaseTerrainBlock extends BaseBlock {
public void setPathBlock(Block roadBlock) { public void setPathBlock(Block roadBlock) {
this.pathBlock = roadBlock; this.pathBlock = roadBlock;
} }
public Block getBaseBlock() { public Block getBaseBlock() {
return baseBlock; return baseBlock;
} }
@Override @Override
public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) {
if (pathBlock != null && FabricToolTags.SHOVELS.contains(player.getMainHandItem().getItem())) { if (pathBlock != null && FabricToolTags.SHOVELS.contains(player.getMainHandItem().getItem())) {
@ -95,7 +93,7 @@ public class BaseTerrainBlock extends BaseBlock {
world.setBlockAndUpdate(pos, Blocks.END_STONE.defaultBlockState()); world.setBlockAndUpdate(pos, Blocks.END_STONE.defaultBlockState());
} }
} }
public boolean canStay(BlockState state, LevelReader worldView, BlockPos pos) { public boolean canStay(BlockState state, LevelReader worldView, BlockPos pos) {
BlockPos blockPos = pos.above(); BlockPos blockPos = pos.above();
BlockState blockState = worldView.getBlockState(blockPos); BlockState blockState = worldView.getBlockState(blockPos);
@ -116,7 +114,7 @@ public class BaseTerrainBlock extends BaseBlock {
public BlockModel getItemModel(ResourceLocation blockId) { public BlockModel getItemModel(ResourceLocation blockId) {
return getBlockModel(blockId, defaultBlockState()); return getBlockModel(blockId, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
@ -131,7 +129,7 @@ public class BaseTerrainBlock extends BaseBlock {
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_TOP_SIDE_BOTTOM, textures); Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_TOP_SIDE_BOTTOM, textures);
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {

View file

@ -1,13 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -21,6 +13,7 @@ import net.minecraft.world.level.block.TrapDoorBlock;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.Half; import net.minecraft.world.level.block.state.properties.Half;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
@ -28,11 +21,17 @@ import ru.bclib.client.models.PatternsHelper;
import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.client.render.BCLRenderLayer;
import ru.bclib.interfaces.IRenderTyped; import ru.bclib.interfaces.IRenderTyped;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class BaseTrapdoorBlock extends TrapDoorBlock implements IRenderTyped, BlockModelProvider { public class BaseTrapdoorBlock extends TrapDoorBlock implements IRenderTyped, BlockModelProvider {
public BaseTrapdoorBlock(Block source) { public BaseTrapdoorBlock(Block source) {
super(FabricBlockSettings.copyOf(source).strength(3.0F, 3.0F).noOcclusion()); super(FabricBlockSettings.copyOf(source).strength(3.0F, 3.0F).noOcclusion());
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
@ -43,19 +42,20 @@ public class BaseTrapdoorBlock extends TrapDoorBlock implements IRenderTyped, Bl
public BCLRenderLayer getRenderLayer() { public BCLRenderLayer getRenderLayer() {
return BCLRenderLayer.CUTOUT; return BCLRenderLayer.CUTOUT;
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation resourceLocation) { public BlockModel getItemModel(ResourceLocation resourceLocation) {
return getBlockModel(resourceLocation, defaultBlockState()); return getBlockModel(resourceLocation, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) {
String name = resourceLocation.getPath(); String name = resourceLocation.getPath();
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_TRAPDOOR, new HashMap<String, String>() { Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_TRAPDOOR, new HashMap<String, String>() {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
{ {
put("%modid%", resourceLocation.getNamespace()); put("%modid%", resourceLocation.getNamespace());
put("%texture%", name); put("%texture%", name);
@ -64,7 +64,7 @@ public class BaseTrapdoorBlock extends TrapDoorBlock implements IRenderTyped, Bl
}); });
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
@ -87,7 +87,8 @@ public class BaseTrapdoorBlock extends TrapDoorBlock implements IRenderTyped, Bl
case WEST: case WEST:
y = (isTop && isOpen) ? 90 : 270; y = (isTop && isOpen) ? 90 : 270;
break; break;
default: break; default:
break;
} }
BlockModelRotation rotation = BlockModelRotation.by(x, y); BlockModelRotation rotation = BlockModelRotation.by(x, y);
return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false);

View file

@ -17,20 +17,11 @@ import net.minecraft.world.level.material.Material;
public abstract class BaseUnderwaterWallPlantBlock extends BaseWallPlantBlock implements LiquidBlockContainer { public abstract class BaseUnderwaterWallPlantBlock extends BaseWallPlantBlock implements LiquidBlockContainer {
public BaseUnderwaterWallPlantBlock() { public BaseUnderwaterWallPlantBlock() {
super(FabricBlockSettings.of(Material.WATER_PLANT) super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).noCollission());
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.sound(SoundType.WET_GRASS)
.noCollission());
} }
public BaseUnderwaterWallPlantBlock(int light) { public BaseUnderwaterWallPlantBlock(int light) {
super(FabricBlockSettings.of(Material.WATER_PLANT) super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).luminance(light).sound(SoundType.WET_GRASS).noCollission());
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.luminance(light)
.sound(SoundType.WET_GRASS)
.noCollission());
} }
public BaseUnderwaterWallPlantBlock(Properties settings) { public BaseUnderwaterWallPlantBlock(Properties settings) {
@ -41,7 +32,7 @@ public abstract class BaseUnderwaterWallPlantBlock extends BaseWallPlantBlock im
public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) { public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) {
return false; return false;
} }
@Override @Override
public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) { public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) {
return false; return false;

View file

@ -1,10 +1,6 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.List;
import java.util.Random;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
@ -37,6 +33,9 @@ import ru.bclib.client.render.BCLRenderLayer;
import ru.bclib.interfaces.IRenderTyped; import ru.bclib.interfaces.IRenderTyped;
import ru.bclib.util.BlocksHelper; import ru.bclib.util.BlocksHelper;
import java.util.List;
import java.util.Random;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock {
public static final EnumProperty<TripleShape> SHAPE = BlockProperties.TRIPLE_SHAPE; public static final EnumProperty<TripleShape> SHAPE = BlockProperties.TRIPLE_SHAPE;
@ -51,12 +50,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon
} }
public BaseVineBlock(int light, boolean bottomOnly) { public BaseVineBlock(int light, boolean bottomOnly) {
super(FabricBlockSettings.of(Material.PLANT) super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).lightLevel((state) -> bottomOnly ? state.getValue(SHAPE) == TripleShape.BOTTOM ? light : 0 : light).noCollission());
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.sound(SoundType.GRASS)
.lightLevel((state) -> bottomOnly ? state.getValue(SHAPE) == TripleShape.BOTTOM ? light : 0 : light)
.noCollission());
this.registerDefaultState(this.stateDefinition.any().setValue(SHAPE, TripleShape.BOTTOM)); this.registerDefaultState(this.stateDefinition.any().setValue(SHAPE, TripleShape.BOTTOM));
} }
@ -64,13 +58,13 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> stateManager) { protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> stateManager) {
stateManager.add(SHAPE); stateManager.add(SHAPE);
} }
@Override @Override
public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) {
Vec3 vec3d = state.getOffset(view, pos); Vec3 vec3d = state.getOffset(view, pos);
return VOXEL_SHAPE.move(vec3d.x, vec3d.y, vec3d.z); return VOXEL_SHAPE.move(vec3d.x, vec3d.y, vec3d.z);
} }
@Override @Override
public BlockBehaviour.OffsetType getOffsetType() { public BlockBehaviour.OffsetType getOffsetType() {
return BlockBehaviour.OffsetType.XZ; return BlockBehaviour.OffsetType.XZ;
@ -79,7 +73,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon
public boolean canGenerate(BlockState state, LevelReader world, BlockPos pos) { public boolean canGenerate(BlockState state, LevelReader world, BlockPos pos) {
return isSupport(state, world, pos); return isSupport(state, world, pos);
} }
@Override @Override
public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) {
return isSupport(state, world, pos); return isSupport(state, world, pos);
@ -89,17 +83,15 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon
BlockState up = world.getBlockState(pos.above()); BlockState up = world.getBlockState(pos.above());
return up.is(this) || up.is(BlockTags.LEAVES) || canSupportCenter(world, pos.above(), Direction.DOWN); return up.is(this) || up.is(BlockTags.LEAVES) || canSupportCenter(world, pos.above(), Direction.DOWN);
} }
@Override @Override
public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) {
if (!canSurvive(state, world, pos)) { if (!canSurvive(state, world, pos)) {
return Blocks.AIR.defaultBlockState(); return Blocks.AIR.defaultBlockState();
} }
else { else {
if (world.getBlockState(pos.below()).getBlock() != this) if (world.getBlockState(pos.below()).getBlock() != this) return state.setValue(SHAPE, TripleShape.BOTTOM);
return state.setValue(SHAPE, TripleShape.BOTTOM); else if (world.getBlockState(pos.above()).getBlock() != this) return state.setValue(SHAPE, TripleShape.TOP);
else if (world.getBlockState(pos.above()).getBlock() != this)
return state.setValue(SHAPE, TripleShape.TOP);
return state.setValue(SHAPE, TripleShape.MIDDLE); return state.setValue(SHAPE, TripleShape.MIDDLE);
} }
} }
@ -119,7 +111,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon
public BCLRenderLayer getRenderLayer() { public BCLRenderLayer getRenderLayer() {
return BCLRenderLayer.CUTOUT; return BCLRenderLayer.CUTOUT;
} }
@Override @Override
public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) { public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) {
while (world.getBlockState(pos).getBlock() == this) { while (world.getBlockState(pos).getBlock() == this) {
@ -127,7 +119,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon
} }
return world.getBlockState(pos).isAir(); return world.getBlockState(pos).isAir();
} }
@Override @Override
public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) {
while (world.getBlockState(pos).getBlock() == this) { while (world.getBlockState(pos).getBlock() == this) {
@ -135,7 +127,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon
} }
return world.isEmptyBlock(pos); return world.isEmptyBlock(pos);
} }
@Override @Override
public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) {
while (world.getBlockState(pos).getBlock() == this) { while (world.getBlockState(pos).getBlock() == this) {

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -21,11 +14,17 @@ import net.minecraft.world.level.block.WallBlock;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.WallSide; import net.minecraft.world.level.block.state.properties.WallSide;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class BaseWallBlock extends WallBlock implements BlockModelProvider { public class BaseWallBlock extends WallBlock implements BlockModelProvider {
private final Block parent; private final Block parent;
@ -34,13 +33,13 @@ public class BaseWallBlock extends WallBlock implements BlockModelProvider {
super(FabricBlockSettings.copyOf(source).noOcclusion()); super(FabricBlockSettings.copyOf(source).noOcclusion());
this.parent = source; this.parent = source;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this)); return Collections.singletonList(new ItemStack(this));
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation blockId) { public BlockModel getItemModel(ResourceLocation blockId) {
@ -48,7 +47,7 @@ public class BaseWallBlock extends WallBlock implements BlockModelProvider {
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.ITEM_WALL, parentId); Optional<String> pattern = PatternsHelper.createJson(BasePatterns.ITEM_WALL, parentId);
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
@ -66,37 +65,28 @@ public class BaseWallBlock extends WallBlock implements BlockModelProvider {
} }
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_post");
"block/" + stateId.getPath() + "_post"); ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_side");
ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(), ResourceLocation sideTallId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_side_tall");
"block/" + stateId.getPath() + "_side");
ResourceLocation sideTallId = new ResourceLocation(stateId.getNamespace(),
"block/" + stateId.getPath() + "_side_tall");
registerBlockModel(postId, postId, blockState, modelCache); registerBlockModel(postId, postId, blockState, modelCache);
registerBlockModel(sideId, sideId, blockState, modelCache); registerBlockModel(sideId, sideId, blockState, modelCache);
registerBlockModel(sideTallId, sideTallId, blockState, modelCache); registerBlockModel(sideTallId, sideTallId, blockState, modelCache);
ModelsHelper.MultiPartBuilder builder = ModelsHelper.MultiPartBuilder.create(stateDefinition); ModelsHelper.MultiPartBuilder builder = ModelsHelper.MultiPartBuilder.create(stateDefinition);
builder.part(sideId).setCondition(state -> state.getValue(NORTH_WALL) == WallSide.LOW).setUVLock(true).add(); builder.part(sideId).setCondition(state -> state.getValue(NORTH_WALL) == WallSide.LOW).setUVLock(true).add();
builder.part(sideId).setCondition(state -> state.getValue(EAST_WALL) == WallSide.LOW) builder.part(sideId).setCondition(state -> state.getValue(EAST_WALL) == WallSide.LOW).setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add();
.setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); builder.part(sideId).setCondition(state -> state.getValue(SOUTH_WALL) == WallSide.LOW).setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add();
builder.part(sideId).setCondition(state -> state.getValue(SOUTH_WALL) == WallSide.LOW) builder.part(sideId).setCondition(state -> state.getValue(WEST_WALL) == WallSide.LOW).setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add();
.setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add();
builder.part(sideId).setCondition(state -> state.getValue(WEST_WALL) == WallSide.LOW)
.setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add();
builder.part(sideTallId).setCondition(state -> state.getValue(NORTH_WALL) == WallSide.TALL).setUVLock(true).add(); builder.part(sideTallId).setCondition(state -> state.getValue(NORTH_WALL) == WallSide.TALL).setUVLock(true).add();
builder.part(sideTallId).setCondition(state -> state.getValue(EAST_WALL) == WallSide.TALL) builder.part(sideTallId).setCondition(state -> state.getValue(EAST_WALL) == WallSide.TALL).setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add();
.setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); builder.part(sideTallId).setCondition(state -> state.getValue(SOUTH_WALL) == WallSide.TALL).setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add();
builder.part(sideTallId).setCondition(state -> state.getValue(SOUTH_WALL) == WallSide.TALL) builder.part(sideTallId).setCondition(state -> state.getValue(WEST_WALL) == WallSide.TALL).setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add();
.setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add();
builder.part(sideTallId).setCondition(state -> state.getValue(WEST_WALL) == WallSide.TALL)
.setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add();
builder.part(postId).setCondition(state -> state.getValue(UP)).add(); builder.part(postId).setCondition(state -> state.getValue(UP)).add();
return builder.build(); return builder.build();
} }
} }

View file

@ -1,10 +1,7 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.EnumMap;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
@ -28,29 +25,18 @@ import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import ru.bclib.util.BlocksHelper; import ru.bclib.util.BlocksHelper;
import java.util.EnumMap;
public abstract class BaseWallPlantBlock extends BasePlantBlock { public abstract class BaseWallPlantBlock extends BasePlantBlock {
private static final EnumMap<Direction, VoxelShape> SHAPES = Maps.newEnumMap(ImmutableMap.of( private static final EnumMap<Direction, VoxelShape> SHAPES = Maps.newEnumMap(ImmutableMap.of(Direction.NORTH, Block.box(1, 1, 8, 15, 15, 16), Direction.SOUTH, Block.box(1, 1, 0, 15, 15, 8), Direction.WEST, Block.box(8, 1, 1, 16, 15, 15), Direction.EAST, Block.box(0, 1, 1, 8, 15, 15)));
Direction.NORTH, Block.box(1, 1, 8, 15, 15, 16),
Direction.SOUTH, Block.box(1, 1, 0, 15, 15, 8),
Direction.WEST, Block.box(8, 1, 1, 16, 15, 15),
Direction.EAST, Block.box(0, 1, 1, 8, 15, 15)));
public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING; public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING;
public BaseWallPlantBlock() { public BaseWallPlantBlock() {
this(FabricBlockSettings.of(Material.PLANT) this(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).noCollission());
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.sound(SoundType.GRASS)
.noCollission());
} }
public BaseWallPlantBlock(int light) { public BaseWallPlantBlock(int light) {
this(FabricBlockSettings.of(Material.PLANT) this(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).luminance(light).sound(SoundType.GRASS).noCollission());
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.luminance(light)
.sound(SoundType.GRASS)
.noCollission());
} }
public BaseWallPlantBlock(Properties settings) { public BaseWallPlantBlock(Properties settings) {
@ -61,17 +47,17 @@ public abstract class BaseWallPlantBlock extends BasePlantBlock {
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> stateManager) { protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> stateManager) {
stateManager.add(FACING); stateManager.add(FACING);
} }
@Override @Override
public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) {
return SHAPES.get(state.getValue(FACING)); return SHAPES.get(state.getValue(FACING));
} }
@Override @Override
public BlockBehaviour.OffsetType getOffsetType() { public BlockBehaviour.OffsetType getOffsetType() {
return BlockBehaviour.OffsetType.NONE; return BlockBehaviour.OffsetType.NONE;
} }
@Override @Override
public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) {
Direction direction = state.getValue(FACING); Direction direction = state.getValue(FACING);
@ -101,7 +87,7 @@ public abstract class BaseWallPlantBlock extends BasePlantBlock {
} }
return null; return null;
} }
@Override @Override
public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) {
if (!canSurvive(state, world, pos)) { if (!canSurvive(state, world, pos)) {
@ -117,7 +103,7 @@ public abstract class BaseWallPlantBlock extends BasePlantBlock {
public BlockState rotate(BlockState state, Rotation rotation) { public BlockState rotate(BlockState state, Rotation rotation) {
return BlocksHelper.rotateHorizontal(state, rotation, FACING); return BlocksHelper.rotateHorizontal(state, rotation, FACING);
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public BlockState mirror(BlockState state, Mirror mirror) { public BlockState mirror(BlockState state, Mirror mirror) {

View file

@ -1,12 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -19,11 +12,17 @@ import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.WeightedPressurePlateBlock; import net.minecraft.world.level.block.WeightedPressurePlateBlock;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implements BlockModelProvider { public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implements BlockModelProvider {
private final Block parent; private final Block parent;
@ -31,19 +30,19 @@ public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implement
super(15, FabricBlockSettings.copyOf(source).noCollission().noOcclusion().requiresCorrectToolForDrops().strength(0.5F)); super(15, FabricBlockSettings.copyOf(source).noCollission().noOcclusion().requiresCorrectToolForDrops().strength(0.5F));
this.parent = source; this.parent = source;
} }
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this)); return Collections.singletonList(new ItemStack(this));
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation resourceLocation) { public BlockModel getItemModel(ResourceLocation resourceLocation) {
return getBlockModel(resourceLocation, defaultBlockState()); return getBlockModel(resourceLocation, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) {
@ -51,18 +50,18 @@ public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implement
Optional<String> pattern; Optional<String> pattern;
if (blockState.getValue(POWER) > 0) { if (blockState.getValue(POWER) > 0) {
pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_DOWN, parentId); pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_DOWN, parentId);
} else { }
else {
pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_UP, parentId); pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_UP, parentId);
} }
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
String state = blockState.getValue(POWER) > 0 ? "_down" : "_up"; String state = blockState.getValue(POWER) > 0 ? "_down" : "_up";
ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + state);
"block/" + stateId.getPath() + state);
registerBlockModel(stateId, modelId, blockState, modelCache); registerBlockModel(stateId, modelId, blockState, modelCache);
return ModelsHelper.createBlockSimple(modelId); return ModelsHelper.createBlockSimple(modelId);
} }

View file

@ -6,11 +6,11 @@ import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
public class BaseWoodenButtonBlock extends BaseButtonBlock { public class BaseWoodenButtonBlock extends BaseButtonBlock {
public BaseWoodenButtonBlock(Block source) { public BaseWoodenButtonBlock(Block source) {
super(source, FabricBlockSettings.copyOf(source).strength(0.5F, 0.5F).noOcclusion(), true); super(source, FabricBlockSettings.copyOf(source).strength(0.5F, 0.5F).noOcclusion(), true);
} }
@Override @Override
protected SoundEvent getSound(boolean clicked) { protected SoundEvent getSound(boolean clicked) {
return clicked ? SoundEvents.WOODEN_BUTTON_CLICK_ON : SoundEvents.WOODEN_BUTTON_CLICK_OFF; return clicked ? SoundEvents.WOODEN_BUTTON_CLICK_ON : SoundEvents.WOODEN_BUTTON_CLICK_OFF;

View file

@ -24,9 +24,7 @@ public class BlockProperties {
public static final IntegerProperty AGE = IntegerProperty.create("age", 0, 3); public static final IntegerProperty AGE = IntegerProperty.create("age", 0, 3);
public enum TripleShape implements StringRepresentable { public enum TripleShape implements StringRepresentable {
TOP("top", 0), TOP("top", 0), MIDDLE("middle", 1), BOTTOM("bottom", 2);
MIDDLE("middle", 1),
BOTTOM("bottom", 2);
private final String name; private final String name;
private final int index; private final int index;
@ -35,7 +33,7 @@ public class BlockProperties {
this.name = name; this.name = name;
this.index = index; this.index = index;
} }
@Override @Override
public String getSerializedName() { public String getSerializedName() {
return name; return name;
@ -56,18 +54,14 @@ public class BlockProperties {
} }
public enum PentaShape implements StringRepresentable { public enum PentaShape implements StringRepresentable {
BOTTOM("bottom"), BOTTOM("bottom"), PRE_BOTTOM("pre_bottom"), MIDDLE("middle"), PRE_TOP("pre_top"), TOP("top");
PRE_BOTTOM("pre_bottom"),
MIDDLE("middle"),
PRE_TOP("pre_top"),
TOP("top");
private final String name; private final String name;
PentaShape(String name) { PentaShape(String name) {
this.name = name; this.name = name;
} }
@Override @Override
public String getSerializedName() { public String getSerializedName() {
return name; return name;

View file

@ -1,13 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -26,10 +18,12 @@ import net.minecraft.world.level.block.SaplingBlock;
import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.Feature;
import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.Material;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
@ -37,65 +31,57 @@ import ru.bclib.client.models.PatternsHelper;
import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.client.render.BCLRenderLayer;
import ru.bclib.interfaces.IRenderTyped; import ru.bclib.interfaces.IRenderTyped;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Random;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public abstract class FeatureSaplingBlock extends SaplingBlock implements IRenderTyped, BlockModelProvider { public abstract class FeatureSaplingBlock extends SaplingBlock implements IRenderTyped, BlockModelProvider {
private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12);
public FeatureSaplingBlock() { public FeatureSaplingBlock() {
super(null, FabricBlockSettings.of(Material.PLANT) super(null, FabricBlockSettings.of(Material.PLANT).breakByHand(true).collidable(false).instabreak().sound(SoundType.GRASS).randomTicks());
.breakByHand(true)
.collidable(false)
.instabreak()
.sound(SoundType.GRASS)
.randomTicks());
} }
public FeatureSaplingBlock(int light) { public FeatureSaplingBlock(int light) {
super(null, FabricBlockSettings.of(Material.PLANT) super(null, FabricBlockSettings.of(Material.PLANT).breakByHand(true).collidable(false).luminance(light).instabreak().sound(SoundType.GRASS).randomTicks());
.breakByHand(true)
.collidable(false)
.luminance(light)
.instabreak()
.sound(SoundType.GRASS)
.randomTicks());
} }
protected abstract Feature<?> getFeature(); protected abstract Feature<?> getFeature();
@Override @Override
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Collections.singletonList(new ItemStack(this)); return Collections.singletonList(new ItemStack(this));
} }
@Override @Override
public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) {
return SHAPE; return SHAPE;
} }
@Override @Override
public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) {
if (!canSurvive(state, world, pos)) if (!canSurvive(state, world, pos)) return Blocks.AIR.defaultBlockState();
return Blocks.AIR.defaultBlockState(); else return state;
else
return state;
} }
@Override @Override
public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) {
return random.nextInt(16) == 0; return random.nextInt(16) == 0;
} }
@Override @Override
public void advanceTree(ServerLevel world, BlockPos pos, BlockState blockState, Random random) { public void advanceTree(ServerLevel world, BlockPos pos, BlockState blockState, Random random) {
FeaturePlaceContext context = new FeaturePlaceContext(world, world.getChunkSource().getGenerator(), random, pos, null); FeaturePlaceContext context = new FeaturePlaceContext(world, world.getChunkSource().getGenerator(), random, pos, null);
getFeature().place(context); getFeature().place(context);
} }
@Override @Override
public void randomTick(BlockState state, ServerLevel world, BlockPos pos, Random random) { public void randomTick(BlockState state, ServerLevel world, BlockPos pos, Random random) {
this.tick(state, world, pos, random); this.tick(state, world, pos, random);
} }
@Override @Override
public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) {
super.tick(state, world, pos, random); super.tick(state, world, pos, random);
@ -103,18 +89,18 @@ public abstract class FeatureSaplingBlock extends SaplingBlock implements IRende
performBonemeal(world, random, pos, state); performBonemeal(world, random, pos, state);
} }
} }
@Override @Override
public BCLRenderLayer getRenderLayer() { public BCLRenderLayer getRenderLayer() {
return BCLRenderLayer.CUTOUT; return BCLRenderLayer.CUTOUT;
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation resourceLocation) { public BlockModel getItemModel(ResourceLocation resourceLocation) {
return ModelsHelper.createBlockItem(resourceLocation); return ModelsHelper.createBlockItem(resourceLocation);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) {

View file

@ -9,28 +9,13 @@ import ru.bclib.interfaces.IRenderTyped;
public class SimpleLeavesBlock extends BaseBlockNotFull implements IRenderTyped { public class SimpleLeavesBlock extends BaseBlockNotFull implements IRenderTyped {
public SimpleLeavesBlock(MaterialColor color) { public SimpleLeavesBlock(MaterialColor color) {
super(FabricBlockSettings.of(Material.LEAVES) super(FabricBlockSettings.of(Material.LEAVES).strength(0.2F).mapColor(color).sound(SoundType.GRASS).noOcclusion().isValidSpawn((state, world, pos, type) -> false).isSuffocating((state, world, pos) -> false).isViewBlocking((state, world, pos) -> false));
.strength(0.2F)
.mapColor(color)
.sound(SoundType.GRASS)
.noOcclusion()
.isValidSpawn((state, world, pos, type) -> false)
.isSuffocating((state, world, pos) -> false)
.isViewBlocking((state, world, pos) -> false));
} }
public SimpleLeavesBlock(MaterialColor color, int light) { public SimpleLeavesBlock(MaterialColor color, int light) {
super(FabricBlockSettings.of(Material.LEAVES) super(FabricBlockSettings.of(Material.LEAVES).luminance(light).mapColor(color).strength(0.2F).sound(SoundType.GRASS).noOcclusion().isValidSpawn((state, world, pos, type) -> false).isSuffocating((state, world, pos) -> false).isViewBlocking((state, world, pos) -> false));
.luminance(light)
.mapColor(color)
.strength(0.2F)
.sound(SoundType.GRASS)
.noOcclusion()
.isValidSpawn((state, world, pos, type) -> false)
.isSuffocating((state, world, pos) -> false)
.isViewBlocking((state, world, pos) -> false));
} }
@Override @Override
public BCLRenderLayer getRenderLayer() { public BCLRenderLayer getRenderLayer() {
return BCLRenderLayer.CUTOUT; return BCLRenderLayer.CUTOUT;

View file

@ -1,10 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
@ -37,29 +32,33 @@ import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids; import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.Nullable;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.client.render.BCLRenderLayer;
import ru.bclib.interfaces.IRenderTyped; import ru.bclib.interfaces.IRenderTyped;
import java.util.Map;
import java.util.Optional;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterloggedBlock, LiquidBlockContainer, IRenderTyped { public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterloggedBlock, LiquidBlockContainer, IRenderTyped {
public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;
public static final BooleanProperty IS_FLOOR = BlockProperties.IS_FLOOR; public static final BooleanProperty IS_FLOOR = BlockProperties.IS_FLOOR;
public static final IntegerProperty SIZE = BlockProperties.SIZE; public static final IntegerProperty SIZE = BlockProperties.SIZE;
private static final VoxelShape[] SHAPES; private static final VoxelShape[] SHAPES;
public StalactiteBlock(Block source) { public StalactiteBlock(Block source) {
super(FabricBlockSettings.copy(source).noOcclusion()); super(FabricBlockSettings.copy(source).noOcclusion());
this.registerDefaultState(getStateDefinition().any().setValue(SIZE, 0).setValue(IS_FLOOR, true).setValue(WATERLOGGED, false)); this.registerDefaultState(getStateDefinition().any().setValue(SIZE, 0).setValue(IS_FLOOR, true).setValue(WATERLOGGED, false));
} }
@Override @Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> stateManager) { protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> stateManager) {
stateManager.add(WATERLOGGED, IS_FLOOR, SIZE); stateManager.add(WATERLOGGED, IS_FLOOR, SIZE);
} }
@Override @Override
public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) {
return SHAPES[state.getValue(SIZE)]; return SHAPES[state.getValue(SIZE)];
@ -95,7 +94,7 @@ public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterlogg
} }
} }
} }
@Override @Override
public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) { public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) {
boolean hasUp = isThis(world, pos.above()); boolean hasUp = isThis(world, pos.above());
@ -183,7 +182,7 @@ public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterlogg
} }
return state; return state;
} }
@Override @Override
public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) {
int size = state.getValue(SIZE); int size = state.getValue(SIZE);
@ -208,22 +207,21 @@ public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterlogg
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_CROSS_SHADED, resourceLocation); Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_CROSS_SHADED, resourceLocation);
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
BlockModelRotation rotation = blockState.getValue(IS_FLOOR) ? BlockModelRotation.X0_Y0 : BlockModelRotation.X180_Y0; BlockModelRotation rotation = blockState.getValue(IS_FLOOR) ? BlockModelRotation.X0_Y0 : BlockModelRotation.X180_Y0;
ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), stateId.getPath() + "_" + blockState.getValue(SIZE));
stateId.getPath() + "_" + blockState.getValue(SIZE));
registerBlockModel(modelId, modelId, blockState, modelCache); registerBlockModel(modelId, modelId, blockState, modelCache);
return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false);
} }
@Override @Override
public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) { public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) {
return false; return false;
} }
@Override @Override
public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) { public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) {
return false; return false;
@ -233,12 +231,12 @@ public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterlogg
public FluidState getFluidState(BlockState state) { public FluidState getFluidState(BlockState state) {
return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : Fluids.EMPTY.defaultFluidState(); return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : Fluids.EMPTY.defaultFluidState();
} }
@Override @Override
public BCLRenderLayer getRenderLayer() { public BCLRenderLayer getRenderLayer() {
return BCLRenderLayer.CUTOUT; return BCLRenderLayer.CUTOUT;
} }
static { static {
float end = 2F / 8F; float end = 2F / 8F;
float start = 5F / 8F; float start = 5F / 8F;

View file

@ -1,15 +1,7 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import org.jetbrains.annotations.Nullable;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.renderer.block.model.BlockModel;
@ -34,11 +26,17 @@ import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.EnumProperty; import net.minecraft.world.level.block.state.properties.EnumProperty;
import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.material.MaterialColor;
import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.BlockHitResult;
import org.jetbrains.annotations.Nullable;
import ru.bclib.blocks.BlockProperties.TripleShape; import ru.bclib.blocks.BlockProperties.TripleShape;
import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BasePatterns;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
public class TripleTerrainBlock extends BaseTerrainBlock { public class TripleTerrainBlock extends BaseTerrainBlock {
public static final EnumProperty<TripleShape> SHAPE = BlockProperties.TRIPLE_SHAPE; public static final EnumProperty<TripleShape> SHAPE = BlockProperties.TRIPLE_SHAPE;
@ -46,7 +44,7 @@ public class TripleTerrainBlock extends BaseTerrainBlock {
super(baseBlock, baseBlock.defaultMaterialColor()); super(baseBlock, baseBlock.defaultMaterialColor());
this.registerDefaultState(defaultBlockState().setValue(SHAPE, TripleShape.BOTTOM)); this.registerDefaultState(defaultBlockState().setValue(SHAPE, TripleShape.BOTTOM));
} }
public TripleTerrainBlock(Block baseBlock, MaterialColor color) { public TripleTerrainBlock(Block baseBlock, MaterialColor color) {
super(baseBlock, color); super(baseBlock, color);
this.registerDefaultState(defaultBlockState().setValue(SHAPE, TripleShape.BOTTOM)); this.registerDefaultState(defaultBlockState().setValue(SHAPE, TripleShape.BOTTOM));
@ -63,7 +61,7 @@ public class TripleTerrainBlock extends BaseTerrainBlock {
TripleShape shape = dir == Direction.UP ? TripleShape.BOTTOM : dir == Direction.DOWN ? TripleShape.TOP : TripleShape.MIDDLE; TripleShape shape = dir == Direction.UP ? TripleShape.BOTTOM : dir == Direction.DOWN ? TripleShape.TOP : TripleShape.MIDDLE;
return defaultBlockState().setValue(SHAPE, shape); return defaultBlockState().setValue(SHAPE, shape);
} }
@Override @Override
public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) {
TripleShape shape = state.getValue(SHAPE); TripleShape shape = state.getValue(SHAPE);
@ -78,7 +76,8 @@ public class TripleTerrainBlock extends BaseTerrainBlock {
TripleShape shape = state.getValue(SHAPE); TripleShape shape = state.getValue(SHAPE);
if (shape == TripleShape.BOTTOM) { if (shape == TripleShape.BOTTOM) {
super.randomTick(state, world, pos, random); super.randomTick(state, world, pos, random);
} else if (random.nextInt(16) == 0) { }
else if (random.nextInt(16) == 0) {
boolean bottom = canStayBottom(world, pos); boolean bottom = canStayBottom(world, pos);
if (shape == TripleShape.TOP) { if (shape == TripleShape.TOP) {
if (!bottom) { if (!bottom) {
@ -89,9 +88,11 @@ public class TripleTerrainBlock extends BaseTerrainBlock {
boolean top = canStay(state, world, pos) || isMiddle(world.getBlockState(pos.above())); boolean top = canStay(state, world, pos) || isMiddle(world.getBlockState(pos.above()));
if (!top && !bottom) { if (!top && !bottom) {
world.setBlockAndUpdate(pos, Blocks.END_STONE.defaultBlockState()); world.setBlockAndUpdate(pos, Blocks.END_STONE.defaultBlockState());
} else if (top && !bottom) { }
else if (top && !bottom) {
world.setBlockAndUpdate(pos, state.setValue(SHAPE, TripleShape.BOTTOM)); world.setBlockAndUpdate(pos, state.setValue(SHAPE, TripleShape.BOTTOM));
} else if (!top) { }
else if (!top) {
world.setBlockAndUpdate(pos, state.setValue(SHAPE, TripleShape.TOP)); world.setBlockAndUpdate(pos, state.setValue(SHAPE, TripleShape.TOP));
} }
} }
@ -103,19 +104,21 @@ public class TripleTerrainBlock extends BaseTerrainBlock {
BlockState blockState = world.getBlockState(blockPos); BlockState blockState = world.getBlockState(blockPos);
if (isMiddle(blockState)) { if (isMiddle(blockState)) {
return true; return true;
} else if (blockState.getFluidState().getAmount() == 8) { }
else if (blockState.getFluidState().getAmount() == 8) {
return false; return false;
} else { }
else {
return !blockState.isFaceSturdy(world, blockPos, Direction.UP); return !blockState.isFaceSturdy(world, blockPos, Direction.UP);
} }
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation blockId) { public BlockModel getItemModel(ResourceLocation blockId) {
return getBlockModel(blockId, defaultBlockState()); return getBlockModel(blockId, defaultBlockState());
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) {
@ -124,7 +127,8 @@ public class TripleTerrainBlock extends BaseTerrainBlock {
if (isMiddle(blockState)) { if (isMiddle(blockState)) {
ResourceLocation topId = new ResourceLocation(blockId.getNamespace(), path + "_top"); ResourceLocation topId = new ResourceLocation(blockId.getNamespace(), path + "_top");
pattern = PatternsHelper.createBlockSimple(topId); pattern = PatternsHelper.createBlockSimple(topId);
} else { }
else {
Map<String, String> textures = Maps.newHashMap(); Map<String, String> textures = Maps.newHashMap();
textures.put("%top%", "betterend:block/" + path + "_top"); textures.put("%top%", "betterend:block/" + path + "_top");
textures.put("%side%", "betterend:block/" + path + "_side"); textures.put("%side%", "betterend:block/" + path + "_side");
@ -133,14 +137,13 @@ public class TripleTerrainBlock extends BaseTerrainBlock {
} }
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
boolean isMiddle = isMiddle(blockState); boolean isMiddle = isMiddle(blockState);
String middle = isMiddle ? "_middle" : ""; String middle = isMiddle ? "_middle" : "";
ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + middle);
"block/" + stateId.getPath() + middle);
registerBlockModel(stateId, modelId, blockState, modelCache); registerBlockModel(stateId, modelId, blockState, modelCache);
if (isMiddle) { if (isMiddle) {
List<Variant> variants = Lists.newArrayList(); List<Variant> variants = Lists.newArrayList();
@ -148,17 +151,13 @@ public class TripleTerrainBlock extends BaseTerrainBlock {
variants.add(new Variant(modelId, rotation.getRotation(), false, 1)); variants.add(new Variant(modelId, rotation.getRotation(), false, 1));
} }
return new MultiVariant(variants); return new MultiVariant(variants);
} else if (blockState.getValue(SHAPE) == TripleShape.TOP) { }
return new MultiVariant(Lists.newArrayList( else if (blockState.getValue(SHAPE) == TripleShape.TOP) {
new Variant(modelId, BlockModelRotation.X180_Y0.getRotation(), false, 1), return new MultiVariant(Lists.newArrayList(new Variant(modelId, BlockModelRotation.X180_Y0.getRotation(), false, 1), new Variant(modelId, BlockModelRotation.X180_Y90.getRotation(), false, 1), new Variant(modelId, BlockModelRotation.X180_Y180.getRotation(), false, 1), new Variant(modelId, BlockModelRotation.X180_Y270.getRotation(), false, 1)));
new Variant(modelId, BlockModelRotation.X180_Y90.getRotation(), false, 1),
new Variant(modelId, BlockModelRotation.X180_Y180.getRotation(), false, 1),
new Variant(modelId, BlockModelRotation.X180_Y270.getRotation(), false, 1)
));
} }
return ModelsHelper.createRandomTopModel(modelId); return ModelsHelper.createRandomTopModel(modelId);
} }
protected boolean isMiddle(BlockState blockState) { protected boolean isMiddle(BlockState blockState) {
return blockState.is(this) && blockState.getValue(SHAPE) == TripleShape.MIDDLE; return blockState.is(this) && blockState.getValue(SHAPE) == TripleShape.MIDDLE;
} }

View file

@ -1,10 +1,6 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.List;
import java.util.Random;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
@ -37,42 +33,36 @@ import net.minecraft.world.phys.shapes.VoxelShape;
import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.client.render.BCLRenderLayer;
import ru.bclib.interfaces.IRenderTyped; import ru.bclib.interfaces.IRenderTyped;
import java.util.List;
import java.util.Random;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock, LiquidBlockContainer { public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock, LiquidBlockContainer {
private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12);
public UnderwaterPlantBlock() { public UnderwaterPlantBlock() {
super(FabricBlockSettings.of(Material.WATER_PLANT) super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).noCollission());
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.sound(SoundType.WET_GRASS)
.noCollission());
} }
public UnderwaterPlantBlock(int light) { public UnderwaterPlantBlock(int light) {
super(FabricBlockSettings.of(Material.WATER_PLANT) super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).luminance(light).sound(SoundType.WET_GRASS).noCollission());
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.luminance(light)
.sound(SoundType.WET_GRASS)
.noCollission());
} }
public UnderwaterPlantBlock(Properties settings) { public UnderwaterPlantBlock(Properties settings) {
super(settings); super(settings);
} }
@Override @Override
public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) {
Vec3 vec3d = state.getOffset(view, pos); Vec3 vec3d = state.getOffset(view, pos);
return SHAPE.move(vec3d.x, vec3d.y, vec3d.z); return SHAPE.move(vec3d.x, vec3d.y, vec3d.z);
} }
@Override @Override
public BlockBehaviour.OffsetType getOffsetType() { public BlockBehaviour.OffsetType getOffsetType() {
return BlockBehaviour.OffsetType.XZ; return BlockBehaviour.OffsetType.XZ;
} }
@Override @Override
public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) {
BlockState down = world.getBlockState(pos.below()); BlockState down = world.getBlockState(pos.below());
@ -81,7 +71,7 @@ public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements I
} }
protected abstract boolean isTerrain(BlockState state); protected abstract boolean isTerrain(BlockState state);
@Override @Override
public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) {
if (!canSurvive(state, world, pos)) { if (!canSurvive(state, world, pos)) {
@ -108,28 +98,28 @@ public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements I
public BCLRenderLayer getRenderLayer() { public BCLRenderLayer getRenderLayer() {
return BCLRenderLayer.CUTOUT; return BCLRenderLayer.CUTOUT;
} }
@Override @Override
public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) { public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) {
return true; return true;
} }
@Override @Override
public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) {
return true; return true;
} }
@Override @Override
public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) {
ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this)); ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this));
world.addFreshEntity(item); world.addFreshEntity(item);
} }
@Override @Override
public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) { public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) {
return false; return false;
} }
@Override @Override
public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) { public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) {
return false; return false;

View file

@ -1,7 +1,5 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.Random;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
@ -14,16 +12,13 @@ import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.block.state.properties.IntegerProperty;
import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.Material;
import java.util.Random;
public abstract class UnderwaterPlantWithAgeBlock extends UnderwaterPlantBlock { public abstract class UnderwaterPlantWithAgeBlock extends UnderwaterPlantBlock {
public static final IntegerProperty AGE = BlockProperties.AGE; public static final IntegerProperty AGE = BlockProperties.AGE;
public UnderwaterPlantWithAgeBlock() { public UnderwaterPlantWithAgeBlock() {
super(FabricBlockSettings.of(Material.WATER_PLANT) super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).randomTicks().noCollission());
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.sound(SoundType.WET_GRASS)
.randomTicks()
.noCollission());
} }
@Override @Override

View file

@ -1,9 +1,6 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.List;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
@ -29,25 +26,23 @@ import net.minecraft.world.phys.shapes.VoxelShape;
import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.client.render.BCLRenderLayer;
import ru.bclib.interfaces.IRenderTyped; import ru.bclib.interfaces.IRenderTyped;
import java.util.List;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public abstract class UpDownPlantBlock extends BaseBlockNotFull implements IRenderTyped { public abstract class UpDownPlantBlock extends BaseBlockNotFull implements IRenderTyped {
private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 16, 12); private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 16, 12);
public UpDownPlantBlock() { public UpDownPlantBlock() {
super(FabricBlockSettings.of(Material.PLANT) super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).noCollission());
.breakByTool(FabricToolTags.SHEARS)
.breakByHand(true)
.sound(SoundType.GRASS)
.noCollission());
} }
protected abstract boolean isTerrain(BlockState state); protected abstract boolean isTerrain(BlockState state);
@Override @Override
public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) {
return SHAPE; return SHAPE;
} }
@Override @Override
public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) {
BlockState down = world.getBlockState(pos.below()); BlockState down = world.getBlockState(pos.below());
@ -58,7 +53,7 @@ public abstract class UpDownPlantBlock extends BaseBlockNotFull implements IRend
protected boolean isSupport(BlockState state, LevelReader world, BlockPos pos) { protected boolean isSupport(BlockState state, LevelReader world, BlockPos pos) {
return canSupportCenter(world, pos.above(), Direction.UP); return canSupportCenter(world, pos.above(), Direction.UP);
} }
@Override @Override
public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) {
if (!canSurvive(state, world, pos)) { if (!canSurvive(state, world, pos)) {

View file

@ -1,9 +1,6 @@
package ru.bclib.blocks; package ru.bclib.blocks;
import java.util.List;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
@ -15,16 +12,11 @@ import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.Material;
import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootContext;
import java.util.List;
public abstract class WallMushroomBlock extends BaseWallPlantBlock { public abstract class WallMushroomBlock extends BaseWallPlantBlock {
public WallMushroomBlock(int light) { public WallMushroomBlock(int light) {
super(FabricBlockSettings.of(Material.PLANT) super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.AXES).breakByHand(true).luminance(light).hardness(0.2F).sound(SoundType.GRASS).sound(SoundType.WOOD).noCollission());
.breakByTool(FabricToolTags.AXES)
.breakByHand(true)
.luminance(light)
.hardness(0.2F)
.sound(SoundType.GRASS)
.sound(SoundType.WOOD)
.noCollission());
} }
@Override @Override

View file

@ -23,10 +23,8 @@ public class BCLibClient implements ClientModInitializer {
Registry.BLOCK.forEach(block -> { Registry.BLOCK.forEach(block -> {
if (block instanceof IRenderTyped) { if (block instanceof IRenderTyped) {
BCLRenderLayer layer = ((IRenderTyped) block).getRenderLayer(); BCLRenderLayer layer = ((IRenderTyped) block).getRenderLayer();
if (layer == BCLRenderLayer.CUTOUT) if (layer == BCLRenderLayer.CUTOUT) BlockRenderLayerMap.INSTANCE.putBlock(block, cutout);
BlockRenderLayerMap.INSTANCE.putBlock(block, cutout); else if (layer == BCLRenderLayer.TRANSLUCENT) BlockRenderLayerMap.INSTANCE.putBlock(block, translucent);
else if (layer == BCLRenderLayer.TRANSLUCENT)
BlockRenderLayerMap.INSTANCE.putBlock(block, translucent);
} }
}); });
} }

View file

@ -45,109 +45,108 @@ public class BlockSignEditScreen extends Screen {
Arrays.fill(strings, ""); Arrays.fill(strings, "");
}); });
private SignRenderer.SignModel model; private SignRenderer.SignModel model;
public BlockSignEditScreen(BaseSignBlockEntity sign) { public BlockSignEditScreen(BaseSignBlockEntity sign) {
super(new TranslatableComponent("sign.edit")); super(new TranslatableComponent("sign.edit"));
this.sign = sign; this.sign = sign;
} }
protected void init() { protected void init() {
//set up a default model //set up a default model
model = new SignRenderer.SignModel(this.minecraft.getEntityModels().bakeLayer(ModelLayers.createSignModelName(WoodType.OAK))); model = new SignRenderer.SignModel(this.minecraft.getEntityModels().bakeLayer(ModelLayers.createSignModelName(WoodType.OAK)));
minecraft.keyboardHandler.setSendRepeatsToGui(true); minecraft.keyboardHandler.setSendRepeatsToGui(true);
this.addRenderableWidget(new Button(this.width / 2 - 100, this.height / 4 + 120, 200, 20, CommonComponents.GUI_DONE, this.addRenderableWidget(new Button(this.width / 2 - 100, this.height / 4 + 120, 200, 20, CommonComponents.GUI_DONE, (buttonWidget) -> {
(buttonWidget) -> { this.finishEditing();
this.finishEditing(); }));
}));
this.sign.setEditable(false); this.sign.setEditable(false);
this.selectionManager = new TextFieldHelper(() -> { this.selectionManager = new TextFieldHelper(() -> {
return this.text[this.currentRow]; return this.text[this.currentRow];
}, (string) -> { }, (string) -> {
this.text[this.currentRow] = string; this.text[this.currentRow] = string;
this.sign.setMessage(this.currentRow, new TextComponent(string)); this.sign.setMessage(this.currentRow, new TextComponent(string));
}, TextFieldHelper.createClipboardGetter(this.minecraft), TextFieldHelper.createClipboardSetter(this.minecraft), }, TextFieldHelper.createClipboardGetter(this.minecraft), TextFieldHelper.createClipboardSetter(this.minecraft), (string) -> {
(string) -> { return this.minecraft.font.width(string) <= 90;
return this.minecraft.font.width(string) <= 90; });
});
} }
public void removed() { public void removed() {
minecraft.keyboardHandler.setSendRepeatsToGui(false); minecraft.keyboardHandler.setSendRepeatsToGui(false);
ClientPacketListener clientPlayNetworkHandler = this.minecraft.getConnection(); ClientPacketListener clientPlayNetworkHandler = this.minecraft.getConnection();
if (clientPlayNetworkHandler != null) { if (clientPlayNetworkHandler != null) {
clientPlayNetworkHandler.send(new ServerboundSignUpdatePacket(this.sign.getBlockPos(), this.text[0], this.text[1], clientPlayNetworkHandler.send(new ServerboundSignUpdatePacket(this.sign.getBlockPos(), this.text[0], this.text[1], this.text[2], this.text[3]));
this.text[2], this.text[3]));
} }
this.sign.setEditable(true); this.sign.setEditable(true);
} }
public void tick() { public void tick() {
++this.ticksSinceOpened; ++this.ticksSinceOpened;
if (!this.sign.getType().isValid(this.sign.getBlockState())) { if (!this.sign.getType().isValid(this.sign.getBlockState())) {
this.finishEditing(); this.finishEditing();
} }
} }
private void finishEditing() { private void finishEditing() {
this.sign.setChanged(); this.sign.setChanged();
this.minecraft.setScreen((Screen) null); this.minecraft.setScreen((Screen) null);
} }
public boolean charTyped(char chr, int keyCode) { public boolean charTyped(char chr, int keyCode) {
this.selectionManager.charTyped(chr); this.selectionManager.charTyped(chr);
return true; return true;
} }
public void onClose() { public void onClose() {
this.finishEditing(); this.finishEditing();
} }
public boolean keyPressed(int keyCode, int scanCode, int modifiers) { public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
if (keyCode == 265) { if (keyCode == 265) {
this.currentRow = this.currentRow - 1 & 3; this.currentRow = this.currentRow - 1 & 3;
this.selectionManager.setCursorToEnd(); this.selectionManager.setCursorToEnd();
return true; return true;
} else if (keyCode != 264 && keyCode != 257 && keyCode != 335) { }
else if (keyCode != 264 && keyCode != 257 && keyCode != 335) {
return selectionManager.keyPressed(keyCode) || super.keyPressed(keyCode, scanCode, modifiers); return selectionManager.keyPressed(keyCode) || super.keyPressed(keyCode, scanCode, modifiers);
} else { }
else {
this.currentRow = this.currentRow + 1 & 3; this.currentRow = this.currentRow + 1 & 3;
this.selectionManager.setCursorToEnd(); this.selectionManager.setCursorToEnd();
return true; return true;
} }
} }
public void render(PoseStack matrices, int mouseX, int mouseY, float delta) { public void render(PoseStack matrices, int mouseX, int mouseY, float delta) {
Lighting.setupForFlatItems(); Lighting.setupForFlatItems();
this.renderBackground(matrices); this.renderBackground(matrices);
GuiComponent.drawCenteredString(matrices, this.font, this.title, this.width / 2, 40, 16777215); GuiComponent.drawCenteredString(matrices, this.font, this.title, this.width / 2, 40, 16777215);
matrices.pushPose(); matrices.pushPose();
matrices.translate((double) (this.width / 2), 0.0D, 50.0D); matrices.translate((double) (this.width / 2), 0.0D, 50.0D);
matrices.scale(93.75F, -93.75F, 93.75F); matrices.scale(93.75F, -93.75F, 93.75F);
matrices.translate(0.0D, -1.3125D, 0.0D); matrices.translate(0.0D, -1.3125D, 0.0D);
BlockState blockState = this.sign.getBlockState(); BlockState blockState = this.sign.getBlockState();
boolean bl = blockState.getValue(BaseSignBlock.FLOOR); boolean bl = blockState.getValue(BaseSignBlock.FLOOR);
if (!bl) { if (!bl) {
matrices.translate(0.0D, -0.3125D, 0.0D); matrices.translate(0.0D, -0.3125D, 0.0D);
} }
boolean bl2 = this.ticksSinceOpened / 6 % 2 == 0; boolean bl2 = this.ticksSinceOpened / 6 % 2 == 0;
matrices.pushPose(); matrices.pushPose();
matrices.scale(0.6666667F, -0.6666667F, -0.6666667F); matrices.scale(0.6666667F, -0.6666667F, -0.6666667F);
MultiBufferSource.BufferSource immediate = minecraft.renderBuffers().bufferSource(); MultiBufferSource.BufferSource immediate = minecraft.renderBuffers().bufferSource();
VertexConsumer vertexConsumer = BaseSignBlockEntityRenderer.getConsumer(immediate, blockState.getBlock()); VertexConsumer vertexConsumer = BaseSignBlockEntityRenderer.getConsumer(immediate, blockState.getBlock());
model.root.getChild("sign").render(matrices, vertexConsumer, 15728880, OverlayTexture.NO_OVERLAY); model.root.getChild("sign").render(matrices, vertexConsumer, 15728880, OverlayTexture.NO_OVERLAY);
if (bl) { if (bl) {
model.stick.render(matrices, vertexConsumer, 15728880, OverlayTexture.NO_OVERLAY); model.stick.render(matrices, vertexConsumer, 15728880, OverlayTexture.NO_OVERLAY);
} }
matrices.popPose(); matrices.popPose();
matrices.translate(0.0D, 0.3333333432674408D, 0.046666666865348816D); matrices.translate(0.0D, 0.3333333432674408D, 0.046666666865348816D);
matrices.scale(0.010416667F, -0.010416667F, 0.010416667F); matrices.scale(0.010416667F, -0.010416667F, 0.010416667F);
int i = this.sign.getColor().getTextColor(); int i = this.sign.getColor().getTextColor();
@ -155,7 +154,7 @@ public class BlockSignEditScreen extends Screen {
int k = this.selectionManager.getSelectionPos(); int k = this.selectionManager.getSelectionPos();
int l = this.currentRow * 10 - this.text.length * 5; int l = this.currentRow * 10 - this.text.length * 5;
Matrix4f matrix4f = matrices.last().pose(); Matrix4f matrix4f = matrices.last().pose();
int m; int m;
String string2; String string2;
int s; int s;
@ -166,29 +165,25 @@ public class BlockSignEditScreen extends Screen {
if (this.font.isBidirectional()) { if (this.font.isBidirectional()) {
string2 = this.font.bidirectionalShaping(string2); string2 = this.font.bidirectionalShaping(string2);
} }
float n = (float) (-this.minecraft.font.width(string2) / 2); float n = (float) (-this.minecraft.font.width(string2) / 2);
this.minecraft.font.drawInBatch(string2, n, (float) (m * 10 - this.text.length * 5), i, false, matrix4f, this.minecraft.font.drawInBatch(string2, n, (float) (m * 10 - this.text.length * 5), i, false, matrix4f, immediate, false, 0, 15728880, false);
immediate, false, 0, 15728880, false);
if (m == this.currentRow && j >= 0 && bl2) { if (m == this.currentRow && j >= 0 && bl2) {
s = this.minecraft.font s = this.minecraft.font.width(string2.substring(0, Math.max(Math.min(j, string2.length()), 0)));
.width(string2.substring(0, Math.max(Math.min(j, string2.length()), 0)));
t = s - this.minecraft.font.width(string2) / 2; t = s - this.minecraft.font.width(string2) / 2;
if (j >= string2.length()) { if (j >= string2.length()) {
this.minecraft.font.drawInBatch("_", (float) t, (float) l, i, false, matrix4f, immediate, false, this.minecraft.font.drawInBatch("_", (float) t, (float) l, i, false, matrix4f, immediate, false, 0, 15728880, false);
0, 15728880, false);
} }
} }
} }
} }
immediate.endBatch(); immediate.endBatch();
for (m = 0; m < this.text.length; ++m) { for (m = 0; m < this.text.length; ++m) {
string2 = this.text[m]; string2 = this.text[m];
if (string2 != null && m == this.currentRow && j >= 0) { if (string2 != null && m == this.currentRow && j >= 0) {
int r = this.minecraft.font int r = this.minecraft.font.width(string2.substring(0, Math.max(Math.min(j, string2.length()), 0)));
.width(string2.substring(0, Math.max(Math.min(j, string2.length()), 0)));
s = r - this.minecraft.font.width(string2) / 2; s = r - this.minecraft.font.width(string2) / 2;
if (bl2 && j < string2.length()) { if (bl2 && j < string2.length()) {
int var31 = l - 1; int var31 = l - 1;
@ -196,14 +191,12 @@ public class BlockSignEditScreen extends Screen {
this.minecraft.font.getClass(); this.minecraft.font.getClass();
fill(matrices, s, var31, var10003, l + 9, -16777216 | i); fill(matrices, s, var31, var10003, l + 9, -16777216 | i);
} }
if (k != j) { if (k != j) {
t = Math.min(j, k); t = Math.min(j, k);
int u = Math.max(j, k); int u = Math.max(j, k);
int v = this.minecraft.font.width(string2.substring(0, t)) int v = this.minecraft.font.width(string2.substring(0, t)) - this.minecraft.font.width(string2) / 2;
- this.minecraft.font.width(string2) / 2; int w = this.minecraft.font.width(string2.substring(0, u)) - this.minecraft.font.width(string2) / 2;
int w = this.minecraft.font.width(string2.substring(0, u))
- this.minecraft.font.width(string2) / 2;
int x = Math.min(v, w); int x = Math.min(v, w);
int y = Math.max(v, w); int y = Math.max(v, w);
Tesselator tessellator = Tesselator.getInstance(); Tesselator tessellator = Tesselator.getInstance();
@ -225,7 +218,7 @@ public class BlockSignEditScreen extends Screen {
} }
} }
} }
matrices.popPose(); matrices.popPose();
Lighting.setupFor3DItems(); Lighting.setupFor3DItems();
super.render(matrices, mouseX, mouseY, delta); super.render(matrices, mouseX, mouseY, delta);

View file

@ -2,90 +2,67 @@ package ru.bclib.client.models;
import net.minecraft.client.model.geom.ModelPart; import net.minecraft.client.model.geom.ModelPart;
import net.minecraft.client.model.geom.PartPose; import net.minecraft.client.model.geom.PartPose;
import net.minecraft.client.model.geom.builders.*; import net.minecraft.client.model.geom.builders.CubeDeformation;
import net.minecraft.client.model.geom.builders.CubeListBuilder;
import net.minecraft.client.model.geom.builders.LayerDefinition;
import net.minecraft.client.model.geom.builders.MeshDefinition;
import net.minecraft.client.model.geom.builders.PartDefinition;
public class BaseChestBlockModel { public class BaseChestBlockModel {
public final ModelPart partA; public final ModelPart partA;
public final ModelPart partC; public final ModelPart partC;
public final ModelPart partB; public final ModelPart partB;
public final ModelPart partRightA; public final ModelPart partRightA;
public final ModelPart partRightC; public final ModelPart partRightC;
public final ModelPart partRightB; public final ModelPart partRightB;
public final ModelPart partLeftA; public final ModelPart partLeftA;
public final ModelPart partLeftC; public final ModelPart partLeftC;
public final ModelPart partLeftB; public final ModelPart partLeftB;
public static LayerDefinition getTexturedModelData() { public static LayerDefinition getTexturedModelData() {
MeshDefinition modelData = new MeshDefinition(); MeshDefinition modelData = new MeshDefinition();
PartDefinition modelPartData = modelData.getRoot(); PartDefinition modelPartData = modelData.getRoot();
CubeDeformation deformation_partC = new CubeDeformation(0.0f); CubeDeformation deformation_partC = new CubeDeformation(0.0f);
modelPartData.addOrReplaceChild("partC", CubeListBuilder.create() modelPartData.addOrReplaceChild("partC", CubeListBuilder.create().texOffs(0, 19).addBox(1.0f, 0.0f, 1.0f, 14.0f, 9.0f, 14.0f, deformation_partC), PartPose.ZERO);
.texOffs(0, 19)
.addBox(1.0f, 0.0f, 1.0f, 14.0f, 9.0f, 14.0f, deformation_partC), CubeDeformation deformation_partA = new CubeDeformation(0.0f);
PartPose.ZERO); modelPartData.addOrReplaceChild("partA", CubeListBuilder.create().texOffs(0, 0).addBox(1.0f, 0.0f, 0.0f, 14.0f, 5.0f, 14.0f, deformation_partA), PartPose.offset(0.0f, 9.0f, 1.0f));
CubeDeformation deformation_partA = new CubeDeformation(0.0f); CubeDeformation deformation_partB = new CubeDeformation(0.0f);
modelPartData.addOrReplaceChild("partA", CubeListBuilder.create() modelPartData.addOrReplaceChild("partB", CubeListBuilder.create().texOffs(0, 0).addBox(7.0f, -1.0f, 15.0f, 2.0f, 4.0f, 1.0f, deformation_partB), PartPose.offset(0.0f, 8.0f, 0.0f));
.texOffs(0, 0)
.addBox(1.0f, 0.0f, 0.0f, 14.0f, 5.0f, 14.0f, deformation_partA), CubeDeformation deformation_partRightC = new CubeDeformation(0.0f);
PartPose.offset(0.0f, 9.0f, 1.0f)); modelPartData.addOrReplaceChild("partRightC", CubeListBuilder.create().texOffs(0, 19).addBox(1.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partRightC), PartPose.ZERO);
CubeDeformation deformation_partB = new CubeDeformation(0.0f); CubeDeformation deformation_partRightA = new CubeDeformation(0.0f);
modelPartData.addOrReplaceChild("partB", CubeListBuilder.create() modelPartData.addOrReplaceChild("partRightA", CubeListBuilder.create().texOffs(0, 0).addBox(1.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partRightA), PartPose.offset(0.0f, 9.0f, 1.0f));
.texOffs(0, 0)
.addBox(7.0f, -1.0f, 15.0f, 2.0f, 4.0f, 1.0f, deformation_partB), CubeDeformation deformation_partRightB = new CubeDeformation(0.0f);
PartPose.offset(0.0f, 8.0f, 0.0f)); PartDefinition partRightB = modelPartData.addOrReplaceChild("partRightB", CubeListBuilder.create().texOffs(0, 0).addBox(15.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partRightB), PartPose.offset(0.0f, 8.0f, 0.0f));
CubeDeformation deformation_partRightC = new CubeDeformation(0.0f); CubeDeformation deformation_partLeftC = new CubeDeformation(0.0f);
modelPartData.addOrReplaceChild("partRightC", CubeListBuilder.create() modelPartData.addOrReplaceChild("partLeftC", CubeListBuilder.create().texOffs(0, 19).addBox(0.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partLeftC), PartPose.ZERO);
.texOffs(0, 19)
.addBox(1.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partRightC), CubeDeformation deformation_partLeftA = new CubeDeformation(0.0f);
PartPose.ZERO); modelPartData.addOrReplaceChild("partLeftA", CubeListBuilder.create().texOffs(0, 0).addBox(0.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partLeftA), PartPose.offset(0.0f, 9.0f, 1.0f));
CubeDeformation deformation_partRightA = new CubeDeformation(0.0f); CubeDeformation deformation_partLeftB = new CubeDeformation(0.0f);
modelPartData.addOrReplaceChild("partRightA", CubeListBuilder.create() modelPartData.addOrReplaceChild("partLeftB", CubeListBuilder.create().texOffs(0, 0).addBox(0.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partLeftB), PartPose.offset(0.0f, 8.0f, 0.0f));
.texOffs(0, 0)
.addBox(1.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partRightA), return LayerDefinition.create(modelData, 64, 64);
PartPose.offset(0.0f, 9.0f, 1.0f)); }
CubeDeformation deformation_partRightB = new CubeDeformation(0.0f); public BaseChestBlockModel(ModelPart modelPart) {
PartDefinition partRightB = modelPartData.addOrReplaceChild("partRightB", CubeListBuilder.create() super();
.texOffs(0, 0)
.addBox(15.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partRightB), partC = modelPart.getChild("partC");
PartPose.offset(0.0f, 8.0f, 0.0f)); partA = modelPart.getChild("partA");
partB = modelPart.getChild("partB");
CubeDeformation deformation_partLeftC = new CubeDeformation(0.0f); partRightC = modelPart.getChild("partRightC");
modelPartData.addOrReplaceChild("partLeftC", CubeListBuilder.create() partRightA = modelPart.getChild("partRightA");
.texOffs(0, 19) partRightB = modelPart.getChild("partRightB");
.addBox(0.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partLeftC), partLeftC = modelPart.getChild("partLeftC");
PartPose.ZERO); partLeftA = modelPart.getChild("partLeftA");
partLeftB = modelPart.getChild("partLeftB");
CubeDeformation deformation_partLeftA = new CubeDeformation(0.0f); }
modelPartData.addOrReplaceChild("partLeftA", CubeListBuilder.create()
.texOffs(0, 0)
.addBox(0.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partLeftA),
PartPose.offset(0.0f, 9.0f, 1.0f));
CubeDeformation deformation_partLeftB = new CubeDeformation(0.0f);
modelPartData.addOrReplaceChild("partLeftB", CubeListBuilder.create()
.texOffs(0, 0)
.addBox(0.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partLeftB),
PartPose.offset(0.0f, 8.0f, 0.0f));
return LayerDefinition.create(modelData, 64, 64);
}
public BaseChestBlockModel(ModelPart modelPart) {
super();
partC = modelPart.getChild("partC");
partA = modelPart.getChild("partA");
partB = modelPart.getChild("partB");
partRightC = modelPart.getChild("partRightC");
partRightA = modelPart.getChild("partRightA");
partRightB = modelPart.getChild("partRightB");
partLeftC = modelPart.getChild("partLeftC");
partLeftA = modelPart.getChild("partLeftA");
partLeftB = modelPart.getChild("partLeftB");
}
} }

View file

@ -57,5 +57,5 @@ public class BasePatterns {
public final static ResourceLocation ITEM_GENERATED = BCLib.makeID("patterns/item/pattern_item_generated.json"); public final static ResourceLocation ITEM_GENERATED = BCLib.makeID("patterns/item/pattern_item_generated.json");
public final static ResourceLocation ITEM_HANDHELD = BCLib.makeID("patterns/item/pattern_item_handheld.json"); public final static ResourceLocation ITEM_HANDHELD = BCLib.makeID("patterns/item/pattern_item_handheld.json");
public final static ResourceLocation ITEM_SPAWN_EGG = BCLib.makeID("patterns/item/pattern_item_spawn_egg.json"); public final static ResourceLocation ITEM_SPAWN_EGG = BCLib.makeID("patterns/item/pattern_item_spawn_egg.json");
} }

View file

@ -1,34 +1,33 @@
package ru.bclib.client.models; package ru.bclib.client.models;
import static net.minecraft.client.resources.model.ModelBakery.MISSING_MODEL_LOCATION;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.renderer.block.model.BlockModel;
import net.minecraft.client.resources.model.UnbakedModel; import net.minecraft.client.resources.model.UnbakedModel;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.Nullable;
import ru.bclib.BCLib; import ru.bclib.BCLib;
import java.util.Map;
import java.util.Optional;
import static net.minecraft.client.resources.model.ModelBakery.MISSING_MODEL_LOCATION;
public interface BlockModelProvider extends ItemModelProvider { public interface BlockModelProvider extends ItemModelProvider {
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
default @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { default @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) {
Optional<String> pattern = PatternsHelper.createBlockSimple(resourceLocation); Optional<String> pattern = PatternsHelper.createBlockSimple(resourceLocation);
return ModelsHelper.fromPattern(pattern); return ModelsHelper.fromPattern(pattern);
} }
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
default UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { default UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath()); ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath());
registerBlockModel(stateId, modelId, blockState, modelCache); registerBlockModel(stateId, modelId, blockState, modelCache);
return ModelsHelper.createBlockSimple(modelId); return ModelsHelper.createBlockSimple(modelId);
} }
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
default void registerBlockModel(ResourceLocation stateId, ResourceLocation modelId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) { default void registerBlockModel(ResourceLocation stateId, ResourceLocation modelId, BlockState blockState, Map<ResourceLocation, UnbakedModel> modelCache) {
if (!modelCache.containsKey(modelId)) { if (!modelCache.containsKey(modelId)) {
@ -36,7 +35,8 @@ public interface BlockModelProvider extends ItemModelProvider {
if (model != null) { if (model != null) {
model.name = modelId.toString(); model.name = modelId.toString();
modelCache.put(modelId, model); modelCache.put(modelId, model);
} else { }
else {
BCLib.LOGGER.warning("Error loading model: {}", modelId); BCLib.LOGGER.warning("Error loading model: {}", modelId);
modelCache.put(modelId, modelCache.get(MISSING_MODEL_LOCATION)); modelCache.put(modelId, modelCache.get(MISSING_MODEL_LOCATION));
} }

View file

@ -1,12 +1,7 @@
package ru.bclib.client.models; package ru.bclib.client.models;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.mojang.math.Transformation; import com.mojang.math.Transformation;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.renderer.block.model.BlockModel;
@ -22,39 +17,43 @@ import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.StateDefinition;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public class ModelsHelper { public class ModelsHelper {
public static BlockModel fromPattern(Optional<String> pattern) { public static BlockModel fromPattern(Optional<String> pattern) {
return pattern.map(BlockModel::fromString).orElse(null); return pattern.map(BlockModel::fromString).orElse(null);
} }
public static BlockModel createItemModel(ResourceLocation resourceLocation) { public static BlockModel createItemModel(ResourceLocation resourceLocation) {
return fromPattern(PatternsHelper.createItemGenerated(resourceLocation)); return fromPattern(PatternsHelper.createItemGenerated(resourceLocation));
} }
public static BlockModel createHandheldItem(ResourceLocation resourceLocation) { public static BlockModel createHandheldItem(ResourceLocation resourceLocation) {
return fromPattern(PatternsHelper.createItemHandheld(resourceLocation)); return fromPattern(PatternsHelper.createItemHandheld(resourceLocation));
} }
public static BlockModel createBlockItem(ResourceLocation resourceLocation) { public static BlockModel createBlockItem(ResourceLocation resourceLocation) {
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.ITEM_BLOCK, resourceLocation); Optional<String> pattern = PatternsHelper.createJson(BasePatterns.ITEM_BLOCK, resourceLocation);
return fromPattern(pattern); return fromPattern(pattern);
} }
public static BlockModel createBlockEmpty(ResourceLocation resourceLocation) { public static BlockModel createBlockEmpty(ResourceLocation resourceLocation) {
Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_EMPTY, resourceLocation); Optional<String> pattern = PatternsHelper.createJson(BasePatterns.BLOCK_EMPTY, resourceLocation);
return fromPattern(pattern); return fromPattern(pattern);
} }
public static MultiVariant createMultiVariant(ResourceLocation resourceLocation, Transformation transform, boolean uvLock) { public static MultiVariant createMultiVariant(ResourceLocation resourceLocation, Transformation transform, boolean uvLock) {
Variant variant = new Variant(resourceLocation, transform, uvLock, 1); Variant variant = new Variant(resourceLocation, transform, uvLock, 1);
return new MultiVariant(Lists.newArrayList(variant)); return new MultiVariant(Lists.newArrayList(variant));
} }
public static MultiVariant createBlockSimple(ResourceLocation resourceLocation) { public static MultiVariant createBlockSimple(ResourceLocation resourceLocation) {
return createMultiVariant(resourceLocation, Transformation.identity(), false); return createMultiVariant(resourceLocation, Transformation.identity(), false);
} }
public static MultiVariant createFacingModel(ResourceLocation resourceLocation, Direction facing, boolean uvLock, boolean inverted) { public static MultiVariant createFacingModel(ResourceLocation resourceLocation, Direction facing, boolean uvLock, boolean inverted) {
if (inverted) { if (inverted) {
facing = facing.getOpposite(); facing = facing.getOpposite();
@ -62,45 +61,45 @@ public class ModelsHelper {
BlockModelRotation rotation = BlockModelRotation.by(0, (int) facing.toYRot()); BlockModelRotation rotation = BlockModelRotation.by(0, (int) facing.toYRot());
return createMultiVariant(resourceLocation, rotation.getRotation(), uvLock); return createMultiVariant(resourceLocation, rotation.getRotation(), uvLock);
} }
public static MultiVariant createRotatedModel(ResourceLocation resourceLocation, Direction.Axis axis) { public static MultiVariant createRotatedModel(ResourceLocation resourceLocation, Direction.Axis axis) {
BlockModelRotation rotation = BlockModelRotation.X0_Y0; BlockModelRotation rotation = BlockModelRotation.X0_Y0;
switch (axis) { switch (axis) {
case X: rotation = BlockModelRotation.X90_Y90; break; case X:
case Z: rotation = BlockModelRotation.X90_Y0; break; rotation = BlockModelRotation.X90_Y90;
default: break; break;
case Z:
rotation = BlockModelRotation.X90_Y0;
break;
default:
break;
} }
return createMultiVariant(resourceLocation, rotation.getRotation(), false); return createMultiVariant(resourceLocation, rotation.getRotation(), false);
} }
public static MultiVariant createRandomTopModel(ResourceLocation resourceLocation) { public static MultiVariant createRandomTopModel(ResourceLocation resourceLocation) {
return new MultiVariant(Lists.newArrayList( return new MultiVariant(Lists.newArrayList(new Variant(resourceLocation, Transformation.identity(), false, 1), new Variant(resourceLocation, BlockModelRotation.X0_Y90.getRotation(), false, 1), new Variant(resourceLocation, BlockModelRotation.X0_Y180.getRotation(), false, 1), new Variant(resourceLocation, BlockModelRotation.X0_Y270.getRotation(), false, 1)));
new Variant(resourceLocation, Transformation.identity(), false, 1),
new Variant(resourceLocation, BlockModelRotation.X0_Y90.getRotation(), false, 1),
new Variant(resourceLocation, BlockModelRotation.X0_Y180.getRotation(), false, 1),
new Variant(resourceLocation, BlockModelRotation.X0_Y270.getRotation(), false, 1)
));
} }
public static class MultiPartBuilder { public static class MultiPartBuilder {
private final static MultiPartBuilder BUILDER = new MultiPartBuilder(); private final static MultiPartBuilder BUILDER = new MultiPartBuilder();
public static MultiPartBuilder create(StateDefinition<Block, BlockState> stateDefinition) { public static MultiPartBuilder create(StateDefinition<Block, BlockState> stateDefinition) {
BUILDER.stateDefinition = stateDefinition; BUILDER.stateDefinition = stateDefinition;
BUILDER.modelParts.clear(); BUILDER.modelParts.clear();
return BUILDER; return BUILDER;
} }
private final List<ModelPart> modelParts = Lists.newArrayList(); private final List<ModelPart> modelParts = Lists.newArrayList();
private StateDefinition<Block, BlockState> stateDefinition; private StateDefinition<Block, BlockState> stateDefinition;
private MultiPartBuilder() {} private MultiPartBuilder() {}
public ModelPart part(ResourceLocation modelId) { public ModelPart part(ResourceLocation modelId) {
return new ModelPart(modelId); return new ModelPart(modelId);
} }
public MultiPart build() { public MultiPart build() {
if (modelParts.size() > 0) { if (modelParts.size() > 0) {
List<Selector> selectors = Lists.newArrayList(); List<Selector> selectors = Lists.newArrayList();
@ -113,32 +112,32 @@ public class ModelsHelper {
} }
throw new IllegalStateException("At least one model part need to be created."); throw new IllegalStateException("At least one model part need to be created.");
} }
public class ModelPart { public class ModelPart {
private final ResourceLocation modelId; private final ResourceLocation modelId;
private Transformation transform = Transformation.identity(); private Transformation transform = Transformation.identity();
private Condition condition = Condition.TRUE; private Condition condition = Condition.TRUE;
private boolean uvLock = false; private boolean uvLock = false;
private ModelPart(ResourceLocation modelId) { private ModelPart(ResourceLocation modelId) {
this.modelId = modelId; this.modelId = modelId;
} }
public ModelPart setCondition(Function<BlockState, Boolean> condition) { public ModelPart setCondition(Function<BlockState, Boolean> condition) {
this.condition = stateDefinition -> condition::apply; this.condition = stateDefinition -> condition::apply;
return this; return this;
} }
public ModelPart setTransformation(Transformation transform) { public ModelPart setTransformation(Transformation transform) {
this.transform = transform; this.transform = transform;
return this; return this;
} }
public ModelPart setUVLock(boolean value) { public ModelPart setUVLock(boolean value) {
this.uvLock = value; this.uvLock = value;
return this; return this;
} }
public void add() { public void add() {
modelParts.add(this); modelParts.add(this);
} }

View file

@ -1,5 +1,10 @@
package ru.bclib.client.models; package ru.bclib.client.models;
import com.google.common.collect.Maps;
import net.minecraft.client.Minecraft;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.ResourceManager;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -8,58 +13,52 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.google.common.collect.Maps;
import net.minecraft.client.Minecraft;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.ResourceManager;
public class PatternsHelper { public class PatternsHelper {
public static Optional<String> createItemGenerated(ResourceLocation itemId) { public static Optional<String> createItemGenerated(ResourceLocation itemId) {
return createJson(BasePatterns.ITEM_GENERATED, itemId); return createJson(BasePatterns.ITEM_GENERATED, itemId);
} }
public static Optional<String> createItemHandheld(ResourceLocation itemId) { public static Optional<String> createItemHandheld(ResourceLocation itemId) {
return createJson(BasePatterns.ITEM_HANDHELD, itemId); return createJson(BasePatterns.ITEM_HANDHELD, itemId);
} }
public static Optional<String> createBlockSimple(ResourceLocation blockId) { public static Optional<String> createBlockSimple(ResourceLocation blockId) {
return createJson(BasePatterns.BLOCK_BASE, blockId); return createJson(BasePatterns.BLOCK_BASE, blockId);
} }
public static Optional<String> createBlockEmpty(ResourceLocation blockId) { public static Optional<String> createBlockEmpty(ResourceLocation blockId) {
return createJson(BasePatterns.BLOCK_EMPTY, blockId); return createJson(BasePatterns.BLOCK_EMPTY, blockId);
} }
public static Optional<String> createBlockPillar(ResourceLocation blockId) { public static Optional<String> createBlockPillar(ResourceLocation blockId) {
return createJson(BasePatterns.BLOCK_PILLAR, blockId); return createJson(BasePatterns.BLOCK_PILLAR, blockId);
} }
public static Optional<String> createBlockBottomTop(ResourceLocation blockId) { public static Optional<String> createBlockBottomTop(ResourceLocation blockId) {
return createJson(BasePatterns.BLOCK_BOTTOM_TOP, blockId); return createJson(BasePatterns.BLOCK_BOTTOM_TOP, blockId);
} }
public static Optional<String> createBlockColored(ResourceLocation blockId) { public static Optional<String> createBlockColored(ResourceLocation blockId) {
return createJson(BasePatterns.BLOCK_COLORED, blockId); return createJson(BasePatterns.BLOCK_COLORED, blockId);
} }
public static Optional<String> createJson(ResourceLocation patternId, ResourceLocation blockId) { public static Optional<String> createJson(ResourceLocation patternId, ResourceLocation blockId) {
Map<String, String> textures = Maps.newHashMap(); Map<String, String> textures = Maps.newHashMap();
textures.put("%modid%", blockId.getNamespace()); textures.put("%modid%", blockId.getNamespace());
textures.put("%texture%", blockId.getPath()); textures.put("%texture%", blockId.getPath());
return createJson(patternId, textures); return createJson(patternId, textures);
} }
public static Optional<String> createJson(ResourceLocation patternId, Map<String, String> textures) { public static Optional<String> createJson(ResourceLocation patternId, Map<String, String> textures) {
ResourceManager resourceManager = Minecraft.getInstance().getResourceManager(); ResourceManager resourceManager = Minecraft.getInstance().getResourceManager();
try (InputStream input = resourceManager.getResource(patternId).getInputStream()) { try (InputStream input = resourceManager.getResource(patternId).getInputStream()) {
String json = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)) String json = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)).lines().collect(Collectors.joining());
.lines().collect(Collectors.joining());
for (Map.Entry<String, String> texture : textures.entrySet()) { for (Map.Entry<String, String> texture : textures.entrySet()) {
json = json.replace(texture.getKey(), texture.getValue()); json = json.replace(texture.getKey(), texture.getValue());
} }
return Optional.of(json); return Optional.of(json);
} catch (Exception ex) { }
catch (Exception ex) {
return Optional.empty(); return Optional.empty();
} }
} }

View file

@ -1,6 +1,5 @@
package ru.bclib.client.render; package ru.bclib.client.render;
public enum BCLRenderLayer { public enum BCLRenderLayer {
CUTOUT, CUTOUT, TRANSLUCENT;
TRANSLUCENT;
} }

View file

@ -18,7 +18,11 @@ import net.minecraft.core.Direction;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.AbstractChestBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.ChestBlock;
import net.minecraft.world.level.block.DoubleBlockCombiner;
import net.minecraft.world.level.block.DoubleBlockCombiner.NeighborCombineResult; import net.minecraft.world.level.block.DoubleBlockCombiner.NeighborCombineResult;
import net.minecraft.world.level.block.entity.ChestBlockEntity; import net.minecraft.world.level.block.entity.ChestBlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
@ -32,17 +36,18 @@ import java.util.HashMap;
public class BaseChestBlockEntityRenderer implements BlockEntityRenderer<BaseChestBlockEntity> { public class BaseChestBlockEntityRenderer implements BlockEntityRenderer<BaseChestBlockEntity> {
private static final HashMap<Block, RenderType[]> LAYERS = Maps.newHashMap(); private static final HashMap<Block, RenderType[]> LAYERS = Maps.newHashMap();
private static final RenderType[] defaultLayer; private static final RenderType[] defaultLayer;
private static final int ID_NORMAL = 0; private static final int ID_NORMAL = 0;
private static final int ID_LEFT = 1; private static final int ID_LEFT = 1;
private static final int ID_RIGHT = 2; private static final int ID_RIGHT = 2;
private final BaseChestBlockModel chestModel; private final BaseChestBlockModel chestModel;
public BaseChestBlockEntityRenderer(BlockEntityRendererProvider.Context ctx) { public BaseChestBlockEntityRenderer(BlockEntityRendererProvider.Context ctx) {
super(); super();
chestModel = new BaseChestBlockModel(BaseChestBlockModel.getTexturedModelData().bakeRoot()); chestModel = new BaseChestBlockModel(BaseChestBlockModel.getTexturedModelData().bakeRoot());
} }
public void render(BaseChestBlockEntity entity, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light, int overlay) { public void render(BaseChestBlockEntity entity, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light, int overlay) {
Level world = entity.getLevel(); Level world = entity.getLevel();
boolean worldExists = world != null; boolean worldExists = world != null;
@ -54,40 +59,42 @@ public class BaseChestBlockEntityRenderer implements BlockEntityRenderer<BaseChe
boolean isDouble = chestType != ChestType.SINGLE; boolean isDouble = chestType != ChestType.SINGLE;
float f = ((Direction) blockState.getValue(ChestBlock.FACING)).toYRot(); float f = ((Direction) blockState.getValue(ChestBlock.FACING)).toYRot();
NeighborCombineResult<? extends ChestBlockEntity> propertySource; NeighborCombineResult<? extends ChestBlockEntity> propertySource;
matrices.pushPose(); matrices.pushPose();
matrices.translate(0.5D, 0.5D, 0.5D); matrices.translate(0.5D, 0.5D, 0.5D);
matrices.mulPose(Vector3f.YP.rotationDegrees(-f)); matrices.mulPose(Vector3f.YP.rotationDegrees(-f));
matrices.translate(-0.5D, -0.5D, -0.5D); matrices.translate(-0.5D, -0.5D, -0.5D);
if (worldExists) { if (worldExists) {
propertySource = abstractChestBlock.combine(blockState, world, entity.getBlockPos(), true); propertySource = abstractChestBlock.combine(blockState, world, entity.getBlockPos(), true);
} else { }
else {
propertySource = DoubleBlockCombiner.Combiner::acceptNone; propertySource = DoubleBlockCombiner.Combiner::acceptNone;
} }
float pitch = ((Float2FloatFunction) propertySource.apply(ChestBlock.opennessCombiner(entity))).get(tickDelta); float pitch = ((Float2FloatFunction) propertySource.apply(ChestBlock.opennessCombiner(entity))).get(tickDelta);
pitch = 1.0F - pitch; pitch = 1.0F - pitch;
pitch = 1.0F - pitch * pitch * pitch; pitch = 1.0F - pitch * pitch * pitch;
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({"unchecked", "rawtypes"}) int blockLight = ((Int2IntFunction) propertySource.apply(new BrightnessCombiner())).applyAsInt(light);
int blockLight = ((Int2IntFunction) propertySource.apply(new BrightnessCombiner())).applyAsInt(light);
VertexConsumer vertexConsumer = getConsumer(vertexConsumers, block, chestType); VertexConsumer vertexConsumer = getConsumer(vertexConsumers, block, chestType);
if (isDouble) { if (isDouble) {
if (chestType == ChestType.LEFT) { if (chestType == ChestType.LEFT) {
renderParts(matrices, vertexConsumer, chestModel.partLeftA, chestModel.partLeftB, chestModel.partLeftC, pitch, blockLight, overlay); renderParts(matrices, vertexConsumer, chestModel.partLeftA, chestModel.partLeftB, chestModel.partLeftC, pitch, blockLight, overlay);
} else { }
else {
renderParts(matrices, vertexConsumer, chestModel.partRightA, chestModel.partRightB, chestModel.partRightC, pitch, blockLight, overlay); renderParts(matrices, vertexConsumer, chestModel.partRightA, chestModel.partRightB, chestModel.partRightC, pitch, blockLight, overlay);
} }
} else { }
else {
renderParts(matrices, vertexConsumer, chestModel.partA, chestModel.partB, chestModel.partC, pitch, blockLight, overlay); renderParts(matrices, vertexConsumer, chestModel.partA, chestModel.partB, chestModel.partC, pitch, blockLight, overlay);
} }
matrices.popPose(); matrices.popPose();
} }
} }
private void renderParts(PoseStack matrices, VertexConsumer vertices, ModelPart modelPart, ModelPart modelPart2, ModelPart modelPart3, float pitch, int light, int overlay) { private void renderParts(PoseStack matrices, VertexConsumer vertices, ModelPart modelPart, ModelPart modelPart2, ModelPart modelPart3, float pitch, int light, int overlay) {
modelPart.xRot = -(pitch * 1.5707964F); modelPart.xRot = -(pitch * 1.5707964F);
modelPart2.xRot = modelPart.xRot; modelPart2.xRot = modelPart.xRot;
@ -95,7 +102,7 @@ public class BaseChestBlockEntityRenderer implements BlockEntityRenderer<BaseChe
modelPart2.render(matrices, vertices, light, overlay); modelPart2.render(matrices, vertices, light, overlay);
modelPart3.render(matrices, vertices, light, overlay); modelPart3.render(matrices, vertices, light, overlay);
} }
private static RenderType getChestTexture(ChestType type, RenderType[] layers) { private static RenderType getChestTexture(ChestType type, RenderType[] layers) {
return switch (type) { return switch (type) {
case LEFT -> layers[ID_LEFT]; case LEFT -> layers[ID_LEFT];
@ -103,28 +110,20 @@ public class BaseChestBlockEntityRenderer implements BlockEntityRenderer<BaseChe
default -> layers[ID_NORMAL]; default -> layers[ID_NORMAL];
}; };
} }
public static VertexConsumer getConsumer(MultiBufferSource provider, Block block, ChestType chestType) { public static VertexConsumer getConsumer(MultiBufferSource provider, Block block, ChestType chestType) {
RenderType[] layers = LAYERS.getOrDefault(block, defaultLayer); RenderType[] layers = LAYERS.getOrDefault(block, defaultLayer);
return provider.getBuffer(getChestTexture(chestType, layers)); return provider.getBuffer(getChestTexture(chestType, layers));
} }
public static void registerRenderLayer(Block block) { public static void registerRenderLayer(Block block) {
ResourceLocation blockId = Registry.BLOCK.getKey(block); ResourceLocation blockId = Registry.BLOCK.getKey(block);
String modId = blockId.getNamespace(); String modId = blockId.getNamespace();
String path = blockId.getPath(); String path = blockId.getPath();
LAYERS.put(block, new RenderType[] { LAYERS.put(block, new RenderType[] {RenderType.entityCutout(new ResourceLocation(modId, "textures/entity/chest/" + path + ".png")), RenderType.entityCutout(new ResourceLocation(modId, "textures/entity/chest/" + path + "_left.png")), RenderType.entityCutout(new ResourceLocation(modId, "textures/entity/chest/" + path + "_right.png"))});
RenderType.entityCutout(new ResourceLocation(modId, "textures/entity/chest/" + path + ".png")),
RenderType.entityCutout(new ResourceLocation(modId, "textures/entity/chest/" + path + "_left.png")),
RenderType.entityCutout(new ResourceLocation(modId, "textures/entity/chest/" + path + "_right.png"))
});
} }
static { static {
defaultLayer = new RenderType[] { defaultLayer = new RenderType[] {RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal.png")), RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal_left.png")), RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal_right.png"))};
RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal.png")),
RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal_left.png")),
RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal_right.png"))
};
} }
} }

View file

@ -39,42 +39,42 @@ public class BaseSignBlockEntityRenderer implements BlockEntityRenderer<BaseSign
private static final RenderType defaultLayer; private static final RenderType defaultLayer;
private final Font font; private final Font font;
private final SignRenderer.SignModel model; private final SignRenderer.SignModel model;
private static final int OUTLINE_RENDER_DISTANCE = Mth.square(16); private static final int OUTLINE_RENDER_DISTANCE = Mth.square(16);
public BaseSignBlockEntityRenderer(BlockEntityRendererProvider.Context ctx) { public BaseSignBlockEntityRenderer(BlockEntityRendererProvider.Context ctx) {
super(); super();
this.font = ctx.getFont(); this.font = ctx.getFont();
//set up a default model //set up a default model
model = new SignRenderer.SignModel(ctx.bakeLayer(ModelLayers.createSignModelName(WoodType.OAK))); model = new SignRenderer.SignModel(ctx.bakeLayer(ModelLayers.createSignModelName(WoodType.OAK)));
} }
public void render(BaseSignBlockEntity signBlockEntity, float tickDelta, PoseStack matrixStack, public void render(BaseSignBlockEntity signBlockEntity, float tickDelta, PoseStack matrixStack, MultiBufferSource provider, int light, int overlay) {
MultiBufferSource provider, int light, int overlay) {
BlockState state = signBlockEntity.getBlockState(); BlockState state = signBlockEntity.getBlockState();
matrixStack.pushPose(); matrixStack.pushPose();
matrixStack.translate(0.5D, 0.5D, 0.5D); matrixStack.translate(0.5D, 0.5D, 0.5D);
float angle = -((float) (state.getValue(StandingSignBlock.ROTATION) * 360) / 16.0F); float angle = -((float) (state.getValue(StandingSignBlock.ROTATION) * 360) / 16.0F);
BlockState blockState = signBlockEntity.getBlockState(); BlockState blockState = signBlockEntity.getBlockState();
if (blockState.getValue(BaseSignBlock.FLOOR)) { if (blockState.getValue(BaseSignBlock.FLOOR)) {
matrixStack.mulPose(Vector3f.YP.rotationDegrees(angle)); matrixStack.mulPose(Vector3f.YP.rotationDegrees(angle));
model.stick.visible = true; model.stick.visible = true;
} else { }
else {
matrixStack.mulPose(Vector3f.YP.rotationDegrees(angle + 180)); matrixStack.mulPose(Vector3f.YP.rotationDegrees(angle + 180));
matrixStack.translate(0.0D, -0.3125D, -0.4375D); matrixStack.translate(0.0D, -0.3125D, -0.4375D);
model.stick.visible = false; model.stick.visible = false;
} }
matrixStack.pushPose(); matrixStack.pushPose();
matrixStack.scale(0.6666667F, -0.6666667F, -0.6666667F); matrixStack.scale(0.6666667F, -0.6666667F, -0.6666667F);
VertexConsumer vertexConsumer = getConsumer(provider, state.getBlock()); VertexConsumer vertexConsumer = getConsumer(provider, state.getBlock());
model.root.render(matrixStack, vertexConsumer, light, overlay); model.root.render(matrixStack, vertexConsumer, light, overlay);
//model.stick.render(matrixStack, vertexConsumer, light, overlay); //model.stick.render(matrixStack, vertexConsumer, light, overlay);
matrixStack.popPose(); matrixStack.popPose();
@ -86,12 +86,11 @@ public class BaseSignBlockEntityRenderer implements BlockEntityRenderer<BaseSign
int o = (int) (NativeImage.getG(m) * 0.4D); int o = (int) (NativeImage.getG(m) * 0.4D);
int p = (int) (NativeImage.getB(m) * 0.4D); int p = (int) (NativeImage.getB(m) * 0.4D);
int q = NativeImage.combine(0, p, o, n); int q = NativeImage.combine(0, p, o, n);
FormattedCharSequence[] formattedCharSequences = signBlockEntity FormattedCharSequence[] formattedCharSequences = signBlockEntity.getRenderMessages(Minecraft.getInstance().isTextFilteringEnabled(), (component) -> {
.getRenderMessages(Minecraft.getInstance().isTextFilteringEnabled(), (component) -> { List<FormattedCharSequence> list = this.font.split(component, 90);
List<FormattedCharSequence> list = this.font.split(component, 90); return list.isEmpty() ? FormattedCharSequence.EMPTY : (FormattedCharSequence) list.get(0);
return list.isEmpty() ? FormattedCharSequence.EMPTY : (FormattedCharSequence) list.get(0); });
});
int drawColor; int drawColor;
boolean drawOutlined; boolean drawOutlined;
int drawLight; int drawLight;
@ -99,57 +98,58 @@ public class BaseSignBlockEntityRenderer implements BlockEntityRenderer<BaseSign
drawColor = signBlockEntity.getColor().getTextColor(); drawColor = signBlockEntity.getColor().getTextColor();
drawOutlined = isOutlineVisible(signBlockEntity, drawColor); drawOutlined = isOutlineVisible(signBlockEntity, drawColor);
drawLight = 15728880; drawLight = 15728880;
} else { }
else {
drawColor = m; drawColor = m;
drawOutlined = false; drawOutlined = false;
drawLight = light; drawLight = light;
} }
for (int s = 0; s < 4; ++s) { for (int s = 0; s < 4; ++s) {
FormattedCharSequence formattedCharSequence = formattedCharSequences[s]; FormattedCharSequence formattedCharSequence = formattedCharSequences[s];
float t = (float) (-this.font.width(formattedCharSequence) / 2); float t = (float) (-this.font.width(formattedCharSequence) / 2);
if (drawOutlined) { if (drawOutlined) {
this.font.drawInBatch8xOutline(formattedCharSequence, t, (float) (s * 10 - 20), drawColor, m, this.font.drawInBatch8xOutline(formattedCharSequence, t, (float) (s * 10 - 20), drawColor, m, matrixStack.last().pose(), provider, drawLight);
matrixStack.last().pose(), provider, drawLight); }
} else { else {
this.font.drawInBatch((FormattedCharSequence) formattedCharSequence, t, (float) (s * 10 - 20), drawColor, false, this.font.drawInBatch((FormattedCharSequence) formattedCharSequence, t, (float) (s * 10 - 20), drawColor, false, matrixStack.last().pose(), provider, false, 0, drawLight);
matrixStack.last().pose(), provider, false, 0, drawLight);
} }
} }
matrixStack.popPose(); matrixStack.popPose();
} }
private static boolean isOutlineVisible(BaseSignBlockEntity signBlockEntity, int i) { private static boolean isOutlineVisible(BaseSignBlockEntity signBlockEntity, int i) {
if (i == DyeColor.BLACK.getTextColor()) { if (i == DyeColor.BLACK.getTextColor()) {
return true; return true;
} else { }
else {
Minecraft minecraft = Minecraft.getInstance(); Minecraft minecraft = Minecraft.getInstance();
LocalPlayer localPlayer = minecraft.player; LocalPlayer localPlayer = minecraft.player;
if (localPlayer != null && minecraft.options.getCameraType().isFirstPerson() && localPlayer.isScoping()) { if (localPlayer != null && minecraft.options.getCameraType().isFirstPerson() && localPlayer.isScoping()) {
return true; return true;
} else { }
else {
Entity entity = minecraft.getCameraEntity(); Entity entity = minecraft.getCameraEntity();
return entity != null && entity.distanceToSqr( return entity != null && entity.distanceToSqr(Vec3.atCenterOf(signBlockEntity.getBlockPos())) < (double) OUTLINE_RENDER_DISTANCE;
Vec3.atCenterOf(signBlockEntity.getBlockPos())) < (double) OUTLINE_RENDER_DISTANCE;
} }
} }
} }
public static WoodType getSignType(Block block) { public static WoodType getSignType(Block block) {
WoodType signType2; WoodType signType2;
if (block instanceof SignBlock) { if (block instanceof SignBlock) {
signType2 = ((SignBlock) block).type(); signType2 = ((SignBlock) block).type();
} else { }
else {
signType2 = WoodType.OAK; signType2 = WoodType.OAK;
} }
return signType2; return signType2;
} }
public static Material getModelTexture(Block block) { public static Material getModelTexture(Block block) {
return Sheets.getSignMaterial(getSignType(block)); return Sheets.getSignMaterial(getSignType(block));
} }
@ -157,14 +157,13 @@ public class BaseSignBlockEntityRenderer implements BlockEntityRenderer<BaseSign
public static VertexConsumer getConsumer(MultiBufferSource provider, Block block) { public static VertexConsumer getConsumer(MultiBufferSource provider, Block block) {
return provider.getBuffer(LAYERS.getOrDefault(block, defaultLayer)); return provider.getBuffer(LAYERS.getOrDefault(block, defaultLayer));
} }
public static void registerRenderLayer(Block block) { public static void registerRenderLayer(Block block) {
ResourceLocation blockId = Registry.BLOCK.getKey(block); ResourceLocation blockId = Registry.BLOCK.getKey(block);
RenderType layer = RenderType.entitySolid(new ResourceLocation(blockId.getNamespace(), RenderType layer = RenderType.entitySolid(new ResourceLocation(blockId.getNamespace(), "textures/entity/sign/" + blockId.getPath() + ".png"));
"textures/entity/sign/" + blockId.getPath() + ".png"));
LAYERS.put(block, layer); LAYERS.put(block, layer);
} }
static { static {
defaultLayer = RenderType.entitySolid(new ResourceLocation("textures/entity/signs/oak.png")); defaultLayer = RenderType.entitySolid(new ResourceLocation("textures/entity/signs/oak.png"));
} }

View file

@ -4,10 +4,5 @@ import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.SoundType;
public class BlockSounds { public class BlockSounds {
public static final SoundType TERRAIN_SOUND = new SoundType(1.0F, 1.0F, public static final SoundType TERRAIN_SOUND = new SoundType(1.0F, 1.0F, SoundEvents.STONE_BREAK, SoundEvents.WART_BLOCK_STEP, SoundEvents.STONE_PLACE, SoundEvents.STONE_HIT, SoundEvents.STONE_FALL);
SoundEvents.STONE_BREAK,
SoundEvents.WART_BLOCK_STEP,
SoundEvents.STONE_PLACE,
SoundEvents.STONE_HIT,
SoundEvents.STONE_FALL);
} }

View file

@ -1,7 +1,7 @@
package ru.bclib.config; package ru.bclib.config;
public class CategoryConfig extends IdConfig { public class CategoryConfig extends IdConfig {
public CategoryConfig(String modID, String group) { public CategoryConfig(String modID, String group) {
super(modID, group, (id, category) -> { super(modID, group, (id, category) -> {
return new ConfigKey(id.getPath(), id.getNamespace(), category); return new ConfigKey(id.getPath(), id.getNamespace(), category);

View file

@ -1,7 +1,6 @@
package ru.bclib.config; package ru.bclib.config;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import ru.bclib.BCLib; import ru.bclib.BCLib;
import ru.bclib.config.ConfigKeeper.BooleanEntry; import ru.bclib.config.ConfigKeeper.BooleanEntry;
import ru.bclib.config.ConfigKeeper.Entry; import ru.bclib.config.ConfigKeeper.Entry;
@ -55,14 +54,15 @@ public abstract class Config {
if (entry == null) return false; if (entry == null) return false;
entry.setValue(value); entry.setValue(value);
return true; return true;
} catch (NullPointerException ex) { }
catch (NullPointerException ex) {
BCLib.LOGGER.catching(ex); BCLib.LOGGER.catching(ex);
} }
return false; return false;
} }
protected int getInt(ConfigKey key, int defaultValue) { protected int getInt(ConfigKey key, int defaultValue) {
Integer val = keeper.getValue(key, IntegerEntry.class); Integer val = keeper.getValue(key, IntegerEntry.class);
if (val == null) { if (val == null) {
IntegerEntry entry = keeper.registerEntry(key, new IntegerEntry(defaultValue)); IntegerEntry entry = keeper.registerEntry(key, new IntegerEntry(defaultValue));
return entry.getValue(); return entry.getValue();
@ -71,7 +71,7 @@ public abstract class Config {
} }
protected int getInt(ConfigKey key) { protected int getInt(ConfigKey key) {
Integer val = keeper.getValue(key, IntegerEntry.class); Integer val = keeper.getValue(key, IntegerEntry.class);
return val != null ? val : 0; return val != null ? val : 0;
} }
@ -81,7 +81,8 @@ public abstract class Config {
if (entry == null) return false; if (entry == null) return false;
entry.setValue(value); entry.setValue(value);
return true; return true;
} catch (NullPointerException ex) { }
catch (NullPointerException ex) {
BCLib.LOGGER.catching(ex); BCLib.LOGGER.catching(ex);
} }
return false; return false;
@ -93,7 +94,8 @@ public abstract class Config {
if (entry == null) return false; if (entry == null) return false;
entry.setValue(value); entry.setValue(value);
return true; return true;
} catch (NullPointerException | ClassCastException ex) { }
catch (NullPointerException | ClassCastException ex) {
BCLib.LOGGER.catching(ex); BCLib.LOGGER.catching(ex);
} }
return false; return false;
@ -119,7 +121,8 @@ public abstract class Config {
if (entry == null) return false; if (entry == null) return false;
entry.setValue(value); entry.setValue(value);
return true; return true;
} catch (NullPointerException ex) { }
catch (NullPointerException ex) {
BCLib.LOGGER.catching(ex); BCLib.LOGGER.catching(ex);
} }
return false; return false;
@ -145,7 +148,8 @@ public abstract class Config {
if (entry == null) return false; if (entry == null) return false;
entry.setValue(value); entry.setValue(value);
return true; return true;
} catch (NullPointerException ex) { }
catch (NullPointerException ex) {
BCLib.LOGGER.catching(ex); BCLib.LOGGER.catching(ex);
} }
return false; return false;

View file

@ -1,45 +1,43 @@
package ru.bclib.config; package ru.bclib.config;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.minecraft.util.GsonHelper;
import org.jetbrains.annotations.Nullable;
import ru.bclib.util.JsonFactory;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.Map; import java.util.Map;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Supplier; import java.util.function.Supplier;
import org.jetbrains.annotations.Nullable;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.minecraft.util.GsonHelper;
import ru.bclib.util.JsonFactory;
public final class ConfigKeeper { public final class ConfigKeeper {
private final Map<ConfigKey, Entry<?>> configEntries = Maps.newHashMap(); private final Map<ConfigKey, Entry<?>> configEntries = Maps.newHashMap();
private final JsonObject configObject; private final JsonObject configObject;
private final ConfigWriter writer; private final ConfigWriter writer;
private boolean changed = false; private boolean changed = false;
public ConfigKeeper(String modID, String group) { public ConfigKeeper(String modID, String group) {
this.writer = new ConfigWriter(modID, group); this.writer = new ConfigWriter(modID, group);
this.configObject = writer.load(); this.configObject = writer.load();
} }
public void save() { public void save() {
if (!changed) return; if (!changed) return;
this.writer.save(); this.writer.save();
this.changed = false; this.changed = false;
} }
private <T, E extends Entry<T>> void initializeEntry(ConfigKey key, E entry) { private <T, E extends Entry<T>> void initializeEntry(ConfigKey key, E entry) {
if (configObject == null) { if (configObject == null) {
return; return;
} }
String[] path = key.getPath(); String[] path = key.getPath();
JsonObject obj = configObject; JsonObject obj = configObject;
if (!key.isRoot()) { if (!key.isRoot()) {
for (String group : path) { for (String group : path) {
JsonElement element = obj.get(group); JsonElement element = obj.get(group);
@ -50,13 +48,13 @@ public final class ConfigKeeper {
obj = element.getAsJsonObject(); obj = element.getAsJsonObject();
} }
} }
String paramKey = key.getEntry(); String paramKey = key.getEntry();
paramKey += " [default: " + entry.getDefault() + "]"; paramKey += " [default: " + entry.getDefault() + "]";
this.changed |= entry.setLocation(obj, paramKey); this.changed |= entry.setLocation(obj, paramKey);
} }
private <T, E extends Entry<T>> void storeValue(E entry, T value) { private <T, E extends Entry<T>> void storeValue(E entry, T value) {
if (configObject == null) { if (configObject == null) {
return; return;
@ -66,14 +64,14 @@ public final class ConfigKeeper {
entry.toJson(value); entry.toJson(value);
this.changed = true; this.changed = true;
} }
private <T, E extends Entry<T>> T getValue(E entry) { private <T, E extends Entry<T>> T getValue(E entry) {
if (!entry.hasLocation()) { if (!entry.hasLocation()) {
return entry.getDefault(); return entry.getDefault();
} }
return entry.fromJson(); return entry.fromJson();
} }
@Nullable @Nullable
public <T, E extends Entry<T>> E getEntry(ConfigKey key, Class<E> type) { public <T, E extends Entry<T>> E getEntry(ConfigKey key, Class<E> type) {
Entry<?> entry = this.configEntries.get(key); Entry<?> entry = this.configEntries.get(key);
@ -82,7 +80,7 @@ public final class ConfigKeeper {
} }
return null; return null;
} }
@Nullable @Nullable
public <T, E extends Entry<T>> T getValue(ConfigKey key, Class<E> type) { public <T, E extends Entry<T>> T getValue(ConfigKey key, Class<E> type) {
Entry<T> entry = this.getEntry(key, type); Entry<T> entry = this.getEntry(key, type);
@ -91,7 +89,7 @@ public final class ConfigKeeper {
} }
return entry.getValue(); return entry.getValue();
} }
public <T, E extends Entry<T>> E registerEntry(ConfigKey key, E entry) { public <T, E extends Entry<T>> E registerEntry(ConfigKey key, E entry) {
entry.setWriter(value -> this.storeValue(entry, value)); entry.setWriter(value -> this.storeValue(entry, value));
entry.setReader(() -> { entry.setReader(() -> {
@ -101,119 +99,119 @@ public final class ConfigKeeper {
this.configEntries.put(key, entry); this.configEntries.put(key, entry);
return entry; return entry;
} }
public static class BooleanEntry extends Entry<Boolean> { public static class BooleanEntry extends Entry<Boolean> {
public BooleanEntry(Boolean defaultValue) { public BooleanEntry(Boolean defaultValue) {
super(defaultValue); super(defaultValue);
} }
@Override @Override
public Boolean fromJson() { public Boolean fromJson() {
return GsonHelper.getAsBoolean(location, key, defaultValue); return GsonHelper.getAsBoolean(location, key, defaultValue);
} }
@Override @Override
public void toJson(Boolean value) { public void toJson(Boolean value) {
this.location.addProperty(key, value); this.location.addProperty(key, value);
} }
} }
public static class FloatEntry extends Entry<Float> { public static class FloatEntry extends Entry<Float> {
public FloatEntry(Float defaultValue) { public FloatEntry(Float defaultValue) {
super(defaultValue); super(defaultValue);
} }
@Override @Override
public Float fromJson() { public Float fromJson() {
return GsonHelper.getAsFloat(location, key, defaultValue); return GsonHelper.getAsFloat(location, key, defaultValue);
} }
@Override @Override
public void toJson(Float value) { public void toJson(Float value) {
this.location.addProperty(key, value); this.location.addProperty(key, value);
} }
} }
public static class FloatRange extends RangeEntry<Float> { public static class FloatRange extends RangeEntry<Float> {
public FloatRange(Float defaultValue, float minVal, float maxVal) { public FloatRange(Float defaultValue, float minVal, float maxVal) {
super(defaultValue, minVal, maxVal); super(defaultValue, minVal, maxVal);
} }
@Override @Override
public Float fromJson() { public Float fromJson() {
return GsonHelper.getAsFloat(location, key, defaultValue); return GsonHelper.getAsFloat(location, key, defaultValue);
} }
@Override @Override
public void toJson(Float value) { public void toJson(Float value) {
this.location.addProperty(key, value); this.location.addProperty(key, value);
} }
} }
public static class IntegerEntry extends Entry<Integer> { public static class IntegerEntry extends Entry<Integer> {
public IntegerEntry(Integer defaultValue) { public IntegerEntry(Integer defaultValue) {
super(defaultValue); super(defaultValue);
} }
@Override @Override
public Integer getDefault() { public Integer getDefault() {
return this.defaultValue; return this.defaultValue;
} }
@Override @Override
public Integer fromJson() { public Integer fromJson() {
return GsonHelper.getAsInt(location, key, defaultValue); return GsonHelper.getAsInt(location, key, defaultValue);
} }
@Override @Override
public void toJson(Integer value) { public void toJson(Integer value) {
this.location.addProperty(key, value); this.location.addProperty(key, value);
} }
} }
public static class IntegerRange extends RangeEntry<Integer> { public static class IntegerRange extends RangeEntry<Integer> {
public IntegerRange(Integer defaultValue, int minVal, int maxVal) { public IntegerRange(Integer defaultValue, int minVal, int maxVal) {
super(defaultValue, minVal, maxVal); super(defaultValue, minVal, maxVal);
} }
@Override @Override
public Integer fromJson() { public Integer fromJson() {
return GsonHelper.getAsInt(location, key, defaultValue); return GsonHelper.getAsInt(location, key, defaultValue);
} }
@Override @Override
public void toJson(Integer value) { public void toJson(Integer value) {
this.location.addProperty(key, value); this.location.addProperty(key, value);
} }
} }
public static class StringEntry extends Entry<String> { public static class StringEntry extends Entry<String> {
public StringEntry(String defaultValue) { public StringEntry(String defaultValue) {
super(defaultValue); super(defaultValue);
} }
@Override @Override
public String fromJson() { public String fromJson() {
return GsonHelper.getAsString(location, key, defaultValue); return GsonHelper.getAsString(location, key, defaultValue);
} }
@Override @Override
public void toJson(String value) { public void toJson(String value) {
this.location.addProperty(key, value); this.location.addProperty(key, value);
} }
} }
public static class EnumEntry<T extends Enum<T>> extends Entry<T> { public static class EnumEntry<T extends Enum<T>> extends Entry<T> {
private final Type type; private final Type type;
public EnumEntry(T defaultValue) { public EnumEntry(T defaultValue) {
super(defaultValue); super(defaultValue);
TypeToken<T> token = new TypeToken<T>() { TypeToken<T> token = new TypeToken<T>() {
@ -221,71 +219,71 @@ public final class ConfigKeeper {
}; };
this.type = token.getType(); this.type = token.getType();
} }
@Override @Override
public T getDefault() { public T getDefault() {
return this.defaultValue; return this.defaultValue;
} }
@Override @Override
public T fromJson() { public T fromJson() {
return JsonFactory.GSON.fromJson(location.get(key), type); return JsonFactory.GSON.fromJson(location.get(key), type);
} }
@Override @Override
public void toJson(T value) { public void toJson(T value) {
location.addProperty(key, JsonFactory.GSON.toJson(value, type)); location.addProperty(key, JsonFactory.GSON.toJson(value, type));
} }
} }
public static abstract class RangeEntry<T extends Comparable<T>> extends Entry<T> { public static abstract class RangeEntry<T extends Comparable<T>> extends Entry<T> {
private final T min, max; private final T min, max;
public RangeEntry(T defaultValue, T minVal, T maxVal) { public RangeEntry(T defaultValue, T minVal, T maxVal) {
super(defaultValue); super(defaultValue);
this.min = minVal; this.min = minVal;
this.max = maxVal; this.max = maxVal;
} }
@Override @Override
public void setValue(T value) { public void setValue(T value) {
super.setValue(value.compareTo(min) < 0 ? min : value.compareTo(max) > 0 ? max : value); super.setValue(value.compareTo(min) < 0 ? min : value.compareTo(max) > 0 ? max : value);
} }
public T minValue() { public T minValue() {
return this.min; return this.min;
} }
public T maxValue() { public T maxValue() {
return this.max; return this.max;
} }
} }
public static abstract class Entry<T> { public static abstract class Entry<T> {
protected final T defaultValue; protected final T defaultValue;
protected Consumer<T> writer; protected Consumer<T> writer;
protected Supplier<T> reader; protected Supplier<T> reader;
protected JsonObject location; protected JsonObject location;
protected String key; protected String key;
public abstract T fromJson(); public abstract T fromJson();
public abstract void toJson(T value); public abstract void toJson(T value);
public Entry(T defaultValue) { public Entry(T defaultValue) {
this.defaultValue = defaultValue; this.defaultValue = defaultValue;
} }
protected void setWriter(Consumer<T> writer) { protected void setWriter(Consumer<T> writer) {
this.writer = writer; this.writer = writer;
} }
protected void setReader(Supplier<T> reader) { protected void setReader(Supplier<T> reader) {
this.reader = reader; this.reader = reader;
} }
protected boolean setLocation(JsonObject location, String key) { protected boolean setLocation(JsonObject location, String key) {
this.location = location; this.location = location;
this.key = key; this.key = key;
@ -295,24 +293,23 @@ public final class ConfigKeeper {
} }
return false; return false;
} }
protected boolean hasLocation() { protected boolean hasLocation() {
return this.location != null && return this.location != null && this.key != null;
this.key != null;
} }
public T getValue() { public T getValue() {
return this.reader.get(); return this.reader.get();
} }
public void setValue(T value) { public void setValue(T value) {
this.writer.accept(value); this.writer.accept(value);
} }
public T getDefault() { public T getDefault() {
return this.defaultValue; return this.defaultValue;
} }
public void setDefault() { public void setDefault() {
this.setValue(defaultValue); this.setValue(defaultValue);
} }

View file

@ -17,11 +17,11 @@ public class ConfigKey {
public ConfigKey(String entry, ResourceLocation path) { public ConfigKey(String entry, ResourceLocation path) {
this(entry, path.getNamespace(), path.getPath()); this(entry, path.getNamespace(), path.getPath());
} }
public String[] getPath() { public String[] getPath() {
return path; return path;
} }
public String getEntry() { public String getEntry() {
return entry; return entry;
} }
@ -29,7 +29,7 @@ public class ConfigKey {
public boolean isRoot() { public boolean isRoot() {
return root; return root;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
@ -38,7 +38,7 @@ public class ConfigKey {
result = prime * result + entry.hashCode(); result = prime * result + entry.hashCode();
return result; return result;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) { if (this == obj) {

View file

@ -1,20 +1,19 @@
package ru.bclib.config; package ru.bclib.config;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.fabricmc.loader.api.FabricLoader;
import ru.bclib.util.JsonFactory;
import java.io.File; import java.io.File;
import java.nio.file.Path; import java.nio.file.Path;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.fabricmc.loader.api.FabricLoader;
import ru.bclib.util.JsonFactory;
public class ConfigWriter { public class ConfigWriter {
private final static Path GAME_CONFIG_DIR = FabricLoader.getInstance().getConfigDir(); private final static Path GAME_CONFIG_DIR = FabricLoader.getInstance().getConfigDir();
private final File configFile; private final File configFile;
private JsonObject configObject; private JsonObject configObject;
public ConfigWriter(String modID, String configFile) { public ConfigWriter(String modID, String configFile) {
this.configFile = new File(new File(GAME_CONFIG_DIR.toFile(), modID), configFile + ".json"); this.configFile = new File(new File(GAME_CONFIG_DIR.toFile(), modID), configFile + ".json");
File parent = this.configFile.getParentFile(); File parent = this.configFile.getParentFile();
@ -23,38 +22,38 @@ public class ConfigWriter {
} }
this.load(); this.load();
} }
public JsonObject getConfig() { public JsonObject getConfig() {
return configObject; return configObject;
} }
public void save() { public void save() {
if (configObject == null) { if (configObject == null) {
return; return;
} }
save(configFile, configObject); save(configFile, configObject);
} }
public JsonObject load() { public JsonObject load() {
if (configObject == null) { if (configObject == null) {
configObject = load(configFile); configObject = load(configFile);
} }
return configObject; return configObject;
} }
public void save(JsonElement config) { public void save(JsonElement config) {
this.configObject = config.getAsJsonObject(); this.configObject = config.getAsJsonObject();
save(configFile, config); save(configFile, config);
} }
public static JsonObject load(File configFile) { public static JsonObject load(File configFile) {
return JsonFactory.getJsonObject(configFile); return JsonFactory.getJsonObject(configFile);
} }
public static void save(File configFile, JsonElement config) { public static void save(File configFile, JsonElement config) {
JsonFactory.storeJson(configFile, config); JsonFactory.storeJson(configFile, config);
} }
public static String scrubFileName(String input) { public static String scrubFileName(String input) {
input = input.replaceAll("[/\\ ]+", "_"); input = input.replaceAll("[/\\ ]+", "_");
input = input.replaceAll("[,:&\"\\|\\<\\>\\?\\*]", "_"); input = input.replaceAll("[,:&\"\\|\\<\\>\\?\\*]", "_");

View file

@ -1,14 +1,13 @@
package ru.bclib.config; package ru.bclib.config;
import java.util.function.BiFunction;
import org.jetbrains.annotations.Nullable;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.Nullable;
import ru.bclib.config.ConfigKeeper.Entry; import ru.bclib.config.ConfigKeeper.Entry;
import ru.bclib.config.ConfigKeeper.FloatRange; import ru.bclib.config.ConfigKeeper.FloatRange;
import ru.bclib.config.ConfigKeeper.IntegerRange; import ru.bclib.config.ConfigKeeper.IntegerRange;
import java.util.function.BiFunction;
public class IdConfig extends Config { public class IdConfig extends Config {
protected final BiFunction<ResourceLocation, String, ConfigKey> keyFactory; protected final BiFunction<ResourceLocation, String, ConfigKey> keyFactory;
@ -16,48 +15,48 @@ public class IdConfig extends Config {
super(modID, group); super(modID, group);
this.keyFactory = keyFactory; this.keyFactory = keyFactory;
} }
@Override @Override
protected void registerEntries() {} protected void registerEntries() {}
protected ConfigKey createKey(ResourceLocation id, String key) { protected ConfigKey createKey(ResourceLocation id, String key) {
return this.keyFactory.apply(id, key); return this.keyFactory.apply(id, key);
} }
@Nullable @Nullable
public <T, E extends Entry<T>> E getEntry(ResourceLocation id, String key, Class<E> type) { public <T, E extends Entry<T>> E getEntry(ResourceLocation id, String key, Class<E> type) {
return this.getEntry(createKey(id, key), type); return this.getEntry(createKey(id, key), type);
} }
@Nullable @Nullable
public <T, E extends Entry<T>> T getDefault(ResourceLocation id, String key, Class<E> type) { public <T, E extends Entry<T>> T getDefault(ResourceLocation id, String key, Class<E> type) {
return this.getDefault(createKey(id, key), type); return this.getDefault(createKey(id, key), type);
} }
public String getString(ResourceLocation id, String key, String defaultValue) { public String getString(ResourceLocation id, String key, String defaultValue) {
return this.getString(createKey(id, key), defaultValue); return this.getString(createKey(id, key), defaultValue);
} }
public String getString(ResourceLocation id, String key) { public String getString(ResourceLocation id, String key) {
return this.getString(createKey(id, key)); return this.getString(createKey(id, key));
} }
public boolean setString(ResourceLocation id, String key, String value) { public boolean setString(ResourceLocation id, String key, String value) {
return this.setString(createKey(id, key), value); return this.setString(createKey(id, key), value);
} }
public int getInt(ResourceLocation id, String key, int defaultValue) { public int getInt(ResourceLocation id, String key, int defaultValue) {
return this.getInt(createKey(id, key), defaultValue); return this.getInt(createKey(id, key), defaultValue);
} }
public int getInt(ResourceLocation id, String key) { public int getInt(ResourceLocation id, String key) {
return this.getInt(createKey(id, key)); return this.getInt(createKey(id, key));
} }
public boolean setInt(ResourceLocation id, String key, int value) { public boolean setInt(ResourceLocation id, String key, int value) {
return this.setInt(createKey(id, key), value); return this.setInt(createKey(id, key), value);
} }
public boolean setRangedInt(ResourceLocation id, String key, int value) { public boolean setRangedInt(ResourceLocation id, String key, int value) {
return this.setRanged(createKey(id, key), value, IntegerRange.class); return this.setRanged(createKey(id, key), value, IntegerRange.class);
} }
@ -65,27 +64,27 @@ public class IdConfig extends Config {
public boolean setRangedFloat(ResourceLocation id, String key, float value) { public boolean setRangedFloat(ResourceLocation id, String key, float value) {
return this.setRanged(createKey(id, key), value, FloatRange.class); return this.setRanged(createKey(id, key), value, FloatRange.class);
} }
public float getFloat(ResourceLocation id, String key, float defaultValue) { public float getFloat(ResourceLocation id, String key, float defaultValue) {
return this.getFloat(createKey(id, key), defaultValue); return this.getFloat(createKey(id, key), defaultValue);
} }
public float getFloat(ResourceLocation id, String key) { public float getFloat(ResourceLocation id, String key) {
return this.getFloat(createKey(id, key)); return this.getFloat(createKey(id, key));
} }
public boolean setFloat(ResourceLocation id, String key, float value) { public boolean setFloat(ResourceLocation id, String key, float value) {
return this.setFloat(createKey(id, key), value); return this.setFloat(createKey(id, key), value);
} }
public boolean getBoolean(ResourceLocation id, String key, boolean defaultValue) { public boolean getBoolean(ResourceLocation id, String key, boolean defaultValue) {
return this.getBoolean(createKey(id, key), defaultValue); return this.getBoolean(createKey(id, key), defaultValue);
} }
public boolean getBoolean(ResourceLocation id, String key) { public boolean getBoolean(ResourceLocation id, String key) {
return this.getBoolean(createKey(id, key)); return this.getBoolean(createKey(id, key));
} }
public boolean setBoolean(ResourceLocation id, String key, boolean value) { public boolean setBoolean(ResourceLocation id, String key, boolean value) {
return this.setBoolean(createKey(id, key), value); return this.setBoolean(createKey(id, key), value);
} }

View file

@ -1,17 +1,16 @@
package ru.bclib.config; package ru.bclib.config;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import ru.bclib.config.ConfigKeeper.Entry; import ru.bclib.config.ConfigKeeper.Entry;
import ru.bclib.config.ConfigKeeper.FloatRange; import ru.bclib.config.ConfigKeeper.FloatRange;
import ru.bclib.config.ConfigKeeper.IntegerRange; import ru.bclib.config.ConfigKeeper.IntegerRange;
public class PathConfig extends Config { public class PathConfig extends Config {
public PathConfig(String modID, String group) { public PathConfig(String modID, String group) {
super(modID, group); super(modID, group);
} }
@Override @Override
protected void registerEntries() {} protected void registerEntries() {}
@ -27,36 +26,36 @@ public class PathConfig extends Config {
public <T, E extends Entry<T>> E getEntry(String category, String key, Class<E> type) { public <T, E extends Entry<T>> E getEntry(String category, String key, Class<E> type) {
return this.getEntry(createKey(category, key), type); return this.getEntry(createKey(category, key), type);
} }
@Nullable @Nullable
public <T, E extends Entry<T>> T getDefault(String category, String key, Class<E> type) { public <T, E extends Entry<T>> T getDefault(String category, String key, Class<E> type) {
return this.getDefault(createKey(category, key), type); return this.getDefault(createKey(category, key), type);
} }
public String getString(String category, String key, String defaultValue) { public String getString(String category, String key, String defaultValue) {
return this.getString(createKey(category, key), defaultValue); return this.getString(createKey(category, key), defaultValue);
} }
public String getString(String category, String key) { public String getString(String category, String key) {
return this.getString(createKey(category, key)); return this.getString(createKey(category, key));
} }
public boolean setString(String category, String key, String value) { public boolean setString(String category, String key, String value) {
return this.setString(createKey(category, key), value); return this.setString(createKey(category, key), value);
} }
public int getInt(String category, String key, int defaultValue) { public int getInt(String category, String key, int defaultValue) {
return this.getInt(createKey(category, key), defaultValue); return this.getInt(createKey(category, key), defaultValue);
} }
public int getInt(String category, String key) { public int getInt(String category, String key) {
return this.getInt(createKey(category, key)); return this.getInt(createKey(category, key));
} }
public boolean setInt(String category, String key, int value) { public boolean setInt(String category, String key, int value) {
return this.setInt(createKey(category, key), value); return this.setInt(createKey(category, key), value);
} }
public boolean setRangedInt(String category, String key, int value) { public boolean setRangedInt(String category, String key, int value) {
return this.setRanged(createKey(category, key), value, IntegerRange.class); return this.setRanged(createKey(category, key), value, IntegerRange.class);
} }
@ -64,27 +63,27 @@ public class PathConfig extends Config {
public boolean setRangedFloat(String category, String key, float value) { public boolean setRangedFloat(String category, String key, float value) {
return this.setRanged(createKey(category, key), value, FloatRange.class); return this.setRanged(createKey(category, key), value, FloatRange.class);
} }
public float getFloat(String category, String key, float defaultValue) { public float getFloat(String category, String key, float defaultValue) {
return this.getFloat(createKey(category, key), defaultValue); return this.getFloat(createKey(category, key), defaultValue);
} }
public float getFloat(String category, String key) { public float getFloat(String category, String key) {
return this.getFloat(createKey(category, key)); return this.getFloat(createKey(category, key));
} }
public boolean setFloat(String category, String key, float value) { public boolean setFloat(String category, String key, float value) {
return this.setFloat(createKey(category, key), value); return this.setFloat(createKey(category, key), value);
} }
public boolean getBoolean(String category, String key, boolean defaultValue) { public boolean getBoolean(String category, String key, boolean defaultValue) {
return this.getBoolean(createKey(category, key), defaultValue); return this.getBoolean(createKey(category, key), defaultValue);
} }
public boolean getBoolean(String category, String key) { public boolean getBoolean(String category, String key) {
return this.getBoolean(createKey(category, key)); return this.getBoolean(createKey(category, key));
} }
public boolean setBoolean(String category, String key, boolean value) { public boolean setBoolean(String category, String key, boolean value) {
return this.setBoolean(createKey(category, key), value); return this.setBoolean(createKey(category, key), value);
} }
@ -94,27 +93,27 @@ public class PathConfig extends Config {
public String getStringRoot(String key, String defaultValue) { public String getStringRoot(String key, String defaultValue) {
return this.getString(createKey(key), defaultValue); return this.getString(createKey(key), defaultValue);
} }
public String getStringRoot(String key) { public String getStringRoot(String key) {
return this.getString(createKey(key)); return this.getString(createKey(key));
} }
public boolean setStringRoot(String key, String value) { public boolean setStringRoot(String key, String value) {
return this.setString(createKey(key), value); return this.setString(createKey(key), value);
} }
public int getIntRoot(String key, int defaultValue) { public int getIntRoot(String key, int defaultValue) {
return this.getInt(createKey(key), defaultValue); return this.getInt(createKey(key), defaultValue);
} }
public int getIntRoot(String key) { public int getIntRoot(String key) {
return this.getInt(createKey(key)); return this.getInt(createKey(key));
} }
public boolean setIntRoot(String key, int value) { public boolean setIntRoot(String key, int value) {
return this.setInt(createKey(key), value); return this.setInt(createKey(key), value);
} }
public boolean setRangedIntRoot(String key, int value) { public boolean setRangedIntRoot(String key, int value) {
return this.setRanged(createKey(key), value, IntegerRange.class); return this.setRanged(createKey(key), value, IntegerRange.class);
} }
@ -122,27 +121,27 @@ public class PathConfig extends Config {
public boolean setRangedFloatRoot(String key, float value) { public boolean setRangedFloatRoot(String key, float value) {
return this.setRanged(createKey(key), value, FloatRange.class); return this.setRanged(createKey(key), value, FloatRange.class);
} }
public float getFloatRoot(String key, float defaultValue) { public float getFloatRoot(String key, float defaultValue) {
return this.getFloat(createKey(key), defaultValue); return this.getFloat(createKey(key), defaultValue);
} }
public float getFloatRoot(String key) { public float getFloatRoot(String key) {
return this.getFloat(createKey(key)); return this.getFloat(createKey(key));
} }
public boolean setFloatRoot(String key, float value) { public boolean setFloatRoot(String key, float value) {
return this.setFloat(createKey(key), value); return this.setFloat(createKey(key), value);
} }
public boolean getBooleanRoot(String key, boolean defaultValue) { public boolean getBooleanRoot(String key, boolean defaultValue) {
return this.getBoolean(createKey(key), defaultValue); return this.getBoolean(createKey(key), defaultValue);
} }
public boolean getBooleanRoot(String key) { public boolean getBooleanRoot(String key) {
return this.getBoolean(createKey(key)); return this.getBoolean(createKey(key));
} }
public boolean setBooleanRoot(String key, boolean value) { public boolean setBooleanRoot(String key, boolean value) {
return this.setBoolean(createKey(key), value); return this.setBoolean(createKey(key), value);
} }

View file

@ -1,10 +1,5 @@
package ru.bclib.integration; package ru.bclib.integration;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import net.fabricmc.fabric.api.tag.TagRegistry; import net.fabricmc.fabric.api.tag.TagRegistry;
import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
@ -25,6 +20,11 @@ import net.minecraft.world.level.levelgen.feature.Feature;
import ru.bclib.BCLib; import ru.bclib.BCLib;
import ru.bclib.world.features.BCLFeature; import ru.bclib.world.features.BCLFeature;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public abstract class ModIntegration { public abstract class ModIntegration {
private final String modID; private final String modID;
@ -45,7 +45,7 @@ public abstract class ModIntegration {
public Item getItem(String name) { public Item getItem(String name) {
return Registry.ITEM.get(getID(name)); return Registry.ITEM.get(getID(name));
} }
public BlockState getDefaultState(String name) { public BlockState getDefaultState(String name) {
return getBlock(name).defaultBlockState(); return getBlock(name).defaultBlockState();
} }
@ -178,7 +178,7 @@ public abstract class ModIntegration {
public Object newInstance(Class<?> cl, Object... args) { public Object newInstance(Class<?> cl, Object... args) {
if (cl != null) { if (cl != null) {
for (Constructor<?> constructor: cl.getConstructors()) { for (Constructor<?> constructor : cl.getConstructors()) {
if (constructor.getParameterCount() == args.length) { if (constructor.getParameterCount() == args.length) {
try { try {
return constructor.newInstance(args); return constructor.newInstance(args);

View file

@ -5,6 +5,6 @@ import net.minecraft.client.color.item.ItemColor;
public interface IColorProvider { public interface IColorProvider {
BlockColor getProvider(); BlockColor getProvider();
ItemColor getItemProvider(); ItemColor getItemProvider();
} }

View file

@ -2,5 +2,6 @@ package ru.bclib.interfaces;
public interface ISpetialItem { public interface ISpetialItem {
boolean canPlaceOnWater(); boolean canPlaceOnWater();
int getStackSize(); int getStackSize();
} }

View file

@ -1,9 +1,5 @@
package ru.bclib.items; package ru.bclib.items;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.renderer.block.model.BlockModel;
@ -18,17 +14,20 @@ import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.Nullable;
import ru.bclib.blocks.BaseAnvilBlock; import ru.bclib.blocks.BaseAnvilBlock;
import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ItemModelProvider;
import java.util.List;
public class BaseAnvilItem extends BlockItem implements ItemModelProvider { public class BaseAnvilItem extends BlockItem implements ItemModelProvider {
public final static String DESTRUCTION = "destruction"; public final static String DESTRUCTION = "destruction";
public BaseAnvilItem(Block block, Properties properties) { public BaseAnvilItem(Block block, Properties properties) {
super(block, properties); super(block, properties);
} }
@Override @Override
protected BlockState getPlacementState(BlockPlaceContext blockPlaceContext) { protected BlockState getPlacementState(BlockPlaceContext blockPlaceContext) {
BlockState blockState = super.getPlacementState(blockPlaceContext); BlockState blockState = super.getPlacementState(blockPlaceContext);
@ -39,7 +38,7 @@ public class BaseAnvilItem extends BlockItem implements ItemModelProvider {
} }
return blockState; return blockState;
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public void appendHoverText(ItemStack itemStack, @Nullable Level level, List<Component> list, TooltipFlag tooltipFlag) { public void appendHoverText(ItemStack itemStack, @Nullable Level level, List<Component> list, TooltipFlag tooltipFlag) {
@ -49,7 +48,7 @@ public class BaseAnvilItem extends BlockItem implements ItemModelProvider {
list.add(new TranslatableComponent("message.bclib.anvil_damage").append(": " + l)); list.add(new TranslatableComponent("message.bclib.anvil_damage").append(": " + l));
} }
} }
@Override @Override
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public BlockModel getItemModel(ResourceLocation resourceLocation) { public BlockModel getItemModel(ResourceLocation resourceLocation) {

View file

@ -1,10 +1,7 @@
package ru.bclib.items; package ru.bclib.items;
import java.util.UUID;
import com.google.common.collect.HashMultimap; import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.ai.attributes.Attribute; import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.ai.attributes.AttributeModifier;
@ -13,17 +10,14 @@ import net.minecraft.world.item.ArmorItem;
import net.minecraft.world.item.ArmorMaterial; import net.minecraft.world.item.ArmorMaterial;
import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ItemModelProvider;
import java.util.UUID;
public class BaseArmorItem extends ArmorItem implements ItemModelProvider { public class BaseArmorItem extends ArmorItem implements ItemModelProvider {
protected static final UUID[] ARMOR_MODIFIER_UUID_PER_SLOT = new UUID[] { protected static final UUID[] ARMOR_MODIFIER_UUID_PER_SLOT = new UUID[] {UUID.fromString("845DB27C-C624-495F-8C9F-6020A9A58B6B"), UUID.fromString("D8499B04-0E66-4726-AB29-64469D734E0D"), UUID.fromString("9F3D476D-C118-4544-8365-64846904B48E"), UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150")};
UUID.fromString("845DB27C-C624-495F-8C9F-6020A9A58B6B"),
UUID.fromString("D8499B04-0E66-4726-AB29-64469D734E0D"),
UUID.fromString("9F3D476D-C118-4544-8365-64846904B48E"),
UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150")
};
protected final Multimap<Attribute, AttributeModifier> defaultModifiers; protected final Multimap<Attribute, AttributeModifier> defaultModifiers;
public BaseArmorItem(ArmorMaterial material, EquipmentSlot equipmentSlot, Properties settings) { public BaseArmorItem(ArmorMaterial material, EquipmentSlot equipmentSlot, Properties settings) {
super(material, equipmentSlot, settings); super(material, equipmentSlot, settings);
this.defaultModifiers = HashMultimap.create(); this.defaultModifiers = HashMultimap.create();
@ -34,12 +28,12 @@ public class BaseArmorItem extends ArmorItem implements ItemModelProvider {
addAttributeModifier(Attributes.KNOCKBACK_RESISTANCE, new AttributeModifier(uuid, "Armor knockback resistance", knockbackResistance, AttributeModifier.Operation.ADDITION)); addAttributeModifier(Attributes.KNOCKBACK_RESISTANCE, new AttributeModifier(uuid, "Armor knockback resistance", knockbackResistance, AttributeModifier.Operation.ADDITION));
} }
} }
@Override @Override
public Multimap<Attribute, AttributeModifier> getDefaultAttributeModifiers(EquipmentSlot equipmentSlot) { public Multimap<Attribute, AttributeModifier> getDefaultAttributeModifiers(EquipmentSlot equipmentSlot) {
return equipmentSlot == slot ? defaultModifiers : super.getDefaultAttributeModifiers(equipmentSlot); return equipmentSlot == slot ? defaultModifiers : super.getDefaultAttributeModifiers(equipmentSlot);
} }
protected void addAttributeModifier(Attribute attribute, AttributeModifier modifier) { protected void addAttributeModifier(Attribute attribute, AttributeModifier modifier) {
if (defaultModifiers.containsKey(attribute)) { if (defaultModifiers.containsKey(attribute)) {
defaultModifiers.removeAll(attribute); defaultModifiers.removeAll(attribute);

View file

@ -17,22 +17,22 @@ public class BaseDrinkItem extends ModelProviderItem {
public BaseDrinkItem(Properties settings) { public BaseDrinkItem(Properties settings) {
super(settings); super(settings);
} }
@Override @Override
public int getUseDuration(ItemStack stack) { public int getUseDuration(ItemStack stack) {
return 32; return 32;
} }
@Override @Override
public UseAnim getUseAnimation(ItemStack stack) { public UseAnim getUseAnimation(ItemStack stack) {
return UseAnim.DRINK; return UseAnim.DRINK;
} }
@Override @Override
public InteractionResultHolder<ItemStack> use(Level world, Player user, InteractionHand hand) { public InteractionResultHolder<ItemStack> use(Level world, Player user, InteractionHand hand) {
return ItemUtils.startUsingInstantly(world, user, hand); return ItemUtils.startUsingInstantly(world, user, hand);
} }
@Override @Override
public ItemStack finishUsingItem(ItemStack stack, Level level, LivingEntity user) { public ItemStack finishUsingItem(ItemStack stack, Level level, LivingEntity user) {
if (this.isEdible()) { if (this.isEdible()) {
@ -45,15 +45,15 @@ public class BaseDrinkItem extends ModelProviderItem {
CriteriaTriggers.CONSUME_ITEM.trigger(serverPlayerEntity, stack); CriteriaTriggers.CONSUME_ITEM.trigger(serverPlayerEntity, stack);
serverPlayerEntity.awardStat(Stats.ITEM_USED.get(this)); serverPlayerEntity.awardStat(Stats.ITEM_USED.get(this));
} }
if (user instanceof Player && !((Player) user).getAbilities().instabuild) { if (user instanceof Player && !((Player) user).getAbilities().instabuild) {
stack.shrink(1); stack.shrink(1);
} }
if (!level.isClientSide) { if (!level.isClientSide) {
user.removeAllEffects(); user.removeAllEffects();
} }
return stack.isEmpty() ? new ItemStack(Items.GLASS_BOTTLE) : stack; return stack.isEmpty() ? new ItemStack(Items.GLASS_BOTTLE) : stack;
} }
} }

View file

@ -1,7 +1,5 @@
package ru.bclib.items; package ru.bclib.items;
import java.util.Optional;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.renderer.block.model.BlockModel;
@ -14,6 +12,8 @@ import ru.bclib.client.models.ItemModelProvider;
import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper;
import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.models.PatternsHelper;
import java.util.Optional;
public class BaseSpawnEggItem extends SpawnEggItem implements ItemModelProvider { public class BaseSpawnEggItem extends SpawnEggItem implements ItemModelProvider {
public BaseSpawnEggItem(EntityType<? extends Mob> type, int primaryColor, int secondaryColor, Properties settings) { public BaseSpawnEggItem(EntityType<? extends Mob> type, int primaryColor, int secondaryColor, Properties settings) {
super(type, primaryColor, secondaryColor, settings); super(type, primaryColor, secondaryColor, settings);

View file

@ -20,7 +20,7 @@ public class BaseAxeItem extends AxeItem implements DynamicAttributeTool, ItemMo
public BaseAxeItem(Tier material, float attackDamage, float attackSpeed, Properties settings) { public BaseAxeItem(Tier material, float attackDamage, float attackSpeed, Properties settings) {
super(material, attackDamage, attackSpeed, settings); super(material, attackDamage, attackSpeed, settings);
} }
@Override @Override
public int getMiningLevel(Tag<Item> tag, BlockState state, ItemStack stack, LivingEntity user) { public int getMiningLevel(Tag<Item> tag, BlockState state, ItemStack stack, LivingEntity user) {
if (tag.equals(FabricToolTags.AXES)) { if (tag.equals(FabricToolTags.AXES)) {

View file

@ -1,15 +1,6 @@
package ru.bclib.mixin.client; package ru.bclib.mixin.client;
import net.minecraft.world.level.material.FogType;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.Camera; import net.minecraft.client.Camera;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.renderer.FogRenderer; import net.minecraft.client.renderer.FogRenderer;
@ -21,7 +12,12 @@ import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.FogType;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import ru.bclib.api.BiomeAPI; import ru.bclib.api.BiomeAPI;
import ru.bclib.util.BackgroundInfo; import ru.bclib.util.BackgroundInfo;
import ru.bclib.util.MHelper; import ru.bclib.util.MHelper;

View file

@ -1,26 +1,25 @@
package ru.bclib.mixin.client; package ru.bclib.mixin.client;
import java.util.Random;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.ParticleTypes; import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.EnchantmentTableBlock; import net.minecraft.world.level.block.EnchantmentTableBlock;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import ru.bclib.api.TagAPI; import ru.bclib.api.TagAPI;
import java.util.Random;
@Mixin(EnchantmentTableBlock.class) @Mixin(EnchantmentTableBlock.class)
public abstract class EnchantingTableBlockMixin extends Block { public abstract class EnchantingTableBlockMixin extends Block {
public EnchantingTableBlockMixin(Properties settings) { public EnchantingTableBlockMixin(Properties settings) {
super(settings); super(settings);
} }
@Inject(method = "animateTick", at = @At(value = "TAIL")) @Inject(method = "animateTick", at = @At(value = "TAIL"))
private void be_onRandomDisplayTick(BlockState state, Level world, BlockPos pos, Random random, CallbackInfo info) { private void be_onRandomDisplayTick(BlockState state, Level world, BlockPos pos, Random random, CallbackInfo info) {
for (int px = -2; px <= 2; ++px) { for (int px = -2; px <= 2; ++px) {
@ -41,6 +40,6 @@ public abstract class EnchantingTableBlockMixin extends Block {
} }
} }
} }
} }
} }

View file

@ -1,16 +1,5 @@
package ru.bclib.mixin.client; package ru.bclib.mixin.client;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import net.minecraft.client.renderer.block.BlockModelShaper; import net.minecraft.client.renderer.block.BlockModelShaper;
import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.renderer.block.model.BlockModel;
import net.minecraft.client.renderer.block.model.multipart.MultiPart; import net.minecraft.client.renderer.block.model.multipart.MultiPart;
@ -24,10 +13,20 @@ import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import ru.bclib.BCLib; import ru.bclib.BCLib;
import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.BlockModelProvider;
import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ItemModelProvider;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Mixin(ModelBakery.class) @Mixin(ModelBakery.class)
public abstract class ModelBakeryMixin { public abstract class ModelBakeryMixin {
@Final @Final
@ -36,10 +35,10 @@ public abstract class ModelBakeryMixin {
@Final @Final
@Shadow @Shadow
private Map<ResourceLocation, UnbakedModel> unbakedCache; private Map<ResourceLocation, UnbakedModel> unbakedCache;
@Shadow @Shadow
protected abstract void cacheAndQueueDependencies(ResourceLocation resourceLocation, UnbakedModel unbakedModel); protected abstract void cacheAndQueueDependencies(ResourceLocation resourceLocation, UnbakedModel unbakedModel);
@Inject(method = "loadModel", at = @At("HEAD"), cancellable = true) @Inject(method = "loadModel", at = @At("HEAD"), cancellable = true)
private void bclib_loadModels(ResourceLocation resourceLocation, CallbackInfo info) { private void bclib_loadModels(ResourceLocation resourceLocation, CallbackInfo info) {
if (resourceLocation instanceof ModelResourceLocation) { if (resourceLocation instanceof ModelResourceLocation) {
@ -55,7 +54,8 @@ public abstract class ModelBakeryMixin {
ItemModelProvider modelProvider = null; ItemModelProvider modelProvider = null;
if (item instanceof ItemModelProvider) { if (item instanceof ItemModelProvider) {
modelProvider = (ItemModelProvider) item; modelProvider = (ItemModelProvider) item;
} else if (item instanceof BlockItem) { }
else if (item instanceof BlockItem) {
Block block = Registry.BLOCK.get(clearLoc); Block block = Registry.BLOCK.get(clearLoc);
if (block instanceof ItemModelProvider) { if (block instanceof ItemModelProvider) {
modelProvider = (ItemModelProvider) block; modelProvider = (ItemModelProvider) block;
@ -67,21 +67,21 @@ public abstract class ModelBakeryMixin {
model.name = itemLoc.toString(); model.name = itemLoc.toString();
cacheAndQueueDependencies(modelId, model); cacheAndQueueDependencies(modelId, model);
unbakedCache.put(itemLoc, model); unbakedCache.put(itemLoc, model);
} else { }
else {
BCLib.LOGGER.warning("Error loading model: {}", itemLoc); BCLib.LOGGER.warning("Error loading model: {}", itemLoc);
} }
info.cancel(); info.cancel();
} }
} }
} else { }
else {
ResourceLocation stateLoc = new ResourceLocation(modId, "blockstates/" + path + ".json"); ResourceLocation stateLoc = new ResourceLocation(modId, "blockstates/" + path + ".json");
if (!resourceManager.hasResource(stateLoc)) { if (!resourceManager.hasResource(stateLoc)) {
Block block = Registry.BLOCK.get(clearLoc); Block block = Registry.BLOCK.get(clearLoc);
if (block instanceof BlockModelProvider) { if (block instanceof BlockModelProvider) {
List<BlockState> possibleStates = block.getStateDefinition().getPossibleStates(); List<BlockState> possibleStates = block.getStateDefinition().getPossibleStates();
Optional<BlockState> possibleState = possibleStates.stream() Optional<BlockState> possibleState = possibleStates.stream().filter(state -> modelId.equals(BlockModelShaper.stateToModelLocation(clearLoc, state))).findFirst();
.filter(state -> modelId.equals(BlockModelShaper.stateToModelLocation(clearLoc, state)))
.findFirst();
if (possibleState.isPresent()) { if (possibleState.isPresent()) {
UnbakedModel modelVariant = ((BlockModelProvider) block).getModelVariant(modelId, possibleState.get(), unbakedCache); UnbakedModel modelVariant = ((BlockModelProvider) block).getModelVariant(modelId, possibleState.get(), unbakedCache);
if (modelVariant != null) { if (modelVariant != null) {
@ -90,10 +90,12 @@ public abstract class ModelBakeryMixin {
ResourceLocation stateId = BlockModelShaper.stateToModelLocation(clearLoc, state); ResourceLocation stateId = BlockModelShaper.stateToModelLocation(clearLoc, state);
cacheAndQueueDependencies(stateId, modelVariant); cacheAndQueueDependencies(stateId, modelVariant);
}); });
} else { }
else {
cacheAndQueueDependencies(modelId, modelVariant); cacheAndQueueDependencies(modelId, modelVariant);
} }
} else { }
else {
BCLib.LOGGER.warning("Error loading variant: {}", modelId); BCLib.LOGGER.warning("Error loading variant: {}", modelId);
} }
info.cancel(); info.cancel();

View file

@ -1,10 +1,5 @@
package ru.bclib.mixin.common; package ru.bclib.mixin.common;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.BlockPos.MutableBlockPos;
import net.minecraft.core.Vec3i; import net.minecraft.core.Vec3i;
@ -16,6 +11,10 @@ import net.minecraft.world.level.biome.Biome.BiomeCategory;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import ru.bclib.api.BiomeAPI; import ru.bclib.api.BiomeAPI;
import ru.bclib.api.BonemealAPI; import ru.bclib.api.BonemealAPI;
import ru.bclib.api.TagAPI; import ru.bclib.api.TagAPI;
@ -25,7 +24,7 @@ import ru.bclib.util.MHelper;
@Mixin(BoneMealItem.class) @Mixin(BoneMealItem.class)
public class BoneMealItemMixin { public class BoneMealItemMixin {
private static final MutableBlockPos bclib_BLOCK_POS = new MutableBlockPos(); private static final MutableBlockPos bclib_BLOCK_POS = new MutableBlockPos();
@Inject(method = "useOn", at = @At("HEAD"), cancellable = true) @Inject(method = "useOn", at = @At("HEAD"), cancellable = true)
private void bclib_onUse(UseOnContext context, CallbackInfoReturnable<InteractionResult> info) { private void bclib_onUse(UseOnContext context, CallbackInfoReturnable<InteractionResult> info) {
Level world = context.getLevel(); Level world = context.getLevel();
@ -134,7 +133,7 @@ public class BoneMealItemMixin {
block = BonemealAPI.getLandGrass(BiomeAPI.getBiomeID(world.getBiome(pos)), block, world.getRandom()); block = BonemealAPI.getLandGrass(BiomeAPI.getBiomeID(world.getBiome(pos)), block, world.getRandom());
return block == null ? null : block.defaultBlockState(); return block == null ? null : block.defaultBlockState();
} }
private BlockState bclib_getNylium(Level world, BlockPos pos) { private BlockState bclib_getNylium(Level world, BlockPos pos) {
Vec3i[] offsets = MHelper.getOffsets(world.getRandom()); Vec3i[] offsets = MHelper.getOffsets(world.getRandom());
for (Vec3i dir : offsets) { for (Vec3i dir : offsets) {

View file

@ -1,10 +1,9 @@
package ru.bclib.mixin.common; package ru.bclib.mixin.common;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.block.ComposterBlock; import net.minecraft.world.level.block.ComposterBlock;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(ComposterBlock.class) @Mixin(ComposterBlock.class)
public interface ComposterBlockAccessor { public interface ComposterBlockAccessor {

View file

@ -1,15 +1,5 @@
package ru.bclib.mixin.common; package ru.bclib.mixin.common;
import java.util.List;
import java.util.Random;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.world.Container; import net.minecraft.world.Container;
import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.AbstractContainerMenu;
@ -20,42 +10,51 @@ import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.item.enchantment.EnchantmentInstance; import net.minecraft.world.item.enchantment.EnchantmentInstance;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import ru.bclib.api.TagAPI; import ru.bclib.api.TagAPI;
import java.util.List;
import java.util.Random;
@Mixin(EnchantmentMenu.class) @Mixin(EnchantmentMenu.class)
public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { public abstract class EnchantmentMenuMixin extends AbstractContainerMenu {
@Final @Final
@Shadow @Shadow
private Container enchantSlots; private Container enchantSlots;
@Final @Final
@Shadow @Shadow
private ContainerLevelAccess access; private ContainerLevelAccess access;
@Final @Final
@Shadow @Shadow
private Random random; private Random random;
@Final @Final
@Shadow @Shadow
private DataSlot enchantmentSeed; private DataSlot enchantmentSeed;
@Shadow @Shadow
@Final @Final
public int[] costs; public int[] costs;
@Shadow @Shadow
@Final @Final
public int[] enchantClue; public int[] enchantClue;
@Shadow @Shadow
@Final @Final
public int[] levelClue; public int[] levelClue;
protected EnchantmentMenuMixin(MenuType<?> type, int syncId) { protected EnchantmentMenuMixin(MenuType<?> type, int syncId) {
super(type, syncId); super(type, syncId);
} }
@Inject(method = "slotsChanged", at = @At("HEAD"), cancellable = true) @Inject(method = "slotsChanged", at = @At("HEAD"), cancellable = true)
private void be_slotsChanged(Container inventory, CallbackInfo info) { private void be_slotsChanged(Container inventory, CallbackInfo info) {
if (inventory == this.enchantSlots) { if (inventory == this.enchantSlots) {
@ -63,7 +62,7 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu {
if (!itemStack.isEmpty() && itemStack.isEnchantable()) { if (!itemStack.isEmpty() && itemStack.isEnchantable()) {
this.access.execute((world, blockPos) -> { this.access.execute((world, blockPos) -> {
int i = 0; int i = 0;
int j; int j;
for (j = -1; j <= 1; ++j) { for (j = -1; j <= 1; ++j) {
for (int k = -1; k <= 1; ++k) { for (int k = -1; k <= 1; ++k) {
@ -71,24 +70,24 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu {
if (world.getBlockState(blockPos.offset(k * 2, 0, j * 2)).is(TagAPI.BOOKSHELVES)) { if (world.getBlockState(blockPos.offset(k * 2, 0, j * 2)).is(TagAPI.BOOKSHELVES)) {
++i; ++i;
} }
if (world.getBlockState(blockPos.offset(k * 2, 1, j * 2)).is(TagAPI.BOOKSHELVES)) { if (world.getBlockState(blockPos.offset(k * 2, 1, j * 2)).is(TagAPI.BOOKSHELVES)) {
++i; ++i;
} }
if (k != 0 && j != 0) { if (k != 0 && j != 0) {
if (world.getBlockState(blockPos.offset(k * 2, 0, j)).is(TagAPI.BOOKSHELVES)) { if (world.getBlockState(blockPos.offset(k * 2, 0, j)).is(TagAPI.BOOKSHELVES)) {
++i; ++i;
} }
if (world.getBlockState(blockPos.offset(k * 2, 1, j)).is(TagAPI.BOOKSHELVES)) { if (world.getBlockState(blockPos.offset(k * 2, 1, j)).is(TagAPI.BOOKSHELVES)) {
++i; ++i;
} }
if (world.getBlockState(blockPos.offset(k, 0, j * 2)).is(TagAPI.BOOKSHELVES)) { if (world.getBlockState(blockPos.offset(k, 0, j * 2)).is(TagAPI.BOOKSHELVES)) {
++i; ++i;
} }
if (world.getBlockState(blockPos.offset(k, 1, j * 2)).is(TagAPI.BOOKSHELVES)) { if (world.getBlockState(blockPos.offset(k, 1, j * 2)).is(TagAPI.BOOKSHELVES)) {
++i; ++i;
} }
@ -96,9 +95,9 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu {
} }
} }
} }
random.setSeed(enchantmentSeed.get()); random.setSeed(enchantmentSeed.get());
for (j = 0; j < 3; ++j) { for (j = 0; j < 3; ++j) {
costs[j] = EnchantmentHelper.getEnchantmentCost(this.random, j, i, itemStack); costs[j] = EnchantmentHelper.getEnchantmentCost(this.random, j, i, itemStack);
enchantClue[j] = -1; enchantClue[j] = -1;
@ -107,7 +106,7 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu {
costs[j] = 0; costs[j] = 0;
} }
} }
for (j = 0; j < 3; ++j) { for (j = 0; j < 3; ++j) {
if (this.costs[j] > 0) { if (this.costs[j] > 0) {
List<EnchantmentInstance> list = this.getEnchantmentList(itemStack, j, this.costs[j]); List<EnchantmentInstance> list = this.getEnchantmentList(itemStack, j, this.costs[j]);
@ -118,7 +117,7 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu {
} }
} }
} }
broadcastChanges(); broadcastChanges();
}); });
} }
@ -132,7 +131,7 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu {
info.cancel(); info.cancel();
} }
} }
@Shadow @Shadow
private List<EnchantmentInstance> getEnchantmentList(ItemStack stack, int slot, int level) { private List<EnchantmentInstance> getEnchantmentList(ItemStack stack, int slot, int level) {
return null; return null;

View file

@ -1,16 +1,9 @@
package ru.bclib.mixin.common; package ru.bclib.mixin.common;
import net.minecraft.data.worldgen.Features;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.level.block.ComposterBlock;
import net.minecraft.world.level.levelgen.placement.ConfiguredDecorator; import net.minecraft.world.level.levelgen.placement.ConfiguredDecorator;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Accessor;
import java.util.Map;
@Mixin(targets = "net.minecraft.data.worldgen.Features$Decorators") @Mixin(targets = "net.minecraft.data.worldgen.Features$Decorators")
public interface FeatureDecoratorsAccessor { public interface FeatureDecoratorsAccessor {
@Accessor("HEIGHTMAP_SQUARE") @Accessor("HEIGHTMAP_SQUARE")

View file

@ -1,17 +1,5 @@
package ru.bclib.mixin.common; package ru.bclib.mixin.common;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
@ -19,9 +7,20 @@ import net.minecraft.server.ServerResources;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.storage.WorldData; import net.minecraft.world.level.storage.WorldData;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import ru.bclib.api.BiomeAPI; import ru.bclib.api.BiomeAPI;
import ru.bclib.recipes.BCLRecipeManager; import ru.bclib.recipes.BCLRecipeManager;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
@Mixin(MinecraftServer.class) @Mixin(MinecraftServer.class)
public class MinecraftServerMixin { public class MinecraftServerMixin {
@Shadow @Shadow
@ -34,18 +33,18 @@ public class MinecraftServerMixin {
@Final @Final
@Shadow @Shadow
protected WorldData worldData; protected WorldData worldData;
@Inject(method = "reloadResources", at = @At(value = "RETURN"), cancellable = true) @Inject(method = "reloadResources", at = @At(value = "RETURN"), cancellable = true)
private void bcl_reloadResources(Collection<String> collection, CallbackInfoReturnable<CompletableFuture<Void>> info) { private void bcl_reloadResources(Collection<String> collection, CallbackInfoReturnable<CompletableFuture<Void>> info) {
bcl_injectRecipes(); bcl_injectRecipes();
} }
@Inject(method = "loadLevel", at = @At(value = "RETURN"), cancellable = true) @Inject(method = "loadLevel", at = @At(value = "RETURN"), cancellable = true)
private void bcl_loadLevel(CallbackInfo info) { private void bcl_loadLevel(CallbackInfo info) {
bcl_injectRecipes(); bcl_injectRecipes();
BiomeAPI.initRegistry(MinecraftServer.class.cast(this)); BiomeAPI.initRegistry(MinecraftServer.class.cast(this));
} }
private void bcl_injectRecipes() { private void bcl_injectRecipes() {
if (FabricLoader.getInstance().isModLoaded("kubejs")) { if (FabricLoader.getInstance().isModLoaded("kubejs")) {
RecipeManagerAccessor accessor = (RecipeManagerAccessor) resources.getRecipeManager(); RecipeManagerAccessor accessor = (RecipeManagerAccessor) resources.getRecipeManager();

View file

@ -1,11 +1,10 @@
package ru.bclib.mixin.common; package ru.bclib.mixin.common;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.item.alchemy.Potion; import net.minecraft.world.item.alchemy.Potion;
import net.minecraft.world.item.alchemy.PotionBrewing; import net.minecraft.world.item.alchemy.PotionBrewing;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(PotionBrewing.class) @Mixin(PotionBrewing.class)
public interface PotionBrewingAccessor { public interface PotionBrewingAccessor {

View file

@ -1,20 +1,19 @@
package ru.bclib.mixin.common; package ru.bclib.mixin.common;
import java.util.Map;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.RecipeManager; import net.minecraft.world.item.crafting.RecipeManager;
import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.item.crafting.RecipeType;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
import java.util.Map;
@Mixin(RecipeManager.class) @Mixin(RecipeManager.class)
public interface RecipeManagerAccessor { public interface RecipeManagerAccessor {
@Accessor("recipes") @Accessor("recipes")
Map<RecipeType<?>, Map<ResourceLocation, Recipe<?>>> bcl_getRecipes(); Map<RecipeType<?>, Map<ResourceLocation, Recipe<?>>> bcl_getRecipes();
@Accessor("recipes") @Accessor("recipes")
void bcl_setRecipes(Map<RecipeType<?>, Map<ResourceLocation, Recipe<?>>> recipes); void bcl_setRecipes(Map<RecipeType<?>, Map<ResourceLocation, Recipe<?>>> recipes);
} }

View file

@ -1,20 +1,6 @@
package ru.bclib.mixin.common; package ru.bclib.mixin.common;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import net.minecraft.Util; import net.minecraft.Util;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.ResourceManager;
@ -24,23 +10,35 @@ import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.RecipeManager; import net.minecraft.world.item.crafting.RecipeManager;
import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import ru.bclib.recipes.BCLRecipeManager; import ru.bclib.recipes.BCLRecipeManager;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Mixin(RecipeManager.class) @Mixin(RecipeManager.class)
public abstract class RecipeManagerMixin { public abstract class RecipeManagerMixin {
@Shadow @Shadow
private Map<RecipeType<?>, Map<ResourceLocation, Recipe<?>>> recipes; private Map<RecipeType<?>, Map<ResourceLocation, Recipe<?>>> recipes;
@Inject(method = "apply", at = @At(value = "RETURN")) @Inject(method = "apply", at = @At(value = "RETURN"))
private void be_apply(Map<ResourceLocation, JsonElement> map, ResourceManager resourceManager, ProfilerFiller profiler, CallbackInfo info) { private void be_apply(Map<ResourceLocation, JsonElement> map, ResourceManager resourceManager, ProfilerFiller profiler, CallbackInfo info) {
recipes = BCLRecipeManager.getMap(recipes); recipes = BCLRecipeManager.getMap(recipes);
} }
@Shadow @Shadow
private <C extends Container, T extends Recipe<C>> Map<ResourceLocation, Recipe<C>> byType(RecipeType<T> type) { private <C extends Container, T extends Recipe<C>> Map<ResourceLocation, Recipe<C>> byType(RecipeType<T> type) {
return null; return null;
} }
/** /**
* @author paulevs * @author paulevs
* @reason Remove conflicts with vanilla tags * @reason Remove conflicts with vanilla tags
@ -56,7 +54,7 @@ public abstract class RecipeManagerMixin {
boolean b2 = v2.getId().getNamespace().equals("minecraft"); boolean b2 = v2.getId().getNamespace().equals("minecraft");
return b1 ^ b2 ? (b1 ? 1 : -1) : 0; return b1 ^ b2 ? (b1 ? 1 : -1) : 0;
}); });
return list.stream().flatMap((recipe) -> { return list.stream().flatMap((recipe) -> {
return Util.toStream(type.tryMatch(recipe, world, inventory)); return Util.toStream(type.tryMatch(recipe, world, inventory));
}).findFirst(); }).findFirst();

View file

@ -1,15 +1,5 @@
package ru.bclib.mixin.common; package ru.bclib.mixin.common;
import java.io.File;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
@ -22,10 +12,19 @@ import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.ServerLevelData; import net.minecraft.world.level.storage.ServerLevelData;
import net.minecraft.world.level.storage.WritableLevelData; import net.minecraft.world.level.storage.WritableLevelData;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import ru.bclib.api.BiomeAPI; import ru.bclib.api.BiomeAPI;
import ru.bclib.api.DataFixerAPI; import ru.bclib.api.DataFixerAPI;
import ru.bclib.api.WorldDataAPI; import ru.bclib.api.WorldDataAPI;
import java.io.File;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
@Mixin(ServerLevel.class) @Mixin(ServerLevel.class)
public abstract class ServerLevelMixin extends Level { public abstract class ServerLevelMixin extends Level {
private static String bcl_lastWorld = null; private static String bcl_lastWorld = null;

View file

@ -1,7 +1,5 @@
package ru.bclib.mixin.common; package ru.bclib.mixin.common;
import java.util.Map;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.Tag; import net.minecraft.tags.Tag;
import net.minecraft.tags.TagLoader; import net.minecraft.tags.TagLoader;
@ -11,11 +9,13 @@ import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.ModifyArg;
import ru.bclib.util.TagHelper; import ru.bclib.util.TagHelper;
import java.util.Map;
@Mixin(TagLoader.class) @Mixin(TagLoader.class)
public class TagLoaderMixin { public class TagLoaderMixin {
@Shadow @Shadow
private String directory; private String directory;
@ModifyArg(method = "loadAndBuild", at = @At(value = "INVOKE", target = "Lnet/minecraft/tags/TagLoader;build(Ljava/util/Map;)Lnet/minecraft/tags/TagCollection;")) @ModifyArg(method = "loadAndBuild", at = @At(value = "INVOKE", target = "Lnet/minecraft/tags/TagLoader;build(Ljava/util/Map;)Lnet/minecraft/tags/TagCollection;"))
public Map<ResourceLocation, Tag.Builder> be_modifyTags(Map<ResourceLocation, Tag.Builder> tagsMap) { public Map<ResourceLocation, Tag.Builder> be_modifyTags(Map<ResourceLocation, Tag.Builder> tagsMap) {
return TagHelper.apply(directory, tagsMap); return TagHelper.apply(directory, tagsMap);

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