示例#1
0
 void setup(const ShaderPtr& shader, bool) override
 {
     shader->setVertexSource(ShaderLoader::vertexSource());
     shader->setFragmentSource(ShaderLoader::fragmentSource());
     shader->compile();
 }
示例#2
0
文件: shader.cpp 项目: Grumbel/viewer
ShaderPtr
Shader::from_file(GLenum type, std::string const& filename,
                  std::vector<std::string> const& defines)
{
  std::ifstream in(filename);
  if (!in)
  {
    throw std::runtime_error((boost::format("%s: failed to open file") % filename).str());
  }
  else
  {
    std::vector<std::string> sources;

    // add version declaration
#ifdef HAVE_OPENGLES2
    sources.emplace_back("#version 100\n");
#else
    sources.emplace_back("#version 330 core\n");
#endif

    { // add custom defines
      std::ostringstream os;
      for(auto const& def : defines)
      {
        auto equal_pos = def.find('=');
        if (equal_pos == std::string::npos)
        {
          os << "#define " << def << '\n';
        }
        else
        {
          os << "#define " << def.substr(0, equal_pos) << ' ' << def.substr(equal_pos+1) << '\n';
        }
      }
      sources.emplace_back(os.str());
    }

    { // add the actual source file
      std::regex include_rx("^#\\s*include\\s+\"([^\"]*)\".*$");
      int line_count = 0;
      std::ostringstream os;
      std::string line;
      while(std::getline(in, line))
      {
        std::smatch rx_results;
        if (std::regex_match(line, rx_results, include_rx))
        {
          boost::filesystem::path include_filename(rx_results[1]);
          if (include_filename.is_absolute())
          {
            include_file(include_filename.string(), os);
          }
          else
          {
            include_file((boost::filesystem::path(filename).parent_path() / include_filename).string(),
                         os);
          }
          os << "#line " << line_count << '\n';
        }
        else
        {
          os << line << '\n';
        }

        line_count += 1;
      }
      sources.emplace_back(os.str());
    }

    ShaderPtr shader = std::make_shared<Shader>(type);

    shader->source(sources);
    shader->compile();

    if (!shader->get_compile_status())
    {
      throw std::runtime_error((boost::format("%s: error:\n %s") % filename % shader->get_info_log()).str());
    }

    //log_debug("%s: shader compile successful", filename);

    return shader;
  }
}