Sunday 15 May 2011

javascript - Trying to figure the logic of the loop in a 2D midpoint subdivide -



javascript - Trying to figure the logic of the loop in a 2D midpoint subdivide -

i understand concept having problem implementing looping logic behind 2d subdivide. have 2d array representing grid corners seeded. believe need 3 loops. 1 loop number of subdivide iterations. sec 1 each column in row, , 3rd each row.

this have. shows results of top-left square subdivide. why row , column loops once. if basic logic rest should cake. loop not work on 3rd iteration. pretty sure loop needs more complex.

iterations manually set variable.

// iterate though subdivision levels for(i = 1; <= iterations; i++) { // iteration // iterate through each row for(row = 1; row <= 1; row += size / ) { // row // iterate through each column , subdivide for(col = 1; col <= 1; col += size / i) { // column //*** showing first subdivide of each iteration ***// // math.pow(2, iterations) / 2 / = 1 // = 1, iteration = 1 heightmap[0][1] = (heightmap[0][0] + heightmap[0][2]) / 2; // math.pow(2, iterations) / 2 / = 2 // = 1, iterations = 2 heightmap[0][2] = (heightmap[0][0] + heightmap[0][4]) / 2; // math.pow(2, iterations) / 2 / = 4 // = 1, iterations = 3 heightmap[0][4] = (heightmap[0][0] + heightmap[0][8]) / 2; // if iterations == 1, != 2 // math.pow(2, iterations) / 2 / = 1 // = 2, iterations = 2 heightmap[0][1] = (heightmap[0][0] + heightmap[0][2]) / 2; // math.pow(2, iterations) / 2 / = 2 // = 2, iterations = 3 heightmap[0][2] = (heightmap[0][0] + heightmap[0][4]) / 2; // if iterations == 1 or 2, != 3 // math.pow(2, iterations) / 2 / = 4/3 != 1 // = 3, iterations = 3 heightmap[0][1] = (heightmap[0][0] + heightmap[0][2]) / 2; } } }

if helps used 1d subdivide.

// increment number of segments for(var = 1; < size; *= 2){ // iterate through each segment calculating center point for(var j = (size / i) / 2; j < size; j += size / i){ points[j] = ((points[j - (size / i) / 2] + points[j + (size / i) / 2]) / 2); } }

it easier subdivide 1 direction @ time:

var points = [[ 0,-1,-1,-1, 1], [-1,-1,-1,-1,-1], [-1,-1,-1,-1,-1], [-1,-1,-1,-1,-1], [ 2,-1,-1,-1, 0]]; var size = 4; (var iteration = 1; iteration < size; iteration *= 2) { var step = size / iteration; // * . * . * // x . x . x // * . * . * (var row = step / 2; row < size; row += step) { (var col = 0; col <= size; col += step) { points[row][col] = ((points[row - step / 2][col] + points[row + step / 2][col]) / 2); } } // * x * x * // * x * x * // * x * x * (var row = 0; row <= size; row += step / 2) { (var col = step / 2; col < size; col += step) { points[row][col] = ((points[row][col - step / 2] + points[row][col + step / 2]) / 2); } } }

the result is:

[[ 0, 0.25, 0.5, 0.75, 1 ], [ 0.5, 0.5625, 0.625, 0.6875, 0.75 ], [ 1, 0.875, 0.75, 0.625, 0.5 ], [ 1.5, 1.1875, 0.875, 0.5625, 0.25 ], [ 2, 1.5, 1, 0.5, 0 ]]

javascript arrays loops logic heightmap

No comments:

Post a Comment