From b8f59f5bcf893376ba8b195abff4a80e3dfb6842 Mon Sep 17 00:00:00 2001 From: LudoCrypt <60561627+LudoCrypt@users.noreply.github.com> Date: Thu, 23 Nov 2023 15:36:16 -0600 Subject: [PATCH] refactor --- gradle.properties | 2 +- .../limlib/api/LimlibRegistryHooks.java | 12 +- .../limlib/api/LimlibTravelling.java | 18 ++- .../net/ludocrypt/limlib/api/LimlibWorld.java | 13 +- .../api/effects/post/EmptyPostEffect.java | 3 +- .../limlib/api/effects/post/PostEffect.java | 14 +- .../api/effects/sky/DimensionEffects.java | 14 +- .../effects/sky/EmptyDimensionEffects.java | 3 +- .../api/effects/sky/SkyPropertiesCreator.java | 6 +- .../effects/sky/StaticDimensionEffects.java | 7 +- .../api/effects/sound/SoundEffects.java | 3 +- .../sound/distortion/DistortionEffect.java | 11 +- .../sound/distortion/DistortionFilter.java | 52 +++++-- .../distortion/StaticDistortionEffect.java | 61 +++++--- .../effects/sound/reverb/ReverbEffect.java | 10 +- .../effects/sound/reverb/ReverbFilter.java | 102 ++++++++++--- .../sound/reverb/StaticReverbEffect.java | 136 ++++++++++++------ .../limlib/api/skybox/EmptySkybox.java | 6 +- .../ludocrypt/limlib/api/skybox/Skybox.java | 9 +- .../limlib/api/skybox/TexturedSkybox.java | 4 +- .../ludocrypt/limlib/api/world/NbtGroup.java | 3 +- .../limlib/api/world/NbtPlacerUtil.java | 133 ++++++++++++----- .../chunk/AbstractNbtChunkGenerator.java | 29 ++-- .../world/chunk/LiminalChunkGenerator.java | 16 ++- .../limlib/api/world/maze/CombineMaze.java | 6 +- .../limlib/api/world/maze/DepthFirstMaze.java | 53 +++---- .../api/world/maze/DepthFirstMazeSolver.java | 6 +- .../limlib/api/world/maze/DilateMaze.java | 36 +++-- .../limlib/api/world/maze/MazeComponent.java | 97 ++++++++++++- .../world/maze/RectangularMazeGenerator.java | 49 ++++--- .../api/world/maze/RectangularMazePiece.java | 4 +- .../net/ludocrypt/limlib/impl/Limlib.java | 20 ++- .../limlib/impl/access/SoundSystemAccess.java | 3 +- .../limlib/impl/bridge/IrisBridge.java | 5 + .../impl/debug/DebugNbtChunkGenerator.java | 42 ++++-- .../limlib/impl/debug/DebugWorld.java | 23 +-- .../mixin/GeneratorTypesBootstrapMixin.java | 4 +- .../impl/debug/mixin/GeneratorTypesMixin.java | 23 +-- .../mixin/WorldPresetTagProviderMixin.java | 3 +- .../mixin/BuiltinDimensionTypesMixin.java | 7 +- .../limlib/impl/mixin/ChunkStatusMixin.java | 13 +- .../impl/mixin/DynamicRegistrySyncMixin.java | 9 +- .../limlib/impl/mixin/RegistriesAccessor.java | 3 +- .../impl/mixin/RegistryLoaderMixin.java | 60 +++++--- .../impl/mixin/ServerPlayerEntityMixin.java | 6 +- .../impl/mixin/WorldDimensionsMixin.java | 4 +- .../impl/mixin/WorldSaveStorageMixin.java | 27 ++-- .../mixin/client/BackgroundRendererMixin.java | 5 +- .../impl/mixin/client/ClientWorldMixin.java | 16 ++- .../client/DimensionVisualEffectsMixin.java | 8 +- .../impl/mixin/client/GameRendererMixin.java | 10 +- .../mixin/client/MinecraftClientMixin.java | 12 +- .../impl/mixin/client/SoundSystemMixin.java | 18 ++- .../mixin/client/WorldRendererAfterMixin.java | 14 +- .../client/WorldRendererBeforeMixin.java | 14 +- .../limlib/impl/shader/PostProcesser.java | 13 +- .../impl/shader/PostProcesserManager.java | 13 +- 57 files changed, 928 insertions(+), 365 deletions(-) diff --git a/gradle.properties b/gradle.properties index 9c518de..f85961f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,6 @@ org.gradle.jvmargs = -Xmx1G org.gradle.parallel = true -version = 9.2.1 +version = 10.0.0 maven_group = net.ludocrypt archives_base_name = limlib \ No newline at end of file diff --git a/src/main/java/net/ludocrypt/limlib/api/LimlibRegistryHooks.java b/src/main/java/net/ludocrypt/limlib/api/LimlibRegistryHooks.java index 9f591a9..099dea5 100644 --- a/src/main/java/net/ludocrypt/limlib/api/LimlibRegistryHooks.java +++ b/src/main/java/net/ludocrypt/limlib/api/LimlibRegistryHooks.java @@ -18,9 +18,11 @@ public class LimlibRegistryHooks { @Internal - public static final Map>, Set>> REGISTRY_HOOKS = Maps.newHashMap(); + public static final Map>, Set>> REGISTRY_HOOKS = Maps + .newHashMap(); @Internal - public static final Map>, Set>> REGISTRY_JSON_HOOKS = Maps.newHashMap(); + public static final Map>, Set>> REGISTRY_JSON_HOOKS = Maps + .newHashMap(); public static > void hook(RegistryKey key, LimlibRegistryHook hook) { Set> hooks = REGISTRY_HOOKS.computeIfAbsent(key, k -> Sets.newHashSet()); @@ -40,7 +42,8 @@ public interface LimlibRegistryHook { * @param registryKey The RegistryKey of the registry. * @param registry The MutableRegistry where to register. */ - void register(RegistryInfoLookup infoLookup, RegistryKey> registryKey, MutableRegistry registry); + void register(RegistryInfoLookup infoLookup, RegistryKey> registryKey, + MutableRegistry registry); } @@ -53,7 +56,8 @@ public interface LimlibJsonRegistryHook { * @param registry The MutableRegistry where to register. * @param jsonElement The jsonElement to modify before being read by a CODEC. */ - void register(RegistryInfoLookup infoLookup, RegistryKey> registryKey, RegistryOps registryOps, JsonElement jsonElement); + void register(RegistryInfoLookup infoLookup, RegistryKey> registryKey, + RegistryOps registryOps, JsonElement jsonElement); } diff --git a/src/main/java/net/ludocrypt/limlib/api/LimlibTravelling.java b/src/main/java/net/ludocrypt/limlib/api/LimlibTravelling.java index a2e8a63..031e899 100644 --- a/src/main/java/net/ludocrypt/limlib/api/LimlibTravelling.java +++ b/src/main/java/net/ludocrypt/limlib/api/LimlibTravelling.java @@ -28,10 +28,13 @@ public class LimlibTravelling { @Internal public static float travelingPitch = 1.0F; - public static E travelTo(E teleported, ServerWorld destination, TeleportTarget target, SoundEvent sound, float volume, float pitch) { + public static E travelTo(E teleported, ServerWorld destination, TeleportTarget target, + SoundEvent sound, float volume, float pitch) { + if (destination.equals(teleported.getWorld())) { BlockPos blockPos = BlockPos.create(target.position.x, target.position.y, target.position.z); + if (!World.isValid(blockPos)) { throw new UnsupportedOperationException("Position " + blockPos.toString() + " is out of this world!"); } @@ -43,10 +46,13 @@ public static E travelTo(E teleported, ServerWorld destinatio ChunkPos chunkPos = new ChunkPos(blockPos); destination.getChunkManager().addTicket(ChunkTicketType.POST_TELEPORT, chunkPos, 1, teleported.getId()); teleported.stopRiding(); + if (((ServerPlayerEntity) teleported).isSleeping()) { ((ServerPlayerEntity) teleported).wakeUp(true, true); } - ((ServerPlayerEntity) teleported).networkHandler.requestTeleport(target.position.x, target.position.y, target.position.z, f, g, Set.of()); + + ((ServerPlayerEntity) teleported).networkHandler + .requestTeleport(target.position.x, target.position.y, target.position.z, f, g, Set.of()); teleported.setHeadYaw(f); } else { @@ -56,10 +62,14 @@ public static E travelTo(E teleported, ServerWorld destinatio } teleported.setVelocity(target.velocity); - teleported.getWorld().playSound(null, teleported.getX(), teleported.getY(), teleported.getZ(), sound, SoundCategory.AMBIENT, volume, pitch); + teleported + .getWorld() + .playSound(null, teleported.getX(), teleported.getY(), teleported.getZ(), sound, SoundCategory.AMBIENT, + volume, pitch); return teleported; } else { + try { travelingSound = sound; travelingVolume = volume; @@ -70,7 +80,9 @@ public static E travelTo(E teleported, ServerWorld destinatio travelingVolume = 0.0F; travelingPitch = 0.0F; } + } + } } diff --git a/src/main/java/net/ludocrypt/limlib/api/LimlibWorld.java b/src/main/java/net/ludocrypt/limlib/api/LimlibWorld.java index ffeb341..b0b8474 100644 --- a/src/main/java/net/ludocrypt/limlib/api/LimlibWorld.java +++ b/src/main/java/net/ludocrypt/limlib/api/LimlibWorld.java @@ -16,13 +16,18 @@ public class LimlibWorld { - public static final RegistryKey> LIMLIB_WORLD_KEY = RegistryKey.ofRegistry(new Identifier("limlib", "limlib_world")); - public static final SimpleRegistry LIMLIB_WORLD = FabricRegistryBuilder.createSimple(LIMLIB_WORLD_KEY).attribute(RegistryAttribute.SYNCED).buildAndRegister(); + public static final RegistryKey> LIMLIB_WORLD_KEY = RegistryKey + .ofRegistry(new Identifier("limlib", "limlib_world")); + public static final SimpleRegistry LIMLIB_WORLD = FabricRegistryBuilder + .createSimple(LIMLIB_WORLD_KEY) + .attribute(RegistryAttribute.SYNCED) + .buildAndRegister(); private Supplier dimensionTypeSupplier; private Function dimensionOptionsSupplier; - public LimlibWorld(Supplier dimensionTypeSupplier, Function dimensionOptionsSupplier) { + public LimlibWorld(Supplier dimensionTypeSupplier, + Function dimensionOptionsSupplier) { this.dimensionTypeSupplier = Suppliers.memoize(dimensionTypeSupplier); this.dimensionOptionsSupplier = dimensionOptionsSupplier; } @@ -36,7 +41,9 @@ public Function getDimensionOptionsSupplier( } public static interface RegistryProvider { + public HolderProvider get(RegistryKey> key); + } // Load the class early so our variables are set diff --git a/src/main/java/net/ludocrypt/limlib/api/effects/post/EmptyPostEffect.java b/src/main/java/net/ludocrypt/limlib/api/effects/post/EmptyPostEffect.java index 6558a99..316c131 100644 --- a/src/main/java/net/ludocrypt/limlib/api/effects/post/EmptyPostEffect.java +++ b/src/main/java/net/ludocrypt/limlib/api/effects/post/EmptyPostEffect.java @@ -7,7 +7,8 @@ public class EmptyPostEffect extends PostEffect { - public static final Codec CODEC = RecordCodecBuilder.create((instance) -> instance.stable(new EmptyPostEffect())); + public static final Codec CODEC = RecordCodecBuilder + .create((instance) -> instance.stable(new EmptyPostEffect())); @Override public Codec getCodec() { diff --git a/src/main/java/net/ludocrypt/limlib/api/effects/post/PostEffect.java b/src/main/java/net/ludocrypt/limlib/api/effects/post/PostEffect.java index 79c7a94..f8ca14e 100644 --- a/src/main/java/net/ludocrypt/limlib/api/effects/post/PostEffect.java +++ b/src/main/java/net/ludocrypt/limlib/api/effects/post/PostEffect.java @@ -12,11 +12,15 @@ public abstract class PostEffect { - public static final RegistryKey>> POST_EFFECT_CODEC_KEY = RegistryKey.ofRegistry(new Identifier("limlib/codec/post_effect")); - public static final Registry> POST_EFFECT_CODEC = RegistriesAccessor.callRegisterSimple(POST_EFFECT_CODEC_KEY, Lifecycle.stable(), - (registry) -> StaticPostEffect.CODEC); - public static final Codec CODEC = POST_EFFECT_CODEC.getCodec().dispatchStable(PostEffect::getCodec, Function.identity()); - public static final RegistryKey> POST_EFFECT_KEY = RegistryKey.ofRegistry(new Identifier("limlib/post_effect")); + public static final RegistryKey>> POST_EFFECT_CODEC_KEY = RegistryKey + .ofRegistry(new Identifier("limlib/codec/post_effect")); + public static final Registry> POST_EFFECT_CODEC = RegistriesAccessor + .callRegisterSimple(POST_EFFECT_CODEC_KEY, Lifecycle.stable(), (registry) -> StaticPostEffect.CODEC); + public static final Codec CODEC = POST_EFFECT_CODEC + .getCodec() + .dispatchStable(PostEffect::getCodec, Function.identity()); + public static final RegistryKey> POST_EFFECT_KEY = RegistryKey + .ofRegistry(new Identifier("limlib/post_effect")); public abstract Codec getCodec(); diff --git a/src/main/java/net/ludocrypt/limlib/api/effects/sky/DimensionEffects.java b/src/main/java/net/ludocrypt/limlib/api/effects/sky/DimensionEffects.java index cf40a4f..90b3e8f 100644 --- a/src/main/java/net/ludocrypt/limlib/api/effects/sky/DimensionEffects.java +++ b/src/main/java/net/ludocrypt/limlib/api/effects/sky/DimensionEffects.java @@ -20,11 +20,15 @@ */ public abstract class DimensionEffects { - public static final RegistryKey>> DIMENSION_EFFECTS_CODEC_KEY = RegistryKey.ofRegistry(new Identifier("limlib/codec/dimension_effects")); - public static final Registry> DIMENSION_EFFECTS_CODEC = RegistriesAccessor.callRegisterSimple(DIMENSION_EFFECTS_CODEC_KEY, Lifecycle.stable(), - (registry) -> StaticDimensionEffects.CODEC); - public static final Codec CODEC = DIMENSION_EFFECTS_CODEC.getCodec().dispatchStable(DimensionEffects::getCodec, Function.identity()); - public static final RegistryKey> DIMENSION_EFFECTS_KEY = RegistryKey.ofRegistry(new Identifier("limlib/dimension_effects")); + public static final RegistryKey>> DIMENSION_EFFECTS_CODEC_KEY = RegistryKey + .ofRegistry(new Identifier("limlib/codec/dimension_effects")); + public static final Registry> DIMENSION_EFFECTS_CODEC = RegistriesAccessor + .callRegisterSimple(DIMENSION_EFFECTS_CODEC_KEY, Lifecycle.stable(), (registry) -> StaticDimensionEffects.CODEC); + public static final Codec CODEC = DIMENSION_EFFECTS_CODEC + .getCodec() + .dispatchStable(DimensionEffects::getCodec, Function.identity()); + public static final RegistryKey> DIMENSION_EFFECTS_KEY = RegistryKey + .ofRegistry(new Identifier("limlib/dimension_effects")); public static final AtomicReference> MIXIN_WORLD_LOOKUP = new AtomicReference>(); diff --git a/src/main/java/net/ludocrypt/limlib/api/effects/sky/EmptyDimensionEffects.java b/src/main/java/net/ludocrypt/limlib/api/effects/sky/EmptyDimensionEffects.java index 75d2a9a..2641fb7 100644 --- a/src/main/java/net/ludocrypt/limlib/api/effects/sky/EmptyDimensionEffects.java +++ b/src/main/java/net/ludocrypt/limlib/api/effects/sky/EmptyDimensionEffects.java @@ -13,7 +13,8 @@ */ public class EmptyDimensionEffects extends StaticDimensionEffects { - public static final Codec CODEC = RecordCodecBuilder.create((instance) -> instance.stable(new EmptyDimensionEffects())); + public static final Codec CODEC = RecordCodecBuilder + .create((instance) -> instance.stable(new EmptyDimensionEffects())); public EmptyDimensionEffects() { super(Optional.empty(), false, "NONE", false, false, false, 1.0F); diff --git a/src/main/java/net/ludocrypt/limlib/api/effects/sky/SkyPropertiesCreator.java b/src/main/java/net/ludocrypt/limlib/api/effects/sky/SkyPropertiesCreator.java index da93f84..dfb4590 100644 --- a/src/main/java/net/ludocrypt/limlib/api/effects/sky/SkyPropertiesCreator.java +++ b/src/main/java/net/ludocrypt/limlib/api/effects/sky/SkyPropertiesCreator.java @@ -9,8 +9,10 @@ @ClientOnly public class SkyPropertiesCreator { - public static DimensionVisualEffects create(float cloudHeight, boolean alternateSkyColor, String skyType, boolean brightenLighting, boolean darkened, boolean thickFog) { - return new DimensionVisualEffects(cloudHeight, alternateSkyColor, SkyType.valueOf(skyType), brightenLighting, darkened) { + public static DimensionVisualEffects create(float cloudHeight, boolean alternateSkyColor, String skyType, + boolean brightenLighting, boolean darkened, boolean thickFog) { + return new DimensionVisualEffects(cloudHeight, alternateSkyColor, SkyType.valueOf(skyType), brightenLighting, + darkened) { @Override public Vec3d adjustFogColor(Vec3d color, float sunHeight) { diff --git a/src/main/java/net/ludocrypt/limlib/api/effects/sky/StaticDimensionEffects.java b/src/main/java/net/ludocrypt/limlib/api/effects/sky/StaticDimensionEffects.java index 6841ff4..15d1b88 100644 --- a/src/main/java/net/ludocrypt/limlib/api/effects/sky/StaticDimensionEffects.java +++ b/src/main/java/net/ludocrypt/limlib/api/effects/sky/StaticDimensionEffects.java @@ -43,7 +43,8 @@ public class StaticDimensionEffects extends DimensionEffects { private final boolean thickFog; private final float skyShading; - public StaticDimensionEffects(Optional cloudHeight, boolean alternateSkyColor, String skyType, boolean brightenLighting, boolean darkened, boolean thickFog, float skyShading) { + public StaticDimensionEffects(Optional cloudHeight, boolean alternateSkyColor, String skyType, + boolean brightenLighting, boolean darkened, boolean thickFog, float skyShading) { this.cloudHeight = cloudHeight; this.alternateSkyColor = alternateSkyColor; this.skyType = skyType; @@ -84,7 +85,9 @@ public boolean hasThickFog() { @Override @ClientOnly public DimensionVisualEffects getDimensionEffects() { - return SkyPropertiesCreator.create(getCloudHeight(), hasAlternateSkyColor(), getSkyType(), shouldBrightenLighting(), isDarkened(), hasThickFog()); + return SkyPropertiesCreator + .create(getCloudHeight(), hasAlternateSkyColor(), getSkyType(), shouldBrightenLighting(), isDarkened(), + hasThickFog()); } @Override diff --git a/src/main/java/net/ludocrypt/limlib/api/effects/sound/SoundEffects.java b/src/main/java/net/ludocrypt/limlib/api/effects/sound/SoundEffects.java index a184bed..43e22cf 100644 --- a/src/main/java/net/ludocrypt/limlib/api/effects/sound/SoundEffects.java +++ b/src/main/java/net/ludocrypt/limlib/api/effects/sound/SoundEffects.java @@ -14,7 +14,8 @@ public class SoundEffects { - public static final RegistryKey> SOUND_EFFECTS_KEY = RegistryKey.ofRegistry(new Identifier("limlib/sound_effects")); + public static final RegistryKey> SOUND_EFFECTS_KEY = RegistryKey + .ofRegistry(new Identifier("limlib/sound_effects")); public static final Codec CODEC = RecordCodecBuilder.create((instance) -> { return instance.group(ReverbEffect.CODEC.optionalFieldOf("reverb").stable().forGetter((soundEffects) -> { diff --git a/src/main/java/net/ludocrypt/limlib/api/effects/sound/distortion/DistortionEffect.java b/src/main/java/net/ludocrypt/limlib/api/effects/sound/distortion/DistortionEffect.java index 3a2de67..6296a2b 100644 --- a/src/main/java/net/ludocrypt/limlib/api/effects/sound/distortion/DistortionEffect.java +++ b/src/main/java/net/ludocrypt/limlib/api/effects/sound/distortion/DistortionEffect.java @@ -17,10 +17,13 @@ */ public abstract class DistortionEffect { - public static final RegistryKey>> DISTORTION_EFFECT_CODEC_KEY = RegistryKey.ofRegistry(new Identifier("limlib/codec/distortion_effect")); - public static final Registry> DISTORTION_EFFECT_CODEC = RegistriesAccessor.callRegisterSimple(DISTORTION_EFFECT_CODEC_KEY, Lifecycle.stable(), - (registry) -> StaticDistortionEffect.CODEC); - public static final Codec CODEC = DISTORTION_EFFECT_CODEC.getCodec().dispatchStable(DistortionEffect::getCodec, Function.identity()); + public static final RegistryKey>> DISTORTION_EFFECT_CODEC_KEY = RegistryKey + .ofRegistry(new Identifier("limlib/codec/distortion_effect")); + public static final Registry> DISTORTION_EFFECT_CODEC = RegistriesAccessor + .callRegisterSimple(DISTORTION_EFFECT_CODEC_KEY, Lifecycle.stable(), (registry) -> StaticDistortionEffect.CODEC); + public static final Codec CODEC = DISTORTION_EFFECT_CODEC + .getCodec() + .dispatchStable(DistortionEffect::getCodec, Function.identity()); public abstract Codec getCodec(); diff --git a/src/main/java/net/ludocrypt/limlib/api/effects/sound/distortion/DistortionFilter.java b/src/main/java/net/ludocrypt/limlib/api/effects/sound/distortion/DistortionFilter.java index 701b5a0..5802a5d 100644 --- a/src/main/java/net/ludocrypt/limlib/api/effects/sound/distortion/DistortionFilter.java +++ b/src/main/java/net/ludocrypt/limlib/api/effects/sound/distortion/DistortionFilter.java @@ -29,6 +29,7 @@ public static void update() { } public static boolean update(SoundInstance soundInstance, DistortionEffect data) { + if (id == -1 || slot == -1) { update(); } @@ -38,18 +39,37 @@ public static boolean update(SoundInstance soundInstance, DistortionEffect data) if (data.isEnabled(client, soundInstance)) { EXTEfx.alAuxiliaryEffectSlotf(slot, EXTEfx.AL_EFFECTSLOT_GAIN, 0); EXTEfx.alEffecti(id, EXTEfx.AL_EFFECT_TYPE, EXTEfx.AL_EFFECT_DISTORTION); - EXTEfx.alEffectf(id, EXTEfx.AL_DISTORTION_EDGE, MathHelper.clamp(data.getEdge(client, soundInstance), EXTEfx.AL_DISTORTION_MIN_EDGE, EXTEfx.AL_DISTORTION_MAX_EDGE)); - EXTEfx.alEffectf(id, EXTEfx.AL_DISTORTION_GAIN, MathHelper.clamp(data.getGain(client, soundInstance), EXTEfx.AL_DISTORTION_MIN_GAIN, EXTEfx.AL_DISTORTION_MAX_GAIN)); - EXTEfx.alEffectf(id, EXTEfx.AL_DISTORTION_LOWPASS_CUTOFF, - MathHelper.clamp(data.getLowpassCutoff(client, soundInstance), EXTEfx.AL_DISTORTION_MIN_LOWPASS_CUTOFF, EXTEfx.AL_DISTORTION_MAX_LOWPASS_CUTOFF)); - EXTEfx.alEffectf(id, EXTEfx.AL_DISTORTION_EQCENTER, MathHelper.clamp(data.getEQCenter(client, soundInstance), EXTEfx.AL_DISTORTION_MIN_EQCENTER, EXTEfx.AL_DISTORTION_MAX_EQCENTER)); - EXTEfx.alEffectf(id, EXTEfx.AL_DISTORTION_EQBANDWIDTH, - MathHelper.clamp(data.getEQBandWidth(client, soundInstance), EXTEfx.AL_DISTORTION_MIN_EQBANDWIDTH, EXTEfx.AL_DISTORTION_MAX_EQBANDWIDTH)); + EXTEfx + .alEffectf(id, EXTEfx.AL_DISTORTION_EDGE, + MathHelper + .clamp(data.getEdge(client, soundInstance), EXTEfx.AL_DISTORTION_MIN_EDGE, + EXTEfx.AL_DISTORTION_MAX_EDGE)); + EXTEfx + .alEffectf(id, EXTEfx.AL_DISTORTION_GAIN, + MathHelper + .clamp(data.getGain(client, soundInstance), EXTEfx.AL_DISTORTION_MIN_GAIN, + EXTEfx.AL_DISTORTION_MAX_GAIN)); + EXTEfx + .alEffectf(id, EXTEfx.AL_DISTORTION_LOWPASS_CUTOFF, + MathHelper + .clamp(data.getLowpassCutoff(client, soundInstance), EXTEfx.AL_DISTORTION_MIN_LOWPASS_CUTOFF, + EXTEfx.AL_DISTORTION_MAX_LOWPASS_CUTOFF)); + EXTEfx + .alEffectf(id, EXTEfx.AL_DISTORTION_EQCENTER, + MathHelper + .clamp(data.getEQCenter(client, soundInstance), EXTEfx.AL_DISTORTION_MIN_EQCENTER, + EXTEfx.AL_DISTORTION_MAX_EQCENTER)); + EXTEfx + .alEffectf(id, EXTEfx.AL_DISTORTION_EQBANDWIDTH, + MathHelper + .clamp(data.getEQBandWidth(client, soundInstance), EXTEfx.AL_DISTORTION_MIN_EQBANDWIDTH, + EXTEfx.AL_DISTORTION_MAX_EQBANDWIDTH)); EXTEfx.alAuxiliaryEffectSloti(slot, EXTEfx.AL_EFFECTSLOT_EFFECT, id); EXTEfx.alAuxiliaryEffectSlotf(slot, EXTEfx.AL_EFFECTSLOT_GAIN, 1); return true; } + return false; } @@ -57,26 +77,40 @@ public static void update(SoundInstance soundInstance, int sourceID) { MinecraftClient client = MinecraftClient.getInstance(); if (!(client == null || client.world == null)) { - Optional soundEffects = LookupGrabber.snatch(client.world.getRegistryManager().getLookup(SoundEffects.SOUND_EFFECTS_KEY).get(), + Optional soundEffects = LookupGrabber + .snatch(client.world.getRegistryManager().getLookup(SoundEffects.SOUND_EFFECTS_KEY).get(), RegistryKey.of(SoundEffects.SOUND_EFFECTS_KEY, client.world.getRegistryKey().getValue())); + if (soundEffects.isPresent()) { Optional distortion = soundEffects.get().getDistortion(); + if (distortion.isPresent()) { + if (!distortion.get().shouldIgnore(soundInstance.getId())) { + for (int i = 0; i < 2; i++) { AL11.alSourcei(sourceID, EXTEfx.AL_DIRECT_FILTER, 0); - AL11.alSource3i(sourceID, EXTEfx.AL_AUXILIARY_SEND_FILTER, update(soundInstance, distortion.get()) ? slot : 0, 0, 0); + AL11 + .alSource3i(sourceID, EXTEfx.AL_AUXILIARY_SEND_FILTER, + update(soundInstance, distortion.get()) ? slot : 0, 0, 0); int error = AL11.alGetError(); + if (error == AL11.AL_NO_ERROR) { break; } else { LOGGER.warn("OpenAl Error {}", error); } + } + } + } + } + } + } } diff --git a/src/main/java/net/ludocrypt/limlib/api/effects/sound/distortion/StaticDistortionEffect.java b/src/main/java/net/ludocrypt/limlib/api/effects/sound/distortion/StaticDistortionEffect.java index ba9b9c9..379de80 100644 --- a/src/main/java/net/ludocrypt/limlib/api/effects/sound/distortion/StaticDistortionEffect.java +++ b/src/main/java/net/ludocrypt/limlib/api/effects/sound/distortion/StaticDistortionEffect.java @@ -20,22 +20,42 @@ public class StaticDistortionEffect extends DistortionEffect { public static final Codec CODEC = RecordCodecBuilder.create((instance) -> { return instance.group(Codec.BOOL.optionalFieldOf("enabled", true).stable().forGetter((distortion) -> { return distortion.enabled; - }), Codec.floatRange(EXTEfx.AL_DISTORTION_MIN_EDGE, EXTEfx.AL_DISTORTION_MAX_EDGE).optionalFieldOf("edge", EXTEfx.AL_DISTORTION_DEFAULT_EDGE).stable().forGetter((distortion) -> { - return distortion.edge; - }), Codec.floatRange(EXTEfx.AL_DISTORTION_MIN_GAIN, EXTEfx.AL_DISTORTION_MAX_GAIN).optionalFieldOf("gain", EXTEfx.AL_DISTORTION_DEFAULT_GAIN).stable().forGetter((distortion) -> { - return distortion.gain; - }), Codec.floatRange(EXTEfx.AL_DISTORTION_MIN_LOWPASS_CUTOFF, EXTEfx.AL_DISTORTION_MAX_LOWPASS_CUTOFF).optionalFieldOf("lowpass_cutoff", EXTEfx.AL_DISTORTION_DEFAULT_LOWPASS_CUTOFF).stable() + }), Codec + .floatRange(EXTEfx.AL_DISTORTION_MIN_EDGE, EXTEfx.AL_DISTORTION_MAX_EDGE) + .optionalFieldOf("edge", EXTEfx.AL_DISTORTION_DEFAULT_EDGE) + .stable() + .forGetter((distortion) -> { + return distortion.edge; + }), + Codec + .floatRange(EXTEfx.AL_DISTORTION_MIN_GAIN, EXTEfx.AL_DISTORTION_MAX_GAIN) + .optionalFieldOf("gain", EXTEfx.AL_DISTORTION_DEFAULT_GAIN) + .stable() + .forGetter((distortion) -> { + return distortion.gain; + }), + Codec + .floatRange(EXTEfx.AL_DISTORTION_MIN_LOWPASS_CUTOFF, EXTEfx.AL_DISTORTION_MAX_LOWPASS_CUTOFF) + .optionalFieldOf("lowpass_cutoff", EXTEfx.AL_DISTORTION_DEFAULT_LOWPASS_CUTOFF) + .stable() .forGetter((distortion) -> { return distortion.lowpassCutoff; - }), Codec.floatRange(EXTEfx.AL_DISTORTION_MIN_EQCENTER, EXTEfx.AL_DISTORTION_MAX_EQCENTER).optionalFieldOf("eq_center", EXTEfx.AL_DISTORTION_DEFAULT_EQCENTER).stable() - .forGetter((distortion) -> { - return distortion.eqCenter; - }), - Codec.floatRange(EXTEfx.AL_DISTORTION_MIN_EQBANDWIDTH, EXTEfx.AL_DISTORTION_MAX_EQBANDWIDTH).optionalFieldOf("eq_band_width", EXTEfx.AL_DISTORTION_DEFAULT_EQBANDWIDTH).stable() - .forGetter((distortion) -> { - return distortion.eqBandWidth; - })) - .apply(instance, instance.stable(StaticDistortionEffect::new)); + }), + Codec + .floatRange(EXTEfx.AL_DISTORTION_MIN_EQCENTER, EXTEfx.AL_DISTORTION_MAX_EQCENTER) + .optionalFieldOf("eq_center", EXTEfx.AL_DISTORTION_DEFAULT_EQCENTER) + .stable() + .forGetter((distortion) -> { + return distortion.eqCenter; + }), + Codec + .floatRange(EXTEfx.AL_DISTORTION_MIN_EQBANDWIDTH, EXTEfx.AL_DISTORTION_MAX_EQBANDWIDTH) + .optionalFieldOf("eq_band_width", EXTEfx.AL_DISTORTION_DEFAULT_EQBANDWIDTH) + .stable() + .forGetter((distortion) -> { + return distortion.eqBandWidth; + })) + .apply(instance, instance.stable(StaticDistortionEffect::new)); }); private final boolean enabled; @@ -45,7 +65,8 @@ public class StaticDistortionEffect extends DistortionEffect { private final float eqCenter; private final float eqBandWidth; - public StaticDistortionEffect(boolean enabled, float edge, float gain, float lowpassCutoff, float eqCenter, float eqBandWidth) { + public StaticDistortionEffect(boolean enabled, float edge, float gain, float lowpassCutoff, float eqCenter, + float eqBandWidth) { this.enabled = enabled; this.edge = edge; this.gain = gain; @@ -61,8 +82,11 @@ public Codec getCodec() { @Override public boolean shouldIgnore(Identifier identifier) { - return identifier.getPath().contains("ui.") || identifier.getPath().contains("music.") || identifier.getPath().contains("block.lava.pop") || identifier.getPath().contains("weather.") - || identifier.getPath().startsWith("atmosfera") || identifier.getPath().startsWith("dynmus"); + return identifier.getPath().contains("ui.") || identifier.getPath().contains("music.") || identifier + .getPath() + .contains("block.lava.pop") || identifier.getPath().contains("weather.") || identifier + .getPath() + .startsWith("atmosfera") || identifier.getPath().startsWith("dynmus"); } @Override @@ -135,7 +159,8 @@ public Builder setEqBandWidth(float eqBandWidth) { } public StaticDistortionEffect build() { - return new StaticDistortionEffect(this.enabled, this.edge, this.gain, this.lowpassCutoff, this.eqCenter, this.eqBandWidth); + return new StaticDistortionEffect(this.enabled, this.edge, this.gain, this.lowpassCutoff, this.eqCenter, + this.eqBandWidth); } } diff --git a/src/main/java/net/ludocrypt/limlib/api/effects/sound/reverb/ReverbEffect.java b/src/main/java/net/ludocrypt/limlib/api/effects/sound/reverb/ReverbEffect.java index 9a03fd6..25daa1f 100644 --- a/src/main/java/net/ludocrypt/limlib/api/effects/sound/reverb/ReverbEffect.java +++ b/src/main/java/net/ludocrypt/limlib/api/effects/sound/reverb/ReverbEffect.java @@ -17,9 +17,13 @@ */ public abstract class ReverbEffect { - public static final RegistryKey>> REVERB_EFFECT_CODEC_KEY = RegistryKey.ofRegistry(new Identifier("limlib/codec/reverb_effect")); - public static final Registry> REVERB_EFFECT_CODEC = RegistriesAccessor.callRegisterSimple(REVERB_EFFECT_CODEC_KEY, Lifecycle.stable(), (registry) -> StaticReverbEffect.CODEC); - public static final Codec CODEC = REVERB_EFFECT_CODEC.getCodec().dispatchStable(ReverbEffect::getCodec, Function.identity()); + public static final RegistryKey>> REVERB_EFFECT_CODEC_KEY = RegistryKey + .ofRegistry(new Identifier("limlib/codec/reverb_effect")); + public static final Registry> REVERB_EFFECT_CODEC = RegistriesAccessor + .callRegisterSimple(REVERB_EFFECT_CODEC_KEY, Lifecycle.stable(), (registry) -> StaticReverbEffect.CODEC); + public static final Codec CODEC = REVERB_EFFECT_CODEC + .getCodec() + .dispatchStable(ReverbEffect::getCodec, Function.identity()); public abstract Codec getCodec(); diff --git a/src/main/java/net/ludocrypt/limlib/api/effects/sound/reverb/ReverbFilter.java b/src/main/java/net/ludocrypt/limlib/api/effects/sound/reverb/ReverbFilter.java index 961a5a1..f3038cb 100644 --- a/src/main/java/net/ludocrypt/limlib/api/effects/sound/reverb/ReverbFilter.java +++ b/src/main/java/net/ludocrypt/limlib/api/effects/sound/reverb/ReverbFilter.java @@ -29,6 +29,7 @@ public static void update() { } public static boolean update(SoundInstance soundInstance, ReverbEffect data) { + if (id == -1 || slot == -1) { update(); } @@ -38,31 +39,76 @@ public static boolean update(SoundInstance soundInstance, ReverbEffect data) { if (data.isEnabled(client, soundInstance)) { EXTEfx.alAuxiliaryEffectSlotf(slot, EXTEfx.AL_EFFECTSLOT_GAIN, 0); EXTEfx.alEffecti(id, EXTEfx.AL_EFFECT_TYPE, EXTEfx.AL_EFFECT_REVERB); - EXTEfx.alEffectf(id, EXTEfx.AL_REVERB_DENSITY, MathHelper.clamp(data.getDensity(client, soundInstance), EXTEfx.AL_REVERB_MIN_DENSITY, EXTEfx.AL_REVERB_MAX_DENSITY)); - EXTEfx.alEffectf(id, EXTEfx.AL_REVERB_DIFFUSION, MathHelper.clamp(data.getDiffusion(client, soundInstance), EXTEfx.AL_REVERB_MIN_DIFFUSION, EXTEfx.AL_REVERB_MAX_DIFFUSION)); - EXTEfx.alEffectf(id, EXTEfx.AL_REVERB_GAIN, MathHelper.clamp(data.getGain(client, soundInstance), EXTEfx.AL_REVERB_MIN_GAIN, EXTEfx.AL_REVERB_MAX_GAIN)); - EXTEfx.alEffectf(id, EXTEfx.AL_REVERB_GAINHF, MathHelper.clamp(data.getGainHF(client, soundInstance), EXTEfx.AL_REVERB_MIN_GAINHF, EXTEfx.AL_REVERB_MAX_GAINHF)); - EXTEfx.alEffectf(id, EXTEfx.AL_REVERB_DECAY_TIME, MathHelper.clamp(data.getDecayTime(client, soundInstance), EXTEfx.AL_REVERB_MIN_DECAY_TIME, EXTEfx.AL_REVERB_MAX_DECAY_TIME)); - EXTEfx.alEffectf(id, EXTEfx.AL_REVERB_DECAY_HFRATIO, MathHelper.clamp(data.getDecayHFRatio(client, soundInstance), EXTEfx.AL_REVERB_MIN_DECAY_HFRATIO, EXTEfx.AL_REVERB_MAX_DECAY_HFRATIO)); - EXTEfx.alEffectf(id, EXTEfx.AL_REVERB_REFLECTIONS_GAIN, - MathHelper.clamp(data.getReflectionsGainBase(client, soundInstance), EXTEfx.AL_REVERB_MIN_REFLECTIONS_GAIN, EXTEfx.AL_REVERB_MAX_REFLECTIONS_GAIN)); - EXTEfx.alEffectf(id, EXTEfx.AL_REVERB_REFLECTIONS_DELAY, - MathHelper.clamp(data.getReflectionsDelay(client, soundInstance), EXTEfx.AL_REVERB_MIN_REFLECTIONS_DELAY, EXTEfx.AL_REVERB_MAX_REFLECTIONS_DELAY)); - EXTEfx.alEffectf(id, EXTEfx.AL_REVERB_LATE_REVERB_GAIN, - MathHelper.clamp(data.getLateReverbGainBase(client, soundInstance), EXTEfx.AL_REVERB_MIN_LATE_REVERB_GAIN, EXTEfx.AL_REVERB_MAX_LATE_REVERB_GAIN)); - EXTEfx.alEffectf(id, EXTEfx.AL_REVERB_LATE_REVERB_DELAY, - MathHelper.clamp(data.getLateReverbDelay(client, soundInstance), EXTEfx.AL_REVERB_MIN_LATE_REVERB_DELAY, EXTEfx.AL_REVERB_MAX_LATE_REVERB_DELAY)); - EXTEfx.alEffectf(id, EXTEfx.AL_REVERB_AIR_ABSORPTION_GAINHF, - MathHelper.clamp(data.getAirAbsorptionGainHF(client, soundInstance), EXTEfx.AL_REVERB_MIN_AIR_ABSORPTION_GAINHF, EXTEfx.AL_REVERB_MAX_AIR_ABSORPTION_GAINHF)); - EXTEfx.alEffectf(id, EXTEfx.AL_REVERB_ROOM_ROLLOFF_FACTOR, - MathHelper.clamp(soundInstance.getAttenuationType() == SoundInstance.AttenuationType.LINEAR ? 2.0F / (Math.max(soundInstance.getVolume(), 1.0F) + 2.0F) : 0.0F, + EXTEfx + .alEffectf(id, EXTEfx.AL_REVERB_DENSITY, + MathHelper + .clamp(data.getDensity(client, soundInstance), EXTEfx.AL_REVERB_MIN_DENSITY, + EXTEfx.AL_REVERB_MAX_DENSITY)); + EXTEfx + .alEffectf(id, EXTEfx.AL_REVERB_DIFFUSION, + MathHelper + .clamp(data.getDiffusion(client, soundInstance), EXTEfx.AL_REVERB_MIN_DIFFUSION, + EXTEfx.AL_REVERB_MAX_DIFFUSION)); + EXTEfx + .alEffectf(id, EXTEfx.AL_REVERB_GAIN, MathHelper + .clamp(data.getGain(client, soundInstance), EXTEfx.AL_REVERB_MIN_GAIN, EXTEfx.AL_REVERB_MAX_GAIN)); + EXTEfx + .alEffectf(id, EXTEfx.AL_REVERB_GAINHF, MathHelper + .clamp(data.getGainHF(client, soundInstance), EXTEfx.AL_REVERB_MIN_GAINHF, EXTEfx.AL_REVERB_MAX_GAINHF)); + EXTEfx + .alEffectf(id, EXTEfx.AL_REVERB_DECAY_TIME, + MathHelper + .clamp(data.getDecayTime(client, soundInstance), EXTEfx.AL_REVERB_MIN_DECAY_TIME, + EXTEfx.AL_REVERB_MAX_DECAY_TIME)); + EXTEfx + .alEffectf(id, EXTEfx.AL_REVERB_DECAY_HFRATIO, + MathHelper + .clamp(data.getDecayHFRatio(client, soundInstance), EXTEfx.AL_REVERB_MIN_DECAY_HFRATIO, + EXTEfx.AL_REVERB_MAX_DECAY_HFRATIO)); + EXTEfx + .alEffectf(id, EXTEfx.AL_REVERB_REFLECTIONS_GAIN, + MathHelper + .clamp(data.getReflectionsGainBase(client, soundInstance), EXTEfx.AL_REVERB_MIN_REFLECTIONS_GAIN, + EXTEfx.AL_REVERB_MAX_REFLECTIONS_GAIN)); + EXTEfx + .alEffectf(id, EXTEfx.AL_REVERB_REFLECTIONS_DELAY, + MathHelper + .clamp(data.getReflectionsDelay(client, soundInstance), EXTEfx.AL_REVERB_MIN_REFLECTIONS_DELAY, + EXTEfx.AL_REVERB_MAX_REFLECTIONS_DELAY)); + EXTEfx + .alEffectf(id, EXTEfx.AL_REVERB_LATE_REVERB_GAIN, + MathHelper + .clamp(data.getLateReverbGainBase(client, soundInstance), EXTEfx.AL_REVERB_MIN_LATE_REVERB_GAIN, + EXTEfx.AL_REVERB_MAX_LATE_REVERB_GAIN)); + EXTEfx + .alEffectf(id, EXTEfx.AL_REVERB_LATE_REVERB_DELAY, + MathHelper + .clamp(data.getLateReverbDelay(client, soundInstance), EXTEfx.AL_REVERB_MIN_LATE_REVERB_DELAY, + EXTEfx.AL_REVERB_MAX_LATE_REVERB_DELAY)); + EXTEfx + .alEffectf(id, EXTEfx.AL_REVERB_AIR_ABSORPTION_GAINHF, + MathHelper + .clamp(data.getAirAbsorptionGainHF(client, soundInstance), + EXTEfx.AL_REVERB_MIN_AIR_ABSORPTION_GAINHF, EXTEfx.AL_REVERB_MAX_AIR_ABSORPTION_GAINHF)); + EXTEfx + .alEffectf(id, EXTEfx.AL_REVERB_ROOM_ROLLOFF_FACTOR, + MathHelper + .clamp( + soundInstance.getAttenuationType() == SoundInstance.AttenuationType.LINEAR + ? 2.0F / (Math.max(soundInstance.getVolume(), 1.0F) + 2.0F) + : 0.0F, EXTEfx.AL_REVERB_MIN_ROOM_ROLLOFF_FACTOR, EXTEfx.AL_REVERB_MAX_ROOM_ROLLOFF_FACTOR)); - EXTEfx.alEffecti(id, EXTEfx.AL_REVERB_DECAY_HFLIMIT, MathHelper.clamp(data.getDecayHFLimit(client, soundInstance), EXTEfx.AL_REVERB_MIN_DECAY_HFLIMIT, EXTEfx.AL_REVERB_MAX_DECAY_HFLIMIT)); + EXTEfx + .alEffecti(id, EXTEfx.AL_REVERB_DECAY_HFLIMIT, + MathHelper + .clamp(data.getDecayHFLimit(client, soundInstance), EXTEfx.AL_REVERB_MIN_DECAY_HFLIMIT, + EXTEfx.AL_REVERB_MAX_DECAY_HFLIMIT)); EXTEfx.alAuxiliaryEffectSloti(slot, EXTEfx.AL_EFFECTSLOT_EFFECT, id); EXTEfx.alAuxiliaryEffectSlotf(slot, EXTEfx.AL_EFFECTSLOT_GAIN, 1); return true; } + return false; } @@ -70,26 +116,40 @@ public static void update(SoundInstance soundInstance, int sourceID) { MinecraftClient client = MinecraftClient.getInstance(); if (!(client == null || client.world == null)) { - Optional soundEffects = LookupGrabber.snatch(client.world.getRegistryManager().getLookup(SoundEffects.SOUND_EFFECTS_KEY).get(), + Optional soundEffects = LookupGrabber + .snatch(client.world.getRegistryManager().getLookup(SoundEffects.SOUND_EFFECTS_KEY).get(), RegistryKey.of(SoundEffects.SOUND_EFFECTS_KEY, client.world.getRegistryKey().getValue())); + if (soundEffects.isPresent()) { Optional reverb = soundEffects.get().getReverb(); + if (reverb.isPresent()) { + if (!reverb.get().shouldIgnore(soundInstance.getId())) { + for (int i = 0; i < 2; i++) { AL11.alSourcei(sourceID, EXTEfx.AL_DIRECT_FILTER, 0); - AL11.alSource3i(sourceID, EXTEfx.AL_AUXILIARY_SEND_FILTER, update(soundInstance, reverb.get()) ? slot : 0, 0, 0); + AL11 + .alSource3i(sourceID, EXTEfx.AL_AUXILIARY_SEND_FILTER, + update(soundInstance, reverb.get()) ? slot : 0, 0, 0); int error = AL11.alGetError(); + if (error == AL11.AL_NO_ERROR) { break; } else { LOGGER.warn("OpenAl Error {}", error); } + } + } + } + } + } + } } diff --git a/src/main/java/net/ludocrypt/limlib/api/effects/sound/reverb/StaticReverbEffect.java b/src/main/java/net/ludocrypt/limlib/api/effects/sound/reverb/StaticReverbEffect.java index de1a4be..32186e8 100644 --- a/src/main/java/net/ludocrypt/limlib/api/effects/sound/reverb/StaticReverbEffect.java +++ b/src/main/java/net/ludocrypt/limlib/api/effects/sound/reverb/StaticReverbEffect.java @@ -20,44 +20,91 @@ public class StaticReverbEffect extends ReverbEffect { public static final Codec CODEC = RecordCodecBuilder.create((instance) -> { return instance.group(Codec.BOOL.optionalFieldOf("enabled", true).stable().forGetter((reverb) -> { return reverb.enabled; - }), Codec.floatRange(EXTEfx.AL_REVERB_MIN_DENSITY, EXTEfx.AL_REVERB_MAX_DENSITY).optionalFieldOf("density", EXTEfx.AL_REVERB_DEFAULT_DENSITY).stable().forGetter((reverb) -> { - return reverb.density; - }), Codec.floatRange(EXTEfx.AL_REVERB_MIN_DIFFUSION, EXTEfx.AL_REVERB_MAX_DIFFUSION).optionalFieldOf("diffusion", EXTEfx.AL_REVERB_DEFAULT_DIFFUSION).stable().forGetter((reverb) -> { - return reverb.diffusion; - }), Codec.floatRange(EXTEfx.AL_REVERB_MIN_GAIN, EXTEfx.AL_REVERB_MAX_GAIN).optionalFieldOf("gain", EXTEfx.AL_REVERB_DEFAULT_GAIN).stable().forGetter((reverb) -> { - return reverb.gain; - }), Codec.floatRange(EXTEfx.AL_REVERB_MIN_GAINHF, EXTEfx.AL_REVERB_MAX_GAINHF).optionalFieldOf("gain_hf", EXTEfx.AL_REVERB_DEFAULT_GAINHF).stable().forGetter((reverb) -> { - return reverb.gainHF; - }), Codec.floatRange(EXTEfx.AL_REVERB_MIN_DECAY_TIME, EXTEfx.AL_REVERB_MAX_DECAY_TIME).optionalFieldOf("decay_time", EXTEfx.AL_REVERB_DEFAULT_DECAY_TIME).stable().forGetter((reverb) -> { - return reverb.decayTime; - }), Codec.floatRange(EXTEfx.AL_REVERB_MIN_DECAY_HFRATIO, EXTEfx.AL_REVERB_MAX_DECAY_HFRATIO).optionalFieldOf("decay_hf_ratio", EXTEfx.AL_REVERB_DEFAULT_DECAY_HFRATIO).stable() + }), Codec + .floatRange(EXTEfx.AL_REVERB_MIN_DENSITY, EXTEfx.AL_REVERB_MAX_DENSITY) + .optionalFieldOf("density", EXTEfx.AL_REVERB_DEFAULT_DENSITY) + .stable() + .forGetter((reverb) -> { + return reverb.density; + }), + Codec + .floatRange(EXTEfx.AL_REVERB_MIN_DIFFUSION, EXTEfx.AL_REVERB_MAX_DIFFUSION) + .optionalFieldOf("diffusion", EXTEfx.AL_REVERB_DEFAULT_DIFFUSION) + .stable() + .forGetter((reverb) -> { + return reverb.diffusion; + }), + Codec + .floatRange(EXTEfx.AL_REVERB_MIN_GAIN, EXTEfx.AL_REVERB_MAX_GAIN) + .optionalFieldOf("gain", EXTEfx.AL_REVERB_DEFAULT_GAIN) + .stable() + .forGetter((reverb) -> { + return reverb.gain; + }), + Codec + .floatRange(EXTEfx.AL_REVERB_MIN_GAINHF, EXTEfx.AL_REVERB_MAX_GAINHF) + .optionalFieldOf("gain_hf", EXTEfx.AL_REVERB_DEFAULT_GAINHF) + .stable() + .forGetter((reverb) -> { + return reverb.gainHF; + }), + Codec + .floatRange(EXTEfx.AL_REVERB_MIN_DECAY_TIME, EXTEfx.AL_REVERB_MAX_DECAY_TIME) + .optionalFieldOf("decay_time", EXTEfx.AL_REVERB_DEFAULT_DECAY_TIME) + .stable() + .forGetter((reverb) -> { + return reverb.decayTime; + }), + Codec + .floatRange(EXTEfx.AL_REVERB_MIN_DECAY_HFRATIO, EXTEfx.AL_REVERB_MAX_DECAY_HFRATIO) + .optionalFieldOf("decay_hf_ratio", EXTEfx.AL_REVERB_DEFAULT_DECAY_HFRATIO) + .stable() .forGetter((reverb) -> { return reverb.decayHFRatio; - }), Codec.floatRange(EXTEfx.AL_REVERB_MIN_AIR_ABSORPTION_GAINHF, EXTEfx.AL_REVERB_MAX_AIR_ABSORPTION_GAINHF) - .optionalFieldOf("air_absorption_gain_hf", EXTEfx.AL_REVERB_DEFAULT_AIR_ABSORPTION_GAINHF).stable().forGetter((reverb) -> { - return reverb.airAbsorptionGainHF; - }), - Codec.floatRange(EXTEfx.AL_REVERB_MIN_REFLECTIONS_GAIN, EXTEfx.AL_REVERB_MAX_REFLECTIONS_GAIN).optionalFieldOf("max_reflections_gain", EXTEfx.AL_REVERB_DEFAULT_REFLECTIONS_GAIN) - .stable().forGetter((reverb) -> { - return reverb.reflectionsGainBase; - }), - Codec.floatRange(EXTEfx.AL_REVERB_MIN_LATE_REVERB_GAIN, EXTEfx.AL_REVERB_MAX_LATE_REVERB_GAIN).optionalFieldOf("late_reverb_gain", EXTEfx.AL_REVERB_DEFAULT_LATE_REVERB_GAIN).stable() - .forGetter((reverb) -> { - return reverb.lateReverbGainBase; - }), - Codec.floatRange(EXTEfx.AL_REVERB_MIN_REFLECTIONS_DELAY, EXTEfx.AL_REVERB_MAX_REFLECTIONS_DELAY).optionalFieldOf("reflections_delay", EXTEfx.AL_REVERB_DEFAULT_REFLECTIONS_DELAY) - .stable().forGetter((reverb) -> { - return reverb.reflectionsDelay; - }), - Codec.floatRange(EXTEfx.AL_REVERB_MIN_LATE_REVERB_DELAY, EXTEfx.AL_REVERB_MAX_LATE_REVERB_DELAY).optionalFieldOf("late_reverb_delay", EXTEfx.AL_REVERB_DEFAULT_LATE_REVERB_DELAY) - .stable().forGetter((reverb) -> { - return reverb.lateReverbDelay; - }), - Codec.intRange(EXTEfx.AL_REVERB_MIN_DECAY_HFLIMIT, EXTEfx.AL_REVERB_MAX_DECAY_HFLIMIT).optionalFieldOf("decay_hf_limit", EXTEfx.AL_REVERB_DEFAULT_DECAY_HFLIMIT).stable() - .forGetter((reverb) -> { - return reverb.decayHFLimit; - })) - .apply(instance, instance.stable(StaticReverbEffect::new)); + }), + Codec + .floatRange(EXTEfx.AL_REVERB_MIN_AIR_ABSORPTION_GAINHF, EXTEfx.AL_REVERB_MAX_AIR_ABSORPTION_GAINHF) + .optionalFieldOf("air_absorption_gain_hf", EXTEfx.AL_REVERB_DEFAULT_AIR_ABSORPTION_GAINHF) + .stable() + .forGetter((reverb) -> { + return reverb.airAbsorptionGainHF; + }), + Codec + .floatRange(EXTEfx.AL_REVERB_MIN_REFLECTIONS_GAIN, EXTEfx.AL_REVERB_MAX_REFLECTIONS_GAIN) + .optionalFieldOf("max_reflections_gain", EXTEfx.AL_REVERB_DEFAULT_REFLECTIONS_GAIN) + .stable() + .forGetter((reverb) -> { + return reverb.reflectionsGainBase; + }), + Codec + .floatRange(EXTEfx.AL_REVERB_MIN_LATE_REVERB_GAIN, EXTEfx.AL_REVERB_MAX_LATE_REVERB_GAIN) + .optionalFieldOf("late_reverb_gain", EXTEfx.AL_REVERB_DEFAULT_LATE_REVERB_GAIN) + .stable() + .forGetter((reverb) -> { + return reverb.lateReverbGainBase; + }), + Codec + .floatRange(EXTEfx.AL_REVERB_MIN_REFLECTIONS_DELAY, EXTEfx.AL_REVERB_MAX_REFLECTIONS_DELAY) + .optionalFieldOf("reflections_delay", EXTEfx.AL_REVERB_DEFAULT_REFLECTIONS_DELAY) + .stable() + .forGetter((reverb) -> { + return reverb.reflectionsDelay; + }), + Codec + .floatRange(EXTEfx.AL_REVERB_MIN_LATE_REVERB_DELAY, EXTEfx.AL_REVERB_MAX_LATE_REVERB_DELAY) + .optionalFieldOf("late_reverb_delay", EXTEfx.AL_REVERB_DEFAULT_LATE_REVERB_DELAY) + .stable() + .forGetter((reverb) -> { + return reverb.lateReverbDelay; + }), + Codec + .intRange(EXTEfx.AL_REVERB_MIN_DECAY_HFLIMIT, EXTEfx.AL_REVERB_MAX_DECAY_HFLIMIT) + .optionalFieldOf("decay_hf_limit", EXTEfx.AL_REVERB_DEFAULT_DECAY_HFLIMIT) + .stable() + .forGetter((reverb) -> { + return reverb.decayHFLimit; + })) + .apply(instance, instance.stable(StaticReverbEffect::new)); }); private final boolean enabled; @@ -74,8 +121,9 @@ public class StaticReverbEffect extends ReverbEffect { private final float lateReverbDelay; private final int decayHFLimit; - public StaticReverbEffect(boolean enabled, float density, float diffusion, float gain, float gainHF, float decayTime, float decayHFRatio, float airAbsorptionGainHF, float reflectionsGainBase, - float lateReverbGainBase, float reflectionsDelay, float lateReverbDelay, int decayHFLimit) { + public StaticReverbEffect(boolean enabled, float density, float diffusion, float gain, float gainHF, float decayTime, + float decayHFRatio, float airAbsorptionGainHF, float reflectionsGainBase, float lateReverbGainBase, + float reflectionsDelay, float lateReverbDelay, int decayHFLimit) { this.enabled = enabled; this.density = density; this.diffusion = diffusion; @@ -98,8 +146,11 @@ public Codec getCodec() { @Override public boolean shouldIgnore(Identifier identifier) { - return identifier.getPath().contains("ui.") || identifier.getPath().contains("music.") || identifier.getPath().contains("block.lava.pop") || identifier.getPath().contains("weather.") - || identifier.getPath().startsWith("atmosfera") || identifier.getPath().startsWith("dynmus"); + return identifier.getPath().contains("ui.") || identifier.getPath().contains("music.") || identifier + .getPath() + .contains("block.lava.pop") || identifier.getPath().contains("weather.") || identifier + .getPath() + .startsWith("atmosfera") || identifier.getPath().startsWith("dynmus"); } @Override @@ -249,8 +300,9 @@ public Builder setReflectionsDelay(float reflectionsDelay) { } public StaticReverbEffect build() { - return new StaticReverbEffect(this.enabled, this.density, this.diffusion, this.gain, this.gainHF, this.decayTime, this.decayHFRatio, this.airAbsorptionGainHF, this.reflectionsGainBase, - this.lateReverbGainBase, this.reflectionsDelay, this.lateReverbDelay, this.decayHFLimit); + return new StaticReverbEffect(this.enabled, this.density, this.diffusion, this.gain, this.gainHF, this.decayTime, + this.decayHFRatio, this.airAbsorptionGainHF, this.reflectionsGainBase, this.lateReverbGainBase, + this.reflectionsDelay, this.lateReverbDelay, this.decayHFLimit); } } diff --git a/src/main/java/net/ludocrypt/limlib/api/skybox/EmptySkybox.java b/src/main/java/net/ludocrypt/limlib/api/skybox/EmptySkybox.java index c31299f..215279b 100644 --- a/src/main/java/net/ludocrypt/limlib/api/skybox/EmptySkybox.java +++ b/src/main/java/net/ludocrypt/limlib/api/skybox/EmptySkybox.java @@ -12,11 +12,13 @@ public class EmptySkybox extends Skybox { - public static final Codec CODEC = RecordCodecBuilder.create((instance) -> instance.stable(new EmptySkybox())); + public static final Codec CODEC = RecordCodecBuilder + .create((instance) -> instance.stable(new EmptySkybox())); @Override @ClientOnly - public void renderSky(WorldRenderer worldRenderer, MinecraftClient client, MatrixStack matrices, Matrix4f projectionMatrix, float tickDelta) { + public void renderSky(WorldRenderer worldRenderer, MinecraftClient client, MatrixStack matrices, + Matrix4f projectionMatrix, float tickDelta) { } @Override diff --git a/src/main/java/net/ludocrypt/limlib/api/skybox/Skybox.java b/src/main/java/net/ludocrypt/limlib/api/skybox/Skybox.java index e47ce36..1e685b8 100644 --- a/src/main/java/net/ludocrypt/limlib/api/skybox/Skybox.java +++ b/src/main/java/net/ludocrypt/limlib/api/skybox/Skybox.java @@ -18,14 +18,17 @@ public abstract class Skybox { - public static final RegistryKey>> SKYBOX_CODEC_KEY = RegistryKey.ofRegistry(new Identifier("limlib/codec/skybox")); - public static final Registry> SKYBOX_CODEC = RegistriesAccessor.callRegisterSimple(SKYBOX_CODEC_KEY, Lifecycle.stable(), (registry) -> TexturedSkybox.CODEC); + public static final RegistryKey>> SKYBOX_CODEC_KEY = RegistryKey + .ofRegistry(new Identifier("limlib/codec/skybox")); + public static final Registry> SKYBOX_CODEC = RegistriesAccessor + .callRegisterSimple(SKYBOX_CODEC_KEY, Lifecycle.stable(), (registry) -> TexturedSkybox.CODEC); public static final Codec CODEC = SKYBOX_CODEC.getCodec().dispatchStable(Skybox::getCodec, Function.identity()); public static final RegistryKey> SKYBOX_KEY = RegistryKey.ofRegistry(new Identifier("limlib/skybox")); public abstract Codec getCodec(); @ClientOnly - public abstract void renderSky(WorldRenderer worldRenderer, MinecraftClient client, MatrixStack matrices, Matrix4f projectionMatrix, float tickDelta); + public abstract void renderSky(WorldRenderer worldRenderer, MinecraftClient client, MatrixStack matrices, + Matrix4f projectionMatrix, float tickDelta); } diff --git a/src/main/java/net/ludocrypt/limlib/api/skybox/TexturedSkybox.java b/src/main/java/net/ludocrypt/limlib/api/skybox/TexturedSkybox.java index c2d9224..a3b9147 100644 --- a/src/main/java/net/ludocrypt/limlib/api/skybox/TexturedSkybox.java +++ b/src/main/java/net/ludocrypt/limlib/api/skybox/TexturedSkybox.java @@ -36,7 +36,8 @@ public TexturedSkybox(Identifier identifier) { @Override @ClientOnly - public void renderSky(WorldRenderer worldRenderer, MinecraftClient client, MatrixStack matrices, Matrix4f projectionMatrix, float tickDelta) { + public void renderSky(WorldRenderer worldRenderer, MinecraftClient client, MatrixStack matrices, + Matrix4f projectionMatrix, float tickDelta) { RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); RenderSystem.depthMask(MinecraftClient.isFabulousGraphicsOrBetter()); @@ -52,6 +53,7 @@ public void renderSky(WorldRenderer worldRenderer, MinecraftClient client, Matri for (int i = 0; i < 6; ++i) { matrices.push(); + if (i == 0) { matrices.multiply(Axis.Z_POSITIVE.rotationDegrees(180.0F)); matrices.multiply(Axis.Y_POSITIVE.rotationDegrees(180.0F)); diff --git a/src/main/java/net/ludocrypt/limlib/api/world/NbtGroup.java b/src/main/java/net/ludocrypt/limlib/api/world/NbtGroup.java index 0a332f9..a53f424 100644 --- a/src/main/java/net/ludocrypt/limlib/api/world/NbtGroup.java +++ b/src/main/java/net/ludocrypt/limlib/api/world/NbtGroup.java @@ -31,7 +31,8 @@ public NbtGroup(Identifier id, Map> groups) { } public Identifier nbtId(String group, String nbt) { - return new Identifier(this.id.getNamespace(), "structures/nbt/" + this.id.getPath() + "/" + group + "/" + nbt + ".nbt"); + return new Identifier(this.id.getNamespace(), + "structures/nbt/" + this.id.getPath() + "/" + group + "/" + nbt + ".nbt"); } public Identifier pick(String key, RandomGenerator random) { diff --git a/src/main/java/net/ludocrypt/limlib/api/world/NbtPlacerUtil.java b/src/main/java/net/ludocrypt/limlib/api/world/NbtPlacerUtil.java index 3a3694b..064b680 100644 --- a/src/main/java/net/ludocrypt/limlib/api/world/NbtPlacerUtil.java +++ b/src/main/java/net/ludocrypt/limlib/api/world/NbtPlacerUtil.java @@ -48,7 +48,8 @@ public class NbtPlacerUtil { public final int sizeZ; public final Vec3i sizeVector; - public NbtPlacerUtil(NbtCompound storedNbt, HashMap>> positions, NbtList entities, BlockPos lowestPos, int sizeX, int sizeY, int sizeZ) { + public NbtPlacerUtil(NbtCompound storedNbt, HashMap>> positions, + NbtList entities, BlockPos lowestPos, int sizeX, int sizeY, int sizeZ) { this.storedNbt = storedNbt; this.positions = positions; this.entities = entities; @@ -59,34 +60,59 @@ public NbtPlacerUtil(NbtCompound storedNbt, HashMap>> positions, NbtList entities, BlockPos lowestPos, BlockPos sizePos) { + public NbtPlacerUtil(NbtCompound storedNbt, HashMap>> positions, + NbtList entities, BlockPos lowestPos, BlockPos sizePos) { this(storedNbt, positions, entities, lowestPos, sizePos.getX(), sizePos.getY(), sizePos.getZ()); } public NbtPlacerUtil manipulate(BlockRotation rotation, BlockMirror mirror) { NbtList paletteList = storedNbt.getList("palette", 10); HashMap palette = new HashMap(paletteList.size()); - List paletteCompoundList = paletteList.stream().filter(nbtElement -> nbtElement instanceof NbtCompound).map(element -> (NbtCompound) element).toList(); + List paletteCompoundList = paletteList + .stream() + .filter(nbtElement -> nbtElement instanceof NbtCompound) + .map(element -> (NbtCompound) element) + .toList(); for (int i = 0; i < paletteCompoundList.size(); i++) { - palette.put(i, NbtHelper.toBlockState(Registries.BLOCK.asLookup(), paletteCompoundList.get(i)).rotate(rotation).mirror(mirror)); + palette + .put(i, + NbtHelper + .toBlockState(Registries.BLOCK.asLookup(), paletteCompoundList.get(i)) + .rotate(rotation) + .mirror(mirror)); } NbtList sizeList = storedNbt.getList("size", 3); - BlockPos sizeVectorRotated = NbtPlacerUtil.mirror(new BlockPos(sizeList.getInt(0), sizeList.getInt(1), sizeList.getInt(2)).rotate(rotation), mirror); - BlockPos sizeVector = new BlockPos(Math.abs(sizeVectorRotated.getX()), Math.abs(sizeVectorRotated.getY()), Math.abs(sizeVectorRotated.getZ())); + BlockPos sizeVectorRotated = NbtPlacerUtil + .mirror(new BlockPos(sizeList.getInt(0), sizeList.getInt(1), sizeList.getInt(2)).rotate(rotation), mirror); + BlockPos sizeVector = new BlockPos(Math.abs(sizeVectorRotated.getX()), Math.abs(sizeVectorRotated.getY()), + Math.abs(sizeVectorRotated.getZ())); NbtList positionsList = storedNbt.getList("blocks", 10); - HashMap>> positions = new HashMap>>(positionsList.size()); - List>>> positionsPairList = positionsList.stream().filter(nbtElement -> nbtElement instanceof NbtCompound) - .map(element -> (NbtCompound) element) - .map((nbtCompound) -> Pair.of( - NbtPlacerUtil.mirror(new BlockPos(nbtCompound.getList("pos", 3).getInt(0), nbtCompound.getList("pos", 3).getInt(1), nbtCompound.getList("pos", 3).getInt(2)).rotate(rotation), - mirror), - Pair.of(palette.get(nbtCompound.getInt("state")), nbtCompound.contains("nbt", NbtElement.COMPOUND_TYPE) ? Optional.of(nbtCompound.getCompound("nbt")) : emptyNbt()))) - .sorted(Comparator.comparing((pair) -> pair.getFirst().getX())).sorted(Comparator.comparing((pair) -> pair.getFirst().getY())) - .sorted(Comparator.comparing((pair) -> pair.getFirst().getZ())).toList(); - positionsPairList.forEach((pair) -> positions.put(pair.getFirst().subtract(positionsPairList.get(0).getFirst()), pair.getSecond())); - return new NbtPlacerUtil(storedNbt, positions, storedNbt.getList("entities", 10), transformSize(sizeVector, rotation, mirror), sizeVector); + HashMap>> positions = new HashMap>>( + positionsList.size()); + List>>> positionsPairList = positionsList + .stream() + .filter(nbtElement -> nbtElement instanceof NbtCompound) + .map(element -> (NbtCompound) element) + .map((nbtCompound) -> Pair + .of(NbtPlacerUtil + .mirror(new BlockPos(nbtCompound.getList("pos", 3).getInt(0), nbtCompound.getList("pos", 3).getInt(1), + nbtCompound.getList("pos", 3).getInt(2)).rotate(rotation), mirror), + Pair + .of(palette.get(nbtCompound.getInt("state")), + nbtCompound.contains("nbt", NbtElement.COMPOUND_TYPE) + ? Optional.of(nbtCompound.getCompound("nbt")) + : emptyNbt()))) + .sorted(Comparator.comparing((pair) -> pair.getFirst().getX())) + .sorted(Comparator.comparing((pair) -> pair.getFirst().getY())) + .sorted(Comparator.comparing((pair) -> pair.getFirst().getZ())) + .toList(); + positionsPairList + .forEach( + (pair) -> positions.put(pair.getFirst().subtract(positionsPairList.get(0).getFirst()), pair.getSecond())); + return new NbtPlacerUtil(storedNbt, positions, storedNbt.getList("entities", 10), + transformSize(sizeVector, rotation, mirror), sizeVector); } public static NbtPlacerUtil load(Identifier id, ResourceManager manager) { @@ -102,7 +128,11 @@ public static Optional loadSafe(Identifier id, ResourceManager ma NbtCompound nbt = nbtOptional.get(); NbtList paletteList = nbt.getList("palette", 10); HashMap palette = new HashMap(paletteList.size()); - List paletteCompoundList = paletteList.stream().filter(nbtElement -> nbtElement instanceof NbtCompound).map(element -> (NbtCompound) element).toList(); + List paletteCompoundList = paletteList + .stream() + .filter(nbtElement -> nbtElement instanceof NbtCompound) + .map(element -> (NbtCompound) element) + .toList(); for (int i = 0; i < paletteCompoundList.size(); i++) { palette.put(i, NbtHelper.toBlockState(Registries.BLOCK.asLookup(), paletteCompoundList.get(i))); @@ -110,17 +140,33 @@ public static Optional loadSafe(Identifier id, ResourceManager ma NbtList sizeList = nbt.getList("size", 3); BlockPos sizeVectorRotated = new BlockPos(sizeList.getInt(0), sizeList.getInt(1), sizeList.getInt(2)); - BlockPos sizeVector = new BlockPos(Math.abs(sizeVectorRotated.getX()), Math.abs(sizeVectorRotated.getY()), Math.abs(sizeVectorRotated.getZ())); + BlockPos sizeVector = new BlockPos(Math.abs(sizeVectorRotated.getX()), Math.abs(sizeVectorRotated.getY()), + Math.abs(sizeVectorRotated.getZ())); NbtList positionsList = nbt.getList("blocks", 10); - HashMap>> positions = new HashMap>>(positionsList.size()); - List>>> positionsPairList = positionsList.stream().filter(nbtElement -> nbtElement instanceof NbtCompound) - .map(element -> (NbtCompound) element) - .map((nbtCompound) -> Pair.of(new BlockPos(nbtCompound.getList("pos", 3).getInt(0), nbtCompound.getList("pos", 3).getInt(1), nbtCompound.getList("pos", 3).getInt(2)), - Pair.of(palette.get(nbtCompound.getInt("state")), nbtCompound.contains("nbt", NbtElement.COMPOUND_TYPE) ? Optional.of(nbtCompound.getCompound("nbt")) : emptyNbt()))) - .sorted(Comparator.comparing((pair) -> pair.getFirst().getX())).sorted(Comparator.comparing((pair) -> pair.getFirst().getY())) - .sorted(Comparator.comparing((pair) -> pair.getFirst().getZ())).toList(); - positionsPairList.forEach((pair) -> positions.put(pair.getFirst().subtract(positionsPairList.get(0).getFirst()), pair.getSecond())); - return Optional.of(new NbtPlacerUtil(nbt, positions, nbt.getList("entities", 10), positionsPairList.get(0).getFirst(), sizeVector)); + HashMap>> positions = new HashMap>>( + positionsList.size()); + List>>> positionsPairList = positionsList + .stream() + .filter(nbtElement -> nbtElement instanceof NbtCompound) + .map(element -> (NbtCompound) element) + .map((nbtCompound) -> Pair + .of(new BlockPos(nbtCompound.getList("pos", 3).getInt(0), nbtCompound.getList("pos", 3).getInt(1), + nbtCompound.getList("pos", 3).getInt(2)), + Pair + .of(palette.get(nbtCompound.getInt("state")), + nbtCompound.contains("nbt", NbtElement.COMPOUND_TYPE) + ? Optional.of(nbtCompound.getCompound("nbt")) + : emptyNbt()))) + .sorted(Comparator.comparing((pair) -> pair.getFirst().getX())) + .sorted(Comparator.comparing((pair) -> pair.getFirst().getY())) + .sorted(Comparator.comparing((pair) -> pair.getFirst().getZ())) + .toList(); + positionsPairList + .forEach((pair) -> positions + .put(pair.getFirst().subtract(positionsPairList.get(0).getFirst()), pair.getSecond())); + return Optional + .of(new NbtPlacerUtil(nbt, positions, nbt.getList("entities", 10), positionsPairList.get(0).getFirst(), + sizeVector)); } throw new NullPointerException(); @@ -153,11 +199,13 @@ public static NbtCompound readStructure(Resource resource) throws IOException { return nbt; } - public NbtPlacerUtil generateNbt(ChunkRegion region, BlockPos at, TriConsumer> consumer) { + public NbtPlacerUtil generateNbt(ChunkRegion region, BlockPos at, + TriConsumer> consumer) { return generateNbt(region, BlockPos.ZERO, at, at.add(this.sizeVector), consumer); } - public NbtPlacerUtil generateNbt(ChunkRegion region, Vec3i offset, BlockPos from, BlockPos to, TriConsumer> consumer) { + public NbtPlacerUtil generateNbt(ChunkRegion region, Vec3i offset, BlockPos from, BlockPos to, + TriConsumer> consumer) { for (int xi = 0; xi < Math.min(to.subtract(from).getX(), this.sizeX); xi++) { @@ -190,21 +238,26 @@ public NbtPlacerUtil spawnEntities(ChunkRegion region, BlockPos pos, BlockRotati return spawnEntities(region, BlockPos.ORIGIN, pos, pos.add(this.sizeX, this.sizeY, this.sizeZ), rotation, mirror); } - public NbtPlacerUtil spawnEntities(ChunkRegion region, BlockPos offset, BlockPos from, BlockPos to, BlockRotation rotation, BlockMirror mirror) { + public NbtPlacerUtil spawnEntities(ChunkRegion region, BlockPos offset, BlockPos from, BlockPos to, + BlockRotation rotation, BlockMirror mirror) { this.entities.forEach((nbtElement) -> spawnEntity(nbtElement, region, offset, from, to, rotation, mirror)); return this; } - public NbtPlacerUtil spawnEntity(NbtElement nbtElement, ChunkRegion region, BlockPos offset, BlockPos from, BlockPos to, BlockRotation rotation, BlockMirror mirror) { + public NbtPlacerUtil spawnEntity(NbtElement nbtElement, ChunkRegion region, BlockPos offset, BlockPos from, BlockPos to, + BlockRotation rotation, BlockMirror mirror) { NbtCompound entityCompound = (NbtCompound) nbtElement; NbtList nbtPos = entityCompound.getList("pos", 6); - Vec3d relativeLocation = mirror(rotate(new Vec3d(nbtPos.getDouble(0), nbtPos.getDouble(1), nbtPos.getDouble(2)), rotation), mirror).subtract(Vec3d.of(lowestPos)); + Vec3d relativeLocation = mirror( + rotate(new Vec3d(nbtPos.getDouble(0), nbtPos.getDouble(1), nbtPos.getDouble(2)), rotation), mirror) + .subtract(Vec3d.of(lowestPos)); Vec3d realPosition = relativeLocation.add(Vec3d.of(from.subtract(offset))); BlockPos min = offset; BlockPos max = to.subtract(from).add(offset); - if (!((relativeLocation.getX() < max.getX() && relativeLocation.getX() >= min.getX()) && (relativeLocation.getY() < max.getY() && relativeLocation.getY() >= min.getY()) - && (relativeLocation.getZ() < max.getZ() && relativeLocation.getZ() >= min.getZ()))) { + if (!((relativeLocation.getX() < max.getX() && relativeLocation.getX() >= min.getX()) && (relativeLocation + .getY() < max.getY() && relativeLocation + .getY() >= min.getY()) && (relativeLocation.getZ() < max.getZ() && relativeLocation.getZ() >= min.getZ()))) { return this; } @@ -246,9 +299,15 @@ public NbtPlacerUtil spawnEntity(NbtElement nbtElement, ChunkRegion region, Bloc entity.refreshPositionAndAngles(realPosition.x, realPosition.y, realPosition.z, yawRotation, entity.getPitch()); if (entity instanceof AbstractDecorationEntity deco) { - double newX = realPosition.getX() - (deco.getWidthPixels() % 32 == 0 ? 0.5 : 0.0) * deco.getHorizontalFacing().rotateYCounterclockwise().getOffsetX(); + double newX = realPosition.getX() - (deco.getWidthPixels() % 32 == 0 ? 0.5 : 0.0) * deco + .getHorizontalFacing() + .rotateYCounterclockwise() + .getOffsetX(); double newY = realPosition.getY() - (deco.getHeightPixels() % 32 == 0 ? 0.5 : 0.0); - double newZ = realPosition.getZ() - (deco.getWidthPixels() % 32 == 0 ? 0.5 : 0.0) * deco.getHorizontalFacing().rotateYCounterclockwise().getOffsetZ(); + double newZ = realPosition.getZ() - (deco.getWidthPixels() % 32 == 0 ? 0.5 : 0.0) * deco + .getHorizontalFacing() + .rotateYCounterclockwise() + .getOffsetZ(); newX += deco.getHorizontalFacing().getOffsetX() * 0.46875D; newZ += deco.getHorizontalFacing().getOffsetZ() * 0.46875D; newX -= 0.5; diff --git a/src/main/java/net/ludocrypt/limlib/api/world/chunk/AbstractNbtChunkGenerator.java b/src/main/java/net/ludocrypt/limlib/api/world/chunk/AbstractNbtChunkGenerator.java index 581a93a..49863f6 100644 --- a/src/main/java/net/ludocrypt/limlib/api/world/chunk/AbstractNbtChunkGenerator.java +++ b/src/main/java/net/ludocrypt/limlib/api/world/chunk/AbstractNbtChunkGenerator.java @@ -30,7 +30,8 @@ public AbstractNbtChunkGenerator(BiomeSource biomeSource, NbtGroup nbtGroup) { this(biomeSource, nbtGroup, new FunctionMap(NbtPlacerUtil::load)); } - public AbstractNbtChunkGenerator(BiomeSource biomeSource, NbtGroup nbtGroup, FunctionMap structures) { + public AbstractNbtChunkGenerator(BiomeSource biomeSource, NbtGroup nbtGroup, + FunctionMap structures) { super(biomeSource); this.nbtGroup = nbtGroup; this.structures = structures; @@ -52,8 +53,11 @@ public void generateNbt(ChunkRegion region, BlockPos at, Identifier id, BlockMir public void generateNbt(ChunkRegion region, BlockPos at, Identifier id, BlockRotation rotation, BlockMirror mirror) { try { - structures.eval(id, region.getServer().getResourceManager()).manipulate(rotation, mirror).generateNbt(region, at, (pos, state, nbt) -> this.modifyStructure(region, pos, state, nbt)) - .spawnEntities(region, at, rotation, mirror); + structures + .eval(id, region.getServer().getResourceManager()) + .manipulate(rotation, mirror) + .generateNbt(region, at, (pos, state, nbt) -> this.modifyStructure(region, pos, state, nbt)) + .spawnEntities(region, at, rotation, mirror); } catch (Exception e) { e.printStackTrace(); throw new NullPointerException("Attempted to load undefined structure \'" + id + "\'"); @@ -61,11 +65,15 @@ public void generateNbt(ChunkRegion region, BlockPos at, Identifier id, BlockRot } - public void generateNbt(ChunkRegion region, BlockPos offset, BlockPos from, BlockPos to, Identifier id, BlockRotation rotation, BlockMirror mirror) { + public void generateNbt(ChunkRegion region, BlockPos offset, BlockPos from, BlockPos to, Identifier id, + BlockRotation rotation, BlockMirror mirror) { try { - structures.eval(id, region.getServer().getResourceManager()).manipulate(rotation, mirror) - .generateNbt(region, offset, from, to, (pos, state, nbt) -> this.modifyStructure(region, pos, state, nbt)).spawnEntities(region, offset, from, to, rotation, mirror); + structures + .eval(id, region.getServer().getResourceManager()) + .manipulate(rotation, mirror) + .generateNbt(region, offset, from, to, (pos, state, nbt) -> this.modifyStructure(region, pos, state, nbt)) + .spawnEntities(region, offset, from, to, rotation, mirror); } catch (Exception e) { e.printStackTrace(); throw new NullPointerException("Attempted to load undefined structure \'" + id + "\'"); @@ -73,11 +81,13 @@ public void generateNbt(ChunkRegion region, BlockPos offset, BlockPos from, Bloc } - protected void modifyStructure(ChunkRegion region, BlockPos pos, BlockState state, Optional blockEntityNbt) { + protected void modifyStructure(ChunkRegion region, BlockPos pos, BlockState state, + Optional blockEntityNbt) { this.modifyStructure(region, pos, state, blockEntityNbt, Block.NOTIFY_ALL); } - protected void modifyStructure(ChunkRegion region, BlockPos pos, BlockState state, Optional blockEntityNbt, int update) { + protected void modifyStructure(ChunkRegion region, BlockPos pos, BlockState state, Optional blockEntityNbt, + int update) { if (!state.isAir()) { @@ -99,7 +109,8 @@ protected void modifyStructure(ChunkRegion region, BlockPos pos, BlockState stat } if (blockEntity instanceof LootableContainerBlockEntity lootTable) { - lootTable.setLootTable(this.getContainerLootTable(lootTable), region.getSeed() + LimlibHelper.blockSeed(pos)); + lootTable + .setLootTable(this.getContainerLootTable(lootTable), region.getSeed() + LimlibHelper.blockSeed(pos)); } } diff --git a/src/main/java/net/ludocrypt/limlib/api/world/chunk/LiminalChunkGenerator.java b/src/main/java/net/ludocrypt/limlib/api/world/chunk/LiminalChunkGenerator.java index 9604419..b3e93a4 100644 --- a/src/main/java/net/ludocrypt/limlib/api/world/chunk/LiminalChunkGenerator.java +++ b/src/main/java/net/ludocrypt/limlib/api/world/chunk/LiminalChunkGenerator.java @@ -38,7 +38,8 @@ public LiminalChunkGenerator(BiomeSource biomeSource) { } @Override - public void carve(ChunkRegion chunkRegion, long seed, RandomState randomState, BiomeAccess biomeAccess, StructureManager structureManager, Chunk chunk, Carver generationStep) { + public void carve(ChunkRegion chunkRegion, long seed, RandomState randomState, BiomeAccess biomeAccess, + StructureManager structureManager, Chunk chunk, Carver generationStep) { } @Override @@ -50,7 +51,8 @@ public void populateEntities(ChunkRegion region) { } @Override - public CompletableFuture populateNoise(Executor executor, Blender blender, RandomState randomState, StructureManager structureManager, Chunk chunk) { + public CompletableFuture populateNoise(Executor executor, Blender blender, RandomState randomState, + StructureManager structureManager, Chunk chunk) { throw new UnsupportedOperationException("populateNoise should never be called in LiminalChunkGenerator"); } @@ -65,9 +67,11 @@ public CompletableFuture populateNoise(Executor executor, Blender blender * ChunkRegion as opposed to world when setting blocks, as it allows you to * extend through multiple chunks in {@link getChunkDistance} away. */ - public abstract CompletableFuture populateNoise(ChunkRegion chunkRegion, ChunkStatus targetStatus, Executor executor, ServerWorld world, ChunkGenerator generator, - StructureTemplateManager structureTemplateManager, ServerLightingProvider lightingProvider, Function>> fullChunkConverter, - List chunks, Chunk chunk); + public abstract CompletableFuture populateNoise(ChunkRegion chunkRegion, ChunkStatus targetStatus, + Executor executor, ServerWorld world, ChunkGenerator generator, + StructureTemplateManager structureTemplateManager, ServerLightingProvider lightingProvider, + Function>> fullChunkConverter, List chunks, + Chunk chunk); @Override public int getSeaLevel() { @@ -87,9 +91,11 @@ public int getHeight(int x, int z, Type heightmap, HeightLimitView world, Random @Override public VerticalBlockSample getColumnSample(int x, int y, HeightLimitView world, RandomState random) { BlockState[] states = new BlockState[world.getHeight()]; + for (int i = 0; i < states.length; i++) { states[i] = Blocks.AIR.getDefaultState(); } + return new VerticalBlockSample(0, states); } diff --git a/src/main/java/net/ludocrypt/limlib/api/world/maze/CombineMaze.java b/src/main/java/net/ludocrypt/limlib/api/world/maze/CombineMaze.java index 8bc5d8b..733d74b 100644 --- a/src/main/java/net/ludocrypt/limlib/api/world/maze/CombineMaze.java +++ b/src/main/java/net/ludocrypt/limlib/api/world/maze/CombineMaze.java @@ -9,7 +9,7 @@ public CombineMaze(MazeComponent... components) { } @Override - public void generateMaze() { + public void create() { for (MazeComponent maze : components) { @@ -34,7 +34,9 @@ public void generateMaze() { this.cellState(x, y).setWest(true); } - if (this.cellState(x, y).isNorth() || this.cellState(x, y).isEast() || this.cellState(x, y).isSouth() || this.cellState(x, y).isWest()) { + if (this.cellState(x, y).isNorth() || this.cellState(x, y).isEast() || this.cellState(x, y).isSouth() || this + .cellState(x, y) + .isWest()) { this.solvedMaze.add(new Vec2i(x, y)); } diff --git a/src/main/java/net/ludocrypt/limlib/api/world/maze/DepthFirstMaze.java b/src/main/java/net/ludocrypt/limlib/api/world/maze/DepthFirstMaze.java index eabf611..2eb487f 100644 --- a/src/main/java/net/ludocrypt/limlib/api/world/maze/DepthFirstMaze.java +++ b/src/main/java/net/ludocrypt/limlib/api/world/maze/DepthFirstMaze.java @@ -19,9 +19,10 @@ public DepthFirstMaze(int width, int height, RandomGenerator RandomGenerator) { } @Override - public void generateMaze() { + public void create() { this.maze[0].visited(); this.stack.push(new Vec2i(0, 0)); + while (visitedCells < this.width * this.height) { List neighbours = Lists.newArrayList(); @@ -50,30 +51,30 @@ public void generateMaze() { int nextCellDir = neighbours.get(random.nextInt(neighbours.size())); switch (nextCellDir) { - case 0: // North - this.cellState(this.stack.peek().getX(), this.stack.peek().getY()).north(); - this.cellState(this.stack.peek().getX() + 1, this.stack.peek().getY()).south(); - this.cellState(this.stack.peek().getX() + 1, this.stack.peek().getY()).visited(); - this.stack.push(new Vec2i(this.stack.peek().getX() + 1, this.stack.peek().getY())); - break; - case 1: // East - this.cellState(this.stack.peek().getX(), this.stack.peek().getY()).east(); - this.cellState(this.stack.peek().getX(), this.stack.peek().getY() + 1).west(); - this.cellState(this.stack.peek().getX(), this.stack.peek().getY() + 1).visited(); - this.stack.push(new Vec2i(this.stack.peek().getX(), this.stack.peek().getY() + 1)); - break; - case 2: // South - this.cellState(this.stack.peek().getX(), this.stack.peek().getY()).south(); - this.cellState(this.stack.peek().getX() - 1, this.stack.peek().getY()).north(); - this.cellState(this.stack.peek().getX() - 1, this.stack.peek().getY()).visited(); - this.stack.push(new Vec2i(this.stack.peek().getX() - 1, this.stack.peek().getY())); - break; - case 3: // West - this.cellState(this.stack.peek().getX(), this.stack.peek().getY()).west(); - this.cellState(this.stack.peek().getX(), this.stack.peek().getY() - 1).east(); - this.cellState(this.stack.peek().getX(), this.stack.peek().getY() - 1).visited(); - this.stack.push(new Vec2i(this.stack.peek().getX(), this.stack.peek().getY() - 1)); - break; + case 0: // North + this.cellState(this.stack.peek().getX(), this.stack.peek().getY()).north(); + this.cellState(this.stack.peek().getX() + 1, this.stack.peek().getY()).south(); + this.cellState(this.stack.peek().getX() + 1, this.stack.peek().getY()).visited(); + this.stack.push(new Vec2i(this.stack.peek().getX() + 1, this.stack.peek().getY())); + break; + case 1: // East + this.cellState(this.stack.peek().getX(), this.stack.peek().getY()).east(); + this.cellState(this.stack.peek().getX(), this.stack.peek().getY() + 1).west(); + this.cellState(this.stack.peek().getX(), this.stack.peek().getY() + 1).visited(); + this.stack.push(new Vec2i(this.stack.peek().getX(), this.stack.peek().getY() + 1)); + break; + case 2: // South + this.cellState(this.stack.peek().getX(), this.stack.peek().getY()).south(); + this.cellState(this.stack.peek().getX() - 1, this.stack.peek().getY()).north(); + this.cellState(this.stack.peek().getX() - 1, this.stack.peek().getY()).visited(); + this.stack.push(new Vec2i(this.stack.peek().getX() - 1, this.stack.peek().getY())); + break; + case 3: // West + this.cellState(this.stack.peek().getX(), this.stack.peek().getY()).west(); + this.cellState(this.stack.peek().getX(), this.stack.peek().getY() - 1).east(); + this.cellState(this.stack.peek().getX(), this.stack.peek().getY() - 1).visited(); + this.stack.push(new Vec2i(this.stack.peek().getX(), this.stack.peek().getY() - 1)); + break; } if (!this.solvedMaze.contains(new Vec2i(this.stack.peek().getX(), this.stack.peek().getY()))) { @@ -87,7 +88,9 @@ public void generateMaze() { // Backtrack this.stack.pop(); } + } + } } diff --git a/src/main/java/net/ludocrypt/limlib/api/world/maze/DepthFirstMazeSolver.java b/src/main/java/net/ludocrypt/limlib/api/world/maze/DepthFirstMazeSolver.java index 92f8432..4995219 100644 --- a/src/main/java/net/ludocrypt/limlib/api/world/maze/DepthFirstMazeSolver.java +++ b/src/main/java/net/ludocrypt/limlib/api/world/maze/DepthFirstMazeSolver.java @@ -35,14 +35,14 @@ public DepthFirstMazeSolver(MazeComponent mazeToSolve, Vec2i start, List } @Override - public void generateMaze() { + public void create() { List> paths = Lists.newArrayList(); this.ends.forEach((end) -> { Stack stack = new Stack(); - stack.push(new Vec2i(start.getX(), start.getY())); + stack.push(new Vec2i(end.getX(), end.getY())); Vec2i peek = stack.peek(); - while (!peek.equals(end)) { + while (!peek.equals(start)) { List neighbours = Lists.newArrayList(); // North Neighbour diff --git a/src/main/java/net/ludocrypt/limlib/api/world/maze/DilateMaze.java b/src/main/java/net/ludocrypt/limlib/api/world/maze/DilateMaze.java index a02351a..45a8e63 100644 --- a/src/main/java/net/ludocrypt/limlib/api/world/maze/DilateMaze.java +++ b/src/main/java/net/ludocrypt/limlib/api/world/maze/DilateMaze.java @@ -5,32 +5,38 @@ public class DilateMaze extends MazeComponent { private MazeComponent mazeIn; - private int dilation; + private int dilationX; + private int dilationY; public DilateMaze(MazeComponent mazeIn, int dilation) { - super(mazeIn.width * dilation, mazeIn.height * dilation); + this(mazeIn, dilation, dilation); + } + + public DilateMaze(MazeComponent mazeIn, int dilationX, int dilationY) { + super(mazeIn.width * dilationX, mazeIn.height * dilationY); this.mazeIn = mazeIn; - this.dilation = dilation; + this.dilationX = dilationX; + this.dilationY = dilationY; } @Override - public void generateMaze() { + public void create() { for (int x = 0; x < mazeIn.width; x++) { for (int y = 0; y < mazeIn.height; y++) { - for (int dx = 0; dx < dilation; dx++) { + for (int dx = 0; dx < dilationX; dx++) { - for (int dy = 0; dy < dilation; dy++) { - int mazeX = x * dilation + dx; - int mazeY = y * dilation + dy; + for (int dy = 0; dy < dilationY; dy++) { + int mazeX = x * dilationX + dx; + int mazeY = y * dilationY + dy; Vec2i position = new Vec2i(mazeX, mazeY); CellState reference = mazeIn.cellState(x, y); - if (dx % dilation == 0) { + if (dx % dilationX == 0) { - if (dy % dilation == 0) { + if (dy % dilationY == 0) { CellState copy = reference.copy(); copy.setPosition(position); this.maze[mazeY * this.width + mazeX] = copy; @@ -51,7 +57,7 @@ public void generateMaze() { } else { - if (dy % dilation == 0) { + if (dy % dilationY == 0) { if (mazeIn.cellState(x, y).isNorth()) { CellState copy = new CellState(); @@ -86,8 +92,12 @@ public MazeComponent getMazeIn() { return mazeIn; } - public int getDilation() { - return dilation; + public int getDilationX() { + return dilationX; + } + + public int getDilationY() { + return dilationY; } } diff --git a/src/main/java/net/ludocrypt/limlib/api/world/maze/MazeComponent.java b/src/main/java/net/ludocrypt/limlib/api/world/maze/MazeComponent.java index 6878628..c83a8f7 100644 --- a/src/main/java/net/ludocrypt/limlib/api/world/maze/MazeComponent.java +++ b/src/main/java/net/ludocrypt/limlib/api/world/maze/MazeComponent.java @@ -6,8 +6,6 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import net.minecraft.util.math.BlockPos; - /** * Abstract maze component **/ @@ -18,6 +16,7 @@ public abstract class MazeComponent { public final CellState[] maze; public final List solvedMaze = Lists.newArrayList(); public int visitedCells = 0; + public boolean generated = false; public MazeComponent(int width, int height) { this.width = width; @@ -38,9 +37,34 @@ public MazeComponent(int width, int height) { } /** - * Generates the full maze + * Attempt to generate the maze + **/ + public void generateMaze() { + this.generateMaze(false); + } + + /** + * Attempt to generate the maze **/ - public abstract void generateMaze(); + public void generateMaze(boolean doesThrow) { + + if (generated) { + + if (doesThrow) { + throw new UnsupportedOperationException("This maze has already been created"); + } + + } else { + create(); + generated = true; + } + + } + + /** + * Create the maze + **/ + public abstract void create(); public CellState cellState(int x, int y) { return this.maze[y * this.width + x]; @@ -67,13 +91,33 @@ public boolean hasWestNeighbor(Vec2i vec) { } public boolean hasNeighbors(Vec2i vec) { - return this.hasNorthNeighbor(vec) || this.hasEastNeighbor(vec) || this.hasSouthNeighbor(vec) || this.hasWestNeighbor(vec); + return this.hasNorthNeighbor(vec) || this.hasEastNeighbor(vec) || this.hasSouthNeighbor(vec) || this + .hasWestNeighbor(vec); } public boolean fits(Vec2i vec) { return vec.getX() >= 0 && vec.getX() < this.width && vec.getY() >= 0 && vec.getY() < this.height; } + @Override + public String toString() { + + StringBuilder row = new StringBuilder(); + row.append("\n"); + + for (int x = width - 1; x >= 0; x--) { + + for (int y = 0; y < height; y++) { + row.append(cellState(x, y).toString()); + + } + + row.append("\n"); + } + + return row.toString(); + } + /** * Describes the state of a particular room or 'cell' in a maze *

@@ -185,6 +229,45 @@ public Map getExtra() { return extra; } + @Override + public String toString() { + + if (this.isWest() && this.isNorth() && this.isEast() && this.isSouth()) { + return ("┼"); + } else if (this.isWest() && this.isNorth() && this.isEast() && !this.isSouth()) { + return ("┴"); + } else if (this.isWest() && this.isNorth() && !this.isEast() && this.isSouth()) { + return ("┤"); + } else if (this.isWest() && this.isNorth() && !this.isEast() && !this.isSouth()) { + return ("┘"); + } else if (this.isWest() && !this.isNorth() && this.isEast() && this.isSouth()) { + return ("┬"); + } else if (this.isWest() && !this.isNorth() && this.isEast() && !this.isSouth()) { + return ("─"); + } else if (this.isWest() && !this.isNorth() && !this.isEast() && this.isSouth()) { + return ("┐"); + } else if (this.isWest() && !this.isNorth() && !this.isEast() && !this.isSouth()) { + return ("╴"); + } else if (!this.isWest() && this.isNorth() && this.isEast() && this.isSouth()) { + return ("├"); + } else if (!this.isWest() && this.isNorth() && this.isEast() && !this.isSouth()) { + return ("└"); + } else if (!this.isWest() && this.isNorth() && !this.isEast() && this.isSouth()) { + return ("│"); + } else if (!this.isWest() && this.isNorth() && !this.isEast() && !this.isSouth()) { + return ("╵"); + } else if (!this.isWest() && !this.isNorth() && this.isEast() && this.isSouth()) { + return ("┌"); + } else if (!this.isWest() && !this.isNorth() && this.isEast() && !this.isSouth()) { + return ("╶"); + } else if (!this.isWest() && !this.isNorth() && !this.isEast() && this.isSouth()) { + return ("╷"); + } else { + return ("░"); + } + + } + } public static class Vec2i { @@ -205,8 +288,8 @@ public int getY() { return y; } - public BlockPos toPos() { - return new BlockPos(x, y, 0); + public Vec2i add(int x, int y) { + return new Vec2i(this.x + x, this.y + y); } @Override diff --git a/src/main/java/net/ludocrypt/limlib/api/world/maze/RectangularMazeGenerator.java b/src/main/java/net/ludocrypt/limlib/api/world/maze/RectangularMazeGenerator.java index be81cf6..c14d7c3 100644 --- a/src/main/java/net/ludocrypt/limlib/api/world/maze/RectangularMazeGenerator.java +++ b/src/main/java/net/ludocrypt/limlib/api/world/maze/RectangularMazeGenerator.java @@ -4,7 +4,7 @@ import net.ludocrypt.limlib.api.world.LimlibHelper; import net.ludocrypt.limlib.api.world.maze.MazeComponent.CellState; -import net.minecraft.util.math.BlockPos; +import net.ludocrypt.limlib.api.world.maze.MazeComponent.Vec2i; import net.minecraft.util.random.RandomGenerator; /** @@ -12,11 +12,11 @@ */ public class RectangularMazeGenerator { - private final HashMap mazes = new HashMap(30); + private final HashMap mazes = new HashMap(30); public final int width; public final int height; - public final int thickness; - public final boolean redundancy; + public final int thicknessX; + public final int thicknessY; public final long seedModifier; /** @@ -25,19 +25,16 @@ public class RectangularMazeGenerator { * * @param width of the maze * @param height of the maze - * @param thickness of the walls. This helps to know where to place adjacent - * cells. - * @param redundancy makes a maze 2 blocks outwards in each direction, and - * only generates the centre part of the maze. This helps - * create the illusion of a larger structure at work. + * @param thicknessX of the cells in real world coordinates. + * @param thicknessY of the cells in real world coordinates. * @param seedModifier is the change to the seed when generating a new random * maze. In code, it uses the world seed + seedModifier */ - public RectangularMazeGenerator(int width, int height, int thickness, boolean redundancy, long seedModifier) { + public RectangularMazeGenerator(int width, int height, int thicknessX, int thicknessY, long seedModifier) { this.width = width; this.height = height; - this.thickness = thickness; - this.redundancy = redundancy; + this.thicknessX = thicknessX; + this.thicknessY = thicknessY; this.seedModifier = seedModifier; } @@ -51,29 +48,31 @@ public RectangularMazeGenerator(int width, int height, int thickness, boolean re * @param cellDecorator funcional interface to generate a single maze block, or * 'cell' */ - public void generateMaze(BlockPos pos, long seed, MazeCreator mazeCreator, CellDecorator cellDecorator) { + public void generateMaze(Vec2i pos, long seed, MazeCreator mazeCreator, CellDecorator cellDecorator) { for (int x = 0; x < 16; x++) { for (int y = 0; y < 16; y++) { - BlockPos inPos = pos.add(x, 0, y); + Vec2i inPos = pos.add(x, y); - if (Math.floorMod(inPos.getX(), thickness) == 0 && Math.floorMod(inPos.getZ(), thickness) == 0) { - BlockPos mazePos = new BlockPos(inPos.getX() - Math.floorMod(inPos.getX(), (width * thickness)), 0, inPos.getZ() - Math.floorMod(inPos.getZ(), (height * thickness))); + if (Math.floorMod(inPos.getX(), thicknessX) == 0 && Math.floorMod(inPos.getY(), thicknessY) == 0) { + Vec2i mazePos = new Vec2i(inPos.getX() - Math.floorMod(inPos.getX(), (width * thicknessX)), + inPos.getY() - Math.floorMod(inPos.getY(), (height * thicknessY))); M maze; if (this.mazes.containsKey(mazePos)) { maze = this.mazes.get(mazePos); } else { - maze = mazeCreator.newMaze(mazePos, redundancy ? width + 4 : width, redundancy ? height + 4 : height, - RandomGenerator.createLegacy(LimlibHelper.blockSeed(mazePos.getX(), mazePos.getZ(), seed + seedModifier))); + maze = mazeCreator + .newMaze(mazePos, width, height, RandomGenerator + .createLegacy(LimlibHelper.blockSeed(mazePos.getX(), mazePos.getY(), seed + seedModifier))); this.mazes.put(mazePos, maze); } - int mazeX = (inPos.getX() - mazePos.getX()) / thickness; - int mazeY = (inPos.getZ() - mazePos.getZ()) / thickness; - CellState originCell = maze.cellState(redundancy ? mazeX + 2 : mazeX, redundancy ? mazeY + 2 : mazeY); - cellDecorator.generate(inPos, mazePos, maze, originCell, this.thickness); + int mazeX = (inPos.getX() - mazePos.getX()) / thicknessX; + int mazeY = (inPos.getY() - mazePos.getY()) / thicknessY; + CellState originCell = maze.cellState(mazeX, mazeY); + cellDecorator.generate(inPos, mazePos, maze, originCell, new Vec2i(this.thicknessX, this.thicknessY)); } } @@ -82,21 +81,21 @@ public void generateMaze(BlockPos pos, long seed, MazeCreator mazeCreator, Ce } - public HashMap getMazes() { + public HashMap getMazes() { return mazes; } @FunctionalInterface public static interface CellDecorator { - void generate(BlockPos pos, BlockPos mazePos, M maze, CellState state, int thickness); + void generate(Vec2i pos, Vec2i mazePos, M maze, CellState state, Vec2i thickness); } @FunctionalInterface public static interface MazeCreator { - M newMaze(BlockPos mazePos, int width, int height, RandomGenerator random); + M newMaze(Vec2i mazePos, int width, int height, RandomGenerator random); } diff --git a/src/main/java/net/ludocrypt/limlib/api/world/maze/RectangularMazePiece.java b/src/main/java/net/ludocrypt/limlib/api/world/maze/RectangularMazePiece.java index 24456eb..75df136 100644 --- a/src/main/java/net/ludocrypt/limlib/api/world/maze/RectangularMazePiece.java +++ b/src/main/java/net/ludocrypt/limlib/api/world/maze/RectangularMazePiece.java @@ -7,6 +7,7 @@ import net.minecraft.util.random.RandomGenerator; public enum RectangularMazePiece { + T_PIECE, F_PIECE, I_PIECE, @@ -22,7 +23,8 @@ public static Pair getFromCell(CellState st if (state.isNorth() && state.isEast() && state.isSouth() && state.isWest()) { piece = RectangularMazePiece.T_PIECE; rotation = random.nextBoolean() ? BlockRotation.NONE - : random.nextBoolean() ? random.nextBoolean() ? BlockRotation.CLOCKWISE_90 : BlockRotation.CLOCKWISE_180 : BlockRotation.COUNTERCLOCKWISE_90; + : random.nextBoolean() ? random.nextBoolean() ? BlockRotation.CLOCKWISE_90 : BlockRotation.CLOCKWISE_180 + : BlockRotation.COUNTERCLOCKWISE_90; } else if (state.isNorth() && state.isEast() && state.isSouth() && !state.isWest()) { piece = RectangularMazePiece.F_PIECE; rotation = BlockRotation.CLOCKWISE_180; diff --git a/src/main/java/net/ludocrypt/limlib/impl/Limlib.java b/src/main/java/net/ludocrypt/limlib/impl/Limlib.java index e2bf401..9d70c02 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/Limlib.java +++ b/src/main/java/net/ludocrypt/limlib/impl/Limlib.java @@ -31,13 +31,23 @@ public class Limlib implements ModInitializer { public void onInitialize(ModContainer mod) { LimlibWorld.load(); Registry.register(ReverbEffect.REVERB_EFFECT_CODEC, new Identifier("limlib", "static"), StaticReverbEffect.CODEC); - Registry.register(DistortionEffect.DISTORTION_EFFECT_CODEC, new Identifier("limlib", "static"), StaticDistortionEffect.CODEC); - Registry.register(DimensionEffects.DIMENSION_EFFECTS_CODEC, new Identifier("limlib", "static"), StaticDimensionEffects.CODEC); - Registry.register(DimensionEffects.DIMENSION_EFFECTS_CODEC, new Identifier("limlib", "empty"), EmptyDimensionEffects.CODEC); + Registry + .register(DistortionEffect.DISTORTION_EFFECT_CODEC, new Identifier("limlib", "static"), + StaticDistortionEffect.CODEC); + Registry + .register(DimensionEffects.DIMENSION_EFFECTS_CODEC, new Identifier("limlib", "static"), + StaticDimensionEffects.CODEC); + Registry + .register(DimensionEffects.DIMENSION_EFFECTS_CODEC, new Identifier("limlib", "empty"), + EmptyDimensionEffects.CODEC); Registry.register(PostEffect.POST_EFFECT_CODEC, new Identifier("limlib", "static"), StaticPostEffect.CODEC); Registry.register(PostEffect.POST_EFFECT_CODEC, new Identifier("limlib", "empty"), EmptyPostEffect.CODEC); - Registry.register(Registries.CHUNK_GENERATOR, new Identifier("limlib", "debug_nbt_chunk_generator"), DebugNbtChunkGenerator.CODEC); - QuiltLoader.getEntrypoints(LimlibRegistrar.ENTRYPOINT_KEY, LimlibRegistrar.class).forEach(LimlibRegistrar::registerHooks); + Registry + .register(Registries.CHUNK_GENERATOR, new Identifier("limlib", "debug_nbt_chunk_generator"), + DebugNbtChunkGenerator.CODEC); + QuiltLoader + .getEntrypoints(LimlibRegistrar.ENTRYPOINT_KEY, LimlibRegistrar.class) + .forEach(LimlibRegistrar::registerHooks); } } diff --git a/src/main/java/net/ludocrypt/limlib/impl/access/SoundSystemAccess.java b/src/main/java/net/ludocrypt/limlib/impl/access/SoundSystemAccess.java index f2c5a88..aee709e 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/access/SoundSystemAccess.java +++ b/src/main/java/net/ludocrypt/limlib/impl/access/SoundSystemAccess.java @@ -7,7 +7,8 @@ public interface SoundSystemAccess { - public void stopSoundsAtPosition(double x, double y, double z, @Nullable Identifier id, @Nullable SoundCategory category); + public void stopSoundsAtPosition(double x, double y, double z, @Nullable Identifier id, + @Nullable SoundCategory category); public static SoundSystemAccess get(Object obj) { return (SoundSystemAccess) obj; diff --git a/src/main/java/net/ludocrypt/limlib/impl/bridge/IrisBridge.java b/src/main/java/net/ludocrypt/limlib/impl/bridge/IrisBridge.java index 091d50b..af3b84f 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/bridge/IrisBridge.java +++ b/src/main/java/net/ludocrypt/limlib/impl/bridge/IrisBridge.java @@ -10,7 +10,9 @@ public class IrisBridge { public static final boolean IRIS_LOADED = QuiltLoader.isModLoaded("iris"); public static boolean areShadersInUse() { + if (IRIS_LOADED) { + try { Class irisApi = Class.forName("net.coderbot.iris.apiimpl.IrisApiV0Impl"); Field irisInstance = irisApi.getField("INSTANCE"); @@ -20,11 +22,14 @@ public static boolean areShadersInUse() { if (areThey instanceof Boolean depends) { return depends; } + } catch (Exception e) { e.printStackTrace(); return false; } + } + return false; } diff --git a/src/main/java/net/ludocrypt/limlib/impl/debug/DebugNbtChunkGenerator.java b/src/main/java/net/ludocrypt/limlib/impl/debug/DebugNbtChunkGenerator.java index 4c47156..7177959 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/debug/DebugNbtChunkGenerator.java +++ b/src/main/java/net/ludocrypt/limlib/impl/debug/DebugNbtChunkGenerator.java @@ -50,7 +50,9 @@ public class DebugNbtChunkGenerator extends AbstractNbtChunkGenerator { public static final Codec CODEC = RecordCodecBuilder.create((instance) -> { - return instance.group(RegistryOps.retrieveElement(Biomes.THE_VOID)).apply(instance, instance.stable(DebugNbtChunkGenerator::new)); + return instance + .group(RegistryOps.retrieveElement(Biomes.THE_VOID)) + .apply(instance, instance.stable(DebugNbtChunkGenerator::new)); }); BidirectionalMap positions = new BidirectionalMap(); @@ -69,9 +71,11 @@ public int getChunkDistance() { } @Override - public CompletableFuture populateNoise(ChunkRegion chunkRegion, ChunkStatus targetStatus, Executor executor, ServerWorld world, ChunkGenerator generator, - StructureTemplateManager structureTemplateManager, ServerLightingProvider lightingProvider, Function>> fullChunkConverter, - List chunks, Chunk chunk) { + public CompletableFuture populateNoise(ChunkRegion chunkRegion, ChunkStatus targetStatus, Executor executor, + ServerWorld world, ChunkGenerator generator, StructureTemplateManager structureTemplateManager, + ServerLightingProvider lightingProvider, + Function>> fullChunkConverter, List chunks, + Chunk chunk) { if (chunk.getPos().getStartPos().getX() < 0 || chunk.getPos().getStartPos().getZ() < 0) { return CompletableFuture.completedFuture(chunk); @@ -80,7 +84,8 @@ public CompletableFuture populateNoise(ChunkRegion chunkRegion, ChunkStat ResourceManager resourceManager = world.getServer().getResourceManager(); if (positions.isEmpty()) { - Map> ids = resourceManager.findAllResources("structures/nbt", (id) -> id.getPath().endsWith(".nbt")); + Map> ids = resourceManager + .findAllResources("structures/nbt", (id) -> id.getPath().endsWith(".nbt")); Map nbts = new LinkedHashMap<>(); for (Identifier id : ids.keySet()) { @@ -102,7 +107,8 @@ public CompletableFuture populateNoise(ChunkRegion chunkRegion, ChunkStat prevSize = BlockPos.ORIGIN.add(-2, 0, 0); } else { prevPos = positions.get(sortedNbts.get(i - 1).getKey()); - prevSize = new BlockPos(sortedNbts.get(i - 1).getValue().sizeX, sortedNbts.get(i - 1).getValue().sizeY, sortedNbts.get(i - 1).getValue().sizeZ); + prevSize = new BlockPos(sortedNbts.get(i - 1).getValue().sizeX, sortedNbts.get(i - 1).getValue().sizeY, + sortedNbts.get(i - 1).getValue().sizeZ); } if (prevPos.getX() > 160) { @@ -115,7 +121,10 @@ public CompletableFuture populateNoise(ChunkRegion chunkRegion, ChunkStat } positions.put(entry.getKey(), prevPos.add(prevSize.getX() + 2, 0, 0)); - this.nbtGroup.getGroups().computeIfAbsent("debug", (s) -> Lists.newArrayList()).add(entry.getKey().toString()); + this.nbtGroup + .getGroups() + .computeIfAbsent("debug", (s) -> Lists.newArrayList()) + .add(entry.getKey().toString()); } this.nbtGroup.fill(this.structures); @@ -129,13 +138,20 @@ public CompletableFuture populateNoise(ChunkRegion chunkRegion, ChunkStat if (positions.reverseMap.containsKey(pos.add(0, -10, 0))) { Identifier id = positions.reverseMap.get(pos.add(0, -10, 0)); this.generateNbt(chunkRegion, pos, id); - chunkRegion.setBlockState(pos.add(-1, -1, -1), Blocks.STRUCTURE_BLOCK.getDefaultState().with(StructureBlock.MODE, StructureBlockMode.SAVE), Block.FORCE_STATE); + chunkRegion + .setBlockState(pos.add(-1, -1, -1), + Blocks.STRUCTURE_BLOCK.getDefaultState().with(StructureBlock.MODE, StructureBlockMode.SAVE), + Block.FORCE_STATE); BlockEntity be = chunkRegion.getBlockEntity(pos.add(-1, -1, -1)); if (be != null && be instanceof StructureBlockBlockEntity blockEntity) { blockEntity - .setSize(new Vec3i(this.structures.eval(id, resourceManager).sizeX, this.structures.eval(id, resourceManager).sizeY, this.structures.eval(id, resourceManager).sizeZ)); - blockEntity.setStructureName(id.toString().substring(0, id.toString().length() - 4).replaceFirst("structures/", "")); + .setSize(new Vec3i(this.structures.eval(id, resourceManager).sizeX, + this.structures.eval(id, resourceManager).sizeY, + this.structures.eval(id, resourceManager).sizeZ)); + blockEntity + .setStructureName( + id.toString().substring(0, id.toString().length() - 4).replaceFirst("structures/", "")); blockEntity.setOffset(new BlockPos(1, 1, 1)); blockEntity.setIgnoreEntities(false); } @@ -156,7 +172,8 @@ public int getWorldHeight() { } @Override - protected void modifyStructure(ChunkRegion region, BlockPos pos, BlockState state, Optional blockEntityNbt, int update) { + protected void modifyStructure(ChunkRegion region, BlockPos pos, BlockState state, Optional blockEntityNbt, + int update) { region.setBlockState(pos, state, update, 1); blockEntityNbt.ifPresent((nbt) -> { if (region.getBlockEntity(pos) != null) @@ -165,7 +182,8 @@ protected void modifyStructure(ChunkRegion region, BlockPos pos, BlockState stat } @Override - public void method_40450(List list, RandomState randomState, BlockPos pos) {} + public void method_40450(List list, RandomState randomState, BlockPos pos) { + } public static class DebugNbtGroup extends NbtGroup { diff --git a/src/main/java/net/ludocrypt/limlib/impl/debug/DebugWorld.java b/src/main/java/net/ludocrypt/limlib/impl/debug/DebugWorld.java index 34d4fb2..d5b8da6 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/debug/DebugWorld.java +++ b/src/main/java/net/ludocrypt/limlib/impl/debug/DebugWorld.java @@ -16,19 +16,24 @@ public class DebugWorld implements LimlibRegistrar { - public static final RegistryKey DEBUG_KEY = RegistryKey.of(RegistryKeys.GENERATOR_TYPE, new Identifier("limlib", "debug_nbt")); + public static final RegistryKey DEBUG_KEY = RegistryKey + .of(RegistryKeys.GENERATOR_TYPE, new Identifier("limlib", "debug_nbt")); @Override public void registerHooks() { LimlibRegistryHooks - .hook(RegistryKeys.GENERATOR_TYPE, - (infoLookup, registryKey, - registry) -> registry - .register(DEBUG_KEY, - new GeneratorType(Map.of(DimensionOptions.OVERWORLD, - new DimensionOptions(infoLookup.lookup(RegistryKeys.DIMENSION_TYPE).get().getter().getHolderOrThrow(DimensionTypes.OVERWORLD), - new DebugNbtChunkGenerator(infoLookup.lookup(RegistryKeys.BIOME).get().getter().getHolderOrThrow(Biomes.THE_VOID))))), - Lifecycle.stable())); + .hook(RegistryKeys.GENERATOR_TYPE, (infoLookup, registryKey, registry) -> registry + .register(DEBUG_KEY, new GeneratorType(Map + .of(DimensionOptions.OVERWORLD, + new DimensionOptions( + infoLookup + .lookup(RegistryKeys.DIMENSION_TYPE) + .get() + .getter() + .getHolderOrThrow(DimensionTypes.OVERWORLD), + new DebugNbtChunkGenerator( + infoLookup.lookup(RegistryKeys.BIOME).get().getter().getHolderOrThrow(Biomes.THE_VOID))))), + Lifecycle.stable())); } } diff --git a/src/main/java/net/ludocrypt/limlib/impl/debug/mixin/GeneratorTypesBootstrapMixin.java b/src/main/java/net/ludocrypt/limlib/impl/debug/mixin/GeneratorTypesBootstrapMixin.java index 7a4b99c..7d67730 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/debug/mixin/GeneratorTypesBootstrapMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/debug/mixin/GeneratorTypesBootstrapMixin.java @@ -27,7 +27,9 @@ public abstract class GeneratorTypesBootstrapMixin { @Inject(method = "Lnet/minecraft/client/world/GeneratorTypes$Bootstrap;method_41600()V", at = @At("TAIL")) public void limlib$addDimensionOpions(CallbackInfo ci) { - this.addDimensionGenerator(DebugWorld.DEBUG_KEY, new DimensionOptions(this.overworld, new DebugNbtChunkGenerator(this.biome.getHolderOrThrow(Biomes.THE_VOID)))); + this + .addDimensionGenerator(DebugWorld.DEBUG_KEY, new DimensionOptions(this.overworld, + new DebugNbtChunkGenerator(this.biome.getHolderOrThrow(Biomes.THE_VOID)))); } abstract void addDimensionGenerator(RegistryKey generator, DimensionOptions dimension); diff --git a/src/main/java/net/ludocrypt/limlib/impl/debug/mixin/GeneratorTypesMixin.java b/src/main/java/net/ludocrypt/limlib/impl/debug/mixin/GeneratorTypesMixin.java index f31e1e7..1054f59 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/debug/mixin/GeneratorTypesMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/debug/mixin/GeneratorTypesMixin.java @@ -20,16 +20,19 @@ public class GeneratorTypesMixin { @Inject(method = "getKey", at = @At("HEAD"), cancellable = true) - private static void limlib$getKey(Registry registry, CallbackInfoReturnable>> ci) { - Optional> optional = registry.getOrEmpty(DimensionOptions.OVERWORLD).flatMap(dimensionOptions -> { - ChunkGenerator chunkGenerator = dimensionOptions.getChunkGenerator(); - - if (chunkGenerator instanceof DebugNbtChunkGenerator) { - return Optional.of(DebugWorld.DEBUG_KEY); - } - - return Optional.empty(); - }); + private static void limlib$getKey(Registry registry, + CallbackInfoReturnable>> ci) { + Optional> optional = registry + .getOrEmpty(DimensionOptions.OVERWORLD) + .flatMap(dimensionOptions -> { + ChunkGenerator chunkGenerator = dimensionOptions.getChunkGenerator(); + + if (chunkGenerator instanceof DebugNbtChunkGenerator) { + return Optional.of(DebugWorld.DEBUG_KEY); + } + + return Optional.empty(); + }); if (optional.isPresent()) { ci.setReturnValue(optional); diff --git a/src/main/java/net/ludocrypt/limlib/impl/debug/mixin/WorldPresetTagProviderMixin.java b/src/main/java/net/ludocrypt/limlib/impl/debug/mixin/WorldPresetTagProviderMixin.java index 8b25449..f63877f 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/debug/mixin/WorldPresetTagProviderMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/debug/mixin/WorldPresetTagProviderMixin.java @@ -21,7 +21,8 @@ @Mixin(WorldPresetTagProvider.class) public abstract class WorldPresetTagProviderMixin extends AbstractTagProvider { - protected WorldPresetTagProviderMixin(DataPackOutput output, RegistryKey> key, CompletableFuture lookupProvider) { + protected WorldPresetTagProviderMixin(DataPackOutput output, RegistryKey> key, + CompletableFuture lookupProvider) { super(output, key, lookupProvider); } diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/BuiltinDimensionTypesMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/BuiltinDimensionTypesMixin.java index 0103fa9..ca26341 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/BuiltinDimensionTypesMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/BuiltinDimensionTypesMixin.java @@ -17,8 +17,11 @@ public class BuiltinDimensionTypesMixin { @Inject(method = "bootstrap(Lnet/minecraft/world/gen/BootstrapContext;)V", at = @At("RETURN")) private static void limlib$initAndGetDefault(BootstrapContext bootstrapContext, CallbackInfo ci) { - LimlibWorld.LIMLIB_WORLD.getEntries() - .forEach((entry) -> bootstrapContext.register(RegistryKey.of(RegistryKeys.DIMENSION_TYPE, entry.getKey().getValue()), entry.getValue().getDimensionTypeSupplier().get())); + LimlibWorld.LIMLIB_WORLD + .getEntries() + .forEach((entry) -> bootstrapContext + .register(RegistryKey.of(RegistryKeys.DIMENSION_TYPE, entry.getKey().getValue()), + entry.getValue().getDimensionTypeSupplier().get())); } } diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/ChunkStatusMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/ChunkStatusMixin.java index 50ba308..b8d6861 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/ChunkStatusMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/ChunkStatusMixin.java @@ -28,13 +28,18 @@ public class ChunkStatusMixin { @Inject(method = "method_38284(Lnet/minecraft/world/chunk/ChunkStatus;Ljava/util/concurrent/Executor;Lnet/minecraft/server/world/ServerWorld;Lnet/minecraft/world/gen/chunk/ChunkGenerator;Lnet/minecraft/structure/StructureTemplateManager;Lnet/minecraft/server/world/ServerLightingProvider;Ljava/util/function/Function;Ljava/util/List;Lnet/minecraft/world/chunk/Chunk;)Ljava/util/concurrent/CompletableFuture;", at = @At("HEAD"), cancellable = true) - private static void limlib$liminalChunkGenerator(ChunkStatus chunkStatus, Executor executor, ServerWorld serverWorld, ChunkGenerator chunkGenerator, - StructureTemplateManager structureTemplateManager, ServerLightingProvider serverLightingProvider, Function>> function, - List chunks, Chunk chunk, CallbackInfoReturnable>> ci) { + private static void limlib$liminalChunkGenerator(ChunkStatus chunkStatus, Executor executor, ServerWorld serverWorld, + ChunkGenerator chunkGenerator, StructureTemplateManager structureTemplateManager, + ServerLightingProvider serverLightingProvider, + Function>> function, List chunks, + Chunk chunk, CallbackInfoReturnable>> ci) { if (chunkGenerator instanceof LiminalChunkGenerator limChunkGen) { ChunkRegion chunkRegion = new ChunkRegion(serverWorld, chunks, chunkStatus, limChunkGen.getChunkDistance()); - ci.setReturnValue(limChunkGen.populateNoise(chunkRegion, chunkStatus, executor, serverWorld, chunkGenerator, structureTemplateManager, serverLightingProvider, function, chunks, chunk) + ci + .setReturnValue(limChunkGen + .populateNoise(chunkRegion, chunkStatus, executor, serverWorld, chunkGenerator, structureTemplateManager, + serverLightingProvider, function, chunks, chunk) .thenApply(chunkx -> { if (chunkx instanceof ProtoChunk protoChunk) { diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/DynamicRegistrySyncMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/DynamicRegistrySyncMixin.java index 2abaff5..320d5a2 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/DynamicRegistrySyncMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/DynamicRegistrySyncMixin.java @@ -24,7 +24,8 @@ public abstract class DynamicRegistrySyncMixin { @Inject(method = "method_45958()Lcom/google/common/collect/ImmutableMap;", at = @At(value = "INVOKE", target = "Lnet/minecraft/registry/DynamicRegistrySync;addSyncedRegistry(Lcom/google/common/collect/ImmutableMap$Builder;Lnet/minecraft/registry/RegistryKey;Lcom/mojang/serialization/Codec;)V", ordinal = 2, shift = Shift.AFTER), locals = LocalCapture.CAPTURE_FAILHARD) - private static void limlib$makeMap$mapped(CallbackInfoReturnable>, DynamicRegistrySync.SyncEntry>> ci, + private static void limlib$makeMap$mapped( + CallbackInfoReturnable>, DynamicRegistrySync.SyncEntry>> ci, Builder>, DynamicRegistrySync.SyncEntry> builder) { addSyncedRegistry(builder, PostEffect.POST_EFFECT_KEY, PostEffect.CODEC); addSyncedRegistry(builder, DimensionEffects.DIMENSION_EFFECTS_KEY, DimensionEffects.CODEC); @@ -33,6 +34,8 @@ public abstract class DynamicRegistrySyncMixin { } @Shadow - private native static void addSyncedRegistry(Builder>, DynamicRegistrySync.SyncEntry> builder, RegistryKey> registryKey, - Codec codec); + private native static void addSyncedRegistry( + Builder>, DynamicRegistrySync.SyncEntry> builder, + RegistryKey> registryKey, Codec codec); + } diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/RegistriesAccessor.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/RegistriesAccessor.java index a18de8d..f9ee654 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/RegistriesAccessor.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/RegistriesAccessor.java @@ -13,7 +13,8 @@ public interface RegistriesAccessor { @Invoker - static Registry callRegisterSimple(RegistryKey> registryKey, Lifecycle lifecycle, Registries.RegistryBootstrap bootstrap) { + static Registry callRegisterSimple(RegistryKey> registryKey, Lifecycle lifecycle, + Registries.RegistryBootstrap bootstrap) { throw new UnsupportedOperationException(); } diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/RegistryLoaderMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/RegistryLoaderMixin.java index 4b4a04a..3a2cb29 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/RegistryLoaderMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/RegistryLoaderMixin.java @@ -67,43 +67,61 @@ public class RegistryLoaderMixin { } @Inject(method = "loadRegistryContents(Lnet/minecraft/registry/RegistryOps$RegistryInfoLookup;Lnet/minecraft/resource/ResourceManager;Lnet/minecraft/registry/RegistryKey;Lnet/minecraft/registry/MutableRegistry;Lcom/mojang/serialization/Decoder;Ljava/util/Map;)V", at = @At(value = "INVOKE", target = "Lcom/mojang/serialization/Decoder;parse(Lcom/mojang/serialization/DynamicOps;Ljava/lang/Object;)Lcom/mojang/serialization/DataResult;", shift = Shift.BEFORE), locals = LocalCapture.CAPTURE_FAILHARD) - private static void limlib$loadRegistryContents(RegistryOps.RegistryInfoLookup infoLookup, ResourceManager resourceManager, RegistryKey> registryKey, - MutableRegistry registry, Decoder decoder, Map, Exception> readFailures, CallbackInfo ci, String string, ResourceFileNamespace resourceFileNamespace, - RegistryOps registryOps, Iterator> var9, Map.Entry entry, Identifier identifier, RegistryKey registryKey2, - Resource resource, Reader reader, JsonElement jsonElement) { + private static void limlib$loadRegistryContents(RegistryOps.RegistryInfoLookup infoLookup, + ResourceManager resourceManager, RegistryKey> registryKey, MutableRegistry registry, + Decoder decoder, Map, Exception> readFailures, CallbackInfo ci, String string, + ResourceFileNamespace resourceFileNamespace, RegistryOps registryOps, + Iterator> var9, Map.Entry entry, Identifier identifier, + RegistryKey registryKey2, Resource resource, Reader reader, JsonElement jsonElement) { if (registryKey2.isOf(RegistryKeys.GENERATOR_TYPE)) { JsonObject presetType = jsonElement.getAsJsonObject(); JsonObject dimensions = presetType.get("dimensions").getAsJsonObject(); - LimlibWorld.LIMLIB_WORLD.getEntries().forEach((world) -> dimensions.add(world.getKey().getValue().toString(), - DimensionOptions.CODEC.encodeStart(registryOps, world.getValue().getDimensionOptionsSupplier().apply(new RegistryProvider() { - - @Override - public HolderProvider get(RegistryKey> key) { - return registryOps.getHolderProvider(key).get(); - } - - })).result().get())); + LimlibWorld.LIMLIB_WORLD + .getEntries() + .forEach((world) -> dimensions + .add(world.getKey().getValue().toString(), + DimensionOptions.CODEC + .encodeStart(registryOps, + world.getValue().getDimensionOptionsSupplier().apply(new RegistryProvider() { + + @Override + public HolderProvider get(RegistryKey> key) { + return registryOps.getHolderProvider(key).get(); + } + + })) + .result() + .get())); } - LimlibRegistryHooks.REGISTRY_JSON_HOOKS.getOrDefault(registryKey, Sets.newHashSet()) - .forEach((registrarhook -> ((LimlibJsonRegistryHook) registrarhook).register(infoLookup, registryKey, registryOps, jsonElement))); + LimlibRegistryHooks.REGISTRY_JSON_HOOKS + .getOrDefault(registryKey, Sets.newHashSet()) + .forEach((registrarhook -> ((LimlibJsonRegistryHook) registrarhook) + .register(infoLookup, registryKey, registryOps, jsonElement))); } @Inject(method = "loadRegistryContents(Lnet/minecraft/registry/RegistryOps$RegistryInfoLookup;Lnet/minecraft/resource/ResourceManager;Lnet/minecraft/registry/RegistryKey;Lnet/minecraft/registry/MutableRegistry;Lcom/mojang/serialization/Decoder;Ljava/util/Map;)V", at = @At("TAIL")) - private static void limlib$loadRegistryContents(RegistryOps.RegistryInfoLookup infoLookup, ResourceManager resourceManager, RegistryKey> registryKey, - MutableRegistry registry, Decoder decoder, Map, Exception> readFailures, CallbackInfo ci) { + private static void limlib$loadRegistryContents(RegistryOps.RegistryInfoLookup infoLookup, + ResourceManager resourceManager, RegistryKey> registryKey, MutableRegistry registry, + Decoder decoder, Map, Exception> readFailures, CallbackInfo ci) { if (registryKey.equals(RegistryKeys.DIMENSION_TYPE)) { - LimlibWorld.LIMLIB_WORLD.getEntries().forEach((world) -> ((MutableRegistry) registry).register(RegistryKey.of(RegistryKeys.DIMENSION_TYPE, world.getKey().getValue()), - world.getValue().getDimensionTypeSupplier().get(), Lifecycle.stable())); + LimlibWorld.LIMLIB_WORLD + .getEntries() + .forEach((world) -> ((MutableRegistry) registry) + .register(RegistryKey.of(RegistryKeys.DIMENSION_TYPE, world.getKey().getValue()), + world.getValue().getDimensionTypeSupplier().get(), Lifecycle.stable())); } - LimlibRegistryHooks.REGISTRY_HOOKS.getOrDefault(registryKey, Sets.newHashSet()).forEach((registrarhook -> ((LimlibRegistryHook) registrarhook).register(infoLookup, registryKey, registry))); + LimlibRegistryHooks.REGISTRY_HOOKS + .getOrDefault(registryKey, Sets.newHashSet()) + .forEach((registrarhook -> ((LimlibRegistryHook) registrarhook).register(infoLookup, registryKey, registry))); } @Inject(method = "loadRegistriesIntoManager(Lnet/minecraft/resource/ResourceManager;Lnet/minecraft/registry/DynamicRegistryManager;Ljava/util/List;)Lnet/minecraft/registry/DynamicRegistryManager$Frozen;", at = @At("TAIL")) - private static void limlib$loadRegistriesIntoManager(ResourceManager resourceManager, DynamicRegistryManager registryManager, List> decodingData, + private static void limlib$loadRegistriesIntoManager(ResourceManager resourceManager, + DynamicRegistryManager registryManager, List> decodingData, CallbackInfoReturnable ci) { SaveStorageSupplier.LOADED_REGISTRY.set(registryManager.freeze()); } diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/ServerPlayerEntityMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/ServerPlayerEntityMixin.java index bc621fb..ed79381 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/ServerPlayerEntityMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/ServerPlayerEntityMixin.java @@ -32,9 +32,13 @@ public ServerPlayerEntityMixin(World world, BlockPos pos, float f, GameProfile g @Inject(method = "moveToWorld", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayNetworkHandler;sendPacket(Lnet/minecraft/network/packet/Packet;)V", ordinal = 5, shift = Shift.AFTER)) public void limlib$moveToWorld(ServerWorld to, CallbackInfoReturnable ci) { + if (LimlibTravelling.travelingSound != null) { - this.playSound(LimlibTravelling.travelingSound, SoundCategory.AMBIENT, LimlibTravelling.travelingVolume, LimlibTravelling.travelingPitch); + this + .playSound(LimlibTravelling.travelingSound, SoundCategory.AMBIENT, LimlibTravelling.travelingVolume, + LimlibTravelling.travelingPitch); } + } @ModifyArg(method = "moveToWorld", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/packet/s2c/play/WorldEventS2CPacket;(ILnet/minecraft/util/math/BlockPos;IZ)V", ordinal = 0), index = 0) diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/WorldDimensionsMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/WorldDimensionsMixin.java index 3ed8c9e..1a31ace 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/WorldDimensionsMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/WorldDimensionsMixin.java @@ -31,7 +31,9 @@ public class WorldDimensionsMixin { private static void limlib$clinit(CallbackInfo ci) { Set> dimensions = Sets.newHashSet(); dimensions.addAll(VANILLA_DIMENSION_KEYS); - LimlibWorld.LIMLIB_WORLD.getEntries().forEach((entry) -> dimensions.add(RegistryKey.of(RegistryKeys.DIMENSION, entry.getKey().getValue()))); + LimlibWorld.LIMLIB_WORLD + .getEntries() + .forEach((entry) -> dimensions.add(RegistryKey.of(RegistryKeys.DIMENSION, entry.getKey().getValue()))); VANILLA_DIMENSION_KEYS = dimensions; } diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/WorldSaveStorageMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/WorldSaveStorageMixin.java index 6119c9d..906c8af 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/WorldSaveStorageMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/WorldSaveStorageMixin.java @@ -28,11 +28,14 @@ public class WorldSaveStorageMixin { @ModifyVariable(method = "readGeneratorProperties(Lcom/mojang/serialization/Dynamic;Lcom/mojang/datafixers/DataFixer;I)Lcom/mojang/serialization/DataResult;", at = @At(value = "STORE"), ordinal = 1) - private static Dynamic limlib$readGeneratorProperties$datafix(Dynamic in, Dynamic levelData, DataFixer dataFixer, int version) { + private static Dynamic limlib$readGeneratorProperties$datafix(Dynamic in, Dynamic levelData, + DataFixer dataFixer, int version) { Dynamic dynamic = in; + for (Entry, LimlibWorld> entry : LimlibWorld.LIMLIB_WORLD.getEntries()) { dynamic = limlib$addDimension(entry.getKey(), entry.getValue(), dynamic); } + return dynamic; } @@ -40,22 +43,30 @@ public class WorldSaveStorageMixin { @SuppressWarnings("unchecked") private static Dynamic limlib$addDimension(RegistryKey key, LimlibWorld world, Dynamic in) { Dynamic dimensions = in.get("dimensions").orElseEmptyMap(); + if (!dimensions.get(key.getValue().toString()).result().isPresent()) { Map, Dynamic> dimensionsMap = Maps.newHashMap(dimensions.getMapValues().result().get()); DynamicRegistryManager registryManager = SaveStorageSupplier.LOADED_REGISTRY.get(); - dimensionsMap.put(dimensions.createString(key.getValue().toString()), new Dynamic(dimensions.getOps(), - (T) DimensionOptions.CODEC.encodeStart(RegistryOps.create(NbtOps.INSTANCE, registryManager), world.getDimensionOptionsSupplier().apply(new RegistryProvider() { + dimensionsMap + .put(dimensions.createString(key.getValue().toString()), + new Dynamic(dimensions.getOps(), + (T) DimensionOptions.CODEC + .encodeStart(RegistryOps.create(NbtOps.INSTANCE, registryManager), + world.getDimensionOptionsSupplier().apply(new RegistryProvider() { - @Override - public HolderProvider get(RegistryKey> key) { - return registryManager.getLookup(key).get(); - } + @Override + public HolderProvider get(RegistryKey> key) { + return registryManager.getLookup(key).get(); + } - })).result().get())); + })) + .result() + .get())); in = in.set("dimensions", in.createMap(dimensionsMap)); } + return in; } diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/BackgroundRendererMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/BackgroundRendererMixin.java index e9d771e..34d243c 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/BackgroundRendererMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/BackgroundRendererMixin.java @@ -19,12 +19,15 @@ public abstract class BackgroundRendererMixin { private static float limlib$modifySkyColor(float in) { MinecraftClient client = MinecraftClient.getInstance(); - Optional dimensionEffects = LookupGrabber.snatch(client.world.getRegistryManager().getLookup(DimensionEffects.DIMENSION_EFFECTS_KEY).get(), + Optional dimensionEffects = LookupGrabber + .snatch(client.world.getRegistryManager().getLookup(DimensionEffects.DIMENSION_EFFECTS_KEY).get(), RegistryKey.of(DimensionEffects.DIMENSION_EFFECTS_KEY, client.world.getRegistryKey().getValue())); + if (dimensionEffects.isPresent()) { return dimensionEffects.get().getSkyShading(); } return in; } + } diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/ClientWorldMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/ClientWorldMixin.java index 6cbe898..cb17798 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/ClientWorldMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/ClientWorldMixin.java @@ -23,15 +23,19 @@ @Mixin(ClientWorld.class) public abstract class ClientWorldMixin extends World { - protected ClientWorldMixin(MutableWorldProperties worldProperties, RegistryKey registryKey, DynamicRegistryManager registryManager, Holder dimension, - Supplier profiler, boolean client, boolean debug, long seed, int maxChainedNeighborUpdates) { - super(worldProperties, registryKey, registryManager, dimension, profiler, client, debug, seed, maxChainedNeighborUpdates); + protected ClientWorldMixin(MutableWorldProperties worldProperties, RegistryKey registryKey, + DynamicRegistryManager registryManager, Holder dimension, Supplier profiler, + boolean client, boolean debug, long seed, int maxChainedNeighborUpdates) { + super(worldProperties, registryKey, registryManager, dimension, profiler, client, debug, seed, + maxChainedNeighborUpdates); } @Inject(method = "(Lnet/minecraft/client/network/ClientPlayNetworkHandler;Lnet/minecraft/client/world/ClientWorld$Properties;Lnet/minecraft/registry/RegistryKey;Lnet/minecraft/registry/Holder;IILjava/util/function/Supplier;Lnet/minecraft/client/render/WorldRenderer;ZJ)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/DimensionVisualEffects;byDimensionType(Lnet/minecraft/world/dimension/DimensionType;)Lnet/minecraft/client/render/DimensionVisualEffects;", shift = Shift.BEFORE)) - private void limlib$init(ClientPlayNetworkHandler netHandler, ClientWorld.Properties clientWorldProperties, RegistryKey registryKey, Holder dimensionType, int chunkManager, - int simulationDistance, Supplier profiler, WorldRenderer worldRenderer, boolean debugWorld, long seed, CallbackInfo ci) { - DimensionEffects.MIXIN_WORLD_LOOKUP.set(this.getRegistryManager().getLookup(DimensionEffects.DIMENSION_EFFECTS_KEY).get()); + private void limlib$init(ClientPlayNetworkHandler netHandler, ClientWorld.Properties clientWorldProperties, + RegistryKey registryKey, Holder dimensionType, int chunkManager, int simulationDistance, + Supplier profiler, WorldRenderer worldRenderer, boolean debugWorld, long seed, CallbackInfo ci) { + DimensionEffects.MIXIN_WORLD_LOOKUP + .set(this.getRegistryManager().getLookup(DimensionEffects.DIMENSION_EFFECTS_KEY).get()); } } diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/DimensionVisualEffectsMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/DimensionVisualEffectsMixin.java index 66cd3e9..0c118df 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/DimensionVisualEffectsMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/DimensionVisualEffectsMixin.java @@ -17,12 +17,16 @@ public class DimensionVisualEffectsMixin { @Inject(method = "byDimensionType", at = @At("HEAD"), cancellable = true) - private static void limlib$byDimensionType(DimensionType dimensionType, CallbackInfoReturnable ci) { - Optional dimensionEffects = LookupGrabber.snatch(DimensionEffects.MIXIN_WORLD_LOOKUP.get(), + private static void limlib$byDimensionType(DimensionType dimensionType, + CallbackInfoReturnable ci) { + Optional dimensionEffects = LookupGrabber + .snatch(DimensionEffects.MIXIN_WORLD_LOOKUP.get(), RegistryKey.of(DimensionEffects.DIMENSION_EFFECTS_KEY, dimensionType.effectsLocation())); + if (dimensionEffects.isPresent()) { ci.setReturnValue(dimensionEffects.get().getDimensionEffects()); } + } } diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/GameRendererMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/GameRendererMixin.java index 43f5a08..c612c60 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/GameRendererMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/GameRendererMixin.java @@ -30,19 +30,25 @@ public class GameRendererMixin { private MinecraftClient client; @Unique - private final Function memoizedShaders = Util.memoize(id -> PostProcesserManager.INSTANCE.find(id)); + private final Function memoizedShaders = Util + .memoize(id -> PostProcesserManager.INSTANCE.find(id)); @Inject(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/WorldRenderer;drawEntityOutlinesFramebuffer()V", shift = Shift.AFTER)) private void limlib$render(float tickDelta, long nanoTime, boolean renderLevel, CallbackInfo info) { - Optional optionalPostEffect = LookupGrabber.snatch(client.world.getRegistryManager().getLookup(PostEffect.POST_EFFECT_KEY).get(), + Optional optionalPostEffect = LookupGrabber + .snatch(client.world.getRegistryManager().getLookup(PostEffect.POST_EFFECT_KEY).get(), RegistryKey.of(PostEffect.POST_EFFECT_KEY, client.world.getRegistryKey().getValue())); + if (optionalPostEffect.isPresent()) { PostEffect postEffect = optionalPostEffect.get(); + if (postEffect.shouldRender()) { postEffect.beforeRender(); memoizedShaders.apply(postEffect.getShaderLocation()).render(tickDelta); } + } + } } diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/MinecraftClientMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/MinecraftClientMixin.java index bbe392c..cabb673 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/MinecraftClientMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/MinecraftClientMixin.java @@ -36,21 +36,29 @@ public class MinecraftClientMixin { @Inject(method = "getMusic", at = @At("HEAD"), cancellable = true) private void limlib$getMusic(CallbackInfoReturnable ci) { + if (this.player != null) { - Optional soundEffects = LookupGrabber.snatch(world.getRegistryManager().getLookup(SoundEffects.SOUND_EFFECTS_KEY).get(), + Optional soundEffects = LookupGrabber + .snatch(world.getRegistryManager().getLookup(SoundEffects.SOUND_EFFECTS_KEY).get(), RegistryKey.of(SoundEffects.SOUND_EFFECTS_KEY, world.getRegistryKey().getValue())); + if (soundEffects.isPresent()) { Optional musicSound = soundEffects.get().getMusic(); + if (musicSound.isPresent()) { ci.setReturnValue(musicSound.get()); } + } + } + } @Inject(method = "onResolutionChanged", at = @At("RETURN")) private void limlib$onResolutionChanged(CallbackInfo info) { - PostProcesserManager.INSTANCE.onResolutionChanged(this.window.getFramebufferWidth(), this.window.getFramebufferHeight()); + PostProcesserManager.INSTANCE + .onResolutionChanged(this.window.getFramebufferWidth(), this.window.getFramebufferHeight()); } } diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/SoundSystemMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/SoundSystemMixin.java index e4e0eb0..5903b7f 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/SoundSystemMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/SoundSystemMixin.java @@ -41,11 +41,15 @@ public abstract class SoundSystemMixin implements SoundSystemAccess { private Multimap sounds; @Override - public void stopSoundsAtPosition(double x, double y, double z, @Nullable Identifier id, @Nullable SoundCategory category) { + public void stopSoundsAtPosition(double x, double y, double z, @Nullable Identifier id, + @Nullable SoundCategory category) { Consumer consumer = (soundInstance) -> { - if ((id != null ? soundInstance.getId().equals(id) : true) && (soundInstance.getX() == x) && (soundInstance.getY() == y) && (soundInstance.getZ() == z)) { + + if ((id != null ? soundInstance.getId().equals(id) + : true) && (soundInstance.getX() == x) && (soundInstance.getY() == y) && (soundInstance.getZ() == z)) { this.stop(soundInstance); } + }; if (category != null) { @@ -53,17 +57,21 @@ public void stopSoundsAtPosition(double x, double y, double z, @Nullable Identif } else { this.sounds.forEach((soundCategory, soundInstance) -> consumer.accept(soundInstance)); } + } @Inject(method = "tick()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/option/GameOptions;getSoundVolume(Lnet/minecraft/sound/SoundCategory;)F", shift = Shift.BEFORE), locals = LocalCapture.CAPTURE_FAILHARD) - public void limlib$tick(CallbackInfo ci, Iterator iterator, Map.Entry entry, Channel.SourceManager sourceManager, SoundInstance soundInstance) { + public void limlib$tick(CallbackInfo ci, Iterator iterator, Map.Entry entry, + Channel.SourceManager sourceManager, SoundInstance soundInstance) { sourceManager.run(source -> ReverbFilter.update(soundInstance, ((SourceAccessor) source).getPointer())); sourceManager.run(source -> DistortionFilter.update(soundInstance, ((SourceAccessor) source).getPointer())); } @Inject(method = "play(Lnet/minecraft/client/sound/SoundInstance;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/sound/Channel$SourceManager;run(Ljava/util/function/Consumer;)V", ordinal = 0, shift = Shift.AFTER), locals = LocalCapture.CAPTURE_FAILHARD) - public void limlib$play(SoundInstance soundInstance, CallbackInfo ci, WeightedSoundSet weightedSoundSet, Identifier identifier, Sound sound, float f, float g, SoundCategory soundCategory, float h, - float i, SoundInstance.AttenuationType attenuationType, boolean bl, Vec3d vec3d, boolean bl3, boolean bl4, CompletableFuture completableFuture, Channel.SourceManager sourceManager) { + public void limlib$play(SoundInstance soundInstance, CallbackInfo ci, WeightedSoundSet weightedSoundSet, + Identifier identifier, Sound sound, float f, float g, SoundCategory soundCategory, float h, float i, + SoundInstance.AttenuationType attenuationType, boolean bl, Vec3d vec3d, boolean bl3, boolean bl4, + CompletableFuture completableFuture, Channel.SourceManager sourceManager) { sourceManager.run(source -> ReverbFilter.update(soundInstance, ((SourceAccessor) source).getPointer())); sourceManager.run(source -> DistortionFilter.update(soundInstance, ((SourceAccessor) source).getPointer())); } diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/WorldRendererAfterMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/WorldRendererAfterMixin.java index aef24af..5da10c0 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/WorldRendererAfterMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/WorldRendererAfterMixin.java @@ -29,19 +29,27 @@ public abstract class WorldRendererAfterMixin { private MinecraftClient client; @Inject(method = "Lnet/minecraft/client/render/WorldRenderer;render(Lnet/minecraft/client/util/math/MatrixStack;FJZLnet/minecraft/client/render/Camera;Lnet/minecraft/client/render/GameRenderer;Lnet/minecraft/client/render/LightmapTextureManager;Lorg/joml/Matrix4f;)V", at = @At(value = "RETURN", shift = At.Shift.BEFORE)) - private void limlib$render$clear(MatrixStack matrices, float tickDelta, long limitTime, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, - LightmapTextureManager lightmapTextureManager, Matrix4f positionMatrix, CallbackInfo ci) { + private void limlib$render$clear(MatrixStack matrices, float tickDelta, long limitTime, boolean renderBlockOutline, + Camera camera, GameRenderer gameRenderer, LightmapTextureManager lightmapTextureManager, Matrix4f positionMatrix, + CallbackInfo ci) { + if (IrisBridge.IRIS_LOADED) { + if (IrisBridge.areShadersInUse()) { MinecraftClient client = MinecraftClient.getInstance(); - Optional sky = LookupGrabber.snatch(client.world.getRegistryManager().getLookup(Skybox.SKYBOX_KEY).get(), + Optional sky = LookupGrabber + .snatch(client.world.getRegistryManager().getLookup(Skybox.SKYBOX_KEY).get(), RegistryKey.of(Skybox.SKYBOX_KEY, client.world.getRegistryKey().getValue())); + if (sky.isPresent()) { sky.get().renderSky(((WorldRenderer) (Object) this), client, matrices, positionMatrix, tickDelta); } + } + } + } } diff --git a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/WorldRendererBeforeMixin.java b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/WorldRendererBeforeMixin.java index c1cfddf..6e56778 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/mixin/client/WorldRendererBeforeMixin.java +++ b/src/main/java/net/ludocrypt/limlib/impl/mixin/client/WorldRendererBeforeMixin.java @@ -23,20 +23,28 @@ public abstract class WorldRendererBeforeMixin { @Inject(method = "Lnet/minecraft/client/render/WorldRenderer;render(Lnet/minecraft/client/util/math/MatrixStack;FJZLnet/minecraft/client/render/Camera;Lnet/minecraft/client/render/GameRenderer;Lnet/minecraft/client/render/LightmapTextureManager;Lorg/joml/Matrix4f;)V", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;clear(IZ)V", ordinal = 0, shift = At.Shift.AFTER, remap = false)) - private void limlib$render$clear(MatrixStack matrices, float tickDelta, long limitTime, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, - LightmapTextureManager lightmapTextureManager, Matrix4f positionMatrix, CallbackInfo ci) { + private void limlib$render$clear(MatrixStack matrices, float tickDelta, long limitTime, boolean renderBlockOutline, + Camera camera, GameRenderer gameRenderer, LightmapTextureManager lightmapTextureManager, Matrix4f positionMatrix, + CallbackInfo ci) { + if (IrisBridge.IRIS_LOADED) { + if (IrisBridge.areShadersInUse()) { return; } + } MinecraftClient client = MinecraftClient.getInstance(); - Optional sky = LookupGrabber.snatch(client.world.getRegistryManager().getLookup(Skybox.SKYBOX_KEY).get(), RegistryKey.of(Skybox.SKYBOX_KEY, client.world.getRegistryKey().getValue())); + Optional sky = LookupGrabber + .snatch(client.world.getRegistryManager().getLookup(Skybox.SKYBOX_KEY).get(), + RegistryKey.of(Skybox.SKYBOX_KEY, client.world.getRegistryKey().getValue())); + if (sky.isPresent()) { sky.get().renderSky(((WorldRenderer) (Object) this), client, matrices, positionMatrix, tickDelta); } + } } diff --git a/src/main/java/net/ludocrypt/limlib/impl/shader/PostProcesser.java b/src/main/java/net/ludocrypt/limlib/impl/shader/PostProcesser.java index 637b355..32822fd 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/shader/PostProcesser.java +++ b/src/main/java/net/ludocrypt/limlib/impl/shader/PostProcesser.java @@ -23,6 +23,7 @@ public PostProcesser(Identifier location) { } public void init(ResourceManager resourceManager) { + try { this.release(); MinecraftClient client = MinecraftClient.getInstance(); @@ -32,14 +33,18 @@ public void init(ResourceManager resourceManager) { this.loaded = true; Limlib.LOGGER.error("Could not create screen shader {}", this.getLocation(), e); } + } - protected ShaderEffect parseShader(ResourceManager resourceManager, MinecraftClient mc, Identifier location) throws IOException { + protected ShaderEffect parseShader(ResourceManager resourceManager, MinecraftClient mc, Identifier location) + throws IOException { return new ShaderEffect(mc.getTextureManager(), resourceManager, mc.getFramebuffer(), location); } public void release() { + if (this.isInitialized()) { + try { assert this.shader != null; this.shader.close(); @@ -47,12 +52,15 @@ public void release() { } catch (Exception e) { throw new RuntimeException("Failed to release shader " + this.location, e); } + } + this.loaded = false; } public void render(float tickDelta) { ShaderEffect shader = this.getShaderEffect(); + if (shader != null) { RenderSystem.disableBlend(); RenderSystem.disableDepthTest(); @@ -63,6 +71,7 @@ public void render(float tickDelta) { RenderSystem.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); RenderSystem.enableDepthTest(); } + } public Identifier getLocation() { @@ -78,9 +87,11 @@ public boolean isInitialized() { } public ShaderEffect getShaderEffect() { + if (!this.isInitialized() && !this.isLoaded()) { this.init(MinecraftClient.getInstance().getResourceManager()); } + return this.shader; } diff --git a/src/main/java/net/ludocrypt/limlib/impl/shader/PostProcesserManager.java b/src/main/java/net/ludocrypt/limlib/impl/shader/PostProcesserManager.java index ef1d780..f1fce92 100644 --- a/src/main/java/net/ludocrypt/limlib/impl/shader/PostProcesserManager.java +++ b/src/main/java/net/ludocrypt/limlib/impl/shader/PostProcesserManager.java @@ -10,6 +10,7 @@ import net.minecraft.util.Identifier; public final class PostProcesserManager implements SimpleSynchronousResourceReloader { + public static final PostProcesserManager INSTANCE = new PostProcesserManager(); public static final Identifier RESOURCE_KEY = new Identifier("limlib:shaders"); @@ -22,14 +23,22 @@ public PostProcesser find(Identifier location) { } public void onResolutionChanged(int newWidth, int newHeight) { + if (!shaders.isEmpty()) { + for (PostProcesser shader : shaders) { + if (shader.isInitialized()) { MinecraftClient client = MinecraftClient.getInstance(); - shader.shader.setupDimensions(client.getWindow().getFramebufferWidth(), client.getWindow().getFramebufferHeight()); + shader.shader + .setupDimensions(client.getWindow().getFramebufferWidth(), + client.getWindow().getFramebufferHeight()); } + } + } + } @Override @@ -39,9 +48,11 @@ public Identifier getQuiltId() { @Override public void reload(ResourceManager mgr) { + for (PostProcesser shader : shaders) { shader.init(mgr); } + } public void dispose(PostProcesser shader) {