现在的位置: 首页 > 综合 > 正文

用模板类封装OpenGL Shader 的Uniform变量

2018年04月08日 ⁄ 综合 ⁄ 共 2217字 ⁄ 字号 评论关闭

   struct UniformTypeName
   {
       std::string name;
       E_UniformType type;
   };

   static UniformTypeName  _datatypeToGlsl[17] = {
        {"float", UT_FLOAT}, {"vec2", UT_FLOAT_VEC2}, {"vec3", UT_FLOAT_VEC3}, {"vec4", UT_FLOAT_VEC4},
        {"int", UT_INT},     {"ivec2", UT_INT_VEC2},  {"ivec3",UT_INT_VEC3},   {"ivec4", UT_INT_VEC4},
        {"bool",UT_BOOL},    {"bvec2", UT_BOOL_VEC2}, {"bvec3",UT_BOOL_VEC3},  {"bvec4", UT_BOOL_VEC4},
        {"mat2", UT_FLOAT_MAT2},  {"mat3", UT_FLOAT_MAT3}, {"mat4", UT_FLOAT_MAT4},
        {"sampler2D", UT_SAMPLER_2D},{"samplerCube", UT_SAMPLER_CUBE}};

   class AutomaticUniformBase: public UniformBase
   {
   public:
       AutomaticUniformBase(){}
       ~AutomaticUniformBase(){}
       std::string getDeclaration(const std::string& name)
       {
           std::string declaration = "uniform " + getDataTypeName(this->_datatype) + " " + name;

           std::stringstream sizestr;
           sizestr<<_size;
           if (_size == 1) {
               declaration += ";";
           } else {
               declaration += "[" + sizestr.str() + "];";
           }

           return declaration;
       }

       std::string getDataTypeName(E_UniformType typeEnum)
       {
           std::string result("");
           for(int i = 0; i< sizeof(_datatypeToGlsl); i++)
           {
               if(typeEnum == _datatypeToGlsl[i].type)
               {
                   result = _datatypeToGlsl[i].name;
                   break;
               }
           }

           return result;
       }
   };

   template<class T>

   class AutomaticUniform: public AutomaticUniformBase
   {
   public:
       AutomaticUniform()
       {
           this->_uniformClassType = UCT_AUTO;
       }
       typedef T (* GetValueFunc)(UniformState*);
       AutomaticUniform( unsigned int size, E_UniformType type, GetValueFunc getValue)
       {
           this->_size = size;
           this->_datatype = type;
           this->_getValue = getValue;
           this->_uniformClassType = UCT_AUTO;
       }

       struct Option
       {
           unsigned int _size;
           E_UniformType _datatype;
           GetValueFunc _getValue;
       };

       AutomaticUniform(const Option& option)
       {
           this->_size = option._size;
           this->_datatype = option._datatype;
           this->_getValue = option._getValue;
           this->_uniformClassType = UCT_AUTO;
       }

   public:
       GetValueFunc _getValue;
   };

抱歉!评论已关闭.