Skip to content

Instantly share code, notes, and snippets.

@justinmeiners
Created July 3, 2020 21:32
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 justinmeiners/17461343cc3e441536d10a3c4d6e46f6 to your computer and use it in GitHub Desktop.
Save justinmeiners/17461343cc3e441536d10a3c4d6e46f6 to your computer and use it in GitHub Desktop.
// node kernel.js > out.txt; gnuplot -p -e 'plot "out.txt" using 1:2 with points pt 7'
function minimizeEnergy(samples, sampleCount, steps) {
// energy conservation
// https://web.archive.org/web/20090422055305/
// http://www.malmer.nu/index.php/2008-04-11_energy-minimization-is-your-friend/
for (var step = 0; step < steps; ++step) {
for (var i = 0; i < sampleCount; ++i) {
var x = samples[i * 2];
var y = samples[i * 2 + 1];
var fx = 0.0;
var fy = 0.0;
for (var j = 0; j < sampleCount; ++j) {
var dX = x - samples[j * 2];
var dY = y - samples[j * 2 + 1];
// inverse square
var lengthSqr = (dX * dX + dY * dY);
if (lengthSqr > 0.01) {
var power = 1.0 / lengthSqr;
fx += power * dX;
fy += power * dY;
}
}
var ex = x + fx * 0.001;
var ey = y + fy * 0.001;
var len = Math.sqrt(ex * ex + ey * ey);
if (len > 1.0) {
ex /= len;
ey /= len;
}
samples[i * 2] = ex;
samples[i * 2 + 1] = ey;
}
}
}
function createSsaoKernel(sampleCount) {
// Random points in disc, biased against center + .
var samples = new Float32Array(sampleCount * 2);
for (var i = 0; i < sampleCount; ++i) {
var theta = i * 2.0 * Math.PI / sampleCount;
var bias = 0.1;
var r = bias + Math.random() * (1.0 - bias);
samples[i * 2] = Math.cos(theta) * r;
samples[i * 2 + 1] = Math.sin(theta) * r;
}
minimizeEnergy(samples, sampleCount, 5);
for (var i = 0; i < sampleCount; ++i) {
console.log("" + samples[i * 2] + "\t" + samples[i * 2 + 1]);
}
return samples;
}
createSsaoKernel(32);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment