Skip to content

Instantly share code, notes, and snippets.

@transitive-bullshit
Last active June 27, 2017 16:31
Show Gist options
  • Save transitive-bullshit/13022a12b616fddf7da6c32afaaebf16 to your computer and use it in GitHub Desktop.
Save transitive-bullshit/13022a12b616fddf7da6c32afaaebf16 to your computer and use it in GitHub Desktop.
/**
* @class GLCompositeNode
*
* Composites all children simulating the standard blend function:
*
* gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA).
*/
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { Shaders, Node, GLSL } from 'gl-react'
export default class GLCompositeNode extends PureComponent {
static propTypes = {
children: PropTypes.node.isRequired
}
componentWillMount() {
this._reset(this.props)
}
componentWillReceiveProps(props) {
this._reset(props)
}
render() {
const {
children,
...other
} = this.props
return (
<Node
shader={this.shaders.composite}
uniforms={{
children
}}
{...other}
/>
)
}
_reset(props) {
const { children } = props
if (Array.isArray(children)) {
const compositeChildren = children.slice(1).map((_, i) => `
src = texture2D(children[${i + 1}], uv);
dest = mix(src.rgb, dest.rgb, 1.0 - src.a);
`).join('\n\n')
this.shaders = Shaders.create({
composite: {
frag: GLSL`
precision highp float;
varying vec2 uv;
uniform sampler2D children[${children.length}];
void main () {
vec3 dest = texture2D(children[0], uv).rgb;
vec4 src;
${compositeChildren}
gl_FragColor = vec4(dest, 1.0);
}
`
}
})
} else {
this.shaders = Shaders.create({
composite: {
frag: GLSL`
precision highp float;
varying vec2 uv;
uniform sampler2D children;
void main () {
vec4 dest = texture2D(children, uv);
gl_FragColor = dest;
}
`
}
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment