2014-11-02 49 views
0

我理解這個概念,但我在實現2D細分背後的循環邏輯時遇到了困難。我有一個二維數組代表一個網格的角落播種。我相信我需要3個循環。 1循環進行細分迭代次數。對於行中的每一列第二個,對於每一行第三個。試圖在2D中點細分中計算環路的邏輯

這就是我所擁有的。它顯示了左上角方形細分的結果。這就是爲什麼行和列只循環一次。如果我得到基本的邏輯,其餘的應該是蛋糕。但是循環在第三次迭代中不起作用。我很確定循環需要更復雜。

迭代是手動設置的變量。

 // iterate though subdivision levels 
     for(i = 1; i <= iterations; i++) {     // iteration 

      // iterate through each row 
      for(row = 1; row <= 1; row += size/i) {  // row 

       // iterate through each column and subdivide 
       for(col = 1; col <= 1; col += size/i) { // column 

        //*** ONLY SHOWING THE FIRST SUBDIVIDE OF EACH ITERATION ***// 

        // Math.pow(2, iterations)/2/i = 1 
        // i = 1, iteration = 1 
        heightmap[0][1] = (heightmap[0][0] + heightmap[0][2])/2; 

        // Math.pow(2, iterations)/2/i = 2 
        // i = 1, iterations = 2 
        heightmap[0][2] = (heightmap[0][0] + heightmap[0][4])/2; 

        // Math.pow(2, iterations)/2/i = 4 
        // i = 1, iterations = 3 
        heightmap[0][4] = (heightmap[0][0] + heightmap[0][8])/2; 

        // if iterations == 1, i != 2 

        // Math.pow(2, iterations)/2/i = 1 
        // i = 2, iterations = 2 
        heightmap[0][1] = (heightmap[0][0] + heightmap[0][2])/2; 

        // Math.pow(2, iterations)/2/i = 2 
        // i = 2, iterations = 3 
        heightmap[0][2] = (heightmap[0][0] + heightmap[0][4])/2; 

        // if iterations == 1 or 2, i != 3 

        // Math.pow(2, iterations)/2/i = 4/3 != 1 
        // i = 3, iterations = 3 
        heightmap[0][1] = (heightmap[0][0] + heightmap[0][2])/2; 
       } 
      } 
     } 

如果這有助於我用於一維細分。

// increase the number of segments 
for(var i = 1; i < size; i *= 2){ 

    // iterate through each segment calculating the 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); 
    } 

} 

回答

1

這將是更容易在時間細分一個方向:

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; 

for (var iteration = 1; iteration < size; iteration *= 2) { 
    var step = size/iteration; 

    // * . * . * 
    // x . x . x 
    // * . * . * 
    for (var row = step/2; row < size; row += step) { 
     for (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 * 
    for (var row = 0; row <= size; row += step/2) { 
     for (var col = step/2; col < size; col += step) { 
      points[row][col] = ((points[row][col - step/2] + points[row][col + step/2])/2); 
     } 
    } 
} 

結果是:

[[ 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 ]]