The name of the initial branch for new projects is now "main" instead of "master". Existing projects remain unchanged. More information: https://doku.lrz.de/display/PUBLIC/GitLab

shadermanager.cpp 41.4 KB
Newer Older
schultezub's avatar
schultezub committed
1 2
/**********************************************************************
 *                                                                    *
3 4 5 6
 * cgt - CAMP Graphics Toolbox, Copyright (C) 2012-2014               *
 *     Chair for Computer Aided Medical Procedures                    *
 *     Technische Universitaet Muenchen, Germany.                     *
 *     <http://campar.in.tum.de/>                                     *
schultezub's avatar
schultezub committed
7
 *                                                                    *
8 9 10 11
 * forked from tgt - Tiny Graphics Toolbox, Copyright (C) 2006-2011   *
 *     Visualization and Computer Graphics Group, Department of       *
 *     Computer Science, University of Muenster, Germany.             *
 *     <http://viscg.uni-muenster.de>                                 *
schultezub's avatar
schultezub committed
12
 *                                                                    *
13
 * This file is part of the cgt library. This library is free         *
schultezub's avatar
schultezub committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 * software; you can redistribute it and/or modify it under the terms *
 * of the GNU Lesser General Public License version 2.1 as published  *
 * by the Free Software Foundation.                                   *
 *                                                                    *
 * This library is distributed in the hope that it will be useful,    *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of     *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the       *
 * GNU Lesser General Public License for more details.                *
 *                                                                    *
 * You should have received a copy of the GNU Lesser General Public   *
 * License in the file "LICENSE.txt" along with this library.         *
 * If not, see <http://www.gnu.org/licenses/>.                        *
 *                                                                    *
 **********************************************************************/

29
#include "cgt/shadermanager.h"
schultezub's avatar
schultezub committed
30

31
#include "cgt/gpucapabilities.h"
schultezub's avatar
schultezub committed
32 33 34 35 36 37

#include <iostream>
#include <fstream>

using std::string;

38
namespace cgt {
schultezub's avatar
schultezub committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

//------------------------------------------------------------------------------

namespace {

/**
 * Resolve the line number to take into account the include directives.
 * Returns a string containing file name and line number in that file.
 */
std::string resolveLineNumber(int number, const std::vector<ShaderObject::LineInfo>& lineTracker) {
    int found = static_cast<int>(lineTracker.size()) - 1;
    for (int i = static_cast<int>(lineTracker.size()) - 1; i >= 0 ; i--) {
        if (lineTracker[i].lineNumber_ <= number) {
            found = i;
            break;
        }
    }

    std::ostringstream result;
    //if (found >= 0) { //found is unsigned...
        result << FileSystem::fileName(lineTracker[found].filename_) << ":"
               << (number - lineTracker[found].lineNumber_ + lineTracker[found].sourceLineNumber_);
    //}
    return result.str();
}

} // namespace

67
const std::string ShaderPreprocessor::loggerCat_("cgt.Shader.ShaderPreprocessor");
schultezub's avatar
schultezub committed
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97

ShaderPreprocessor::ShaderPreprocessor(ShaderObject* obj, Mode /*mode*/)
    : shd_(obj), lineTracker_(obj->lineTracker_), inputType_(0), outputType_(0), verticesOut_(0)
{
    parse();
}

void ShaderPreprocessor::parsePart(const std::string& input, const std::string& name) {
    std::istringstream source(input);
    int locallinenumber = 0;

    lineTracker_.push_back(ShaderObject::LineInfo(activeLine_, name, 1));

    string line;
    while (std::getline(source, line)) {
        locallinenumber++;
        string::size_type pos = line.find("#include");

        // At least partly support for comments.
        // "/*"-style comments starting on previous lines are not detected.
        string::size_type comment1 = line.find("//");
        string::size_type comment2 = line.find("/*");
        bool inComment = (comment1 != string::npos && comment1 < pos) || (comment2 != string::npos && comment2 < pos);

        if (pos != string::npos && !inComment) {
            pos = line.find("\"", pos + 1);
            string::size_type end = line.find("\"", pos + 1);
            string filename(line, pos + 1, end - pos - 1);
            filename = ShdrMgr.completePath(filename);

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
            if (includedFilenames_.find(filename) == includedFilenames_.end()) {
                File* file = FileSys.open(filename);
                string content;
                if ((!file) || (!file->isOpen())) {
                    LERROR("Cannot open shader include '" << filename << "' in " << resolveLineNumber(activeLine_, lineTracker_));
                }
                else {
                    size_t len = file->size();
                    // check if file is empty
                    if (len == 0)
                        content = "";
                    else
                        content = file->getAsString();
                    file->close();

                    outputComment("BEGIN INCLUDE " + filename, "BEGIN");

                    if (!content.empty() && content[content.size() - 1] != '\n')
                        content += "\n";

                    parsePart(content, filename);

                    outputComment("END INCLUDE " + filename, "END");

                    lineTracker_.push_back(ShaderObject::LineInfo(activeLine_, name, locallinenumber + 1));
                }
                delete file;

                includedFilenames_.insert(filename);
schultezub's avatar
schultezub committed
127 128 129 130 131 132 133 134 135 136 137 138
            }
        } else {
            result_ << line << "\n";
            activeLine_++;
        }
    }
}

void ShaderPreprocessor::parse() {
    activeLine_ = 1;
    lineTracker_.clear();
    result_.clear();
139
    includedFilenames_.clear();
schultezub's avatar
schultezub committed
140

141 142 143 144 145 146 147 148 149 150 151 152 153 154
    if (! shd_->customGlslVersion_.empty()) {
        parsePart("#version " + shd_->customGlslVersion_ + "\n", "Custom per-shader version");
    }
    else {
        if (! ShdrMgr.getDefaultGlslVersion().empty()) {
            parsePart("#version " + ShdrMgr.getDefaultGlslVersion() + "\n", "Global version");
        }
    }

    if (! ShdrMgr.getGlobalHeader().empty()) {
        outputComment("BEGIN GLOBAL HEADER");
        parsePart(ShdrMgr.getGlobalHeader(), "GLOBAL HEADER");
        outputComment("END GLOBAL HEADER");
    }
155

schultezub's avatar
schultezub committed
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
    if (!shd_->header_.empty()) {
        outputComment("BEGIN HEADER");
        parsePart(shd_->header_, "HEADER");
        outputComment("END HEADER");
    }

    parsePart(shd_->unparsedSource_, shd_->filename_);
}

void ShaderPreprocessor::outputComment(const std::string& comment, const std::string& type) {
    result_ << "// " << comment << "\n";
    lineTracker_.push_back(ShaderObject::LineInfo(activeLine_, type, 0));
    activeLine_++;
}

bool ShaderPreprocessor::scanGeomShaderDirectives() {
    LDEBUG("Scanning for geometry shader compile directives...");
    std::string input = getGeomShaderDirective("GL_GEOMETRY_INPUT_TYPE_EXT");

    if (input == "GL_POINTS")
        inputType_ = GL_POINTS;
    else if (input == "GL_LINES")
        inputType_ = GL_LINES;
    else if (input == "GL_LINES_ADJACENCY_EXT")
        inputType_ = GL_LINES_ADJACENCY_EXT;
    else if (input == "GL_TRIANGLES")
        inputType_ = GL_TRIANGLES;
    else if (input == "GL_TRIANGLES_ADJACENCY_EXT")
        inputType_ = GL_TRIANGLES_ADJACENCY_EXT;
    else {
        LERROR("Unknown input type: " << input);
        return false;
    };

    std::string output = getGeomShaderDirective("GL_GEOMETRY_OUTPUT_TYPE_EXT");
    if (output == "GL_POINTS")
        outputType_ = GL_POINTS;
    else if (output == "GL_LINE_STRIP")
        outputType_ = GL_LINE_STRIP;
    else if (output == "GL_TRIANGLE_STRIP")
        outputType_ = GL_TRIANGLE_STRIP;
    else {
        LERROR("Unknown output type: " << output);
        return false;
    };

    std::string verticesOut = getGeomShaderDirective("GL_GEOMETRY_VERTICES_OUT_EXT");

    std::istringstream myStream(verticesOut);
    if (myStream >> verticesOut_) {
        LDEBUG("VERTICES_OUT: " << verticesOut_);
    }
    else {
        LERROR("Failed to parse argument(" << verticesOut << ") as integer for directive GL_GEOMETRY_VERTICES_OUT_EXT.");
        return false;
    }

    return true;
}

std::string ShaderPreprocessor::getGeomShaderDirective(const std::string& d) {
    string sourceStr(shd_->source_);
    string::size_type curPos = sourceStr.find(d + "(", 0);
    string::size_type length = d.length() + 1;
    if (curPos != string::npos) {
        string::size_type endPos = sourceStr.find(")", curPos);

        if (endPos != string::npos) {
            std::string ret = sourceStr.substr(curPos + length, endPos - curPos - length);
            // test for space, newline:
            if ((ret.find(" ", 0) == string::npos) && (ret.find("\n", 0) == string::npos) ) {
                LINFO("Directive " << d << ": " << ret);
                return ret;
            }
            else {
                LERROR("No spaces/newlines allowed inbetween directive brackets! Directive: " << d);
                return "";
            }
        }
        LERROR("Missing ending bracket for directive " << d);
        return "";
    }
    else {
        LWARNING("Could not locate directive " << d << "!");
        return "";
    }
}

std::string ShaderPreprocessor::getResult() const {
    return result_.str();
}

GLint ShaderPreprocessor::getGeomShaderOutputType() const {
    return outputType_;
}

GLint ShaderPreprocessor::getGeomShaderInputType() const {
    return inputType_;
}

GLint ShaderPreprocessor::getGeomShaderVerticesOut() const {
    return verticesOut_;
}

//------------------------------------------------------------------------------

262
const string ShaderObject::loggerCat_("cgt.Shader.ShaderObject");
schultezub's avatar
schultezub committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

ShaderObject::ShaderObject(const string& filename, ShaderType type)
    : filename_(filename)
    , shaderType_(type)
    , isCompiled_(false)
    , inputType_(GL_TRIANGLES)
    , outputType_(GL_TRIANGLE_STRIP)
    , verticesOut_(16)
{
    id_ = glCreateShader(shaderType_);
    if (id_ == 0)
        LERROR("ShaderObject(" + filename + ")::glCreateShader() returned 0");
}

ShaderObject::~ShaderObject() {
    glDeleteShader(id_);
}

void ShaderObject::loadSourceFromFile(const string& filename) throw (Exception) {
282
    //LDEBUG("Loading " << filename);
schultezub's avatar
schultezub committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
    File* file = FileSys.open(filename);

    // check if file is open
    if (!file || !file->isOpen()) {
        LDEBUG("File not found: " << filename);
        delete file;
        throw FileNotFoundException("", filename);
    }

    filename_ = filename;
    unparsedSource_ = file->getAsString();
    source_ = unparsedSource_;

    file->close();
    delete file;
}

void ShaderObject::uploadSource() {
    const GLchar* s = source_.c_str();
    glShaderSource(id_, 1,  &s, 0);
}

bool ShaderObject::compileShader() {
    isCompiled_ = false;

    ShaderPreprocessor p(this);
    source_ = p.getResult();

    if (shaderType_ == GEOMETRY_SHADER) {
        if (p.getGeomShaderInputType())
            inputType_ = p.getGeomShaderInputType();
        if (p.getGeomShaderOutputType())
            outputType_ = p.getGeomShaderOutputType();
        if (p.getGeomShaderVerticesOut())
            verticesOut_ = p.getGeomShaderVerticesOut();
    }

    uploadSource();

    glCompileShader(id_);
    GLint check = 0;
    glGetShaderiv(id_, GL_COMPILE_STATUS, &check);
    isCompiled_ = (check == GL_TRUE);
    return isCompiled_;
}

namespace {

int parseLogLineNumberNVIDIA(const std::string& message) {
    // Errors look like this:
    // 0(1397) : error C0000: syntax error, unexpected '=' at token "="
    std::istringstream ls(message);
    int id; // first number (probably used when multiple sources are bound), ignored
    if (ls >> id) {
        char c = 0; // should be an opening parenthesis
        if (ls >> c &&c == '(') {
            int num; // line number
            if (ls >> num)
                return num;
        }
    }
    return 0;
}

int parseLogLineNumberATI(const std::string& message) {
    // Errors look like this:
    // ERROR: 0:2785: 'frontPos' : undeclared identifier
    std::istringstream ls(message);
    std::string s;
    if (ls >> s && s == "ERROR:") {
        int id; // first number (probably used when multiple sources are bound), ignored
        if (ls >> id) {
            char c = 0; // should be a colon
            if (ls >> c && c == ':') {
                int num; // line number
                if (ls >> num)
                    return num;
            }
        }
    }

    return 0;
}

/**
 * Tries to extract the line number for a given compile messages.
 * Returns 0 if no line number was found.
 */
int parseLogLineNumber(const std::string& message) {
    int n = 0;

    n = parseLogLineNumberNVIDIA(message);
    if (n > 0)
        return n;

    n = parseLogLineNumberATI(message);
    if (n > 0)
        return n;

    return 0;
}

} // namespace

string ShaderObject::getCompilerLog() const {
    GLint len;
    glGetShaderiv(id_, GL_INFO_LOG_LENGTH , &len);

    if (len > 1) {
        GLchar* log = new GLchar[len];
        if (log == 0)
            return "Memory allocation for log failed!";
        GLsizei l;  // length returned
        glGetShaderInfoLog(id_, len, &l, log);
        std::istringstream str(log);
        delete[] log;

        std::ostringstream result;

        string line;
        while (getline(str, line)) {
            result << line;

            int num = parseLogLineNumber(line);
            if (num > 0)
                result << " [" << resolveLineNumber(num, lineTracker_) << "]";

            result << '\n';
        }

        return result.str();
    } else {
        return "";
    }
}

void ShaderObject::setHeader(const string& h) {
    header_ = h;
}

bool ShaderObject::rebuildFromFile() {
    try {
        loadSourceFromFile(filename_);
    }
    catch (const Exception& e) {
        LWARNING("Failed to load shader " << filename_ << ": " << e.what());
        return false;
    }

    uploadSource();

    if (!compileShader()) {
        LERROR("Failed to compile shader object " << filename_);
        LERROR("Compiler Log: \n" << getCompilerLog());
        return false;
    }

    return true;
}

//------------------------------------------------------------------------------

445
const string Shader::loggerCat_("cgt.Shader.Shader");
schultezub's avatar
schultezub committed
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

Shader::Shader()
    : isLinked_(false)
    , ignoreError_(false)
{
    id_ = glCreateProgram();
    if (id_ == 0)
        LERROR("Shader(): glCreateProgram() returned 0");
}

Shader::~Shader() {
    for (ShaderObjects::iterator iter = objects_.begin(); iter != objects_.end(); ++iter) {
        glDetachShader(id_, (*iter)->id_);
        delete (*iter);
    }
    glDeleteProgram(id_);
}

void Shader::attachObject(ShaderObject* obj) {
    glAttachShader(id_, obj->id_);
    objects_.push_back(obj);
}

void Shader::detachObject(ShaderObject* obj) {
    glDetachShader(id_, obj->id_);
    objects_.remove(obj);
    isLinked_ = false;
}

void Shader::activate() {
    if (isLinked_)
477
        activate(id_);
schultezub's avatar
schultezub committed
478 479 480
}

void Shader::activate(GLint id) {
481 482
#if CGT_DEBUG
    if (cgt::getGlInt(GL_CURRENT_PROGRAM) != 0)
483 484 485
        LWARNING("Binding a new Shader while another Shader is active. Do you really want to do this?");
#endif

schultezub's avatar
schultezub committed
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
    glUseProgram(id);
}

void Shader::deactivate() {
    glUseProgram(0);
}

GLint Shader::getCurrentProgram() {
    GLint id;
    glGetIntegerv(GL_CURRENT_PROGRAM, &id);
    return id;
}

bool Shader::isActivated() {
    GLint shader_nr;
    glGetIntegerv(GL_CURRENT_PROGRAM, &shader_nr);
    return (id_ == static_cast<GLuint>(shader_nr));
}

void Shader::detachObjectsByType(ShaderObject::ShaderType type) {
    for (ShaderObjects::iterator iter = objects_.begin(); iter != objects_.end(); ++iter) {
        if ((*iter)->getType() == type)
            detachObject(*iter);
        delete (*iter);
    }
    isLinked_ = false;
}

bool Shader::linkProgram() {
    isLinked_ = false;
    glLinkProgram(id_);
    GLint check = 0;
    glGetProgramiv(id_, GL_LINK_STATUS, &check);
    if (check)
        isLinked_ = true;

    return isLinked_;
}

string Shader::getLinkerLog() const {
    GLint len;
    glGetProgramiv(id_, GL_INFO_LOG_LENGTH , &len);

    if (len > 1) {
        GLchar* log = new GLchar[len];
        if (log == 0)
            return "Memory allocation for log failed!";
        GLsizei l;  // length returned
        glGetProgramInfoLog(id_, len, &l, log);
        string retStr(log);
        delete[] log;
        return retStr;
    }

    return "";
}

bool Shader::rebuild() {
    if (isLinked_) {
        // program is already linked: detach and re-attach everything
        for (ShaderObjects::iterator iter = objects_.begin(); iter != objects_.end(); ++iter) {
            glDetachShader(id_, (*iter)->id_);
            (*iter)->uploadSource();
            if (!(*iter)->compileShader()) {
                LERROR("Failed to compile shader object.");
                LERROR("Compiler Log: \n" << (*iter)->getCompilerLog());
                return false;
            }

            glAttachShader(id_, (*iter)->id_);
        }
    }
    isLinked_ = false;
    glLinkProgram(id_);
    GLint check = 0;
    glGetProgramiv(id_, GL_LINK_STATUS, &check);

    if (check) {
        isLinked_ = true;
        return true;
    } else {
        LERROR("Shader::rebuild(): Failed to link shader." );
        LERROR("Linker Log: \n" << getLinkerLog());
        return false;
    }
}

bool Shader::rebuildFromFile() {
    bool result = true;

    for (ShaderObjects::iterator iter = objects_.begin(); iter != objects_.end(); ++iter)
        result &= (*iter)->rebuildFromFile();

    result &= rebuild();

    return result;
}

void Shader::setHeaders(const string& customHeader) {
    for (ShaderObjects::iterator iter = objects_.begin(); iter != objects_.end(); ++iter) {
        (*iter)->setHeader(customHeader);
    }
}

void Shader::bindFragDataLocation(GLuint colorNumber, std::string name) {
    if (GpuCaps.getShaderVersion() >= GpuCapabilities::GlVersion::SHADER_VERSION_130) {
schultezub's avatar
schultezub committed
592
        glBindFragDataLocation(id_, colorNumber, name.c_str());
schultezub's avatar
schultezub committed
593 594 595 596 597 598 599 600
    }
}

void Shader::load(const string& filename, const string& customHeader) throw (Exception) {
    return loadSeparate(filename + ".vert", "", filename + ".frag", customHeader);
}

void Shader::loadSeparate(const string& vert_filename, const string& geom_filename,
601
                          const string& frag_filename, const string& customHeader, const std::string& customGlslVersion)
schultezub's avatar
schultezub committed
602 603 604 605 606 607 608 609 610 611 612 613
                          throw (Exception)
{
    ShaderObject* frag = 0;
    ShaderObject* vert = 0;
    ShaderObject* geom = 0;

    if (!vert_filename.empty()) {
        vert = new ShaderObject(vert_filename, ShaderObject::VERTEX_SHADER);

        if (!customHeader.empty()) {
            vert->setHeader(customHeader);
        }
614 615 616
        if (!customGlslVersion.empty()) {
            vert->setCustomGlslVersion(customGlslVersion);
        }
schultezub's avatar
schultezub committed
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642

        try {
            vert->loadSourceFromFile(vert_filename);
        }
        catch (const Exception& e) {
            LDEBUG("Failed to load vertex shader " << vert_filename << ": " << e.what());
            delete vert;
            throw Exception("Failed to load vertex shader " + vert_filename + ": " + e.what());
        }

        vert->uploadSource();

        if (!vert->compileShader()) {
            LERROR("Failed to compile vertex shader " << vert_filename);
            LERROR("Compiler Log: \n" << vert->getCompilerLog());
            delete vert;
            throw Exception("Failed to compile vertex shader: " + vert_filename);
        }
    }

    if (!geom_filename.empty()) {
        geom = new ShaderObject(geom_filename, ShaderObject::GEOMETRY_SHADER);

        if (!customHeader.empty()) {
            geom->setHeader(customHeader);
        }
643 644 645
        if (!customGlslVersion.empty()) {
            geom->setCustomGlslVersion(customGlslVersion);
        }
schultezub's avatar
schultezub committed
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672

        try {
            geom->loadSourceFromFile(geom_filename);
        }
        catch (const Exception& e) {
            LDEBUG("Failed to load geometry shader " << geom_filename << ": " << e.what());
            delete vert;
            delete geom;
            throw Exception("Failed to load geometry shader " + geom_filename + ": " + e.what());
        }

        geom->uploadSource();
        if (!geom->compileShader()) {
            LERROR("Failed to compile geometry shader " << geom_filename);
            LERROR("Compiler Log: \n" << geom->getCompilerLog());
            delete vert;
            delete geom;
            throw Exception("Failed to compile geometry shader: " + geom_filename);
        }
    }

    if (!frag_filename.empty()) {
        frag = new ShaderObject(frag_filename, ShaderObject::FRAGMENT_SHADER);

        if (!customHeader.empty()) {
            frag->setHeader(customHeader);
        }
673 674 675
        if (!customGlslVersion.empty()) {
            frag->setCustomGlslVersion(customGlslVersion);
        }
schultezub's avatar
schultezub committed
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852

        try {
            frag->loadSourceFromFile(frag_filename);
        }
        catch (const Exception& e) {
            LDEBUG("Failed to load fragment shader " << frag_filename);
            delete frag;
            delete geom;
            delete vert;
            throw Exception("Failed to load fragment shader " + frag_filename + ": " + e.what());
        }

        if (GpuCaps.getShaderVersion() >= GpuCapabilities::GlVersion::SHADER_VERSION_130)
            bindFragDataLocation(0, "FragData0");

        frag->uploadSource();

        if (!frag->compileShader()) {
            LERROR("Failed to compile fragment shader " << frag_filename);
            LERROR("Compiler Log: \n" << frag->getCompilerLog());
            delete vert;
            delete geom;
            delete frag;
            throw Exception("Failed to compile fragment shader: " + frag_filename);
        }
    }

    // Attach ShaderObjects, dtor will take care of freeing them
    if (frag)
        attachObject(frag);
    if (vert)
        attachObject(vert);
    if (geom)
        attachObject(geom);

    if (!linkProgram()) {
        LERROR("Failed to link shader (" << vert_filename << ","  << frag_filename << "," << geom_filename << ")");
        if (vert) {
            LERROR(vert->filename_ << " Vertex shader compiler log: \n" << vert->getCompilerLog());
            detachObject(vert);
            delete vert;
        }
        if (geom) {
            LERROR(geom->filename_ << " Geometry shader compiler log: \n" << geom->getCompilerLog());
            detachObject(geom);
            delete geom;
        }
        if (frag) {
            LERROR(frag->filename_ << " Fragment shader compiler log: \n" << frag->getCompilerLog());
            detachObject(frag);
            delete frag;
        }

        LERROR("Linker Log: \n" << getLinkerLog());
        throw Exception("Failed to link shader (" + vert_filename + "," + frag_filename + "," + geom_filename + ")");
    }


    if (vert && vert->getCompilerLog().size() > 1) {
        LDEBUG("Vertex shader compiler log for file '" << vert_filename
               << "': \n" << vert->getCompilerLog());
    }
    if (geom && geom->getCompilerLog().size() > 1) {
        LDEBUG("Geometry shader compiler log for file '" << geom_filename
               << "': \n" << geom->getCompilerLog());
    }
    if (frag && frag->getCompilerLog().size() > 1) {
        LDEBUG("Fragment shader compiler log for file '" << frag_filename
               << "': \n" << frag->getCompilerLog());
    }

    if (getLinkerLog().size() > 1) {
        LDEBUG("Linker log for '" << vert_filename << "' and '"
               << frag_filename << "' and '"
               << geom_filename << "': \n" << getLinkerLog());
    }
}

GLint Shader::getUniformLocation(const string& name) {
    GLint l;
    l = glGetUniformLocation(id_, name.c_str());
    if (l == -1 && !ignoreError_)
        LWARNING("Failed to locate uniform Location: " << name);
    return l;
}

void Shader::setIgnoreUniformLocationError(bool ignoreError) {
    ignoreError_ = ignoreError;
}

bool Shader::getIgnoreUniformLocationError() {
    return ignoreError_;
}

// Floats
bool Shader::setUniform(const string& name, GLfloat value) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform1f(l, value);
    return true;
}

bool Shader::setUniform(const string& name, GLfloat v1, GLfloat v2) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform2f(l, v1, v2);
    return true;
}

bool Shader::setUniform(const string& name, GLfloat v1, GLfloat v2, GLfloat v3) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform3f(l, v1, v2, v3);
    return true;
}

bool Shader::setUniform(const string& name, GLfloat v1, GLfloat v2, GLfloat v3, GLfloat v4) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform4f(l, v1, v2, v3, v4);
    return true;
}

bool Shader::setUniform(const string& name, GLfloat* v, int count) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform1fv(l, count, v);
    return true;
}

// Integers
bool Shader::setUniform(const string& name, GLint value) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform1i(l, value);
    return true;
}

bool Shader::setUniform(const string& name, GLint v1, GLint v2) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform2i(l, v1, v2);
    return true;
}

bool Shader::setUniform(const string& name, GLint v1, GLint v2, GLint v3) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform3i(l, v1, v2, v3);
    return true;
}

bool Shader::setUniform(const string& name, GLint v1, GLint v2, GLint v3, GLint v4) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform4i(l, v1, v2, v3, v4);
    return true;
}

bool Shader::setUniform(const string& name, GLint* v, int count) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform1iv(l, count, v);
    return true;
}


853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
// Unsigned Integers
bool Shader::setUniform(const string& name, GLuint value) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform1ui(l, value);
    return true;
}

bool Shader::setUniform(const string& name, GLuint v1, GLuint v2) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform2ui(l, v1, v2);
    return true;
}

bool Shader::setUniform(const string& name, GLuint v1, GLuint v2, GLuint v3) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform3ui(l, v1, v2, v3);
    return true;
}

bool Shader::setUniform(const string& name, GLuint v1, GLuint v2, GLuint v3, GLuint v4) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform4ui(l, v1, v2, v3, v4);
    return true;
}

bool Shader::setUniform(const string& name, GLuint* v, int count) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    glUniform1uiv(l, count, v);
    return true;
}



schultezub's avatar
schultezub committed
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
bool Shader::setUniform(const string& name, bool value) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    setUniform(l, static_cast<GLint>(value));
    return true;
}

bool Shader::setUniform(const string& name, bool v1, bool v2) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    setUniform(l, static_cast<GLint>(v1), static_cast<GLint>(v2));
    return true;
}

bool Shader::setUniform(const string& name, bool v1, bool v2, bool v3) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    setUniform(l, static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3));
    return true;
}

bool Shader::setUniform(const string& name, bool v1, bool v2, bool v3, bool v4) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    setUniform(l, static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3), static_cast<GLint>(v4));
    return true;
}

bool Shader::setUniform(const string& name, GLboolean* v, int count) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    GLint* vector = new GLint[count];
    for (int i=0; i < count; i++)
        vector[i] = static_cast<GLint>( v[i] );
    glUniform1iv(l, count, vector);
    delete[] vector;
    return true;
}

// Vectors
bool Shader::setUniform(const string& name, const Vector2f& value) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    setUniform(l, value);
    return true;
}

bool Shader::setUniform(const string& name, Vector2f* vectors, GLsizei count) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    //TODO: use the adress directly, without copying, same below. joerg
    GLfloat* values = new GLfloat[2*count];
    for (int i=0; i < count; i++){
        values[2*i] = vectors[i].x;
        values[2*i+1] = vectors[i].y;
    }
    glUniform2fv(l, count, values);
    delete[] values;
    return true;
}

bool Shader::setUniform(const string& name, const Vector3f& value) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    setUniform(l, value);
    return true;
}

bool Shader::setUniform(const string& name, Vector3f* vectors, GLsizei count) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    GLfloat* values = new GLfloat[3*count];
    for (int i=0; i < count; i++) {
        values[3*i] = vectors[i].x;
        values[3*i+1] = vectors[i].y;
        values[3*i+2] = vectors[i].z;
    }
    glUniform3fv(l, count, values);
    delete[] values;
    return true;
}

bool Shader::setUniform(const string& name, const Vector4f& value) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    setUniform(l, value);
    return true;
}

bool Shader::setUniform(const string& name, Vector4f* vectors, GLsizei count) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    GLfloat* values = new GLfloat[4*count];
    for (int i=0; i < count; i++) {
        values[4*i] = vectors[i].x;
        values[4*i+1] = vectors[i].y;
        values[4*i+2] = vectors[i].z;
        values[4*i+3] = vectors[i].a;
    }
    glUniform4fv(l, count, values);
    delete[] values;
    return true;
}

bool Shader::setUniform(const string& name, const ivec2& value) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    setUniform(l, value);
    return true;
}

bool Shader::setUniform(const string& name, ivec2* vectors, GLsizei count) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    GLint* values = new GLint[2*count];
    for (int i=0; i < count; i++) {
        values[2*i] = vectors[i].x;
        values[2*i+1] = vectors[i].y;
    }
    glUniform2iv(l, count, values);
    delete[] values;
    return true;
}

bool Shader::setUniform(const string& name, const ivec3& value) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    setUniform(l, value);
    return true;
}

bool Shader::setUniform(const string& name, ivec3* vectors, GLsizei count) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    GLint* values = new GLint[3*count];
    for (int i=0; i < count; i++) {
        values[3*i] = vectors[i].x;
        values[3*i+1] = vectors[i].y;
        values[3*i+2] = vectors[i].z;
    }
    glUniform3iv(l, count, values);
    delete[] values;
    return true;
}

bool Shader::setUniform(const string& name, const ivec4& value) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    setUniform(l, value);
    return true;
}

bool Shader::setUniform(const string& name, ivec4* vectors, GLsizei count) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    GLint* values = new GLint[4*count];
    for (int i=0; i < count; i++) {
        values[4*i] = vectors[i].x;
        values[4*i+1] = vectors[i].y;
        values[4*i+2] = vectors[i].z;
        values[4*i+3] = vectors[i].a;
    }
    glUniform4iv(l, count, values);
    delete[] values;
    return true;
}

// Note: Matrix is transposed by OpenGL
bool Shader::setUniform(const string& name, const Matrix2f& value, bool transpose) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    setUniform(l, value, transpose);
    return true;
}

bool Shader::setUniform(const string& name, const Matrix3f& value, bool transpose) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    setUniform(l, value, transpose);
    return true;
}

bool Shader::setUniform(const string& name, const Matrix4f& value, bool transpose) {
    GLint l = getUniformLocation(name);
    if (l == -1)
        return false;
    setUniform(l, value, transpose);
    return true;
}

// No location lookup
//
// Floats
void Shader::setUniform(GLint l, GLfloat value) {
    glUniform1f(l, value);
}

void Shader::setUniform(GLint l, GLfloat v1, GLfloat v2) {
    glUniform2f(l, v1, v2);
}

void Shader::setUniform(GLint l, GLfloat v1, GLfloat v2, GLfloat v3) {
    glUniform3f(l, v1, v2, v3);
}

void Shader::setUniform(GLint l, GLfloat v1, GLfloat v2, GLfloat v3, GLfloat v4) {
    glUniform4f(l, v1, v2, v3, v4);
}

// Integers
void Shader::setUniform(GLint l, GLint value) {
    glUniform1i(l, value);
}

void Shader::setUniform(GLint l, GLint v1, GLint v2) {
    glUniform2i(l, v1, v2);
}

void Shader::setUniform(GLint l, GLint v1, GLint v2, GLint v3) {
    glUniform3i(l, v1, v2, v3);
}

void Shader::setUniform(GLint l, GLint v1, GLint v2, GLint v3, GLint v4) {
    glUniform4i(l, v1, v2, v3, v4);
}

// Vectors
void Shader::setUniform(GLint l, const Vector2f& value) {
    glUniform2fv(l, 1, value.elem);
}

void Shader::setUniform(GLint l, const Vector3f& value) {
    glUniform3fv(l, 1, value.elem);
}

void Shader::setUniform(GLint l, const Vector4f& value) {
    glUniform4fv(l, 1, value.elem);
}

void Shader::setUniform(GLint l, const ivec2& value) {
    glUniform2i(l, static_cast<GLint>(value.x), static_cast<GLint>(value.y));
}

void Shader::setUniform(GLint l, const ivec3& value) {
    glUniform3i(l, static_cast<GLint>(value.x), static_cast<GLint>(value.y), static_cast<GLint>(value.z));
}

void Shader::setUniform(GLint l, const ivec4& value) {
    glUniform4i(l, static_cast<GLint>(value.x), static_cast<GLint>(value.y),
                static_cast<GLint>(value.z), static_cast<GLint>(value.w));
}

void Shader::setUniform(GLint l, const Matrix2f& value, bool transpose) {
    glUniformMatrix2fv(l, 1, !transpose, value.elem);
}

void Shader::setUniform(GLint l, const Matrix3f& value, bool transpose) {
    glUniformMatrix3fv(l, 1, !transpose, value.elem);
}

void Shader::setUniform(GLint l, const Matrix4f& value, bool transpose) {
    glUniformMatrix4fv(l, 1, !transpose, value.elem);
}

// Attributes
//
// 1 component
void Shader::setAttribute(GLint index, GLfloat v1) {
    glVertexAttrib1f(index, v1);
}

void Shader::setAttribute(GLint index, GLshort v1) {
    glVertexAttrib1s(index, v1);
}

void Shader::setAttribute(GLint index, GLdouble v1) {
    glVertexAttrib1d(index, v1);
}

// 2 components
void Shader::setAttribute(GLint index, GLfloat v1, GLfloat v2) {
    glVertexAttrib2f(index, v1, v2);
}

void Shader::setAttribute(GLint index, GLshort v1, GLshort v2) {
    glVertexAttrib2s(index, v1, v2);
}

void Shader::setAttribute(GLint index, GLdouble v1, GLdouble v2) {
    glVertexAttrib2d(index, v1, v2);
}

// 3 components
void Shader::setAttribute(GLint index, GLfloat v1, GLfloat v2, GLfloat v3) {
    glVertexAttrib3f(index, v1, v2, v3);
}

void Shader::setAttribute(GLint index, GLshort v1, GLshort v2, GLshort v3) {
    glVertexAttrib3s(index, v1, v2, v3);
}

void Shader::setAttribute(GLint index, GLdouble v1, GLdouble v2, GLdouble v3) {
    glVertexAttrib3d(index, v1, v2, v3);
}

// 4 components
void Shader::setAttribute(GLint index, GLfloat v1, GLfloat v2, GLfloat v3, GLfloat v4) {
    glVertexAttrib4f(index, v1, v2, v3, v4);
}

void Shader::setAttribute(GLint index, GLshort v1, GLshort v2, GLshort v3, GLshort v4) {
    glVertexAttrib4s(index, v1, v2, v3, v4);
}

void Shader::setAttribute(GLint index, GLdouble v1, GLdouble v2, GLdouble v3, GLdouble v4) {
    glVertexAttrib4d(index, v1, v2, v3, v4);
}

// For vectors
void Shader::setAttribute(GLint index, const Vector2f& v) {
    glVertexAttrib2fv(index, v.elem);
}

void Shader::setAttribute(GLint index, const Vector3f& v) {
    glVertexAttrib3fv(index, v.elem);
}

void Shader::setAttribute(GLint index, const Vector4f& v) {
    glVertexAttrib4fv(index, v.elem);
}

void Shader::setAttribute(GLint index, const Vector2d& v) {
    glVertexAttrib2dv(index, v.elem);
}

void Shader::setAttribute(GLint index, const Vector3d& v) {
    glVertexAttrib3dv(index, v.elem);
}

void Shader::setAttribute(GLint index, const Vector4d& v) {
    glVertexAttrib4dv(index, v.elem);
}

void Shader::setAttribute(GLint index, const Vector2<GLshort>& v) {
    glVertexAttrib2sv(index, v.elem);
}

void Shader::setAttribute(GLint index, const Vector3<GLshort>& v) {
    glVertexAttrib3sv(index, v.elem);
}

void Shader::setAttribute(GLint index, const Vector4<GLshort>& v) {
    glVertexAttrib4sv(index, v.elem);
}

void Shader::setAttribute(GLint index, const Vector4<GLint>& v) {
    glVertexAttrib4iv(index, v.elem);
}

void Shader::setAttribute(GLint index, const Vector4<GLbyte>& v) {
    glVertexAttrib4bv(index, v.elem);
}

void Shader::setAttribute(GLint index, const Vector4<GLubyte>& v) {
    glVertexAttrib4ubv(index, v.elem);
}

void Shader::setAttribute(GLint index, const Vector4<GLushort>& v) {
    glVertexAttrib4usv(index, v.elem);
}

void Shader::setAttribute(GLint index, const Vector4<GLuint>& v) {
    glVertexAttrib4uiv(index, v.elem);
}

// Attribute locations
void Shader::setAttributeLocation(GLuint index, const std::string& name) {
    glBindAttribLocation(id_, index, name.c_str());
}

GLint Shader::getAttributeLocation(const string& name) {
    GLint l;
    l = glGetAttribLocation(id_, name.c_str());
    if (l == -1)
        LERROR("Failed to locate attribute Location: " << name);
    return l;
}

// Normalized attributes
void Shader::setNormalizedAttribute(GLint index, GLubyte v1, GLubyte v2, GLubyte v3, GLubyte v4) {
    glVertexAttrib4Nub(index, v1, v2, v3, v4);
}

void Shader::setNormalizedAttribute(GLint index, const Vector4<GLbyte>& v) {
    glVertexAttrib4Nbv(index, v.elem);
}

void Shader::setNormalizedAttribute(GLint index, const Vector4<GLshort>& v) {
    glVertexAttrib4Nsv(index, v.elem);
}

void Shader::setNormalizedAttribute(GLint index, const Vector4<GLint>& v) {
    glVertexAttrib4Niv(index, v.elem);
}

// Unsigned version
void Shader::setNormalizedAttribute(GLint index, const Vector4<GLubyte>& v) {
    glVertexAttrib4Nubv(index, v.elem);
}

void Shader::setNormalizedAttribute(GLint index, const Vector4<GLushort>& v) {
    glVertexAttrib4Nusv(index, v.elem);
}

void Shader::setNormalizedAttribute(GLint index, const Vector4<GLuint>& v) {
    glVertexAttrib4Nuiv(index, v.elem);
}

1333 1334
bool Shader::selectSubroutine(ShaderObject::ShaderType type, const std::string& subroutineName) {
    GLuint index = glGetSubroutineIndex(id_, type, subroutineName.c_str());
1335
    if (index == GL_INVALID_INDEX) {
1336 1337 1338 1339 1340 1341 1342
        LWARNING("Failed to locate subroutine Location: " << subroutineName);
        return false;
    }
    glUniformSubroutinesuiv(type, 1, &index);
    return true;
}

schultezub's avatar
schultezub committed
1343 1344
//------------------------------------------------------------------------------

1345
const string ShaderManager::loggerCat_("cgt.Shader.Manager");
schultezub's avatar
schultezub committed
1346 1347 1348 1349 1350

ShaderManager::ShaderManager()
  : ResourceManager<Shader>(false)
{}

1351 1352
Shader* ShaderManager::load(const std::string& vertFilename, const std::string& fragFilename, const std::string& customHeader) throw (Exception) {
    return loadWithCustomGlslVersion(vertFilename, "", fragFilename, customHeader, "");
schultezub's avatar
schultezub committed
1353 1354
}

1355 1356
Shader* ShaderManager::load(const std::string& vertFilename, const std::string& geomFilename, const std::string& fragFilename, const std::string& customHeader) throw(Exception) {
    return loadWithCustomGlslVersion(vertFilename, geomFilename, fragFilename, customHeader, "");
schultezub's avatar
schultezub committed
1357 1358
}

1359
Shader* ShaderManager::loadWithCustomGlslVersion(const std::string& vertFilename, const std::string& geomFilename, const std::string& fragFilename, const std::string& customHeader, const std::string& customGlslVersion) throw(Exception) {
1360
    //LDEBUG("Loading files " << vertFilename << " and " << fragFilename);
schultezub's avatar
schultezub committed
1361 1362 1363 1364 1365 1366
    if (!GpuCaps.areShadersSupported()) {
        LERROR("Shaders are not supported.");
        throw Exception("Shaders are not supported.");
    }

    // create a somewhat unique identifier for this shader triple
1367
    string identifier = vertFilename + "#" +  fragFilename + "#" + geomFilename;
schultezub's avatar
schultezub committed
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378

    if (isLoaded(identifier)) {
        LDEBUG("Shader already loaded. Increase usage count.");
        increaseUsage(identifier);
        return get(identifier);
    }

    Shader* shdr = new Shader();

    // searching in all paths for every shader
    string vert_completeFilename;
1379 1380
    if (!vertFilename.empty())
        vert_completeFilename = completePath(vertFilename);
schultezub's avatar
schultezub committed
1381 1382

    string geom_completeFilename;
1383 1384
    if (!geomFilename.empty())
        geom_completeFilename = completePath(geomFilename);
schultezub's avatar
schultezub committed
1385 1386

    string frag_completeFilename;
1387 1388
    if (!fragFilename.empty())
        frag_completeFilename = completePath(fragFilename);
schultezub's avatar
schultezub committed
1389 1390 1391 1392

    // loading and linking found shaders
    try {
        shdr->loadSeparate(vert_completeFilename, geom_completeFilename,
1393 1394
            frag_completeFilename, customHeader, customGlslVersion);

schultezub's avatar
schultezub committed
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
        // register even when caching is disabled, needed for rebuildFromFile()
        reg(shdr, identifier);

        return shdr;
    }
    catch (const Exception& /*e*/) {
        delete shdr;
        throw;
    }
}

bool ShaderManager::rebuildAllShadersFromFile() {
    bool result = true;

    for (std::map<Shader*, ResourceManager<Shader>::Resource*>::iterator iter = resourcesByPtr_.begin();
         iter != resourcesByPtr_.end(); ++iter)
    {
        result &= iter->first->rebuildFromFile();
    }

    return result;
}

1418

schultezub's avatar
schultezub committed
1419
} // namespace