# Surface shader - Optimization BUG ?

Hi im doing some custom shaders and 1st thought i was doing something wrong, but i found a problem that happens with any shader using reflection and bump-mapping

Code off unity website:

``````Shader "Example/WorldRefl Normalmap" {
Properties {
_MainTex ("Texture", 2D) = "white" {}
_BumpMap ("Bumpmap", 2D) = "bump" {}
_Cube ("Cubemap", CUBE) = "" {}
}
Tags { "RenderType" = "Opaque" }
CGPROGRAM
#pragma surface surf Lambert
struct Input {
float2 uv_MainTex;
float2 uv_BumpMap;
float3 worldRefl;
INTERNAL_DATA
};
sampler2D _MainTex;
sampler2D _BumpMap;
samplerCUBE _Cube;
void surf (Input IN, inout SurfaceOutput o) {
o.Albedo = tex2D (_MainTex, IN.uv_MainTex).rgb * 0.5;
o.Normal = UnpackNormal (tex2D (_BumpMap, IN.uv_BumpMap));
o.Emission = texCUBE (_Cube, WorldReflectionVector (IN, o.Normal)).rgb;
}
ENDCG
}
Fallback "Diffuse"
}
``````

now if you look at the compiled code below â€¦ it calculates the worldNormal 2 times per pixel for most of the iterations of shader madeâ€¦

Part of Compiled Code from frag:

`````` tmpvar_7.x = dot (xlv_TEXCOORD1.xyz, normal_6);
tmpvar_7.y = dot (xlv_TEXCOORD2.xyz, normal_6);
tmpvar_7.z = dot (xlv_TEXCOORD3.xyz, normal_6);
worldN_1.x = dot (xlv_TEXCOORD1.xyz, normal_6);
worldN_1.y = dot (xlv_TEXCOORD2.xyz, normal_6);
worldN_1.z = dot (xlv_TEXCOORD3.xyz, normal_6);
``````

is this a bug/oversight ? does this get optimized out by driver ? is there anyway around this ?

Happens in unity 5.0.1 thru 5.1.1 â€¦

@Aras will know what is happening here.

Confirmed, guess the question is whether this gets optimized out later or not, although as this is the compiled code I would have expected the compiler to have caught this in the first place.

Have you logged a bug for this? Would be better than just posting on the forum.

No not yet i will later today .

WorldReflectionVector puts the 2nd calc in there â€¦ i tried to find â€śWorldReflectionVectorâ€ť in a cginc header file but its not there â€¦

bug submitted

1 Like