I want to fade the scene into grayscale, but this also applies to other post-processing effects I'd like to fade in or out.
So for this example I'm using the THREE.ColorifyShader, but when activating it, the whole scene instantly receives the intended color
How can I "apply opacity/alpha" to post-processing?
Code example:
var effectColorify,
copyPass;
effectColorify = new THREE.ShaderPass(THREE.ColorifyShader);
effectColorify.uniforms['color'].value.setRGB(0.8, 0.8, 0.8); // Grayscale
copyPass = new THREE.ShaderPass(THREE.CopyShader);
copyPass.renderToScreen = true;
this.composerGrayscale = new THREE.EffectComposer(this.engine.renderer);
this.composerGrayscale.addPass(this.renderPass);
this.composerGrayscale.addPass(effectColorify);
this.composerGrayscale.addPass(copyPass);
I solved the issue by adding an "opacity" uniform to the colorify shader. This allows to smoothly blend from the normal, colored, scene to a certain color by increasing opacity or the other way round.
effectColorify.uniforms['opacity'].value = 0.5; // 50% scene-color, 50% shader-color.
Here is the adjusted shader code you can copy into ColorifyShader.js, which is backwards compatible to the previous version, since default opacity is 1.0:
THREE.ColorifyShader = {
uniforms: {
"tDiffuse": { type: "t", value: null },
"color": { type: "c", value: new THREE.Color( 0xffffff ) },
"opacity": { type: "f", value: 1.0 }
},
vertexShader: [
"varying vec2 vUv;",
"void main() {",
"vUv = uv;",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join("\n"),
fragmentShader: [
"uniform float opacity;",
"uniform vec3 color;",
"uniform sampler2D tDiffuse;",
"varying vec2 vUv;",
"void main() {",
"vec4 texel = texture2D( tDiffuse, vUv );",
"vec3 luma = vec3( 0.299, 0.587, 0.114 );",
"float v = dot( texel.xyz, luma );",
"vec3 finalColor = vec3(",
"(opacity * v * color.x) + ((1.0 - opacity) * texel.x),",
"(opacity * v * color.y) + ((1.0 - opacity) * texel.y),",
"(opacity * v * color.z) + ((1.0 - opacity) * texel.z)",
");",
"gl_FragColor = vec4( finalColor, texel.w );",
"}"
].join("\n")
};