├── settings.zip ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src └── main │ ├── resources │ ├── assets │ │ └── soundphysics │ │ │ ├── icon.png │ │ │ └── lang │ │ │ └── en_us.json │ ├── bluetapepack.mixins.json │ ├── soundphysics.mixins.json │ └── fabric.mod.json │ └── java │ └── com │ └── sonicether │ └── soundphysics │ ├── SourceAccessor.java │ ├── performance │ ├── WorldChunkAccess.java │ ├── Shapes.java │ ├── SPHitResult.java │ ├── LiquidStorage.java │ └── RaycastFix.java │ ├── config │ ├── BlueTapePack │ │ ├── mixin │ │ │ ├── GuiRegistriesAccessorMixin.java │ │ │ └── NestedListSaveContentMixin.java │ │ ├── ModMenuIntegration.java │ │ ├── GuiRegistryinit.java │ │ └── ConfigManager.java │ ├── MaterialData.java │ ├── presets │ │ ├── ConfigChanger.java │ │ └── ConfigPresets.java │ ├── PrecomputedConfig.java │ └── SoundPhysicsConfig.java │ ├── mixin │ ├── server │ │ ├── ReloadCommandMixin.java │ │ ├── ServerWorldMixin.java │ │ └── EntityMixin.java │ ├── RendererMixin.java │ ├── SourceMixin.java │ ├── SoundSystemMixin.java │ └── WorldChunkMixin.java │ ├── SPLog.java │ ├── RaycastRenderer.java │ ├── ALstuff │ ├── SPEfx.java │ └── ReverbSlot.java │ ├── SoundPhysicsMod.java │ └── SoundPhysics.java ├── settings.gradle ├── gradle.properties ├── README.md ├── gradlew.bat ├── gradlew └── LICENSE /settings.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vlad2305m/Sound-Physics-Fabric/HEAD/settings.zip -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vlad2305m/Sound-Physics-Fabric/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/resources/assets/soundphysics/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vlad2305m/Sound-Physics-Fabric/HEAD/src/main/resources/assets/soundphysics/icon.png -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | maven { 4 | name = 'Fabric' 5 | url = 'https://maven.fabricmc.net/' 6 | } 7 | gradlePluginPortal() 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/SourceAccessor.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics; 2 | 3 | import net.minecraft.sound.SoundCategory; 4 | 5 | public interface SourceAccessor { 6 | void calculateReverb(SoundCategory category, String name); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/performance/WorldChunkAccess.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.performance; 2 | 3 | public interface WorldChunkAccess { 4 | 5 | LiquidStorage getNotAirLiquidStorage(); 6 | //LiquidStorage getWaterLiquidStorage(); 7 | //LiquidStorage getLavaLiquidStorage(); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/resources/bluetapepack.mixins.json: -------------------------------------------------------------------------------- 1 | { 2 | "required": false, 3 | "minVersion": "0.8.2", 4 | "package": "com.sonicether.soundphysics.config.BlueTapePack.mixin", 5 | "compatibilityLevel": "JAVA_17", 6 | "mixins": [ ], 7 | "client": [ 8 | "GuiRegistriesAccessorMixin", 9 | "NestedListSaveContentMixin" 10 | ], 11 | "injectors": { 12 | "defaultRequire": 1 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/performance/Shapes.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.performance; 2 | 3 | import net.minecraft.util.shape.VoxelShape; 4 | 5 | public record Shapes(VoxelShape solid, VoxelShape liquid) { 6 | 7 | public VoxelShape getSolid() { 8 | return this.solid; 9 | } 10 | public VoxelShape getLiquid() { 11 | return this.liquid; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/resources/soundphysics.mixins.json: -------------------------------------------------------------------------------- 1 | { 2 | "required": true, 3 | "minVersion": "0.8.2", 4 | "package": "com.sonicether.soundphysics.mixin", 5 | "compatibilityLevel": "JAVA_17", 6 | "mixins": [ 7 | "server.EntityMixin", 8 | "server.ReloadCommandMixin", 9 | "server.ServerWorldMixin" 10 | ], 11 | "client": [ 12 | "RendererMixin", 13 | "SoundSystemMixin", 14 | "SourceMixin", 15 | "WorldChunkMixin", 16 | "WorldChunkMixin$Unloaded" 17 | ], 18 | "injectors": { 19 | "defaultRequire": 1 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Done to increase the memory available to gradle. 2 | org.gradle.jvmargs=-Xmx4G 3 | # Fabric Properties 4 | # check this on https://fabricmc.net/versions.html 5 | minecraft_version=1.18.1 6 | yarn_mappings=1.18.1+build.2 7 | loader_version=0.12.12 8 | # Mod Properties 9 | mod_version=0.5.5 10 | maven_group=com.soniether 11 | archives_base_name=soundphysics 12 | # Dependencies 13 | # check this on https://fabricmc.net/versions.html 14 | fabric_version=0.44.0+1.18 15 | # https://www.curseforge.com/minecraft/mc-mods/cloth-config/files 16 | cloth_config_version=6.1.48 17 | # https://www.curseforge.com/minecraft/mc-mods/modmenu/files 18 | mod_menu_version=3.0.0 19 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/config/BlueTapePack/mixin/GuiRegistriesAccessorMixin.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.config.BlueTapePack.mixin; 2 | 3 | import me.shedaniel.autoconfig.AutoConfig; 4 | import me.shedaniel.autoconfig.ConfigData; 5 | import me.shedaniel.autoconfig.gui.registry.GuiRegistry; 6 | import org.spongepowered.asm.mixin.Mixin; 7 | import org.spongepowered.asm.mixin.gen.Accessor; 8 | 9 | import java.util.Map; 10 | 11 | @Mixin(AutoConfig.class) 12 | public interface GuiRegistriesAccessorMixin { 13 | @Accessor(value = "guiRegistries", remap = false) 14 | static Map, GuiRegistry> getGuiRegistries() { 15 | throw new AssertionError(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/config/BlueTapePack/ModMenuIntegration.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.config.BlueTapePack; 2 | 3 | import com.sonicether.soundphysics.config.SoundPhysicsConfig; 4 | import com.terraformersmc.modmenu.api.ConfigScreenFactory; 5 | import com.terraformersmc.modmenu.api.ModMenuApi; 6 | import me.shedaniel.autoconfig.AutoConfig; 7 | import net.fabricmc.api.EnvType; 8 | import net.fabricmc.api.Environment; 9 | 10 | @SuppressWarnings({"unused", "overrides", "deprecated"}) 11 | @Environment(EnvType.CLIENT) 12 | public class ModMenuIntegration implements ModMenuApi 13 | { 14 | 15 | @Override 16 | public ConfigScreenFactory getModConfigScreenFactory() { 17 | return screen -> AutoConfig.getConfigScreen(SoundPhysicsConfig.class, screen).get(); 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/mixin/server/ReloadCommandMixin.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.mixin.server; 2 | 3 | import com.sonicether.soundphysics.config.BlueTapePack.ConfigManager; 4 | import net.minecraft.server.command.ReloadCommand; 5 | import org.spongepowered.asm.mixin.Mixin; 6 | import org.spongepowered.asm.mixin.injection.At; 7 | import org.spongepowered.asm.mixin.injection.Inject; 8 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; 9 | 10 | @Mixin(ReloadCommand.class) 11 | public class ReloadCommandMixin { 12 | @Inject(method = "method_13530(Lcom/mojang/brigadier/context/CommandContext;)I", at = @At("HEAD"), remap = false) 13 | private static void reloadConfigHook(CallbackInfoReturnable cir) { 14 | ConfigManager.reload(true); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/config/MaterialData.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.config; 2 | 3 | @SuppressWarnings("CanBeFinal") 4 | public class MaterialData { 5 | public String example; 6 | public double reflectivity; 7 | public double absorption; 8 | 9 | public MaterialData(String s, double r, double a){ 10 | reflectivity = r; absorption = a; example = s; 11 | } 12 | 13 | public MaterialData(double r, double a){ 14 | reflectivity = r; absorption = a; example = null; 15 | } 16 | 17 | @SuppressWarnings("unused") 18 | public MaterialData() { reflectivity = 0; absorption = 1; example = ""; } 19 | 20 | public String getExample() {return example;} 21 | public double getReflectivity() {return reflectivity;} 22 | public double getAbsorption() {return absorption;} 23 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Sound Physics Fabric 2 | 3 | **!!! REQUIRES Cloth Config !!!** 4 | 5 | If you have a question about the mod, feel free to start a Q&A in the Discussions tab. 6 | 7 | Sound Physics Fabric is a Minecraft mod that uses efficient ray tracing to calculate realistic sound attenuation, reverberation, and absorption through blocks. It is fully configurable and new features are being developed all the time. Sound Physics Fabric also integrates with the [Plasmo Voice](https://github.com/plasmoapp/plasmo-voice) mod for the ultimate immersive voice chat experience. I encourage you to share your favourite config [here](https://github.com/vlad2305m/Sound-Physics-Fabric/discussions/2) for me to create config presets for the mod. 8 | 9 | Ported to 1.17 fabric and maintained by vlad2305m, featuring some improvements and contributions by daipenjer, henkelmax and thedocruby. 10 | 11 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/mixin/server/ServerWorldMixin.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.mixin.server; 2 | 3 | import net.minecraft.server.world.ServerWorld; 4 | import org.spongepowered.asm.mixin.Mixin; 5 | import org.spongepowered.asm.mixin.injection.At; 6 | import org.spongepowered.asm.mixin.injection.ModifyArg; 7 | 8 | import static com.sonicether.soundphysics.config.PrecomputedConfig.soundDistanceAllowance; 9 | 10 | @Mixin(ServerWorld.class) 11 | public class ServerWorldMixin { 12 | 13 | @ModifyArg(method = {"playSound","playSoundFromEntity"}, at = @At(value = "INVOKE", target = "net/minecraft/server/PlayerManager.sendToAround (Lnet/minecraft/entity/player/PlayerEntity;DDDDLnet/minecraft/util/registry/RegistryKey;Lnet/minecraft/network/Packet;)V"),index = 4) 14 | private double SoundDistanceModifierInjector(double d){ 15 | return d * soundDistanceAllowance; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/mixin/RendererMixin.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.mixin; 2 | 3 | import com.sonicether.soundphysics.RaycastRenderer; 4 | import net.minecraft.client.MinecraftClient; 5 | import net.minecraft.client.render.VertexConsumerProvider; 6 | import net.minecraft.client.render.debug.DebugRenderer; 7 | import net.minecraft.client.util.math.MatrixStack; 8 | import org.spongepowered.asm.mixin.Mixin; 9 | import org.spongepowered.asm.mixin.injection.At; 10 | import org.spongepowered.asm.mixin.injection.Inject; 11 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 12 | 13 | @Mixin(DebugRenderer.class) 14 | public class RendererMixin { 15 | 16 | @Inject(method = "render(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider$Immediate;DDD)V", at = @At("HEAD")) 17 | private void onDrawBlockOutline(MatrixStack matrices, VertexConsumerProvider.Immediate vertexConsumers, double cameraX, double cameraY, double cameraZ, CallbackInfo ci) { 18 | RaycastRenderer.renderRays(cameraX, cameraY, cameraZ, MinecraftClient.getInstance().world); 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /src/main/resources/fabric.mod.json: -------------------------------------------------------------------------------- 1 | { 2 | "schemaVersion": 1, 3 | "id": "soundphysics", 4 | "version": "${version}", 5 | "name": "Sound Physics", 6 | "description": "Provides realistic sound attenuation, reverberation, and absorption through blocks using physically-based raytraced audio shaders.", 7 | "authors": ["Sonic Ether","vlad2305m","Dr. Rubisco"], 8 | "contact": { 9 | "sources": "https://github.com/vlad2305m/Sound-Physics-Fabric", 10 | "issues": "https://github.com/vlad2305m/Sound-Physics-Fabric/issues" 11 | }, 12 | "license": "GPL", 13 | "icon": "assets/soundphysics/icon.png", 14 | "environment": "*", 15 | "entrypoints": { 16 | "main": [ 17 | "com.sonicether.soundphysics.SoundPhysicsMod" 18 | ], 19 | "modmenu": [ 20 | "com.sonicether.soundphysics.config.BlueTapePack.ModMenuIntegration" 21 | ] 22 | }, 23 | "mixins": [ 24 | "soundphysics.mixins.json", 25 | "bluetapepack.mixins.json" 26 | ], 27 | "depends": { 28 | "cloth-config2": ">=6.0.0", 29 | "fabricloader": ">=0.12.11", 30 | "minecraft": "1.18.x" 31 | }, 32 | "suggests": { 33 | "modmenu": ">=3.0.0" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/config/BlueTapePack/mixin/NestedListSaveContentMixin.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.config.BlueTapePack.mixin; 2 | 3 | import me.shedaniel.clothconfig2.api.ReferenceProvider; 4 | import me.shedaniel.clothconfig2.gui.entries.AbstractListListEntry; 5 | import me.shedaniel.clothconfig2.gui.entries.NestedListListEntry; 6 | import net.minecraft.text.Text; 7 | import org.spongepowered.asm.mixin.Final; 8 | import org.spongepowered.asm.mixin.Mixin; 9 | import org.spongepowered.asm.mixin.Shadow; 10 | 11 | import java.util.List; 12 | import java.util.function.BiFunction; 13 | import java.util.function.Consumer; 14 | import java.util.function.Supplier; 15 | 16 | @SuppressWarnings("ALL") 17 | @Mixin(NestedListListEntry.class) 18 | public abstract class NestedListSaveContentMixin extends AbstractListListEntry { 19 | @Shadow @Final private List> referencableEntries; 20 | 21 | public NestedListSaveContentMixin(Text fieldName, List value, boolean defaultExpanded, Supplier tooltipSupplier, Consumer saveConsumer, Supplier defaultValue, Text resetButtonKey, boolean requiresRestart, boolean deleteButtonEnabled, boolean insertInFront, BiFunction createNewCell) { 22 | super(fieldName, value, defaultExpanded, tooltipSupplier, saveConsumer, defaultValue, resetButtonKey, requiresRestart, deleteButtonEnabled, insertInFront, createNewCell); 23 | } 24 | 25 | @Override 26 | public void save(){ 27 | try { 28 | referencableEntries.forEach((e) -> e.provideReferenceEntry().save()); 29 | } catch (Exception ignored) {} 30 | super.save(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/mixin/server/EntityMixin.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.mixin.server; 2 | 3 | import net.minecraft.entity.Entity; 4 | import net.minecraft.entity.player.PlayerEntity; 5 | import net.minecraft.sound.SoundCategory; 6 | import net.minecraft.sound.SoundEvent; 7 | import org.jetbrains.annotations.Nullable; 8 | import org.spongepowered.asm.mixin.Mixin; 9 | import org.spongepowered.asm.mixin.Shadow; 10 | import org.spongepowered.asm.mixin.injection.At; 11 | import org.spongepowered.asm.mixin.injection.ModifyArg; 12 | 13 | import java.util.regex.Pattern; 14 | 15 | @Mixin(Entity.class) 16 | public class EntityMixin { 17 | 18 | @Shadow @SuppressWarnings("SameReturnValue") 19 | public float getStandingEyeHeight(){return 0.0f;} 20 | 21 | @ModifyArg(method = "playSound", at = @At(value = "INVOKE", target = "net/minecraft/world/World.playSound (Lnet/minecraft/entity/player/PlayerEntity;DDDLnet/minecraft/sound/SoundEvent;Lnet/minecraft/sound/SoundCategory;FF)V"), index = 2) 22 | private double EyeHeightOffsetInjector(@Nullable PlayerEntity player, double x, double y, double z, SoundEvent sound, SoundCategory category, float volume, float pitch) { 23 | return y + calculateEntitySoundOffset(getStandingEyeHeight(),sound); 24 | } 25 | 26 | private static final Pattern stepPattern = Pattern.compile(".*step.*"); 27 | private static double calculateEntitySoundOffset(float standingEyeHeight, SoundEvent sound) 28 | { 29 | if (stepPattern.matcher(sound.getId().getPath()).matches()) 30 | { 31 | return 0.01; 32 | } 33 | return standingEyeHeight; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/SPLog.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics; 2 | 3 | import org.lwjgl.openal.AL10; 4 | 5 | public class SPLog { 6 | 7 | private static final String logPrefix = "[SOUND PHYSICS]"; 8 | public static void log(String message) 9 | { 10 | System.out.println(logPrefix + ": " + message); 11 | } 12 | 13 | protected static void logOcclusion(String message) {System.out.println(logPrefix + " [OCCLUSION] " + ": " + message);} 14 | 15 | protected static void logEnvironment(String message) {System.out.println(logPrefix + " [ENVIRONMENT] " + ": " + message);} 16 | 17 | public static void logGeneral(String message) {System.out.println(logPrefix + ": " + message);} 18 | 19 | public static void logError(String errorMessage) 20 | { 21 | System.out.println(logPrefix + " [ERROR]: " + errorMessage); 22 | } 23 | 24 | public static void checkErrorLog(final String errorMessage) 25 | { 26 | final int error = AL10.alGetError(); 27 | if (error == AL10.AL_NO_ERROR) { 28 | return; 29 | } 30 | 31 | String errorName; 32 | 33 | errorName = switch (error) { 34 | case AL10.AL_INVALID_NAME -> "AL_INVALID_NAME"; 35 | case AL10.AL_INVALID_ENUM -> "AL_INVALID_ENUM"; 36 | case AL10.AL_INVALID_VALUE -> "AL_INVALID_VALUE"; 37 | case AL10.AL_INVALID_OPERATION -> "AL_INVALID_OPERATION"; 38 | case AL10.AL_OUT_OF_MEMORY -> "AL_OUT_OF_MEMORY"; 39 | default -> Integer.toString(error); 40 | }; 41 | 42 | logError(errorMessage + " OpenAL error " + errorName); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/performance/SPHitResult.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.performance; 2 | 3 | import net.minecraft.block.BlockState; 4 | import net.minecraft.util.hit.BlockHitResult; 5 | import net.minecraft.util.hit.HitResult; 6 | import net.minecraft.util.math.BlockPos; 7 | import net.minecraft.util.math.Direction; 8 | import net.minecraft.util.math.Vec3d; 9 | import net.minecraft.world.chunk.WorldChunk; 10 | 11 | public class SPHitResult extends HitResult { 12 | private final Direction side; 13 | private final BlockPos blockPos; 14 | private final boolean missed; 15 | private final BlockState blockState; 16 | public final WorldChunk chunk; 17 | 18 | public static SPHitResult createMissed(Vec3d pos, Direction side, BlockPos blockPos, WorldChunk c) { 19 | return new SPHitResult(true, pos, side, blockPos, null, c); 20 | } 21 | 22 | public SPHitResult(BlockHitResult blockHitResult, BlockState bs, WorldChunk c) { 23 | super(blockHitResult.getPos()); 24 | this.missed = false;//blockHitResult.getType() == Type.MISS; 25 | this.side = blockHitResult.getSide(); 26 | this.blockPos = blockHitResult.getBlockPos(); 27 | this.blockState = bs; 28 | this.chunk = c; 29 | } 30 | 31 | public SPHitResult(boolean missed, Vec3d pos, Direction side, BlockPos blockPos, BlockState bs, WorldChunk c) { 32 | super(pos); 33 | this.missed = missed; 34 | this.side = side; 35 | this.blockPos = blockPos; 36 | this.blockState = bs; 37 | this.chunk = c; 38 | } 39 | public static SPHitResult get(BlockHitResult bhr, BlockState bs, WorldChunk c){ 40 | if (bhr == null) return null; 41 | return new SPHitResult(bhr, bs, c); 42 | } 43 | 44 | public BlockPos getBlockPos() {return this.blockPos;} 45 | public Direction getSide() {return this.side;} 46 | @Deprecated 47 | public Type getType() {return this.missed ? Type.MISS : Type.BLOCK;} 48 | public boolean isMissed() {return this.missed;} 49 | public BlockState getBlockState() {return blockState;} 50 | } -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/mixin/SourceMixin.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.mixin; 2 | 3 | import com.sonicether.soundphysics.SPLog; 4 | import com.sonicether.soundphysics.SourceAccessor; 5 | import com.sonicether.soundphysics.config.BlueTapePack.ConfigManager; 6 | import com.sonicether.soundphysics.SoundPhysics; 7 | import net.minecraft.client.sound.Source; 8 | import net.minecraft.sound.SoundCategory; 9 | import net.minecraft.util.math.Vec3d; 10 | import org.spongepowered.asm.mixin.Final; 11 | import org.spongepowered.asm.mixin.Mixin; 12 | import org.spongepowered.asm.mixin.Shadow; 13 | import org.spongepowered.asm.mixin.injection.At; 14 | import org.spongepowered.asm.mixin.injection.Inject; 15 | import org.spongepowered.asm.mixin.injection.ModifyArg; 16 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 17 | 18 | 19 | @Mixin(Source.class) 20 | public class SourceMixin implements SourceAccessor { 21 | 22 | @Shadow 23 | @Final 24 | private int pointer; 25 | 26 | private Vec3d pos; 27 | 28 | @Inject(method = "setPosition", at = @At("HEAD")) 29 | private void SoundPosStealer(Vec3d poss, CallbackInfo ci) {this.pos = poss;} 30 | 31 | @Inject(method = "play", at = @At("HEAD")) 32 | private void OnPlaySoundInjector(CallbackInfo ci) { 33 | SoundPhysics.onPlaySoundReverb(pos.x, pos.y, pos.z, pointer, false); 34 | SPLog.checkErrorLog("onplayinjector"); 35 | } 36 | 37 | // For sounds unchanged by evaluation (noteblocks, menu, ui) 38 | @ModifyArg(method = "setAttenuation", at = @At(value = "INVOKE", target = "org/lwjgl/openal/AL10.alSourcef (IIF)V", ordinal = 0, remap = false), index = 2) 39 | private float AttenuationHijack(int pointer2, int param_id, float attenuation) { 40 | if (param_id != 4131) throw new IllegalArgumentException("Tried modifying wrong field. No attenuation here."); 41 | return attenuation / (float)(ConfigManager.getConfig().General.attenuationFactor); 42 | } 43 | 44 | public void calculateReverb(SoundCategory category, String name) { 45 | SoundPhysics.setLastSoundCategoryAndName(category, name); 46 | SoundPhysics.onPlaySoundReverb(pos.x, pos.y, pos.z, pointer, false); 47 | SPLog.checkErrorLog("onRecalculate"); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/mixin/SoundSystemMixin.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.mixin; 2 | 3 | import com.sonicether.soundphysics.ALstuff.SPEfx; 4 | import com.sonicether.soundphysics.SoundPhysics; 5 | import com.sonicether.soundphysics.SourceAccessor; 6 | import com.sonicether.soundphysics.config.PrecomputedConfig; 7 | import net.minecraft.client.sound.*; 8 | import net.minecraft.sound.SoundCategory; 9 | import net.minecraft.util.Identifier; 10 | import org.objectweb.asm.Opcodes; 11 | import org.spongepowered.asm.mixin.Mixin; 12 | import org.spongepowered.asm.mixin.injection.At; 13 | import org.spongepowered.asm.mixin.injection.Inject; 14 | import org.spongepowered.asm.mixin.injection.ModifyArg; 15 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 16 | import org.spongepowered.asm.mixin.injection.callback.LocalCapture; 17 | 18 | import java.util.Iterator; 19 | import java.util.Map; 20 | 21 | import static com.sonicether.soundphysics.SoundPhysics.mc; 22 | import static com.sonicether.soundphysics.config.PrecomputedConfig.pC; 23 | 24 | @Mixin(SoundSystem.class) 25 | public class SoundSystemMixin { 26 | 27 | @Inject(method = "start", at = @At(value = "INVOKE", target = "net/minecraft/client/sound/SoundListener.init ()V")) 28 | private void SoundPhysicsInitInjector(CallbackInfo ci){ 29 | SoundPhysics.init(); 30 | } 31 | 32 | @Inject(method = "play(Lnet/minecraft/client/sound/SoundInstance;)V", at = @At(value = "FIELD", target = "net/minecraft/client/sound/SoundSystem.sounds : Lcom/google/common/collect/Multimap;"), locals = LocalCapture.CAPTURE_FAILHARD) 33 | private void SoundInfoStealer(SoundInstance sound, CallbackInfo ci, WeightedSoundSet weightedSoundSet, Identifier identifier, Sound sound2, float f, float g, SoundCategory soundCategory){ 34 | SoundPhysics.setLastSoundCategoryAndName(soundCategory, sound.getId().getPath()); 35 | } 36 | 37 | @Inject(method = "tick()V", at = @At(value = "HEAD")) 38 | private void Ticker(CallbackInfo ci){SPEfx.updateSmoothedRain();} 39 | 40 | @ModifyArg(method = "getAdjustedVolume", at = @At(value = "INVOKE", target = "net/minecraft/util/math/MathHelper.clamp (FFF)F"), index = 0) 41 | private float VolumeMultiplierInjector(float vol){ 42 | return vol * PrecomputedConfig.globalVolumeMultiplier; 43 | } 44 | @SuppressWarnings("InvalidInjectorMethodSignature") 45 | @Inject(method = "tick()V", at = @At(value = "JUMP", opcode = Opcodes.IFEQ, ordinal = 3), locals = LocalCapture.CAPTURE_FAILHARD) 46 | private void recalculate(CallbackInfo ci, Iterator iterator, Map.Entry entry, Channel.SourceManager f, SoundInstance g, float vec3d){ 47 | if (mc.world != null && mc.world.getTime()%pC.continuousRefreshRate==0){ 48 | f.run((s) -> ((SourceAccessor)s).calculateReverb(g.getCategory(), g.getId().getPath())); 49 | } 50 | //((SourceAccessor)null) 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/config/BlueTapePack/GuiRegistryinit.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.config.BlueTapePack; 2 | 3 | import com.sonicether.soundphysics.config.SoundPhysicsConfig; 4 | import me.shedaniel.autoconfig.ConfigData; 5 | import me.shedaniel.autoconfig.gui.registry.GuiRegistry; 6 | import me.shedaniel.autoconfig.gui.registry.api.GuiRegistryAccess; 7 | import me.shedaniel.autoconfig.util.Utils; 8 | import me.shedaniel.clothconfig2.api.AbstractConfigListEntry; 9 | import me.shedaniel.clothconfig2.gui.entries.MultiElementListEntry; 10 | import me.shedaniel.clothconfig2.gui.entries.NestedListListEntry; 11 | import net.minecraft.text.LiteralText; 12 | import net.minecraft.text.TranslatableText; 13 | 14 | import java.lang.reflect.ParameterizedType; 15 | import java.util.*; 16 | import java.util.function.Supplier; 17 | import java.util.stream.Collectors; 18 | 19 | import static com.sonicether.soundphysics.config.BlueTapePack.mixin.GuiRegistriesAccessorMixin.getGuiRegistries; 20 | 21 | @SuppressWarnings("ALL") // its the blue tape after all 22 | public class GuiRegistryinit { 23 | public static void register() { 24 | Map, GuiRegistry> guiRegistries = getGuiRegistries(); 25 | GuiRegistry registry = new GuiRegistry(); 26 | 27 | 28 | 29 | registry.registerPredicateProvider((i13n, field, config, defaults, registry1) -> { 30 | List configValue = new ArrayList<>(((Map) Utils.getUnsafely(field, config)).values()); 31 | Class fieldTypeParam = (Class)((ParameterizedType)field.getGenericType()).getActualTypeArguments()[1]; 32 | Object defaultElemValue = Utils.constructUnsafely(fieldTypeParam); 33 | String remainingI13n = i13n.substring(0, i13n.indexOf(".option") + ".option".length()); 34 | String classI13n = String.format("%s.%s", remainingI13n, fieldTypeParam.getSimpleName()); 35 | return Collections.singletonList(new NestedListListEntry(new TranslatableText(i13n), configValue, false, (Supplier)null, (abstractConfigListEntries) -> { 36 | }, () -> { 37 | Map ll = (Map) Utils.getUnsafely(field, defaults); 38 | return ll == null ? List.of() : new ArrayList<>(ll.values()); 39 | }, new LiteralText(""), false, true, (elem, nestedListListEntry) -> { 40 | if (elem == null) { 41 | Object newDefaultElemValue = Utils.constructUnsafely(fieldTypeParam); 42 | return new MultiElementListEntry(new TranslatableText(classI13n), newDefaultElemValue, getChildren(classI13n, fieldTypeParam, newDefaultElemValue, defaultElemValue, registry1), true); 43 | } else { 44 | return new MultiElementListEntry(new TranslatableText(classI13n), elem, getChildren(classI13n, fieldTypeParam, elem, defaultElemValue, registry1), true); 45 | 46 | } 47 | })); 48 | }, (field) -> Map.class.isAssignableFrom(field.getType())); 49 | 50 | 51 | 52 | guiRegistries.put(SoundPhysicsConfig.class, registry); 53 | } 54 | 55 | @SuppressWarnings("unchecked") 56 | private static List> getChildren(String i13n, Class fieldType, Object iConfig, Object iDefaults, GuiRegistryAccess guiProvider) { 57 | 58 | return (List) Arrays.stream(fieldType.getDeclaredFields()).map((iField) -> { 59 | String iI13n = String.format("%s.%s", i13n, iField.getName()); 60 | return guiProvider.getAndTransform(iI13n, iField, iConfig, iDefaults, guiProvider); 61 | }).filter(Objects::nonNull).flatMap(Collection::stream).collect(Collectors.toList()); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/resources/assets/soundphysics/lang/en_us.json: -------------------------------------------------------------------------------- 1 | { 2 | "text.autoconfig.sound_physics.title": "Sound Physics Config", 3 | 4 | "text.autoconfig.sound_physics.option.enabled": "Enable rendering", 5 | 6 | "text.autoconfig.sound_physics.option.General": "General options:", 7 | "text.autoconfig.sound_physics.option.Performance": "Performance options:", 8 | "text.autoconfig.sound_physics.option.Materials": "Materials:", 9 | "text.autoconfig.sound_physics.option.Vlads_Tweaks": "Vlad's tweaks:", 10 | "text.autoconfig.sound_physics.option.Misc": "Logging options:", 11 | 12 | "text.autoconfig.sound_physics.option.General.attenuationFactor": "Attenuation (fade over distance) factor", 13 | "text.autoconfig.sound_physics.option.General.globalReverbGain": "Reverb volume gain", 14 | "text.autoconfig.sound_physics.option.General.globalReverbBrightness": "Reverb brightness", 15 | "text.autoconfig.sound_physics.option.General.globalBlockAbsorption": "Block passthrough sound absorption", 16 | "text.autoconfig.sound_physics.option.General.globalBlockReflectance": "Block reflectance multiplier", 17 | "text.autoconfig.sound_physics.option.General.soundDistanceAllowance": "Sound max distance multiplier", 18 | "text.autoconfig.sound_physics.option.General.airAbsorption": "Sound absorption by air", 19 | "text.autoconfig.sound_physics.option.General.humidityAbsorption": "Sound absorption by humidity", 20 | "text.autoconfig.sound_physics.option.General.rainAbsorption": "Sound absorption by rain drops", 21 | "text.autoconfig.sound_physics.option.General.underwaterFilter": "Underwater filter strength", 22 | 23 | "text.autoconfig.sound_physics.option.Performance.skipRainOcclusionTracing": "Skip tracing for rain sounds", 24 | "text.autoconfig.sound_physics.option.Performance.environmentEvaluationRays": "Rays per sound", 25 | "text.autoconfig.sound_physics.option.Performance.environmentEvaluationRayBounces": "Reflections per ray", 26 | "text.autoconfig.sound_physics.option.Performance.simplerSharedAirspaceSimulation": "Cheap shared airspace detection", 27 | 28 | "text.autoconfig.sound_physics.option.Materials.materialProperties": "Material Properties", 29 | "text.autoconfig.sound_physics.option.Materials.blockWhiteList": "Block Whitelist", 30 | 31 | "text.autoconfig.sound_physics.option.Vlads_Tweaks.recordsDisable": "Skip Jukebox/Note Block occlusion", 32 | "text.autoconfig.sound_physics.option.Vlads_Tweaks.continuousRefreshRate": "Continuous sources refresh interval", 33 | "text.autoconfig.sound_physics.option.Vlads_Tweaks.maxDirectOcclusionFromBlocks": "Maximum direct occlusion", 34 | "text.autoconfig.sound_physics.option.Vlads_Tweaks._9RayDirectOcclusion": "9 ray direct occlusion calculation", 35 | "text.autoconfig.sound_physics.option.Vlads_Tweaks.soundDirectionEvaluation": "Re-calculate sound direction", 36 | "text.autoconfig.sound_physics.option.Vlads_Tweaks.directRaysDirEvalMultiplier": "Sound reflection bias", 37 | "text.autoconfig.sound_physics.option.Vlads_Tweaks.notOccludedNoRedirect": "Skip redirecting visible blocks", 38 | 39 | "text.autoconfig.sound_physics.option.Misc.debugLogging": "Logging", 40 | "text.autoconfig.sound_physics.option.Misc.occlusionLogging": "Occlusion logging", 41 | "text.autoconfig.sound_physics.option.Misc.environmentLogging": "Environment logging", 42 | "text.autoconfig.sound_physics.option.Misc.performanceLogging": "Performance logging", 43 | "text.autoconfig.sound_physics.option.Misc.raytraceParticles": "Raytracing Particles", 44 | 45 | "text.autoconfig.sound_physics.option.preset": "Preset", 46 | 47 | "text.autoconfig.sound_physics.option.MaterialData": "Set material properties:", 48 | "text.autoconfig.sound_physics.option.MaterialData.example": "Material", 49 | "text.autoconfig.sound_physics.option.MaterialData.reflectivity": "Reflectivity", 50 | "text.autoconfig.sound_physics.option.MaterialData.absorption": "Occlusion density" 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/RaycastRenderer.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics; 2 | 3 | import com.mojang.blaze3d.systems.RenderSystem; 4 | import net.minecraft.client.render.*; 5 | import net.minecraft.util.math.Vec3d; 6 | import net.minecraft.world.World; 7 | import static com.sonicether.soundphysics.config.PrecomputedConfig.pC; 8 | 9 | import java.util.ArrayList; 10 | import java.util.Collections; 11 | import java.util.List; 12 | 13 | public class RaycastRenderer { 14 | 15 | private static final List rays = Collections.synchronizedList(new ArrayList<>()); 16 | 17 | public static void renderRays(double x, double y, double z, World world) { 18 | if (world == null) { 19 | return; 20 | } 21 | // ψ Get the name of the block you are standing on ψ 22 | //world.getPlayers().forEach((p) -> p.sendMessage(new LiteralText(world.getBlockState(p.getBlockPos().add(0,-1,0)).getBlock().getTranslationKey()),true)); 23 | long gameTime = world.getTime(); 24 | synchronized (rays) { 25 | for (Ray ray : rays) { 26 | if (ray.tickCreated == -1) ray.tickCreated = gameTime; 27 | renderRay(ray, x, y, z); 28 | } 29 | rays.removeIf(ray -> (gameTime - ray.tickCreated) > ray.lifespan || (gameTime - ray.tickCreated) < 0L); 30 | } 31 | } 32 | 33 | public static void addSoundBounceRay(Vec3d start, Vec3d end, int color) { 34 | if (!pC.dRays) { 35 | return; 36 | } 37 | addRay(start, end, color, false); 38 | } 39 | 40 | public static void addOcclusionRay(Vec3d start, Vec3d end, int color) { 41 | if (!pC.dRays) { 42 | return; 43 | } 44 | addRay(start, end, color, true); 45 | } 46 | 47 | public static void addRay(Vec3d start, Vec3d end, int color, boolean throughWalls) { 48 | synchronized (rays) { 49 | rays.add(new Ray(start, end, color, throughWalls)); 50 | } 51 | } 52 | 53 | public static void renderRay(Ray ray, double x, double y, double z) { 54 | int red = getRed(ray.color); 55 | int green = getGreen(ray.color); 56 | int blue = getBlue(ray.color); 57 | 58 | if (!ray.throughWalls) { 59 | RenderSystem.enableDepthTest(); 60 | } 61 | RenderSystem.setShader(GameRenderer::getPositionColorShader); 62 | Tessellator tessellator = Tessellator.getInstance(); 63 | BufferBuilder bufferBuilder = tessellator.getBuffer(); 64 | RenderSystem.disableTexture(); 65 | RenderSystem.disableBlend(); 66 | RenderSystem.lineWidth(ray.throughWalls ? 3F : 0.25F); 67 | 68 | bufferBuilder.begin(VertexFormat.DrawMode.DEBUG_LINE_STRIP, VertexFormats.POSITION_COLOR); 69 | 70 | bufferBuilder.vertex(ray.start.x - x, ray.start.y - y, ray.start.z - z).color(red, green, blue, 255).next(); 71 | bufferBuilder.vertex(ray.end.x - x, ray.end.y - y, ray.end.z - z).color(red, green, blue, 255).next(); 72 | 73 | tessellator.draw(); 74 | RenderSystem.lineWidth(1F); 75 | RenderSystem.enableBlend(); 76 | RenderSystem.enableTexture(); 77 | } 78 | 79 | private static int getRed(int argb) { 80 | return (argb >> 16) & 0xFF; 81 | } 82 | 83 | private static int getGreen(int argb) { 84 | return (argb >> 8) & 0xFF; 85 | } 86 | 87 | private static int getBlue(int argb) { 88 | return argb & 0xFF; 89 | } 90 | 91 | private static class Ray { 92 | private final Vec3d start; 93 | private final Vec3d end; 94 | private final int color; 95 | private long tickCreated; 96 | private final long lifespan; 97 | private final boolean throughWalls; 98 | 99 | public Ray(Vec3d start, Vec3d end, int color, boolean throughWalls) { 100 | this.start = start; 101 | this.end = end; 102 | this.color = color; 103 | this.throughWalls = throughWalls; 104 | this.tickCreated = -1; 105 | this.lifespan = 20 * 2; 106 | } 107 | } 108 | 109 | } -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/config/BlueTapePack/ConfigManager.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.config.BlueTapePack; 2 | 3 | import com.sonicether.soundphysics.ALstuff.SPEfx; 4 | import com.sonicether.soundphysics.SPLog; 5 | import com.sonicether.soundphysics.SoundPhysicsMod; 6 | import com.sonicether.soundphysics.config.MaterialData; 7 | import com.sonicether.soundphysics.config.PrecomputedConfig; 8 | import com.sonicether.soundphysics.config.SoundPhysicsConfig; 9 | import com.sonicether.soundphysics.config.presets.ConfigPresets; 10 | import me.shedaniel.autoconfig.AutoConfig; 11 | import me.shedaniel.autoconfig.ConfigHolder; 12 | import me.shedaniel.autoconfig.serializer.JanksonConfigSerializer; 13 | import net.minecraft.util.ActionResult; 14 | 15 | import java.util.HashMap; 16 | import java.util.List; 17 | import java.util.Map; 18 | import java.util.Objects; 19 | import java.util.stream.Collectors; 20 | 21 | public class ConfigManager { 22 | private static ConfigHolder holder; 23 | 24 | public static final SoundPhysicsConfig DEFAULT = new SoundPhysicsConfig(){{ 25 | Map map = 26 | SoundPhysicsMod.blockSoundGroups.entrySet().stream() 27 | .collect(Collectors.toMap((e)-> e.getValue().getLeft(), (e) -> new MaterialData(e.getValue().getRight(), 0.5, 0.5))); 28 | map.putIfAbsent("DEFAULT", new MaterialData(SoundPhysicsMod.groupMap.get("DEFAULT"), 0.5, 0.5)); 29 | Materials.materialProperties = map; 30 | }}; 31 | 32 | public static void registerAutoConfig() { 33 | if (holder != null) {throw new IllegalStateException("Configuration already registered");} 34 | holder = AutoConfig.register(SoundPhysicsConfig.class, JanksonConfigSerializer::new); 35 | 36 | try {GuiRegistryinit.register();} catch (Throwable ignored){SPLog.logError("Failed to register config menu unwrappers. Edit config that isn't working in the config file");} 37 | 38 | holder.registerSaveListener((holder, config) -> onSave(config)); 39 | holder.registerLoadListener((holder, config) -> onSave(config)); 40 | reload(true); 41 | } 42 | 43 | public static SoundPhysicsConfig getConfig() { 44 | if (holder == null) {return DEFAULT;} 45 | 46 | return holder.getConfig(); 47 | } 48 | 49 | public static void reload(boolean load) { 50 | if (holder == null) {return;} 51 | 52 | if(load) holder.load(); 53 | holder.getConfig().preset.setConfig(); 54 | SPEfx.syncReverbParams(); 55 | holder.save(); 56 | } 57 | 58 | public static void save() { if (holder == null) {registerAutoConfig();} else {holder.save();} } 59 | 60 | public static void handleBrokenMaterials( SoundPhysicsConfig c ){ 61 | SPLog.logError("Critical materialProperties error. Resetting materialProperties"); 62 | SoundPhysicsConfig fallback = DEFAULT; 63 | ConfigPresets.RESET_MATERIALS.configChanger.accept(fallback); 64 | c.Materials.materialProperties = fallback.Materials.materialProperties; 65 | c.Materials.blockWhiteList = List.of("block.minecraft.water"); 66 | } 67 | 68 | public static void handleUnstableConfig( SoundPhysicsConfig c ){ 69 | SPLog.logError("Error: Config file is not from a compatible version! Resetting the config..."); 70 | ConfigPresets.DEFAULT_PERFORMANCE.configChanger.accept(c); 71 | ConfigPresets.RESET_MATERIALS.configChanger.accept(c); 72 | c.version = "0.5.5"; 73 | } 74 | 75 | public static ActionResult onSave(SoundPhysicsConfig c) { 76 | if (c.Materials.materialProperties == null || c.Materials.materialProperties.get("DEFAULT") == null) handleBrokenMaterials(c); 77 | if (c.preset != ConfigPresets.LOAD_SUCCESS) c.preset.configChanger.accept(c); 78 | if (c.version == null || !Objects.equals(c.version, "0.5.5")) handleUnstableConfig(c); 79 | if(PrecomputedConfig.pC != null) PrecomputedConfig.pC.deactivate(); 80 | try {PrecomputedConfig.pC = new PrecomputedConfig(c);} catch (CloneNotSupportedException e) {e.printStackTrace(); return ActionResult.FAIL;} 81 | SPEfx.syncReverbParams(); 82 | return ActionResult.SUCCESS; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/performance/LiquidStorage.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.performance; 2 | 3 | import com.sonicether.soundphysics.SPLog; 4 | import net.minecraft.block.Block; 5 | import net.minecraft.block.Blocks; 6 | import net.minecraft.world.chunk.WorldChunk; 7 | import org.apache.commons.lang3.ArrayUtils; 8 | 9 | import java.util.Set; 10 | 11 | /* 12 | Data structure to detect if a desired block is the medium for sound. 13 | 14 | Should attach to every chunk 15 | */ 16 | 17 | public class LiquidStorage { 18 | private boolean full; 19 | public int bottom; 20 | public int top; 21 | private boolean[][] sections; 22 | private boolean[] sFull; 23 | public static boolean[] empty() {return new boolean[16*16];} 24 | public final WorldChunk chunk; 25 | 26 | public WorldChunk xp = null; 27 | public WorldChunk xm = null; 28 | public WorldChunk zp = null; 29 | public WorldChunk zm = null; 30 | 31 | public enum LIQUIDS { 32 | //WATER(Set.of(Blocks.WATER, Blocks.BUBBLE_COLUMN)), 33 | //LAVA(Set.of(Blocks.LAVA)), 34 | AIR(Set.of(Blocks.AIR, Blocks.CAVE_AIR, Blocks.VOID_AIR, Blocks.SCAFFOLDING)); 35 | final Set allowed; 36 | LIQUIDS(Set a){allowed = a;} 37 | public boolean matches(Block b){ return allowed.contains(b); } 38 | } 39 | 40 | public boolean isEmpty(){return !full;} 41 | 42 | public boolean[] getSection(int y) { 43 | if (!full || y > top || y < bottom) return null; 44 | return sections[y-bottom]; 45 | } 46 | 47 | public boolean[] getOrCreateSection(int y) { 48 | if (getSection(y) == null) return initSection(y); 49 | return sections[y-bottom]; 50 | } 51 | 52 | public boolean getBlock(int x, int y, int z) { // must be very fast 53 | if (!full || y > top || y < bottom) return false; 54 | boolean[] section = sections[y-bottom]; 55 | if (section == null) return false; 56 | return section[x+(z<<4)]; 57 | } 58 | 59 | public boolean[] initSection(int y) { 60 | if (!full) { sFull = new boolean[]{false}; bottom = y; top = y; full = true; return (sections = new boolean[][]{empty()})[0];} 61 | else if (y < bottom) { sFull = ArrayUtils.addAll(new boolean[bottom-y], sFull); 62 | sections = ArrayUtils.addAll(new boolean[bottom-y][], sections); bottom = y; return sections[0]=empty(); } 63 | else if (y > top) { sFull = ArrayUtils.addAll(sFull, new boolean[y-top]); 64 | sections = ArrayUtils.addAll(sections, new boolean[y-top][]); top = y; return sections[y-bottom]=empty(); } 65 | else return sections[y-bottom]=empty(); 66 | } 67 | 68 | //public LiquidStorage(){}; 69 | public LiquidStorage(boolean[][] s, int t, int b, boolean[] sf, WorldChunk ch ){ 70 | int n = t-b+1; if (s.length != n || sf.length != n) SPLog.logError("Top("+t+") to Bottom("+b+") != "+s.length+" or "+sf.length); 71 | full = true; sections = s; top = t; bottom = b; sFull = sf; chunk = ch; 72 | } 73 | 74 | public LiquidStorage(WorldChunk ch ){ 75 | full = false; chunk = ch; 76 | } 77 | 78 | public void setBlock(int x, int y, int z, boolean block) { // rare ⇒ can be expensive 79 | if (x >= 16 || x < 0 || z >= 16 || z < 0) SPLog.logError("Coords: "+x+", "+z+" are out of bounds"); 80 | else if (getBlock(x, y, z) != block) { 81 | getOrCreateSection(y)[x+(z<<4)] = block; 82 | if (!block) { 83 | sFull[y-bottom] = false; 84 | tryCull(y); 85 | } 86 | else { 87 | if (!ArrayUtils.contains(sections[y-bottom], false)) sFull[y-bottom] = true; 88 | } 89 | } 90 | } 91 | 92 | public void tryCull(int y){ 93 | if (!ArrayUtils.contains(sections[y - bottom], true)) { 94 | sections[y - bottom] = null; 95 | if (y == bottom) { 96 | int y1 = y; 97 | for (boolean[] s: sections) { if (s == null) y1++; else break; } 98 | if (y1 > top) unload(); 99 | else { 100 | sections = ArrayUtils.subarray(sections, y1-bottom , top-bottom+1); 101 | sFull = ArrayUtils.subarray(sFull, y1-bottom , top-bottom+1); 102 | bottom = y1; 103 | } 104 | } 105 | else if(y == top){ 106 | int y1 = y; 107 | for (int i = 0, l = sections.length; i < l; i++) {if (sections[l-i-1] != null) {y1-=i; break;}} 108 | if (y1 == y) unload(); 109 | else { 110 | sFull = ArrayUtils.subarray(sFull, 0 , y1-bottom+1); 111 | sections = ArrayUtils.subarray(sections, 0 , y1-bottom+1); 112 | top = y1; 113 | } 114 | } 115 | } 116 | } 117 | public void unload() {full = false; sections = null; sFull = null;} 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/config/presets/ConfigChanger.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.config.presets; 2 | 3 | import com.sonicether.soundphysics.SoundPhysicsMod; 4 | import com.sonicether.soundphysics.config.MaterialData; 5 | import com.sonicether.soundphysics.config.SoundPhysicsConfig; 6 | import org.jetbrains.annotations.Nullable; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | import static com.sonicether.soundphysics.SoundPhysicsMod.groupMap; 12 | 13 | public class ConfigChanger { 14 | public static void changeConfig(SoundPhysicsConfig config, @Nullable Boolean enabled, 15 | @Nullable Double attenuationFactor, @Nullable Double globalReverbGain, @Nullable Double globalReverbBrightness, @Nullable Double globalBlockAbsorption, @Nullable Double globalBlockReflectance, @Nullable Double soundDistanceAllowance, @Nullable Double airAbsorption, @Nullable Double humidityAbsorption, @Nullable Double rainAbsorption, @Nullable Double underwaterFilter, 16 | @Nullable Boolean skipRainOcclusionTracing, @Nullable Integer environmentEvaluationRays, @Nullable Integer environmentEvaluationRayBounces, @Nullable Boolean simplerSharedAirspaceSimulation, 17 | @Nullable Map materialProperties, 18 | @Nullable Integer continuousRefreshRate, @Nullable Double maxDirectOcclusionFromBlocks, @Nullable Boolean _9RayDirectOcclusion, @Nullable Boolean soundDirectionEvaluation, @Nullable Double directRaysDirEvalMultiplier, @Nullable Boolean notOccludedNoRedirect 19 | ) { 20 | if (enabled != null) config.enabled = enabled; 21 | setGeneral(config.General, attenuationFactor, globalReverbGain, globalReverbBrightness, globalBlockAbsorption, globalBlockReflectance, soundDistanceAllowance, airAbsorption, humidityAbsorption, rainAbsorption, underwaterFilter); 22 | setPerformance(config.Performance, skipRainOcclusionTracing, environmentEvaluationRays, environmentEvaluationRayBounces, simplerSharedAirspaceSimulation); 23 | setMaterial_Properties(config.Materials, materialProperties); 24 | setVlads_Tweaks(config.Vlads_Tweaks, continuousRefreshRate, maxDirectOcclusionFromBlocks, _9RayDirectOcclusion, soundDirectionEvaluation, directRaysDirEvalMultiplier, notOccludedNoRedirect); 25 | config.preset = ConfigPresets.LOAD_SUCCESS; 26 | } 27 | 28 | public static void setGeneral(SoundPhysicsConfig.General general, @Nullable Double attenuationFactor, @Nullable Double globalReverbGain, @Nullable Double globalReverbBrightness, @Nullable Double globalBlockAbsorption, @Nullable Double globalBlockReflectance, @Nullable Double soundDistanceAllowance, @Nullable Double airAbsorption, @Nullable Double humidityAbsorption, @Nullable Double rainAbsorption, @Nullable Double underwaterFilter) { 29 | if (attenuationFactor != null) general.attenuationFactor = attenuationFactor; 30 | if (globalReverbGain != null) general.globalReverbGain = globalReverbGain; 31 | if (globalReverbBrightness != null) general.globalReverbBrightness = globalReverbBrightness; 32 | if (globalBlockAbsorption != null) general.globalBlockAbsorption = globalBlockAbsorption; 33 | if (globalBlockReflectance != null) general.globalBlockReflectance = globalBlockReflectance; 34 | if (soundDistanceAllowance != null) general.soundDistanceAllowance = soundDistanceAllowance; 35 | if (airAbsorption != null) general.airAbsorption = airAbsorption; 36 | if (humidityAbsorption != null) general.humidityAbsorption = humidityAbsorption; 37 | if (rainAbsorption != null) general.rainAbsorption = rainAbsorption; 38 | if (underwaterFilter != null) general.underwaterFilter = underwaterFilter; 39 | } 40 | 41 | public static void setPerformance(SoundPhysicsConfig.Performance performance, @Nullable Boolean skipRainOcclusionTracing, @Nullable Integer environmentEvaluationRays, @Nullable Integer environmentEvaluationRayBounces, @Nullable Boolean simplerSharedAirspaceSimulation) { 42 | if (skipRainOcclusionTracing != null) performance.skipRainOcclusionTracing = skipRainOcclusionTracing; 43 | if (environmentEvaluationRays != null) performance.environmentEvaluationRays = environmentEvaluationRays; 44 | if (environmentEvaluationRayBounces != null) performance.environmentEvaluationRayBounces = environmentEvaluationRayBounces; 45 | if (simplerSharedAirspaceSimulation != null) performance.simplerSharedAirspaceSimulation = simplerSharedAirspaceSimulation; 46 | } 47 | 48 | public static void setMaterial_Properties(SoundPhysicsConfig.Materials materials, @Nullable Map materialProperties) { 49 | if (materialProperties != null) materialProperties.forEach((s, newData) -> materials.materialProperties.compute(s, (k, v) -> (v == null) ? 50 | new MaterialData( hasExample(s) ? getExample(s) : "error", 51 | newData.getReflectivity() == -1 ? 0.5 : newData.getReflectivity(), 52 | newData.getAbsorption() == -1 ? 0.5 : newData.getAbsorption()) 53 | : new MaterialData( (v.getExample() == null) ? (hasExample(s) ? getExample(s) : "error") : v.getExample(), 54 | newData.getReflectivity() == -1 ? v.getReflectivity() : newData.getReflectivity(), 55 | newData.getAbsorption() == -1 ? v.getAbsorption() : newData.getAbsorption()))); 56 | } 57 | 58 | public static void setVlads_Tweaks(SoundPhysicsConfig.Vlads_Tweaks vlads_tweaks, @Nullable Integer continuousRefreshRate, @Nullable Double maxDirectOcclusionFromBlocks, @Nullable Boolean _9RayDirectOcclusion, @Nullable Boolean soundDirectionEvaluation, @Nullable Double directRaysDirEvalMultiplier, @Nullable Boolean notOccludedNoRedirect) { 59 | if (continuousRefreshRate != null) vlads_tweaks.continuousRefreshRate = continuousRefreshRate; 60 | if (maxDirectOcclusionFromBlocks != null) vlads_tweaks.maxDirectOcclusionFromBlocks = maxDirectOcclusionFromBlocks; 61 | if (_9RayDirectOcclusion != null) vlads_tweaks._9RayDirectOcclusion = _9RayDirectOcclusion; 62 | if (soundDirectionEvaluation != null) vlads_tweaks.soundDirectionEvaluation = soundDirectionEvaluation; 63 | if (directRaysDirEvalMultiplier != null) vlads_tweaks.directRaysDirEvalMultiplier = directRaysDirEvalMultiplier; 64 | if (notOccludedNoRedirect != null) vlads_tweaks.notOccludedNoRedirect = notOccludedNoRedirect; 65 | } 66 | public static String getExample(String s) {return groupMap.get(s);} 67 | public static boolean hasExample(String s) {return groupMap.containsKey(s);} 68 | } 69 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MSYS* | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/config/PrecomputedConfig.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.config; 2 | 3 | import com.sonicether.soundphysics.SPLog; 4 | import com.sonicether.soundphysics.SoundPhysics; 5 | import com.sonicether.soundphysics.SoundPhysicsMod; 6 | import it.unimi.dsi.fastutil.objects.Reference2DoubleOpenHashMap; 7 | import net.minecraft.sound.BlockSoundGroup; 8 | import net.minecraft.util.Pair; 9 | 10 | import java.util.*; 11 | import java.util.stream.Collectors; 12 | 13 | /* 14 | Values, which remain constant after the config has changed 15 | Only one instance allowed 16 | */ 17 | public class PrecomputedConfig { 18 | public final static float globalVolumeMultiplier = 4f; 19 | public static double soundDistanceAllowance = 4; 20 | public static double defaultAttenuationFactor = 1; 21 | public static PrecomputedConfig pC = null; 22 | public final boolean multiThreading = true; 23 | 24 | public final boolean off; 25 | 26 | public final float globalReverbGain; 27 | public final float globalReverbBrightness; 28 | public final double globalBlockAbsorption; 29 | public final double globalBlockReflectance; 30 | public final float airAbsorption; 31 | public final float humidityAbsorption; 32 | public final float rainAbsorption; 33 | public final double underwaterFilter; 34 | 35 | public final boolean skipRainOcclusionTracing; 36 | public final int nRays; 37 | public final double rcpNRays; 38 | public final int nRayBounces; 39 | public final double rcpTotRays; 40 | public final boolean simplerSharedAirspaceSimulation; 41 | 42 | public final Reference2DoubleOpenHashMap reflectivityMap; 43 | public final double defaultReflectivity; 44 | public final Reference2DoubleOpenHashMap absorptionMap; 45 | public final double defaultAbsorption; 46 | public final Set blockWhiteSet; 47 | public final Map blockWhiteMap; 48 | 49 | public final boolean recordsDisable; 50 | public final int continuousRefreshRate; 51 | public final double maxDirectOcclusionFromBlocks; 52 | public final boolean _9Ray; 53 | public final boolean soundDirectionEvaluation; 54 | public final double directRaysDirEvalMultiplier; 55 | public final boolean notOccludedRedirect; 56 | 57 | public final boolean dLog; 58 | public final boolean oLog; 59 | public final boolean eLog; 60 | public final boolean pLog; 61 | public final boolean dRays; 62 | 63 | private boolean active = true; 64 | 65 | public PrecomputedConfig(SoundPhysicsConfig c) throws CloneNotSupportedException { 66 | if (pC != null && pC.active) throw new CloneNotSupportedException("Tried creating second instance of precomputedConfig"); 67 | off = !c.enabled; 68 | 69 | defaultAttenuationFactor = c.General.attenuationFactor; 70 | globalReverbGain = (float) (c.General.globalReverbGain * 0.0595); 71 | globalReverbBrightness = (float) (c.General.globalReverbBrightness * 0.7); 72 | globalBlockAbsorption = c.General.globalBlockAbsorption * 2; 73 | soundDistanceAllowance = c.General.soundDistanceAllowance; 74 | globalBlockReflectance = c.General.globalBlockReflectance; 75 | airAbsorption = (float) c.General.airAbsorption; 76 | humidityAbsorption = (float) c.General.humidityAbsorption; 77 | rainAbsorption = (float) c.General.rainAbsorption; 78 | underwaterFilter = 1 - c.General.underwaterFilter; 79 | 80 | skipRainOcclusionTracing = c.Performance.skipRainOcclusionTracing; 81 | nRays = c.Performance.environmentEvaluationRays; 82 | rcpNRays = 1d/nRays; 83 | nRayBounces = c.Performance.environmentEvaluationRayBounces; 84 | rcpTotRays = rcpNRays/nRayBounces; 85 | simplerSharedAirspaceSimulation = c.Performance.simplerSharedAirspaceSimulation; 86 | 87 | blockWhiteSet = new HashSet<>(c.Materials.blockWhiteList); 88 | defaultReflectivity = c.Materials.materialProperties.get("DEFAULT").reflectivity; 89 | defaultAbsorption = c.Materials.materialProperties.get("DEFAULT").absorption; 90 | blockWhiteMap = c.Materials.blockWhiteList.stream() 91 | .map((a) -> new Pair<>(a, c.Materials.materialProperties.get(a))) 92 | .map((e) -> { 93 | if (e.getRight() != null) return e; 94 | SPLog.logError("Missing material data for "+e.getLeft()+", Default entry created"); 95 | final MaterialData newData = new MaterialData(e.getLeft(), defaultReflectivity, defaultAbsorption); 96 | c.Materials.materialProperties.put(e.getLeft(), newData); 97 | e.setRight(newData); return e; 98 | }).collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); 99 | 100 | reflectivityMap = new Reference2DoubleOpenHashMap<>(); 101 | absorptionMap = new Reference2DoubleOpenHashMap<>(); 102 | final List wrong = new java.util.ArrayList<>(); 103 | final List toRemove = new java.util.ArrayList<>(); 104 | c.Materials.materialProperties.forEach((k, v) -> { 105 | BlockSoundGroup bsg = SoundPhysicsMod.groupSoundBlocks.get(k); 106 | if (bsg != null){ 107 | reflectivityMap.put(bsg, v.reflectivity); 108 | absorptionMap.put(bsg, v.absorption * 2); 109 | } 110 | else { 111 | if (!k.equals("DEFAULT") && !blockWhiteSet.contains(k)){ 112 | wrong.add(k+" ("+v.example+")"); 113 | toRemove.add(k); 114 | } 115 | } 116 | }); 117 | if (!wrong.isEmpty()) { 118 | SPLog.logError("MaterialData map contains "+wrong.size()+" extra entries: "+ Arrays.toString(new List[]{wrong})+"\nRemoving..."); 119 | toRemove.forEach((e) -> c.Materials.materialProperties.remove(e)); 120 | } 121 | 122 | recordsDisable = c.Vlads_Tweaks.recordsDisable; 123 | continuousRefreshRate = c.Vlads_Tweaks.continuousRefreshRate; 124 | maxDirectOcclusionFromBlocks = c.Vlads_Tweaks.maxDirectOcclusionFromBlocks; 125 | _9Ray = c.Vlads_Tweaks._9RayDirectOcclusion; 126 | soundDirectionEvaluation = c.Vlads_Tweaks.soundDirectionEvaluation; 127 | directRaysDirEvalMultiplier = Math.pow(c.Vlads_Tweaks.directRaysDirEvalMultiplier, 10.66); 128 | notOccludedRedirect = !c.Vlads_Tweaks.notOccludedNoRedirect; 129 | 130 | dLog = c.Misc.debugLogging; 131 | oLog = c.Misc.occlusionLogging; 132 | eLog = c.Misc.environmentLogging; 133 | pLog = c.Misc.performanceLogging; 134 | dRays = c.Misc.raytraceParticles; 135 | } 136 | 137 | public void deactivate(){ active = false;} 138 | } 139 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/mixin/WorldChunkMixin.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.mixin; 2 | 3 | import com.sonicether.soundphysics.performance.LiquidStorage; 4 | import com.sonicether.soundphysics.performance.WorldChunkAccess; 5 | import net.fabricmc.api.EnvType; 6 | import net.fabricmc.api.Environment; 7 | import net.minecraft.block.Block; 8 | import net.minecraft.block.BlockState; 9 | import net.minecraft.client.world.ClientChunkManager; 10 | import net.minecraft.nbt.NbtCompound; 11 | import net.minecraft.network.PacketByteBuf; 12 | import net.minecraft.network.packet.s2c.play.ChunkData; 13 | import net.minecraft.util.math.BlockPos; 14 | import net.minecraft.util.math.ChunkPos; 15 | import net.minecraft.util.registry.Registry; 16 | import net.minecraft.world.HeightLimitView; 17 | import net.minecraft.world.World; 18 | import net.minecraft.world.biome.Biome; 19 | import net.minecraft.world.chunk.*; 20 | import net.minecraft.world.gen.chunk.BlendingData; 21 | import net.minecraft.world.tick.ChunkTickScheduler; 22 | import org.apache.commons.lang3.ArrayUtils; 23 | import org.jetbrains.annotations.Nullable; 24 | import org.spongepowered.asm.mixin.Final; 25 | import org.spongepowered.asm.mixin.Mixin; 26 | import org.spongepowered.asm.mixin.Shadow; 27 | import org.spongepowered.asm.mixin.injection.At; 28 | import org.spongepowered.asm.mixin.injection.Inject; 29 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 30 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; 31 | 32 | import java.util.concurrent.atomic.AtomicInteger; 33 | import java.util.function.Consumer; 34 | import java.util.stream.Stream; 35 | 36 | @Mixin(WorldChunk.class) 37 | public abstract class WorldChunkMixin extends Chunk implements WorldChunkAccess { 38 | private LiquidStorage notAirLiquidStorage = null; 39 | //private LiquidStorage waterLiquidStorage = null;//todo 40 | 41 | public LiquidStorage getNotAirLiquidStorage() {return notAirLiquidStorage;} 42 | //public LiquidStorage getWaterLiquidStorage() {return waterLiquidStorage;} 43 | 44 | @Shadow @Final World world; 45 | 46 | public WorldChunkMixin(ChunkPos pos, UpgradeData upgradeData, HeightLimitView heightLimitView, Registry biome, long inhabitedTime, @Nullable ChunkSection[] sectionArrayInitializer, @Nullable BlendingData blendingData) { 47 | super(pos, upgradeData, heightLimitView, biome, inhabitedTime, sectionArrayInitializer, blendingData); 48 | } 49 | 50 | @Inject(method = "loadFromPacket(Lnet/minecraft/network/PacketByteBuf;Lnet/minecraft/nbt/NbtCompound;Ljava/util/function/Consumer;)V", at = @At("RETURN")) 51 | private void load(PacketByteBuf buf, NbtCompound nbt, Consumer consumer, CallbackInfo ci){initStorage();} 52 | 53 | @Inject(method = "(Lnet/minecraft/world/World;Lnet/minecraft/util/math/ChunkPos;Lnet/minecraft/world/chunk/UpgradeData;Lnet/minecraft/world/tick/ChunkTickScheduler;Lnet/minecraft/world/tick/ChunkTickScheduler;J[Lnet/minecraft/world/chunk/ChunkSection;Lnet/minecraft/world/chunk/WorldChunk$EntityLoader;Lnet/minecraft/world/gen/chunk/BlendingData;)V", at = @At("RETURN")) 54 | private void create(World world, ChunkPos pos, UpgradeData upgradeData, ChunkTickScheduler blockTickScheduler, ChunkTickScheduler fluidTickScheduler, long inhabitedTime, ChunkSection[] sectionArrayInitializer, WorldChunk.EntityLoader entityLoader, BlendingData blendingData, CallbackInfo ci){if (sectionArrayInitializer != null) initStorage();} 55 | 56 | private void initStorage() { 57 | if (world == null || !world.isClient) return; 58 | ChunkSection[] chunkSections = getSectionArray(); 59 | boolean[][] notAirSections = new boolean[512][]; AtomicInteger bottomNotAir = new AtomicInteger(-600); AtomicInteger topNotAir = new AtomicInteger(-600); boolean[] notAirFull = new boolean[512]; 60 | 61 | //for (ChunkSection chunkSection: chunkSections) { //horrible performance code 62 | Stream.of(chunkSections).parallel().forEach((chunkSection) -> { // surprisingly good-performance code (actually 0 impact) 63 | if (chunkSection.isEmpty()) return; 64 | for (int y = chunkSection.getYOffset(), l = y+16; y v == -600 ? Y : Math.min(v, Y)); 77 | topNotAir.getAndUpdate((v) -> v == -600 ? Y : Math.max(v, Y)); 78 | synchronized (notAirFull) {notAirFull[y+64] = (notAirCount == 16*16);} 79 | } 80 | } 81 | }); 82 | 83 | if (topNotAir.get() != -600) notAirLiquidStorage = new LiquidStorage(ArrayUtils.subarray(notAirSections, bottomNotAir.get() +64, topNotAir.get() +64+1), topNotAir.get(), bottomNotAir.get(), ArrayUtils.subarray(notAirFull, bottomNotAir.get() +64, topNotAir.get() +64+1), (WorldChunk) (Object) this); 84 | else notAirLiquidStorage = new LiquidStorage((WorldChunk) (Object) this); 85 | WorldChunkAccess[] adj = new WorldChunkAccess[4]; 86 | for (int i = 0; i <= 3; i++) { 87 | adj[i] = (WorldChunkAccess) world.getChunk(super.pos.x + (i==0?-1:i==1?1:0), super.pos.z + (i==2?-1:i==3?1:0), ChunkStatus.FULL, false); 88 | } 89 | if (adj[0] != null) {adj[0].getNotAirLiquidStorage().xm = (WorldChunk) (Object) this; notAirLiquidStorage.xp = (WorldChunk) adj[0];} 90 | if (adj[1] != null) {adj[1].getNotAirLiquidStorage().xp = (WorldChunk) (Object) this; notAirLiquidStorage.xm = (WorldChunk) adj[1];} 91 | if (adj[2] != null) {adj[2].getNotAirLiquidStorage().zm = (WorldChunk) (Object) this; notAirLiquidStorage.zp = (WorldChunk) adj[2];} 92 | if (adj[3] != null) {adj[3].getNotAirLiquidStorage().zp = (WorldChunk) (Object) this; notAirLiquidStorage.zm = (WorldChunk) adj[3];} 93 | } 94 | 95 | @Shadow public ChunkStatus getStatus() {return null;} 96 | 97 | @Inject(method = "setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Z)Lnet/minecraft/block/BlockState;", at = @At("HEAD")) 98 | private void setBlock(BlockPos pos, BlockState state, boolean moved, CallbackInfoReturnable cir){ 99 | if (!world.isClient) return; 100 | Block block = state.getBlock(); 101 | notAirLiquidStorage.setBlock(pos.getX() & 15, pos.getY(), pos.getZ() & 15, !LiquidStorage.LIQUIDS.AIR.matches(block)); 102 | } 103 | 104 | @Mixin(ClientChunkManager.class) 105 | public abstract static class Unloaded { 106 | @SuppressWarnings("SameReturnValue") @Shadow public WorldChunk getChunk(int x, int z, ChunkStatus chunkStatus, boolean bl){return null;} 107 | @Inject(method = "unload(II)V", at = @At("HEAD")) 108 | public void unload(int chunkX, int chunkZ, CallbackInfo ci) { 109 | 110 | WorldChunkAccess[] adj = new WorldChunkAccess[4]; 111 | for (int i = 0; i <= 3; i++) { 112 | adj[i] = (WorldChunkAccess) getChunk(chunkX + (i==0?-1:i==1?1:0), chunkZ + (i==2?-1:i==3?1:0), ChunkStatus.FULL, false); 113 | } 114 | if (adj[0] != null) adj[0].getNotAirLiquidStorage().xm = null; 115 | if (adj[1] != null) adj[1].getNotAirLiquidStorage().xp = null; 116 | if (adj[2] != null) adj[2].getNotAirLiquidStorage().zm = null; 117 | if (adj[3] != null) adj[3].getNotAirLiquidStorage().zp = null; 118 | } 119 | } 120 | } 121 | 122 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/config/SoundPhysicsConfig.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.config; 2 | 3 | import com.sonicether.soundphysics.config.presets.ConfigPresets; 4 | import me.shedaniel.autoconfig.ConfigData; 5 | import me.shedaniel.autoconfig.annotation.Config; 6 | import me.shedaniel.autoconfig.annotation.ConfigEntry; 7 | import me.shedaniel.cloth.clothconfig.shadowed.blue.endless.jankson.Comment; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | @SuppressWarnings("CanBeFinal") 14 | @Config(name = "sound_physics") 15 | @Config.Gui.Background("minecraft:textures/block/note_block.png") 16 | public class SoundPhysicsConfig implements ConfigData { 17 | 18 | @Comment("Enable reverb?") 19 | public boolean enabled = true; 20 | 21 | @ConfigEntry.Gui.CollapsibleObject 22 | public General General = new General(); 23 | 24 | @ConfigEntry.Gui.CollapsibleObject 25 | public Performance Performance = new Performance(); 26 | 27 | @ConfigEntry.Gui.CollapsibleObject 28 | public Materials Materials = new Materials(); 29 | 30 | @ConfigEntry.Gui.CollapsibleObject 31 | public Vlads_Tweaks Vlads_Tweaks = new Vlads_Tweaks(); 32 | 33 | @ConfigEntry.Gui.CollapsibleObject 34 | public Misc Misc = new Misc(); 35 | 36 | public static class General{ 37 | @Comment("Affects how quiet a sound gets based on distance. Lower values mean distant sounds are louder.\n1.0 is the physically correct value.\n0.2 - 1.0 or just don't set it to 0") 38 | public double attenuationFactor = 1.0; 39 | @Comment("The global volume of simulated reverberations.\n0.1 - 2.0") 40 | public double globalReverbGain = 1.0; 41 | @Comment("The brightness of reverberation.\nHigher values result in more high frequencies in reverberation.\nLower values give a more muffled sound to the reverb.\n0.1 - 2.0") 42 | public double globalReverbBrightness = 1.0; 43 | @Comment("The global amount of sound that will be absorbed when traveling through blocks.\n 0.1 - 4.0") 44 | public double globalBlockAbsorption = 1.0; 45 | @Comment("The global amount of sound reflectance energy of all blocks.\nLower values result in more conservative reverb simulation with shorter reverb tails.\nHigher values result in more generous reverb simulation with higher reverb tails.\n0.1 - 4.0") 46 | public double globalBlockReflectance = 1.0; 47 | @Comment("Minecraft won't allow sounds to play past a certain distance;\nSoundPhysics makes that configurable by multiplying this parameter by the default distance.\nValues too high can cause polyphony issues.\n1.0 - 6.0") 48 | public double soundDistanceAllowance = 4.0; 49 | @Comment("Represents how aggressively air absorbs high frequencies over distance.\nA value of 1.0 is physically correct for air with normal humidity and temperature.\nHigher values mean air will absorb more high frequencies with distance.\nA value of 0.0 disables this effect. 0.0 - 10.0") 50 | public double airAbsorption = 1.0; 51 | @Comment("How much humidity contributes to the air absorption.\nA value of 1.0 is physically correct.\nHigher values mean air will absorb more high frequencies with distance, depending on the local humidity.\nA value of 0.0 disables this effect. 0.0 - 4.0") 52 | public double humidityAbsorption = 1.0; 53 | @Comment("How much rain drops contribute to the air absorption.\nA value of 1.0 is approximately physically correct.\nHigher values mean air will absorb more high frequencies with distance, depending on the local rainfall.\nA value of 0.0 disables this effect. 0.0 - 2.0") 54 | public double rainAbsorption = 1.0; 55 | @Comment("How much sound is filtered when the player is underwater.\n0.0 means no filter. 1.0 means fully filtered.\n0.0 - 1.0") 56 | public double underwaterFilter = 0.8; 57 | } 58 | 59 | public static class Performance{ 60 | @Comment("If true, rain sound sources won't trace for sound occlusion.\nThis can help performance during rain.") 61 | public boolean skipRainOcclusionTracing = true; 62 | @Comment("The number of rays to trace to determine reverberation for each sound source.\nMore rays provides more consistent tracing results but takes more time to calculate.\nDecrease this value if you experience lag spikes when sounds play.") 63 | @ConfigEntry.BoundedDiscrete(max = 768, min = 8) 64 | public int environmentEvaluationRays = 224; 65 | @Comment("The number of rays bounces to trace to determine reverberation for each sound source.\nMore bounces provides more echo and sound ducting but takes more time to calculate.\nDecrease this value if you experience lag spikes when sounds play. Capped by max distance.") 66 | @ConfigEntry.BoundedDiscrete(max = 32, min = 2) 67 | public int environmentEvaluationRayBounces = 12; 68 | @Comment("If true, enables a simpler technique for determining when the player and a sound source share airspace.\nMight sometimes miss recognizing shared airspace, but it's faster to calculate.") 69 | public boolean simplerSharedAirspaceSimulation = false; 70 | } 71 | 72 | public static class Materials { 73 | @Comment("Material properties for blocks.\n0.0 - 1.0") 74 | public Map materialProperties = null; 75 | 76 | @Comment("Makes blocks use ID (e.g. block.minecraft.stone) instead of sound group to determine material") 77 | public List blockWhiteList = new ArrayList<>(); 78 | } 79 | 80 | public static class Vlads_Tweaks { 81 | @Comment("Disable occlusion of jukeboxes and note blocks.\nUseful if you have an audio signaling system that you need to hear clearly") 82 | public boolean recordsDisable = false; 83 | @Comment("Continuous sources reverb refresh interval (ticks per refresh or 1/(20Hz))") 84 | public int continuousRefreshRate = 4; 85 | @Comment("The amount at which occlusion is capped. 10 * block_occlusion is the theoretical limit") 86 | public double maxDirectOcclusionFromBlocks = 10; 87 | @Comment("Calculate direct occlusion as the minimum of 9 rays from vertices of a block") 88 | public boolean _9RayDirectOcclusion = true; 89 | @Comment("Whether to try calculating where the sound should come from based on reflections") 90 | public boolean soundDirectionEvaluation = true; 91 | @Comment("How much the sound direction depends on reflected sounds.\nRequires \"Re-calculate sound direction\" to be enabled.\n0.0 is no reflected sounds, 1.0 is 100% reflected sounds.\n0.5 is approximately physically accurate.") 92 | public double directRaysDirEvalMultiplier = 0.5; 93 | @Comment("Skip redirecting non-occluded sounds (the ones you can see directly).\nCan be inaccurate in some situations, especially when \"Re-calculate sound direction\" is enabled.") 94 | public boolean notOccludedNoRedirect = false; 95 | } 96 | 97 | public static class Misc { 98 | @Comment("General debug logging") 99 | public boolean debugLogging = false; 100 | @Comment("Occlusion tracing information logging") 101 | public boolean occlusionLogging = false; 102 | @Comment("Environment evaluation information logging") 103 | public boolean environmentLogging = false; 104 | @Comment("Performance information logging") 105 | public boolean performanceLogging = false; 106 | @Comment("Particles on traced blocks (structure_void is a block)") 107 | public boolean raytraceParticles = false; 108 | } 109 | 110 | @ConfigEntry.Gui.EnumHandler(option = ConfigEntry.Gui.EnumHandler.EnumDisplayOption.DROPDOWN) 111 | @Comment("Soft presets. Some of these can be applied one after another to stack effects onto a base profile.") 112 | public ConfigPresets preset = ConfigPresets.DEFAULT_PERFORMANCE; 113 | 114 | @ConfigEntry.Gui.Excluded 115 | public String version; 116 | } 117 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/ALstuff/SPEfx.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.ALstuff; 2 | 3 | import net.minecraft.util.math.Vec3d; 4 | import net.minecraft.util.math.MathHelper; 5 | import org.lwjgl.openal.AL10; 6 | import org.lwjgl.openal.ALC10; 7 | import org.lwjgl.openal.EXTEfx; 8 | 9 | import static com.sonicether.soundphysics.SoundPhysics.mc; 10 | 11 | import static com.sonicether.soundphysics.SPLog.*; 12 | import static com.sonicether.soundphysics.config.PrecomputedConfig.pC; 13 | 14 | /* 15 | !!!Documentation for OpenAL!!! 16 | * I am not responsible for anything that happens after you go to these links * 17 | - ExtEfx(aka Effects Extension) https://github.com/rtpHarry/Sokoban/blob/master/libraries/OpenAL%201.1%20SDK/docs/Effects%20Extension%20Guide.pdf or https://usermanual.wiki/Pdf/Effects20Extension20Guide.90272296/view 18 | - Core spec(aka OpenAL 1.1 Specification and Reference) https://www.openal.org/documentation/openal-1.1-specification.pdf 19 | - Core guide(aka OpenAL Programmer's Guide) http://openal.org/documentation/OpenAL_Programmers_Guide.pdf 20 | 21 | 22 | Source attributes(2&3): https://www.openal.org/documentation/openal-1.1-specification.pdf#page=34 & http://openal.org/documentation/OpenAL_Programmers_Guide.pdf#page=34 23 | */ 24 | 25 | public class SPEfx { 26 | 27 | private static final ReverbSlot slot1 = new ReverbSlot(0.15f , 0.0f, 1.0f, 2, 0.99f, 0.8571429f, 2.5f, 0.001f, 1.26f, 0.011f, 0.994f, 0.16f); 28 | private static final ReverbSlot slot2 = new ReverbSlot(0.55f , 0.0f, 1.0f, 3, 0.99f, 1 , 0.2f, 0.015f, 1.26f, 0.011f, 0.994f, 0.15f); 29 | private static final ReverbSlot slot3 = new ReverbSlot(1.68f , 0.1f, 1.0f, 5, 0.99f, 1 , 0.0f, 0.021f, 1.26f, 0.021f, 0.994f, 0.13f); 30 | private static final ReverbSlot slot4 = new ReverbSlot(4.142f, 0.5f, 1.0f, 4, 0.89f, 1 , 0.0f, 0.025f, 1.26f, 0.021f, 0.994f, 0.11f); 31 | private static int directFilter0; 32 | private static final float rainDecayConstant = (float) (Math.log(2.0) / 1200); 33 | private static float rainAccumulator; 34 | private static boolean rainHasInitialValue; 35 | 36 | public static void syncReverbParams() 37 | { //Set the global reverb parameters and apply them to the effect and effectslot 38 | if (slot1.initialised){slot1.set(); slot2.set(); slot3.set(); slot4.set();} 39 | } 40 | 41 | public static void setupEFX() 42 | { 43 | //Get current context and device 44 | final long currentContext = ALC10.alcGetCurrentContext(); 45 | final long currentDevice = ALC10.alcGetContextsDevice(currentContext); 46 | if (ALC10.alcIsExtensionPresent(currentDevice, "ALC_EXT_EFX")) { 47 | log("EFX Extension recognized."); 48 | } else { 49 | logError("EFX Extension not found on current device. Aborting."); 50 | return; 51 | } 52 | // Delete previous filter if it was there 53 | if (slot1.initialised) EXTEfx.alDeleteFilters(directFilter0); 54 | 55 | // Create auxiliary effect slots 56 | slot1.initialize(); 57 | slot2.initialize(); 58 | slot3.initialize(); 59 | slot4.initialize(); 60 | 61 | // Create filters 62 | directFilter0 = EXTEfx.alGenFilters(); 63 | EXTEfx.alFilteri(directFilter0, EXTEfx.AL_FILTER_TYPE, EXTEfx.AL_FILTER_LOWPASS); 64 | logGeneral("directFilter0: "+directFilter0); 65 | } 66 | 67 | public static void setEnvironment( 68 | final int sourceID, 69 | final float sendGain0, final float sendGain1, final float sendGain2, final float sendGain3, 70 | final float sendCutoff0, final float sendCutoff1, final float sendCutoff2, final float sendCutoff3, 71 | final float directCutoff, final float directGain 72 | ) 73 | { 74 | if (pC.off) return; 75 | float absorptionHF = getAbsorptionHF(); 76 | slot1.airAbsorptionGainHF = absorptionHF; 77 | slot2.airAbsorptionGainHF = absorptionHF; 78 | slot3.airAbsorptionGainHF = absorptionHF; 79 | slot4.airAbsorptionGainHF = absorptionHF; 80 | 81 | syncReverbParams(); 82 | 83 | // Set reverb send filter values and set source to send to all reverb fx slots 84 | slot1.applyFilter(sourceID, sendGain0, sendCutoff0); 85 | slot2.applyFilter(sourceID, sendGain1, sendCutoff1); 86 | slot3.applyFilter(sourceID, sendGain2, sendCutoff2); 87 | slot4.applyFilter(sourceID, sendGain3, sendCutoff3); 88 | 89 | EXTEfx.alFilterf(directFilter0, EXTEfx.AL_LOWPASS_GAIN, directGain); 90 | EXTEfx.alFilterf(directFilter0, EXTEfx.AL_LOWPASS_GAINHF, directCutoff); 91 | AL10.alSourcei(sourceID, EXTEfx.AL_DIRECT_FILTER, directFilter0); 92 | checkErrorLog("Set Environment directFilter0:"); 93 | 94 | AL10.alSourcef(sourceID, EXTEfx.AL_AIR_ABSORPTION_FACTOR, MathHelper.clamp(pC.airAbsorption, 0.0f, 10.0f)); 95 | checkErrorLog("Set Environment airAbsorption:"); 96 | } 97 | 98 | public static float getAbsorptionHF() { 99 | if(mc == null || mc.world == null || mc.player == null) 100 | return 1.0f; 101 | double rain = getRain(); 102 | double rainS = rainAccumulator; 103 | double biomeHumidity = mc.world.getBiome(mc.player.getBlockPos()).getDownfall(); 104 | double biomeTemp = mc.world.getBiome(mc.player.getBlockPos()).getTemperature(); 105 | double freq = 10000.0d; 106 | 107 | double relhum = 100.0d * MathHelper.lerp(Math.max(rain, rainS), Math.max(biomeHumidity, 0.2d), 1.0d); // convert biomeHumidity and rain gradients into a dynamic relative humidity value 108 | double tempK = 25.0d * biomeTemp + 273.15d; // Convert biomeTemp to degrees kelvin 109 | 110 | double hum = relhum*Math.pow(10.0d,4.6151d-6.8346d*Math.pow((273.15d/tempK),1.261d)); 111 | double tempr = tempK/293.15d; // convert tempK to temperature relative to room temp 112 | 113 | double frO = (24+4.04E+4*hum*(0.02d+hum)/(0.391d+hum)); 114 | double frN = Math.pow(tempr,-0.5)*(9+280*hum*Math.exp(-4.17d*(Math.pow(tempr,-1.0f/3.0f)-1))); 115 | double alpha = 8.686d*freq*freq*(1.84E-11*Math.sqrt(tempr)+Math.pow(tempr,-2.5)*(0.01275d*(Math.exp(-2239.1d/tempK)*1/(frO+freq*freq/frO))+0.1068d*(Math.exp(-3352/tempK)*1/(frN+freq*freq/frN)))); 116 | 117 | return (float) Math.pow(10.0d, (alpha * -1.0d * pC.humidityAbsorption)/20.0d); // convert alpha (decibels per meter of attenuation) into airAbsorptionGainHF value and return 118 | } 119 | 120 | public static void setSoundPos(final int sourceID, final Vec3d pos) 121 | { 122 | if (pC.off) return; 123 | //System.out.println(pos);//TO DO 124 | AL10.alSourcefv(sourceID, 4100, new float[]{(float) pos.x, (float) pos.y, (float) pos.z}); 125 | } 126 | public static float getRain(){ 127 | float tickDelta = 1.0f; 128 | return (mc==null || mc.world==null) ? 0.0f : mc.world.getRainGradient(tickDelta); 129 | } 130 | public static void updateSmoothedRain() { 131 | if (!rainHasInitialValue) { 132 | // There is no smoothing on the first value. 133 | // This is not an optimal approach to choosing the initial value: 134 | // https://en.wikipedia.org/wiki/Exponential_smoothing#Choosing_the_initial_smoothed_value 135 | // 136 | // However, it works well enough for now. 137 | rainAccumulator = getRain(); 138 | rainHasInitialValue = true; 139 | 140 | return; 141 | } 142 | 143 | // Implements the basic variant of exponential smoothing 144 | // https://en.wikipedia.org/wiki/Exponential_smoothing#Basic_(simple)_exponential_smoothing_(Holt_linear) 145 | 146 | // xₜ 147 | float newValue = getRain(); 148 | 149 | // 𝚫t 150 | float tickDelta = 1.0f; 151 | 152 | // Compute the smoothing factor based on our 153 | // α = 1 - e^(-𝚫t/τ) = 1 - e^(-k𝚫t) 154 | float smoothingFactor = (float) (1.0f - Math.exp(-1*rainDecayConstant*tickDelta)); 155 | 156 | // sₜ = αxₜ + (1 - α)sₜ₋₁ 157 | rainAccumulator = MathHelper.lerp(smoothingFactor, rainAccumulator, newValue); 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/SoundPhysicsMod.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics; 2 | 3 | import com.sonicether.soundphysics.config.BlueTapePack.ConfigManager; 4 | import net.fabricmc.api.ModInitializer; 5 | import net.minecraft.sound.BlockSoundGroup; 6 | import net.minecraft.util.Pair; 7 | 8 | 9 | import java.lang.reflect.Modifier; 10 | import java.util.Arrays; 11 | import java.util.Map; 12 | import java.util.stream.Collectors; 13 | 14 | import static java.util.Map.entry; 15 | 16 | /* 17 | Notes for developers: 18 | !!! Import settings.zip to your IDEA !!! - important notices are marked like that 19 | ψ This is for anchors that you'd like to jump to from the scroll bar ψ 20 | //rm is for temporary test code like "System.out.println(var) //rm" (actually */ //rm) 21 | //*/ 22 | 23 | public class SoundPhysicsMod implements ModInitializer { 24 | public static Map> blockSoundGroups; 25 | public static Map groupSoundBlocks; 26 | @Override 27 | public void onInitialize() 28 | { 29 | blockSoundGroups = Arrays.stream(BlockSoundGroup.class.getDeclaredFields()) 30 | .filter((f) -> { 31 | try { 32 | return Modifier.isStatic(f.getModifiers()) && Modifier.isPublic(f.getModifiers()) 33 | && (f.get(null) instanceof BlockSoundGroup group) && !redirectMap.containsKey(group); 34 | } catch (IllegalAccessException e) { 35 | e.printStackTrace(); 36 | } 37 | return false; 38 | }) 39 | .collect(Collectors.toMap( 40 | (f) -> { 41 | try { 42 | return (BlockSoundGroup)f.get(null); 43 | } catch (IllegalAccessException | ClassCastException e) { 44 | e.printStackTrace(); 45 | } 46 | return null; 47 | }, 48 | (f) -> { 49 | try { 50 | return new Pair<>(f.getName(), (f.get(null) instanceof BlockSoundGroup g ? (groupMap.containsKey(f.getName()) ? groupMap.get(f.getName()) : g.getBreakSound().getId().getPath().split("\\.")[1] ): "not a group")); 51 | } catch (IllegalAccessException e) { 52 | e.printStackTrace(); 53 | } 54 | return new Pair<>("", ""); 55 | })); 56 | groupSoundBlocks = Arrays.stream(BlockSoundGroup.class.getDeclaredFields()) 57 | .filter((f) -> { 58 | try { 59 | return Modifier.isStatic(f.getModifiers()) && Modifier.isPublic(f.getModifiers()) 60 | && (f.get(null) instanceof BlockSoundGroup group) && !redirectMap.containsKey(group); 61 | } catch (IllegalAccessException e) { 62 | e.printStackTrace(); 63 | } 64 | return false; 65 | }).map((f)-> { 66 | BlockSoundGroup b; 67 | try { b = (BlockSoundGroup)f.get(null); } 68 | catch (IllegalAccessException | ClassCastException e) { e.printStackTrace(); b = null;} 69 | return new Pair<>(f.getName(),b); 70 | }).filter((f) -> f.getRight() != null) 71 | .collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); 72 | 73 | ConfigManager.registerAutoConfig(); 74 | } 75 | 76 | public static final Map redirectMap = // 77 | Map.ofEntries( // first becomes second 78 | entry(BlockSoundGroup.MOSS_CARPET, BlockSoundGroup.MOSS_BLOCK), 79 | entry(BlockSoundGroup.AMETHYST_CLUSTER, BlockSoundGroup.AMETHYST_BLOCK), 80 | entry(BlockSoundGroup.SMALL_AMETHYST_BUD, BlockSoundGroup.AMETHYST_BLOCK), 81 | entry(BlockSoundGroup.MEDIUM_AMETHYST_BUD, BlockSoundGroup.AMETHYST_BLOCK), 82 | entry(BlockSoundGroup.LARGE_AMETHYST_BUD, BlockSoundGroup.AMETHYST_BLOCK), 83 | entry(BlockSoundGroup.POINTED_DRIPSTONE, BlockSoundGroup.DRIPSTONE_BLOCK), 84 | entry(BlockSoundGroup.FLOWERING_AZALEA, BlockSoundGroup.AZALEA), 85 | entry(BlockSoundGroup.DEEPSLATE_BRICKS, BlockSoundGroup.POLISHED_DEEPSLATE), 86 | entry(BlockSoundGroup.COPPER, BlockSoundGroup.METAL), 87 | entry(BlockSoundGroup.ANVIL, BlockSoundGroup.METAL), 88 | entry(BlockSoundGroup.NETHER_SPROUTS, BlockSoundGroup.ROOTS), 89 | entry(BlockSoundGroup.WEEPING_VINES_LOW_PITCH, BlockSoundGroup.WEEPING_VINES), 90 | entry(BlockSoundGroup.LILY_PAD, BlockSoundGroup.WET_GRASS), 91 | entry(BlockSoundGroup.NETHER_GOLD_ORE, BlockSoundGroup.NETHERRACK), 92 | entry(BlockSoundGroup.NETHER_ORE, BlockSoundGroup.NETHERRACK), 93 | entry(BlockSoundGroup.CALCITE, BlockSoundGroup.STONE), 94 | entry(BlockSoundGroup.GILDED_BLACKSTONE, BlockSoundGroup.STONE), 95 | entry(BlockSoundGroup.SMALL_DRIPLEAF, BlockSoundGroup.CAVE_VINES), 96 | entry(BlockSoundGroup.BIG_DRIPLEAF, BlockSoundGroup.CAVE_VINES), 97 | entry(BlockSoundGroup.SPORE_BLOSSOM, BlockSoundGroup.CAVE_VINES), 98 | entry(BlockSoundGroup.GLOW_LICHEN, BlockSoundGroup.VINE), 99 | entry(BlockSoundGroup.HANGING_ROOTS, BlockSoundGroup.VINE), 100 | entry(BlockSoundGroup.ROOTED_DIRT, BlockSoundGroup.GRAVEL), 101 | entry(BlockSoundGroup.WART_BLOCK, BlockSoundGroup.NETHER_WART), 102 | entry(BlockSoundGroup.CROP, BlockSoundGroup.GRASS), 103 | entry(BlockSoundGroup.BAMBOO_SAPLING, BlockSoundGroup.GRASS), 104 | entry(BlockSoundGroup.SWEET_BERRY_BUSH, BlockSoundGroup.GRASS), 105 | entry(BlockSoundGroup.SCAFFOLDING, BlockSoundGroup.BAMBOO), 106 | entry(BlockSoundGroup.LODESTONE, BlockSoundGroup.NETHERITE), 107 | entry(BlockSoundGroup.LADDER, BlockSoundGroup.WOOD) 108 | );// 109 | public static final Map groupMap = // 110 | Map.ofEntries( 111 | entry("field_11528", "Coral" ), // Coral (coral_block) 112 | entry("field_11529", "Gravel, Dirt" ), // Gravel, Dirt (gravel, rooted_dirt) 113 | entry("field_27197", "Amethyst" ), // Amethyst (amethyst_block, small_amethyst_bud, medium_amethyst_bud, large_amethyst_bud, amethyst_cluster) 114 | entry("field_11526", "Sand" ), // Sand (sand) 115 | entry("field_27196", "Candle Wax" ), // Candle Wax (candle) 116 | entry("field_22140", "Weeping Vines" ), // Weeping Vines (weeping_vines, weeping_vines_low_pitch) 117 | entry("field_22141", "Soul Sand" ), // Soul Sand (soul_sand) 118 | entry("field_22142", "Soul Soil" ), // Soul Soil (soul_soil) 119 | entry("field_22143", "Basalt" ), // Basalt (basalt) 120 | entry("field_22145", "Netherrack" ), // Netherrack (netherrack, nether_ore, nether_gold_ore) 121 | entry("field_22146", "Nether Brick" ), // Nether Brick (nether_bricks) 122 | entry("field_21214", "Honey" ), // Honey (honey_block) 123 | entry("field_22149", "Bone" ), // Bone (bone_block) 124 | entry("field_17581", "Nether Wart" ), // Nether Wart (nether_wart, wart_block) 125 | entry("field_11535", "Grass, Crops, Foliage" ), // Grass, Crops, Foliage (grass, crop, bamboo_sapling, sweet_berry_bush) 126 | entry("field_11533", "Metal" ), // Metal (metal, copper, anvil) 127 | entry("field_11534", "Aquatic Foliage" ), // Aquatic Foliage (wet_grass, lily_pad) 128 | entry("field_11537", "Glass, Ice" ), // Glass, Ice (glass) 129 | entry("field_28116", "Sculk Sensor" ), // Sculk Sensor (sculk_sensor) 130 | entry("field_22138", "Nether Foliage" ), // Nether Foliage (roots, nether_sprouts) 131 | entry("field_22139", "Shroomlight" ), // Shroomlight (shroomlight) 132 | entry("field_24119", "Chain" ), // Chain (chain) 133 | entry("field_29033", "Deepslate" ), // Deepslate (deepslate) 134 | entry("field_11547", "Wood" ), // Wood (wood, ladder) 135 | entry("field_29035", "Deepslate Tiles" ), // Deepslate Tiles (deepslate_tiles) 136 | entry("field_11544", "Stone, Blackstone" ), // Stone, Blackstone (stone, calcite, gilded_blackstone) 137 | entry("field_11545", "Slime" ), // Slime (slime_block) 138 | entry("field_29036", "Polished Deepslate" ), // Polished Deepslate (polished_deepslate, deepslate_bricks) 139 | entry("field_11548", "Snow" ), // Snow (snow) 140 | entry("field_28702", "Azalea Leaves" ), // Azalea Leaves (azalea_leaves) 141 | entry("field_11542", "Bamboo" ), // Bamboo (bamboo, scaffolding) 142 | entry("field_18852", "Mushroom Stems" ), // Mushroom Stems (stem) 143 | entry("field_11543", "Wool" ), // Wool (wool) 144 | entry("field_23083", "Dry Foliage" ), // Dry Foliage (vine, hanging_roots, glow_lichen) 145 | entry("field_28694", "Azalea Bush" ), // Azalea Bush (azalea) 146 | entry("field_28692", "Lush Cave Foliage" ), // Lush Cave Foliage (cave_vines, spore_blossom, small_dripleaf, big_dripleaf) 147 | entry("field_22150", "Netherite" ), // Netherite (netherite_block, lodestone) 148 | entry("field_22151", "Ancient Debris" ), // Ancient Debris (ancient_debris) 149 | entry("field_22152", "Nether Fungus Stem" ), // Nether Fungus Stem (nether_stem) 150 | entry("field_27884", "Powder Snow" ), // Powder Snow (powder_snow) 151 | entry("field_27202", "Tuff" ), // Tuff (tuff) 152 | entry("field_28697", "Moss" ), // Moss (moss, moss_carpet) 153 | entry("field_22153", "Nylium" ), // Nylium (nylium) 154 | entry("field_22154", "Nether Mushroom" ), // Nether Mushroom (fungus) 155 | entry("field_17734", "Lanterns" ), // Lanterns (lantern) 156 | entry("field_28060", "Dripstone" ), // Dripstone (dripstone_block, pointed_dripstone) 157 | entry("DEFAULT" , "Default Material" ) // Default Material () 158 | );/**/ 159 | 160 | } 161 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/performance/RaycastFix.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.performance; 2 | 3 | import net.minecraft.block.BlockState; 4 | import net.minecraft.block.Blocks; 5 | import net.minecraft.particle.ParticleTypes; 6 | import net.minecraft.util.math.BlockPos; 7 | import net.minecraft.util.math.Direction; 8 | import net.minecraft.util.math.MathHelper; 9 | import net.minecraft.util.math.Vec3d; 10 | import net.minecraft.util.shape.VoxelShape; 11 | import net.minecraft.util.shape.VoxelShapes; 12 | import net.minecraft.world.World; 13 | import net.minecraft.world.chunk.ChunkStatus; 14 | import net.minecraft.world.chunk.WorldChunk; 15 | import org.jetbrains.annotations.Nullable; 16 | 17 | import java.util.Map; 18 | import java.util.concurrent.ConcurrentHashMap; 19 | 20 | import static com.sonicether.soundphysics.config.PrecomputedConfig.pC; 21 | 22 | public class RaycastFix { 23 | 24 | public static long lastUpd = 0; 25 | public static Map shapeCache = new ConcurrentHashMap<>(2048); 26 | // reset every tick, usually up to 2200 27 | // {pos, (block state, block, fluid) } 28 | 29 | public static int maxY; 30 | public static int minY; 31 | public static int maxX; 32 | public static int minX; 33 | public static int maxZ; 34 | public static int minZ; 35 | 36 | private final static VoxelShape EMPTY = VoxelShapes.empty(); 37 | private final static VoxelShape CUBE = VoxelShapes.fullCube(); 38 | 39 | // ===copied and modified=== 40 | 41 | public static SPHitResult fixedRaycast(Vec3d start, Vec3d end, World world, @Nullable BlockPos ignore, @Nullable WorldChunk chunk) { 42 | LiquidStorage currentNotAirStorage = chunk == null ? null : ((WorldChunkAccess)chunk).getNotAirLiquidStorage(); 43 | int currentX = chunk == null ? ((int) Math.floor(start.x)) >> 4 : chunk.getPos().x; 44 | int currentZ = chunk == null ? ((int) Math.floor(start.z)) >> 4 : chunk.getPos().z; 45 | boolean[] currentSlice = currentNotAirStorage == null ? null :currentNotAirStorage.getSection((int)Math.floor(start.y)); 46 | int currentY = (int) start.y; 47 | // 48 | 49 | if (start.x > maxX || start.y > maxY || start.z > maxZ || start.x < minX || start.y < minY || start.z < minZ) { 50 | return SPHitResult.createMissed(start, null, new BlockPos(start), chunk); 51 | } 52 | Vec3d delta = end.subtract(start); 53 | if (!(end.x <= maxX && end.y <= maxY && end.z <= maxZ && end.x >= minX && end.y >= minY && end.z >= minZ)) { 54 | double fx = delta.x == 0 ? Double.MAX_VALUE : (((delta.x > 0 ? maxX : minX) - start.x) / delta.x); 55 | double fy = delta.y == 0 ? Double.MAX_VALUE : (((delta.y > 0 ? maxY : minY) - start.y) / delta.y); 56 | double fz = delta.z == 0 ? Double.MAX_VALUE : (((delta.z > 0 ? maxZ : minZ) - start.z) / delta.z); 57 | double factor = Math.min(Math.min(fx, fy), fz); 58 | delta = delta.multiply(factor); 59 | end = start.add(delta); 60 | }// 61 | 62 | 63 | if (start.equals(end)) { 64 | return SPHitResult.createMissed(end, null, new BlockPos(end), chunk); 65 | } else { 66 | double xe1 = MathHelper.lerp(-1.0E-7D, end.x, start.x); // x end v1.1 67 | double ye1 = MathHelper.lerp(-1.0E-7D, end.y, start.y); 68 | double ze1 = MathHelper.lerp(-1.0E-7D, end.z, start.z); 69 | double xs1 = MathHelper.lerp(-1.0E-7D, start.x, end.x); // x start v1.1 70 | double ys1 = MathHelper.lerp(-1.0E-7D, start.y, end.y); 71 | double zs1 = MathHelper.lerp(-1.0E-7D, start.z, end.z); 72 | int xbs = MathHelper.floor(xs1); // x blockPos start v1.1 73 | int ybs = MathHelper.floor(ys1); 74 | int zbs = MathHelper.floor(zs1); 75 | BlockPos.Mutable blockPosStart1 = new BlockPos.Mutable(xbs, ybs, zbs); 76 | ////////////////////// 77 | int xx = xbs >> 4; int zz = zbs >> 4; 78 | if (currentX != xx || currentZ != zz) { 79 | if (currentNotAirStorage != null) { 80 | int ddx = currentX - xx; int ddz = currentZ - zz; 81 | if (ddz == 0) { 82 | if (ddx == -1) chunk = currentNotAirStorage.xm; 83 | else if (ddx == 1) chunk = currentNotAirStorage.xp; 84 | } else if (ddx == 0) { 85 | if (ddz == -1) chunk = currentNotAirStorage.zm; 86 | else if (ddz == 1) chunk = currentNotAirStorage.zp; 87 | } else chunk = (WorldChunk) world.getChunk(xx, zz, ChunkStatus.FULL, false); 88 | } else 89 | chunk = (WorldChunk) world.getChunk(xx, zz, ChunkStatus.FULL, false); 90 | currentX = xx; currentZ = zz; currentY = ybs; 91 | currentNotAirStorage = chunk == null ? null : ((WorldChunkAccess)chunk).getNotAirLiquidStorage(); 92 | currentSlice = currentNotAirStorage == null ? null : currentNotAirStorage.getSection(ybs); 93 | } else if (ybs != currentY) { 94 | currentSlice = currentNotAirStorage == null ? null : currentNotAirStorage.getSection(ybs); 95 | currentY = ybs; 96 | } 97 | ///////////////////// 98 | final SPHitResult hitResultStart; 99 | if (currentSlice == null || !currentSlice[(xbs & 15) + ((zbs & 15) << 4)] || blockPosStart1.equals(ignore)) 100 | hitResultStart = null; 101 | else { 102 | BlockState bs1 = chunk.getBlockState(blockPosStart1); 103 | if (bs1.isAir() || bs1.getBlock().equals(Blocks.MOVING_PISTON)) hitResultStart = null; 104 | else hitResultStart = finalRaycast(world, bs1, blockPosStart1, start, end, chunk, (short)4); 105 | } 106 | 107 | if (hitResultStart != null) { 108 | return hitResultStart; 109 | } else { 110 | double dx = xe1 - xs1; 111 | double dy = ye1 - ys1; 112 | double dz = ze1 - zs1; 113 | int dirx = MathHelper.sign(dx); 114 | int diry = MathHelper.sign(dy); 115 | int dirz = MathHelper.sign(dz); 116 | double rdx = dirx == 0 ? 1.7976931348623157E300D : (double)dirx / dx; // 1/dx 117 | double rdy = diry == 0 ? 1.7976931348623157E300D : (double)diry / dy; 118 | double rdz = dirz == 0 ? 1.7976931348623157E300D : (double)dirz / dz; 119 | double tx = rdx * (dirx > 0 ? 1.0D - MathHelper.fractionalPart(xs1) : MathHelper.fractionalPart(xs1)); // relative to blockPos start 120 | double ty = rdy * (diry > 0 ? 1.0D - MathHelper.fractionalPart(ys1) : MathHelper.fractionalPart(ys1)); 121 | double tz = rdz * (dirz > 0 ? 1.0D - MathHelper.fractionalPart(zs1) : MathHelper.fractionalPart(zs1)); 122 | 123 | SPHitResult object2 = null; 124 | do { 125 | if (tx > 1.0D && ty > 1.0D && tz > 1.0D) { 126 | return SPHitResult.createMissed(end, null, new BlockPos(end), chunk); 127 | } 128 | 129 | short side; 130 | 131 | if (tx < ty) { 132 | if (tx < tz) { 133 | xbs += dirx; 134 | tx += rdx; 135 | side = 1; 136 | } else { 137 | zbs += dirz; 138 | tz += rdz; 139 | side = 3; 140 | } 141 | } else if (ty < tz) { 142 | ybs += diry; 143 | ty += rdy; 144 | side = 2; 145 | } else { 146 | zbs += dirz; 147 | tz += rdz; 148 | side = 3; 149 | } 150 | 151 | ///////////////////// 152 | int x = xbs >> 4; int z = zbs >> 4; 153 | if (currentX != x || currentZ != z) { 154 | if (currentNotAirStorage != null) { 155 | int ddx = currentX - x; int ddz = currentZ - z; 156 | if (ddz == 0) { 157 | if (ddx == -1) chunk = currentNotAirStorage.xm; 158 | else if (ddx == 1) chunk = currentNotAirStorage.xp; 159 | } else if (ddx == 0) { 160 | if (ddz == -1) chunk = currentNotAirStorage.zm; 161 | else if (ddz == 1) chunk = currentNotAirStorage.zp; 162 | } else chunk = (WorldChunk) world.getChunk(x, z, ChunkStatus.FULL, false); 163 | } else 164 | chunk = (WorldChunk) world.getChunk(x, z, ChunkStatus.FULL, false); 165 | currentX = x; currentZ = z; currentY = ybs; 166 | currentNotAirStorage = chunk == null ? null : ((WorldChunkAccess)chunk).getNotAirLiquidStorage(); 167 | currentSlice = currentNotAirStorage == null ? null : currentNotAirStorage.getSection(ybs); 168 | } else if (ybs != currentY) { 169 | currentSlice = currentNotAirStorage == null ? null : currentNotAirStorage.getSection(ybs); 170 | currentY = ybs; 171 | } 172 | ///////////////////// 173 | blockPosStart1.set(xbs, ybs, zbs); 174 | //SoundPhysics.t1(); 175 | //final long t = System.nanoTime();// rm 176 | //SoundPhysics.tt.addAndGet(System.nanoTime()-t);// rm 177 | 178 | if (currentSlice != null) { 179 | if (currentSlice[(xbs & 15) + ((zbs & 15) << 4)] && !blockPosStart1.equals(ignore)) { 180 | BlockState bs = chunk.getBlockState(blockPosStart1); 181 | 182 | if (!bs.isAir() && !bs.getBlock().equals(Blocks.MOVING_PISTON)) { 183 | Vec3d start1; 184 | double f; 185 | if (side == 1) { 186 | f = (((-dirx * 0.499 + xbs + 0.5) - start.x) * rdx * dirx); 187 | } else if (side == 2) { 188 | f = (((-diry * 0.499 + ybs + 0.5) - start.y) * rdy * diry); 189 | } else { 190 | f = (((-dirz * 0.499 + zbs + 0.5) - start.z) * rdz * dirz); 191 | } 192 | start1 = start.add(delta.multiply(f)); 193 | Vec3d end1; 194 | double fx = (((dirx * 0.5001 + xbs + 0.5) - start.x) * rdx * dirx); 195 | double fy = (((diry * 0.5001 + ybs + 0.5) - start.y) * rdy * diry); 196 | double fz = (((dirz * 0.5001 + zbs + 0.5) - start.z) * rdz * dirz); 197 | end1 = start.add(delta.multiply(Math.min(Math.min(fx, fy), fz))); 198 | 199 | object2 = finalRaycast(world, bs, blockPosStart1, start1, end1, chunk, side); 200 | } 201 | } 202 | } else { 203 | int dx1 = ((dirx * 15 + (x<<5) + 15)>>1) - xbs; int dz1 = ((dirz * 15 + (z<<5) + 15)>>1) - zbs; 204 | double dtx1 = dx1 * rdx * dirx; double dtz1 = dz1 * rdz * dirz; 205 | if (currentNotAirStorage == null || currentNotAirStorage.isEmpty() 206 | || (diry == 1 && ybs > currentNotAirStorage.top) || (diry == -1 && ybs < currentNotAirStorage.bottom) 207 | || (dtx1+tx < ty && dtz1+tz < ty)) { 208 | 209 | if (dtx1 > dtz1){ 210 | zbs+=dz1; tz+=dtz1; 211 | } else { 212 | xbs+=dx1; tx+=dtx1; 213 | } 214 | } else { while (dx1 > 0 && dz1 > 0) { 215 | if (tx < ty) { 216 | if (tx < tz) { 217 | xbs += dirx; 218 | tx += rdx; 219 | dx1-=dirx; 220 | } else { 221 | zbs += dirz; 222 | tz += rdz; 223 | dz1-=dirz; 224 | } 225 | } else if (ty < tz) { 226 | break; 227 | } else { 228 | zbs += dirz; 229 | tz += rdz; 230 | dz1-=dirz; 231 | } 232 | } } 233 | } 234 | } while(object2 == null); 235 | 236 | return object2; 237 | } 238 | } 239 | } 240 | 241 | private static SPHitResult finalRaycast(World world, BlockState bs, BlockPos pos, Vec3d start, Vec3d end, WorldChunk c, Short side) { 242 | long posl = pos.asLong(); 243 | Shapes shapes; 244 | shapes = shapeCache.get(posl); 245 | if (shapes == null) { 246 | if (pC.dRays) world.addParticle(ParticleTypes.END_ROD, false, pos.getX() + 0.5d, pos.getY() + 1d, pos.getZ() + 0.5d, 0, 0, 0); 247 | VoxelShape fluidShape = bs.getFluidState().getShape(world, pos); 248 | VoxelShape collisionShape = bs.getCollisionShape(world, pos); 249 | shapes = new Shapes(collisionShape == EMPTY ? null : collisionShape, fluidShape == EMPTY ? null : fluidShape); 250 | shapeCache.put(posl, shapes); 251 | } 252 | 253 | VoxelShape voxelShape = shapes.getSolid();//BlockShape 254 | VoxelShape voxelShape2 = shapes.getLiquid();//FluidShape 255 | if (voxelShape == CUBE || voxelShape2 == CUBE) { 256 | Direction direction = 257 | side == 1 ? Direction.EAST : 258 | side == 2 ? Direction.UP : 259 | side == 3 ? Direction.NORTH : 260 | Direction.getFacing(start.x-pos.getX()-0.5, start.y-pos.getY()-0.5, start.z-pos.getZ()-0.5); 261 | return new SPHitResult(false, start, direction, pos, bs, c); 262 | } 263 | SPHitResult blockHitResult = voxelShape == null ? null : SPHitResult.get(voxelShape.raycast(start, end, pos), bs, c); 264 | SPHitResult blockHitResult2 = voxelShape2 == null ? null : SPHitResult.get(voxelShape2.raycast(start, end, pos), bs, c); 265 | 266 | if (blockHitResult2 == null) return blockHitResult; 267 | if (blockHitResult == null) return blockHitResult2; 268 | double d = start.squaredDistanceTo(blockHitResult.getPos()); 269 | double e = start.squaredDistanceTo(blockHitResult2.getPos()); 270 | return d <= e ? blockHitResult : blockHitResult2; 271 | } 272 | 273 | 274 | } 275 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/config/presets/ConfigPresets.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.config.presets; 2 | 3 | import com.sonicether.soundphysics.config.BlueTapePack.ConfigManager; 4 | import com.sonicether.soundphysics.config.MaterialData; 5 | import com.sonicether.soundphysics.config.SoundPhysicsConfig; 6 | import org.jetbrains.annotations.Nullable; 7 | 8 | import java.util.Map; 9 | import static java.util.Map.entry; 10 | import java.util.function.Consumer; 11 | import java.lang.String; 12 | 13 | import static com.sonicether.soundphysics.config.presets.ConfigChanger.changeConfig; 14 | 15 | @SuppressWarnings({"unused", "RedundantTypeArguments"}) 16 | public enum ConfigPresets { 17 | // Press ctrl+shift+numpad_'-' to collapse all 18 | LOAD_SUCCESS("Choose", null), 19 | // 20 | DEFAULT_BALANCED("Balanced (Base)", (SoundPhysicsConfig c) -> changeConfig(c, true, 21 | 22 | 1.0, 1.0, 1.0, 1.0, 23 | 1.0, 4.0, 1.0, 1.0, 1.0, 0.8, 24 | 25 | true, 224, 12, false, 26 | 27 | Map.ofEntries(entry("DEFAULT", new MaterialData(0.5, 0.5))), 28 | 29 | 4, 10.0, true, true, 0.5, false 30 | )),// 31 | // 32 | DEFAULT_PERFORMANCE("Performance (Base)", (SoundPhysicsConfig c) -> changeConfig(c, true, 33 | 34 | 1.0, 1.0, 1.0, 1.0, 35 | 1.0, 4.0, 1.0, 1.0, 1.0, 0.8, 36 | 37 | true, 96, 6, true, 38 | 39 | Map.ofEntries(entry("DEFAULT", new MaterialData(0.5, 0.5))), 40 | 41 | 4, 10.0, true, true, 0.5, true 42 | )),// 43 | // 44 | DEFAULT_QUALITY("Quality (Base)", (SoundPhysicsConfig c) -> changeConfig(c, true, 45 | 46 | 1.0, 1.0, 1.0, 1.0, 47 | 1.0, 4.0, 1.0, 1.0, 1.0, 0.8, 48 | 49 | false, 512, 24, false, 50 | 51 | Map.ofEntries(entry("DEFAULT", new MaterialData(0.5, 0.5))), 52 | 53 | 4, 10.0, true, true, 0.5, false 54 | )),// 55 | // 56 | THEDOCRUBY("Dr. Rubisco's Signature Sound", (SoundPhysicsConfig c) -> changeConfig(c, true, 57 | 58 | 1.0, 0.8, 1.0, 0.8, 59 | 1.0, 3.5, 1.0, 1.0, 1.0, 0.8, 60 | 61 | true, 256, 16, false, 62 | 63 | // 64 | Map.ofEntries( 65 | entry("field_11528", new MaterialData(0.2, 0.45 )), // Coral (coral_block) 66 | entry("field_11529", new MaterialData(0.5, 0.4 )), // Gravel, Dirt (gravel, rooted_dirt) 67 | entry("field_27197", new MaterialData(0.75, 0.45 )), // Amethyst (amethyst_block, small_amethyst_bud, medium_amethyst_bud, large_amethyst_bud, amethyst_cluster) 68 | entry("field_11526", new MaterialData(0.1, 0.45 )), // Sand (sand) 69 | entry("field_27196", new MaterialData(0.4, 0.3 )), // Candle Wax (candle) 70 | entry("field_22140", new MaterialData(0.2, 0.2 )), // Weeping Vines (weeping_vines, weeping_vines_low_pitch) 71 | entry("field_22141", new MaterialData(0.05, 0.65 )), // Soul Sand (soul_sand) 72 | entry("field_22142", new MaterialData(0.1, 0.7 )), // Soul Soil (soul_soil) 73 | entry("field_22143", new MaterialData(0.8, 0.3 )), // Basalt (basalt) 74 | entry("field_22145", new MaterialData(0.75, 0.45 )), // Netherrack (netherrack, nether_ore, nether_gold_ore) 75 | entry("field_22146", new MaterialData(0.85, 0.55 )), // Nether Brick (nether_bricks) 76 | entry("field_21214", new MaterialData(0.08, 0.85 )), // Honey (honey_block) 77 | entry("field_22149", new MaterialData(0.7, 0.55 )), // Bone (bone_block) 78 | entry("field_17581", new MaterialData(0.2, 0.8 )), // Nether Wart (nether_wart, wart_block) 79 | entry("field_11535", new MaterialData(0.2, 0.6 )), // Crops and Foliage (grass, crop, bamboo_sapling, sweet_berry_bush) 80 | entry("field_11533", new MaterialData(0.85, 0.5 )), // Metal (metal, copper, anvil) 81 | entry("field_11534", new MaterialData(0.15, 0.8 )), // Aquatic Foliage (wet_grass, lily_pad) 82 | entry("field_11537", new MaterialData(0.5, 0.45 )), // Glass, Ice (glass) 83 | entry("field_28116", new MaterialData(0.4, 0.6 )), // Sculk Sensor (sculk_sensor) 84 | entry("field_22138", new MaterialData(0.15, 0.55 )), // Nether Foliage (roots, nether_sprouts) 85 | entry("field_22139", new MaterialData(0.85, 0.75 )), // Shroomlight (shroomlight) 86 | entry("field_24119", new MaterialData(0.4, 0.4 )), // Chain (chain) 87 | entry("field_29033", new MaterialData(0.88, 0.55 )), // Deepslate (deepslate) 88 | entry("field_11547", new MaterialData(0.65, 0.45 )), // Wood (wood, ladder) 89 | entry("field_29035", new MaterialData(0.95, 0.55 )), // Deepslate Tiles (deepslate_tiles) 90 | entry("field_11544", new MaterialData(0.83, 0.5 )), // Stone, Blackstone (stone, calcite, gilded_blackstone) 91 | entry("field_11545", new MaterialData(1.0, 0.25 )), // Slime (slime_block) 92 | entry("field_29036", new MaterialData(0.99, 0.55 )), // Polished Deepslate (polished_deepslate, deepslate_bricks) 93 | entry("field_11548", new MaterialData(0.1, 0.5 )), // Snow (snow) 94 | entry("field_28702", new MaterialData(0.3, 0.35 )), // Azalea Leaves (azalea_leaves) 95 | entry("field_11542", new MaterialData(0.5, 0.4 )), // Bamboo (bamboo, scaffolding) 96 | entry("field_18852", new MaterialData(0.6, 0.65 )), // Mushroom Stems (stem) 97 | entry("field_11543", new MaterialData(0.02, 1.0 )), // Wool (wool) 98 | entry("field_23083", new MaterialData(0.1, 0.15 )), // Dry Foliage (vine, hanging_roots, glow_lichen) 99 | entry("field_28694", new MaterialData(0.15, 0.5 )), // Azalea Bush (azalea) 100 | entry("field_28692", new MaterialData(0.2, 0.2 )), // Lush Foliage (cave_vines, spore_blossom, small_dripleaf, big_dripleaf) 101 | entry("field_22150", new MaterialData(1.0, 0.6 )), // Netherite (netherite_block, lodestone) 102 | entry("field_22151", new MaterialData(0.45, 0.8 )), // Ancient Debris (ancient_debris) 103 | entry("field_22152", new MaterialData(0.3, 0.55 )), // Nether Fungus Stem (nether_stem) 104 | entry("field_27884", new MaterialData(0.01, 0.1 )), // Powder Snow (powder_snow) 105 | entry("field_27202", new MaterialData(0.35, 0.4 )), // Tuff (tuff) 106 | entry("field_28697", new MaterialData(0.1, 0.85 )), // Moss (moss, moss_carpet) 107 | entry("field_22153", new MaterialData(0.4, 0.55 )), // Nylium (nylium) 108 | entry("field_22154", new MaterialData(0.4, 0.6 )), // Nether Fungus (fungus) 109 | entry("field_17734", new MaterialData(0.75, 0.4 )), // Lanterns (lantern) 110 | entry("field_28060", new MaterialData(0.9, 0.6 )), // Dripstone (dripstone_block, pointed_dripstone) 111 | entry("DEFAULT" , new MaterialData(0.5, 0.5 )), // Default Material () 112 | entry("block.minecraft.water" , new MaterialData(0.5, 0.03 )) // Water (block.minecraft.water) 113 | ),// 114 | 115 | 4, 10.0, true, true, 0.5, false 116 | 117 | )),// 118 | // 119 | SUPER_REVERB("Super Reverb", (SoundPhysicsConfig c) -> changeConfig(c, true, 120 | null, 1.8, null, null, 121 | 4.0, null, null, null, null, null, 122 | 123 | null, null, null, null, 124 | 125 | null, 126 | 127 | null, null, null, null, null, null 128 | 129 | )),// 130 | // 131 | LUSH_REVERB("More Lush Cave Reverb", (SoundPhysicsConfig c) -> changeConfig(c, true, 132 | null, null, null, null, 133 | null, null, null, null, null, null, 134 | 135 | null, null, null, null, 136 | 137 | // 138 | Map.ofEntries( 139 | entry("field_28697", new MaterialData(0.85, 0.85 )), // Moss (moss, moss_carpet) 140 | entry("field_11529", new MaterialData(0.7, 0.4 )), // Gravel, Dirt (gravel, rooted_dirt) 141 | entry("field_23083", new MaterialData(0.25, 0.15 )), // Dry Foliage (vine, hanging_roots, glow_lichen) 142 | entry("field_28694", new MaterialData(0.45, 0.5 )), // Azalea Bush (azalea) 143 | entry("field_28692", new MaterialData(0.65, 0.2 )) // Lush Foliage (cave_vines, spore_blossom, small_dripleaf, big_dripleaf) 144 | ),// 145 | 146 | null, null, null, null, null, null 147 | )),// 148 | // 149 | NO_ABSORPTION("No Absorption", (SoundPhysicsConfig c) -> changeConfig(c, true, 150 | null, null, null, 0.0, 151 | null, null, 0.0, 0.0, 0.0, null, 152 | 153 | null, null, null, null, 154 | 155 | null, 156 | 157 | null, 0.0, null, null, null, null 158 | )),// 159 | // 160 | LOW_FREQ("Bass Boost", (SoundPhysicsConfig c) -> changeConfig(c, true, 161 | null, null, 0.2, null, 162 | null, null, 2.0, 2.0, 2.0, null, 163 | 164 | null, null, null, null, 165 | 166 | null, 167 | 168 | null, null, null, null, null, null 169 | )),// 170 | // 171 | HIGH_FREQ("Treble Boost", (SoundPhysicsConfig c) -> changeConfig(c, true, 172 | null, null, 1.8, null, 173 | null, null, 0.5, 0.5, 0.5, null, 174 | 175 | null, null, null, null, 176 | 177 | null, 178 | 179 | null, null, null, null, null, null 180 | )),// 181 | // 182 | FOG("Foggy Air", (SoundPhysicsConfig c) -> changeConfig(c, true, 183 | 2.5, null, null, null, 184 | null, null, 7.5, 0.5, 1.0, null, 185 | 186 | null, null, null, null, 187 | 188 | null, 189 | 190 | null, null, null, null, null, null 191 | )),// 192 | // 193 | TOTAL_OCCLUSION("Total Occlusion", (SoundPhysicsConfig c) -> changeConfig(c, true, 194 | 195 | null, null, null, 10.0, 196 | null, null, null, null, null, null, 197 | 198 | null, null, null, null, 199 | 200 | null, 201 | 202 | null, 10.0, null, null, null, null 203 | )),// 204 | // 205 | RESET_MATERIALS("Clear Material Properties", (SoundPhysicsConfig c) -> changeConfig(c, true, 206 | 207 | null, null, null, null, 208 | null, null, null, null, 209 | 210 | null, null, null, null, null, null, 211 | 212 | // 213 | Map.ofEntries( 214 | entry("field_11528", new MaterialData(0.2, 0.45 )), // Coral (coral_block) 215 | entry("field_11529", new MaterialData(0.5, 0.4 )), // Gravel, Dirt (gravel, rooted_dirt) 216 | entry("field_27197", new MaterialData(0.75, 0.45 )), // Amethyst (amethyst_block, small_amethyst_bud, medium_amethyst_bud, large_amethyst_bud, amethyst_cluster) 217 | entry("field_11526", new MaterialData(0.1, 0.45 )), // Sand (sand) 218 | entry("field_27196", new MaterialData(0.4, 0.3 )), // Candle Wax (candle) 219 | entry("field_22140", new MaterialData(0.2, 0.2 )), // Weeping Vines (weeping_vines, weeping_vines_low_pitch) 220 | entry("field_22141", new MaterialData(0.05, 0.65 )), // Soul Sand (soul_sand) 221 | entry("field_22142", new MaterialData(0.1, 0.7 )), // Soul Soil (soul_soil) 222 | entry("field_22143", new MaterialData(0.8, 0.3 )), // Basalt (basalt) 223 | entry("field_22145", new MaterialData(0.75, 0.45 )), // Netherrack (netherrack, nether_ore, nether_gold_ore) 224 | entry("field_22146", new MaterialData(0.85, 0.55 )), // Nether Brick (nether_bricks) 225 | entry("field_21214", new MaterialData(0.08, 0.85 )), // Honey (honey_block) 226 | entry("field_22149", new MaterialData(0.7, 0.55 )), // Bone (bone_block) 227 | entry("field_17581", new MaterialData(0.2, 0.8 )), // Nether Wart (nether_wart, wart_block) 228 | entry("field_11535", new MaterialData(0.2, 0.6 )), // Crops and Foliage (grass, crop, bamboo_sapling, sweet_berry_bush) 229 | entry("field_11533", new MaterialData(0.85, 0.5 )), // Metal (metal, copper, anvil) 230 | entry("field_11534", new MaterialData(0.15, 0.8 )), // Aquatic Foliage (wet_grass, lily_pad) 231 | entry("field_11537", new MaterialData(0.5, 0.45 )), // Glass, Ice (glass) 232 | entry("field_28116", new MaterialData(0.4, 0.6 )), // Sculk Sensor (sculk_sensor) 233 | entry("field_22138", new MaterialData(0.15, 0.55 )), // Nether Foliage (roots, nether_sprouts) 234 | entry("field_22139", new MaterialData(0.85, 0.75 )), // Shroomlight (shroomlight) 235 | entry("field_24119", new MaterialData(0.4, 0.4 )), // Chain (chain) 236 | entry("field_29033", new MaterialData(0.88, 0.55 )), // Deepslate (deepslate) 237 | entry("field_11547", new MaterialData(0.65, 0.45 )), // Wood (wood, ladder) 238 | entry("field_29035", new MaterialData(0.95, 0.55 )), // Deepslate Tiles (deepslate_tiles) 239 | entry("field_11544", new MaterialData(0.83, 0.5 )), // Stone, Blackstone (stone, calcite, gilded_blackstone) 240 | entry("field_11545", new MaterialData(1.0, 0.25 )), // Slime (slime_block) 241 | entry("field_29036", new MaterialData(0.99, 0.55 )), // Polished Deepslate (polished_deepslate, deepslate_bricks) 242 | entry("field_11548", new MaterialData(0.1, 0.5 )), // Snow (snow) 243 | entry("field_28702", new MaterialData(0.3, 0.35 )), // Azalea Leaves (azalea_leaves) 244 | entry("field_11542", new MaterialData(0.5, 0.4 )), // Bamboo (bamboo, scaffolding) 245 | entry("field_18852", new MaterialData(0.6, 0.65 )), // Mushroom Stems (stem) 246 | entry("field_11543", new MaterialData(0.02, 1.0 )), // Wool (wool) 247 | entry("field_23083", new MaterialData(0.1, 0.15 )), // Dry Foliage (vine, hanging_roots, glow_lichen) 248 | entry("field_28694", new MaterialData(0.15, 0.5 )), // Azalea Bush (azalea) 249 | entry("field_28692", new MaterialData(0.2, 0.2 )), // Lush Foliage (cave_vines, spore_blossom, small_dripleaf, big_dripleaf) 250 | entry("field_22150", new MaterialData(1.0, 0.6 )), // Netherite (netherite_block, lodestone) 251 | entry("field_22151", new MaterialData(0.45, 0.8 )), // Ancient Debris (ancient_debris) 252 | entry("field_22152", new MaterialData(0.3, 0.55 )), // Nether Fungus Stem (nether_stem) 253 | entry("field_27884", new MaterialData(0.01, 0.1 )), // Powder Snow (powder_snow) 254 | entry("field_27202", new MaterialData(0.35, 0.4 )), // Tuff (tuff) 255 | entry("field_28697", new MaterialData(0.1, 0.85 )), // Moss (moss, moss_carpet) 256 | entry("field_22153", new MaterialData(0.4, 0.55 )), // Nylium (nylium) 257 | entry("field_22154", new MaterialData(0.4, 0.6 )), // Nether Fungus (fungus) 258 | entry("field_17734", new MaterialData(0.75, 0.4 )), // Lanterns (lantern) 259 | entry("field_28060", new MaterialData(0.9, 0.6 )), // Dripstone (dripstone_block, pointed_dripstone) 260 | entry("DEFAULT" , new MaterialData(0.5, 0.5 )), // Default Material () 261 | entry("block.minecraft.water" , new MaterialData(0.5, 0.03 )) // Water (block.minecraft.water) 262 | ),// 263 | 264 | null, null, null, null,null, null 265 | ));// 266 | 267 | public final Consumer configChanger; 268 | public final String text; 269 | public void setConfig(){ if (configChanger != null) {configChanger.accept(ConfigManager.getConfig());ConfigManager.save();}} 270 | 271 | ConfigPresets(String text, @Nullable Consumer c) { 272 | this.configChanger = c; 273 | this.text = text; 274 | } 275 | 276 | @Override 277 | public String toString() { 278 | return this.text; 279 | } 280 | } 281 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/SoundPhysics.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics; 2 | 3 | import com.sonicether.soundphysics.performance.RaycastFix; 4 | import com.sonicether.soundphysics.performance.SPHitResult; 5 | import net.fabricmc.api.EnvType; 6 | import net.fabricmc.api.Environment; 7 | import net.minecraft.block.BlockState; 8 | import net.minecraft.client.MinecraftClient; 9 | import net.minecraft.sound.BlockSoundGroup; 10 | import net.minecraft.sound.SoundCategory; 11 | import net.minecraft.util.Formatting; 12 | import net.minecraft.util.math.BlockPos; 13 | import net.minecraft.util.math.MathHelper; 14 | import net.minecraft.util.math.Vec3d; 15 | import net.minecraft.util.math.Vec3i; 16 | import net.minecraft.world.chunk.WorldChunk; 17 | import org.jetbrains.annotations.NotNull; 18 | 19 | import java.awt.*; 20 | import java.util.List; 21 | import java.util.Map; 22 | import java.util.Vector; 23 | import java.util.concurrent.ConcurrentHashMap; 24 | import java.util.regex.Pattern; 25 | import java.util.stream.IntStream; 26 | 27 | import static com.sonicether.soundphysics.ALstuff.SPEfx.*; 28 | import static com.sonicether.soundphysics.SPLog.*; 29 | import static com.sonicether.soundphysics.performance.RaycastFix.fixedRaycast; 30 | import static com.sonicether.soundphysics.config.PrecomputedConfig.pC; 31 | 32 | @SuppressWarnings({"NonAsciiCharacters", "CommentedOutCode"}) 33 | @Environment(EnvType.CLIENT) //IDK why 34 | public class SoundPhysics 35 | { 36 | 37 | private static final Pattern rainPattern = Pattern.compile(".*rain.*"); 38 | public static final Pattern stepPattern = Pattern.compile(".*step.*"); // Also in EntityMixin.class 39 | private static final Pattern blockPattern = Pattern.compile(".*block..*"); 40 | private static final Pattern uiPattern = Pattern.compile("ui..*"); 41 | //Private fields 42 | // ψ time ψ 43 | //public static long tt = 0; 44 | //private static long ttt; 45 | //private static double cumtt = 0; 46 | //private static long navgt = 0; 47 | //public static void t1() {ttt = System.nanoTime(); } 48 | //public static void t2() { SoundPhysics.tt+=(System.nanoTime()-ttt);} 49 | //public static void tavg() { cumtt += tt; navgt++; } 50 | //public static void tout() { System.out.println((SoundPhysics.tt/1e6d) + " Avg: " + cumtt/navgt/1e6d); } 51 | //public static void tres() { SoundPhysics.tt=0; } 52 | 53 | public static MinecraftClient mc; 54 | private static SoundCategory lastSoundCategory; 55 | private static String lastSoundName; 56 | 57 | public static void init() { 58 | log("Initializing Sound Physics..."); 59 | setupEFX(); 60 | log("EFX ready..."); 61 | mc = MinecraftClient.getInstance(); 62 | //rand = new Random(System.currentTimeMillis()); 63 | } 64 | 65 | public static void setLastSoundCategoryAndName(SoundCategory sc, String name) { lastSoundCategory = sc; lastSoundName = name; } 66 | 67 | @SuppressWarnings("unused") @Deprecated 68 | public static void onPlaySound(double posX, double posY, double posZ, int sourceID){onPlaySoundReverb(posX, posY, posZ, sourceID, false);} 69 | 70 | @SuppressWarnings("unused") @Deprecated 71 | public static void onPlayReverb(double posX, double posY, double posZ, int sourceID){onPlaySoundReverb(posX, posY, posZ, sourceID, true);} 72 | 73 | public static void onPlaySoundReverb(double posX, double posY, double posZ, int sourceID, boolean auxOnly) { 74 | if (pC.dLog) logGeneral("On play sound... Source ID: " + sourceID + " " + posX + ", " + posY + ", " + posZ + " Sound category: " + lastSoundCategory.toString() + " Sound name: " + lastSoundName); 75 | 76 | long startTime = 0; 77 | long endTime; 78 | 79 | if (pC.pLog) startTime = System.nanoTime(); 80 | //t1();// rm 81 | evaluateEnvironment(sourceID, posX, posY, posZ, auxOnly); // time = 0.5? OωO 82 | //t2(); 83 | //tavg();tres();//tout();// ψ time ψ 84 | if (pC.pLog) { endTime = System.nanoTime(); 85 | log("Total calculation time for sound " + lastSoundName + ": " + (double)(endTime - startTime)/(double)1000000 + " milliseconds"); } 86 | 87 | } 88 | 89 | private static double getBlockReflectivity(final BlockState blockState) { 90 | BlockSoundGroup soundType = blockState.getSoundGroup(); 91 | String blockName = blockState.getBlock().getTranslationKey(); 92 | if (pC.blockWhiteSet.contains(blockName)) return pC.blockWhiteMap.get(blockName).reflectivity; 93 | 94 | double r = pC.reflectivityMap.getOrDefault(soundType, Double.NaN); 95 | return Double.isNaN(r) ? pC.defaultReflectivity : r; 96 | } 97 | 98 | private static double getBlockOcclusionD(final BlockState blockState) { 99 | BlockSoundGroup soundType = blockState.getSoundGroup(); 100 | String blockName = blockState.getBlock().getTranslationKey(); 101 | if (pC.blockWhiteSet.contains(blockName)) return pC.blockWhiteMap.get(blockName).absorption; 102 | 103 | double r = pC.absorptionMap.getOrDefault(soundType, Double.NaN); 104 | return Double.isNaN(r) ? pC.defaultAbsorption : r; 105 | } 106 | 107 | private static Vec3d pseudoReflect(Vec3d dir, Vec3i normal) 108 | {return new Vec3d(normal.getX() == 0 ? dir.x : -dir.x, normal.getY() == 0 ? dir.y : -dir.y, normal.getZ() == 0 ? dir.z : -dir.z);} 109 | 110 | @SuppressWarnings("ConstantConditions") 111 | private static void evaluateEnvironment(final int sourceID, double posX, double posY, double posZ, boolean auxOnly) { 112 | if (pC.off) return; 113 | 114 | if (mc.player == null || mc.world == null || posY <= mc.world.getBottomY() || (pC.recordsDisable && lastSoundCategory == SoundCategory.RECORDS) || uiPattern.matcher(lastSoundName).matches() || (posX == 0.0 && posY == 0.0 && posZ == 0.0)) 115 | { 116 | //logDetailed("Menu sound!"); 117 | setEnvironment(sourceID, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, auxOnly ? 0.0f : 1.0f); 118 | return; 119 | } 120 | final long timeT = mc.world.getTime(); 121 | 122 | final boolean isRain = rainPattern.matcher(lastSoundName).matches(); 123 | boolean block = blockPattern.matcher(lastSoundName).matches() && !stepPattern.matcher(lastSoundName).matches(); 124 | if (lastSoundCategory == SoundCategory.RECORDS){posX+=0.5;posY+=0.5;posZ+=0.5;block = true;} 125 | 126 | if (pC.skipRainOcclusionTracing && isRain) 127 | { 128 | setEnvironment(sourceID, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, auxOnly ? 0.0f : 1.0f); 129 | return; 130 | } 131 | 132 | if (RaycastFix.lastUpd != timeT) { 133 | if (timeT % 1024 == 0) { 134 | RaycastFix.shapeCache = new ConcurrentHashMap<>(2048); // just in case something gets corrupted 135 | //cumtt = 0; navgt = 0; ψ time ψ 136 | } 137 | else { 138 | RaycastFix.shapeCache.clear(); 139 | } 140 | RaycastFix.lastUpd = timeT; 141 | } 142 | final Vec3d playerPosOld = mc.player.getPos(); 143 | final Vec3d playerPos = new Vec3d(playerPosOld.x, playerPosOld.y + mc.player.getEyeHeight(mc.player.getPose()), playerPosOld.z); 144 | 145 | RaycastFix.maxY = mc.world.getTopY(); 146 | RaycastFix.minY = mc.world.getBottomY(); 147 | int dist = mc.options.viewDistance * 16; 148 | RaycastFix.maxX = (int) (playerPos.getX() + dist); 149 | RaycastFix.minX = (int) (playerPos.getX() - dist); 150 | RaycastFix.maxZ = (int) (playerPos.getZ() + dist); 151 | RaycastFix.minZ = (int) (playerPos.getZ() - dist); 152 | final WorldChunk soundChunk = mc.world.getChunk(((int)Math.floor(posX))>>4,((int)Math.floor(posZ))>>4); 153 | 154 | 155 | //Direct sound occlusion // time = 0.1 // TODO: This can be done better 156 | 157 | final Vec3d soundPos = new Vec3d(posX, posY, posZ); 158 | Vec3d normalToPlayer = playerPos.subtract(soundPos).normalize(); 159 | 160 | final BlockPos soundBlockPos = new BlockPos(soundPos.x, soundPos.y,soundPos.z); 161 | 162 | if (pC.dLog) logGeneral("Player pos: " + playerPos.x + ", " + playerPos.y + ", " + playerPos.z + " Sound Pos: " + soundPos.x + ", " + soundPos.y + ", " + soundPos.z + " To player vector: " + normalToPlayer.x + ", " + normalToPlayer.y + ", " + normalToPlayer.z); 163 | double occlusionAccumulation = 0; 164 | final List> directions = new Vector<>(10, 10); 165 | //Cast a ray from the source towards the player 166 | Vec3d rayOrigin = soundPos; 167 | //System.out.println(rayOrigin.toString()); 168 | BlockPos lastBlockPos = soundBlockPos; 169 | final boolean _9ray = pC._9Ray && (lastSoundCategory == SoundCategory.BLOCKS || block); 170 | final int nOccRays = _9ray ? 9 : 1; 171 | double occlusionAccMin = Double.MAX_VALUE; 172 | for (int j = 0; j < nOccRays; j++) { 173 | if(j > 0){ 174 | final int jj = j - 1; 175 | rayOrigin = new Vec3d(soundBlockPos.getX() + 0.001 + 0.998 * (jj % 2), soundBlockPos.getY() + 0.001 + 0.998 * ((jj >> 1) % 2), soundBlockPos.getZ() + 0.001 + 0.998 * ((jj >> 2) % 2)); 176 | lastBlockPos = soundBlockPos; 177 | occlusionAccumulation = 0; 178 | 179 | } 180 | boolean oAValid = false; 181 | SPHitResult rayHit = fixedRaycast(rayOrigin, playerPos, mc.world, lastBlockPos, soundChunk); 182 | 183 | for (int i = 0; i < 10; i++) { 184 | 185 | lastBlockPos = rayHit.getBlockPos(); 186 | //If we hit a block 187 | 188 | if (pC.dRays) RaycastRenderer.addOcclusionRay(rayOrigin, rayHit.getPos(), Color.getHSBColor((float) (1F / 3F * (1F - Math.min(1F, occlusionAccumulation / 12F))), 1F, 1F).getRGB()); 189 | if (rayHit.isMissed()) { 190 | if (pC.soundDirectionEvaluation) directions.add(Map.entry(rayOrigin.subtract(playerPos), 191 | (_9ray?9:1) * Math.pow(soundPos.distanceTo(playerPos), 2.0)* pC.rcpTotRays 192 | / 193 | (Math.exp(-occlusionAccumulation * pC.globalBlockAbsorption)* pC.directRaysDirEvalMultiplier) 194 | )); 195 | oAValid = true; 196 | break; 197 | } 198 | 199 | final Vec3d rayHitPos = rayHit.getPos(); 200 | final BlockState blockHit = rayHit.getBlockState(); 201 | double blockOcclusion = getBlockOcclusionD(blockHit); 202 | 203 | // Regardless to whether we hit from inside or outside 204 | 205 | if (pC.oLog) logOcclusion(blockHit.getBlock().getTranslationKey() + " " + rayHitPos.x + ", " + rayHitPos.y + ", " + rayHitPos.z); 206 | 207 | rayOrigin = rayHitPos; //new Vec3d(rayHit.getPos().x + normalToPlayer.x * 0.1, rayHit.getPos().y + normalToPlayer.y * 0.1, rayHit.getPos().z + normalToPlayer.z * 0.1); 208 | 209 | rayHit = fixedRaycast(rayOrigin, playerPos, mc.world, lastBlockPos, rayHit.chunk); 210 | 211 | SPHitResult rayBack = fixedRaycast(rayHit.getPos(), rayOrigin, mc.world, rayHit.getBlockPos(), rayHit.chunk); 212 | 213 | if (rayBack.getBlockPos().equals(lastBlockPos)) { 214 | //Accumulate density 215 | occlusionAccumulation += blockOcclusion * (rayOrigin.distanceTo(rayBack.getPos())); 216 | if (occlusionAccumulation > pC.maxDirectOcclusionFromBlocks) break; 217 | } 218 | 219 | if (pC.oLog) logOcclusion("New trace position: " + rayOrigin.x + ", " + rayOrigin.y + ", " + rayOrigin.z); 220 | } 221 | if (oAValid) occlusionAccMin = Math.min(occlusionAccMin, occlusionAccumulation); 222 | } 223 | occlusionAccumulation = Math.min(occlusionAccMin, pC.maxDirectOcclusionFromBlocks); 224 | double directCutoff = Math.exp(-occlusionAccumulation * pC.globalBlockAbsorption); 225 | double directGain = auxOnly ? 0 : Math.pow(directCutoff, 0.01); 226 | 227 | if (pC.oLog) logOcclusion("direct cutoff: " + directCutoff + " direct gain:" + directGain); 228 | 229 | final double[] δsendGain = {0d,0d,0d,0d}; 230 | 231 | if (isRain) {finalizeEnvironment(true, sourceID, directCutoff, 0, directGain, auxOnly, null, δsendGain); return;} 232 | 233 | // Shoot rays around sound 234 | 235 | final double maxDistance = 256 * pC.nRayBounces; 236 | 237 | boolean doDirEval = pC.soundDirectionEvaluation && (occlusionAccumulation > 0 || pC.notOccludedRedirect); 238 | 239 | final double[] bounceReflectivityRatio = new double[pC.nRayBounces]; 240 | 241 | final double[] sharedAirspace = new double[1]; 242 | 243 | final double gRatio = 1.618033988; 244 | final double epsilon; 245 | 246 | if (pC.nRays >= 600000) { epsilon = 214d; } 247 | else if (pC.nRays >= 400000) { epsilon = 75d; } 248 | else if (pC.nRays >= 11000) { epsilon = 27d; } 249 | else if (pC.nRays >= 890) { epsilon = 10d; } 250 | else if (pC.nRays >= 177) { epsilon = 3.33d; } 251 | else if (pC.nRays >= 24) { epsilon = 1.33d; } 252 | else { epsilon = 0.33d; } 253 | 254 | //for (int i = 0; i < pC.nRays; i++) 255 | 256 | IntStream stream = IntStream.range(0, pC.nRays); 257 | (pC.multiThreading ? stream.parallel() : stream).forEach((i) -> { // time = 3 258 | final double x = (i + epsilon) / (pC.nRays - 1d + 2d*epsilon); 259 | final double y = (double) i / gRatio; 260 | final double theta = 2d * Math.PI * y; 261 | final double phi = Math.acos(1d - 2d*x); 262 | 263 | final Vec3d rayDir = new Vec3d(Math.cos(theta) * Math.sin(phi), 264 | Math.sin(theta) * Math.sin(phi), Math.cos(phi)); 265 | 266 | final Vec3d rayEnd = new Vec3d(soundPos.x + rayDir.x * maxDistance, soundPos.y + rayDir.y * maxDistance, 267 | soundPos.z + rayDir.z * maxDistance); 268 | 269 | SPHitResult rayHit = fixedRaycast(soundPos, rayEnd, mc.world, soundBlockPos, soundChunk); 270 | 271 | if (pC.dRays) RaycastRenderer.addSoundBounceRay(soundPos, rayHit.getPos(), Formatting.GREEN.getColorValue()); 272 | 273 | // TODO: This can be done better 274 | if (!rayHit.isMissed()) { 275 | 276 | // Additional bounces 277 | BlockPos lastHitBlock = rayHit.getBlockPos(); 278 | Vec3d lastHitPos = rayHit.getPos(); 279 | Vec3i lastHitNormal = rayHit.getSide().getVector(); 280 | Vec3d lastRayDir = rayDir; 281 | 282 | double totalRayDistance = soundPos.distanceTo(rayHit.getPos()); 283 | 284 | double blockReflectivity = getBlockReflectivity(rayHit.getBlockState()); 285 | 286 | double totalReflectivityCoefficient = Math.min(blockReflectivity, 1); 287 | 288 | // Secondary ray bounces 289 | for (int j = 0; j < pC.nRayBounces; j++) { 290 | // Cast (one) final ray towards the player. If it's 291 | // unobstructed, then the sound source and the player 292 | // share airspace. 293 | final double energyTowardsPlayer = Math.pow(blockReflectivity, 1 / pC.globalBlockReflectance) * 0.1875 + 0.0625; 294 | if (!pC.simplerSharedAirspaceSimulation || j == pC.nRayBounces - 1) { 295 | final Vec3d finalRayStart = new Vec3d(lastHitPos.x + lastHitNormal.getX() * 0.01, 296 | lastHitPos.y + lastHitNormal.getY() * 0.01, lastHitPos.z + lastHitNormal.getZ() * 0.01); 297 | 298 | final SPHitResult finalRayHit = fixedRaycast(finalRayStart, playerPos, mc.world, null, rayHit.chunk); 299 | 300 | int color = Formatting.GRAY.getColorValue(); 301 | if (finalRayHit.isMissed()) { 302 | color = Formatting.WHITE.getColorValue(); 303 | 304 | double totalFinalRayDistance = totalRayDistance + finalRayStart.distanceTo(playerPos); 305 | 306 | if (doDirEval) synchronized (directions) {directions.add(Map.entry(finalRayStart.subtract(playerPos), (totalFinalRayDistance*totalFinalRayDistance)*(totalReflectivityCoefficient == 0d ? 1000000d : 1d/totalReflectivityCoefficient)));} 307 | //log("Secondary ray hit the player!"); 308 | 309 | synchronized (sharedAirspace) { sharedAirspace[0] += 1d; } 310 | 311 | final double reflectionDelay = Math.max(totalRayDistance, 0.0) * 0.12 * Math.pow(blockReflectivity, 1 / pC.globalBlockReflectance); 312 | 313 | final double cross0 = 1d - MathHelper.clamp(Math.abs(reflectionDelay - 0d), 0d, 1d); 314 | final double cross1 = 1d - MathHelper.clamp(Math.abs(reflectionDelay - 1d), 0d, 1d); 315 | final double cross2 = 1d - MathHelper.clamp(Math.abs(reflectionDelay - 2d), 0d, 1d); 316 | final double cross3 = MathHelper.clamp(reflectionDelay - 2d, 0d, 1d); 317 | 318 | double factor = energyTowardsPlayer * 12.8 * pC.rcpTotRays; 319 | synchronized (δsendGain) { 320 | δsendGain[0] += cross0 * factor * 0.5; 321 | δsendGain[1] += cross1 * factor; 322 | δsendGain[2] += cross2 * factor; 323 | δsendGain[3] += cross3 * factor; 324 | } 325 | 326 | } 327 | if (pC.dRays) RaycastRenderer.addSoundBounceRay(finalRayStart, finalRayHit.getPos(), color); 328 | } 329 | 330 | final Vec3d newRayDir = pseudoReflect(lastRayDir, lastHitNormal); 331 | final Vec3d newRayStart = lastHitPos; 332 | final Vec3d newRayEnd = new Vec3d(newRayStart.x + newRayDir.x * (maxDistance - totalRayDistance), 333 | newRayStart.y + newRayDir.y * (maxDistance - totalRayDistance), newRayStart.z + newRayDir.z * (maxDistance - totalRayDistance)); 334 | 335 | //log("New ray dir: " + newRayDir.xCoord + ", " + newRayDir.yCoord + ", " + newRayDir.zCoord); 336 | 337 | rayHit = fixedRaycast(newRayStart, newRayEnd, mc.world, lastHitBlock, rayHit.chunk); 338 | 339 | 340 | if (rayHit.isMissed()) { 341 | if (pC.dRays) RaycastRenderer.addSoundBounceRay(newRayStart, newRayEnd, Formatting.DARK_RED.getColorValue()); 342 | break; 343 | } else { 344 | final Vec3d newRayHitPos = rayHit.getPos(); 345 | final double newRayLength = lastHitPos.distanceTo(newRayHitPos); 346 | 347 | if (pC.dRays) RaycastRenderer.addSoundBounceRay(newRayStart, newRayHitPos, Formatting.BLUE.getColorValue()); 348 | 349 | 350 | synchronized (bounceReflectivityRatio) { bounceReflectivityRatio[j] += Math.pow(blockReflectivity, 1 / pC.globalBlockReflectance); } 351 | 352 | totalRayDistance += newRayLength; 353 | 354 | lastHitPos = newRayHitPos; 355 | lastHitNormal = rayHit.getSide().getVector(); 356 | lastRayDir = newRayDir; 357 | lastHitBlock = rayHit.getBlockPos(); 358 | blockReflectivity = getBlockReflectivity(rayHit.getBlockState()); 359 | totalReflectivityCoefficient *= Math.min(blockReflectivity, 1); 360 | 361 | } 362 | } 363 | } 364 | }); 365 | for (int i = 0; i < pC.nRayBounces; i++) { 366 | bounceReflectivityRatio[i] = bounceReflectivityRatio[i] / pC.nRays; // TODO: Why is this here? 367 | } 368 | 369 | // Take weighted (on squared distance) average of the directions sound reflection came from 370 | dirEval: // time = 0.04 // TODO: Make this better 371 | { 372 | if (directions.isEmpty()) break dirEval; 373 | 374 | if (pC.pLog) log("Evaluating direction from " + sharedAirspace[0] + " entries..."); 375 | Vec3d sum = new Vec3d(0, 0, 0); 376 | double weight = 0; 377 | 378 | for (Map.Entry direction : directions) { 379 | double val = direction.getValue(); 380 | if ( val <= 0.0 ) break dirEval; 381 | final double w = 1 / val; 382 | weight += w; 383 | sum = sum.add(direction.getKey().normalize().multiply(w)); 384 | } 385 | sum = sum.multiply(1 / weight); 386 | setSoundPos(sourceID, sum.normalize().multiply(soundPos.distanceTo(playerPos)).add(playerPos)); 387 | 388 | // ψ this shows a star at perceived sound pos ψ 389 | // Vec3d pos = sum.normalize().multiply(soundPos.distanceTo(playerPos)).add(playerPos); 390 | // mc.world.addParticle(ParticleTypes.END_ROD, false, pos.getX(), pos.getY(), pos.getZ(), 0,0,0); 391 | } 392 | 393 | 394 | finalizeEnvironment(false, sourceID, directCutoff, sharedAirspace[0], directGain, auxOnly, bounceReflectivityRatio, δsendGain); 395 | } 396 | 397 | private static void finalizeEnvironment(boolean isRain, int sourceID, double directCutoff, double sharedAirspace, double directGain, boolean auxOnly, double[] bounceReflectivityRatio, double @NotNull [] δsendGain) { // TODO: Fix questionable math 398 | // Calculate reverb parameters for this sound 399 | double sendGain0 = 0d + δsendGain[0]; 400 | double sendGain1 = 0d + δsendGain[1]; 401 | double sendGain2 = 0d + δsendGain[2]; 402 | double sendGain3 = 0d + δsendGain[3]; 403 | 404 | double sendCutoff0 = 1d; 405 | double sendCutoff1 = 1d; 406 | double sendCutoff2 = 1d; 407 | double sendCutoff3 = 1d; 408 | 409 | double directCutoff0 = directCutoff; 410 | assert mc.player != null; 411 | if (mc.player.isSubmergedInWater()) 412 | { 413 | directCutoff *= pC.underwaterFilter; 414 | } 415 | 416 | if (isRain) 417 | { 418 | setEnvironment(sourceID, (float) sendGain0, (float) sendGain1, (float) sendGain2, (float) sendGain3, (float) sendCutoff0, (float) sendCutoff1, (float) sendCutoff2, (float) sendCutoff3, (float) directCutoff, (float) directGain); 419 | return; 420 | } 421 | 422 | sharedAirspace *= 64d; 423 | 424 | if (pC.simplerSharedAirspaceSimulation) 425 | sharedAirspace /= pC.nRays; 426 | else 427 | sharedAirspace /= pC.nRays * pC.nRayBounces; 428 | 429 | final double sharedAirspaceWeight0 = MathHelper.clamp(sharedAirspace * 0.05, 0d, 1d); 430 | final double sharedAirspaceWeight1 = MathHelper.clamp(sharedAirspace * 0.06666666666666667, 0d, 1d); 431 | final double sharedAirspaceWeight2 = MathHelper.clamp(sharedAirspace * 0.1, 0d, 1d); 432 | final double sharedAirspaceWeight3 = MathHelper.clamp(sharedAirspace * 0.1, 0d, 1d); 433 | 434 | sendCutoff0 = directCutoff0 * (1d - sharedAirspaceWeight0) + sharedAirspaceWeight0; 435 | sendCutoff1 = directCutoff0 * (1d - sharedAirspaceWeight1) + sharedAirspaceWeight1; 436 | sendCutoff2 = directCutoff0 * (1d - sharedAirspaceWeight2) + sharedAirspaceWeight2; 437 | sendCutoff3 = directCutoff0 * (1d - sharedAirspaceWeight3) + sharedAirspaceWeight3; 438 | 439 | // attempt to preserve directionality when airspace is shared by allowing some dry signal through but filtered 440 | final double averageSharedAirspace = (sharedAirspaceWeight0 + sharedAirspaceWeight1 + sharedAirspaceWeight2 + sharedAirspaceWeight3) * 0.25; 441 | directCutoff = Math.max(Math.pow(averageSharedAirspace, 0.5) * 0.2, directCutoff); 442 | 443 | directGain = auxOnly ? 0d : Math.pow(directCutoff, 0.1); 444 | 445 | //logDetailed("HitRatio0: " + hitRatioBounce1 + " HitRatio1: " + hitRatioBounce2 + " HitRatio2: " + hitRatioBounce3 + " HitRatio3: " + hitRatioBounce4); 446 | 447 | if (pC.eLog) logEnvironment("Bounce reflectivity 0: " + bounceReflectivityRatio[0] + " bounce reflectivity 1: " + bounceReflectivityRatio[1] + " bounce reflectivity 2: " + bounceReflectivityRatio[2] + " bounce reflectivity 3: " + bounceReflectivityRatio[3]); 448 | 449 | 450 | sendGain1 *= bounceReflectivityRatio[1]; 451 | sendGain2 *= Math.pow(bounceReflectivityRatio[2], 3.0); 452 | sendGain3 *= Math.pow(bounceReflectivityRatio[3], 4.0); 453 | 454 | sendGain0 = MathHelper.clamp(sendGain0, 0d, 1d); 455 | sendGain1 = MathHelper.clamp(sendGain1, 0d, 1d); 456 | sendGain2 = MathHelper.clamp(sendGain2 * 1.05 - 0.05, 0d, 1d); 457 | sendGain3 = MathHelper.clamp(sendGain3 * 1.05 - 0.05, 0d, 1d); 458 | 459 | sendGain0 *= Math.pow(sendCutoff0, 0.1); 460 | sendGain1 *= Math.pow(sendCutoff1, 0.1); 461 | sendGain2 *= Math.pow(sendCutoff2, 0.1); 462 | sendGain3 *= Math.pow(sendCutoff3, 0.1); 463 | 464 | if (pC.eLog) logEnvironment("Final environment settings: " + sendGain0 + ", " + sendGain1 + ", " + sendGain2 + ", " + sendGain3); 465 | 466 | assert mc.player != null; 467 | if (mc.player.isSubmergedInWater()) 468 | { 469 | sendCutoff0 *= 0.4; 470 | sendCutoff1 *= 0.4; 471 | sendCutoff2 *= 0.4; 472 | sendCutoff3 *= 0.4; 473 | } 474 | setEnvironment(sourceID, (float) sendGain0, (float) sendGain1, (float) sendGain2, (float) sendGain3, (float) sendCutoff0, (float) sendCutoff1, (float) sendCutoff2, (float) sendCutoff3, (float) directCutoff, (float) directGain); 475 | 476 | } 477 | 478 | } 479 | -------------------------------------------------------------------------------- /src/main/java/com/sonicether/soundphysics/ALstuff/ReverbSlot.java: -------------------------------------------------------------------------------- 1 | package com.sonicether.soundphysics.ALstuff; 2 | 3 | import org.lwjgl.openal.AL10; 4 | import org.lwjgl.openal.AL11; 5 | import org.lwjgl.openal.EXTEfx; 6 | 7 | import static com.sonicether.soundphysics.SPLog.*; 8 | import static com.sonicether.soundphysics.config.PrecomputedConfig.pC; 9 | import static com.sonicether.soundphysics.config.PrecomputedConfig.defaultAttenuationFactor; 10 | 11 | @SuppressWarnings("DanglingJavadoc")//!!!!!!!!!!!! Ctrl + Shift + '-' !!!!!!!!!!!! 12 | public class ReverbSlot { 13 | public boolean initialised = false; 14 | public int auxSlotId; 15 | public int effectId; 16 | public int filterId; 17 | 18 | // 19 | // from: Effects Guide (p. 66+) and other sources; altered 20 | /** 21 | * Reverb Modal Density controls the coloration of the late reverb. 22 | * Lowering the value adds more coloration to the late reverb. 23 | * 24 | * Modal density is defined as the expected number of modes per unit frequency, which is given by: n(ω)=∂N(ω)∂ω=∂∂ω(kL/π)=Lπcg 25 | * 26 | * In music, normal modes of vibrating instruments (strings, air pipes, drums, etc.) are called "harmonics" or "overtones". 27 | * 28 | * ∴ High-frequency "depth"? 29 | *

30 | * Strutt|Building Acoustics|Room Modal Density allows the user to calculate the number of room modes present in a room up to a given frequency cut-off (number of modes) as well as the modal density (the number of modes per frequency band) using the Bolt and Morse formula. 31 | * 32 | * The number of modes, N from 0 Hz up to f Hz is given by: 33 | * 34 | * N=4πf³V/3c³+πf²S/4c²+fP/8c 35 | * 36 | * where: 37 | * f is the frequency (Hz) 38 | * V is the room volume (m³) 39 | * S is the room surface area (m²) 40 | * P is the total room perimeter (m) 41 | * 42 | * The above terms describe the number of oblique (∝f³), lateral (∝f²) and normal (∝f) modes in the room. Especially for high frequencies, the number of oblique modes is generally dominant. 43 | * 44 | * The modal density is given by: 45 | * 46 | * ⇒⇒⇒ dN/df=4πf²/Vc³+πfS/2c²+P/8c 47 | * 48 | * Although derived for rectangular rooms, the above expressions give good estimates of the modal behaviour for rooms of arbitrary shape, provided that the aspect ratio of the room is not too extreme. 49 | *

50 | */ 51 | public final float density; // min: 0.0f max: 1.0f (?) default: 1.0f 52 | /** 53 | * The Reverb Diffusion property controls the echo density in the reverberation decay. 54 | * It is set by default to 1.0, which provides the highest density. 55 | * Reducing diffusion gives the reverberation a more “grainy” character 56 | * that is especially noticeable with percussive (a rhythmic patterning of noise, ex. clapping, stomping) sound sources. 57 | * If you set a diffusion value of 0.0, the later reverberation sounds like a succession of distinct echoes. 58 | * ∴ 1.0 ⇒ uniform noise 59 | * 60 | * #See other fields for more# 61 | * 62 | * A commonly overlooked parameter on reverb plugins is diffusion. 63 | * This helps to control the initial build up of echo density and effects how you hear the reverb reflections. 64 | * As a guide, for clearer more natural sounding mixes, vocals and instruments use low parameter settings. 65 | * If you’re looking to enhance percussion and drum hits use medium to high settings. 66 | */ 67 | public final float diffusion; // min: 0.0f max: 1.0f (a linear multiplier value) default: 1.0f 68 | /** 69 | * The Reverb Gain property is the master volume control for the reflected sound 70 | * (both early reflections and reverberation), that the reverb effect adds to all sound sources. 71 | * It sets the maximum amount of reflections and reverberation added to the final sound mix. 72 | * The value of the Reverb Gain property ranges from 1.0 (0db) (the maximum amount) 73 | * to 0.0 (-100db) (no reflected sound at all). 74 | */ 75 | public final float gain; // min: 0.0f max: 1.0f (Linear gain) default: 0.32f 76 | /** 77 | * The Reverb Gain HF property further tweaks reflected sound by attenuating (gradually fading) it at high frequencies. 78 | * It controls a low-pass filter that applies globally to the reflected sound of all sound sources feeding the particular instance of the reverb effect. 79 | * The value of the Reverb Gain HF property ranges from 1.0 (0db) (no filter) to 0.0 (-100db) (virtually no reflected sound). 80 | * #HF Reference# sets the frequency at which the value of this property is measured. 81 | */ 82 | public final float gainHF; // min: 0.0f max: 1.0f (Linear gain) default: 0.89f 83 | /** 84 | * The Reverb Gain LF property further tweaks reflected sound by attenuating it at low frequencies. 85 | * It controls a high-pass filter that applies globally to the reflected sound of all sound sources feeding the particular instance of the reverb effect. 86 | * The value of the Reverb Gain LF property ranges from 1.0 (0db) (no filter) to 0.0 (-100db) (virtually no reflected sound). 87 | * #LF Reference# sets the frequency at which the value of this property is measured. 88 | */ 89 | //public final float gainLF; // min: 0.0f max: 1.0f (Linear gain) default: 0.0f 90 | /** 91 | * The Decay Time property sets the reverberation decay time. 92 | * It ranges from 0.1 (typically a small room with very dead surfaces) 93 | * to 20.0 (typically a large room with very live surfaces). 94 | */ 95 | public final float decayTime; // min: 0.1f max: 20.0f (Seconds) default: 1.49f 96 | /** 97 | * The Decay HF Ratio property adjusts the spectral quality of the Decay Time parameter. 98 | * It is the ratio of high-frequency decay time relative to the time set by Decay Time. 99 | * The Decay HF Ratio value 1.0 is neutral: the decay time is equal for all frequencies. 100 | * 101 | * As Decay HF Ratio increases above 1.0, the high-frequency decay time increases, 102 | * so it’s longer than the decay time at mid-frequencies. 103 | * You hear a more brilliant reverberation with a longer decay at high frequencies. 104 | * 105 | * As the Decay HF Ratio value decreases below 1.0, the high-frequency decay time decreases, 106 | * so it’s shorter than the decay time of the mid-frequencies. 107 | * You hear a more natural reverberation. 108 | */ 109 | public final float decayHFRatio; // min: 0.1f max: 20.0f (Linear multiplier) default: 0.83f 110 | /** 111 | * The Decay LF Ratio property adjusts the spectral quality of the Decay Time parameter. 112 | * It is the ratio of low-frequency decay time relative to the time set by Decay Time. 113 | * The Decay LF Ratio value 1.0 is neutral: the decay time is equal for all frequencies. 114 | * 115 | * As Decay LF Ratio increases above 1.0, the low-frequency decay time increases, 116 | * so it’s longer than the decay time at mid-frequencies. 117 | * You hear a more booming reverberation with a longer decay at low frequencies. 118 | * 119 | * As the Decay LF Ratio value decreases below 1.0, the low-frequency decay time decreases, 120 | * so it’s shorter than the decay time of the mid-frequencies. 121 | * You hear a more tinny reverberation. 122 | */ 123 | //public final float decayLFRatio; // min: 0.1f max: 20.0f (Linear multiplier) default: 1.0f 124 | /** 125 | * The Reflections Gain property controls the overall amount of initial reflections relative to the Gain property. 126 | * (The Gain property sets the overall amount of reflected sound: both initial reflections and later reverberation.) 127 | * The value of Reflections Gain ranges from a maximum of 3.16 (+10 dB) 128 | * to a minimum of 0.0 (-100 dB) (no initial reflections at all), and is corrected by the value of the Gain property. 129 | * The Reflections Gain property does not affect the subsequent reverberation decay. 130 | * You can increase the amount of initial reflections to simulate a more narrow space or closer walls, 131 | * especially effective if you associate the initial reflections increase with a reduction in reflections delays 132 | * by lowering the value of the Reflection Delay property. 133 | * To simulate open or semi-open environments, you can maintain the amount of early reflections while reducing the value of 134 | * the Late Reverb Gain property, which controls later reflections. 135 | */ 136 | public final float reflectionsGain; // min: 0.1f max: 3.16f (Linear gain) default: 0.05 137 | /** 138 | * The Reflections Delay property is the amount of delay between the arrival time of the direct path from the source 139 | * to the first reflection from the source. It ranges from 0 to 300 milliseconds. 140 | * You can reduce or increase "Reflections Delay" to simulate closer or more distant reflective surfaces, 141 | * and therefore control the perceived size of the room. 142 | */ 143 | public final float reflectionsDelay; // min: 0.0f max: 0.3f (Seconds) default: 0.007 144 | /** 145 | * The Reflections Pan property is a 3D vector that controls the spatial distribution of the cluster of early reflections. 146 | * The direction of this vector controls the global direction of the reflections, 147 | * while its magnitude controls how focused the reflections are towards this direction. 148 | * It is important to note that the direction of the vector is interpreted in the coordinate system of the user, 149 | * without taking into account the orientation of the virtual listener. 150 | * For instance, assuming a four-point loudspeaker playback system, 151 | * setting Reflections Pan to (0., 0., 0.7) means that the reflections are panned to the front speaker pair, 152 | * whereas setting of (0., 0., −0.7) pans the reflections towards the rear speakers. 153 | * These vectors follow a left-handed coordinate system, unlike OpenAL uses a right-handed coordinate system. 154 | * If the magnitude of Reflections Pan is zero (the default setting), the early reflections come evenly from all directions. 155 | * As the magnitude increases, the reflections become more focused in the direction pointed to by the vector. 156 | * A magnitude of 1.0 would represent the extreme case, where all reflections come from a single direction. 157 | */ 158 | //public float[] reflectionsPan;//magnitude min: 0.0f max: 1.0f (Vector) default: [0f, 0f, 0f] 159 | /** 160 | * The Late Reverb Gain property controls the overall amount of later reverberation relative to the Gain property. 161 | * (The Gain property sets the overall amount of both initial reflections and later reverberation.) 162 | * The value of Late Reverb Gain ranges from a maximum of 10.0 (+20 dB) to a minimum of 0.0 (-100 dB) (no late reverberation at all). 163 | * Note that Late Reverb Gain and Decay Time are independent properties: 164 | * If you adjust Decay Time without changing Late Reverb Gain, the total intensity 165 | * (the averaged square of the amplitude) of the late reverberation remains constant. 166 | */ 167 | public final float lateReverbGain; // min: 0.0f max: 10.0f (Linear gain) default: 1.26f 168 | /** 169 | * The Late Reverb Delay property defines the beginning time of the late reverberation 170 | * relative to the time of the initial reflection (the first of the early reflections). It ranges from 0 to 100 milliseconds. 171 | * Reducing or increasing Late Reverb Delay is useful for simulating a smaller or larger room. 172 | */ 173 | public final float lateReverbDelay; // min: 0.0f max: 0.1f (Seconds) default: 0.011f 174 | /** 175 | * The Late Reverb Pan property is a 3D vector that controls the spatial distribution of the late reverb. 176 | * The direction of this vector controls the global direction of the reverb, 177 | * while its magnitude controls how focused the reverb are towards this direction. 178 | * The details under Reflections Pan (above) also apply to Late Reverb Pan. 179 | */ 180 | //public float[] lateReverbPan;//magnitude min: 0.0f max: 1.0f (Vector) default: [0f, 0f, 0f] 181 | /** 182 | * Echo Depth introduces a cyclic echo in the reverberation decay, which will be noticeable with transient or percussive sounds. 183 | * A larger value of Echo Depth will make this effect more prominent. 184 | * 185 | * Echo Time controls the rate at which the cyclic echo repeats itself along the reverberation decay. 186 | * For example, the default setting for Echo Time is 250 ms., causing the echo to occur 4 times per second. 187 | * Therefore, if you were to clap your hands in this type of environment, you will hear four repetitions of clap per second. 188 | * Together with Reverb Diffusion, Echo Depth will control how long the echo effect will persist along the reverberation decay. 189 | * 190 | * In a more diffuse environment, echoes will wash out more quickly after the direct sound. 191 | * 192 | * In an environment that is less diffuse, you will be able to hear a larger number of repetitions of the echo, 193 | * which will wash out later in the reverberation decay. 194 | * 195 | * If Diffusion is set to 0.0 and Echo Depth is set to 1.0, the echo will persist distinctly until the end of the reverberation decay. 196 | */ 197 | //public float echoTime; // min: 0.075f max: 0.25f (Seconds) default: 0.25f 198 | //public float echoDepth; // min: 0.0f max: 1.0f (Linear multiplier) default: 0.0f 199 | /** 200 | * Using these two properties, you can create a pitch modulation in the reverberant sound. 201 | * This will be most noticeable applied to sources that have tonal color or pitch. 202 | * You can use this to make some trippy effects! 203 | * Modulation Time controls the speed of the vibrato (rate of periodic changes in pitch). 204 | * Modulation Depth controls the amount of pitch change. 205 | * Low values of Diffusion will contribute to reinforcing the perceived effect by 206 | * reducing the mixing of overlapping reflections in the reverberation decay. 207 | */ 208 | //public final float modulationTime; // min: 0.004f max: 4.0f (Seconds) default: 0.25f 209 | //public final float modulationDepth; // min: 0.0f max: 1.0f (Linear multiplier) default: 0.0f 210 | /** 211 | * The properties "HF Reference" and "LF Reference" determine respectively the frequencies at which 212 | * the high-frequency effects and the low-frequency effects created by EAX Reverb properties are measured, 213 | * for example #Decay HF Ratio# and #Decay LF Ratio#. 214 | * Note that it is necessary to maintain a factor of at least 10 between these two reference frequencies so that 215 | * low frequency and high frequency properties can be accurately controlled and will produce independent effects. 216 | * In other words, the LF Reference value should be less than 1/10 of the HF Reference value. 217 | */ 218 | //public final float HFReference; // min: 1000f max: 20000f (Hertz) default: 5000f 219 | //public final float LFReference; // min: 20.0f max: 1000f (Hertz) default: 250f 220 | /** 221 | * The Room Rolloff Factor property is one of the two methods available to attenuate the reflected sound 222 | * (containing both reflections and reverberation) according to source-listener distance. 223 | * It is defined the same way as OpenAL’s Rolloff Factor, but operates on reverb sound instead of direct-path sound. 224 | * Setting the Room Rolloff Factor value to 1.0 specifies that the reflected sound will decay by 6 dB every time the distance doubles. 225 | * Any value other than 1.0 is equivalent to a scaling factor applied to the quantity specified by 226 | * ((Source listener distance) - (Reference Distance)). 227 | * Reference Distance is an OpenAL source parameter that specifies the inner border for distance rolloff effects: 228 | * if the source comes closer to the listener than the reference distance, 229 | * the direct-path sound isn’t increased as the source comes closer to the listener, 230 | * and neither is the reflected sound. The default value of Room Rolloff Factor is 0.0 because, by default, 231 | * the Effects Extension reverb effect naturally manages the reflected sound level automatically for each 232 | * sound source to simulate the natural rolloff of reflected sound vs. distance in typical rooms. 233 | * (Note that this isn’t the case if the source property flag AL_AUXILIARY_SEND_FILTER_GAIN_AUTO is set to AL_FALSE) 234 | * You can use Room Rolloff Factor as an option to automatic control, so you can exaggerate or replace the default automatically-controlled rolloff. 235 | */ 236 | public final float roomRolloffFactor; // min: 0.0f max: 10.0f (Linear multiplier) default: 0.0f 237 | /** 238 | * The Air Absorption Gain HF property controls the distance-dependent attenuation at high frequencies caused by the propagation medium. 239 | * It applies to reflected sound only. 240 | * You can use Air Absorption Gain HF to simulate sound transmission through foggy air, dry air, smoky atmosphere, and so on. 241 | * The default value is 0.994 (-0.05 dB) per meter, which roughly corresponds to typical condition of atmospheric humidity, temperature, and so on. 242 | * Lowering the value simulates a more absorbent medium (more humidity in the air, for example); 243 | * raising the value simulates a less absorbent medium (dry desert air, for example). 244 | */ 245 | public float airAbsorptionGainHF; // min: 0.892f max: 1.0f (Linear gain per meter) default: 0.994f 246 | /** 247 | * When this flag is set, the high-frequency decay time automatically stays below a limit value that is 248 | * derived from the setting of the property Air Absorption Gain HF. 249 | * This limit applies regardless of the setting of the property Decay HF Ratio, and the limit doesn't affect the value of Decay HF Ratio. 250 | * This limit, when on, maintains a natural sounding reverberation decay by allowing you to increase the 251 | * value of Decay Time without the risk of getting an unnaturally long decay time at high frequencies. 252 | * If this flag is set to AL_FALSE, high-frequency decay time isn’t automatically limited. 253 | */ 254 | //public final int decayHFLimit; // min:AL_FALSE max:AL_TRUE (Boolean) default: true 255 | //
256 | 257 | public ReverbSlot(/**/float decayTime, float density, float diffusion, float gain, float gainHF, float decayHFRatio, float reflectionsGain, float reflectionsDelay, float lateReverbGain, float lateReverbDelay, float airAbsorptionGainHF, float roomRolloffFactor/**/) { 258 | this.decayTime = decayTime; 259 | this.density = density; 260 | this.diffusion = diffusion; 261 | this.gain = gain; 262 | this.gainHF = gainHF; 263 | this.decayHFRatio = decayHFRatio; 264 | this.reflectionsGain = reflectionsGain; 265 | this.reflectionsDelay = reflectionsDelay; 266 | this.lateReverbGain = lateReverbGain; 267 | this.lateReverbDelay = lateReverbDelay; 268 | this.airAbsorptionGainHF = airAbsorptionGainHF; 269 | this.roomRolloffFactor = roomRolloffFactor; 270 | } 271 | 272 | public void initialize() { 273 | if (initialised) delete(); 274 | 275 | // 276 | // Create auxiliary effect slot (secondary audio output) 277 | auxSlotId = EXTEfx.alGenAuxiliaryEffectSlots(); 278 | logGeneral("Aux slot " + auxSlotId + " created"); 279 | EXTEfx.alAuxiliaryEffectSloti(auxSlotId, EXTEfx.AL_EFFECTSLOT_AUXILIARY_SEND_AUTO, AL10.AL_TRUE); 280 | checkErrorLog("Failed creating reverb slot "+auxSlotId+"!"); 281 | 282 | //Create effect objects 283 | effectId = EXTEfx.alGenEffects(); //Create effect object 284 | EXTEfx.alEffecti(effectId, EXTEfx.AL_EFFECT_TYPE, EXTEfx.AL_EFFECT_EAXREVERB); //Set effect object to be reverb 285 | checkErrorLog("Failed creating reverb effect "+effectId+"!"); 286 | logGeneral("effect for "+auxSlotId+": "+effectId); 287 | 288 | filterId = EXTEfx.alGenFilters(); 289 | EXTEfx.alFilteri(filterId, EXTEfx.AL_FILTER_TYPE, EXTEfx.AL_FILTER_LOWPASS); 290 | logGeneral("filter for "+auxSlotId+": "+filterId); 291 | // 292 | 293 | initialised = true; 294 | this.set(); 295 | } 296 | 297 | public void delete() { 298 | EXTEfx.alDeleteAuxiliaryEffectSlots(auxSlotId); 299 | EXTEfx.alDeleteEffects(effectId); 300 | EXTEfx.alDeleteFilters(filterId); 301 | initialised = false; 302 | } 303 | 304 | public void set() { 305 | // 306 | EXTEfx.alEffectf(effectId, EXTEfx.AL_EAXREVERB_DENSITY, density); 307 | checkErrorLog("Error while assigning reverb density: " + density); 308 | EXTEfx.alEffectf(effectId, EXTEfx.AL_EAXREVERB_DIFFUSION, diffusion); 309 | checkErrorLog("Error while assigning reverb diffusion: " + diffusion); 310 | EXTEfx.alEffectf(effectId, EXTEfx.AL_EAXREVERB_GAIN, gain * pC.globalReverbGain); 311 | checkErrorLog("Error while assigning reverb gain: " + gain * pC.globalReverbGain); 312 | EXTEfx.alEffectf(effectId, EXTEfx.AL_EAXREVERB_GAINHF, gainHF); 313 | checkErrorLog("Error while assigning reverb gainHF: " + gainHF); 314 | EXTEfx.alEffectf(effectId, EXTEfx.AL_EAXREVERB_DECAY_TIME, decayTime); 315 | checkErrorLog("Error while assigning reverb decayTime: " + decayTime); 316 | EXTEfx.alEffectf(effectId, EXTEfx.AL_EAXREVERB_DECAY_HFRATIO, decayHFRatio * pC.globalReverbBrightness); 317 | checkErrorLog("Error while assigning reverb decayHFRatio: " + decayHFRatio * pC.globalReverbBrightness); 318 | EXTEfx.alEffectf(effectId, EXTEfx.AL_EAXREVERB_REFLECTIONS_GAIN, reflectionsGain); 319 | checkErrorLog("Error while assigning reverb reflectionsGain: " + reflectionsGain); 320 | EXTEfx.alEffectf(effectId, EXTEfx.AL_EAXREVERB_REFLECTIONS_DELAY, reflectionsDelay); 321 | checkErrorLog("Error while assigning reverb reflectionsDelay: " + reflectionsDelay); 322 | EXTEfx.alEffectf(effectId, EXTEfx.AL_EAXREVERB_LATE_REVERB_GAIN, lateReverbGain); 323 | checkErrorLog("Error while assigning reverb lateReverbGain: " + lateReverbGain); 324 | EXTEfx.alEffectf(effectId, EXTEfx.AL_EAXREVERB_LATE_REVERB_DELAY, lateReverbDelay); 325 | checkErrorLog("Error while assigning reverb lateReverbDelay: " + lateReverbDelay); 326 | EXTEfx.alEffectf(effectId, EXTEfx.AL_EAXREVERB_AIR_ABSORPTION_GAINHF, airAbsorptionGainHF); 327 | checkErrorLog("Error while assigning reverb airAbsorptionGainHF: " + airAbsorptionGainHF); 328 | EXTEfx.alEffectf(effectId, EXTEfx.AL_EAXREVERB_ROOM_ROLLOFF_FACTOR, (float) (roomRolloffFactor * defaultAttenuationFactor)); 329 | checkErrorLog("Error while assigning reverb roomRolloffFactor: " + roomRolloffFactor * defaultAttenuationFactor); 330 | // 331 | 332 | //Attach updated effect object 333 | EXTEfx.alAuxiliaryEffectSloti(auxSlotId, EXTEfx.AL_EFFECTSLOT_EFFECT, effectId); 334 | } 335 | 336 | public void applyFilter(int sourceID, float gain, float cutoff) { 337 | // Set reverb send filter values and set source to send to all reverb fx slots 338 | EXTEfx.alFilterf(filterId, EXTEfx.AL_LOWPASS_GAIN, gain); 339 | EXTEfx.alFilterf(filterId, EXTEfx.AL_LOWPASS_GAINHF, cutoff); 340 | AL11.alSource3i(sourceID, EXTEfx.AL_AUXILIARY_SEND_FILTER, auxSlotId, 1, filterId); 341 | checkErrorLog("Set Environment filter"+filterId+" to "+auxSlotId+":"); 342 | } 343 | } 344 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------