Skip to content

Instantly share code, notes, and snippets.

@digitalicarus
Created July 5, 2012 02:37
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 digitalicarus/3050734 to your computer and use it in GitHub Desktop.
Save digitalicarus/3050734 to your computer and use it in GitHub Desktop.
2d midpoint displacement
/* http://www.gameprogrammer.com/fractal.html */
// Also, as expected, shifting is waaay faster than division, even in JS :) http://jsperf.com/division-vs-shift unfortunately it also truncates to the mantissa of floating points
// http://jsfiddle.net/digitalicarus/YUDgH/24/
// TODO: abs option, obj args, exception reason
var calcTerrain = function(conf) {
var height = conf.height,
swing = conf.swing,
h = conf.decay || conf.smooth || conf.smoothness,
i = conf.degree,
lb = (height-swing < 0) ? conf.lowerBound : null,
ub = (swing>height) ? conf.upperBound : null;
function CTE(msg) {
this.name="CalcTerrainException";
this.message = msg;
this.toString = function() {
return this.name+": "+this.message;
};
};
if(typeof(i) != "number" || i<1) {
throw new CTE("degree must be an integer greater than 1");
}
if(typeof(swing) != "number" || swing<1) {
throw new CTE("swing must be an integer greater than 1");
}
if(typeof(height) != "number" || height<0) {
throw new CTE("height must be an integer greater than 0");
}
if(typeof(h) != "number" || h<0 || h>1) {
throw new CTE("smoothness must be a floating point between 0 and 1 non-inclusive");
}
var decay = (Math.pow(2,-h));
function gen(start,mid,end,swing,i) {
// displace midpoint zero center swing
// 0 -> x : -x/2 -> x/2
mid = mid + Math.random()*swing-(swing/2);
mid = (lb && mid < lb) ? lb : mid;
mid = (ub && mid > ub) ? ub : mid;
if(i==1) {
i--;
return [mid>>0];
}
if(i>1) {
var midleft = (mid+start)/2;
var midright = (end+mid)/2;
swing = swing * decay;
i--;
/*
start startright
startleft mid
| endleft endright
| | |
. . . . .
| |
midleft midright
*/
return gen(start,midleft,mid,swing,i)
.concat([mid>>0])
.concat(gen(mid,midright,end,swing,i));
}
}
return gen(height,height,height,swing,i);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment