Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Is "fixed4 color = tex2D(_MainTex, i.uv);" Considered Precision Conversion?

Discussion in 'Shaders' started by AhSai, Sep 27, 2019.

  1. AhSai

    AhSai

    Joined:
    Jun 25, 2017
    Posts:
    129
    Is the line
    Code (CSharp):
    1. fixed4 color = tex2D(_MainTex, i.uv);
    considered as precision conversion?
    According to Nvidia's cg library http://developer.download.nvidia.com/cg/tex2D.html the return type of tex2D is a "float4". If I have many tex2D in my frag shader, will it be beneficial in terms of performance to use float4 instead?
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,329
    First, Unity does not use Cg anymore. It has not for several years now.

    Second, yes, tex2D always returns a float4. Even in HLSL, even in GLSL. Even if the texture it's sampling isn't a floating point texture. This is a hardware level thing, not something strictly controlled by the graphics API in use. Texture sampling is one of the few remaining bits of specialized fixed function hardware that still exists on every modern GPU. It's a very specialized task that bespoke hardware is better at than the more generalized compute units that most of the rest of the GPUs are made of these days. But to simplify that hardware, they always output a float4, and let the compute units handle any kind of conversion to different types.

    Also important, on desktop and consoles fixed4, half4, and float4 are the same thing*. It's only on mobile platforms where the floating point precision variable type does anything.

    So, is it beneficial? On mobile platforms, yes. Any operations you do with only fixed floating point values will be faster than those using any float floating point value. Whether this is faster than half or not depends on the hardware, as some mobile GPUs don't actually implement fixed and only have half and float, like desktop only has float.

    * Recent desktop GPUs have added back in support for 16 bit precision floats, but when writing shaders in Unity half isn’t treated as 16 bit.
     
    Vedran_M and Olmi like this.