How to use WebGL shaders in sprites?

Very nice shaders like this one can be used in openFL, the question is, how to use those shaders within a sprite? is there any example to use such shaders to have the effect as if I use GlowFilter on a sprite or elements within SWF library? to apply on light bulb sprite and make it glowing for example?
Any idea?

Anyone can help? I am targeting HTML5 but could not find any example

The system needs to continue to improve – we need to implement cacheAsBitmap with framebuffer use again (it was disabled during a lot of other fixes)

In the meantime, this works for “simple” objects, such as Bitmap, Tilemap, TextField, or Shape. It does not work for a display object hierarchy of child objects – it must be applied to each object individually (right now).

Here’s a quick sample with a custom fragment shader:


import openfl.display.Shader;
import openfl.display.Sprite;
import openfl.filters.ShaderFilter;

class Main extends Sprite {
	public function new () {
		super ();
		var sprite = new Sprite (); (0xFF0000); (0, 0, 100, 100);
		sprite.filters = [ new ShaderFilter (new CustomShader ()) ];
		addChild (sprite);

class CustomShader extends Shader {
	public function new () {
		glFragmentSource = 
			"varying float vAlpha;
			varying vec2 vTexCoord;
			uniform sampler2D uImage0;
			void main(void) {
				vec4 color = texture2D (uImage0, vTexCoord);
				if (color.a == 0.0) {
					gl_FragColor = vec4 (0.0, 0.0, 0.0, 0.0);
				} else {
					// Flip color order
					//gl_FragColor = vec4 (color.rgb / color.a, color.a * vAlpha);
					gl_FragColor = vec4 (color.bgr / color.a, color.a * vAlpha);
		super ();

This should work on WebGL, GL and GLES, but won’t work in software.

You can also override glVertexSource (see the original value in openfl.display.Shader) if you need to, though fragment shaders are usually what you need :slight_smile:

Thanks for the useful example, but as its my first time to play with shaders in openFL, I have those few questions, please bear with me:

  1. How can I pass parameters to the shader? If I could, can I use Actuate to animate colors?
  2. What is the minimal version of webGL supported? ( 2D effects only )
  3. What’s the equivalent shader of GlowFilter ?
  4. Can I use the shader in openFL 3.6?

Finally, do you encourage me to use shaders over normal filters? Actually, I found my self with no options in HTML5 target, unless you suggest a better approach to save me rewrite effects.

Thank you

Any update is highly appreciated…