Skip to content

Instantly share code, notes, and snippets.

@FreyaHolmer
Created August 11, 2020 13:56
Show Gist options
  • Save FreyaHolmer/e0a2fffe4c94440dfaaff07ea50f2d67 to your computer and use it in GitHub Desktop.
Save FreyaHolmer/e0a2fffe4c94440dfaaff07ea50f2d67 to your computer and use it in GitHub Desktop.
Alpha blending comparisons
// alpha blending test
// more info: https://twitter.com/FreyaHolmer/status/1293163103035817985
// add this script to an object in the scene,
// then edit src and dst to see - will it blend?
using UnityEngine;
[ExecuteAlways]
public class BlendTest : MonoBehaviour {
public Color src, dst; // modify these and see what happens to the ones below
public Color outSimpleAlphaBlend;
public Color outHackAlphaBlend;
public Color outReference;
public void Update() {
outSimpleAlphaBlend = SimpleAlphaBlending( src, dst );
outHackAlphaBlend = HackyAlphaBlending( src, dst );
outReference = CorrectAlphaBlending( src, dst );
}
// rgba: SrcAlpha OneMinusSrcAlpha
static Color SimpleAlphaBlending( Color src, Color dst ) => src * src.a + dst * ( 1 - src.a );
// rgb: SrcAlpha OneMinusSrcAlpha
// a: One OneMinusSrcAlpha
static Color HackyAlphaBlending( Color src, Color dst ) {
Color o = SimpleAlphaBlending( src, dst ); // same as simple for rgb
o.a = src.a + dst.a * ( 1 - src.a );
return o;
}
// reference/correct alpha blending
// (there is no simple blend mode equivalent)
static Color CorrectAlphaBlending( Color src, Color dst ) {
Color o = default;
o.a = src.a + dst.a * ( 1 - src.a );
if( o.a <= 0 )
return new Color( 0, 0, 0, 0 );
for( int i = 0; i < 3; i++ ) // thanks Unity for no swizzling >:I
o[i] = ( src[i] * src.a + dst[i] * dst.a * ( 1 - src.a ) ) / o.a;
return o;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment