Search code examples
graphicsshaderskinningvertex-shadercg

Non-constant index into uniform array CG Shader


According to this nVidia CG tutorial (and my own experience) accessing uniform arrays in CG shaders with a non-constant index is either inefficient or unsupported (more often than not, unsupported it seems).

My question is; how can I circumvent this problem?

I am currently writing a GPU skinning shader in which I pass an array of bones (4x4 matrices), which I need to access using an index stored in a vertex attribute (specifically, a float4 vector who's components are cast to ints). Obviously, because of the limitations mentioned above, this doesn't work...perhaps I'm missing a better method of doing this?


Solution

  • That is indeed the common way of doing it, e.g. (this is HLSL but essentially the same -- note the global uniform 'boneArray')

    float4x3 CalcBoneTransform(float4 blendWeights, float4 boneIndices)
    {
      // Calculate normalized fourth bone weight2
      float4 weights = float4(blendWeights.x, blendWeights.y, blendWeights.z , 1.0f - blendWeights.x - blendWeights.y - blendWeights.z);
      // Calculate bone transform
      float4x3 boneTransform;
      int4 indices = boneIndices;
      boneTransform =  weights.x * boneArray[indices.x];
      boneTransform += weights.y * boneArray[indices.y];
      boneTransform += weights.z * boneArray[indices.z];
      boneTransform += weights.w * boneArray[indices.w];
      return boneTransform;
    }