InTerra_MeshTerrain.hlsl 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #define INTERRA_MESH_TERRAIN
  2. #include "InTerra_URP_DefinedGlobalKeywords.hlsl"
  3. #include "InTerra_Functions.hlsl"
  4. void MeshTerrain_float(float3 positionOS, float3 viewDirWS, float3 normalWS, out float3 vertexPos, out float3 normalOS, out float3 tangentViewDir)
  5. {
  6. float3 worldPos = (TransformObjectToWorld(positionOS));
  7. float2 hmUV = float2 ((worldPos.x - _TerrainPosition.x) * (1 / _TerrainSize.x), (worldPos.z - _TerrainPosition.z) * (1 / _TerrainSize.z));
  8. vertexPos = positionOS;
  9. if (_CheckHeight)
  10. {
  11. float hm = UnpackHeightmap(SAMPLE_TEXTURE2D_LOD(_TerrainHeightmapTexture, sampler_TerrainHeightmapTexture, hmUV, 0));
  12. float heightOffset = _TerrainPosition.y - (hm * -_TerrainHeightmapScale.y);
  13. float3 objVertPos = (TransformWorldToObject(float3(worldPos.x, heightOffset, worldPos.z)));
  14. vertexPos = TransformWorldToObject((float3(worldPos.x, heightOffset, worldPos.z)));
  15. }
  16. normalOS = normalWS;
  17. if (_NormalsFromHeightmap)
  18. {
  19. float2 ts = float2(_TerrainHeightmapTexture_TexelSize.x, _TerrainHeightmapTexture_TexelSize.y);
  20. float hsX = _TerrainHeightmapScale.w / _TerrainHeightmapScale.x;
  21. float hsZ = _TerrainHeightmapScale.w / _TerrainHeightmapScale.z;
  22. float height[4];
  23. float3 terrainNormal;
  24. height[0] = UnpackHeightmap(SAMPLE_TEXTURE2D_LOD(_TerrainHeightmapTexture, sampler_TerrainHeightmapTexture, hmUV + float2(ts * float2(0, -1)), 0)).r * hsZ;
  25. height[1] = UnpackHeightmap(SAMPLE_TEXTURE2D_LOD(_TerrainHeightmapTexture, sampler_TerrainHeightmapTexture, hmUV + float2(ts * float2(-1, 0)), 0)).r * hsX;
  26. height[2] = UnpackHeightmap(SAMPLE_TEXTURE2D_LOD(_TerrainHeightmapTexture, sampler_TerrainHeightmapTexture, hmUV + float2(ts * float2(1, 0)), 0)).r * hsX;
  27. height[3] = UnpackHeightmap(SAMPLE_TEXTURE2D_LOD(_TerrainHeightmapTexture, sampler_TerrainHeightmapTexture, hmUV + float2(ts * float2(0, 1)), 0)).r * hsZ;
  28. terrainNormal.x = height[1] - height[2];
  29. terrainNormal.z = height[0] - height[3];
  30. terrainNormal.y = 1;
  31. normalOS = (terrainNormal).xyz;
  32. }
  33. tangentViewDir = 0;
  34. #if defined (_TERRAIN_PARALLAX)
  35. half3 axisSign = normalWS < 0 ? -1 : 1;
  36. half3 tangentY = normalize(cross(normalWS.xyz, half3(1e-5f, 1e-5f, axisSign.y)));
  37. half3 bitangentY = normalize(cross(tangentY.xyz, normalWS.xyz)) * axisSign.y;
  38. half3x3 tbnY = half3x3(tangentY, bitangentY, normalWS);
  39. tangentViewDir = mul(tbnY, viewDirWS);
  40. #endif
  41. }