Transform positions in a custom URP shader
Transform vertex, fragment, normal and tangent positions between coordinate spaces.
阅读时间2 分钟最后更新于 1 个月前
To transform positions in a custom Universal Render Pipeline (URP) shader, follow these steps:
- Add inside the
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"in your shader file. TheHLSLPROGRAMfile imports theCore.hlslfile.ShaderVariablesFunction.hlsl - Use one of the following methods from the file.
ShaderVariablesFunction.hlsl
Method | Syntax | Description |
|---|---|---|
| | Converts a position in clip space to screen space. |
| | Converts a position in object space to the normalized direction towards the viewer. |
| | Converts the normal of a vertex in object space to a tangent, bitangent, and normal in world space. You can also input both the normal and a |
| | Converts the position of a vertex in object space to positions in world space, view space, clip space, and normalized device coordinates. |
| | Returns the direction from a position in world space to the viewer, and normalizes the direction. |
| | Returns the direction from a position in world space to the viewer. |
Structs
VertexPositionInputs
Use the GetVertexPositionInputs method to get this struct.
Field | Description |
|---|---|
| The position in world space. |
| The position in view space. |
| The position in clip space. |
| The position as normalized device coordinates (NDC). |
VertexNormalInputs
Use the method to get this struct.
GetVertexNormalInputsField | Description |
|---|---|
| The tangent in world space. |
| The bitangent in world space. |
| The normal in world space. |
Example
The following URP shader draws object surfaces with colors that represent their position in screen space.
Shader "Custom/ScreenSpacePosition"{ SubShader { Tags { "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" } Pass { HLSLPROGRAM #pragma vertex vert #pragma fragment frag #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" struct Attributes { float4 positionOS : POSITION; float2 uv: TEXCOORD0; }; struct Varyings { float4 positionCS : SV_POSITION; float2 uv: TEXCOORD0; float3 positionWS : TEXCOORD2; }; Varyings vert(Attributes IN) { Varyings OUT; OUT.positionCS = TransformObjectToHClip(IN.positionOS.xyz); // Get the position of the vertex in different spaces VertexPositionInputs positions = GetVertexPositionInputs(IN.positionOS); // Set positionWS to the world space position of the vertex OUT.positionWS = positions.positionWS.xyz; return OUT; } half4 frag(Varyings IN) : SV_Target { // Set the fragment color to the world space position vector return float4(IN.positionWS.xy, 0, 1); } ENDHLSL } }}