ue4 material custom node - global function and method


在ue4 material中定義全局函數

1. 背景

  原文unreal-engine-4-custom-shaders-tutorial 中,提出了一種在material生成的hlsl文件中定義全局函數的方法,記錄到這里以備復習。

  ue4 材質中的custom節點是用來使用hlsl代碼的地方。一般來說都是直接編輯邏輯,最后添加return返回。類似這樣:

1 float4 color = {1,0,0,1};
2 return color;

使用ue4材質 menu window->hlsl shader查看實際生成的hlsl代碼,會看到這段代碼會被宏替換到一個CustomExpression0的函數里面。

類似於:

MaterialFloat4 CustomExpression0(FMaterialPixelParameters Parameters)
{
    float4 color = {1,0, 0, 1};
    return color;
};

優點是可以快速編輯算法。

這種方式的特點是:

  1. 函數內不能定義函數(可以定義struct,然后用struct的方法代替函數)

  2. 定義的內容只在該函數內部可見,無法重用。

2. 定義全局函數的 trick

因為ue4 custom material使用的是替換,所以我們可以寫出這樣的代碼 

1     return 1;
2 }
3 
4 float Calculate1DGaussian(float x)
5 {
6     return exp(-0.5 * pow(3.141 * (x), 2));

替換的結果就變成了

 

MaterialFloat4 CustomExpression0(FMaterialPixelParameters Parameters)
{
    return 1;
}

float Calculate1DGaussian(float x)
{
    return exp(-0.5 * pow(3.141 * (x), 2));
}

生成的函數變成了兩個,

Calculate1DGaussian函數就變成了全局函數。

使用上需要注意的是:為了保證函數的引用在函數的聲明之前,定義全局函數的custom節點和使用全局函數的custom節點需要在材質藍圖中存在前后關系。

可見,紅色箭頭所指的custom節點引用的全局函數,定義在名為Global的custom節點中,兩者通過multiply連接。

3. 定義struct

 1 struct Functions 
 2 {
 3     float plot(float2 st, float pct)
 4     {
 5       return  smoothstep( pct-0.02, pct, st.y) -
 6           smoothstep( pct, pct+0.02, st.y);
 7     }
 8 };
 9 
10 Functions f;
11 return f.plot();

custom代碼塊中不能方便的定義函數,但是使用以上這樣定義struct再實例化調用是可以的,方便在同一個custom代碼塊中組織邏輯


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM