3

I have this function that I use to calculate the index from u,v points based on its respective uStep and vStep values

function getIndex1( u,v, uStep, vStep ) {
    var res = [];

    for( var i = 0; i < 45; i++ ) {
        res[i] = Math.round( v ) * 128 + Math.round( u ); 
        v += vStep;
        u += uStep;
    }
    return res;
}

If I try to interpolate this function, I get this

function getIndex2( u,v, uStep, vStep ) {
    var res = [];

    v *= 128;
    vStep *= 128;
    for( var i = 0; i < 45; i++ ) {
        res[i] = Math.round( v + u );
        v += vStep;
        u += uStep;
    }
    return res;
}

This works great when u,v,uStep,vStep are integers, the problem arise when these values are floats. I have the hunch that I need some "bresenham code" to accomplish my goal. Hope that some can help me.

arcollector
  • 101
  • 5
  • let me guess, you're drawing a line? – tobspr Nov 21 '13 at 20:42
  • nope, linear texturing mapping – arcollector Nov 21 '13 at 20:47
  • You should maybe handle the floats in some way by using .tofixed() or by converting them to Ints before the round() takes place. There are quite a few other questions related to the Javascript float problem - http://stackoverflow.com/questions/2221167/javascript-formatting-a-rounded-number-to-n-decimals – Asta Nov 21 '13 at 21:43
  • This is the best answer I've found on the problem : http://stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem – Zachary Carter Nov 28 '13 at 01:36

1 Answers1

1

I think the problem is that when your step values are floating points the mathematical error accumulates each iteration of the loop. The way to fix this is to multiply each step value by the index.

function getIndex(u, v, uStep, vStep) {
  var res = [];
  for (var i = 0; i < 45; ++i) {
    var du = uStep * i;
    var dv = vStep * i;
    res[i] = Math.round(v + dv) * 128 + Math.round(u + du);
  }
  return res;
}

This reduces error because the floating point calculations only occur once per loop and have no affect on the next iteration. As a side benefit this should slightly improve the performance of your algorithm.

Ethan Lynn
  • 1,009
  • 6
  • 13