Search Unity

Resolved Get Triangle ID

Discussion in 'Shaders' started by CinnamonCereals, Jan 23, 2022.

  1. CinnamonCereals

    CinnamonCereals

    Joined:
    Jan 19, 2022
    Posts:
    23
    Hello, I am trying to print the triangle ID in unity editor but it's always returned 0. Can anyone help me figure out the proper way to do this?

    I print it with the basic material.GetInt("_TestInt");

    in the shader the simplification code is (using URP):
    Code (CSharp):
    1.     Properties {  
    2.       ...
    3.       _TestInt("Int", Int) = 0
    4.     }
    5. SuShader
    6. {
    7. ...
    8.     Pass
    9.            {
    10.             ...
    11. CBUFFER_START(UnityPerMaterial)
    12. int _TestInt;
    13. CBUFFER_END
    14.  
    15. float3 Fragment(VertexOutput IN, uint triangleID: SV_PrimitiveID) :  SV_Target
    16. {
    17.    float4 pixelColor = SAMPLE_TEXTURE2D(_MainTexture, sampler_MainTexture, IN.uv);
    18.   _TestInt = trinagleID;
    19.    return pixelColor * _Color;
    20. }
    21.            }
    22. }
    23.  
    24.  
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    The TLDR answer is you’re getting a 0 because that code never runs. And even if it did the value on the CPU side would never be changed.

    The longer answer is the material property cannot be modified by the GPU. It's something that's set on the CPU, then copied to the GPU, and then another copy is made for each individual invocation of the shader. By that I mean each pixel the shader runs on gets a copy of that data that is then thrown out once that pixel is done rendering for that frame. As soon as return is called, the rest of the data is thrown away. But in this particular snippet because
    _TestInt
    isn't used for the pixel color, that code never even runs because the shader compiler is going to remove that code.

    You can get that data back to the CPU, and make sure it runs, but you have to use a compute buffer set to be a read / write target and then manually pull it from the GPU back to the CPU. But that's still not actually that useful unless you have a mesh that is only one triangle because every pixel rendered of your mesh is going to be writing to it meaning you'll only get the value of the last pixel that rendered.

    The real question is what exactly do you want this information for? Because what you're trying to do probably isn't the way to do it.
     
    CinnamonCereals likes this.
  3. CinnamonCereals

    CinnamonCereals

    Joined:
    Jan 19, 2022
    Posts:
    23
    I was trying to find my way into debugging something but I figured a way around that (very new to shaders, I thought for a second that I'm not using SV_PrimitiveID properly but that was not the case), your comments in this community were very useful in helping me understand shaders more, thank you! I will close this as solved.