Skip to content

Instantly share code, notes, and snippets.

@troufster
Created February 8, 2011 21:26
Show Gist options
  • Save troufster/817287 to your computer and use it in GitHub Desktop.
Save troufster/817287 to your computer and use it in GitHub Desktop.
Simple 2d-vector interpolator
function Interpolator(type) {
this._i = type.func;
this._snum = type.samples;
this.s = []; //Samples
};
Interpolator.prototype.addSample = function(sample){
var p = this.s;
p.push(sample);
if(p.length > this._snum) p.shift();
};
Interpolator.prototype.getValue = function(t){
return this._i(this.s, t);
};
Interpolator.Linear = {
samples : 2,
func : function(d,t){
var v1 = d[0],
v2 = d[1];
if(!v2) return new Vector(0,0);
var r1x = v1.x * (1-t),
r1y = v1.y * (1-t),
r2x = v2.x * t,
r2y = v2.y * t
return(new Vector(r1x+r2x,r1y+r2y));
}
};
Interpolator.CatmullRom = {
samples : 4,
func : function(d,mu) {
var v0 = d[0],
v1 = d[1],
v2 = d[2],
v3 = d[3],
a0,a1,a2,a3,mu2;
if(!v0 || !v1 || !v2 || !v3 || !mu) return new Vector(0,0);
mu2 = mu*mu;
var a0x = -0.5 * v0.x + 1.5 * v1.x - 1.5 * v2.x + 0.5 * v3.x,
a0y = -0.5 * v0.y + 1.5 * v1.y - 1.5 * v2.y + 0.5 * v3.y,
a1x = v0.x - 2.5 * v1.x + 2 * v2.x - 0.5 * v3.x,
a1y = v0.y - 2.5 * v1.y + 2 * v2.y - 0.5 * v3.y,
a2x = -0.5 * v0.x + 0.5 * v2.x,
a2y = -0.5 * v0.y + 0.5 * v2.y,
a3x = v1.x,
a3y = v1.y,
rx = a0x * mu * mu2 + a1x * mu2 + a2x * mu + a3x,
ry = a0y * mu * mu2 + a1y * mu2 + a2y * mu + a3y;
return new Vector(rx,ry);
}
};
Interpolator.Hermite = {
samples : 4,
func : function(d,mu) {
var v0 = d[0],
v1 = d[1],
v2 = d[2],
v3 = d[3],
bias = 0,
tension = -0.3;
if(!v0 || !v1 || !v2 || !v3 || !mu) return new Vector(0,0);
var mu2 = mu * mu,
mu3 = mu2 *mu,
bbias = (1+bias),
cbias = (1-bias),
ten = (1-tension),
pb = bbias * ten / 2,
nb = cbias * ten / 2;
var m0x = (v1.x-v0.x) * pb,
m0y = (v1.y-v0.y) * pb;
m0x += (v2.x-v1.x) * nb;
m0y += (v2.y-v1.y) * nb;
var m1x = (v2.x-v1.x) * pb,
m1y = (v2.y-v1.y) * pb;
m1x += (v3.x-v2.x) * nb;
m1y += (v3.y-v2.y) * nb;
var a0 = 2*mu3 - 3*mu2 + 1,
a1 = mu3 - 2*mu2 + mu,
a2 = mu3 - mu2,
a3 = -2*mu3 + 3*mu2,
rx = a0*v1.x + a1*m0x + a2*m1x + a3*v2.x,
ry = a0*v1.y + a1*m0y + a2*m1y + a3*v2.y;
return new Vector(rx,ry);
}
};
Interpolator.Cubic = {
samples : 4,
func : function(d,mu) {
var v0 = d[0],
v1 = d[1],
v2 = d[2],
v3 = d[3];
if(!v0 || !v1 || !v2 || !v3 || !mu) return new Vector(0,0);
var mu2 = mu*mu,
a0x = v3.x - v2.x - v0.x + v1.x,
a0y = v3.y - v2.y - v0.y + v1.y,
a1x = v0.x - v1.x - a0x,
a1y = v0.y - v1.y - a0y,
a2x = v2.x - v0.x,
a2y = v2.y - v0.y,
a3x = v1.x,
a3y = v1.y,
rx = a0x * mu * mu2 + a1x * mu2 + a2x * mu + a3x,
ry = a0y * mu * mu2 + a1y * mu2 + a2y * mu + a3y;
return new Vector(rx,ry);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment