我一直在尝试在C#中的高度图(或高度域)类中实现双线性插值,但是并不真正理解Wiki上的数学。这是heightfield类的实现。我有第二个函数,Mathf.BilinearInterpolation(...),它抛出一个NotImplementedException。
/// <summary>
/// A flattened 2D array which contains the surface elevation data.
/// </summary>
public float[] Elevation { get; }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float ElevationAtVertex(int x, int y)
{
return Elevation[x + y + (y * Length)];
}
public float ElevationAtPoint(float x, float y)
{
float f1 = ElevationAtVertex(Mathf.Floor(x), Mathf.Floor(y));
float f2 = ElevationAtVertex(Mathf.Floor(x), Mathf.Ceiling(y));
float f3 = ElevationAtVertex(Mathf.Ceiling(x), Mathf.Floor(y));
float f4 = ElevationAtVertex(Mathf.Ceiling(x), Mathf.Ceiling(y));
return Mathf.BilinearInterpolation(f1, f2, f3, f4);
}
答案 0 :(得分:1)
在x上层“水平”线上插值,然后在x天花板“水平”线上插值,最后在连接前2个插值的“垂直”线上插值。请注意,从“垂直”线开始,然后“水平”插值提供相同的结果。
float xratio = x-Math.floor(x) ;
float yratio = y-Math.floor(y) ;
float f12 = f1+(f2-f1)*xratio ;
float f34 = f3+(f4-f3)*xratio ;
float result = f12+(f34-f12)*yratio ;
答案 1 :(得分:0)
这段代码是否正确?
public float ElevationAtPoint(float x, float y)
{
int x1 = Mathf.Floor(x);
int x2 = Mathf.Ceiling(x);
int y1 = Mathf.Floor(y);
int y2 = Mathf.Ceiling(y);
float q11 = ElevationAtVertex(x1, y1);
float q12 = ElevationAtVertex(x1, y2);
float q21 = ElevationAtVertex(x2, y1);
float q22 = ElevationAtVertex(x2, y2);
float r1 = ((x2 - x) / (x2 - x1)) * q11 + ((x - x1) / (x2 - x1)) * q21;
float r2 = ((x2 - x) / (x2 - x1)) * q12 + ((x - x1) / (x2 - x1)) * q22;
return ((y2 - y) / (y2 - y1)) * r1 + ((y - y1) / (y2 - y1)) * r2;
}