Skip to content

Commit

Permalink
Merge pull request #638 from MOARdV/master
Browse files Browse the repository at this point in the history
Update shaders, replace asset bundle loading
  • Loading branch information
MOARdV authored Jul 20, 2017
2 parents 3eb152f + 4cc49b6 commit 819b0dc
Show file tree
Hide file tree
Showing 14 changed files with 144 additions and 174 deletions.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
201 changes: 89 additions & 112 deletions RasterPropMonitor/Core/UtilityFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1678,8 +1678,6 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
[KSPAddon(KSPAddon.Startup.MainMenu, true)]
public class RPMShaderLoader : MonoBehaviour
{
//private bool reloadInProgress = false;

RPMShaderLoader()
{
// I don't want this object destroyed on scene change, since the database
Expand All @@ -1688,25 +1686,103 @@ public class RPMShaderLoader : MonoBehaviour
DontDestroyOnLoad(this);
}

/// <summary>
/// Wake up and ask for all of the shaders in our asset bundle and kick off
/// the coroutines that look for global RPM config data.
/// </summary>
private void Awake()
private void LoadAssets()
{
if (KSPAssets.Loaders.AssetLoader.Ready == false)
String assetsPath = KSPUtil.ApplicationRootPath + "GameData/JSI/RasterPropMonitor/";
String shaderAssetBundleName = "rasterpropmonitor";
if (Application.platform == RuntimePlatform.WindowsPlayer)
{
shaderAssetBundleName += "-win";
}
else if (Application.platform == RuntimePlatform.LinuxPlayer)
{
shaderAssetBundleName += "-lin";
}
else if (Application.platform == RuntimePlatform.OSXPlayer)
{
shaderAssetBundleName += "-osx";
}
shaderAssetBundleName += ".assetbundle";

WWW www = new WWW("file://" + assetsPath + shaderAssetBundleName);

if (!string.IsNullOrEmpty(www.error))
{
JUtil.LogErrorMessage(this, "Error loading AssetBundle: {0}", www.error);
return;
}
else if (www.assetBundle == null)
{
JUtil.LogErrorMessage(this, "Unable to load shaders - AssetLoader is not ready.");
JUtil.LogErrorMessage(this, "Unable to load AssetBundle {0}", www);
return;
}

KSPAssets.AssetDefinition[] rpmShaders = KSPAssets.Loaders.AssetLoader.GetAssetDefinitionsWithType("JSI/RasterPropMonitor/rasterpropmonitor", typeof(Shader));
if (rpmShaders == null || rpmShaders.Length == 0)
JUtil.parsedShaders.Clear();

AssetBundle bundle = www.assetBundle;

string[] assetNames = bundle.GetAllAssetNames();
int len = assetNames.Length;

Shader shader;
for (int i = 0; i < len; i++)
{
if (assetNames[i].EndsWith(".shader"))
{
shader = bundle.LoadAsset<Shader>(assetNames[i]);
if (!shader.isSupported)
{
JUtil.LogErrorMessage(this, "Shader {0} - unsupported in this configuration", shader.name);
}
JUtil.parsedShaders[shader.name] = shader;
}
}

bundle.Unload(false);

string fontAssetBundleName = "rasterpropmonitor-font.assetbundle";
www = new WWW("file://" + assetsPath + fontAssetBundleName);

if (!string.IsNullOrEmpty(www.error))
{
JUtil.LogErrorMessage(this, "Unable to load shaders - No shaders found in RPM asset bundle.");
JUtil.LogErrorMessage(this, "Error loading AssetBundle: {0}", www.error);
return;
}
else if (www.assetBundle == null)
{
JUtil.LogErrorMessage(this, "Unable to load AssetBundle {0}", www);
return;
}

JUtil.loadedFonts.Clear();

bundle = www.assetBundle;

assetNames = bundle.GetAllAssetNames();
len = assetNames.Length;

Font font;
for (int i = 0; i < len; i++)
{
if (assetNames[i].EndsWith(".ttf"))
{
font = bundle.LoadAsset<Font>(assetNames[i]);
JUtil.LogInfo(this, "Adding RPM-included font {0} / {1}", font.name, font.fontSize);

JUtil.loadedFonts[font.name] = font;
}
}
bundle.Unload(false);

JUtil.LogInfo(this, "Found {0} RPM shaders and {1} fonts.", JUtil.parsedShaders.Count, JUtil.loadedFonts.Count);
}

/// <summary>
/// Wake up and ask for all of the shaders in our asset bundle and kick off
/// the coroutines that look for global RPM config data.
/// </summary>
private void Awake()
{
if (!GameDatabase.Instance.IsReady())
{
JUtil.LogErrorMessage(this, "GameDatabase.IsReady is false");
Expand Down Expand Up @@ -1782,12 +1858,8 @@ private void Awake()
}
}

// HACK: Pass only one of the asset definitions, since LoadAssets
// behaves badly if we ask it to load more than one. If that ever
// gets fixed, I can clean up AssetsLoaded drastically.
KSPAssets.Loaders.AssetLoader.LoadAssets(AssetsLoaded, rpmShaders[0]);
LoadAssets();

//reloadInProgress = true;
StartCoroutine("LoadRasterPropMonitorValues");

// Register a callback with ModuleManager so we can get notified
Expand Down Expand Up @@ -1982,104 +2054,9 @@ private IEnumerator LoadRasterPropMonitorValues()
JUtil.LogMessage(this, "Remembering system resource {1} as SYSR_{0}", varname, thatResource.name);
}

//reloadInProgress = false;
yield return null;
}

/// <summary>
/// Callback that fires once the requested assets have loaded.
/// </summary>
/// <param name="loader">Object containing our loaded assets (see comments in this method)</param>
private void AssetsLoaded(KSPAssets.Loaders.AssetLoader.Loader loader)
{
// This is an unforunate hack. AssetLoader.LoadAssets barfs if
// multiple assets are loaded, leaving us with only one valid asset
// and some nulls afterwards in loader.objects. We are forced to
// traverse the LoadedBundles list to find our loaded bundle so we
// can find the rest of our shaders.
string aShaderName = string.Empty;
for (int i = 0; i < loader.objects.Length; ++i)
{
UnityEngine.Object o = loader.objects[i];
if (o != null && o is Shader)
{
// We'll remember the name of whichever shader we were
// able to load.
aShaderName = o.name;
break;
}
}

if (string.IsNullOrEmpty(aShaderName))
{
JUtil.LogErrorMessage(this, "Unable to find a named shader in loader.objects");
return;
}

var loadedBundles = KSPAssets.Loaders.AssetLoader.LoadedBundles;
if (loadedBundles == null)
{
JUtil.LogErrorMessage(this, "Unable to find any loaded bundles in AssetLoader");
return;
}

// Iterate over all loadedBundles. Experimentally, my bundle was
// the only one in the array, but I expect that to change as other
// mods use asset bundles (maybe none of the mods I have load this
// early).
for (int i = 0; i < loadedBundles.Count; ++i)
{
Shader[] shaders = null;
Font[] fonts = null;
bool theRightBundle = false;

try
{
// Try to get a list of all the shaders in the bundle.
shaders = loadedBundles[i].LoadAllAssets<Shader>();
if (shaders != null)
{
// Look through all the shaders to see if our named
// shader is one of them. If so, we assume this is
// the bundle we want.
for (int shaderIdx = 0; shaderIdx < shaders.Length; ++shaderIdx)
{
if (shaders[shaderIdx].name == aShaderName)
{
theRightBundle = true;
break;
}
}
}
fonts = loadedBundles[i].LoadAllAssets<Font>();
}
catch { }

if (theRightBundle)
{
// If we found our bundle, set up our parsedShaders
// dictionary and bail - our mission is complete.
JUtil.LogInfo(this, "Found {0} RPM shaders and {1} fonts.", shaders.Length, fonts.Length);
for (int j = 0; j < shaders.Length; ++j)
{
if (!shaders[j].isSupported)
{
JUtil.LogErrorMessage(this, "Shader {0} - unsupported in this configuration", shaders[j].name);
}
JUtil.parsedShaders[shaders[j].name] = shaders[j];
}
for (int j = 0; j < fonts.Length; ++j)
{
JUtil.LogInfo(this, "Adding RPM-included font {0} / {1}", fonts[j].name, fonts[j].fontSize);
JUtil.loadedFonts[fonts[j].name] = fonts[j];
}
return;
}
}

JUtil.LogErrorMessage(this, "No RasterPropMonitor shaders were loaded - how did this callback execute?");
}

public void PostPatchCallback()
{
JUtil.LogMessage(this, "ModuleManager has reloaded - reloading RPM values");
Expand Down
4 changes: 2 additions & 2 deletions RasterPropMonitor/Shaders/RPM-CroppedDisplayShader.shader
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Shader "RPM/CroppedDisplayShader"
float2 pixelPos : TEXCOORD1;
};

sampler2D _MainTex;
UNITY_DECLARE_TEX2D(_MainTex);

uniform float4 _MainTex_ST;
// Color modulation
Expand Down Expand Up @@ -70,7 +70,7 @@ Shader "RPM/CroppedDisplayShader"
}
else
{
float4 diffuse = tex2D(_MainTex, i.texcoord);
float4 diffuse = UNITY_SAMPLE_TEX2D(_MainTex, i.texcoord);
diffuse.a *= _Color.a * _Opacity;
diffuse.rgb = (diffuse.rgb * _Color.rgb) * diffuse.a;
return diffuse;
Expand Down
4 changes: 2 additions & 2 deletions RasterPropMonitor/Shaders/RPM-DisplayShader.shader
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Shader "RPM/DisplayShader"
float2 texcoord : TEXCOORD0;
};

sampler2D _MainTex;
UNITY_DECLARE_TEX2D(_MainTex);

uniform float4 _MainTex_ST;
uniform float4 _Color;
Expand All @@ -55,7 +55,7 @@ Shader "RPM/DisplayShader"

float4 frag (v2f_displayshader i) : COLOR
{
float4 diffuse = tex2D(_MainTex, i.texcoord);
float4 diffuse = UNITY_SAMPLE_TEX2D(_MainTex, i.texcoord);
diffuse.a *= _Color.a * _Opacity;
diffuse.rgb = (diffuse.rgb * _Color.rgb) * diffuse.a;
return diffuse;
Expand Down
30 changes: 11 additions & 19 deletions RasterPropMonitor/Shaders/RPM-FontShader.shader
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,21 @@

Tags { "RenderType"="Overlay" "Queue" = "Transparent" }

Pass
{
// Premultiplied Alpha shader for rendering text on displays.

Lighting Off
//Lighting Off
Blend One OneMinusSrcAlpha
Cull Off
Fog { Mode Off }
//Cull Off
//Fog { Mode Off }
ZWrite Off
ZTest Always
//ZTest Off

// Premultiplied Alpha shader for rendering text on displays.
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 3.0

#include "UnityCG.cginc"

struct appdata_t
{
float4 vertex : POSITION;
Expand All @@ -43,9 +39,7 @@
float2 texcoord : TEXCOORD0;
};

sampler2D _MainTex;

//float4 _MainTex_ST;
UNITY_DECLARE_TEX2D(_MainTex);

v2f_fontshader vert (appdata_t v)
{
Expand All @@ -54,25 +48,23 @@
// Unfortunately, the original font implementation used a
// Unity shader that used 0.5 as full brightness, which skews
// everything. Doubling alpha appears to fix the problem for
// both DX and OGL paths. When the Unity 5 version of KSP
// arrives, I'll break the legacy system and use normal values
// for everything.
// both DX and OGL paths.
dataOut.color = fixed4(v.color.rgb, v.color.a * 2.0);

dataOut.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
//dataOut.texcoord = TRANSFORM_TEX(v.texcoord.xy,_MainTex);
dataOut.texcoord = v.texcoord;

return dataOut;
}

fixed4 frag (v2f_fontshader dataIn) : SV_TARGET
fixed4 frag (v2f_fontshader dataIn) : SV_Target
{
fixed4 diffuse = tex2D(_MainTex, dataIn.texcoord);
fixed4 diffuse = UNITY_SAMPLE_TEX2D(_MainTex, dataIn.texcoord);
diffuse.a *= dataIn.color.a;
diffuse.rgb = (diffuse.rgb * dataIn.color.rgb) * diffuse.a;
return diffuse;
}

ENDCG
}
}
Expand Down
6 changes: 2 additions & 4 deletions RasterPropMonitor/Shaders/RPM-JSILabel.shader
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,12 @@ Shader "RPM/JSILabel"

CGPROGRAM

//#include "../../SquadCore/LightingKSP.cginc"
#pragma surface surf Lambert alpha
//#pragma surface surf BlinnPhongSmooth alphatest:_Cutoff
#pragma target 3.0

half _Shininess;

sampler2D _MainTex;
UNITY_DECLARE_TEX2D(_MainTex);

float _Opacity;
float _Fresnel;
Expand All @@ -73,7 +71,7 @@ Shader "RPM/JSILabel"
{
float4 color = IN.color * _BurnColor;

float alpha = tex2D(_MainTex, (IN.uv_MainTex)).a * IN.color.a;
float alpha = UNITY_SAMPLE_TEX2D(_MainTex, (IN.uv_MainTex)).a * IN.color.a;

float3 normal = float3(0.0,0.0,1.0);
half rim = 1.0 - saturate(dot (normalize(IN.viewDir), normal));
Expand Down
Loading

0 comments on commit 819b0dc

Please sign in to comment.