Unity using shader for water effect but I need the normal and location of the shader triangle not the mesh - unity3d

I am working on a game and I bought a water shader, I am just to time strapped to learn it right now. I am making a game with water and ships. I need the ships to respond to the water shader vertex normal at the ray cast hit position. Frankly I just don't know what I am doing and I would appreciate any help.
Shader
Shader "StylizedWater/Mobile"
{
Properties
{
[HDR]_WaterColor("Water Color", Color) = (0.1176471,0.6348885,1,0)
[HDR]_WaterShallowColor("WaterShallowColor", Color) = (0.4191176,0.7596349,1,0)
_Wavetint("Wave tint", Range( -1 , 1)) = 0
[HDR]_RimColor("Rim Color", Color) = (1,1,1,0.5019608)
_NormalStrength("NormalStrength", Range( 0 , 1)) = 0.25
_Transparency("Transparency", Range( 0 , 1)) = 0.75
_Glossiness("Glossiness", Range( 0 , 1)) = 0.85
[Toggle]_Worldspacetiling("Worldspace tiling", Float) = 1
_NormalTiling("NormalTiling", Range( 0 , 1)) = 0.9
_EdgeFade("EdgeFade", Range( 0.01 , 3)) = 0.2448298
_RimSize("Rim Size", Range( 0 , 20)) = 5
_Rimfalloff("Rim falloff", Range( 0.1 , 50)) = 3
_Rimtiling("Rim tiling", Float) = 0.5
_FoamOpacity("FoamOpacity", Range( -1 , 1)) = 0.05
_FoamSpeed("FoamSpeed", Range( 0 , 1)) = 0.1
_FoamSize("FoamSize", Float) = 0
_FoamTiling("FoamTiling", Float) = 0.05
_Depth("Depth", Range( 0 , 100)) = 30
_Wavesspeed("Waves speed", Range( 0 , 10)) = 0.75
_WaveHeight("Wave Height", Range( 0 , 1)) = 0.5366272
_WaveFoam("Wave Foam", Range( 0 , 10)) = 0
_WaveSize("Wave Size", Range( 0 , 10)) = 0.1
_WaveDirection("WaveDirection", Vector) = (1,0,0,0)
[NoScaleOffset][Normal]_Normals("Normals", 2D) = "bump" {}
[NoScaleOffset]_Shadermap("Shadermap", 2D) = "black" {}
[Toggle(_USEINTERSECTIONFOAM_ON)] _UseIntersectionFoam("UseIntersectionFoam", Float) = 0
[Toggle]_ENABLE_VC("ENABLE_VC", Float) = 0
[Toggle(_LIGHTING_ON)] _LIGHTING("LIGHTING", Float) = 0
[Toggle]_Unlit("Unlit", Float) = 0
_Metallicness("Metallicness", Range( 0 , 1)) = 0
[Toggle(_NORMAL_MAP_ON)] _NORMAL_MAP("NORMAL_MAP", Float) = 0
[Toggle]_USE_VC_INTERSECTION("USE_VC_INTERSECTION", Float) = 0
[Toggle]_EnableDepthTexture("EnableDepthTexture", Float) = 1
[HideInInspector] __dirty( "", Int ) = 1
}
SubShader
{
Tags{ "RenderType" = "Transparent" "Queue" = "Transparent+0" "IgnoreProjector" = "True" "ForceNoShadowCasting" = "True" }
LOD 200
Cull Back
CGPROGRAM
#include "UnityPBSLighting.cginc"
#include "UnityShaderVariables.cginc"
#include "UnityCG.cginc"
#pragma target 3.0
#pragma multi_compile __ _LIGHTING_ON
#pragma multi_compile __ _NORMAL_MAP_ON
#pragma shader_feature _USEINTERSECTIONFOAM_ON
#pragma fragmentoption ARB_precision_hint_fastest
#pragma exclude_renderers xbox360 psp2 n3ds wiiu
#pragma surface surf StandardCustomLighting alpha:fade keepalpha noshadow nolightmap nodynlightmap nodirlightmap nometa noforwardadd vertex:vertexDataFunc
struct Input
{
float3 worldPos;
float4 screenPos;
float4 vertexColor : COLOR;
float2 vertexToFrag713;
float2 vertexToFrag714;
float3 worldRefl;
INTERNAL_DATA
float3 vertexToFrag746;
float3 worldNormal;
};
struct SurfaceOutputCustomLightingCustom
{
half3 Albedo;
half3 Normal;
half3 Emission;
half Metallic;
half Smoothness;
half Occlusion;
half Alpha;
Input SurfInput;
UnityGIInput GIData;
};
uniform sampler2D _Normals;
uniform sampler2D _Shadermap;
uniform half _WaveHeight;
uniform float _ENABLE_VC;
uniform float _Worldspacetiling;
uniform float _WaveSize;
uniform float _Wavesspeed;
uniform float4 _WaveDirection;
uniform float _EnableDepthTexture;
uniform sampler2D_float _CameraDepthTexture;
uniform half _EdgeFade;
uniform half _Transparency;
uniform float _Depth;
uniform half4 _WaterShallowColor;
uniform float4 _RimColor;
uniform float _USE_VC_INTERSECTION;
uniform half _Rimfalloff;
uniform float _Rimtiling;
uniform half _RimSize;
uniform float _NormalTiling;
uniform half _NormalStrength;
uniform half _Glossiness;
uniform float _Unlit;
uniform half4 _WaterColor;
uniform half _Wavetint;
uniform half _FoamOpacity;
uniform float _FoamTiling;
uniform float _FoamSpeed;
uniform half _FoamSize;
uniform float _WaveFoam;
uniform float _Metallicness;
void vertexDataFunc( inout appdata_full v, out Input o )
{
UNITY_INITIALIZE_OUTPUT( Input, o );
float3 ase_vertexNormal = v.normal.xyz;
float4 VertexColors729 = lerp(float4( 0,0,0,0 ),v.color,_ENABLE_VC);
float3 ase_worldPos = mul( unity_ObjectToWorld, v.vertex );
float2 Tiling21 = lerp(( -20.0 * v.texcoord.xy ),( (ase_worldPos).xz * float2( 0.1,0.1 ) ),_Worldspacetiling);
float2 appendResult500 = (float2(_WaveDirection.x , _WaveDirection.z));
float2 WaveSpeed40 = ( ( _Wavesspeed * _Time.x ) * appendResult500 );
float2 HeightmapUV581 = ( ( ( Tiling21 * _WaveSize ) * float2( 0.1,0.1 ) ) + ( WaveSpeed40 * float2( 0.5,0.5 ) ) );
float4 tex2DNode94 = tex2Dlod( _Shadermap, float4( HeightmapUV581, 0, 1.0) );
float temp_output_95_0 = ( saturate( ( _WaveHeight - (VertexColors729).b ) ) * tex2DNode94.g );
float3 Displacement100 = ( ase_vertexNormal * temp_output_95_0 );
v.vertex.xyz += Displacement100;
o.vertexToFrag713 = lerp(( -20.0 * v.texcoord.xy ),( (ase_worldPos).xz * float2( 0.1,0.1 ) ),_Worldspacetiling);
o.vertexToFrag714 = ( ( _Wavesspeed * _Time.x ) * appendResult500 );
#if defined(LIGHTMAP_ON) && ( UNITY_VERSION < 560 || ( defined(LIGHTMAP_SHADOW_MIXING) && !defined(SHADOWS_SHADOWMASK) && defined(SHADOWS_SCREEN) ) )//aselc
float4 ase_lightColor = 0;
#else //aselc
float4 ase_lightColor = _LightColor0;
#endif //aselc
o.vertexToFrag746 = ase_lightColor.rgb;
}
inline half4 LightingStandardCustomLighting( inout SurfaceOutputCustomLightingCustom s, half3 viewDir, UnityGI gi )
{
UnityGIInput data = s.GIData;
Input i = s.SurfInput;
half4 c = 0;
//Start - Stylized Water custom depth
float4 ase_screenPos = float4( i.screenPos.xyz , i.screenPos.w + 0.00000000001 );
float4 ase_screenPosNorm = ase_screenPos / ase_screenPos.w;
ase_screenPosNorm.z = ( UNITY_NEAR_CLIP_VALUE >= 0 ) ? ase_screenPosNorm.z : ase_screenPosNorm.z * 0.5 + 0.5;
float screenDepth795 = LinearEyeDepth(UNITY_SAMPLE_DEPTH(tex2Dproj(_CameraDepthTexture,UNITY_PROJ_COORD(ase_screenPos))));
float distanceDepth795 = ( screenDepth795 - LinearEyeDepth( ase_screenPosNorm.z ) ) / ( lerp( 1.0 , ( 1.0 / _ProjectionParams.z ) , unity_OrthoParams.w) );
#if SHADER_API_MOBILE && UNITY_VERSION >= 20183 //Build only, abs() function causes offset in depth on mobile in 2018.3
#else
distanceDepth795 = abs(distanceDepth795);
#endif
//End - Stylized Water custom depth
float DepthTexture494 = distanceDepth795;
float ColorDepth479 = lerp(1.0,saturate( ( DepthTexture494 / _Depth ) ),_EnableDepthTexture);
float4 VertexColors729 = lerp(float4( 0,0,0,0 ),i.vertexColor,_ENABLE_VC);
float2 Tiling21 = i.vertexToFrag713;
float2 temp_output_24_0 = ( Tiling21 * _Rimtiling );
float2 WaveSpeed40 = i.vertexToFrag714;
float temp_output_30_0 = ( tex2D( _Shadermap, ( ( 0.5 * temp_output_24_0 ) + WaveSpeed40 ) ).b * tex2D( _Shadermap, ( temp_output_24_0 + ( 1.0 - WaveSpeed40 ) ) ).b );
float Intersection42 = saturate( ( _RimColor.a * ( 1.0 - ( ( ( lerp(lerp(1.0,DepthTexture494,_EnableDepthTexture),( 1.0 - (VertexColors729).r ),_USE_VC_INTERSECTION) / _Rimfalloff ) * temp_output_30_0 ) + ( lerp(lerp(1.0,DepthTexture494,_EnableDepthTexture),( 1.0 - (VertexColors729).r ),_USE_VC_INTERSECTION) / _RimSize ) ) ) ) );
float Opacity121 = saturate( ( ( lerp(1.0,saturate( ( DepthTexture494 / _EdgeFade ) ),_EnableDepthTexture) * saturate( ( ( _Transparency * saturate( ( ColorDepth479 + _WaterShallowColor.a ) ) ) + Intersection42 ) ) ) - (VertexColors729).g ) );
float3 ase_worldPos = i.worldPos;
#if defined(LIGHTMAP_ON) && UNITY_VERSION < 560 //aseld
float3 ase_worldlightDir = 0;
#else //aseld
float3 ase_worldlightDir = normalize( UnityWorldSpaceLightDir( ase_worldPos ) );
#endif //aseld
half3 _BlankNormal = half3(0,0,1);
float2 temp_output_705_0 = ( _NormalTiling * Tiling21 );
#ifdef _NORMAL_MAP_ON
float2 staticSwitch760 = ( ( float2( 0.25,0.25 ) * temp_output_705_0 ) + WaveSpeed40 );
#else
float2 staticSwitch760 = float2( 0,0 );
#endif
#ifdef _NORMAL_MAP_ON
float2 staticSwitch761 = ( temp_output_705_0 + ( 1.0 - WaveSpeed40 ) );
#else
float2 staticSwitch761 = float2( 0,0 );
#endif
#ifdef _NORMAL_MAP_ON
float3 staticSwitch763 = ( ( UnpackNormal( tex2D( _Normals, staticSwitch760 ) ) + UnpackNormal( tex2D( _Normals, staticSwitch761 ) ) ) / float3( 2,2,2 ) );
#else
float3 staticSwitch763 = _BlankNormal;
#endif
float3 lerpResult621 = lerp( _BlankNormal , staticSwitch763 , _NormalStrength);
float3 NormalMap52 = lerpResult621;
float dotResult741 = dot( ase_worldlightDir , normalize( WorldReflectionVector( i , NormalMap52 ) ) );
float GlossParam754 = _Glossiness;
float3 lerpResult478 = lerp( (_WaterShallowColor).rgb , (_WaterColor).rgb , ColorDepth479);
float3 WaterColor350 = lerpResult478;
float2 HeightmapUV581 = ( ( ( Tiling21 * _WaveSize ) * float2( 0.1,0.1 ) ) + ( WaveSpeed40 * float2( 0.5,0.5 ) ) );
float4 tex2DNode94 = tex2D( _Shadermap, HeightmapUV581 );
float Heightmap99 = tex2DNode94.g;
float3 temp_cast_0 = (( Heightmap99 * _Wavetint )).xxx;
float3 RimColor102 = (_RimColor).rgb;
float3 lerpResult61 = lerp( ( WaterColor350 - temp_cast_0 ) , ( RimColor102 * 3.0 ) , Intersection42);
float2 temp_output_634_0 = ( WaveSpeed40 * _FoamSpeed );
float4 tex2DNode67 = tex2D( _Shadermap, ( ( _FoamTiling * Tiling21 ) + temp_output_634_0 + ( Heightmap99 * 0.1 ) ) );
#ifdef _USEINTERSECTIONFOAM_ON
float staticSwitch725 = ( 1.0 - tex2DNode67.b );
#else
float staticSwitch725 = saturate( ( 1000.0 * ( ( tex2D( _Shadermap, ( ( _FoamTiling * ( Tiling21 * float2( 0.5,0.5 ) ) ) + temp_output_634_0 ) ).r - tex2DNode67.r ) - _FoamSize ) ) );
#endif
float Foam73 = ( _FoamOpacity * staticSwitch725 );
float3 temp_cast_1 = (2.0).xxx;
float FoamTex244 = staticSwitch725;
float WaveFoam221 = saturate( ( pow( ( tex2DNode94.g * _WaveFoam ) , 2.0 ) * FoamTex244 ) );
float3 lerpResult223 = lerp( ( lerpResult61 + Foam73 ) , temp_cast_1 , WaveFoam221);
float3 FinalColor114 = lerpResult223;
#ifdef _LIGHTING_ON
float3 staticSwitch769 = float3( 0,0,0 );
#else
float3 staticSwitch769 = ( saturate( ( pow( max( 0.0 , dotResult741 ) , ( GlossParam754 * 128.0 ) ) * GlossParam754 ) ) + lerp(( i.vertexToFrag746 * FinalColor114 ),FinalColor114,_Unlit) );
#endif
float3 CustomLighting753 = staticSwitch769;
SurfaceOutputStandard s733 = (SurfaceOutputStandard ) 0;
s733.Albedo = FinalColor114;
s733.Normal = WorldNormalVector( i , NormalMap52 );
s733.Emission = float3( 0,0,0 );
s733.Metallic = _Metallicness;
s733.Smoothness = GlossParam754;
s733.Occlusion = 1.0;
data.light = gi.light;
UnityGI gi733 = gi;
#ifdef UNITY_PASS_FORWARDBASE
Unity_GlossyEnvironmentData g733 = UnityGlossyEnvironmentSetup( s733.Smoothness, data.worldViewDir, s733.Normal, float3(0,0,0));
gi733 = UnityGlobalIllumination( data, s733.Occlusion, s733.Normal, g733 );
#endif
float3 surfResult733 = LightingStandard ( s733, viewDir, gi733 ).rgb;
surfResult733 += s733.Emission;
#ifdef UNITY_PASS_FORWARDADD//733
surfResult733 -= s733.Emission;
#endif//733
#ifdef _LIGHTING_ON
float3 staticSwitch734 = surfResult733;
#else
float3 staticSwitch734 = CustomLighting753;
#endif
c.rgb = staticSwitch734;
c.a = Opacity121;
return c;
}
inline void LightingStandardCustomLighting_GI( inout SurfaceOutputCustomLightingCustom s, UnityGIInput data, inout UnityGI gi )
{
s.GIData = data;
}
void surf( Input i , inout SurfaceOutputCustomLightingCustom o )
{
o.SurfInput = i;
o.Normal = float3(0,0,1);
}
ENDCG
}
}
My Code
private void FixedUpdate()
{
RaycastHit hit;
LayerMask mask = LayerMask.GetMask("ignore");
Physics.Raycast(transform.position, Vector3.down, out hit, Mathf.Infinity, mask);
MeshCollider meshCollider = hit.collider as MeshCollider;
if (!(meshCollider == null || meshCollider.sharedMesh == null))
{
Mesh mesh = meshCollider.sharedMesh;
mesh.RecalculateNormals();
Vector3[] normals = mesh.normals;
int[] triangles = mesh.triangles;
// Extract local space normals of the triangle we hit
Vector3 n0 = normals[triangles[hit.triangleIndex * 3 + 0]];
Vector3 n1 = normals[triangles[hit.triangleIndex * 3 + 1]];
Vector3 n2 = normals[triangles[hit.triangleIndex * 3 + 2]];
// interpolate using the barycentric coordinate of the hitpoint
Vector3 baryCenter = hit.barycentricCoordinate;
// Use barycentric coordinate to interpolate normal
Vector3 interpolatedNormal = n0 * baryCenter.x + n1 * baryCenter.y + n2 * baryCenter.z;
// normalize the interpolated normal
interpolatedNormal = interpolatedNormal.normalized;
// Transform local space normals to world space
Transform hitTransform = hit.collider.transform;
interpolatedNormal = hitTransform.TransformDirection(interpolatedNormal);
// Display with Debug.DrawLine
Debug.DrawRay(gameObject.transform.position, interpolatedNormal * 10f, Color.black);
}
//0-1 on max speed
currentShipScalar = ((shipSpeed - (shipSpeed - Body.velocity.magnitude)) / (shipSpeed));
this only returns the mesh normal not the shader. I used this enter link description here
and this enter link description here
as my code source. I feel dumb I am just exhausted. I don't like that I have not yet understood whats going on but I have a dead line of one week. any help would be apreciated.

The asset you are using is just a shader. Changes in the vertex position inside a shader are just on the GPU and can not be accessed by the CPU. The asset also states, it does not support Buoyancy, so it really just is a visual thing.
To be able to access the wave distortion you either need to have a compute shader or some other preprocessing step that calculates your changes for you, which are used afterwards inside you wave shader.
More information on the same problem
Might be worth taking a look at another solution (maybe the boat attack repo would be a good fit), but I don't know your target device and scope of the project (I guess you're on builtin renderer right now).

Related

Unity TextMeshPro with Fog URP

Im using TextMeshPro and fog in my game scene (URP) but texts are not affecting by the fog.
I changed 'Fog { Mode Off }' to 'Fog { Mode Global }' inside shader TextMeshPro/DistanceFieldFog that I duplicated from the original for texts but it didnt work. Do you guys know how to make texts affected by the fog?
My shader looks like:
Shader "TextMeshPro/Distance Field Fog" {
Properties {
_FaceTex ("Face Texture", 2D) = "white" {}
_FaceUVSpeedX ("Face UV Speed X", Range(-5, 5)) = 0.0
_FaceUVSpeedY ("Face UV Speed Y", Range(-5, 5)) = 0.0
[HDR]_FaceColor ("Face Color", Color) = (1,1,1,1)
_FaceDilate ("Face Dilate", Range(-1,1)) = 0
[HDR]_OutlineColor ("Outline Color", Color) = (0,0,0,1)
_OutlineTex ("Outline Texture", 2D) = "white" {}
_OutlineUVSpeedX ("Outline UV Speed X", Range(-5, 5)) = 0.0
_OutlineUVSpeedY ("Outline UV Speed Y", Range(-5, 5)) = 0.0
_OutlineWidth ("Outline Thickness", Range(0, 1)) = 0
_OutlineSoftness ("Outline Softness", Range(0,1)) = 0
_Bevel ("Bevel", Range(0,1)) = 0.5
_BevelOffset ("Bevel Offset", Range(-0.5,0.5)) = 0
_BevelWidth ("Bevel Width", Range(-.5,0.5)) = 0
_BevelClamp ("Bevel Clamp", Range(0,1)) = 0
_BevelRoundness ("Bevel Roundness", Range(0,1)) = 0
_LightAngle ("Light Angle", Range(0.0, 6.2831853)) = 3.1416
[HDR]_SpecularColor ("Specular", Color) = (1,1,1,1)
_SpecularPower ("Specular", Range(0,4)) = 2.0
_Reflectivity ("Reflectivity", Range(5.0,15.0)) = 10
_Diffuse ("Diffuse", Range(0,1)) = 0.5
_Ambient ("Ambient", Range(1,0)) = 0.5
_BumpMap ("Normal map", 2D) = "bump" {}
_BumpOutline ("Bump Outline", Range(0,1)) = 0
_BumpFace ("Bump Face", Range(0,1)) = 0
_ReflectFaceColor ("Reflection Color", Color) = (0,0,0,1)
_ReflectOutlineColor("Reflection Color", Color) = (0,0,0,1)
_Cube ("Reflection Cubemap", Cube) = "black" { /* TexGen CubeReflect */ }
_EnvMatrixRotation ("Texture Rotation", vector) = (0, 0, 0, 0)
[HDR]_UnderlayColor ("Border Color", Color) = (0,0,0, 0.5)
_UnderlayOffsetX ("Border OffsetX", Range(-1,1)) = 0
_UnderlayOffsetY ("Border OffsetY", Range(-1,1)) = 0
_UnderlayDilate ("Border Dilate", Range(-1,1)) = 0
_UnderlaySoftness ("Border Softness", Range(0,1)) = 0
[HDR]_GlowColor ("Color", Color) = (0, 1, 0, 0.5)
_GlowOffset ("Offset", Range(-1,1)) = 0
_GlowInner ("Inner", Range(0,1)) = 0.05
_GlowOuter ("Outer", Range(0,1)) = 0.05
_GlowPower ("Falloff", Range(1, 0)) = 0.75
_WeightNormal ("Weight Normal", float) = 0
_WeightBold ("Weight Bold", float) = 0.5
_ShaderFlags ("Flags", float) = 0
_ScaleRatioA ("Scale RatioA", float) = 1
_ScaleRatioB ("Scale RatioB", float) = 1
_ScaleRatioC ("Scale RatioC", float) = 1
_MainTex ("Font Atlas", 2D) = "white" {}
_TextureWidth ("Texture Width", float) = 512
_TextureHeight ("Texture Height", float) = 512
_GradientScale ("Gradient Scale", float) = 5.0
_ScaleX ("Scale X", float) = 1.0
_ScaleY ("Scale Y", float) = 1.0
_PerspectiveFilter ("Perspective Correction", Range(0, 1)) = 0.875
_Sharpness ("Sharpness", Range(-1,1)) = 0
_VertexOffsetX ("Vertex OffsetX", float) = 0
_VertexOffsetY ("Vertex OffsetY", float) = 0
_MaskCoord ("Mask Coordinates", vector) = (0, 0, 32767, 32767)
_ClipRect ("Clip Rect", vector) = (-32767, -32767, 32767, 32767)
_MaskSoftnessX ("Mask SoftnessX", float) = 0
_MaskSoftnessY ("Mask SoftnessY", float) = 0
_StencilComp ("Stencil Comparison", Float) = 8
_Stencil ("Stencil ID", Float) = 0
_StencilOp ("Stencil Operation", Float) = 0
_StencilWriteMask ("Stencil Write Mask", Float) = 255
_StencilReadMask ("Stencil Read Mask", Float) = 255
_CullMode ("Cull Mode", Float) = 0
_ColorMask ("Color Mask", Float) = 15
}
SubShader {
Tags
{
"Queue"="Transparent"
"IgnoreProjector"="True"
"RenderType"="Transparent"
}
Stencil
{
Ref [_Stencil]
Comp [_StencilComp]
Pass [_StencilOp]
ReadMask [_StencilReadMask]
WriteMask [_StencilWriteMask]
}
Cull [_CullMode]
ZWrite Off
Lighting Off
Fog { Mode Global }
ZTest [unity_GUIZTestMode]
Blend One OneMinusSrcAlpha
ColorMask [_ColorMask]
Pass {
CGPROGRAM
#pragma target 3.0
#pragma vertex VertShader
#pragma fragment PixShader
#pragma shader_feature __ BEVEL_ON
#pragma shader_feature __ UNDERLAY_ON UNDERLAY_INNER
#pragma shader_feature __ GLOW_ON
#pragma multi_compile __ UNITY_UI_CLIP_RECT
#pragma multi_compile __ UNITY_UI_ALPHACLIP
#include "UnityCG.cginc"
#include "UnityUI.cginc"
#include "TMPro_Properties.cginc"
#include "TMPro.cginc"
struct vertex_t {
UNITY_VERTEX_INPUT_INSTANCE_ID
float4 position : POSITION;
float3 normal : NORMAL;
fixed4 color : COLOR;
float2 texcoord0 : TEXCOORD0;
float2 texcoord1 : TEXCOORD1;
};
struct pixel_t {
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
float4 position : SV_POSITION;
fixed4 color : COLOR;
float2 atlas : TEXCOORD0; // Atlas
float4 param : TEXCOORD1; // alphaClip, scale, bias, weight
float4 mask : TEXCOORD2; // Position in object space(xy), pixel Size(zw)
float3 viewDir : TEXCOORD3;
#if (UNDERLAY_ON || UNDERLAY_INNER)
float4 texcoord2 : TEXCOORD4; // u,v, scale, bias
fixed4 underlayColor : COLOR1;
#endif
float4 textures : TEXCOORD5;
};
// Used by Unity internally to handle Texture Tiling and Offset.
float4 _FaceTex_ST;
float4 _OutlineTex_ST;
pixel_t VertShader(vertex_t input)
{
pixel_t output;
UNITY_INITIALIZE_OUTPUT(pixel_t, output);
UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input,output);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
float bold = step(input.texcoord1.y, 0);
float4 vert = input.position;
vert.x += _VertexOffsetX;
vert.y += _VertexOffsetY;
float4 vPosition = UnityObjectToClipPos(vert);
float2 pixelSize = vPosition.w;
pixelSize /= float2(_ScaleX, _ScaleY) * abs(mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy));
float scale = rsqrt(dot(pixelSize, pixelSize));
scale *= abs(input.texcoord1.y) * _GradientScale * (_Sharpness + 1);
if (UNITY_MATRIX_P[3][3] == 0) scale = lerp(abs(scale) * (1 - _PerspectiveFilter), scale, abs(dot(UnityObjectToWorldNormal(input.normal.xyz), normalize(WorldSpaceViewDir(vert)))));
float weight = lerp(_WeightNormal, _WeightBold, bold) / 4.0;
weight = (weight + _FaceDilate) * _ScaleRatioA * 0.5;
float bias =(.5 - weight) + (.5 / scale);
float alphaClip = (1.0 - _OutlineWidth * _ScaleRatioA - _OutlineSoftness * _ScaleRatioA);
#if GLOW_ON
alphaClip = min(alphaClip, 1.0 - _GlowOffset * _ScaleRatioB - _GlowOuter * _ScaleRatioB);
#endif
alphaClip = alphaClip / 2.0 - ( .5 / scale) - weight;
#if (UNDERLAY_ON || UNDERLAY_INNER)
float4 underlayColor = _UnderlayColor;
underlayColor.rgb *= underlayColor.a;
float bScale = scale;
bScale /= 1 + ((_UnderlaySoftness*_ScaleRatioC) * bScale);
float bBias = (0.5 - weight) * bScale - 0.5 - ((_UnderlayDilate * _ScaleRatioC) * 0.5 * bScale);
float x = -(_UnderlayOffsetX * _ScaleRatioC) * _GradientScale / _TextureWidth;
float y = -(_UnderlayOffsetY * _ScaleRatioC) * _GradientScale / _TextureHeight;
float2 bOffset = float2(x, y);
#endif
// Generate UV for the Masking Texture
float4 clampedRect = clamp(_ClipRect, -2e10, 2e10);
float2 maskUV = (vert.xy - clampedRect.xy) / (clampedRect.zw - clampedRect.xy);
// Support for texture tiling and offset
float2 textureUV = UnpackUV(input.texcoord1.x);
float2 faceUV = TRANSFORM_TEX(textureUV, _FaceTex);
float2 outlineUV = TRANSFORM_TEX(textureUV, _OutlineTex);
output.position = vPosition;
output.color = input.color;
output.atlas = input.texcoord0;
output.param = float4(alphaClip, scale, bias, weight);
output.mask = half4(vert.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * half2(_MaskSoftnessX, _MaskSoftnessY) + pixelSize.xy));
output.viewDir = mul((float3x3)_EnvMatrix, _WorldSpaceCameraPos.xyz - mul(unity_ObjectToWorld, vert).xyz);
#if (UNDERLAY_ON || UNDERLAY_INNER)
output.texcoord2 = float4(input.texcoord0 + bOffset, bScale, bBias);
output.underlayColor = underlayColor;
#endif
output.textures = float4(faceUV, outlineUV);
return output;
}
fixed4 PixShader(pixel_t input) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(input);
float c = tex2D(_MainTex, input.atlas).a;
#ifndef UNDERLAY_ON
clip(c - input.param.x);
#endif
float scale = input.param.y;
float bias = input.param.z;
float weight = input.param.w;
float sd = (bias - c) * scale;
float outline = (_OutlineWidth * _ScaleRatioA) * scale;
float softness = (_OutlineSoftness * _ScaleRatioA) * scale;
half4 faceColor = _FaceColor;
half4 outlineColor = _OutlineColor;
faceColor.rgb *= input.color.rgb;
faceColor *= tex2D(_FaceTex, input.textures.xy + float2(_FaceUVSpeedX, _FaceUVSpeedY) * _Time.y);
outlineColor *= tex2D(_OutlineTex, input.textures.zw + float2(_OutlineUVSpeedX, _OutlineUVSpeedY) * _Time.y);
faceColor = GetColor(sd, faceColor, outlineColor, outline, softness);
#if BEVEL_ON
float3 dxy = float3(0.5 / _TextureWidth, 0.5 / _TextureHeight, 0);
float3 n = GetSurfaceNormal(input.atlas, weight, dxy);
float3 bump = UnpackNormal(tex2D(_BumpMap, input.textures.xy + float2(_FaceUVSpeedX, _FaceUVSpeedY) * _Time.y)).xyz;
bump *= lerp(_BumpFace, _BumpOutline, saturate(sd + outline * 0.5));
n = normalize(n- bump);
float3 light = normalize(float3(sin(_LightAngle), cos(_LightAngle), -1.0));
float3 col = GetSpecular(n, light);
faceColor.rgb += col*faceColor.a;
faceColor.rgb *= 1-(dot(n, light)*_Diffuse);
faceColor.rgb *= lerp(_Ambient, 1, n.z*n.z);
fixed4 reflcol = texCUBE(_Cube, reflect(input.viewDir, -n));
faceColor.rgb += reflcol.rgb * lerp(_ReflectFaceColor.rgb, _ReflectOutlineColor.rgb, saturate(sd + outline * 0.5)) * faceColor.a;
#endif
#if UNDERLAY_ON
float d = tex2D(_MainTex, input.texcoord2.xy).a * input.texcoord2.z;
faceColor += input.underlayColor * saturate(d - input.texcoord2.w) * (1 - faceColor.a);
#endif
#if UNDERLAY_INNER
float d = tex2D(_MainTex, input.texcoord2.xy).a * input.texcoord2.z;
faceColor += input.underlayColor * (1 - saturate(d - input.texcoord2.w)) * saturate(1 - sd) * (1 - faceColor.a);
#endif
#if GLOW_ON
float4 glowColor = GetGlowColor(sd, scale);
faceColor.rgb += glowColor.rgb * glowColor.a;
#endif
// Alternative implementation to UnityGet2DClipping with support for softness.
#if UNITY_UI_CLIP_RECT
half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(input.mask.xy)) * input.mask.zw);
faceColor *= m.x * m.y;
#endif
#if UNITY_UI_ALPHACLIP
clip(faceColor.a - 0.001);
#endif
return faceColor * input.color.a;
}
ENDCG
}
}
Fallback "TextMeshPro/Mobile/Distance Field"
CustomEditor "TMPro.EditorUtilities.TMP_SDFShaderGUI"
}

How to design a shader in Unity so it uses directions from the camera

I have found a few unique shaders from Shadertoy which I would like to impart an experience of 'sky' within models of buildings in Unity AR.
An example might be this one: https://www.shadertoy.com/view/4tdSWr which is just the sky looking up, or this one, https://www.shadertoy.com/view/4tdSWr which has some directional input from the mouse (click and drag) - the HLSL/unity version of this code except for changes to mouse input is at the end of this post.
Right now the clouds feel more like a green screen projection on the model, so there is no implication of direction or horizon if you are looking parallel to the plane the building is on. (ie, if I am standing with the clouds moving from right to left, as I turn left they don't appear to be moving from behind me and receding into the distance)
I have been trying to understand how to use the camera to 'rotate' the shader result so the direction of the camera is used to ensure the direction of the clouds movement. I would also like to use the angle of the camera with respect to the ground plane to impart a horizon when you are looking out towards the walls.
Any insight on how to do this would be great, especially if it is more than just a 'use _WorldSpaceCameraPos' or 'just add UNITY_MATRIX_MVP' as the results I found through excessive googling haven't really been that helpful so far.
The code for the second shader linked, adjusted for HLSL/Unity except for the mouse inputs is at the end of this post.
Shader "Unlit/skybox"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
iChannel0 ("noise-image", 2D) = "noise-image.png" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
sampler2D iChannel0;
float4 _MainTex_ST;
float random(in float2 uv)
{
return tex2D(iChannel0, uv / 64.).r;
}
float noise(in float2 uv)
{
float2 i = floor(uv);
float2 f = frac(uv);
f = f * f * (3. - 2. * f);
float lb = random(i + float2(0., 0.));
float rb = random(i + float2(1., 0.));
float lt = random(i + float2(0., 1.));
float rt = random(i + float2(1., 1.));
return lerp(lerp(lb, rb, f.x),
lerp(lt, rt, f.x), f.y);
}
#define OCTAVES 8
float fbm(in float2 uv)
{
float value = 0.;
float amplitude = .5;
for (int i = 0; i < OCTAVES; i++)
{
value += noise(uv) * amplitude;
amplitude *= .5;
uv *= 2.;
}
return value;
}
float3 Sky(in float3 ro, in float3 rd)
{
const float SC = 1e5;
// Calculate sky plane
float dist = (SC - ro.y) / rd.y;
float2 p = (ro + dist * rd).xz;
p *= 1.2 / SC;
// from iq's shader, https://www.shadertoy.com/view/MdX3Rr
float3 lightDir = normalize(float3(-.8, .15, -.3));
float sundot = clamp(dot(rd, lightDir), 0.0, 1.0);
float3 cloudCol = float3(1.,1.0,1.0);
//float3 skyCol = float3(.6, .71, .85) - rd.y * .2 * float3(1., .5, 1.) + .15 * .5;
float3 skyCol = float3(0.3,0.5,0.85) - rd.y*rd.y*0.5;
skyCol = lerp( skyCol, mul(0.85, float3(0.7,0.75,0.85)), pow( 1.0 - max(rd.y, 0.0), 4.0 ) );
// sun
float3 sun = mul(mul(0.25 , float3(1.0,0.7,0.4)) , pow( sundot,5.0 ));
sun += mul(mul(0.25 , float3(1.0,0.8,0.6)) , pow( sundot,64.0 ));
sun += mul(mul(0.2 , float3(1.0,0.8,0.6)) , pow( sundot,512.0 ));
skyCol += sun;
// clouds
float t = mul(_Time.y , 0.1);
float den = fbm(float2(p.x - t, p.y - t));
skyCol = lerp( skyCol, cloudCol, smoothstep(.4, .8, den));
// horizon
skyCol = lerp( skyCol, mul(0.68 , float3(.418, .394, .372)), pow( 1.0 - max(rd.y, 0.0), 16.0 ) );
return skyCol;
}
float3x3 setCamera( in float3 ro, in float3 ta, float cr )
{
float3 cw = normalize(ta-ro);
float3 cp = float3(sin(cr), cos(cr),0.0);
float3 cu = normalize( cross(cw,cp) );
float3 cv = normalize( cross(cu,cw) );
return float3x3( cu, cv, cw );
}
void mainImage( out float4 fragColor, in float2 fragCoord )
{
float2 uv = fragCoord.xy / _ScreenParams.xy;
uv -= 0.5;
uv.x *= _ScreenParams.x / _ScreenParams.y;
float2 mouse = iMouse.xy/_ScreenParams.xy;
float3 ro = float3(0.0, 0.0, 0.0);
float3 ta = float3(cos(mul(mouse.x , 6.28)), mul(mouse.y , 2.0), sin(mul(mouse.x , 6.28)));
float3x3 cam = setCamera(ro, ta, 0.0);
float3 rd = normalize(mul(cam , float3(uv, 1.0)));
float3 col = Sky(ro, rd);
fragColor = float4(float3(col),1.0);
}
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// sample the texture
fixed4 col = tex2D(_MainTex, i.uv);
// apply fog
UNITY_APPLY_FOG(i.fogCoord, col);
return col;
}
ENDCG
}
}
}

Making TMPro shader compatible with LWRP

In my unity Project, here is the code for TMpro shader:
Shader "TextMeshPro/Distance Field" {
Properties {
_FaceTex ("Face Texture", 2D) = "white" {}
_FaceUVSpeedX ("Face UV Speed X", Range(-5, 5)) = 0.0
_FaceUVSpeedY ("Face UV Speed Y", Range(-5, 5)) = 0.0
_FaceColor ("Face Color", Color) = (1,1,1,1)
_FaceDilate ("Face Dilate", Range(-1,1)) = 0
_OutlineColor ("Outline Color", Color) = (0,0,0,1)
_OutlineTex ("Outline Texture", 2D) = "white" {}
_OutlineUVSpeedX ("Outline UV Speed X", Range(-5, 5)) = 0.0
_OutlineUVSpeedY ("Outline UV Speed Y", Range(-5, 5)) = 0.0
_OutlineWidth ("Outline Thickness", Range(0, 1)) = 0
_OutlineSoftness ("Outline Softness", Range(-1,1)) = 0
_Bevel ("Bevel", Range(0,1)) = 0.5
_BevelOffset ("Bevel Offset", Range(-0.5,0.5)) = 0
_BevelWidth ("Bevel Width", Range(-.5,0.5)) = 0
_BevelClamp ("Bevel Clamp", Range(0,1)) = 0
_BevelRoundness ("Bevel Roundness", Range(0,1)) = 0
_LightAngle ("Light Angle", Range(0.0, 6.2831853)) = 3.1416
_SpecularColor ("Specular", Color) = (1,1,1,1)
_SpecularPower ("Specular", Range(0,4)) = 2.0
_Reflectivity ("Reflectivity", Range(5.0,15.0)) = 10
_Diffuse ("Diffuse", Range(0,1)) = 0.5
_Ambient ("Ambient", Range(1,0)) = 0.5
_BumpMap ("Normal map", 2D) = "bump" {}
_BumpOutline ("Bump Outline", Range(0,1)) = 0
_BumpFace ("Bump Face", Range(0,1)) = 0
_ReflectFaceColor ("Reflection Color", Color) = (0,0,0,1)
_ReflectOutlineColor("Reflection Color", Color) = (0,0,0,1)
_Cube ("Reflection Cubemap", Cube) = "black" { /* TexGen CubeReflect */ }
_EnvMatrixRotation ("Texture Rotation", vector) = (0, 0, 0, 0)
_UnderlayColor ("Border Color", Color) = (0,0,0, 0.5)
_UnderlayOffsetX ("Border OffsetX", Range(-1,1)) = 0
_UnderlayOffsetY ("Border OffsetY", Range(-1,1)) = 0
_UnderlayDilate ("Border Dilate", Range(-1,1)) = 0
_UnderlaySoftness ("Border Softness", Range(0,1)) = 0
_GlowColor ("Color", Color) = (0, 1, 0, 0.5)
_GlowOffset ("Offset", Range(-1,1)) = 0
_GlowInner ("Inner", Range(0,1)) = 0.05
_GlowOuter ("Outer", Range(0,1)) = 0.05
_GlowPower ("Falloff", Range(1, 0)) = 0.75
_WeightNormal ("Weight Normal", float) = 0
_WeightBold ("Weight Bold", float) = 0.5
_ShaderFlags ("Flags", float) = 0
_ScaleRatioA ("Scale RatioA", float) = 1
_ScaleRatioB ("Scale RatioB", float) = 1
_ScaleRatioC ("Scale RatioC", float) = 1
_MainTex ("Font Atlas", 2D) = "white" {}
_TextureWidth ("Texture Width", float) = 512
_TextureHeight ("Texture Height", float) = 512
_GradientScale ("Gradient Scale", float) = 5.0
_ScaleX ("Scale X", float) = 1.0
_ScaleY ("Scale Y", float) = 1.0
_PerspectiveFilter ("Perspective Correction", Range(0, 1)) = 0.875
_VertexOffsetX ("Vertex OffsetX", float) = 0
_VertexOffsetY ("Vertex OffsetY", float) = 0
_MaskCoord ("Mask Coordinates", vector) = (0, 0, 32767, 32767)
_ClipRect ("Clip Rect", vector) = (-32767, -32767, 32767, 32767)
_MaskSoftnessX ("Mask SoftnessX", float) = 0
_MaskSoftnessY ("Mask SoftnessY", float) = 0
_StencilComp ("Stencil Comparison", Float) = 8
_Stencil ("Stencil ID", Float) = 0
_StencilOp ("Stencil Operation", Float) = 0
_StencilWriteMask ("Stencil Write Mask", Float) = 255
_StencilReadMask ("Stencil Read Mask", Float) = 255
_ColorMask ("Color Mask", Float) = 15
}
HLSLINCLUDE
#include "Packages/com.unity.render-pipelines.lightweight/ShaderLibrary/Core.hlsl"
ENDHLSL
SubShader {
Tags {"Queue" = "Transparent" "RenderType" = "Transparent" "RenderPipeline" = "LightweightPipeline" }
Blend SrcAlpha OneMinusSrcAlpha
Cull Off
ZWrite Off
Stencil
{
Ref [_Stencil]
Comp [_StencilComp]
Pass [_StencilOp]
ReadMask [_StencilReadMask]
WriteMask [_StencilWriteMask]
}
Cull [_CullMode]
ZWrite Off
Lighting Off
Fog { Mode Off }
ZTest [unity_GUIZTestMode]
Blend One OneMinusSrcAlpha
ColorMask [_ColorMask]
Pass {
Tags { "LightMode" = "Lightweight2D" }
CGPROGRAM
#pragma prefer_hlslcc gles
#pragma target 3.0
#pragma multi_compile_instancing
#pragma vertex VertShader
#pragma fragment PixShader
#pragma shader_feature __ BEVEL_ON
#pragma shader_feature __ UNDERLAY_ON UNDERLAY_INNER
#pragma shader_feature __ GLOW_ON
#pragma multi_compile __ UNITY_UI_CLIP_RECT
#pragma multi_compile __ UNITY_UI_ALPHACLIP
#pragma multi_compile _ _MAIN_LIGHT_SHADOWS
#pragma multi_compile _ _MAIN_LIGHT_SHADOWS_CASCADE
#pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS
#pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS
#pragma multi_compile _ _SHADOWS_SOFT
#pragma multi_compile _ _MIXED_LIGHTING_SUBTRACTIVE
#include "UnityCG.cginc"
#include "UnityUI.cginc"
#include "TMPro_Properties.cginc"
#include "TMPro.cginc"
struct vertex_t {
float4 position : POSITION;
float3 normal : NORMAL;
fixed4 color : COLOR;
float2 texcoord0 : TEXCOORD0;
float2 texcoord1 : TEXCOORD1;
};
struct pixel_t {
float4 position : SV_POSITION;
fixed4 color : COLOR;
float2 atlas : TEXCOORD0; // Atlas
float4 param : TEXCOORD1; // alphaClip, scale, bias, weight
float4 mask : TEXCOORD2; // Position in object space(xy), pixel Size(zw)
float3 viewDir : TEXCOORD3;
#if (UNDERLAY_ON || UNDERLAY_INNER)
float4 texcoord2 : TEXCOORD4; // u,v, scale, bias
fixed4 underlayColor : COLOR1;
#endif
float4 textures : TEXCOORD5;
};
// Used by Unity internally to handle Texture Tiling and Offset.
float4 _FaceTex_ST;
float4 _OutlineTex_ST;
pixel_t VertShader(vertex_t input)
{
float bold = step(input.texcoord1.y, 0);
float4 vert = input.position;
vert.x += _VertexOffsetX;
vert.y += _VertexOffsetY;
float4 vPosition = UnityObjectToClipPos(vert);
float2 pixelSize = vPosition.w;
pixelSize /= float2(_ScaleX, _ScaleY) * abs(mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy));
float scale = rsqrt(dot(pixelSize, pixelSize));
scale *= abs(input.texcoord1.y) * _GradientScale * 1.5;
if (UNITY_MATRIX_P[3][3] == 0) scale = lerp(abs(scale) * (1 - _PerspectiveFilter), scale, abs(dot(UnityObjectToWorldNormal(input.normal.xyz), normalize(WorldSpaceViewDir(vert)))));
float weight = lerp(_WeightNormal, _WeightBold, bold) / 4.0;
weight = (weight + _FaceDilate) * _ScaleRatioA * 0.5;
float bias =(.5 - weight) + (.5 / scale);
float alphaClip = (1.0 - _OutlineWidth*_ScaleRatioA - _OutlineSoftness*_ScaleRatioA);
#if GLOW_ON
alphaClip = min(alphaClip, 1.0 - _GlowOffset * _ScaleRatioB - _GlowOuter * _ScaleRatioB);
#endif
alphaClip = alphaClip / 2.0 - ( .5 / scale) - weight;
#if (UNDERLAY_ON || UNDERLAY_INNER)
float4 underlayColor = _UnderlayColor;
underlayColor.rgb *= underlayColor.a;
float bScale = scale;
bScale /= 1 + ((_UnderlaySoftness*_ScaleRatioC) * bScale);
float bBias = (0.5 - weight) * bScale - 0.5 - ((_UnderlayDilate * _ScaleRatioC) * 0.5 * bScale);
float x = -(_UnderlayOffsetX * _ScaleRatioC) * _GradientScale / _TextureWidth;
float y = -(_UnderlayOffsetY * _ScaleRatioC) * _GradientScale / _TextureHeight;
float2 bOffset = float2(x, y);
#endif
// Generate UV for the Masking Texture
float4 clampedRect = clamp(_ClipRect, -2e10, 2e10);
float2 maskUV = (vert.xy - clampedRect.xy) / (clampedRect.zw - clampedRect.xy);
// Support for texture tiling and offset
float2 textureUV = UnpackUV(input.texcoord1.x);
float2 faceUV = TRANSFORM_TEX(textureUV, _FaceTex);
float2 outlineUV = TRANSFORM_TEX(textureUV, _OutlineTex);
pixel_t output = {
vPosition,
input.color,
input.texcoord0,
float4(alphaClip, scale, bias, weight),
half4(vert.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * half2(_MaskSoftnessX, _MaskSoftnessY) + pixelSize.xy)),
mul((float3x3)_EnvMatrix, _WorldSpaceCameraPos.xyz - mul(unity_ObjectToWorld, vert).xyz),
#if (UNDERLAY_ON || UNDERLAY_INNER)
float4(input.texcoord0 + bOffset, bScale, bBias),
underlayColor,
#endif
float4(faceUV, outlineUV),
};
return output;
}
fixed4 PixShader(pixel_t input) : SV_Target
{
float c = tex2D(_MainTex, input.atlas).a;
#ifndef UNDERLAY_ON
clip(c - input.param.x);
#endif
float scale = input.param.y;
float bias = input.param.z;
float weight = input.param.w;
float sd = (bias - c) * scale;
float outline = (_OutlineWidth * _ScaleRatioA) * scale;
float softness = (_OutlineSoftness * _ScaleRatioA) * scale;
half4 faceColor = _FaceColor;
half4 outlineColor = _OutlineColor;
faceColor.rgb *= input.color.rgb;
faceColor *= tex2D(_FaceTex, input.textures.xy + float2(_FaceUVSpeedX, _FaceUVSpeedY) * _Time.y);
outlineColor *= tex2D(_OutlineTex, input.textures.zw + float2(_OutlineUVSpeedX, _OutlineUVSpeedY) * _Time.y);
faceColor = GetColor(sd, faceColor, outlineColor, outline, softness);
#if BEVEL_ON
float3 dxy = float3(0.5 / _TextureWidth, 0.5 / _TextureHeight, 0);
float3 n = GetSurfaceNormal(input.atlas, weight, dxy);
float3 bump = UnpackNormal(tex2D(_BumpMap, input.textures.xy + float2(_FaceUVSpeedX, _FaceUVSpeedY) * _Time.y)).xyz;
bump *= lerp(_BumpFace, _BumpOutline, saturate(sd + outline * 0.5));
n = normalize(n- bump);
float3 light = normalize(float3(sin(_LightAngle), cos(_LightAngle), -1.0));
float3 col = GetSpecular(n, light);
faceColor.rgb += col*faceColor.a;
faceColor.rgb *= 1-(dot(n, light)*_Diffuse);
faceColor.rgb *= lerp(_Ambient, 1, n.z*n.z);
fixed4 reflcol = texCUBE(_Cube, reflect(input.viewDir, -n));
faceColor.rgb += reflcol.rgb * lerp(_ReflectFaceColor.rgb, _ReflectOutlineColor.rgb, saturate(sd + outline * 0.5)) * faceColor.a;
#endif
#if UNDERLAY_ON
float d = tex2D(_MainTex, input.texcoord2.xy).a * input.texcoord2.z;
faceColor += input.underlayColor * saturate(d - input.texcoord2.w) * (1 - faceColor.a);
#endif
#if UNDERLAY_INNER
float d = tex2D(_MainTex, input.texcoord2.xy).a * input.texcoord2.z;
faceColor += input.underlayColor * (1 - saturate(d - input.texcoord2.w)) * saturate(1 - sd) * (1 - faceColor.a);
#endif
#if GLOW_ON
float4 glowColor = GetGlowColor(sd, scale);
faceColor.rgb += glowColor.rgb * glowColor.a;
#endif
// Alternative implementation to UnityGet2DClipping with support for softness.
#if UNITY_UI_CLIP_RECT
half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(input.mask.xy)) * input.mask.zw);
faceColor *= m.x * m.y;
#endif
#if UNITY_UI_ALPHACLIP
clip(faceColor.a - 0.001);
#endif
return faceColor * input.color.a;
}
ENDCG
}
}
Fallback "TextMeshPro/Mobile/Distance Field"
CustomEditor "TMPro.EditorUtilities.TMP_SDFShaderGUI"
}
But in some devices, I have trouble with this shader when using LWRP.
Any TextMeshPro object that's in world space get's all in one position when I use LWRP. HUD elements work just fine:
The texts in the center of screen each should be on the white space of airplanes. If I switch the shader on my font mat to LWRP shaders they work as normal, except they look horrible.
When I try to upgrade the font material I get :
material was not upgraded. There's no upgrader to convert
TextMeshPro/Distance Field shader to selected pipeline
How can I fix this issue?

Shader works just fine in Unity Editor, but became black in WebGL build

I am working on a project which encodes sensor values at different positions into a 3d heatmap of a building. I use a vertex shader for this purpose and this works just fine in Editor:example, but after I built the scene in WebGL, this turned out to be black.
I has tried using constant loop indices or always include this shader in project settings etc., but none of these works. Here are some of the code:
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.worldPos = mul(unity_ObjectToWorld, v.vertex);
o.screenPos = ComputeScreenPos(o.vertex);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
//...
float2 boxIntersection(in float3 ro, in float3 rd, in float3 rad)
{
float3 m = 1.0 / rd;
float3 n = m * ro;
float3 k = abs(m) * rad;
float3 t1 = -n - k;
float3 t2 = -n + k;
float tN = max(max(t1.x, t1.y), t1.z);
float tF = min(min(t2.x, t2.y), t2.z);
if (tN > tF || tF < 0.0) return float2(-1.0, -1.0); // no intersection
return float2(tN, tF);
}
//p in object space
float SampleValue(float3 p) {
float totalValue = 0.0;
float denom = 0.0;
for (int i = 0; i < 34; ++i) { // _DataSize
float4 sd = _SensorData[i];
float dist = length(p - sd.xyz);
totalValue += sd.w / (dist * dist);
denom += 1.0 / (dist * dist);
}
if (denom == 0.0) {
return 0.0;
}
return totalValue / denom;
}
float4 transferFunction(float value) {
float tv = (value - _DataScale.x) / (_DataScale.y - _DataScale.x); // _DataScale.x, _DataScale.y
float4 col = tex2D(_TransferTexture, float2(0.5, tv));
col.w *= _Strength; // _Strength
return float4(col.xyz * col.w, col.w);
}
float4 rayMarch(float3 ro, float3 rd, float dp) {
float3 ro1 = mul(unity_WorldToObject, float4(ro, 1.0));
float3 rd1 = mul(unity_WorldToObject, rd);
float2 t = boxIntersection(ro1, rd1, float3(1, 1, 1) * 0.5);
t.x = length(mul(unity_ObjectToWorld, float4(ro1 + rd1 * max(t.x, 0.0), 1.0)) - ro);
t.y = length(mul(unity_ObjectToWorld, float4(ro1 + rd1 * t.y, 1.0)) - ro);
t.y = min(t.y, dp);
float4 acc = float4(0.0, 0.0, 0.0, 1.0);
float totalDelta = (t.y - t.x);
float delta = totalDelta / float(_RM_Samples - 1.0);
float3 p = ro + t.x * rd;
for (int i = 0; i < 34; ++i) { // _RM_Samples
float v = SampleValue(p);
float4 tf = transferFunction(v);
float tr = exp(-tf.w * delta);
acc.xyz += tf.xyz * acc.w * delta;
acc.w *= tr;
p += delta * rd;
}
return float4(acc.xyz, (1.0 - acc.w) * step(t.x, t.y));
}
fixed4 frag(v2f i) : SV_Target
{
float2 tc = i.screenPos.xy / i.screenPos.w;
float depth = UNITY_SAMPLE_DEPTH(tex2D(_CameraDepthTexture, tc));
float eD = LinearEyeDepth(depth);
float3 ro = _WorldSpaceCameraPos;
float3 rd = normalize(i.worldPos - ro);
float4 col = rayMarch(ro, rd, eD);
//if (col.w < 1) col = float4(1, 0, 0, 1);
//else col = float4(0, 1, 0, 1);
if (wingCullPlaneValue(i.worldPos.xyz) == 0 || cullPlaneValue(i.worldPos.xyz) == 0) {
discard;
}
UNITY_APPLY_FOG(i.fogCoord, col);
return col;
}
Since this works fine in Editor, I don't think there is any error in boxIntersection or rayMarching functions. I wonder if there is anything special in WebGl that it processes the pixels differently, and I has to tweak some codes accordingly. I am new to WebGL and Shader, and would appreciate any help or advice, thanks in advance.
that's because of the step function.
Approximate it with your own sigmoid function (might be expensive)
float emulated_step(float a, float x){
return 1.0/(1+pow(1000, -(x-a)*8192));
}

SCNProgram not affecting SCNFloor

In my experiments using the shader modifier, I saw that the array data could not be transferred to the shader.
Scenekit giving buffer size error while passing array data to uniform array in openGL shader
For this reason I decided to try SCNProgram. But now I realize that the shaders I added using SCNProgram do not work on SCNFloor.
Is there a particular reason for this problem?
Super simple shaders which I use for testing;
vertex shader
precision highp float;
attribute vec3 vertex;
uniform mat4 ModelViewProjectionMatrix;
void main()
{
gl_Position = ModelViewProjectionMatrix * vec4(vertex, 1.0);
}
fragment shader
precision mediump float;
void main( void )
{
gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
}
You can try to make your own vert and frag shaders to kinda do the same thing. I've done a similar thing with webgl / glsl es2, or just paint it solid, tint the existing floor:
uniform mat4 uCameraWM; //camera world matrix
uniform vec2 uCamAspFov; //x:aspect ratio y:tan(fov/2)
varying vec3 vVDw; //view direction
void main(){
//construct frustum, scale and transform a unit quad
vec4 viewDirWorld = vec4(
position.x * uCamAspFov.x,
position.y,
-uCamAspFov.y, //move it to where 1:aspect fits
0.
);
vVDw = ( uCameraWM * viewDirWorld ).xyz; //transform to world
gl_Position = vec4( position.xy , 0. , 1. ); //draw a full screen quad
}
Frag:
(ignore the cruft, point is to intersect the view direction ray with a plane, map it, you can look up a cubemap in the sky portion instead of discarding it)
uniform float uHeight;
uniform sampler2D uTexDiff;
uniform sampler2D uTexNorm;
uniform sampler2D uTexMask;
varying vec2 vUv;
varying vec3 vVDw;
struct Plane
{
vec3 point;
vec3 normal;
float d;
};
bool rpi( in Plane p , in vec3 p0 , in vec3 vd , out vec3 wp )
{
float t;
t = -( dot( p0 , p.normal ) + p.d ) / dot( vd , p.normal );
wp = p0 + t * vd;
return t > 0. ? true : false;
}
void main(){
Plane plane;
plane.point = vec3( 0. , uHeight , 0. );
plane.normal = vec3( 0. , 1. , .0 );
plane.d = -dot( plane.point , plane.normal );
vec3 ld = normalize( vec3(1.,1.,1.) );
vec3 norm = plane.normal;
float ndl = dot( norm , ld ) ;
vec2 uv;
vec3 wp;
vec3 viewDir = normalize( vVDw );
vec3 h = normalize((-viewDir + ld));
float spec = clamp( dot( h , norm ) , .0 , 1. );
// spec = pow( spec , 5. );
if( dot(plane.normal , cameraPosition) < 0. ) discard;
if( !rpi( plane , cameraPosition , viewDir , wp ) ) discard;
uv = wp.xz;
vec2 uvm = uv * .0105;
vec2 uvt = uv * .2;
vec4 tmask = texture2D( uTexMask , uvm );
vec2 ch2Scale = vec2(1.8,1.8);
vec2 ch2Scale2 = vec2(1.6,1.6);
vec2 t1 = uvt * ch2Scale2 - vec2(tmask.z , -tmask.z) ;
// vec2 t2 = uvt * ch2Scale + tmask.z ;
// vec2 t3 = uvt + vec2(0. , mask.z-.5) * 1.52;
vec3 diffLevels = ( texture2D( uTexDiff , t1 ) ).xyz;
// vec3 diffuse2 = ( texture2D( uTexDiff, fract(t1) * vec2(.5,1.) + vec2(.5,.0) ) ).xyz;
// vec3 diffuse1 = ( texture2D( uTexDiff, fract(t2) * vec2(.5,1.) ) ).xyz;
// vec4 normalMap2 = texture2D( uTexNorm, fract(t1) * vec2(.5,1.) + vec2(.5,.0) );
// vec4 normalMap1 = texture2D( uTexNorm, fract(t2) * vec2(.5,1.) );
float diffLevel = mix(diffLevels.y, diffLevels.x, tmask.x);
diffLevel = mix( diffLevel , diffLevels.z, tmask.y );
// vec3 normalMix = mix(normalMap1.xyz, normalMap2.xyz, tmask.x);
// vec2 g = fract(uv*.1) - .5;
// float e = .1;
// g = -abs( g ) + e;
float fog = distance( wp.xz , cameraPosition.xz );
// float r = max( smoothstep( 0.,e,g.x) , smoothstep( 0.,e,g.y) );
gl_FragColor.w = 1.;
gl_FragColor.xyz = vec3(tmask.xxx);
gl_FragColor.xyz = vec3(diffLevel) * ndl + spec * .5;
}
But overall, the better advice would be just to give up on scenekit and save yourself a TON of frustration.
Finally Apple Developer Technical Support answered the question I asked about this issue.
Here is the answer that they give.
Unfortunately, there is not a way to shade floor as such. The
SceneKit team admits that SCNFloor is a different kind of object that
is not intended for use with SCNProgram. Furthermore, using the
.fragment shader entry point does not work either (such as:)
func setFragmentEntryPoint( _ node: SCNNode ) {
print( #function + " setting fragment entry point for \(node)" )
DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds( 2500 ) ) {
let geometry = node.geometry!
let dict: [SCNShaderModifierEntryPoint:String] = [.fragment :
"_output.color = vec4( 0.0, 1.0, 0.0, 1.0 );"]
geometry.shaderModifiers = dict
}
}
Though the SceneKit team considered this behavior to be expected, you
may still file a bug report which in this case will be interpreted as
an API enhancement request.