API Documentation for: 0.8.2
Show:

File:easeljs\filters\webgl\ColorMatrixFilter.js

/*
* ColorMatrixFilter
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/

/**
 * @module EaselJS
 */

// namespace:
this.createjs = this.createjs||{};

(function() {
	"use strict";

/**
 * Allows you to carry out complex color operations such as modifying saturation, brightness, or inverting. See the
 * {{#crossLink "ColorMatrix"}}{{/crossLink}} for more information on changing colors. For an easier color transform,
 * consider the {{#crossLink "ColorFilter"}}{{/crossLink}}.
 *
 * <h4>Example</h4>
 * This example creates a red circle, inverts its hue, and then saturates it to brighten it up.
 *
 *      var shape = new createjs.Shape().set({x:100,y:100});
 *      shape.graphics.beginFill("#ff0000").drawCircle(0,0,50);
 *
 *      var matrix = new createjs.ColorMatrix().adjustHue(180).adjustSaturation(100);
 *      shape.filters = [
 *          new createjs.ColorMatrixFilter(matrix)
 *      ];
 *
 *      shape.cache(-50, -50, 100, 100);
 *
 * See {{#crossLink "Filter"}}{{/crossLink}} for an more information on applying filters.
 * @class ColorMatrixFilter
 * @constructor
 * @extends Filter
 * @param {Array} matrix A 4x5 matrix describing the color operation to perform. See also the {{#crossLink "ColorMatrix"}}{{/crossLink}}
 * class.
 **/
var ColorMatrixFilter = function(matrix) {
  this.initialize(matrix);
};
var p = ColorMatrixFilter.prototype = new createjs.Filter();

// public properties:
	p.matrix = null;

// constructor:
	// TODO: detailed docs.
	/**
	 * @method initialize
	 * @protected
	 * @param {Array} matrix A 4x5 matrix describing the color operation to perform.
	 **/
	p.initialize = function(matrix) {
		this.matrix = matrix;

		// Create WebGL canvas for fast rendering.
		this._createWebGLRenderer();
	}

// public methods:

	p.Filter_applyFilter = p.applyFilter;
	/**
	 * Applies the filter to the specified context.
	 * @method applyFilter
	 * @param {CanvasRenderingContext2D} ctx The 2D context to use as the source.
	 * @param {Number} x The x position to use for the source rect.
	 * @param {Number} y The y position to use for the source rect.
	 * @param {Number} width The width to use for the source rect.
	 * @param {Number} height The height to use for the source rect.
	 * @param {CanvasRenderingContext2D} targetCtx Optional. The 2D context to draw the result to. Defaults to the context passed to ctx.
	 * @param {Number} targetX Optional. The x position to draw the result to. Defaults to the value passed to x.
	 * @param {Number} targetY Optional. The y position to draw the result to. Defaults to the value passed to y.
	 * @return {Boolean}
	 **/
	p.applyFilter = function(ctx, x, y, width, height, targetCtx, targetX, targetY) {
		targetCtx = targetCtx || ctx;
		if (targetX == null) { targetX = x; }
		if (targetY == null) { targetY = y; }

		var wctx = this._workContext;
		if(this.useGL && wctx) {
			var source = ctx.canvas;

			this._initViewport(wctx, source.width, source.height);
			this._initTexture(wctx, source, false);

			var mat = this.matrix;
			var colorMatrix = new Float32Array([
				mat[0],mat[1],mat[2],mat[3],
				mat[5],mat[6],mat[7],mat[8],
				mat[10],mat[11],mat[12],mat[13],
				mat[15],mat[16],mat[17],mat[18]
			]);
			wctx.uniformMatrix4fv(wctx.colorMatrixUniform, false, colorMatrix);
			wctx.uniform4f(wctx.colorMatrixOffsetUniform, mat[4], mat[9], mat[14], mat[19]);

			wctx.drawArrays(wctx.TRIANGLE_STRIP, 0, 4);

			var glData = new Uint8Array(width*height*4);
			wctx.readPixels(0,0,width,height, wctx.RGBA, wctx.UNSIGNED_BYTE, glData);
			var imageData = targetCtx.createImageData(width, height);
			imageData.data.set(glData);

			targetCtx.putImageData(imageData, targetX, targetY);

			return true;
		}

		try {
			var imageData = ctx.getImageData(x, y, width, height);
		} catch(e) {
			//if (!this.suppressCrossDomainErrors) throw new Error("unable to access local image data: " + e);
			return false;
		}
		var data = imageData.data;
		var l = data.length;
		var r,g,b,a;
		var mtx = this.matrix;
		var m0 =  mtx[0],  m1 =  mtx[1],  m2 =  mtx[2],  m3 =  mtx[3],  m4 =  mtx[4];
		var m5 =  mtx[5],  m6 =  mtx[6],  m7 =  mtx[7],  m8 =  mtx[8],  m9 =  mtx[9];
		var m10 = mtx[10], m11 = mtx[11], m12 = mtx[12], m13 = mtx[13], m14 = mtx[14];
		var m15 = mtx[15], m16 = mtx[16], m17 = mtx[17], m18 = mtx[18], m19 = mtx[19];

		for (var i=0; i<l; i+=4) {
			r = data[i];
			g = data[i+1];
			b = data[i+2];
			a = data[i+3];
			data[i] = r*m0+g*m1+b*m2+a*m3+m4; // red
			data[i+1] = r*m5+g*m6+b*m7+a*m8+m9; // green
			data[i+2] = r*m10+g*m11+b*m12+a*m13+m14; // blue
			data[i+3] = r*m15+g*m16+b*m17+a*m18+m19; // alpha
		}
		targetCtx.putImageData(imageData, targetX, targetY);
		return true;
	};

	p.toString = function() {
		return "[ColorMatrixFilter]";
	};

	/**
	 * Returns a clone of this ColorMatrixFilter instance.
	 * @method clone
	 * @return {ColorMatrixFilter} A clone of the current ColorMatrixFilter instance.
	 **/
	p.clone = function() {
		return new ColorMatrixFilter(this.matrix);
	}

// private methods:

	p._initUniforms = function(ctx, program) {
		// Color matrix filter uniform references.
		ctx.colorMatrixUniform = 	ctx.getUniformLocation(program, "uColorMatrix");
		ctx.colorMatrixOffsetUniform = 	ctx.getUniformLocation(program, "uColorMatrixOffset");
	}

	/**
	 * @method _getFragmentShader
	 * Get fragment shader code in GLSL.
	 * @returns {String}
	 * @protected
	 */
	p._getFragmentShader = function() {
		return "" +
			"precision mediump float;				\n" +

			"varying vec2 vTextureCoord;			\n" +

			"uniform sampler2D uSampler;			\n" +
			"uniform mat4 uColorMatrix;				\n" +
			"uniform vec4 uColorMatrixOffset;		\n" +

			// Main
			"void main(void) {" +
			"vec4 color = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));" +
			"mat4 m = uColorMatrix;" +
			"vec4 newColor = vec4(0,0,0,0);" +
			"newColor.r = color.r*m[0][0] + color.g*m[0][1] + color.b*m[0][2] + color.a*m[0][3];" +
			"newColor.g = color.r*m[1][0] + color.g*m[1][1] + color.b*m[1][2] + color.a*m[1][3];" +
			"newColor.b = color.r*m[2][0] + color.g*m[2][1] + color.b*m[2][2] + color.a*m[2][3];" +
			"newColor.a = color.r*m[3][0] + color.g*m[3][1] + color.b*m[3][2] + color.a*m[3][3];" +
			"gl_FragColor = newColor + uColorMatrixOffset;" +
			"}";
	};

createjs.ColorMatrixFilter = ColorMatrixFilter;
}());