Skip to content

Instantly share code, notes, and snippets.

@Erkaman
Last active May 21, 2017 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Erkaman/f3f30eb02106c30d41d7ccf135df63a7 to your computer and use it in GitHub Desktop.
Save Erkaman/f3f30eb02106c30d41d7ccf135df63a7 to your computer and use it in GitHub Desktop.
/*
The MIT License (MIT)
Copyright (c) 2017 Eric Arnebäck
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.
*/
const VIDEO_WIDTH = 800
const VIDEO_HEIGHT = 400
const canvas = document.body.appendChild(document.createElement('canvas'))
canvas.width = VIDEO_WIDTH
canvas.height = VIDEO_HEIGHT
const regl = require('regl')({ canvas: canvas })
//const regl = require('regl')(require('gl')(VIDEO_WIDTH, VIDEO_HEIGHT, {preserveDrawingBuffer: true}))
//var recorder = require('regl-recorder')(regl, 100)
const mat4 = require('gl-mat4')
const vec3 = require('gl-vec3')
const quat = require('gl-quat')
const normals = require('angle-normals')
// ssaa magnification.
const SSAAX = 2
// camera settings.
const camera = require('regl-camera')(regl, {
center: [8.5, 3, 0],
distance: 18,
theta: Math.PI*0.5,
phi: 0.6,
near: 0.01,
far: 1000
})
const normalFboBig = regl.framebuffer({
color: regl.texture({wrap: 'clamp', min: 'linear', max: 'linear' })})
const normalFbo = regl.framebuffer({
color: regl.texture({wrap: 'clamp', min: 'linear', max: 'linear' })})
var totalTime = 0.0
const mirrorFbo = []
mirrorFbo[0] = regl.framebuffer({
color: regl.texture({wrap: 'clamp', min: 'linear', max: 'linear' })})
mirrorFbo[1] = regl.framebuffer({
color: regl.texture({wrap: 'clamp', min: 'linear', max: 'linear' })})
const mirrorFboBig = regl.framebuffer({
color: regl.texture({wrap: 'clamp', min: 'linear', max: 'linear' })})
const barchart = regl({
frag: `
precision mediump float;
varying vec3 vPosition;
varying vec3 vNormal;
varying vec3 vWorldSpacePosition;
varying vec3 myval;
uniform vec4 uColor;
uniform vec3 eye;
uniform float uAmbientLight;
uniform float uDiffuseLight;
uniform float uSpecularLight;
uniform float uIndex;
uniform float uTotalTime;
void main () {
vec3 n = normalize(vNormal);
vec3 l = normalize(vec3(0.3, 0.8, 0.55));
vec3 v = normalize(eye - vWorldSpacePosition);
float spec = pow( max(dot(normalize(l+v),n),0.0) ,20.0);
gl_FragColor = vec4(
uColor.xyz * uAmbientLight +
vec3(spec) * uSpecularLight +
clamp(dot(n, l), 0.0, 1.0) * uColor.xyz * uDiffuseLight
, 1.0);
}`,
vert: `
precision mediump float;
attribute vec3 position;
attribute vec3 normal;
varying vec3 vPosition;
varying vec3 vWorldSpacePosition;
varying vec3 vNormal;
varying vec3 myval;
uniform mat4 model, normalMatrix, projection, view;
uniform vec3 eye;
uniform float uIndex;
uniform int uMirror;
uniform float uTotalTime;
void main() {
vec4 worldSpacePos = model * vec4(position , 1);
float t = uTotalTime;
float s = step(0.0, worldSpacePos.y - 0.5);
int i = int(uIndex);
// i = int(float(i) - 3.0 * floor( float(i) / 3.0 ));
float pi = 3.14159;
if(i == 0) {
worldSpacePos.y += s * 7.0 * (0.6 + 0.2*sin(t * 10.0) );
} else if(i == 1) {
worldSpacePos.y += s * 7.0 * (0.6 + 0.2*sin(t * 5.0) );
}else if(i == 2) {
worldSpacePos.y += s * 7.0 * (0.5 + 0.5*sin(t * 2.5) );
} else if(i == 3) {
worldSpacePos.y += s * 7.0 * (0.6 + 0.2*sin(t * 10.0 + 2.0*pi / 5.0 ) );
} else if(i == 4) {
worldSpacePos.y += s * 7.0 * (0.6 + 0.4*sin(t * 5.0 + (2.0*pi) / 5.0 ) );
}else if(i == 5) {
worldSpacePos.y += s * 7.0 * (0.6 + 0.3*sin(t * 2.5) );
} else if(i == 6) {
worldSpacePos.y += s * 7.0 * (0.4 + 0.1*sin(t * 10.0 + 1.0*pi / 5.0 ) );
} else if(i == 7) {
worldSpacePos.y += s * 7.0 * (0.6 + 0.4*sin(t * 5.0 ) );
} else if(i == 8) {
worldSpacePos.y += s * 7.0 * (0.3 + 0.2*sin(t * 5.0) );
} else if(i == 9) {
worldSpacePos.y += s * 7.0 * (0.4 + 0.3*sin(t * 10.0) );
}
if(uMirror == 1)
worldSpacePos.y *= -1.0;
vec4 p = projection * view * worldSpacePos;
vNormal = normalize((normalMatrix * vec4(normal, 0.0)).xyz);
vPosition = p.xyz / p.w;
vWorldSpacePosition = worldSpacePos.xyz;
gl_Position = p;
}`,
uniforms: {
uMirror: regl.prop('mirror'),
uTotalTime: regl.prop('totalTime'),
},
cull: {
// must do this, since we mirrored the mesh.
enable: true,
face: (_, props, batchId) => {
return props.mirror == 1 ? 'front' : 'back'
}
},
framebuffer: regl.prop('outFbo')
})
const combine = regl({
frag: `
precision mediump float;
varying vec2 uv;
uniform sampler2D normalTex;
uniform sampler2D mirrorTex;
uniform float wRcp, hRcp;
void main() {
vec4 n = texture2D(normalTex, uv);
// reflection in white floor.
vec4 m = mix(texture2D(mirrorTex, uv), vec4(1.0), 0.40);
vec3 color ;
color = mix(m.xyz, n.xyz, n.a);
gl_FragColor = vec4(color, 1.0);
}`,
vert: `
precision mediump float;
attribute vec2 position;
varying vec2 uv;
void main() {
uv = 0.5 * (position + 1.0);
gl_Position = vec4(position, 0, 1);
}`,
attributes: {
position: [ -4, -4, 4, -4, 0, 4 ]
},
uniforms: {
normalTex: () => normalFbo,
mirrorTex: () => mirrorFbo[0],
wRcp: ({viewportWidth}) => 1.0 / viewportWidth,
hRcp: ({viewportHeight}) => 1.0 / viewportHeight
},
depth: { enable: false },
count: 3
})
const downsample = regl({
frag: `
precision mediump float;
varying vec2 uv;
uniform sampler2D tex;
uniform float wRcp, hRcp;
#define N int(${SSAAX})
#define W 1.0 / (float(${SSAAX})*float(${SSAAX}))
void main() {
vec4 avg = vec4(0.0);
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++) {
avg += W * texture2D(tex, uv + vec2(float(x) * wRcp, float(y) * hRcp));
}
}
gl_FragColor = avg;
}`,
vert: `
precision mediump float;
attribute vec2 position;
varying vec2 uv;
void main() {
uv = 0.5 * (position + 1.0);
gl_Position = vec4(position, 0, 1);
}`,
attributes: {
position: [ -4, -4, 4, -4, 0, 4 ]
},
uniforms: {
tex: (_, props, batchId) => {return props.inFbo},
wRcp: (_, props, batchId) => { return 1.0 / props.inFboWidth},
hRcp: (_, props, batchId) => {return 1.0 / props.inFboHeight},
},
depth: { enable: false },
count: 3,
framebuffer: regl.prop('outFbo')
})
const blur = regl({
frag: `
precision mediump float;
varying vec2 uv;
uniform sampler2D tex;
uniform float wRcp, hRcp;
uniform vec2 direction;
void main() {
vec4 avg = vec4(0.0);
// taken from
// https://github.com/Jam3/glsl-fast-gaussian-blur
vec2 off1 = vec2(1.411764705882353) * direction;
vec2 off2 = vec2(3.2941176470588234) * direction;
vec2 off3 = vec2(5.176470588235294) * direction;
avg += texture2D(tex, uv) * 0.1964825501511404;
avg += texture2D(tex, uv + (off1 * vec2(wRcp,hRcp))) * 0.2969069646728344;
avg += texture2D(tex, uv - (off1 * vec2(wRcp,hRcp))) * 0.2969069646728344;
avg += texture2D(tex, uv + (off2 * vec2(wRcp,hRcp))) * 0.09447039785044732;
avg += texture2D(tex, uv - (off2 * vec2(wRcp,hRcp))) * 0.09447039785044732;
avg += texture2D(tex, uv + (off3 * vec2(wRcp,hRcp))) * 0.010381362401148057;
avg += texture2D(tex, uv - (off3 * vec2(wRcp,hRcp))) * 0.010381362401148057;
gl_FragColor = avg;
}`,
vert: `
precision mediump float;
attribute vec2 position;
varying vec2 uv;
void main() {
uv = 0.5 * (position + 1.0);
gl_Position = vec4(position, 0, 1);
}`,
attributes: {
position: [ -4, -4, 4, -4, 0, 4 ]
},
uniforms: {
tex: (_, props, batchId) => {return props.inFbo},
wRcp: (_, props, batchId) => { return 1.0 / props.inFboWidth},
hRcp: (_, props, batchId) => {return 1.0 / props.inFboHeight},
direction: regl.prop('direction')
},
depth: { enable: false },
count: 3,
framebuffer: regl.prop('outFbo')
})
const globalScope = regl({
uniforms: {
uAmbientLight: 0.3,
uDiffuseLight: 0.5,
uSpecularLight: 0.4,
uTotalTime: totalTime
}
})
function Mesh (elements, position, normal) {
this.elements = elements
this.position = position
this.normal = normal
}
// get single matrix from quaternion, translation and scale.
function fromRotationTranslationScale2 (out, q, v, s) {
mat4.identity(out)
var quatMat = mat4.create()
mat4.fromQuat(quatMat, q)
mat4.translate(out, out, v)
mat4.multiply(out, out, quatMat)
mat4.scale(out, out, s)
return out
}
Mesh.prototype.draw = regl({
context: {
model: (_, props, batchId) => {
var m = mat4.identity([])
var rot = quat.create()
quat.rotateX(rot, rot, props.rotation[0])
quat.rotateY(rot, rot, props.rotation[1])
quat.rotateZ(rot, rot, props.rotation[2])
fromRotationTranslationScale2(m, rot, props.translate, [props.scale, props.scale, props.scale])
return m
}
},
uniforms: {
model: regl.context('model'),
normalMatrix: (context) => {
return mat4.transpose([], mat4.invert([], context.model))
},
uColor: regl.prop('color'),
uIndex: regl.prop('index')
},
attributes: {
position: regl.this('position'),
normal: regl.this('normal')
},
elements: regl.this('elements'),
cull: {
enable: true
}
})
var m = require('primitive-rounded-cube')(1, 1, 1, 20, 20, 20, 0.1)
for(var i = 0; i < m.positions.length; i++) {
var p = m.positions[i]
p[1] = p[1] + 0.5
m.positions[i] = p
}
var cubeMesh = new Mesh(m.cells, m.positions, m.normals)
regl.frame(({tick, viewportWidth, viewportHeight}) => {
normalFboBig.resize(viewportWidth*SSAAX, viewportHeight*SSAAX)
mirrorFboBig.resize(viewportWidth*SSAAX, viewportHeight*SSAAX)
normalFbo.resize(viewportWidth, viewportHeight)
mirrorFbo[0].resize(viewportWidth, viewportHeight)
mirrorFbo[1].resize(viewportWidth, viewportHeight)
camera(() => {
// draw bars.
drawCubes = () => {
for(var i = 0; i < 10; i++) {
cubeMesh.draw({scale: 1.0, translate: [i*2.0,0,0], color: [1.0,0.0,0.0, 1.0], rotation: [0.0, 0.0, 0.0], index: i})
}
}
globalScope(() => {
barchart({mirror: 0, outFbo: normalFboBig, totalTime: totalTime}, () => {
regl.clear({color: [255, 255, 255, 0], depth: 1})
drawCubes()
})
// draw mirrored bars.
barchart({mirror: 1, outFbo: mirrorFboBig, totalTime: totalTime}, () => {
regl.clear({color: [255, 255, 255, 0], depth: 1})
drawCubes()
})
// downsample ssaa
downsample({
outFbo: mirrorFbo[0],
inFboWidth: viewportWidth*SSAAX,
inFboHeight: viewportHeight*SSAAX,
inFbo: mirrorFboBig})
// downsample ssaa
downsample({
outFbo: normalFbo,
inFboWidth: viewportWidth*SSAAX,
inFboHeight: viewportHeight*SSAAX,
inFbo: normalFboBig})
var N = 1
// gaussian blur.
for(var i = 0; i < N; i++) {
var rad = 0.5 * (N - i);
blur({
outFbo: mirrorFbo[1],
inFboWidth: viewportWidth,
inFboHeight: viewportHeight,
direction: [rad, 0.0],
inFbo: mirrorFbo[0]})
blur({
outFbo: mirrorFbo[0],
inFboWidth: viewportWidth,
inFboHeight: viewportHeight,
direction: [0.0, rad],
inFbo: mirrorFbo[1]})
}
regl.clear({color: [255, 255, 255, 255], depth: 1})
// combine the two fbos.
combine()
})
})
// console.log(totalTime)
totalTime += ((4.0*Math.PI)/5.0) / 200.0
// recorder.frame(viewportWidth, viewportHeight)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment