# How to do trilinear interpolation?

Hello there. I’ve been working on something that needs trilinear interpolation, and here is my current function

I based it on this answer on stackoverflow.

And this.

The issue is it’s supposed to interpolate where one corner is one, and all other corners are 0 however, this doesn’t seem to do that. (I’m interpolating part transparencies for the sake of making sure it works)

In the screenshot, notice how one corner is supposed to be one, and all other corners are supposed to be 0

It might be hard to see, but in the second screenshot, notice how 2 corners are transparent instead of one. Is there any way I can fix this?

Here is the code, for those of you who don’t want to get the model

``````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

function getTriValue(v1, v2, v3, v4, v5, v6, v7, v8, x, y, z)
local top = getBilinearValue(v1, v2, v3, v4, x, y)
local bottom = getBilinearValue(v5, v6, v7, v8, x, y)
local middle = interpolate(top, bottom, z)
return middle
end

for x = 1, 16 do
wait()
for y = 1, 16 do
for z = 1, 16 do
local value = getTriValue(0, 0, 0, 1, 0, 0, 0, 0, x / 16, y / 16, z / 16)
local block = Instance.new("Part")
block.Anchored = true
block.Size = Vector3.new(2, 2, 2)
block.CFrame = CFrame.new(x * 2, y * 2, z * 2)
block.Parent = workspace
block.Transparency = value
end
end
end

``````

Is there any way I can fix this issue?

This should say:

``````local bottom=interpolate(value01,value11,xProgress)
``````

here is my own code for doing this which i think looks much nicer than your scrap pile.

``````local function linear(x, y, a)
return (1 - a) * x + a * y
end

local function bilinear(x, y, j, k, a, b)
return linear(linear(x, y, a), linear(j, k, a), b)
end

local function trilinear(x, y, j, k, l, m, n, o, a, b, c)
return linear(bilinear(x, y, j, k, a, b), bilinear(l, m, n, o, a, b), c)
end

for x = 1, 16 do
for y = 1, 16 do
for z = 1, 16 do
local w = trilinear(0, 0, 0, 1, 0, 0, 0, 0, x / 16, y / 16, z / 16)
local p = Instance.new("Part")

p.Anchored = true
p.Size = Vector3.new(2, 2, 2)
p.CFrame = CFrame.new(x * 2, y * 2, z * 2)
p.Transparency = w
p.Parent = workspace
end
end
end
``````

3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.