Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Refactor block hardness code into block properties and copycat stuff #477

Merged
merged 1 commit into from
Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.txt
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Added:
- Added ability to place Autocannon Ammo Containers as blocks
- Added tooltip to Autocannon Ammo Container showing contained items and spacing
- Added Creative Autocannon Ammo Container, an endless source of autocannon ammo
- Added block hardness compatibility with Create Copycat blocks
Changes:
- Reduced the stress cost of the Cannon Loader to match that of the Mechanical Piston
- Reduced default blob count of Fluid Shell
Expand All @@ -41,6 +42,7 @@ Changes:
- The old fields still work, but a warning will be printed in the game log highlighting any deprecated files.
- Changed minimum timing for Timed Fuze from 20 ticks (1 second) to 1 tick, reduced maximum time from 25s 15t to 24s 15t
- Changed minimum timing for Delayed Impact Fuze from 20 ticks (1 second) to 1 tick, reduced maximum time from 6s to 5s
- Improved data pack config for block hardness and block properties for terminal ballistics in general
Fixes:
- Fixed drop mortar not dropping stored item if disassembled or broken before fired
- Fixed drop mortar holding entire stack
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo;
import net.minecraft.world.phys.BlockHitResult;
import rbasamoyai.createbigcannons.CBCTags;
import rbasamoyai.createbigcannons.CreateBigCannons;
import rbasamoyai.createbigcannons.block_hardness.TerminalBallisticsBlockPropertiesHandler;
import rbasamoyai.createbigcannons.cannon_control.contraption.PitchOrientedContraptionEntity;
import rbasamoyai.createbigcannons.cannon_loading.CannonLoaderBlock;
import rbasamoyai.createbigcannons.cannon_loading.CannonLoaderBlockEntity;
Expand All @@ -55,7 +54,6 @@
import rbasamoyai.createbigcannons.munitions.big_cannon.propellant.BigCartridgeBlock;
import rbasamoyai.createbigcannons.munitions.big_cannon.propellant.BigCartridgeBlockItem;
import rbasamoyai.createbigcannons.munitions.config.BigCannonPropellantCompatibilityHandler;
import rbasamoyai.createbigcannons.munitions.config.BlockHardnessHandler;
import rbasamoyai.createbigcannons.munitions.config.DimensionMunitionPropertiesHandler;
import rbasamoyai.createbigcannons.munitions.config.MunitionPropertiesHandler;
import rbasamoyai.createbigcannons.network.CBCRootNetwork;
Expand Down Expand Up @@ -201,13 +199,13 @@ public static boolean destroyCannonLoader(BlockState state, Level level, BlockPo
public static void onLoadLevel(LevelAccessor level) {
CreateBigCannons.BLOCK_DAMAGE.levelLoaded(level);
if (level.getServer() != null && !level.isClientSide() && level.getServer().overworld() == level) {
BlockHardnessHandler.loadTags();
TerminalBallisticsBlockPropertiesHandler.loadTags();
FluidCastingTimeHandler.loadTags();
}
}

public static void onDatapackReload(MinecraftServer server) {
BlockHardnessHandler.loadTags();
TerminalBallisticsBlockPropertiesHandler.loadTags();
BlockRecipesManager.syncToAll(server);
MunitionPropertiesHandler.syncToAll(server);
AutocannonMaterialPropertiesHandler.syncToAll(server);
Expand All @@ -229,7 +227,7 @@ public static void onDatapackSync(ServerPlayer player) {
public static void onAddReloadListeners(BiConsumer<PreparableReloadListener, ResourceLocation> cons) {
cons.accept(BlockRecipeFinder.LISTENER, CreateBigCannons.resource("block_recipe_finder"));
cons.accept(BlockRecipesManager.ReloadListener.INSTANCE, CreateBigCannons.resource("block_recipe_manager"));
cons.accept(BlockHardnessHandler.BlockReloadListener.INSTANCE, CreateBigCannons.resource("block_hardness_handler"));
cons.accept(TerminalBallisticsBlockPropertiesHandler.BlockReloadListener.INSTANCE, CreateBigCannons.resource("block_hardness_handler"));
cons.accept(MunitionPropertiesHandler.ReloadListenerProjectiles.INSTANCE, CreateBigCannons.resource("projectile_properties_handler"));
cons.accept(MunitionPropertiesHandler.ReloadListenerBlockPropellant.INSTANCE, CreateBigCannons.resource("block_propellant_properties_handler"));
cons.accept(MunitionPropertiesHandler.ReloadListenerItemPropellant.INSTANCE, CreateBigCannons.resource("item_propellant_properties_handler"));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package rbasamoyai.createbigcannons.base;

import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.function.Predicate;

import javax.annotation.Nullable;

import com.google.common.base.Splitter;
import com.google.common.collect.Maps;

import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.Property;

public class BlockStatePredicateHelper {

private static final Splitter COMMA_SPLITTER = Splitter.on(',');
private static final Splitter EQUAL_SPLITTER = Splitter.on('=').limit(2);

// Taken from ModelBakery
public static Predicate<BlockState> variantPredicate(StateDefinition<Block, BlockState> container, String variant) {
Map<Property<?>, Comparable<?>> map = Maps.newHashMap();

for(String s : COMMA_SPLITTER.split(variant)) {
Iterator<String> iterator = EQUAL_SPLITTER.split(s).iterator();
if (!iterator.hasNext()) continue;
String s1 = iterator.next();
Property<?> property = container.getProperty(s1);
if (property != null && iterator.hasNext()) {
String s2 = iterator.next();
Comparable<?> comparable = getValueHelper(property, s2);
if (comparable == null) {
throw new RuntimeException("Unknown value: '" + s2 + "' for blockstate property: '" + s1 + "' " + property.getPossibleValues());
}
map.put(property, comparable);
} else if (!s1.isEmpty()) {
throw new RuntimeException("Unknown blockstate property: '" + s1 + "'");
}
}

Block block = container.getOwner();
return arg2 -> {
if (arg2 == null || !arg2.is(block)) return false;
for(Map.Entry<Property<?>, Comparable<?>> entry : map.entrySet()) {
if (!Objects.equals(arg2.getValue((Property) entry.getKey()), entry.getValue())) {
return false;
}
}
return true;
};
}

@Nullable
private static <T extends Comparable<T>> T getValueHelper(Property<T> property, String value) {
return property.getValue(value).orElse(null);
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package rbasamoyai.createbigcannons.base;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.minecraft.core.BlockPos;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
Expand All @@ -9,11 +13,7 @@
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Material;
import rbasamoyai.createbigcannons.munitions.config.BlockHardnessHandler;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import rbasamoyai.createbigcannons.block_hardness.TerminalBallisticsBlockPropertiesHandler;

public class PartialBlockDamageManager {

Expand Down Expand Up @@ -81,7 +81,7 @@ public void tick(Level level) {
} else {
newSet.put(entry.getKey(), newProgress);
}
double hardnessRec = 1 / BlockHardnessHandler.getHardness(state, level, pos);
double hardnessRec = 1 / TerminalBallisticsBlockPropertiesHandler.getProperties(state).hardness(level, state, pos, true);
int oldPart = (int) Math.floor(oldProgress * hardnessRec);
int newPart = (int) Math.floor(newProgress * hardnessRec);
if (oldPart - newPart > 0) level.destroyBlockProgress(-1, pos, newPart);
Expand All @@ -102,7 +102,7 @@ public void damageBlock(BlockPos pos, int added, BlockState state, Level level)
int oldProgress = levelSet.getOrDefault(pos, 0);
levelSet.merge(pos, added, Integer::sum);

double hardnessRec = 1 / BlockHardnessHandler.getHardness(state, level, pos);
double hardnessRec = 1 / TerminalBallisticsBlockPropertiesHandler.getProperties(state).hardness(level, state, pos, true);
int oldPart = (int) Math.floor(oldProgress * hardnessRec);
int newPart = (int) Math.floor(levelSet.get(pos) * hardnessRec);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package rbasamoyai.createbigcannons.block_hardness;

import com.google.gson.JsonObject;

public interface HasSpecialTerminalBallisticsBlockProperties extends TerminalBallisticsBlockPropertiesProvider {

default void loadTerminalBallisticsBlockPropertiesFromJson(String id, JsonObject obj) {}

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package rbasamoyai.createbigcannons.munitions.config;
package rbasamoyai.createbigcannons.block_hardness;

import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.world.InteractionResult;
Expand All @@ -7,8 +7,9 @@
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import rbasamoyai.createbigcannons.multiloader.IndexPlatform;
import net.minecraft.world.level.block.state.BlockState;
import rbasamoyai.createbigcannons.CreateBigCannons;
import rbasamoyai.createbigcannons.multiloader.IndexPlatform;

public class InspectResistanceToolItem extends Item {

Expand All @@ -22,7 +23,8 @@ public InteractionResult useOn(UseOnContext ctx) {
Level level = ctx.getLevel();
if (!level.isClientSide && player != null && !IndexPlatform.isFakePlayer(player)) {
String key = "debug." + CreateBigCannons.MOD_ID + ".block_resistance";
double hardness = BlockHardnessHandler.getHardness(level.getBlockState(ctx.getClickedPos()), level, ctx.getClickedPos());
BlockState state = level.getBlockState(ctx.getClickedPos());
double hardness = TerminalBallisticsBlockPropertiesHandler.getProperties(state).hardness(level, state, ctx.getClickedPos(), true);
player.displayClientMessage(new TranslatableComponent(key, String.format("%.2f", hardness)), true);
}
return super.useOn(ctx);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package rbasamoyai.createbigcannons.block_hardness;

import com.google.gson.JsonObject;

import net.minecraft.core.BlockPos;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;

public record SimpleTerminalBallisticsBlockProperties(double hardness) implements TerminalBallisticsBlockPropertiesProvider {
@Override
public double hardness(Level level, BlockState state, BlockPos pos, boolean recurse) {
return this.hardness;
}

public static SimpleTerminalBallisticsBlockProperties fromJson(String id, JsonObject obj) {
double hardness = Math.max(GsonHelper.getAsDouble(obj, "block_hardness", 1), 0);
return new SimpleTerminalBallisticsBlockProperties(hardness);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package rbasamoyai.createbigcannons.block_hardness;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;

import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener;
import net.minecraft.tags.TagKey;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import rbasamoyai.createbigcannons.CreateBigCannons;
import rbasamoyai.createbigcannons.base.BlockStatePredicateHelper;

public class TerminalBallisticsBlockPropertiesHandler {

private static final Map<Block, SimpleTerminalBallisticsBlockProperties> TAG_MAP = new HashMap<>();
private static final Map<BlockState, SimpleTerminalBallisticsBlockProperties> SIMPLE_BLOCK_MAP = new HashMap<>();
private static final Map<TagKey<Block>, SimpleTerminalBallisticsBlockProperties> TAGS_TO_EVALUATE = new LinkedHashMap<>();

private static final TerminalBallisticsBlockPropertiesProvider FALLBACK_PROVIDER = new TerminalBallisticsBlockPropertiesProvider() {
@Override public double hardness(Level level, BlockState state, BlockPos pos, boolean recurse) { return state.getBlock().getExplosionResistance(); }
};

public static class BlockReloadListener extends SimpleJsonResourceReloadListener {
private static final Gson GSON = new Gson();
public static final BlockReloadListener INSTANCE = new BlockReloadListener();

public BlockReloadListener() { super(GSON, "block_terminal_ballistics"); }

@Override
protected void apply(Map<ResourceLocation, JsonElement> map, ResourceManager manager, ProfilerFiller profiler) {
cleanUp();

for (Map.Entry<ResourceLocation, JsonElement> entry : map.entrySet()) {
JsonElement el = entry.getValue();
if (!el.isJsonObject()) continue;
try {
ResourceLocation loc = entry.getKey();
if (loc.getPath().startsWith("tags/")) {
ResourceLocation pruned = new ResourceLocation(loc.getNamespace(), loc.getPath().substring(5));
TagKey<Block> tag = TagKey.create(Registry.BLOCK_REGISTRY, pruned);
SimpleTerminalBallisticsBlockProperties properties = SimpleTerminalBallisticsBlockProperties.fromJson("#" + loc, el.getAsJsonObject());
TAGS_TO_EVALUATE.put(tag, properties);
} else {
Block block = Registry.BLOCK.getOptional(loc).orElseThrow(() -> {
return new JsonSyntaxException("Unknown block '" + loc + "'");
});
if (block instanceof HasSpecialTerminalBallisticsBlockProperties special) {
special.loadTerminalBallisticsBlockPropertiesFromJson(loc.toString(), el.getAsJsonObject());
} else {
loadSimpleProperties(block, loc, el.getAsJsonObject());
}
}
} catch (Exception e) {
CreateBigCannons.LOGGER.warn("Exception loading terminal ballistics block properties: {}", e.getMessage());
}
}
}
}

private static void loadSimpleProperties(Block block, ResourceLocation loc, JsonObject obj) {
StateDefinition<Block, BlockState> definition = block.getStateDefinition();
Set<BlockState> states = new HashSet<>(definition.getPossibleStates());
if (obj.has("variants") && obj.get("variants").isJsonObject()) {
JsonObject variants = obj.getAsJsonObject("variants");
for (String key : variants.keySet()) {
Predicate<BlockState> pred = BlockStatePredicateHelper.variantPredicate(definition, key);
JsonElement el = variants.get(key);
if (!el.isJsonObject()) {
throw new JsonSyntaxException("Invalid info for variant '" + key + "''");
}
JsonObject variantInfo = el.getAsJsonObject();
SimpleTerminalBallisticsBlockProperties properties = SimpleTerminalBallisticsBlockProperties.fromJson(loc.toString(), variantInfo);
for (Iterator<BlockState> stateIter = states.iterator(); stateIter.hasNext(); ) {
BlockState state = stateIter.next();
if (pred.test(state)) {
SIMPLE_BLOCK_MAP.put(state, properties);
stateIter.remove();
}
}
}
} else {
SimpleTerminalBallisticsBlockProperties properties = SimpleTerminalBallisticsBlockProperties.fromJson(loc.toString(), obj);
for (BlockState state : states) {
SIMPLE_BLOCK_MAP.put(state, properties);
}
}
}

public static void loadTags() {
TAG_MAP.clear();
for (Map.Entry<TagKey<Block>, SimpleTerminalBallisticsBlockProperties> entry : TAGS_TO_EVALUATE.entrySet()) {
SimpleTerminalBallisticsBlockProperties properties = entry.getValue();
for (Holder<Block> holder : Registry.BLOCK.getTagOrEmpty(entry.getKey())) {
TAG_MAP.put(holder.value(), properties);
}
}
TAGS_TO_EVALUATE.clear();
}

public static void cleanUp() {
TAG_MAP.clear();
SIMPLE_BLOCK_MAP.clear();
TAGS_TO_EVALUATE.clear();
}

public static TerminalBallisticsBlockPropertiesProvider getProperties(BlockState state) {
Block block = state.getBlock();
if (block instanceof HasSpecialTerminalBallisticsBlockProperties special) return special;
if (SIMPLE_BLOCK_MAP.containsKey(state)) return SIMPLE_BLOCK_MAP.get(state);
if (TAG_MAP.containsKey(block)) return TAG_MAP.get(block);
return FALLBACK_PROVIDER;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package rbasamoyai.createbigcannons.block_hardness;

import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;

public interface TerminalBallisticsBlockPropertiesProvider {

double hardness(Level level, BlockState state, BlockPos pos, boolean recurse);

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import rbasamoyai.createbigcannons.datagen.loot.CBCLootTableProvider;
import rbasamoyai.createbigcannons.datagen.recipes.BlockRecipeProvider;
import rbasamoyai.createbigcannons.datagen.recipes.CBCCraftingRecipeProvider;
import rbasamoyai.createbigcannons.datagen.values.BlockHardnessProvider;
import rbasamoyai.createbigcannons.index.CBCSoundEvents;
import rbasamoyai.createbigcannons.multiloader.IndexPlatform;
import rbasamoyai.createbigcannons.ponder.CBCPonderIndex;
Expand All @@ -21,7 +20,6 @@ public static void register(DataGenerator gen, ExistingFileHelper helper, boolea
BlockRecipeProvider.registerAll(gen);
CBCCraftingRecipeProvider.register();
gen.addProvider(new CBCLootTableProvider(CreateBigCannons.REGISTRATE, gen));
gen.addProvider(new BlockHardnessProvider(CreateBigCannons.MOD_ID, gen));
IndexPlatform.addSidedDataGenerators(gen);
}
if (client) {
Expand Down
Loading
Loading