Skip to content

Commit

Permalink
Initial commit for repository creation
Browse files Browse the repository at this point in the history
  • Loading branch information
SerTheGreat committed Oct 9, 2016
0 parents commit def885e
Show file tree
Hide file tree
Showing 11 changed files with 377 additions and 0 deletions.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
//MUFFLER CONFIG

debug = false //spew various messages as stuff happens inside the plugin
enabled = true //self-explanatory
wallCutoff = 500 //sound that pass through a part's wall will be reduced to this frequency
minimalCutoff = 0 //minimal frequency to which sound are reduced by air sparseness. 300 is the value of the old Audio Muffler (makes sounds become a deep bass rumble in vacuum instead of total silence)
66 changes: 66 additions & 0 deletions Muffler/AudioMixerFacade.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using System;
using UnityEngine;
using UnityEngine.Audio;

namespace AudioMuffler {

/// <summary>
/// Description of AudioMixerFacade.
/// </summary>
public class AudioMixerFacade
{

private static bool BundleLoaded = false;

private static AudioMixer audioMixer;

public AudioMixerGroup masterGroup {get; set;}
public AudioMixerGroup inVesselGroup {get; set;}
public AudioMixerGroup outsideGroup {get; set;}

public void setInVesselCutoff(float cutoff) {
audioMixer.SetFloat("InVesselCutoff", cutoff);
}

public void setOutsideCutoff(float cutoff) {
audioMixer.SetFloat("OutsideCutoff", cutoff);
}

public static AudioMixerFacade initializeMixer(string path) {
AudioMixerFacade instance = new AudioMixerFacade ();
if (audioMixer == null) {
audioMixer = LoadBundle (path);
}
instance.masterGroup = audioMixer.FindMatchingGroups ("Master") [0];
instance.inVesselGroup = audioMixer.FindMatchingGroups ("InVessel") [0];
instance.outsideGroup = audioMixer.FindMatchingGroups ("Outside") [0];
return instance;
}

public static AudioMixer LoadBundle(string path)
{
if (BundleLoaded) {
return null;
}

using (WWW www = new WWW ("file://" + path)) {
if (www.error != null) {
Debug.Log ("Audio Muffler: Mixer bundle not found!");
return null;
}

AssetBundle bundle = www.assetBundle;

AudioMixer audioMixer = bundle.LoadAsset<AudioMixer> ("KSPAudioMixer");

bundle.Unload (false);
www.Dispose ();

BundleLoaded = true;
return audioMixer;
}
}

}

}
21 changes: 21 additions & 0 deletions Muffler/MeshToPart.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using UnityEngine;

namespace AudioMuffler {

/// <summary>
/// Description of MeshToPart.
/// </summary>
public class MeshToPart
{

public MeshFilter meshFilter { get; set;}
public Part part { get; set;}

public MeshToPart(MeshFilter meshFilter, Part part)
{
this.meshFilter = meshFilter;
this.part = part;
}
}

}
138 changes: 138 additions & 0 deletions Muffler/Muffler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
using System.Collections.Generic;
using System;
using UnityEngine;

namespace AudioMuffler {

[KSPAddon(KSPAddon.Startup.Flight, false)]
public class Muffler : MonoBehaviour
{
private bool debug = true;
private bool engageMuffler = true;
private float wallCutoff = 500f;
private float minimalCutoff = 0f;
private List<MeshToPart> meshToPartList = new List<MeshToPart>();
private AudioMixerFacade audioMixer;

void Awake()
{
string path = KSP.IO.IOUtils.GetFilePathFor(typeof(Muffler), "muffler.cfg").Replace("/", System.IO.Path.DirectorySeparatorChar.ToString());
if (debug) {
writeDebug("Loading cfg from path " + path);
}

ConfigNode node = ConfigNode.Load(path);

debug = bool.Parse(node.GetValue("debug"));
engageMuffler = bool.Parse(node.GetValue("enabled"));
wallCutoff = float.Parse(node.GetValue("wallCutoff"));
minimalCutoff = float.Parse(node.GetValue("minimalCutoff"));
}

void Start()
{
if (!engageMuffler)
return;

GameEvents.onVesselChange.Add(VesselChange);
GameEvents.onVesselWasModified.Add(VesselWasModified);

AudioSource[] audioSources = FindObjectsOfType(typeof(AudioSource)) as AudioSource[];
audioMixer = AudioMixerFacade.initializeMixer(KSP.IO.IOUtils.GetFilePathFor(typeof(Muffler), "mixer.bundle").Replace("/", System.IO.Path.DirectorySeparatorChar.ToString()));
StockAudio.prepareAudioSources(audioMixer, audioSources);
audioMixer.setInVesselCutoff(wallCutoff);
rebuildVesselMeshList();
}

void VesselChange(Vessel v)
{
rebuildVesselMeshList();
}

void VesselWasModified(Vessel vessel) {
if (vessel.isActiveVessel) {
rebuildVesselMeshList();
}
}

void Update()
{
if (!engageMuffler)
return;

Vector3 earPosition = CameraManager.GetCurrentCamera().transform.position;

//Looking for a part containing the Ear:
Part earPart = null;
for (int i = 0; i < meshToPartList.Count && earPart == null; i++) {
if (isPointInMesh(earPosition, meshToPartList[i].meshFilter)) {
earPart = meshToPartList[i].part;
}
}

float atmosphericCutoff = Mathf.Lerp(minimalCutoff, 30000, (float)FlightGlobals.ActiveVessel.atmDensity);
if (earPart != null) {
audioMixer.setOutsideCutoff(Mathf.Min(wallCutoff, atmosphericCutoff));
} else {
audioMixer.setOutsideCutoff(atmosphericCutoff);
}

AudioSource[] audioSources = FindObjectsOfType(typeof(AudioSource)) as AudioSource[];

for (int i = 0; i < audioSources.Length; i++) {
AudioSource audioSource = audioSources[i];

writeDebug("Sound " + i + ":" + audioSource.transform.name + " " + audioSource.transform.position + " " + audioSource.bypassEffects + " " + audioSource.bypassListenerEffects + " " +
(audioSource.clip == null ? "null" : audioSource.clip.name) + " " + StockAudio.isAmbient(audioSource));

if (audioSource.bypassEffects || StockAudio.isPreserved(audioSource)) {
continue;
}

bool isFilterSet = false;
for (int j = 0; earPart != null && j < meshToPartList.Count && !isFilterSet; j++) {
MeshToPart meshToPart = meshToPartList[j];
if (!StockAudio.isAmbient(audioSource) && isPointInMesh(audioSource.transform.position, meshToPart.meshFilter)) {
if (meshToPart.part.Equals(earPart)) {
writeDebug("Sound " + i + ":" + audioSource.name + " SAME AS EAR");
audioSource.outputAudioMixerGroup = null; //if audioSource is in the same part with the Ear then skipping filtering
} else {
writeDebug("Sound " + i + ":" +audioSource.name + " ANOTHER PART");
audioSource.outputAudioMixerGroup = audioMixer.inVesselGroup; //if audioSource is in another part of the vessel then applying constant muffling
}
isFilterSet = true;
}
}
if (isFilterSet) {
continue;
}
audioSource.outputAudioMixerGroup = audioMixer.outsideGroup;
writeDebug("Sound " + i + ":" + audioSource.name + " OUTSIDE");
}

}

private void rebuildVesselMeshList() {
meshToPartList.Clear();
for (int i = 0; i < FlightGlobals.ActiveVessel.Parts.Count; i++) {
Part part = FlightGlobals.ActiveVessel.Parts[i];
List<MeshFilter> filters = part.FindModelComponents<MeshFilter>();
for (int j = 0; j < filters.Count; j++) {
meshToPartList.Add(new MeshToPart(filters[j], part));
}
}
}

private bool isPointInMesh(Vector3 point, MeshFilter meshFilter) {
Vector3 localPoint = meshFilter.transform.InverseTransformPoint(point);
return meshFilter.mesh.bounds.Contains(localPoint);
}

private void writeDebug(string message) {
if (debug) {
KSPLog.print ("Audio Muffler:" + message);
}
}

}
}
64 changes: 64 additions & 0 deletions Muffler/Muffler.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<PropertyGroup>
<ProjectGuid>{3C73640C-77D8-4DEE-BBBA-64102183BCC9}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<OutputType>Library</OutputType>
<RootNamespace>Audio_Muffler</RootNamespace>
<AssemblyName>Audio Muffler Redux</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<AppDesignerFolder>Properties</AppDesignerFolder>
<TargetFrameworkProfile />
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<DebugSymbols>True</DebugSymbols>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<OutputPath>bin\Release\</OutputPath>
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Assembly-CSharp">
<HintPath>..\..\Managed\Assembly-CSharp.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="UnityEngine">
<HintPath>..\..\Managed\UnityEngine.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.UI">
<HintPath>..\..\Managed\UnityEngine.UI.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="AudioMixerFacade.cs" />
<Compile Include="MeshToPart.cs" />
<Compile Include="Muffler.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StockAudio.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
31 changes: 31 additions & 0 deletions Muffler/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#region Using directives

using System;
using System.Reflection;
using System.Runtime.InteropServices;

#endregion

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Audio Muffler Redux")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Audio Muffler Redux")]
[assembly: AssemblyCopyright("Copyright 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
[assembly: ComVisible(false)]

// The assembly version has following format :
//
// Major.Minor.Build.Revision
//
// You can specify all the values or you can use the default the Revision and
// Build Numbers by using the '*' as shown below:
[assembly: AssemblyVersion("2.0.*")]
45 changes: 45 additions & 0 deletions Muffler/StockAudio.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using System.Collections.Generic;
using System.Collections;
using UnityEngine;

namespace AudioMuffler {

/// <summary>
/// Description of StockAudio.
/// </summary>
public class StockAudio
{

private static List<string> AMBIENT = new List<string> {"FX Sound", "airspeedNoise"};
private static List<string> PRESERVED = new List<string> {"MusicLogic"};

public static bool isAmbient(AudioSource audioSource) {
return AMBIENT.Contains(audioSource.name);
}

public static bool isPreserved(AudioSource audioSource) {
return PRESERVED.Contains(audioSource.name);
}

public static void prepareAudioSources(AudioMixerFacade audioMixer, AudioSource[] audioSources) {
for (int i = 0; i < audioSources.Length; i++) {
if (isAmbient (audioSources [i])) {
audioSources [i].outputAudioMixerGroup = audioMixer.outsideGroup;
}
}
}

/*public static void prepareAudioSources(AudioSource[] audioSources) {
for (int i = 0; i < audioSources.Length; i++) {
if (isAmbient(audioSources[i])) {
audioSources[i].bypassEffects = false;
audioSources[i].bypassListenerEffects = false;
} else if (isPreserved(audioSources[i])) {
audioSources[i].bypassEffects = true;
}
}
}*/


}
}
Binary file added mixer.bundle
Binary file not shown.
6 changes: 6 additions & 0 deletions muffler.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
//MUFFLER CONFIG

debug = false //spew various messages as stuff happens inside the plugin
enabled = true //self-explanatory
wallCutoff = 500 //sound that pass through a part's wall will be reduced to this frequency
minimalCutoff = 0 //minimal frequency to which sound are reduced by air sparseness. 300 is the value of the old Audio Muffler (makes sounds become a deep bass rumble in vacuum instead of total silence)

0 comments on commit def885e

Please sign in to comment.