Input data into HLSL
Create a struct that declares shader variables and connects them to the vertex data of the mesh.
阅读时间2 分钟最后更新于 22 天前
To pass data into a custom shader in High-Level Shader Language (HLSL), create a that declares shader variables and connects them to the mesh vertex data.
structUse one of the following methods:
- Include a prebuilt vertex structure from Unity's shader library.
- Declare a custom vertex structure.
Include a prebuilt structure
Unity has a library of High-Level Shader Language (HLSL) shader files that contain prebuilt HLSL structures with common vertex inputs. For more information, refer to:
- Shader methods in URP and Convert custom shaders for URP compatibility
- Built-in HLSL structures in the Built-In Render Pipeline
Declare a custom structure
To declare a custom vertex structure, follow these steps:
- At the top of your , add a
HLSLPROGRAMthat declares a variable for each input you want to access from the mesh.struct - In each variable declaration, add a semantic that connects the variable to the mesh data. For more information about semantics, refer to Semantics in the Microsoft HLSL documentation.
For a list of semantics, refer to HLSL semantics reference.
For example:
Shader "VertexInputCustom" { SubShader { Pass { HLSLPROGRAM ... struct custom_vertex_input { // Declare a variable for the vertex position, and connect it to the mesh data using the POSITION semantic. float4 vertex : POSITION; // Declare a variable for the vertex normal, and connect it to the mesh data using the NORMAL semantic. float3 normal : NORMAL; }; ... v2f vert (custom_vertex_input v) { ... } ENDHLSL } }}
If a variable contains more components than the mesh data, the extra components are 0 for x, y, and z, and 1 for w. For example, if you declare a with , the value is (u, v, 0, 1).
float4TEXCOORD0Passing data from the vertex shader to the fragment shader
The data you pass from the vertex shader to the fragment shader, known as interpolators, has limits based on the target platform and GPU.
To minimize the number of interpolators you use, pack data into single variables. For example, combine two sets of UV coordinates into one variable, where x and y contain the first UV coordinate and z and w contain the second UV coordinate.
float2float4Add a custom buffer for uniform variables
DirectX groups all uniform variables into constant buffers. Rendering might be faster if you group uniform variables into separate constant buffers depending on how often they change.
To create a constant buffer, use the and Unity macros. For example:
CBUFFER_STARTCBUFFER_ENDCBUFFER_START(RarelyUpdatedVariables) float4 lightPosition;CBUFFER_ENDCBUFFER_START(FrequentlyUpdatedVariables) float4 colorTint;CBUFFER_END