jit.gl.pix.codebox function return incorrect value.

filete's icon

I'm learning shaders, so I tried to make my own lerp function.

This is the codeblock in question:

l_erp(a,b,factor){
    return (a-factor + (b*factor));
}
Param fctr(0);
color1 = vec(1,0,0,1);
color2 = vec(0,1,0,1);
frag_color = l_erp(color1, color2, fctr;
out = frag_color;

The param fctr is a dial input.

Well, when doing [ a - factor ] and [ b factor ] individually, it works; the problem happens when adding both. Also tried [ a- factor + b ] , and the result is the same as [ (a+b) -factor ].

However, i tried returning [a * factor + (b*(norm.x+factor)) ] and the result was as expected.
But when changing [ a * factor ... ] for [ a - factor ... ] it broke again, the second factor was not multiplying b.

Am I doing something wrong?

Matteo Marson's icon

Hey there,

there are a few mistakes in your code:

  • the math for the lerp function looks wrong, because it should be:
    result = A*(1-i) + B*i

Where A and B are the two inputs to interpolate, and "i" is an interpolation factor between 0 and 1. When "i" is 0, result = A*1 + B*0 = A; when "i" is 1, result = A*0 + B*1 = B; for any "i" value in between, the result is a weighted blend of the inputs.
Eventually, you can rework the math, and express it as:
result = A + i*(B-A)

  • You forgot to close the parenthesis where you call the l_erp function

  • the output variable is "out1", not "out".

    For reference, i copied here a working version of the code

Max Patch
Copy patch and select New From Clipboard in Max.

filete's icon

Thank you for your help.