1 UNITY_INSTANCING_BUFFER_START(Terrain)
2 UNITY_DEFINE_INSTANCED_PROP(float4, _TerrainPatchInstanceData) // float4(xBase, yBase, skipScale, ~)
3 UNITY_INSTANCING_BUFFER_END(Terrain)
5 AttributesMesh ApplyMeshModification(AttributesMesh input)
7 #ifdef UNITY_INSTANCING_ENABLED
8 float2 patchVertex = input.positionOS.xy;
9 float4 instanceData = UNITY_ACCESS_INSTANCED_PROP(Terrain, _TerrainPatchInstanceData);
11 float2 sampleCoords = (patchVertex.xy + instanceData.xy) * instanceData.z; // (xy + float2(xBase,yBase)) * skipScale
12 float height = UnpackHeightmap(_TerrainHeightmapTexture.Load(int3(sampleCoords, 0)));
14 input.positionOS.xz = sampleCoords * _TerrainHeightmapScale.xz;
15 input.positionOS.y = height * _TerrainHeightmapScale.y;
17 #ifdef ATTRIBUTES_NEED_NORMAL
18 input.normalOS = _TerrainNormalmapTexture.Load(int3(sampleCoords, 0)).rgb * 2 - 1;
21 #if defined(VARYINGS_NEED_TEXCOORD0) || defined(VARYINGS_DS_NEED_TEXCOORD0)
22 #ifdef ENABLE_TERRAIN_PERPIXEL_NORMAL
23 input.uv0 = sampleCoords;
25 input.uv0 = sampleCoords * _TerrainHeightmapRecipSize.zw;
30 #ifdef ATTRIBUTES_NEED_TANGENT
31 // Consider a flat terrain.It should have tangent be(1, 0, 0) and bitangent be(0, 0, 1) as the UV of the terrain grid mesh is a scale of the world XZ position.
32 // In CreateWorldToTangent function(in SpaceTransform.hlsl), it is cross(normal, tangent) * sgn for the bitangent vector.
33 // It is not true in a left - handed coordinate system for the terrain bitangent, if we provide 1 as the tangent.w.It would produce(0, 0, -1) instead of(0, 0, 1).
34 // Also terrain's tangent calculation was wrong in a left handed system because I used `cross((0,0,1), terrainNormalOS)`. It points to the wrong direction as negative X.
35 // Therefore all the 4 xyzw components of the tangent needs to be flipped to correct the tangent frame.
36 // (See TerrainLitData.hlsl - GetSurfaceAndBuiltinData)
37 input.tangentOS.xyz = cross(input.normalOS, float3(0, 0, 1));
38 input.tangentOS.w = -1;
43 void ApplyVertexModification(AttributesMesh input, float3 normalWS, inout float3 positionWS, float4 time)