取自《Focus On 3D Terrain Programming》中的一段:
bool CTERRAIN::MakeTerrainFault( int iSize, int iIterations, int iMinDelta, int iMaxDelta, float fFilter )
{
......
.............
for( iCurrentIteration=; iCurrentIteration<iIterations; iCurrentIteration++ )
{
//calculate the height range (linear interpolation from iMaxDelta to iMinDelta) for this fault-pass
iHeight= iMaxDelta - ( ( iMaxDelta-iMinDelta )*iCurrentIteration )/iIterations; //pick two points at random from the entire height map
iRandX1= rand( )%m_iSize;
iRandZ1= rand( )%m_iSize; //check to make sure that the points are not the same
do
{
iRandX2= rand( )%m_iSize;
iRandZ2= rand( )%m_iSize;
} while ( iRandX2==iRandX1 && iRandZ2==iRandZ1 ); //iDirX1, iDirZ1 is a vector going the same direction as the line
iDirX1= iRandX2-iRandX1;
iDirZ1= iRandZ2-iRandZ1; for( z=; z<m_iSize; z++ )
{
for( x=; x<m_iSize; x++ )
{
//iDirX2, iDirZ2 is a vector from iRandX1, iRandZ1 to the current point (in the loop)
iDirX2= x-iRandX1;
iDirZ2= z-iRandZ1; //if the result of ( iDirX2*iDirZ1 - iDirX1*iDirZ2 ) is "up" (above 0),
//then raise this point by iHeight
if( ( iDirX2*iDirZ1 - iDirX1*iDirZ2 )> )
fTempBuffer[( z*m_iSize )+x]+= ( float )iHeight;
}
}
//erode terrain
FilterHeightField( fTempBuffer, fFilter );
}
.......
..............
return true;
}
===================
代码的核心内容就是实现一个fault formation算法,算法是一个简单的数学模型,所以只要按照在纸上画个图就明白了。随笔的重点只是一行代码:
iDirX2*iDirZ1 - iDirX1*iDirZ2>0
这行代码参考的是二维向量共线定理:若设a=(x1,y1),b=(x2,y2),则有x1y2=x2y1。即与平行概念相同x1y2 - x2y1=0
另外,iMinDelta和iMaxDelta确实不符合我们的习惯,我们一般都习惯iMinValue和iMaxValue这样