Custom Filters

Important!
This Tutorial is for my Filters Plugin, it can be applied to PIXI.js in general but some concepts will be specific to my Filters Plugin.
You can find my Filters Plugin here; hbgames.org/forums/viewtopic.php?p=930983

IDE Recommendation
As a JS development IDE I highly recommend the multi-platform IDE "Visual Studio Code" (Available for Windows, OS X and Linux). code.visualstudio.com

Below are framework Filters. They are bare-bones with what they do.
First filter is a single-pass "multiplier" which will multiply the RGB components of the input by a fixed number.
Second filter is an example multi-pass filter, which will perform the multiply operation of the first filter twice in separate passes.

Included are an example of a custom Filter with animation and a custom texture (Refract.js) and an example of a custom multi-pass Filter (Retro.js).

Basic Custom Filter
BasicCustomFilter.js
basic_custom { "multiplier" : 1.0 }
  1. (function() {
  2.    
  3.     // BasicCustomFilter construction function
  4.     BasicCustomFilter = function() {
  5.         PIXI.AbstractFilter.call( this ); // Call parent constructor
  6.        
  7.         this.passes = [this]; // A Filter can be multi-pass (See MultiPassFilter below)
  8.  
  9.         // Uniforms are sent to the GPU shader (See Uniform Values table below)
  10.         this.uniforms = {
  11.             multiplier: { type: '1f', value : 1.0 } // multiplier uniform is a float with a default value of 1.0
  12.         };
  13.  
  14.         // Filters only use the fragment shader (usually)
  15.         // This is the source for the GPU program, performed per-pixel
  16.         // It is a string array that is joined at a later stage before uploading to the GPU
  17.         this.fragmentSrc = [
  18.             'precision mediump float;',       // Precision is the accuracy of the result - lowp is faster but less accurate, highp is slower but more accurate
  19.             'varying vec2 vTextureCoord;',    // DEFAULT - input from MV for the input texture UV
  20.             'varying vec4 vColor;',           // DEFAULT - input from MV from the vertex shader (can be ignored)
  21.             'uniform sampler2D uSampler;',    // DEFAULT - input from MV for the input texture itself
  22.             // A Filters Plugin default input is uTime, which requires a getter/setter to be written (See multiplier getter/setter above for an example)
  23.             'uniform float multiplier;',  // This is our custom uniform value (see above)
  24.  
  25.             // GLSL main entry point
  26.             'void main(void) {',
  27.  
  28.             '   gl_FragColor = texture2D( uSampler, vTextureCoord );', // Read the colour of our source image
  29.             '   gl_FragColor.rgb *= multiplier;', // Do some operation on it (multiply by the multiplier uniform)
  30.            
  31.             '}'
  32.         ];
  33.     }
  34.    
  35.     // Prototype setup
  36.     BasicCustomFilter.prototype = Object.create( BasicCustomFilter.prototype );
  37.     BasicCustomFilter.prototype.constructor = BasicCustomFilter;
  38.    
  39.     // BasicCustomFilter.multiplier getter and setter (notice the use of .value)
  40.     // This is to avoid accessing the uniform directly and lets us do cool things later
  41.     Object.defineProperty( BasicCustomFilter.prototype, 'multiplier', {
  42.         // Getter
  43.         get: function() {
  44.             return this.uniforms.multiplier.value;
  45.         },
  46.         // Setter
  47.         set: function( value ) {
  48.             this.uniforms.multiplier.value = value;
  49.         }
  50.     });
  51.    
  52.     if ( Filter ) {
  53.         // Filters Plugin standard naming is to remove the "Filter" and switch from camel case to lower-case with underscore
  54.         // BasicCustomFilter -> basic_custom
  55.         Filter.add( "basic_custom", BasicCustomFilter );
  56.     }
  57.  
  58. })();
Expand to see the code.


Multi Pass Custom Filter
MultiPassCustomFilter.js
multi_pass_custom { "multiplier" : [1.0, 1.0] }
  1. (function() {
  2.    
  3.     // MultiPassCustomFilter construction function
  4.     function MultiPassCustomFilter() {
  5.         this.firstFilter = new BasicCustomFilter(); // Create our first Filter instance
  6.         this.secondFilter = new BasicCustomFilter(); // Create our second Filter instance
  7.  
  8.         this.passes = [this.firstFilter, this.secondFilter]; // The passes are set here
  9.     }
  10.    
  11.     // Prototype setup
  12.     MultiPassCustomFilter.prototype = Object.create( MultiPassCustomFilter.prototype );
  13.     MultiPassCustomFilter.prototype.constructor = MultiPassCustomFilter;
  14.    
  15.     // Forward the properties from both our passes to this interface
  16.     Object.defineProperty( MultiPassCustomFilter.prototype, 'multiplier', {
  17.         // Getter
  18.         get: function() {
  19.             // Returns an array containing the first and second multiplier uniforms
  20.             return [ this.firstFilter.multiplier, this.secondFilter.multiplier ];
  21.         },
  22.         // Setter
  23.         set: function( value ) {
  24.             this.firstFilter.multiplier = value[0];
  25.             this.secondFilter.multiplier = value[1];
  26.         }
  27.     });
  28.    
  29.     if ( Filter ) {
  30.         // Filters Plugin standard naming is to remove the "Filter" and switch from camel case to lower-case with underscore
  31.         // MultiPassCustomFilter -> multi_pass_custom
  32.         Filter.add( "multi_pass_custom", MultiPassCustomFilter );
  33.     }
  34.  
  35. })();
Expand to see the code.


Uniform Values
name      | GLSL type | JS type | example 
----------|-----------|---------|---------
sampler2D | sampler2D | Bitmap | ImageManager.loadPicture( "my_picture" )
1f | float | Number | 1.0
2f | vec2 | Object | { x : 1.0, y : 2.0 }
3f | vec3 | Object | { x : 1.0, y : 2.0, z : 3.0 }
4f | vec4 | Object | { x : 1.0, y : 2.0, z : 3.0, w : 4.0 }
2fv | vec2 | Array | [ 1.0, 2.0 ]
3fv | vec3 | Array | [ 1.0, 2.0, 3.0 ]
4fv | vec4 | Array | [ 1.0, 2.0, 3.0, 4.0 ]
mat2 | mat2 | Array | [ 1.0, 2.0, 3.0, 4.0 ]
mat3 | mat3 | Array | [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 ]
mat4 | mat4 | Array | [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0 ]


Custom Texture Uploads
Things get more advanced when you need custom textures (one example would be a refraction shader).
The Filters plugin can accept strings as uniforms. The string will switch from source state to destination state at the mid-point of the Filter interpolation animation.
An example getter/setter for a customer texture would be;
  1. Object.defineProperty( TextureCustomFilter.prototype, 'customTexture', {
  2.     // Returns the texture url
  3.     get: function() {
  4.         if ( this.uniforms.customTexture.value === null ) {
  5.             return null;
  6.         }
  7.         return this.uniforms.customTexture.value.texture_url;
  8.     },
  9.     // value is a string (texture name within the pictures folder)
  10.     set: function( value ) {
  11.         if ( this.uniforms.customTexture.value === null || this.uniforms.customTexture.value.texture_url != value ) {
  12.             this.uniforms.customTexture.value = ImageManager.loadPicture( value );
  13.             this.uniforms.customTexture.value.texture_url = value;
  14.         }
  15.     }
  16. });
Expand to see the code.


Animation
The Filters Plugin will attempt to set a uTime property if it exists. To make uTime visible a getter/setter needs to be created;
  1. Object.defineProperty( AnimatedCustomFilter.prototype, 'uTime', {
  2.     get: function() {
  3.         return this.uniforms.uTime.value * 60.0; // 60.0 is used to control the animation speed
  4.     },
  5.     set: function( value ) {
  6.         this.uniforms.uTime.value = value / 60.0; // The multiply/divide value should be consistent with getter/setter
  7.     }
  8. });
Expand to see the code.


Notes
fragmentSrc is where the GLSL lives. This is the most important part as this is the shader code itself. You must know GLSL to be able to write this (it is rather different to Javascript!). You can do an awful lot with this.

Refraction Filter
This is an example custom filter which features animation (set the speed) and the use of a custom texture (set the refractMap to the name of a .png image in the Pictures folder).
Version 2.0 of this Filter will be part of Filter Pack 1.

Refract.js
refract { "refractMap" : null, "strength" : 0.1, "speed" : { "x" : 0, "y" : 0 }, "uTime" : 0 }
  1. //=============================================================================
  2. // Refract.js
  3. //=============================================================================
  4.  
  5. /*:
  6.  * @plugindesc Refract Filter. For Xilefian's Filter Plugin.
  7.  * @author Felix "Xilefian" Jones
  8.  *
  9.  * @help
  10.  *
  11.  * Version 1.0
  12.  * Website http://www.hbgames.org
  13.  *
  14.  * Filter:
  15.  *   refract    { "refractMap":null, "strength":0.1, "speed":{ "x":0, "y":0 }, "uTime":0 }
  16.  *
  17.  * Change log:
  18.  *   Version 1.0:
  19.  *     Initial version.
  20.  *
  21.  */
  22.  
  23. (function() {
  24.  
  25.     /**
  26.      * @author Felix "Xilefian" Jones
  27.      * The RefractFilter
  28.      *
  29.      * @class RefractFilter
  30.      * @extends AbstractFilter
  31.      * @constructor
  32.      */
  33.     RefractFilter = function() {
  34.         PIXI.AbstractFilter.call( this );        
  35.         this.passes = [this];
  36.  
  37.         this.uniforms = {
  38.             refractMap: {type: 'sampler2D', value:null },
  39.             strength:   {type: '1f', value:0.1},
  40.             speed:      {type: '2f', value:{x:0,y:0}},
  41.             uTime:      {type: '1f', value:0}
  42.         };
  43.  
  44.         this.fragmentSrc = [
  45.             'precision mediump float;',
  46.             'varying vec2 vTextureCoord;',
  47.             'varying vec4 vColor;',
  48.             'uniform sampler2D uSampler;',
  49.             'uniform float uTime;',
  50.             'uniform sampler2D refractMap;',
  51.             'uniform float strength;',
  52.             'uniform vec2 speed;',
  53.            
  54.             'void main(void) {',
  55.             '   vec2 ruv = fract( vTextureCoord.xy + ( speed * uTime ) );',
  56.             '   vec3 offset = texture2D( refractMap, ruv ).rgb;',
  57.             '   offset -= ( offset / 2.0 );',
  58.             '   offset *= 2.0;',
  59.             '   offset.z *= strength;',
  60.             '   gl_FragColor = texture2D( uSampler, vTextureCoord.xy + offset.xy * offset.z );',
  61.             '}'
  62.         ];
  63.     };
  64.  
  65.     RefractFilter.prototype = Object.create( RefractFilter.prototype );
  66.     RefractFilter.prototype.constructor = RefractFilter;
  67.  
  68.     /**
  69.      * Sets the refract texture
  70.      *
  71.      * @property refractMap
  72.      * @type String
  73.      * @default null
  74.      */
  75.     Object.defineProperty( RefractFilter.prototype, 'refractMap', {
  76.         get: function() {
  77.             if ( this.uniforms.refractMap.value === null ) {
  78.                 return null;
  79.             }
  80.             return this.uniforms.refractMap.value.xi_url;
  81.         },
  82.         set: function( value ) {
  83.             if ( this.uniforms.refractMap.value === null || this.uniforms.refractMap.value.xi_url != value ) {
  84.                 this.uniforms.refractMap.value = ImageManager.loadPicture( value );
  85.                 this.uniforms.refractMap.value.xi_url = value;
  86.             }
  87.         }
  88.     });
  89.    
  90.     /**
  91.      * Sets the power of the refraction
  92.      *
  93.      * @property strength
  94.      * @type Number
  95.      * @default 0.1
  96.      */
  97.     Object.defineProperty( RefractFilter.prototype, 'strength', {
  98.         get: function() {
  99.             return this.uniforms.strength.value;
  100.         },
  101.         set: function( value ) {
  102.             this.uniforms.strength.value = value;
  103.         }
  104.     });
  105.    
  106.     /**
  107.      * Animation time
  108.      *
  109.      * @property uTime
  110.      * @type Number
  111.      * @default 0
  112.      */
  113.     Object.defineProperty( RefractFilter.prototype, 'uTime', {
  114.         get: function() {
  115.             return this.uniforms.uTime.value * 60.0;
  116.         },
  117.         set: function( value ) {
  118.             this.uniforms.uTime.value = value / 60.0;
  119.         }
  120.     });
  121.    
  122.     /**
  123.      * Animation speed
  124.      *
  125.      * @property speed
  126.      * @type Point
  127.      * @default 0, 0
  128.      */
  129.     Object.defineProperty( RefractFilter.prototype, 'speed', {
  130.         get: function() {
  131.             return this.uniforms.speed.value;
  132.         },
  133.         set: function( value ) {
  134.             this.uniforms.speed.value = value;
  135.         }
  136.     });
  137.    
  138.     /**
  139.      * Register filter class with the Filter Plugin (if available)
  140.      */
  141.     if ( Filter ) {
  142.         Filter.add( "refract", RefractFilter );
  143.     }
  144.        
  145. })();
Expand to see the code.


Retro Filter
This is an example custom multi-pass filter which both pixelates and reduces the colour of the screen.

Retro.js
retro { "step" : 3.779, "size" : 2 }
  1. //=============================================================================
  2. // Retro.js
  3. //=============================================================================
  4.  
  5. /*:
  6.  * @plugindesc Retro Filter. For Xilefian's Filter Plugin.
  7.  * @author Felix "Xilefian" Jones
  8.  *
  9.  * @help
  10.  *
  11.  * Version 1.0
  12.  * Website http://www.hbgames.org
  13.  *
  14.  * Filter:
  15.  *   retro    { "step":3.779, "size":2 }
  16.  *
  17.  * Change log:
  18.  *   Version 1.0:
  19.  *     Initial version.
  20.  *
  21.  */
  22.  
  23. (function() {
  24.  
  25.     /**
  26.      * @author Felix "Xilefian" Jones
  27.      * The RetroFilter
  28.      *
  29.      * @class RetroFilter
  30.      * @extends AbstractFilter
  31.      * @constructor
  32.      */
  33.     RetroFilter = function() {
  34.         this.colorStep = new PIXI.ColorStepFilter(); // To reduce the colours
  35.         this.pixelate = new PIXI.PixelateFilter(); // To reduce the sampling resolution
  36.  
  37.         this.passes = [this.colorStep, this.pixelate]; // We reduce colour first, then resolution (avoids an anti-aliasing blur)
  38.  
  39.         this.step = 3.779;
  40.         this.size = 2.0;
  41.     };
  42.  
  43.     RetroFilter.prototype = Object.create( RetroFilter.prototype );
  44.     RetroFilter.prototype.constructor = RetroFilter;
  45.  
  46.     /**
  47.      * Sets the colorStep reduction
  48.      *
  49.      * @property step
  50.      * @type Number
  51.      * @default 3.779
  52.      */
  53.     Object.defineProperty( RetroFilter.prototype, 'step', {
  54.         get: function() {
  55.             return this.colorStep.step;
  56.         },
  57.         set: function( value ) {
  58.             this.colorStep.step = value;
  59.         }
  60.     });
  61.    
  62.     /**
  63.      * Sets the pixelate size
  64.      *
  65.      * @property size
  66.      * @type Number
  67.      * @default 2.0
  68.      */
  69.     Object.defineProperty( RetroFilter.prototype, 'size', {
  70.         get: function() {
  71.             return this.pixelate.size.x;
  72.         },
  73.         set: function( value ) {
  74.             this.pixelate.size.x = value;
  75.             this.pixelate.size.y = value;
  76.         }
  77.     });
  78.    
  79.     /**
  80.      * Register filter class with the Filter Plugin (if available)
  81.      */
  82.     if ( Filter ) {
  83.         Filter.add( "retro", RetroFilter );
  84.     }
  85.        
  86. })();
Expand to see the code.

Original thread: https://www.hbgames.org/forums/viewtopic.php?t=78969