Skip to content

Instantly share code, notes, and snippets.

@EliteMasterEric
Created December 30, 2022 00:28
Show Gist options
  • Select an option

  • Save EliteMasterEric/f125ea0dea647d37320a114c9c0c7be2 to your computer and use it in GitHub Desktop.

Select an option

Save EliteMasterEric/f125ea0dea647d37320a114c9c0c7be2 to your computer and use it in GitHub Desktop.
package;
import flixel.system.FlxAssets.FlxShader;
import openfl.display.BitmapData;
/**
* Implements the overlay blend mode as a Flixel shader.
*
* @see https://en.wikipedia.org/wiki/Blend_modes#Overlay
* @author EliteMasterEric
*/
class OverlayShader extends FlxShader
{
@:glFragmentSource('
#pragma header
// Takes an image as the input.
uniform sampler2D bitmapOverlay;
vec4 blendOverlay(vec4 base, vec4 blend)
{
// Depending on the base color, compute a linear interpolation
// between black (base layer = 0), the top layer (base layer = 0.5), and white (base layer = 1.0)
return mix(1.0 - 2.0 * (1.0 - base) * (1.0 - blend), 2.0 * base * blend, step(base, vec4(0.5)));
}
void main()
{
// Get the current pixel from the base layer.
vec4 base = texture2D(bitmap, openfl_TextureCoordv);
// Get the current pixel from the overlay layer.
vec4 blend = texture2D(bitmapOverlay, openfl_TextureCoordv);
// Compute the overlay blend mode.
gl_FragColor = blendOverlay(base, blend);
}')
public function new()
{
super();
}
/**
* Assigns the bitmap to be used as the overlay.
* @param bitmap A BitmapData object containing the image to use as the overlay.
*/
public function setBitmapOverlay(bitmap:BitmapData):Void
{
this.bitmapOverlay.input = bitmap;
}
}
@EliteMasterEric
Copy link
Author

EliteMasterEric commented Dec 30, 2022

OpenFL provides the ability to call sprite.blend = BlendMode.OVERLAY;, however this does not do anything on most platforms. This code implements the functionality as a shader. This means it is not as compatible with multiple layered sprites, or with animated sprites, but it's still useful if you want to apply a single texture as an overlay to another sprite.

This shader also serves as a good example for those looking to use multiple textures as an input for a shader.

image

This code is made available under the MIT License. It is based on this code, which is also available under the MIT License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment