Search Unity

Methods Returning Arrays (in .cginc)

Discussion in 'Shaders' started by LaireonGames, Nov 30, 2019.

  1. LaireonGames

    LaireonGames

    Joined:
    Nov 16, 2013
    Posts:
    432
    I think I found a way to massively optimise some of my procedurally generated meshes, but to do so I need to access what is effectively a nested array in my shaders.

    So first approach, flatten the thing but I will need more than 1024 values which is likely Unitys limit for array sizes (Reference: https://forum.unity.com/threads/material-setvectorarray-array-size-limit.512068/)

    Instead what I am trying to do is something like this in a CG Includes file:

    Code (CSharp):
    1. float4 BendAxis1 [14];
    2. float4 BendAxis2 [14];
    3.  
    4.         float4[] GetAxis(int index)
    5.         {
    6.           if(index == 0)
    7.             return BendAxis1;
    8.          else
    9.            return BendAxis2;
    10. //then many more checks for other axis
    11.         }
    12.  
    Problem is, the shader wont compile and doesn't like: float4[] GetAxis(int index) because of "Unexpected token '['"

    Any idea if its possible to return an array in shaders and if so what the syntax would be?

    I could probably get around this with a baked texture lookup but would be a far messier solution so would rather avoid that!
     
  2. Przemyslaw_Zaworski

    Przemyslaw_Zaworski

    Joined:
    Jun 9, 2017
    Posts:
    183
    Example:

    Code (CSharp):
    1.             // fill array with random data - 2..xxxx is shorthand for "float4(2,2,2,2)" etc.
    2.             static const float4 BendAxis1 [14] = {float4(1,0,0,1), { 0.2, 0.3, 0.4, 0.5 }, 2..xxxx,3..xxxx,4..xxxx,5..xxxx,6..xxxx,0..xxxx,1..xxxx,2..xxxx,3..xxxx,4..xxxx,5..xxxx,6..xxxx};
    3.             static const float4 BendAxis2 [14] = {float4(0,0,1,1), { 0.2, 1.0, 0.4, 0.1 }, 4..xxxx,6..xxxx,8..xxxx,0..xxxx,2..xxxx,4..xxxx,6..xxxx,8..xxxx,0..xxxx,2..xxxx,4..xxxx,6..xxxx};
    4.            
    5.             void GetAxis(int index, float4 a[14], float4 b[14], out float4 c[14])
    6.             {
    7.                 if(index == 0)
    8.                     c = a;
    9.                 else
    10.                     c = b;
    11.             }
    12.            
    13.             fixed4 frag (v2f i) : SV_Target
    14.             {
    15.                 float4 BendAxis3 [14];
    16.                 GetAxis(0, BendAxis1, BendAxis2, BendAxis3);
    17.                 return BendAxis3[0];  // return red
    18.                
    19.                 //GetAxis(1, BendAxis1, BendAxis2, BendAxis3);
    20.                 //return BendAxis3[0];  // return blue              
    21.             }
     
    LaireonGames likes this.
  3. LaireonGames

    LaireonGames

    Joined:
    Nov 16, 2013
    Posts:
    432
    Huh didn't think to try 'out'. Thanks this works :D