Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

custom textures #40

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,36 @@
surface = { centerX: 0, centerY: 0, width: 1, height: 1, isPanning: false, isZooming: false, lastX: 0, lastY: 0 },
frontTarget, backTarget, screenProgram, getWebGL, resizer = {}, compileOnChangeCode = true;

var customTextures, textureCache = {}, loadCustomTexture = function ( url ) {
if (!textureCache[ url ]) {

var tex = gl.createTexture();
var img = new Image();

// assume cross-domain image
img.crossOrigin = 'anonymous';

img.onload = function () {
gl.bindTexture(gl.TEXTURE_2D, tex);

// assume NPOT texture
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);

gl.bindTexture(gl.TEXTURE_2D, null);
};

img.src = url;

textureCache[ url ] = tex;
}

return textureCache[ url ];
};

init();
if (gl) { animate(); }

Expand Down Expand Up @@ -299,6 +329,8 @@

} else {

gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, true );

// enable dFdx, dFdy, fwidth
gl.getExtension('OES_standard_derivatives');

Expand Down Expand Up @@ -621,6 +653,17 @@
cacheUniformLocation( program, 'backbuffer' );
cacheUniformLocation( program, 'surfaceSize' );

// Custom textures

customTextures = {};

var matches, regexp = /sampler2D\s+(\w+)\s*;\s*\/\/\s*([^\s]+)/g;
while (matches = regexp.exec (fragment)) {
var name = matches[ 1 ];
cacheUniformLocation( program, name );
customTextures[ name ] = matches[ 2 ];
}

// Load program into GPU

gl.useProgram( currentProgram );
Expand Down Expand Up @@ -893,6 +936,18 @@
gl.activeTexture( gl.TEXTURE0 );
gl.bindTexture( gl.TEXTURE_2D, backTarget.texture );

// Load custom textures

var sampler = 1;
for (var samplerName in customTextures) {
gl.uniform1i( currentProgram.uniformsCache[ samplerName ], sampler );

gl.activeTexture( gl[ 'TEXTURE' + sampler ] );
gl.bindTexture( gl.TEXTURE_2D, loadCustomTexture( customTextures[ samplerName ] ) );

sampler++;
}

// Render custom shader to front buffer

gl.bindFramebuffer( gl.FRAMEBUFFER, frontTarget.framebuffer );
Expand Down