added source code for ominousdarkness to be ported to 1.20.1, ores are no longer glowing

New project that will take some time but seems to be worth it
This commit is contained in:
2025-05-27 06:42:23 -05:00
parent abab9430fa
commit d0d125303a
38 changed files with 1930 additions and 2 deletions

View File

@ -0,0 +1,9 @@
package dcaedll.ominousdarkness;
import net.minecraft.world.damagesource.*;
public class DarknessDamageSource
{
public static final DamageSource DARKNESS
= (new DamageSource(OminousDarkness.MODID.concat(".darkness"))).bypassArmor().bypassInvul();
}

View File

@ -0,0 +1,92 @@
package dcaedll.ominousdarkness;
import javax.annotation.*;
import dcaedll.ominousdarkness.util.*;
import net.minecraft.core.*;
import net.minecraft.resources.*;
import net.minecraft.world.effect.*;
import net.minecraft.world.entity.player.*;
public class DarknessEffect
{
private MobEffect _mobEffect;
private String _name;
private boolean _indefinite;
private int _duration = 40;
private int _power = 1;
private float _factor = 0.0f;
public String get_registryName()
{
return _name;
}
public int get_duration()
{
return _duration;
}
public void set_duration(int duration)
{
_duration = (int)MathHelper.clamp(duration, 0, Integer.MAX_VALUE);
set_indefinite(false);
}
public int get_power()
{
return _power;
}
public void set_power(int value)
{
_power = (int)MathHelper.clamp(value, 1, Integer.MAX_VALUE);
}
public float get_factor()
{
return _factor;
}
public void set_factor(float value)
{
_factor = MathHelper.clamp(value, 0.0f, 1.0f);
}
public boolean get_indefinite()
{
return _indefinite;
}
public void set_indefinite(boolean value)
{
_indefinite = value;
}
@Nullable
public MobEffect get_mobEffect()
{
return _mobEffect;
}
@SuppressWarnings("deprecation")
public DarknessEffect(@Nonnull String registryName)
{
_name = registryName;
_mobEffect = Registry.MOB_EFFECT.get(new ResourceLocation(get_registryName()));
set_indefinite(true);
}
public void apply(@Nonnull Player player)
{
if (_mobEffect != null)
player.addEffect(newEffectInstance());
}
private MobEffectInstance newEffectInstance()
{
MobEffectInstance i = new MobEffectInstance(_mobEffect, get_duration(), get_power() - 1);
i.setNoCounter(get_indefinite());
return i;
}
}

View File

@ -0,0 +1,341 @@
package dcaedll.ominousdarkness;
import java.util.*;
import javax.annotation.*;
import dcaedll.ominousdarkness.capability.*;
import dcaedll.ominousdarkness.config.*;
import dcaedll.ominousdarkness.net.*;
import net.minecraft.client.*;
import net.minecraft.client.player.*;
import net.minecraft.server.level.*;
import net.minecraft.world.entity.player.*;
import net.minecraft.world.item.*;
import net.minecraftforge.api.distmarker.*;
import net.minecraftforge.network.*;
public class DarknessProcessor
{
public static final int EFFECT_REAPPLICATION_RATE = 10;
private static DarknessEffect[] _eff;
private static float _effLowerBound = 0.0f;
public static void tickPlayer(@Nonnull final ServerPlayer player)
{
if (player.isCreative() || player.isSpectator())
return;
player.getCapability(DarknessHandlerProvider.CAP).ifPresent(cap ->
{
if (cap instanceof DarknessHandler)
{
DarknessHandler dh = (DarknessHandler)cap;
if (_validatePlayerDim(player, dh))
{
_tickDarkness(player, dh);
_shareDarknessUpdate(player, dh);
}
}
});
}
public static void onConfigSetUp()
{
reloadEffects();
}
public static void reloadEffects()
{
_eff = _parseEffects(ConfigHandler.getCommonCustom().effects.get(), ConfigHandler.getCommonCustom().growth.get().floatValue() * 20.0f);
_updateEffectsLowerBound();
}
@SuppressWarnings("resource")
@OnlyIn(Dist.CLIENT)
public static void receiveDarknessUpdate(float factor)
{
LocalPlayer player = Minecraft.getInstance().player;
if (player != null)
{
player.getCapability(DarknessHandlerProvider.CAP).ifPresent(cap -> ((DarknessHandler)cap).set_factor(factor));
}
}
private static void _shareDarknessUpdate(ServerPlayer player, DarknessHandler dh)
{
if (dh.dirty)
{
DarknessPacket packet = new DarknessPacket(dh.get_factor());
PacketHandler.CHANNEL_INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), packet);
dh.dirty = false;
}
}
private static void _tickDarkness(final Player player, final DarknessHandler dh)
{
int th = _getLightLevelThreshold();
int total = _calcTotalLightValue(player);
if (total <= th)
{
if (dh.update(true) && _getDarknessKills())
{
_kill(player);
return;
}
if (dh.aboveZero())
{
_handleEffects(player, dh);
}
}
else
{
if (dh.update(false))
{
dh.reappliedEffects.clear();
dh.damageDelayCounter = 0;
dh.damageCounter = 0;
}
dh.effectCounter = 0;
}
if (dh.aboveZero())
{
if (dh.damageDelayCounter + 1 >= _getDamageDelay() * 20)
{
dh.damageCounter--;
if (dh.damageCounter <= 0)
{
_damage(player);
dh.damageCounter = (int)(_getDamageInterval() * 20);
}
}
else dh.damageDelayCounter++;
if (dh.reTickCounter++ >= EFFECT_REAPPLICATION_RATE)
{
_reapplyEffects(player, dh);
dh.reTickCounter = 0;
}
}
}
private static void _kill(Player player)
{
player.hurt(DarknessDamageSource.DARKNESS, Float.MAX_VALUE);
}
private static void _damage(Player player)
{
player.hurt(DarknessDamageSource.DARKNESS, _getDamage());
}
private static DarknessEffect[] _parseEffects(List<? extends Object> effs, float growthTicks)
{
DarknessEffect[] arr = new DarknessEffect[effs.size()];
for (int j = 0; j < effs.size(); j++)
{
String s = (String)effs.get(j);
String[] split = s.split("(?=\\[)");
DarknessEffect de = new DarknessEffect(split[0]);
if (de.get_mobEffect() == null)
continue;
if (split.length > 1)
{
for (int i = 1; i < split.length; i++)
{
if (split[i].length() >= 5 && split[i].startsWith("[") && split[i].endsWith("]"))
{
String[] paramSplit = split[i].split("\\=");
if (paramSplit.length == 2 && paramSplit[0].length() > 1 && paramSplit[1].length() > 1)
{
paramSplit[0] = paramSplit[0].substring(1);
paramSplit[1] = paramSplit[1].substring(0, paramSplit[1].length() - 1);
String param = paramSplit[0].toLowerCase();
try
{
if (param.equals("duration"))
{
de.set_duration(Integer.parseInt(paramSplit[1]) * 20);
}
else if (param.equals("level"))
{
de.set_power(Integer.parseInt(paramSplit[1]));
}
else if (param.equals("timing"))
{
String dim = paramSplit[1].substring(paramSplit[1].length() - 1);
float num = Float.valueOf(paramSplit[1].substring(0, paramSplit[1].length() - 1));
if (dim.equals("%"))
{
de.set_factor(num / 100.0f);
}
else if (dim.equals("s"))
{
de.set_factor(num * 20.0f / growthTicks);
}
}
}
catch (Exception e)
{
_logEffectParameterError(paramSplit[0], paramSplit[1]);
}
}
}
}
}
arr[j] = de;
}
// sort by factor in asc order
for (int i = 0; i < arr.length; i++)
{
for (int j = 0; j > i && j < arr.length; j++)
{
if (arr[i].get_factor() < arr[j].get_factor())
{
DarknessEffect de = arr[i];
arr[i] = arr[j];
arr[j] = de;
}
}
}
return arr;
}
private static void _logEffectParameterError(String param, String value)
{
OminousDarkness.LOGGER.error("Invalid effect parameter {} with value {}", param, value);
}
private static void _updateEffectsLowerBound()
{
_effLowerBound = Float.MAX_VALUE;
for (DarknessEffect eff : _eff)
{
if (eff.get_factor() <= _effLowerBound)
_effLowerBound = eff.get_factor();
}
}
private static boolean _validatePlayerDim(ServerPlayer player, DarknessHandler dh)
{
if (player.getLevel().dimension().location() != dh.dim)
{
String dim = (dh.dim = player.getLevel().dimension().location()).toString();
dh.isInSuitableDim = _dimIsWhitelist() ? _dimContains(dim) : !_dimContains(dim);
}
return dh.isInSuitableDim;
}
private static boolean _dimContains(String dim)
{
return ConfigHandler.getCommonCustom().dimBlacklist.get().contains(dim);
}
private static boolean _dimIsWhitelist()
{
return ConfigHandler.getCommonCustom().dimListAsWhitelist.get().booleanValue();
}
private static int _calcTotalLightValue(Player player)
{
return player.level.getMaxLocalRawBrightness(player.blockPosition())
+ _getShinyValueForItems(player.getMainHandItem().getItem(), player.getOffhandItem().getItem());
}
private static int _getLightLevelThreshold()
{
return ConfigHandler.getCommonCustom().lightLevelThreshold.get().intValue();
}
private static boolean _getDarknessKills()
{
return ConfigHandler.getCommonCustom().darknessKills.get().booleanValue();
}
private static float _getDamageInterval()
{
return ConfigHandler.getCommonCustom().damageInterval.get().floatValue();
}
private static float _getDamageDelay()
{
return ConfigHandler.getCommonCustom().damageDelay.get().floatValue();
}
private static float _getDamage()
{
return ConfigHandler.getCommonCustom().damage.get().floatValue();
}
private static int _getShinyValueForItems(Item item1, Item item2)
{
boolean flag1 = false;
boolean flag2 = false;
int val = 0;
List<? extends Object> shiny = ConfigHandler.getCommonCustom().shinyItems.get();
for (Object item : shiny)
{
String[] split = _splitShinyItemString((String)item);
if (!flag1 && item1.getRegistryName().toString().equals(split[0]))
{
val += (split.length >= 2 ? _getShinyValueForItem(item1, split[1]) : 0xF);
flag1 = true;
}
if (!flag2 && item2.getRegistryName().toString().equals(split[0]))
{
val += (split.length >= 2 ? _getShinyValueForItem(item2, split[1]) : 0xF);
flag2 = true;
}
if (flag1 && flag2) break;
}
return val;
}
private static String[] _splitShinyItemString(String item)
{
return item.split("\\$");
}
private static int _getShinyValueForItem(Item item, String val)
{
try
{
return Integer.parseInt(val);
}
catch(NumberFormatException e) {};
return 0;
}
private static void _handleEffects(Player player, DarknessHandler dh)
{
float factor = dh.get_factor();
if (factor < _effLowerBound)
return;
for (; dh.effectCounter < _eff.length && factor >= _eff[dh.effectCounter].get_factor(); dh.effectCounter++)
{
DarknessEffect de = _eff[dh.effectCounter];
de.apply(player);
if (de.get_indefinite() && !dh.reappliedEffects.contains(de))
{
dh.reappliedEffects.add(de);
}
}
}
private static void _reapplyEffects(Player player, DarknessHandler dh)
{
for (DarknessEffect de : dh.reappliedEffects)
{
de.apply(player);
}
}
}

View File

@ -0,0 +1,10 @@
package dcaedll.ominousdarkness;
import net.minecraft.nbt.*;
public interface ICompoundTagSerializable
{
void serializeNBT(CompoundTag tag);
void deserializeNBT(CompoundTag tag);
}

View File

@ -0,0 +1,51 @@
package dcaedll.ominousdarkness;
import org.apache.logging.log4j.*;
import dcaedll.ominousdarkness.client.*;
import dcaedll.ominousdarkness.config.*;
import dcaedll.ominousdarkness.event.*;
import dcaedll.ominousdarkness.net.*;
import dcaedll.ominousdarkness.sound.*;
import net.minecraftforge.common.*;
import net.minecraftforge.eventbus.api.*;
import net.minecraftforge.fml.common.*;
import net.minecraftforge.fml.event.lifecycle.*;
import net.minecraftforge.fml.javafmlmod.*;
@Mod(OminousDarkness.MODID)
public class OminousDarkness
{
public static final String MODID = "ominousdarkness";
public static final Logger LOGGER = LogManager.getLogger();
static
{
ConfigHandler.init();
}
public OminousDarkness()
{
ConfigHandler.register();
IEventBus eventBus = FMLJavaModLoadingContext.get().getModEventBus();
eventBus.addListener(ConfigHandler::configLoading);
eventBus.addListener(ConfigHandler::configReloading);
eventBus.addListener(this::_setup);
eventBus.addListener(this::_clientSetup);
MinecraftForge.EVENT_BUS.register(new EventHandler());
SoundEventHandler.register(eventBus);
}
private void _setup(final FMLCommonSetupEvent event)
{
LOGGER.info("Embracing the darkness...");
PacketHandler.init();
}
private void _clientSetup(final FMLClientSetupEvent event)
{
DarknessGuiHandler.init();
}
}

View File

@ -0,0 +1,178 @@
package dcaedll.ominousdarkness.capability;
import java.util.*;
import dcaedll.ominousdarkness.*;
import dcaedll.ominousdarkness.config.*;
import dcaedll.ominousdarkness.util.*;
import net.minecraft.nbt.*;
import net.minecraft.resources.*;
public class DarknessHandler implements IDarknessEmbrace
{
public ResourceLocation dim;
public boolean isInSuitableDim;
public final List<DarknessEffect> reappliedEffects = new ArrayList<>();
public int effectCounter;
public int reTickCounter;
public int damageDelayCounter;
public int damageCounter;
public boolean dirty = true;
private float _factor;
private float _growthTime;
private float _growthTimeTicks;
private float _growthStep;
private float _falloffTime;
private float _falloffTimeTicks;
private float _falloffStep;
private float _delayValue;
private float _delay;
private float _delayTicks;
@Override
public float get_factor()
{
return _factor;
}
@Override
public void set_factor(float factor)
{
float f = _factor;
_factor = MathHelper.clamp(factor, 0.0f, 1.0f);
if (_factor != f)
dirty = true;
}
public float get_growthTime()
{
return _growthTime;
}
public void set_growthTime(float value)
{
_growthTime = MathHelper.clamp(value, 0, Float.MAX_VALUE);
_growthTimeTicks = _growthTime * 20;
_growthStep = getGrowthInTicks() > 0 ? 1 / getGrowthInTicks() : 1;
}
public float get_falloffTime()
{
return _falloffTime;
}
public void set_falloffTime(float value)
{
_falloffTime = MathHelper.clamp(value, 0, Float.MAX_VALUE);
_falloffTimeTicks = _falloffTime * 20;
_falloffStep = getFalloffInTicks() > 0 ? 1 / getFalloffInTicks() : 1;
}
public float get_delay()
{
return _delay;
}
public void set_delay(float value)
{
_delay = MathHelper.clamp(value, 0, Float.MAX_VALUE);
_delayTicks = _delay * 20;
}
public float get_delayValue()
{
return _delayValue;
}
public void set_delayValue(float value)
{
_delayValue = MathHelper.clamp(value, 0.0f, getDelayInTicks());
}
public DarknessHandler()
{
set_growthTime(ConfigHandler.getCommonCustom().growth.get().floatValue());
set_falloffTime(ConfigHandler.getCommonCustom().falloff.get().floatValue());
set_delay(ConfigHandler.getCommonCustom().delay.get().floatValue());
}
public float getGrowthInTicks()
{
return _growthTimeTicks;
}
public float getFalloffInTicks()
{
return _falloffTimeTicks;
}
public float getDelayInTicks()
{
return _delayTicks;
}
public boolean atFull()
{
return get_factor() >= 1;
}
public boolean atZero()
{
return get_factor() <= 0;
}
public boolean aboveZero()
{
return get_factor() > 0;
}
public boolean delayFinished()
{
return aboveZero() || (getDelayInTicks() > 0 ? get_delayValue() / getDelayInTicks() >= 1 : true);
}
public boolean update(boolean grow)
{
if (aboveZero())
set_delayValue(0);
if (grow)
{
if (!_tickDelay())
{
return false;
}
set_factor(get_factor() + _growthStep);
return atFull();
}
set_factor(get_factor() - _falloffStep);
return atZero();
}
@Override
public void serializeNBT(CompoundTag tag)
{
tag.putFloat("factor", get_factor());
tag.putFloat("delay", get_delayValue());
tag.putInt("damageDelayCounter", damageDelayCounter);
tag.putInt("damageCounter", damageCounter);
}
@Override
public void deserializeNBT(CompoundTag tag)
{
set_factor(tag.getFloat("factor"));
set_delayValue(tag.getFloat("delay"));
damageDelayCounter = tag.getInt("damageDelayCounter");
damageCounter = tag.getInt("damageCounter");
}
private boolean _tickDelay()
{
set_delayValue(get_delayValue() + 1);
return delayFinished();
}
}

View File

@ -0,0 +1,45 @@
package dcaedll.ominousdarkness.capability;
import javax.annotation.*;
import dcaedll.ominousdarkness.*;
import net.minecraft.core.*;
import net.minecraft.nbt.*;
import net.minecraft.resources.*;
import net.minecraftforge.common.capabilities.*;
import net.minecraftforge.common.util.*;
public class DarknessHandlerProvider implements ICapabilitySerializable<CompoundTag>
{
public static final ResourceLocation RESOURCE = new ResourceLocation(OminousDarkness.MODID, "darkness_handler");
public static final Capability<IDarknessEmbrace> CAP = CapabilityManager.get(new CapabilityToken<>() {});
private final IDarknessEmbrace _cap;
private final LazyOptional<IDarknessEmbrace> _lazyOpt;
public DarknessHandlerProvider()
{
_cap = new DarknessHandler();
_lazyOpt = LazyOptional.of(() -> _cap);
}
@Override
public @Nonnull <T> LazyOptional<T> getCapability(@Nonnull final Capability<T> cap, @Nullable final Direction side)
{
return CAP.orEmpty(cap, _lazyOpt);
}
@Override
public CompoundTag serializeNBT()
{
CompoundTag tag = new CompoundTag();
_cap.serializeNBT(tag);
return tag;
}
@Override
public void deserializeNBT(CompoundTag nbt)
{
_cap.deserializeNBT(nbt);
}
}

View File

@ -0,0 +1,10 @@
package dcaedll.ominousdarkness.capability;
import dcaedll.ominousdarkness.*;
public interface IDarknessEmbrace extends ICompoundTagSerializable
{
float get_factor();
void set_factor(float factor);
}

View File

@ -0,0 +1,69 @@
package dcaedll.ominousdarkness.client;
import org.lwjgl.opengl.*;
import com.mojang.blaze3d.systems.*;
import com.mojang.blaze3d.vertex.*;
import dcaedll.ominousdarkness.capability.*;
import dcaedll.ominousdarkness.config.*;
import net.minecraft.client.*;
import net.minecraft.client.player.*;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.texture.*;
import net.minecraft.world.level.block.*;
import net.minecraftforge.api.distmarker.*;
import net.minecraftforge.client.gui.*;
@SuppressWarnings("deprecation")
@OnlyIn(Dist.CLIENT)
public class DarknessGuiHandler
{
public static void init()
{
OverlayRegistry.registerOverlayAbove(ForgeIngameGui.VIGNETTE_ELEMENT, "darknesstakeme.vignette", DarknessGuiHandler::_renderDarknessEffect);
}
private static void _renderDarknessEffect(ForgeIngameGui gui, PoseStack poseStack, float partialTicks, int screenWidth, int screenHeight)
{
if (!ConfigHandler.getCommonCustom().showOverlay.get())
return;
Minecraft mc = Minecraft.getInstance();
LocalPlayer player = mc.player;
if (player.isCreative() || player.isSpectator())
return;
player.getCapability(DarknessHandlerProvider.CAP).ifPresent(cap ->
{
if (cap.get_factor() <= 0)
return;
RenderSystem.enableBlend();
RenderSystem.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
RenderSystem.setShaderTexture(0, TextureAtlas.LOCATION_BLOCKS);
RenderSystem.setShaderColor(0.107f, 0.083f, 0.201f, cap.get_factor() * 0.96f);
RenderSystem.setShader(GameRenderer::getPositionTexShader);
_renderPortalIcon(mc, screenWidth, screenHeight);
RenderSystem.disableBlend();
RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
});
}
private static void _renderPortalIcon(Minecraft mc, int screenWidth, int screenHeight)
{
TextureAtlasSprite portalSprite = mc.getBlockRenderer().getBlockModelShaper().getParticleIcon(Blocks.NETHER_PORTAL.defaultBlockState());
float u0 = portalSprite.getU0();
float v0 = portalSprite.getV0();
float u1 = portalSprite.getU1();
float v1 = portalSprite.getV1();
Tesselator tesselator = Tesselator.getInstance();
BufferBuilder bufferbuilder = tesselator.getBuilder();
bufferbuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX);
bufferbuilder.vertex(0.0D, (double)screenHeight, -90.0d).uv(u0, v1).endVertex();
bufferbuilder.vertex((double)screenWidth, (double)screenHeight, -90.0d).uv(u1, v1).endVertex();
bufferbuilder.vertex((double)screenWidth, 0.0D, -90.0d).uv(u1, v0).endVertex();
bufferbuilder.vertex(0.0D, 0.0D, -90.0d).uv(u0, v0).endVertex();
tesselator.end();
}
}

View File

@ -0,0 +1,40 @@
package dcaedll.ominousdarkness.client;
import dcaedll.ominousdarkness.capability.*;
import dcaedll.ominousdarkness.config.*;
import dcaedll.ominousdarkness.sound.*;
import net.minecraft.client.*;
import net.minecraft.client.multiplayer.*;
import net.minecraft.client.player.*;
import net.minecraft.sounds.*;
public class SoundPlayback
{
public static DarknessSoundInstance soundInstance;
public static final void playDarknessSoundEffects(LocalPlayer player)
{
if (player.isCreative() || player.isSpectator() || !ConfigHandler.getCommonCustom().playSoundEffect.get())
{
if (soundInstance != null) soundInstance.doStop();
return;
}
if (soundInstance == null || soundInstance.isStopped())
{
soundInstance = new DarknessSoundInstance(SoundEventHandler.DARKNESS_SOUND_EVENT.get(), SoundSource.AMBIENT);
Minecraft.getInstance().getSoundManager().play(soundInstance);
}
player.getCapability(DarknessHandlerProvider.CAP).ifPresent(cap ->
{
float factor = cap.get_factor();
soundInstance.factor = factor;
soundInstance.setPos(player.getEyePosition());
});
}
public static final void onClientLevelLoad(ClientLevel level)
{
soundInstance = null;
}
}

View File

@ -0,0 +1,182 @@
package dcaedll.ominousdarkness.config;
import java.util.*;
import net.minecraftforge.common.*;
import net.minecraftforge.common.ForgeConfigSpec.*;
public class ConfigCommon
{
public final IntValue lightLevelThreshold;
public final DoubleValue delay;
public final DoubleValue growth;
public final DoubleValue falloff;
public final BooleanValue darknessKills;
public final ConfigValue<List<? extends Object>> dimBlacklist;
public final BooleanValue dimListAsWhitelist;
public final DoubleValue damage;
public final DoubleValue damageInterval;
public final DoubleValue damageDelay;
public final BooleanValue showOverlay;
public final BooleanValue playSoundEffect;
public final DoubleValue soundEffectVolume;
public final ConfigValue<List<? extends Object>> shinyItems;
public final ConfigValue<List<? extends Object>> effects;
public ConfigCommon(ForgeConfigSpec.Builder builder)
{
builder.comment("The basic configuration for how the darkness should behave").push("darkness");
int max = 65536;
lightLevelThreshold = builder
.comment("", "The light level threshold (inclusive), at and below which the darkness will start consuming a player over time")
.defineInRange("light_level_threshold", 4, -max, max);
delay = builder
.comment("", "The time (in seconds) a player has to spend in the darkness before it starts accumulating",
"The timer gets reset once the player is in a lit enough area, and starts ticking again once in the darkness and the player's darkness level is at 0")
.defineInRange("delay", 4.0f, 0.0f, max);
growth = builder
.comment("", "The time (in seconds) it takes for the darkness to fully consume a player",
"In this context, 0 would mean that the darkness should consume the player instantly, once in an unlit area")
.defineInRange("growth_time", 10.0f, 0.0f, max);
falloff = builder
.comment("", "The time (in seconds) it takes for the darkness to fall off",
"In this context, 0 would mean that the darkness should fall off instantly, once in a lit enough area")
.defineInRange("falloff_time", 2.0f, 0.0f, max);
darknessKills = builder
.comment("", "Whether the darkness should kill a player upon fully consuming them")
.define("darkness_kills", true);
builder.comment("Any dimension-related configuration").push("dimension");
List<String> dimPath = new ArrayList<String>();
dimPath.add("dim_blacklist");
dimBlacklist = builder
.comment("", "The list of dimension registry names where the effects of the darkness should be disabled",
"e.g., \"minecraft:overworld\", \"minecraft:the_nether\", \"minecraft:the_end\"")
.defineListAllowEmpty(dimPath, () -> new ArrayList<>(), ConfigCommon::_itemIsNotBlankString);
dimListAsWhitelist = builder
.comment("", "Whether to use dimension blacklist as whitelist instead")
.define("dim_blacklist_as_whitelist", false);
builder.pop();
builder.comment("Any damage-over-time-related configuration").push("damage");
damage = builder
.comment("", "The amount of damage (in half-hearts) the darkness deals at customizable [damage_interval] intervals")
.defineInRange("damage", 0.0f, 0.0f, max);
damageInterval = builder
.comment("", "The interval (in seconds) at which the darkness damages a player",
"For example, 3 would mean that the darkness will hit the player every 3 seconds")
.defineInRange("damage_interval", 3.0f, 0.0f, max);
damageDelay = builder
.comment("", "The delay (in seconds) after which a player will start taking damage",
"This timer starts ticking once the darkness begins consuming the player")
.defineInRange("damage_delay", 0.0f, 0.0f, max);
builder.pop();
builder.comment("Miscellaneous configuration").push("misc");
showOverlay = builder
.comment("", "Whether to show the darkness overlay")
.define("show_overlay", true);
playSoundEffect = builder
.comment("", "Whether to play the darkness sound effect")
.define("play_sound_effect", true);
soundEffectVolume = builder
.comment("", "The darkness sound effect's volume")
.defineInRange("sound_effect_volume", .8f, 0.0f, 1.0f);
List<String> shinyItemsPath = new ArrayList<String>();
shinyItemsPath.add("shiny_items");
List<String> shinyItemsDef = _initVanillaShinyItems();
shinyItems = builder
.comment("", "Items that should add to the total light value when a player is holding them in either hand",
"An item should be included as follows: \"item_registry_name$N\", where N is an additive light value",
"$N can be omitted, in this case it is implied that the item has the light value of 15",
"If the player is holding two items specified in this list (one in each hand), their light values are summed",
"Stack size does not participate in calculations")
.defineListAllowEmpty(shinyItemsPath, () -> shinyItemsDef, ConfigCommon::_itemIsNotBlankString);
List<String> effectsPath = new ArrayList<String>();
effectsPath.add("effects");
List<String> effectsDef = new ArrayList<String>();
effects = builder
.comment("", "Any additional effects to apply to a player",
"An effect should be included as follows: \"effect_registry_name[duration=A][level=B][timing=C]\"",
"Duration is a number and determines the duration of the effect in seconds, defaults to infinite (for as long as the darkness level persists)",
"Level is a number and determines the power of the effect, defaults to 1",
"Timing is a number followed by either '%' or 's' (for percentage or seconds respectively) and determines the timestamp at which the effect occurs, defaults to 0s",
"Any parameters can be omitted, in this case they are set to their default values",
"Examples:",
"\"minecraft:hunger[duration=2][timing=50%]\" would apply Hunger I to a player for 2 seconds roughly halfway through (that is, if growth_time is set to 20, the effect would be applied at 10 seconds)",
"\"minecraft:slowness[timing=2.8s][level=2]\" would apply Slowness II to a player for as long as they are being consumed by the darkness, starting at 2.8 seconds",
"\"minecraft:strength\" would apply Strength I to a player right after they start gaining the darkness level, with the effect persisting for as long as their darkness level is higher than 0")
.defineListAllowEmpty(effectsPath, () -> effectsDef, ConfigCommon::_itemIsNotBlankString);
}
private static boolean _itemIsNotBlankString(Object item)
{
return item instanceof String && !((String)item).isBlank();
}
private static ArrayList<String> _initVanillaShinyItems()
{
ArrayList<String> list = new ArrayList<String>();
String[] shiny = new String[]
{
"beacon$8",
"conduit$8",
"glowstone$8",
"jack_o_lantern$8",
"lantern$8",
"soul_lantern$5",
"sea_lantern$8",
"shroomlight$8",
"glow_berries$3",
"end_rod$7",
"torch$7",
"crying_obsidian$5",
"enchanting_table$4",
"ender_chest$4",
"glow_lichen$4",
"redstone_torch$2",
"small_amethyst_bud$1",
"medium_amethyst_bud$1",
"large_amethyst_bud$2",
"amethyst_cluster$3",
"magma_block$2",
"brewing_stand$1",
"brown_mushroom$1",
"dragon_egg$1",
"end_portal_frame$1",
"light$8",
"ender_pearl$1",
"ender_eye$1",
"experience_bottle$1",
"redstone$1",
"lava_bucket$8",
"spectral_arrow$3",
"enchanted_golden_apple$3",
"glow_ink_sac$2",
"amethyst_shard$1",
"nether_star$8",
"glistering_melon_slice$2",
"glowstone_dust$4",
"blaze_powder$1",
"blaze_rod$1",
"magma_cream$1",
};
for (int i = 0; i < shiny.length; i++)
{
list.add("minecraft:".concat(shiny[i]));
}
return list;
}
}

View File

@ -0,0 +1,42 @@
package dcaedll.ominousdarkness.config;
import java.util.*;
import org.apache.commons.lang3.tuple.*;
import dcaedll.ominousdarkness.*;
import net.minecraftforge.common.*;
import net.minecraftforge.fml.*;
import net.minecraftforge.fml.config.*;
import net.minecraftforge.fml.event.config.*;
public class ConfigHandler
{
public static final List<Pair<?, ForgeConfigSpec>> configList = new ArrayList<>();
public static Pair<ConfigCommon, ForgeConfigSpec> common;
public static void init()
{
configList.add(common = new ForgeConfigSpec.Builder().configure(ConfigCommon::new));
}
public static void register()
{
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, common.getRight());
}
public static void configLoading(final ModConfigEvent.Loading event)
{
DarknessProcessor.onConfigSetUp();
}
public static void configReloading(final ModConfigEvent.Reloading event)
{
DarknessProcessor.onConfigSetUp();
}
public static ConfigCommon getCommonCustom()
{
return common.getLeft();
}
}

View File

@ -0,0 +1,62 @@
package dcaedll.ominousdarkness.event;
import dcaedll.ominousdarkness.*;
import dcaedll.ominousdarkness.capability.*;
import dcaedll.ominousdarkness.client.*;
import net.minecraft.client.multiplayer.*;
import net.minecraft.client.player.*;
import net.minecraft.server.level.*;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.player.*;
import net.minecraft.world.level.*;
import net.minecraftforge.api.distmarker.*;
import net.minecraftforge.common.capabilities.*;
import net.minecraftforge.event.*;
import net.minecraftforge.event.world.*;
import net.minecraftforge.eventbus.api.*;
import net.minecraftforge.fml.*;
public class EventHandler
{
@SubscribeEvent
public void registerCapabilities(final RegisterCapabilitiesEvent event)
{
event.register(IDarknessEmbrace.class);
}
@SubscribeEvent
public void attachCapabilities(final AttachCapabilitiesEvent<Entity> event)
{
if (!(event.getObject() instanceof Player)) return;
event.addCapability(DarknessHandlerProvider.RESOURCE, new DarknessHandlerProvider());
}
@SubscribeEvent
public void playerTick(final TickEvent.PlayerTickEvent event)
{
if (event.phase == TickEvent.Phase.END && event.side == LogicalSide.SERVER && event.player instanceof ServerPlayer)
{
DarknessProcessor.tickPlayer((ServerPlayer)event.player);
}
}
@OnlyIn(Dist.CLIENT)
@SubscribeEvent
public void localPlayerTick(final TickEvent.PlayerTickEvent event)
{
if (event.phase == TickEvent.Phase.END && event.side == LogicalSide.CLIENT && event.player instanceof LocalPlayer)
{
SoundPlayback.playDarknessSoundEffects((LocalPlayer)event.player);
}
}
@OnlyIn(Dist.CLIENT)
@SubscribeEvent
public void localLevelLoad(final WorldEvent.Load event)
{
LevelAccessor level = event.getWorld();
if (level instanceof ClientLevel)
SoundPlayback.onClientLevelLoad((ClientLevel)level);
}
}

View File

@ -0,0 +1,48 @@
package dcaedll.ominousdarkness.net;
import java.util.function.*;
import dcaedll.ominousdarkness.*;
import net.minecraft.network.*;
import net.minecraftforge.api.distmarker.*;
import net.minecraftforge.fml.*;
import net.minecraftforge.network.*;
public class DarknessPacket
{
public float factor;
public DarknessPacket()
{
}
public DarknessPacket(float factor)
{
this.factor = factor;
}
public static void encode(DarknessPacket packet, FriendlyByteBuf buf)
{
buf.writeFloat(packet.factor);
}
public static DarknessPacket decode(FriendlyByteBuf buf)
{
DarknessPacket packet = new DarknessPacket();
packet.factor = buf.readFloat();
return packet;
}
public static void handle(DarknessPacket packet, Supplier<NetworkEvent.Context> ctx)
{
ctx.get().enqueueWork(() ->
{
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () ->
{
DarknessProcessor.receiveDarknessUpdate(packet.factor);
});
});
ctx.get().setPacketHandled(true);
}
}

View File

@ -0,0 +1,23 @@
package dcaedll.ominousdarkness.net;
import dcaedll.ominousdarkness.*;
import net.minecraft.resources.*;
import net.minecraftforge.network.*;
import net.minecraftforge.network.simple.*;
public class PacketHandler
{
private static int _packetId = 0;
public static final String PROTOCOL_VERSION = "1";
public static final SimpleChannel CHANNEL_INSTANCE = NetworkRegistry.newSimpleChannel(
new ResourceLocation(OminousDarkness.MODID, "main"),
() -> PROTOCOL_VERSION,
PROTOCOL_VERSION::equals,
PROTOCOL_VERSION::equals);
public static void init()
{
CHANNEL_INSTANCE.registerMessage(_packetId++, DarknessPacket.class, DarknessPacket::encode, DarknessPacket::decode, DarknessPacket::handle);
}
}

View File

@ -0,0 +1,43 @@
package dcaedll.ominousdarkness.sound;
import dcaedll.ominousdarkness.config.*;
import net.minecraft.client.resources.sounds.*;
import net.minecraft.sounds.*;
import net.minecraft.world.phys.*;
public class DarknessSoundInstance extends AbstractTickableSoundInstance
{
public float factor = 0;
public float maxVolume = ConfigHandler.getCommonCustom().soundEffectVolume.get().floatValue();
public DarknessSoundInstance(SoundEvent event, SoundSource source)
{
super(event, source);
volume = 0;
delay = 0;
looping = true;
}
@Override
public void tick()
{
volume = factor * maxVolume;
}
public void setPos(Vec3 pos)
{
x = pos.x;
y = pos.y;
z = pos.z;
}
public boolean canStartSilent()
{
return true;
}
public void doStop()
{
stop();
}
}

View File

@ -0,0 +1,23 @@
package dcaedll.ominousdarkness.sound;
import dcaedll.ominousdarkness.*;
import net.minecraft.resources.*;
import net.minecraft.sounds.*;
import net.minecraftforge.eventbus.api.*;
import net.minecraftforge.registries.*;
public class SoundEventHandler
{
public static final DeferredRegister<SoundEvent> SOUND_EVENTS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, OminousDarkness.MODID);
public static final RegistryObject<SoundEvent> DARKNESS_SOUND_EVENT = registerSoundEvent("darkness_hissing");
public static final RegistryObject<SoundEvent> registerSoundEvent(String name)
{
return SOUND_EVENTS.register(name, () -> new SoundEvent(new ResourceLocation(OminousDarkness.MODID, name)));
}
public static final void register(IEventBus eventBus)
{
SOUND_EVENTS.register(eventBus);
}
}

View File

@ -0,0 +1,17 @@
package dcaedll.ominousdarkness.util;
public class MathHelper
{
public static float clamp(float value, float min, float max)
{
if (min >= max)
return min;
if (value < min)
return min;
else if (value > max)
return max;
return value;
}
}

View File

@ -0,0 +1,28 @@
modLoader="javafml"
loaderVersion="[38,)"
license="https://raw.githubusercontent.com/dcaedll/OminousDarkness/main/LICENSE"
issueTrackerURL="https://github.com/dcaedll/OminousDarkness/issues"
[[mods]]
modId="ominousdarkness"
version="${file.jarVersion}"
displayName="Ominous Darkness"
updateJSONURL="https://raw.githubusercontent.com/dcaedll/OminousDarkness/main/update.json"
displayURL="https://github.com/dcaedll/OminousDarkness"
logoFile="ominous_darkness_logo.png"
credits="toujourspareil https://twitter.com/toujourspareil_"
authors="dcaedll"
description='''
Being in the darkness for too long is now life-threatening, as you start feeling the presence of something evil within.
This mod makes exploration and adventures a whole lot more difficult; now you're hunted by the darkness itself!
Simply being out in the darkness for too long kills you (this behavior can be changed in the config), effectively rendering your exploration capabilities limited.
Watch out and make sure to bring some light with you to dispel the darkness!
'''
[[dependencies.ominousdarkness]]
modId="forge"
mandatory=true
versionRange="[38,)"
ordering="NONE"
side="BOTH"

View File

@ -0,0 +1,4 @@
{
"death.attack.ominousdarkness.darkness": "%s fell into the darkness",
"death.attack.ominousdarkness.darkness.player": "%s fell into the darkness"
}

View File

@ -0,0 +1,8 @@
{
"darkness_hissing": {
"category": "ambient",
"sounds": [
"ominousdarkness:darkness_hissing"
]
}
}

Binary file not shown.

View File

@ -0,0 +1,6 @@
{
"pack": {
"description": "examplemod resources",
"pack_format": 9
}
}