# How do I do Bilinear Interpolation?

1. What do you want to achieve? Keep it simple and clear!

I want to do bilinear interpolation (https://en.wikipedia.org/wiki/Bilinear_interpolation) but I can’t figure out how to do it.

1. What is the issue? Include screenshots / videos if possible!

I don’t know how to do it and the algorithms shown on the Wikipedia page look complicated and I don’t know how to use it.

1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

I have tried searching how to do bilinear interpolation but I can’t figure out how to do it in lua.

The information you’re providing is kinda limited. What are you actually trying to create using bilinear interpolation? What’s your end goal?

I am trying to do procedural terrain generation and in order to make the elevation of four biomes blend seamlessly I need to do bilinear interpolation because linear interpolation only works with two biomes blending seamlessly.

Alrighty, it seems that the bilinear interpolation process isn’t too difficult. This article does a really good job of explaining the steps (I’d highly recommend reading it to understand how it works), and the steps can then be converted into a Lua function:

``````function interpolate(x,y,alpha) --simple linear interpolation
local difference=y-x
local progress=alpha*difference
local result=progress+x
return result
end

function getBilinearValue(value00,value10,value01,value11,xProgress,yProgress)
local top=interpolate(value00,value10,xProgress) --get progress across line A
local bottom=interpolate(value01,value11,yProgress) --get line B progress
local middle=interpolate(top,bottom,yProgress) --get progress of line going
return middle                              --between point A and point B
end
``````

``````--an example:
local value00=78
local value10=954
local value01=856
local value11=24

local xProgress=0.35
local yProgress=0.35

local bilinearValue=getBilinearValue(value00,value10,value01,value11,xProgress,yProgress)
print(bilinearValue)
``````

The function I wrote takes six parameters. The first four are the values of the corners, and the last two are floats representing how far between the top left and bottom right the point is.

3 Likes

Thank you, this is very useful.

For a much deeper understanding, have a look at Bilinear Interpolation Calculator.

It goes much more in-depth on the uses of bilinear(2d) interpolation and the technical stuff

Here is the raw lua code:

``````local function interpolate2d(x1, y1, x2,y2, q11, q12, q21, q22, x, y)

return (q11 * (x2 - x) * (y2 - y) +

q21 * (x - x1) * (y2 - y) +

q12 * (x2 - x) * (y - y1) +

q22 * (x - x1) * (y - y1)

) / ((x2 - x1) * (y2 - y1))

end

print(interpolate2d(0,0,15,15,0,3,4,3,4,4)) --test
``````

(and if you really want, have a look at trilinear interpolation (3d) Interpolation (Trilinear Interpolation))

1 Like