ShaderGenerator.cc 81.6 KB
Newer Older
Jan Möbius's avatar
Jan Möbius committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 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 67 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 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 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
/*===========================================================================*\
 *                                                                           *
 *                              OpenFlipper                                  *
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
 *           Department of Computer Graphics and Multimedia                  *
 *                          All rights reserved.                             *
 *                            www.openflipper.org                            *
 *                                                                           *
 *---------------------------------------------------------------------------*
 * This file is part of OpenFlipper.                                         *
 *---------------------------------------------------------------------------*
 *                                                                           *
 * Redistribution and use in source and binary forms, with or without        *
 * modification, are permitted provided that the following conditions        *
 * are met:                                                                  *
 *                                                                           *
 * 1. Redistributions of source code must retain the above copyright notice, *
 *    this list of conditions and the following disclaimer.                  *
 *                                                                           *
 * 2. Redistributions in binary form must reproduce the above copyright      *
 *    notice, this list of conditions and the following disclaimer in the    *
 *    documentation and/or other materials provided with the distribution.   *
 *                                                                           *
 * 3. Neither the name of the copyright holder nor the names of its          *
 *    contributors may be used to endorse or promote products derived from   *
 *    this software without specific prior written permission.               *
 *                                                                           *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       *
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A           *
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,  *
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,       *
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR        *
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    *
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      *
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
 *   $Revision$                                                       *
 *   $Author$                                                      *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/

#include "ShaderGenerator.hh"
#include <cstdio>
#include <iostream>

#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QTextStream>
#include <QDateTime>

namespace ACG
{


int ShaderProgGenerator::numRegisteredModifiers_ = 0;
std::vector<ShaderModifier*> ShaderProgGenerator::registeredModifiers_;



// space naming
// OS : object space
// VS : view space
// CS : clip space


ShaderGenerator::Keywords::Keywords()
// attribute request keywords
: macro_requestPosVS("#define SG_REQUEST_POSVS"),
macro_requestPosOS("#define SG_REQUEST_POSOS"),
macro_requestTexcoord("#define SG_REQUEST_TEXCOORD"),
macro_requestVertexColor("#define SG_REQUEST_VERTEXCOLOR"),
macro_requestNormalVS("#define SG_REQUEST_NORMALVS"),
macro_requestNormalOS("#define SG_REQUEST_NORMALOS"),

// generic default attribute input keywords
//  these are extended by the correct input name by the generator for each stage
macro_inputPosVS("SG_INPUT_POSVS"),
macro_inputPosOS("SG_INPUT_POSOS"),
macro_inputPosCS("SG_INPUT_POSCS"),
macro_inputNormalVS("SG_INPUT_NORMALVS"),
macro_inputNormalOS("SG_INPUT_NORMALOS"),
macro_inputTexcoord("SG_INPUT_TEXCOORD"),
macro_inputVertexColor("SG_INPUT_VERTEXCOLOR"),

macro_outputPosVS("SG_OUTPUT_POSVS"),
macro_outputPosOS("SG_OUTPUT_POSOS"),
macro_outputPosCS("SG_OUTPUT_POSCS"),
macro_outputNormalVS("SG_OUTPUT_NORMALVS"),
macro_outputNormalOS("SG_OUTPUT_NORMALOS"),
macro_outputTexcoord("SG_OUTPUT_TEXCOORD"),
macro_outputVertexColor("SG_OUTPUT_VERTEXCOLOR"),

ioPosCS("PosCS"),
ioPosOS("PosOS"),
ioPosVS("PosVS"),
ioNormalVS("NormalVS"),
ioNormalOS("NormalOS"),
ioTexcoord("TexCoord"),
ioColor("Color"),

vs_inputPrefix("in"),
vs_outputPrefix("outVertex"),
tcs_outputPrefix("outTc"),
tes_outputPrefix("outTe"),
gs_outputPrefix("outGeometry"),
fs_outputPrefix("outFragment"),

vs_inputPosition(vs_inputPrefix + "Position"),
vs_inputNormal(vs_inputPrefix + "Normal"),
vs_inputTexCoord(vs_inputPrefix + ioTexcoord),
vs_inputColor(vs_inputPrefix + ioColor),

vs_outputPosCS(vs_outputPrefix + ioPosCS),
vs_outputPosVS(vs_outputPrefix + ioPosVS),
vs_outputPosOS(vs_outputPrefix + ioPosOS),
vs_outputTexCoord(vs_outputPrefix + ioTexcoord),
vs_outputNormalVS(vs_outputPrefix + ioNormalVS),
vs_outputNormalOS(vs_outputPrefix + ioNormalOS),
vs_outputVertexColor(vs_outputPrefix + ioColor),
fs_outputFragmentColor(fs_outputPrefix)
{
}

const ShaderGenerator::Keywords ShaderGenerator::keywords;


ShaderGenerator::ShaderGenerator()
  : version_(150), inputArrays_(false), outputArrays_(false)
{
}

ShaderGenerator::~ShaderGenerator()
{

}


void ShaderGenerator::initVertexShaderIO(const ShaderGenDesc* _desc, const DefaultIODesc* _iodesc)
{
  // set type of IO
  inputArrays_ = false;
  outputArrays_ = false;
  inputPrefix_ = keywords.vs_inputPrefix;   // inputs: inPosition, inTexCoord...
  outputPrefix_ = keywords.vs_outputPrefix; // outputs: outVertexPosition, outVertexTexCoord..

  addInput("vec4", keywords.vs_inputPosition);
  addOutput("vec4", keywords.vs_outputPosCS);

  if (_iodesc->inputNormal_)
    addInput("vec3", keywords.vs_inputNormal);

  if (_desc->textured())
  {
    std::map<size_t,ShaderGenDesc::TextureType>::const_iterator iter = _desc->textureTypes().begin();

    /// TODO Setup for multiple texture coordinates as input
    if (iter->second.type == GL_TEXTURE_3D) {
      addInput("vec3", keywords.vs_inputTexCoord);
      addOutput("vec3", keywords.vs_outputTexCoord);
    } else {
      addInput("vec2", keywords.vs_inputTexCoord);
      addOutput("vec2", keywords.vs_outputTexCoord);
    }
  }

  if (_iodesc->inputColor_)
    addInput("vec4", keywords.vs_inputColor);

  if (_iodesc->passNormalVS_)
179
    addStringToList("vec3 " + keywords.vs_outputNormalVS, &outputs_, _desc->vertexNormalInterpolator + " out ", ";");
Jan Möbius's avatar
Jan Möbius committed
180 181

  if (_iodesc->passNormalOS_)
182
    addStringToList("vec3 " + keywords.vs_outputNormalOS, &outputs_, _desc->vertexNormalInterpolator + " out ", ";");
Jan Möbius's avatar
Jan Möbius committed
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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 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 445 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 477 478 479 480 481 482 483 484 485 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 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 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 643 644 645 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 673 674 675 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

  // vertex color output

  if (_desc->vertexColorsInterpolator.isEmpty())
  {
    QString strColorOut;
    if (_desc->shadeMode == SG_SHADE_FLAT)
    {
      if (!_desc->geometryTemplateFile.isEmpty())
        strColorOut = keywords.vs_outputVertexColor;
      else
      {
        // Bypass the output setter, as we have to set that directly with the flat.
        addStringToList("vec4 " + keywords.vs_outputVertexColor, &outputs_, "flat out ", "; ");
      }
    }
    else if (_desc->shadeMode == SG_SHADE_GOURAUD || _desc->vertexColors || _iodesc->inputColor_)
      strColorOut = keywords.vs_outputVertexColor;

    if (strColorOut.size())
      addOutput("vec4", strColorOut);
  }
  else
    addStringToList("vec4 " + keywords.vs_outputVertexColor, &outputs_, _desc->vertexColorsInterpolator + " out ", ";");



  // handle other requests: normals, positions, texcoords

  if (_iodesc->passPosVS_)
    addOutput("vec4", keywords.vs_outputPosVS);

  if (_iodesc->passPosOS_)
    addOutput("vec4", keywords.vs_outputPosOS);

  if (_iodesc->passTexCoord_ && !_desc->textured())
  {
    // assume 2d texcoords as default
    int texdim = 2;

    if (_desc->texGenMode && _desc->texGenDim > 0 && _desc->texGenDim <= 4 && !_desc->texGenPerFragment)
      texdim = _desc->texGenDim;

    QString texcoordType;
    if (texdim > 1)
      texcoordType.sprintf("vec%i", texdim);
    else
      texcoordType = "float";

    addInput(texcoordType, keywords.vs_inputTexCoord);
    addOutput(texcoordType, keywords.vs_outputTexCoord);
  }


  defineIOAbstraction(_iodesc, true, false);
}

void ShaderGenerator::initTessControlShaderIO(const ShaderGenDesc* _desc, ShaderGenerator* _prevStage, const DefaultIODesc* _iodesc) 
{
  // set type of IO
  inputArrays_ = true;
  outputArrays_ = true;
  inputPrefix_ = _prevStage->outputPrefix_;
  outputPrefix_ = keywords.tcs_outputPrefix; // outputs: outTcPosition, outTcTexCoord..

  matchInputs(_prevStage, true, inputPrefix_, outputPrefix_);

  defineIOAbstraction(_iodesc, false, false);
}

void ShaderGenerator::initTessEvalShaderIO(const ShaderGenDesc* _desc, ShaderGenerator* _prevStage, const DefaultIODesc* _iodesc) 
{
  // set type of IO
  inputArrays_ = true;
  outputArrays_ = false;
  inputPrefix_ = _prevStage->outputPrefix_;
  outputPrefix_ = keywords.tes_outputPrefix; // outputs: outTePosition, outTeTexCoord..

  matchInputs(_prevStage, true, inputPrefix_, outputPrefix_);

  defineIOAbstraction(_iodesc, false, false);
}

void ShaderGenerator::initGeometryShaderIO(const ShaderGenDesc* _desc, ShaderGenerator* _prevStage, const DefaultIODesc* _iodesc) 
{
  // set type of IO
  inputArrays_ = true;
  outputArrays_ = false;
  inputPrefix_ = _prevStage->outputPrefix_;
  outputPrefix_ = keywords.gs_outputPrefix; // outputs: outGeometryPosition, outGeometryTexCoord..

  matchInputs(_prevStage, true, inputPrefix_, outputPrefix_);

  defineIOAbstraction(_iodesc, false, false);
}



void ShaderGenerator::initFragmentShaderIO(const ShaderGenDesc* _desc, ShaderGenerator* _prevStage, const DefaultIODesc* _iodesc)
{
  // set type of IO
  inputArrays_ = false;
  outputArrays_ = false;
  inputPrefix_ = _prevStage->outputPrefix_;
  outputPrefix_ = keywords.fs_outputPrefix;

  matchInputs(_prevStage, false);
  addOutput("vec4", keywords.fs_outputFragmentColor);

  defineIOAbstraction(_iodesc, false, true);
}


void ShaderGenerator::defineIOAbstraction( const DefaultIODesc* _iodesc, bool _vs, bool _fs )
{
  if (_vs)
  {
    // input name abstraction

    addIODefine(keywords.macro_inputPosOS, keywords.vs_inputPosition);

    if (_iodesc->inputTexCoord_)
      addIODefine(keywords.macro_inputTexcoord, keywords.vs_inputTexCoord);

    if (_iodesc->inputNormal_)
      addIODefine(keywords.macro_inputNormalOS, keywords.vs_inputNormal);

    if (_iodesc->inputColor_)
      addIODefine(keywords.macro_inputVertexColor, keywords.vs_inputColor);



    // output name abstraction

    addIODefine(keywords.macro_outputPosCS, keywords.vs_outputPosCS);

    if (_iodesc->passPosVS_)
      addIODefine(keywords.macro_outputPosVS, keywords.vs_outputPosVS);

    if (_iodesc->passPosOS_)
      addIODefine(keywords.macro_outputPosOS, keywords.vs_outputPosOS);

    if (_iodesc->passTexCoord_)
      addIODefine(keywords.macro_outputTexcoord, keywords.vs_outputTexCoord);

    if (_iodesc->passNormalVS_)
      addIODefine(keywords.macro_outputNormalVS, keywords.vs_outputNormalVS);

    if (_iodesc->passNormalOS_)
      addIODefine(keywords.macro_outputNormalOS, keywords.vs_outputNormalOS);

    if (_iodesc->passColor_)
      addIODefine(keywords.macro_outputVertexColor, keywords.vs_outputVertexColor);
  }
  else
  {
    if (_iodesc->passPosVS_)
    {
      addIODefine(keywords.macro_inputPosVS, inputPrefix_ + keywords.ioPosVS);
      if (!_fs)
        addIODefine(keywords.macro_outputPosVS, outputPrefix_ + keywords.ioPosVS);
    }

    if (_iodesc->passPosOS_)
    {
      addIODefine(keywords.macro_inputPosOS, inputPrefix_ + keywords.ioPosOS);
      if (!_fs)
        addIODefine(keywords.macro_outputPosOS, outputPrefix_ + keywords.ioPosOS);
    }

    addIODefine(keywords.macro_inputPosCS, inputPrefix_ + keywords.ioPosCS);
    if (!_fs)
      addIODefine(keywords.macro_outputPosCS, outputPrefix_ + keywords.ioPosCS);

    if (_iodesc->passNormalVS_)
    {
      addIODefine(keywords.macro_inputNormalVS, inputPrefix_ + keywords.ioNormalVS);
      if (!_fs)
        addIODefine(keywords.macro_outputNormalVS, outputPrefix_ + keywords.ioNormalVS);
    }

    if (_iodesc->passNormalOS_)
    {
      addIODefine(keywords.macro_inputNormalOS, inputPrefix_ + keywords.ioNormalOS);
      if (!_fs)
        addIODefine(keywords.macro_outputNormalOS, outputPrefix_ + keywords.ioNormalOS);
    }

    if (_iodesc->passTexCoord_)
    {
      addIODefine(keywords.macro_inputTexcoord, inputPrefix_ + keywords.ioTexcoord);
      if (!_fs)
        addIODefine(keywords.macro_outputTexcoord, outputPrefix_ + keywords.ioTexcoord);
    }

    if (_iodesc->passColor_)
    {
      addIODefine(keywords.macro_inputVertexColor, inputPrefix_ + keywords.ioColor);
      if (!_fs)
        addIODefine(keywords.macro_outputVertexColor, outputPrefix_ + keywords.ioColor);
    }
  }

  
}



void ShaderGenerator::initDefaultUniforms()
{
  addUniform("mat4 g_mWVP" , "  // Projection * Modelview");       // Transforms directly from Object space to NDC
  addUniform("mat4 g_mWV" , "   // Modelview matrix");             // Modelview transforms from Object to World to View coordinates
  addUniform("mat3 g_mWVIT" , " // Modelview inverse transposed"); // Modelview inverse transposed, transforms from view across World into Object coordinates
  addUniform("mat4 g_mP", "     // Projection matrix");            // Projection Matrix

  addUniform("vec3 g_vCamPos");
  addUniform("vec3 g_vCamDir");

  addUniform("vec3 g_cDiffuse");
  addUniform("vec3 g_cAmbient");
  addUniform("vec3 g_cEmissive");
  addUniform("vec3 g_cSpecular");
  addUniform("vec4 g_vMaterial");
  addUniform("vec3 g_cLightModelAmbient");
}


#define ADDLIGHT(x) (sz.sprintf(x"_%d", lightIndex_), addUniform(sz))

void ShaderGenerator::addLight(int lightIndex_, ShaderGenLightType _light)
{
  QString sz;

  ADDLIGHT("vec3 g_cLightDiffuse");
  ADDLIGHT("vec3 g_cLightAmbient");
  ADDLIGHT("vec3 g_cLightSpecular");

  if (_light == SG_LIGHT_POINT ||
    _light == SG_LIGHT_SPOT)
  {
    ADDLIGHT("vec3 g_vLightPos");
    ADDLIGHT("vec3 g_vLightAtten");
  }

  if (_light == SG_LIGHT_DIRECTIONAL ||
    _light == SG_LIGHT_SPOT)
    ADDLIGHT("vec3 g_vLightDir");


  if (_light == SG_LIGHT_SPOT)
    ADDLIGHT("vec2 g_vLightAngleExp");
}



void ShaderGenerator::addStringToList(QString _str, 
                                      QStringList* _arr,
                                      QString _prefix,
                                      QString _postfix)
{
  // Construct the whole string
  QString tmp = _str;

  if (!_str.startsWith(_prefix))
    tmp = _prefix + tmp;

  if (!_str.endsWith(_postfix))
     tmp += _postfix;

  // normalize string
  //  remove tabs, double whitespace
  tmp = tmp.simplified();

  // avoid duplicates
  if (!_arr->contains(tmp))
    _arr->push_back(tmp);

}


void ShaderGenerator::addInput(const QString& _input)
{
  addStringToList(_input, &inputs_, "in ", ";");
}


void ShaderGenerator::addOutput(const QString& _output)
{
  addStringToList(_output, &outputs_, "out ", ";");
}


void ShaderGenerator::addDefine(const QString& _def)
{
  addStringToList(_def, &genDefines_, "#define ");
}


void ShaderGenerator::addIODefine(const QString& _macroName, const QString& _resolvedName)
{
  addDefine(_macroName + QString(" ") + _resolvedName);
}

void ShaderGenerator::addMacros(const QStringList& _macros)
{
  // prepend macros to the "defines" list

  // QStringList reverse_iterator:
  typedef std::reverse_iterator<QStringList::const_iterator> QStringListReverseIterator;
  QStringListReverseIterator rbegin( _macros.end() ), rend( _macros.begin() );

  for (QStringListReverseIterator it = rbegin; it != rend; ++it)
    genDefines_.push_front(*it);
}

bool ShaderGenerator::hasDefine(QString _define) const
{
  if (genDefines_.contains(_define))
    return true;

  // check trimmed strings and with startsWith()

  QString trimmedDef = _define.trimmed();

  for (QStringList::const_iterator it = genDefines_.constBegin(); it != genDefines_.constEnd(); ++it)
  {
    QString trimmedRef = it->trimmed();

    if (trimmedRef.startsWith(trimmedDef))
      return true;
  }

  // also check raw io blocks
  for (QStringList::const_iterator it = rawIO_.constBegin(); it != rawIO_.constEnd(); ++it)
  {
    QString trimmedRef = it->trimmed();

    if (trimmedRef.startsWith(trimmedDef))
      return true;
  }

  return false;
}

void ShaderGenerator::addLayout(QString _def)
{
  addStringToList(_def, &layouts_);
}


void ShaderGenerator::addUniform(QString _uniform, QString _comment)
{
  QString prefix = "";
  if (!_uniform.startsWith("uniform ") && !_uniform.contains(" uniform "))
    prefix = "uniform ";

  addStringToList(_uniform, &uniforms_, prefix, "; " + _comment );
}



void ShaderGenerator::addIOToCode(const QStringList& _cmds)
{
  QString it;
  foreach(it, _cmds)
  {
    code_.push_back(it);
    // append ; eventually

    if (!it.contains(";"))
      code_.back().append(";");
  }
}



void ShaderGenerator::buildShaderCode(QStringList* _pMainCode, const QStringList& _defaultLightingFunctions)
{
  QString glslversion;
  glslversion.sprintf("#version %d", version_);

  code_.push_back(glslversion);

  // provide defines
  QString it;

  foreach(it, genDefines_)
    code_.push_back(it);

  // layouts
  foreach(it, layouts_)
    code_.push_back(it);

  // IO
  addIOToCode(inputs_);
  addIOToCode(outputs_);
  addIOToCode(uniforms_);

  // eventually attach lighting functions if required
  bool requiresLightingCode = false;

  // search for references in imports
  foreach(it, imports_)
  {
    if (it.contains("LitDirLight") || it.contains("LitPointLight") || it.contains("LitSpotLight"))
      requiresLightingCode = true;
  }

  if (requiresLightingCode)
  {
    foreach(it, _defaultLightingFunctions)
      code_.push_back(it);
  }

  // provide imports
  foreach(it, imports_)
    code_.push_back(it);


  // search for lighting references in main code

  if (!requiresLightingCode)
  {
    foreach(it, (*_pMainCode))
    {
      if (it.contains("LitDirLight") || it.contains("LitPointLight") || it.contains("LitSpotLight"))
        requiresLightingCode = true;
    }

    if (requiresLightingCode)
    {
      foreach(it, _defaultLightingFunctions)
        code_.push_back(it);
    }
  }


  // add raw IO code block
  code_.append(rawIO_);


  // main function
  foreach(it, (*_pMainCode))
    code_.push_back(it);
}



void ShaderGenerator::addIncludeFile(QString _fileName)
{
  QFile file(_fileName);

  if (file.open(QIODevice::ReadOnly | QIODevice::Text))
  {
    QTextStream fileStream(&file);
    
    // track source of include files in shader comment
    
    imports_.push_back("// ==============================================================================");
    imports_.push_back(QString("// ShaderGenerator - begin of imported file: ") + _fileName);
    

    while (!fileStream.atEnd())
    {
      QString tmpLine = fileStream.readLine();

      imports_.push_back(tmpLine.simplified());
    }
    
    
    // mark end of include file in comment
    
    imports_.push_back(QString("// ShaderGenerator - end of imported file #include \"") + _fileName);
    imports_.push_back("// ==============================================================================");
    
  }

}



void ShaderGenerator::saveToFile(const char* _fileName)
{
  QFile file(_fileName);
  if (file.open(QIODevice::WriteOnly | QIODevice::Text))
  {
    QTextStream fileStream(&file);

    QString it;
    foreach(it, code_)
      fileStream << it << '\n';
  }
}



const QStringList& ShaderGenerator::getShaderCode()
{
  return code_;
}

void ShaderGenerator::setGLSLVersion( int _version )
{
  version_ = _version;
}

void ShaderGenerator::matchInputs(const ShaderGenerator* _previousShaderStage,
  bool _passToNextStage,
  QString _inputPrefix, 
  QString _outputPrefix)
{
  if (!_previousShaderStage)
  {
    std::cout << "error: ShaderGenerator::matchInputs called without providing input stage" << std::endl;
    return;
  }

  QString it;
  foreach(it, _previousShaderStage->outputs_)
  {
    QString input = it;

    QString outKeyword = "out ";
    QString inKeyword = "in  ";

    // replace first occurrence of "out" with "in"
    input.replace(input.indexOf(outKeyword), outKeyword.size(), inKeyword);

    // special case for array IO

    if (inputArrays_ && !_previousShaderStage->outputArrays_)
    {
      QRegExp alphaNum("[a-zA-Z0-9]");
      int lastNameChar = input.lastIndexOf(alphaNum);
      input.insert(lastNameChar+1, "[]");
//      input.insert(lastNameChar+1, "[gl_in.length()]");
    }


    // add to input list with duplicate check
    addStringToList(input, &inputs_);

    if (_passToNextStage)
    {
      // replace prefixes of in/outputs to avoid name collision

      QString output = input;
      output.replace(output.indexOf(_inputPrefix), _inputPrefix.size(), _outputPrefix);
      output.replace(output.indexOf(inKeyword), inKeyword.size(), outKeyword);

      // take care of arrays
      if (inputArrays_ && !outputArrays_)
      {
        int bracketStart = output.indexOf("[");
        int bracketEnd = output.indexOf("]");
        output.remove(bracketStart, bracketEnd-bracketStart+1);
      }
      else if (!inputArrays_ && outputArrays_)
      {
        QRegExp alphaNum("[a-zA-Z0-9]");
        int lastNameChar = output.lastIndexOf(alphaNum);
        output.insert(lastNameChar+1, "[]");
//        output.insert(lastNameChar+1, "[gl_in.length()]");
      }


      // add to output list with duplicate check
      addStringToList(output, &outputs_);
    }
  }
}

int ShaderGenerator::getNumOutputs() const
{
  return outputs_.size();
}

QString ShaderGenerator::getOutputName(int _id) const
{
  QString output = outputs_.at(_id);

  output.remove(";");
  output.remove("out ");

  int bracketStart = output.indexOf("[");
  int bracketEnd = output.lastIndexOf("]");

  if (bracketStart >= 0)
    output.remove(bracketStart, bracketEnd-bracketStart+1);

  // decompose output declaration
  QStringList decompOutput = output.split(" ");
  return decompOutput.last();
}

int ShaderGenerator::getNumInputs() const
{
  return inputs_.size();
}

QString ShaderGenerator::getInputName(int _id) const
{
  QString input = inputs_.at(_id);

  input.remove(";");
  input.remove("out ");
  
  int bracketStart = input.indexOf("[");
  int bracketEnd = input.lastIndexOf("]");

  if (bracketStart >= 0)
    input.remove(bracketStart, bracketEnd-bracketStart+1);

  // decompose output declaration
  QStringList decompInput = input.split(" ");
  return decompInput.last();
}

QString ShaderGenerator::getIOMapName(int _inId) const
{
  QString inputName = getInputName(_inId);

  // output name = input name with swapped prefix
  QString outputName = inputName;
  outputName.replace(outputName.indexOf(inputPrefix_), inputPrefix_.size(), outputPrefix_);

  return outputName;
}


ShaderGenerator::DefaultIODesc::DefaultIODesc()
  : inputTexCoord_(false),
  inputColor_(false),
  inputNormal_(false),
  passPosVS_(false), passPosOS_(false), 
  passTexCoord_(false), 
  passColor_(false),
  passNormalVS_(false), passNormalOS_(false)
{
}




QString ShaderProgGenerator::shaderDir_;
QStringList ShaderProgGenerator::lightingCode_;


ShaderProgGenerator::ShaderProgGenerator( const ShaderGenDesc* _desc )
832
  : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0)
Jan Möbius's avatar
Jan Möbius committed
833 834 835 836 837
{
  init(_desc, (ShaderModifier**)0, 0);
}

ShaderProgGenerator::ShaderProgGenerator( const ShaderGenDesc* _desc, const unsigned int* _modifierIDs, unsigned int _numActiveMods )
838
  : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0)
Jan Möbius's avatar
Jan Möbius committed
839 840 841 842 843
{
  init(_desc, _modifierIDs, _numActiveMods);
}

ShaderProgGenerator::ShaderProgGenerator(const ShaderGenDesc* _desc, const std::vector<unsigned int>& _modifierIDs)
844
  : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0)
Jan Möbius's avatar
Jan Möbius committed
845 846 847 848 849
{
  init(_desc, _modifierIDs.empty() ? 0 : &_modifierIDs[0], (unsigned int)_modifierIDs.size());
}

ShaderProgGenerator::ShaderProgGenerator(const ShaderGenDesc* _desc, const std::vector<unsigned int>* _modifierIDs)
850
  : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0)
Jan Möbius's avatar
Jan Möbius committed
851 852 853 854 855 856
{
  unsigned int numMods = !_modifierIDs || _modifierIDs->empty() ? 0 : (unsigned int)_modifierIDs->size();
  init(_desc, numMods ? &((*_modifierIDs)[0]) : 0, numMods);
}

ShaderProgGenerator::ShaderProgGenerator(const ShaderGenDesc* _desc, ShaderModifier* const* _modifiers, unsigned int _numActiveMods)
857
  : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0)
Jan Möbius's avatar
Jan Möbius committed
858 859 860 861 862
{
  init(_desc, _modifiers, _numActiveMods);
}

ShaderProgGenerator::ShaderProgGenerator(const ShaderGenDesc* _desc, const std::vector<ShaderModifier*>& _modifierIDs)
863
  : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0)
Jan Möbius's avatar
Jan Möbius committed
864 865 866 867 868
{
  init(_desc, _modifierIDs.empty() ? 0 : &(_modifierIDs[0]), (unsigned int)_modifierIDs.size());
}

ShaderProgGenerator::ShaderProgGenerator(const ShaderGenDesc* _desc, const std::vector<ShaderModifier*>* _modifierIDs)
869
  : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0)
Jan Möbius's avatar
Jan Möbius committed
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 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 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
{
  unsigned int numMods = !_modifierIDs || _modifierIDs->empty() ? 0 : (unsigned int)_modifierIDs->size();
  init(_desc, numMods ? &((*_modifierIDs)[0]) : 0, numMods);
}


void ShaderProgGenerator::init( const ShaderGenDesc* _desc, const unsigned int* _modifierIDs, unsigned int _numActiveMods )
{
  if (_modifierIDs && _numActiveMods)
  {
    activeMods_.resize(_numActiveMods);

    for (unsigned int i = 0; i < _numActiveMods; ++i)
      activeMods_[i] = registeredModifiers_[ _modifierIDs[i] ];
  }

  init(_desc, (ShaderModifier**)0, 0);
}

void ShaderProgGenerator::init( const ShaderGenDesc* _desc, ShaderModifier* const* _modifiers, unsigned int _numActiveMods )
{
  // mods provided by renderer are passed via parameters _modifiers, _numActiveMods
  // mods provided by individual render objects are passed via ShaderGenDesc* _desc
  // combine them
  size_t numDescMods = _desc->shaderMods.size();
  size_t numTotalMods = _numActiveMods + numDescMods;
  if (numTotalMods)
  {
    activeMods_.resize(numTotalMods);

    for (size_t i = 0; i < numDescMods; ++i)
    {
      unsigned int modID = _desc->shaderMods[i];
      activeMods_[i] = registeredModifiers_[modID];
    }

    if (_modifiers && _numActiveMods)
    {
      for (unsigned int i = 0; i < _numActiveMods; ++i)
        activeMods_[i + numDescMods] = _modifiers[i];
    }
  }




  if (shaderDir_.isEmpty())
    std::cout << "error: call ShaderProgGenerator::setShaderDir() first!" << std::endl;
  else
  {
    desc_ = *_desc;

    // We need at least version 3.2 or higher to support geometry shaders
    if ( !ACG::openGLVersion(3,2) )
    {
      if (!desc_.geometryTemplateFile.isEmpty())
        std::cerr << "Warning: removing geometry shader from ShaderDesc" << std::endl;

      desc_.geometryTemplateFile.clear();
    }

    // We need at least version 4.0 or higher to support tessellation
    if ( !ACG::openGLVersion(4, 0) )
    {
      if (!desc_.tessControlTemplateFile.isEmpty() || !desc_.tessEvaluationTemplateFile.isEmpty())
        std::cerr << "Warning: removing tessellation shader from ShaderDesc" << std::endl;

      desc_.tessControlTemplateFile.clear();
      desc_.tessEvaluationTemplateFile.clear();
    }

    // adjust glsl version to requirement

    if (!desc_.geometryTemplateFile.isEmpty())
      desc_.version = std::max(desc_.version, 150);

    if (!desc_.tessControlTemplateFile.isEmpty() || !desc_.tessEvaluationTemplateFile.isEmpty())
      desc_.version = std::max(desc_.version, 400);


    loadLightingFunctions();

    generateShaders();
  }
}


ShaderProgGenerator::~ShaderProgGenerator(void)
{
  delete vertex_;
  delete fragment_;
  delete geometry_;
  delete tessControl_;
  delete tessEval_;
}



bool ShaderProgGenerator::loadStringListFromFile(QString _fileName, QStringList* _out)
{
  bool success = false;

  QString absFilename = getAbsFilePath(_fileName);


  QFile file(absFilename);

  if (file.open(QIODevice::ReadOnly | QIODevice::Text))
  {
    if (!file.isReadable())
      std::cout << "error: unreadable file -> \"" << absFilename.toStdString() << "\"" << std::endl;
    else
    {
      QTextStream filestream(&file);

      while (!filestream.atEnd())
      {
        QString szLine = filestream.readLine();
        _out->push_back(szLine.trimmed());
      }

      success = true;
    }

    file.close();
  }
  else
    std::cout << "error: " << file.errorString().toStdString() << " -> \"" << absFilename.toStdString() << "\"" << std::endl;

  return success;
}


void ShaderProgGenerator::loadLightingFunctions()
{
  if (lightingCode_.size()) return;
  
  static const QString lightingCodeFile = "ShaderGen/SG_LIGHTING.GLSL";

  QString fileName = shaderDir_ + QDir::separator() + QString(lightingCodeFile);

  lightingCode_.push_back("// ==============================================================================");
  lightingCode_.push_back(QString("// ShaderGenerator - default lighting functions imported from file: ") + fileName);
  
  
  // load shader code from file
  loadStringListFromFile(fileName, &lightingCode_);
  
  lightingCode_.push_back(QString("// ShaderGenerator - end of default lighting functions"));
  lightingCode_.push_back("// ==============================================================================");
}



void ShaderProgGenerator::initGenDefines(ShaderGenerator* _gen)
{
  switch (desc_.shadeMode)
  {
  case SG_SHADE_GOURAUD:
    _gen->addDefine("SG_GOURAUD 1"); break;
  case SG_SHADE_FLAT:
    _gen->addDefine("SG_FLAT 1"); break;
  case SG_SHADE_UNLIT:
    _gen->addDefine("SG_UNLIT 1"); break;
  case SG_SHADE_PHONG:
    _gen->addDefine("SG_PHONG 1"); break;

  default:
    std::cout << __FUNCTION__ << " -> unknown shade mode: " << desc_.shadeMode << std::endl;
  }

  if (desc_.textured())
    _gen->addDefine("SG_TEXTURED 1");

  if (desc_.vertexColors)
    _gen->addDefine("SG_VERTEX_COLOR 1");

//  if (desc_.shadeMode != SG_SHADE_UNLIT)
  if (ioDesc_.passNormalVS_)
    _gen->addDefine("SG_NORMALS 1");

  if (ioDesc_.passPosVS_)
    _gen->addDefine("SG_POSVS 1");

  if (ioDesc_.passPosOS_)
    _gen->addDefine("SG_POSOS 1");

  // # lights define
  QString strNumLights;
  strNumLights.sprintf("SG_NUM_LIGHTS %d", desc_.numLights);
  _gen->addDefine(strNumLights);

  // light types define
  const char* lightTypeNames[] = {"SG_LIGHT_DIRECTIONAL",
    "SG_LIGHT_POINT", "SG_LIGHT_SPOT"};

  for (int i = 0; i < 3; ++i)
    _gen->addDefine(lightTypeNames[i]);


  for (int i = 0; i < desc_.numLights; ++i)
  {
    QString strLightType;
    strLightType.sprintf("SG_LIGHT_TYPE_%d %s", i, lightTypeNames[desc_.lightTypes[i]]);
    _gen->addDefine(strLightType);
  }

  _gen->addDefine("SG_ALPHA g_vMaterial.y");


  _gen->addMacros(desc_.macros);
}




void ShaderProgGenerator::buildVertexShader()
{
  delete vertex_;

  vertex_  = new ShaderGenerator();
  vertex_->setGLSLVersion(desc_.version);

  vertex_->initVertexShaderIO(&desc_, &ioDesc_);

  vertex_->initDefaultUniforms();


  if (desc_.texGenDim && (desc_.texGenMode == GL_OBJECT_LINEAR || desc_.texGenMode == GL_EYE_LINEAR) && !desc_.texGenPerFragment)
  {
    // application has to provide texture projection planes
    QString uniformDecl = "vec4 g_vTexGenPlane";
    if (desc_.texGenDim > 1)
      uniformDecl += "[" + QString::number(desc_.texGenDim) + "]";
    vertex_->addUniform(uniformDecl, " // texture projection planes");
  }


  // apply i/o modifiers
  for (size_t i = 0; i < activeMods_.size(); ++i)
    activeMods_[i]->modifyVertexIO(vertex_);


  initGenDefines(vertex_);



  // IO

  // when to use vertex lights
  if (desc_.shadeMode == SG_SHADE_GOURAUD ||
    desc_.shadeMode == SG_SHADE_FLAT)
  {
    for (int i = 0; i < desc_.numLights; ++i)
      vertex_->addLight(i, desc_.lightTypes[i]);
  }


  // assemble main function
  QStringList mainCode;

  if (!vertexTemplate_.size())
  {
    mainCode.push_back("void main()");
    mainCode.push_back("{");

    addVertexBeginCode(&mainCode);
    addVertexEndCode(&mainCode);

    mainCode.push_back("}");
  }
  else
  {
    // interpret loaded shader template:
    //  import #includes and replace SG_VERTEX_BEGIN/END markers

    QString it;
    foreach(it,vertexTemplate_)
    {
      if (!checkForIncludes(it, vertex_, getPathName(vertexShaderFile_)))
      {
        // str line is no include directive
        // check for SG_ markers

        if (it.contains("SG_VERTEX_BEGIN"))
          addVertexBeginCode(&mainCode);
        else
        {
          if (it.contains("SG_VERTEX_END"))
            addVertexEndCode(&mainCode);
          else
          {
            // no SG marker
            mainCode.push_back(it);
          }
        }

      }
    }

  }

  vertex_->buildShaderCode(&mainCode, lightingCode_);

}


void ShaderProgGenerator::addVertexBeginCode(QStringList* _code)
{
  // size in pixel of rendered point-lists, set by user via uniform

  _code->push_back(QString("vec4 sg_vPosPS = g_mWVP * ") + ShaderGenerator::keywords.macro_inputPosOS + QString(";"));
  _code->push_back("vec4 sg_vPosVS = g_mWV * inPosition;");
  _code->push_back("vec3 sg_vNormalVS = vec3(0.0, 1.0, 0.0);");
  _code->push_back("vec3 sg_vNormalOS = vec3(0.0, 1.0, 0.0);");

  if (desc_.vertexColors && (desc_.colorMaterialMode == GL_AMBIENT || desc_.colorMaterialMode == GL_AMBIENT_AND_DIFFUSE))
    _code->push_back(QString("vec4 sg_cColor = vec4(g_cEmissive + g_cLightModelAmbient * ") + ShaderGenerator::keywords.macro_inputVertexColor + QString(".xyz, SG_ALPHA);"));
  else
    _code->push_back("vec4 sg_cColor = vec4(g_cEmissive + g_cLightModelAmbient * g_cAmbient, SG_ALPHA);");

  if (ioDesc_.inputNormal_)
  {
    _code->push_back("sg_vNormalVS = normalize(g_mWVIT * inNormal);");
    _code->push_back("sg_vNormalOS = normalize(inNormal);");
  }

  if (ioDesc_.inputColor_ && (desc_.shadeMode == SG_SHADE_UNLIT || desc_.colorMaterialMode == GL_EMISSION))
    _code->push_back(QString("sg_cColor = ") + ShaderGenerator::keywords.macro_inputVertexColor + QString(";"));

  // texcoord generation
  addTexGenCode(_code, false);


  // apply modifiers
  for (size_t i = 0; i < activeMods_.size(); ++i)
    activeMods_[i]->modifyVertexBeginCode(_code);
}


void ShaderProgGenerator::addVertexEndCode(QStringList* _code)
{
  if (desc_.shadeMode == SG_SHADE_GOURAUD ||
    desc_.shadeMode == SG_SHADE_FLAT)
  {
    // add lighting code here

    addLightingCode(_code);
  }

  _code->push_back("gl_Position = sg_vPosPS;");
  _code->push_back("outVertexPosCS = sg_vPosPS;");

  if (ioDesc_.passTexCoord_)
    _code->push_back("outVertexTexCoord = sg_vTexCoord;");

  if (ioDesc_.passColor_)
    _code->push_back("outVertexColor = sg_cColor;");

  if (ioDesc_.passNormalVS_)
    _code->push_back(ShaderGenerator::keywords.macro_outputNormalVS + QString(" = sg_vNormalVS;"));

  if (ioDesc_.passNormalOS_)
    _code->push_back(ShaderGenerator::keywords.macro_outputNormalOS + QString(" = sg_vNormalOS;"));

  if (ioDesc_.passPosVS_)
    _code->push_back(ShaderGenerator::keywords.macro_outputPosVS + QString(" = sg_vPosVS;"));

  if (ioDesc_.passPosOS_)
    _code->push_back(ShaderGenerator::keywords.macro_outputPosOS + QString(" = ") + ShaderGenerator::keywords.macro_inputPosOS + QString(";"));



  // apply modifiers
  for (size_t i = 0; i < activeMods_.size(); ++i)
    activeMods_[i]->modifyVertexEndCode(_code);
}


int ShaderProgGenerator::checkForIncludes(QString _str, ShaderGenerator* _gen, QString _includePath)
{
  if (_str.contains("#include "))
  {
    QString strIncludeFile = _str.remove("#include ").remove('\"').remove('<').remove('>').trimmed();

    if (strIncludeFile.isEmpty())
      std::cout << "wrong include syntax: " << _str.toStdString() << std::endl;
    else
    {
      QString fullPathToIncludeFile = _includePath + QDir::separator() + strIncludeFile;

      _gen->addIncludeFile(fullPathToIncludeFile);
    }

    return 1;
  }

  return 0;
}

int ShaderProgGenerator::checkForIncludes(QString _str, QStringList* _outImport, QString _includePath)
{
  if (_str.contains("#include "))
  {
    QString strIncludeFile = _str.remove("#include ").remove('\"').remove('<').remove('>').trimmed();

    if (strIncludeFile.isEmpty())
      std::cout << "wrong include syntax: " << _str.toStdString() << std::endl;
    else
    {
      QString fullPathToIncludeFile = _includePath + QDir::separator() + strIncludeFile;

      // unify separator chars
      fullPathToIncludeFile.replace('\\', '/');

      // get rid of ".." usage inside shader includes
      QString cleanFilepath = QDir::cleanPath(fullPathToIncludeFile);

      loadStringListFromFile(cleanFilepath, _outImport);
    }

    return 1;
  }

  return 0;
}

void ShaderProgGenerator::buildTessControlShader()
{
  // Only build a tess-control shader if enabled
  if ( desc_.tessControlTemplateFile.isEmpty() )
    return;

  // the generator provides an IO mapping function and adds default uniforms to this stage
  // - template is necessary
  // - combination/modification of tess-control shader is not supported
  // - template may call sg_MapIO(inId) somewhere in code to take care of default IO pass-through
  //         this function reads elements from gl_in[inID] and writes them to elements of gl_out[gl_InvocationID]
  //         inId can be gl_InvocationID if the patch size is not modified

  delete tessControl_;

  tessControl_  = new ShaderGenerator();
  tessControl_->setGLSLVersion(desc_.version);

  QString it;
  foreach(it, tessControlLayout_)
    tessControl_->addLayout(it);

  // find previous shader stage
  ShaderGenerator* prevStage = vertex_;

  tessControl_->initTessControlShaderIO(&desc_, prevStage, &ioDesc_);

  tessControl_->initDefaultUniforms();


  // apply i/o modifiers
  for (size_t i = 0; i < activeMods_.size(); ++i)
    activeMods_[i]->modifyTessControlIO(tessControl_);

  initGenDefines(tessControl_);



  // assemble main function
  QStringList mainCode; 

  // add simple io passthrough mapper

  {
    mainCode.push_back("void sg_MapIO(const int inIdx)");
    mainCode.push_back("{");

    // built-in IO
    mainCode.push_back("gl_out[gl_InvocationID].gl_Position = gl_in[inIdx].gl_Position;");
    
    // custom IO
    for (int i = 0; i < tessControl_->getNumInputs(); ++i)
    {
      QString inputName = tessControl_->getInputName(i);
      QString outputName = tessControl_->getIOMapName(i);

      QString outputAssignCode = outputName + QString("[gl_InvocationID] = ") + inputName + QString("[inIdx];");

      mainCode.push_back(outputAssignCode);
    }

    mainCode.push_back("}");
  }


  // interpret loaded shader template:
  //  import #includes
  foreach(it,tessControlTemplate_)
  {
    if (!checkForIncludes(it, tessControl_, getPathName(tessControlShaderFile_)))
    {
      // str line is no include directive
      mainCode.push_back(it);
    }
  }

  tessControl_->buildShaderCode(&mainCode, lightingCode_);
}

void ShaderProgGenerator::buildTessEvalShader()
{
  // Only build a tess-eval shader if enabled
  if ( desc_.tessEvaluationTemplateFile.isEmpty() )
    return;

  // the generator provides default interpolation functions and adds default uniforms to this stage
  // - template is necessary
  // - combination/modification of tess-eval shader is not supported
  // - template may call sg_MapIOBarycentric() or sg_MapIOBilinear() somewhere in code to take care of default IO pass-through
  //        - barycentric interpolation can be used for triangle patches
  //        - bilinear interpolation can be used for quad patches
  //        - other interpolation schemes have to be user defined

  delete tessEval_;

  tessEval_  = new ShaderGenerator();
  tessEval_->setGLSLVersion(desc_.version);


  // find previous shader stage
  ShaderGenerator* prevStage = tessControl_;

  if (!prevStage)
    prevStage = vertex_;

  tessEval_->initTessEvalShaderIO(&desc_, prevStage, &ioDesc_);

  tessEval_->initDefaultUniforms();

  QString itLayout;
  foreach(itLayout, tessEvalLayout_)
    tessEval_->addLayout(itLayout);

  // apply i/o modifiers
  for (size_t i = 0; i < activeMods_.size(); ++i)
    activeMods_[i]->modifyTessControlIO(tessEval_);

  initGenDefines(tessEval_);


  // assemble main function
  QStringList mainCode; 

  // add simple io passthrough mapper

  {
    // barycentric interpolation

    mainCode.push_back("void sg_MapIOBarycentric()");
    mainCode.push_back("{");

    // built-in IO
    mainCode.push_back("gl_Position = gl_TessCoord.x * gl_in[0].gl_Position + gl_TessCoord.y * gl_in[1].gl_Position + gl_TessCoord.z * gl_in[2].gl_Position;");

    // custom IO
    for (int i = 0; i < tessEval_->getNumInputs(); ++i)
    {
      QString inputName = tessEval_->getInputName(i);
      QString outputName = tessEval_->getIOMapName(i);

      QString outputAssignCode = outputName + QString(" = ") +
        QString("gl_TessCoord.x*") + inputName + QString("[0] + ") +
        QString("gl_TessCoord.y*") + inputName + QString("[1] + ") +
        QString("gl_TessCoord.z*") + inputName + QString("[2];");

      mainCode.push_back(outputAssignCode);
    }

    mainCode.push_back("}");

    
    // bilinear interpolation

    mainCode.push_back("void sg_MapIOBilinear()");
    mainCode.push_back("{");

    // built-in IO
    mainCode.push_back("gl_Position = mix(  mix(gl_in[0].gl_Position, gl_in[1].gl_Position, gl_TessCoord.x), mix(gl_in[2].gl_Position, gl_in[3].gl_Position, gl_TessCoord.x), gl_TessCoord.y);");

    // custom IO
    for (int i = 0; i < tessEval_->getNumInputs(); ++i)
    {
      QString inputName = tessEval_->getInputName(i);
      QString outputName = tessEval_->getIOMapName(i);

      QString outputAssignCode = outputName + QString(" = mix( ") +
        QString("mix(") + inputName + QString("[0], ") + inputName + QString("[1], gl_TessCoord.x), ") + 
        QString("mix(") + inputName + QString("[2], ") + inputName + QString("[3], gl_TessCoord.x), gl_TessCoord.y); ");

      mainCode.push_back(outputAssignCode);
    }

    mainCode.push_back("}");
  }


  // interpret loaded shader template:
  //  replace (SG_INPUT, SG_OUTPUT) with matching io pairs
  QStringList::iterator it;
  for (it = tessEvalTemplate_.begin(); it != tessEvalTemplate_.end(); ++it)
  {
    QString line = *it;

    // replace IO line matching the pattern:
    //  SG_OUTPUT = r_expression(SG_INPUT);
    // the complete expression must be contained in a single line for this to work
    // more complex interpolation code should use #if SG_NORMALS etc.

    if (line.contains("SG_INPUT") || line.contains("SG_OUTPUT"))
    {

      QStringList resolvedCode;

      resolvedCode.push_back("// ----------------------------------------");
      resolvedCode.push_back("// ShaderGen: resolve SG_OUTPUT = expression(SG_INPUT);");

      int numOccurrences = 0;

      for (int i = 0; i < tessEval_->getNumInputs(); ++i)
      {
        QString inputName = tessEval_->getInputName(i);
        QString outputName = tessEval_->getIOMapName(i);

        // replace SG_INPUT, SG_OUTPUT with actual names
        QString resolvedLine = line;

        // avoid confusion with SG_INPUT_NORMALVS etc. naming convention
        //  resolvedLine.replace("SG_INPUT", inputName);
        //  resolvedLine.replace("SG_OUTPUT", outputName);
        // fails to do this
        
        // maybe this can be simplified with regexp
        // ie. replace SG_INPUT with inputName,  but not SG_INPUTN, SG_INPUT_ ..

        for (int k = 0; k < 2; ++k)
        {
          const QString stringToReplace = k ? "SG_OUTPUT" : "SG_INPUT";
          const int lenStringToReplace = stringToReplace.length();
          const QString replacementString = k ? outputName : inputName;

          int linePos = resolvedLine.indexOf(stringToReplace);

          while (linePos >= 0)
          {
            bool replaceOcc = true;

            int nextCharPos = linePos + lenStringToReplace;

            if (nextCharPos >= resolvedLine.size())
              nextCharPos = -1;

            if (nextCharPos > 0)
            {
              QChar nextChar = resolvedLine.at(nextCharPos);

              if (nextChar == '_' || nextChar.isDigit() || nextChar.isLetter())
              {
                // name token continues, this should not be replaced!

                linePos += lenStringToReplace;
                replaceOcc = false;
              }
            }

            // replace

            if (replaceOcc)
            {
              resolvedLine.replace(linePos, lenStringToReplace, replacementString);
              ++numOccurrences;
            }

            linePos = resolvedLine.indexOf(stringToReplace, linePos + 1);
          }
        }


        


        resolvedCode.push_back(resolvedLine);
      }

      resolvedCode.push_back("// ----------------------------------------");

      if (numOccurrences)
        mainCode.append(resolvedCode);
      else
        mainCode.push_back(line); // nothing to replace in this line
    }
    else
      mainCode.push_back(line);
  }

  tessEval_->buildShaderCode(&mainCode, lightingCode_);
}

void ShaderProgGenerator::buildGeometryShader()
{
  // Only build a geometry shader if enabled
  if ( desc_.geometryTemplateFile.isEmpty() )
    return;


  delete geometry_;

  geometry_  = new ShaderGenerator();
  geometry_->setGLSLVersion(desc_.version);


  // find previous shader stage
  ShaderGenerator* prevStage = tessEval_;

  if (!prevStage)
    prevStage = vertex_;

  geometry_->initGeometryShaderIO(&desc_, prevStage, &ioDesc_);

  geometry_->initDefaultUniforms();


  // apply i/o modifiers
  for (size_t i = 0; i < activeMods_.size(); ++i)
    activeMods_[i]->modifyGeometryIO(geometry_);

  initGenDefines(geometry_);


  // assemble main function
  QStringList mainCode; 

  // add simple io passthrough mapper

  {
    mainCode.push_back("void sg_MapIO(const int inIdx)");
    mainCode.push_back("{");

    // built-in IO
    mainCode.push_back("gl_Position = gl_in[inIdx].gl_Position;");
    mainCode.push_back("gl_PrimitiveID = gl_PrimitiveIDIn;");

Christopher Tenter's avatar
Christopher Tenter committed
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635

    // built-in gl_ClipDistance[]
    static int maxClipDistances = -1;
    if (maxClipDistances < 0)
    {
#ifdef GL_MAX_CLIP_DISTANCES
      glGetIntegerv(GL_MAX_CLIP_DISTANCES, &maxClipDistances);
      maxClipDistances = std::min(maxClipDistances, 32); // clamp to 32 bits
#else
      maxClipDistances = 32;
#endif
    }
    for (int i = 0; i < maxClipDistances; ++i)
    {
      if (desc_.clipDistanceMask & (1 << i))
        mainCode.push_back(QString("gl_ClipDistance[%1] = gl_in[inIdx].gl_ClipDistance[%1];").arg(i));
    }

Jan Möbius's avatar
Jan Möbius committed
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
    // custom IO
    for (int i = 0; i < geometry_->getNumInputs(); ++i)
    {
      QString inputName = geometry_->getInputName(i);
      QString outputName = geometry_->getIOMapName(i);

      QString outputAssignCode = outputName + QString(" = ") + inputName + QString("[inIdx];");

      mainCode.push_back(outputAssignCode);
    }

    mainCode.push_back("}");
  }


  // interpret loaded shader template:
  //  import #includes
  QString it;
  foreach(it,geometryTemplate_)
  {
    if (!checkForIncludes(it, geometry_, getPathName(geometryShaderFile_)))
    {
      // str line is no include directive
      mainCode.push_back(it);
    }
  }

  geometry_->buildShaderCode(&mainCode, lightingCode_);
}


void ShaderProgGenerator::buildFragmentShader()
{
  delete fragment_;

  fragment_  = new ShaderGenerator();
  fragment_->setGLSLVersion(desc_.version);

  // find previous shader stage
  ShaderGenerator* prevStage = geometry_;

  if (!prevStage)
    prevStage = tessEval_;
  if (!prevStage)
    prevStage = tessControl_;
  if (!prevStage)
    prevStage = vertex_;


  fragment_->initFragmentShaderIO(&desc_, prevStage, &ioDesc_);

  if (desc_.texGenDim && (desc_.texGenMode == GL_OBJECT_LINEAR || desc_.texGenMode == GL_EYE_LINEAR) && desc_.texGenPerFragment)
  {
    // application has to provide texture projection planes
    QString uniformDecl = "vec4 g_vTexGenPlane";
    if (desc_.texGenDim > 1)
      uniformDecl += "[" + QString::number(desc_.texGenDim) + "]";
    fragment_->addUniform(uniformDecl, " // texture projection planes");
  }


  fragment_->initDefaultUniforms();


  // texture sampler id
  if (desc_.textured())
  {
    for (std::map<size_t,ShaderGenDesc::TextureType>::const_iterator iter = desc_.textureTypes().begin();
        iter != desc_.textureTypes().end(); ++iter)
    {
      QString name = QString("g_Texture%1").arg(iter->first);
      QString type = "";
      switch (iter->second.type)
      {
        case GL_TEXTURE_1D: type = "sampler1D"; break;
        case GL_TEXTURE_2D: type = "sampler2D"; break;
        case GL_TEXTURE_3D: type = "sampler3D"; break;
        case GL_TEXTURE_CUBE_MAP: type = "samplerCube"; break;
#ifdef GL_ARB_texture_rectangle //ARCH_DARWIN doesn't support all texture defines with all xcode version (xcode 5.0 seems to support all)
        case GL_TEXTURE_RECTANGLE_ARB: type = "sampler2DRect"; break;
#endif
#ifdef GL_ARB_texture_buffer_object
        case GL_TEXTURE_BUFFER_ARB: type = "samplerBuffer"; break;
#endif
#ifdef GL_EXT_texture_array
        case GL_TEXTURE_1D_ARRAY_EXT: type = "sampler1DArray"; break;
        case GL_TEXTURE_2D_ARRAY_EXT: type = "sampler2DArray"; break;
#endif
#ifdef GL_ARB_texture_cube_map_array
        case GL_TEXTURE_CUBE_MAP_ARRAY_ARB: type = "samplerCubeArray"; break;
#endif
#ifdef GL_ARB_texture_multisample
        case GL_TEXTURE_2D_MULTISAMPLE: type = "sampler2DMS"; break;
        case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: type = "sampler2DMSArray"; break;
#endif
        default: std::cerr << "Texture Type not supported "<< iter->second.type << std::endl; break;
      }
      // todo: check if texture type supports shadowtype
      if (iter->second.shadow)
        type += "Shadow";
      fragment_->addUniform(type + " " + name);
    }
  }

  // apply i/o modifiers
  for (size_t i = 0; i < activeMods_.size(); ++i)
    activeMods_[i]->modifyFragmentIO(fragment_);


  initGenDefines(fragment_);



  // io

  // when to use fragment lights
  if (desc_.shadeMode == SG_SHADE_PHONG)
  {
    for (int i = 0; i < desc_.numLights; ++i)
      fragment_->addLight(i, desc_.lightTypes[i]);
  }

  // assemble main function
  QStringList mainCode;

  if (!fragmentTemplate_.size())
  {
    mainCode.push_back("void main()");
    mainCode.push_back("{");

    addFragmentBeginCode(&mainCode);
    addFragmentEndCode(&mainCode);

    mainCode.push_back("}");
  }
  else
  {
    // interpret loaded shader template:
    //  import #includes and replace SG_VERTEX_BEGIN/END markers
    QString it;
    foreach(it,fragmentTemplate_)
    {
      if (!checkForIncludes(it, fragment_, getPathName(fragmentShaderFile_)))
      {
        // str line is no include directive
        // check for SG_ markers

        if (it.contains("SG_FRAGMENT_BEGIN"))
          addFragmentBeginCode(&mainCode);
        else if (it.contains("SG_FRAGMENT_END"))
          addFragmentEndCode(&mainCode);
        else if (it.contains("SG_FRAGMENT_LIGHTING"))
          addLightingCode(&mainCode);
        else // no SG marker
          mainCode.push_back(it);

      }

      
    }

  }



  fragment_->buildShaderCode(&mainCode, lightingCode_);
}


void ShaderProgGenerator::addFragmentBeginCode(QStringList* _code)
{
  // support for projective texture mapping
  _code->push_back(QString("vec4 sg_vPosCS = ") + ShaderGenerator::keywords.macro_inputPosCS + QString(";"));
  _code->push_back("vec2 sg_vScreenPos = sg_vPosCS.xy / sg_vPosCS.w * 0.5 + vec2(0.5, 0.5);");

  _code->push_back(QString("#ifdef ") + ShaderGenerator::keywords.macro_inputPosVS);
  _code->push_back(QString("vec4 sg_vPosVS = ") + ShaderGenerator::keywords.macro_inputPosVS + QString(";"));
  _code->push_back("#endif");

  _code->push_back(QString("#ifdef ") + ShaderGenerator::keywords.macro_inputNormalVS);
  _code->push_back(QString("vec3 sg_vNormalVS = ") + ShaderGenerator::keywords.macro_inputNormalVS + QString(";"));
1817
  _code->push_back("sg_vNormalVS = normalize(sg_vNormalVS);");
Jan Möbius's avatar
Jan Möbius committed
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357
  _code->push_back("#endif");


  if (desc_.vertexColors && (desc_.colorMaterialMode == GL_AMBIENT || desc_.colorMaterialMode == GL_AMBIENT_AND_DIFFUSE))
    _code->push_back(QString("vec4 sg_cColor = vec4(g_cEmissive + g_cLightModelAmbient * ") + ShaderGenerator::keywords.macro_inputVertexColor + QString(".xyz, SG_ALPHA);"));
  else
    _code->push_back("vec4 sg_cColor = vec4(g_cEmissive + g_cLightModelAmbient * g_cAmbient, SG_ALPHA);");

  if (desc_.shadeMode == SG_SHADE_GOURAUD ||
      desc_.shadeMode == SG_SHADE_FLAT ||
      (ioDesc_.passColor_ && (desc_.shadeMode == SG_SHADE_UNLIT || desc_.colorMaterialMode == GL_EMISSION)))
      _code->push_back(QString("sg_cColor = ") + ShaderGenerator::keywords.macro_inputVertexColor + QString(";"));

  if (desc_.shadeMode == SG_SHADE_PHONG)
    addLightingCode(_code);


  addTexGenCode(_code, true);

  if (desc_.textured())
  {
    std::map<size_t,ShaderGenDesc::TextureType>::const_iterator iter = desc_.textureTypes().begin();
    _code->push_back("vec4 sg_cTex = texture(g_Texture"+QString::number(iter->first)+", sg_vTexCoord);");

    for (++iter; iter != desc_.textureTypes().end(); ++iter)
      _code->push_back("sg_cTex += texture(g_Texture"+QString::number(iter->first)+", sg_vTexCoord);");

    if (desc_.textureTypes().size() > 1 && desc_.normalizeTexColors)
      _code->push_back("sg_cTex = sg_cTex * 1.0/" + QString::number(desc_.textureTypes().size()) +".0 ;");

    if (desc_.shadeMode == SG_SHADE_UNLIT)
      _code->push_back("sg_cColor += sg_cTex;");
    else
      _code->push_back("sg_cColor *= sg_cTex;");
  }

  
  // apply modifiers
  for (size_t i = 0; i < activeMods_.size(); ++i)
    activeMods_[i]->modifyFragmentBeginCode(_code);
}

void ShaderProgGenerator::addFragmentEndCode(QStringList* _code)
{
  _code->push_back(ShaderGenerator::keywords.fs_outputFragmentColor + QString(" = sg_cColor;"));

  // apply modifiers
  for (size_t i = 0; i < activeMods_.size(); ++i)
    activeMods_[i]->modifyFragmentEndCode(_code);
}



void ShaderProgGenerator::addLightingCode(QStringList* _code)
{

  ShaderModifier* lightingModifier = 0;

  // check if any modifier replaces the default lighting function
  for (size_t i = 0; i < activeMods_.size() && !lightingModifier; ++i)
  {
    if (activeMods_[i]->replaceDefaultLightingCode())
        lightingModifier = activeMods_[i];
  }

  if (!lightingModifier)
  {
    // default lighting code:

    QString buf;

    QString vertexColorString = (ioDesc_.inputColor_ && ioDesc_.passColor_) ? (ShaderGenerator::keywords.macro_inputVertexColor + QString(".xyz * ")) : "";
    QString diffuseVertexColor = (desc_.colorMaterialMode == GL_DIFFUSE || desc_.colorMaterialMode == GL_AMBIENT_AND_DIFFUSE) ? vertexColorString : "";
    QString ambientVertexColor = (desc_.colorMaterialMode == GL_AMBIENT || desc_.colorMaterialMode == GL_AMBIENT_AND_DIFFUSE) ? vertexColorString : "";
    QString specularVertexColor = (desc_.colorMaterialMode == GL_SPECULAR) ? vertexColorString : "";

    for (int i = 0; i < desc_.numLights; ++i)
    {
      ShaderGenLightType lgt = desc_.lightTypes[i];

      switch (lgt)
      {
      case SG_LIGHT_DIRECTIONAL:
//        buf.sprintf("sg_cColor.xyz += LitDirLight(sg_vPosVS.xyz, sg_vNormalVS, g_vLightDir_%d, %s g_cLightAmbient_%d, %s g_cLightDiffuse_%d,  %s g_cLightSpecular_%d);", i, ambientVertexColor, i, diffuseVertexColor, i, specularVertexColor, i);
        buf = QString("sg_cColor.xyz += LitDirLight(sg_vPosVS.xyz, sg_vNormalVS, g_vLightDir_%1, %2 g_cLightAmbient_%1, %3 g_cLightDiffuse_%1,  %4 g_cLightSpecular_%1);").arg(QString::number(i), ambientVertexColor, diffuseVertexColor, specularVertexColor);
        break;

      case SG_LIGHT_POINT:
//        buf.sprintf("sg_cColor.xyz += LitPointLight(sg_vPosVS.xyz, sg_vNormalVS,  g_vLightPos_%d, %s g_cLightAmbient_%d, %s g_cLightDiffuse_%d, %s g_cLightSpecular_%d,  g_vLightAtten_%d);", i, ambientVertexColor, i, diffuseVertexColor, i, specularVertexColor, i, i);
        buf = QString("sg_cColor.xyz += LitPointLight(sg_vPosVS.xyz, sg_vNormalVS,  g_vLightPos_%1, %2 g_cLightAmbient_%1, %3 g_cLightDiffuse_%1, %4 g_cLightSpecular_%1,  g_vLightAtten_%1);").arg(QString::number(i), ambientVertexColor, diffuseVertexColor, specularVertexColor);
        break;

      case SG_LIGHT_SPOT:
//        buf.sprintf("sg_cColor.xyz += LitSpotLight(sg_vPosVS.xyz,  sg_vNormalVS,  g_vLightPos_%d,  g_vLightDir_%d, %s g_cLightAmbient_%d, %s g_cLightDiffuse_%d, %s g_cLightSpecular_%d,  g_vLightAtten_%d,  g_vLightAngleExp_%d);", i, i, ambientVertexColor, i, diffuseVertexColor, i, specularVertexColor, i, i, i);
        buf = QString("sg_cColor.xyz += LitSpotLight(sg_vPosVS.xyz,  sg_vNormalVS,  g_vLightPos_%1,  g_vLightDir_%1, %2 g_cLightAmbient_%1, %3 g_cLightDiffuse_%1, %4 g_cLightSpecular_%1,  g_vLightAtten_%1,  g_vLightAngleExp_%1);").arg(QString::number(i), ambientVertexColor, diffuseVertexColor, specularVertexColor);
        break;

      default: break;
      }

      _code->push_back(buf);
    }

    // modify lighting color afterwards

    for (size_t i = 0; i < activeMods_.size(); ++i)
      modifyLightingCode(_code, activeMods_[i]);
  }
  else
  {
    // there exists a lighting modifier that completely replaces the default lighting shader
    modifyLightingCode(_code, lightingModifier);


    // apply remaining modifiers that do not replace the complete lighting code

    for (size_t i = 0; i < activeMods_.size(); ++i)
    {
      if (lightingModifier != activeMods_[i])
        modifyLightingCode(_code, activeMods_[i]);
    }
  }

}

void ShaderProgGenerator::modifyLightingCode( QStringList* _code, ShaderModifier* _modifier )
{
  if (!_modifier) return;

  for (int i = 0; i < desc_.numLights; ++i)
  {
    ShaderGenLightType lgt = desc_.lightTypes[i];

    _modifier->modifyLightingCode(_code, i, lgt);
  }
}


void ShaderProgGenerator::addLightingFunctions(QStringList* _code)
{
  QString it;
  foreach(it,lightingCode_)
    _code->push_back(it);
}


void ShaderProgGenerator::addTexGenCode( QStringList* _code, bool _fragmentShader )
{
  // declare local texcoord variable name as "sg_vTexCoord"
  int texcoordVarDim = 2;
  if (ioDesc_.inputTexCoord_ && 
    !desc_.textureTypes().empty() &&
    desc_.textureTypes().begin()->second.type == GL_TEXTURE_3D)
    texcoordVarDim = 3;

  bool generateTexCoord = desc_.texGenDim && desc_.texGenMode && (_fragmentShader == desc_.texGenPerFragment);
  if (generateTexCoord)
    texcoordVarDim = desc_.texGenDim;

  QString texcoordVarInit;
  if (texcoordVarDim == 1)
    texcoordVarInit = "float sg_vTexCoord";
  else
    texcoordVarInit.sprintf("vec%i sg_vTexCoord", texcoordVarDim);

  // init with default value: input or zero
  if (ioDesc_.inputTexCoord_ && !generateTexCoord)
    texcoordVarInit += QString("= ") + ShaderGenerator::keywords.macro_inputTexcoord + QString(";");
  else if (0 <= texcoordVarDim && texcoordVarDim <= 4)
  {
    QString zeroVecDefs[] = 
    {
      ";",
      "= 0;",
      "= vec2(0,0);",
      "= vec3(0,0,0);",
      "= vec4(0,0,0,0);"
    };
    texcoordVarInit += zeroVecDefs[texcoordVarDim];
  }

  _code->push_back(texcoordVarInit);


  // texcoord generation
  // https://www.opengl.org/wiki/Mathematics_of_glTexGen
  if (generateTexCoord)
  {

    const char* texGenCoordString[] = { "x", "y", "z", "w" };

    switch (desc_.texGenMode)
    {
    case GL_OBJECT_LINEAR:
    {
      for (int i = 0; i < desc_.texGenDim; ++i)
      {
        QString assignmentInstrString;
        assignmentInstrString = "sg_vTexCoord";
        if (desc_.texGenDim > 1)
        {
          assignmentInstrString +=".";
          assignmentInstrString += texGenCoordString[i];
        }
        assignmentInstrString += " = dot(";
        assignmentInstrString += ShaderGenerator::keywords.macro_inputPosOS;
        assignmentInstrString += ", g_vTexGenPlane";
        if (desc_.texGenDim > 1)
        {
          assignmentInstrString += "[";
          assignmentInstrString += QString::number(i);
          assignmentInstrString += "]";
        }
        assignmentInstrString += ");";
        _code->push_back(assignmentInstrString);
      }
    } break;

    case GL_EYE_LINEAR:
    {
      for (int i = 0; i < desc_.texGenDim; ++i)
      {
        QString assignmentInstrString;
        assignmentInstrString = "sg_vTexCoord";
        if (desc_.texGenDim > 1)
        {
          assignmentInstrString += ".";
          assignmentInstrString += texGenCoordString[i];
        }
        assignmentInstrString += " = dot(sg_vPosVS, g_vTexGenPlane";
        if (desc_.texGenDim > 1)
        {
          assignmentInstrString += "[";
          assignmentInstrString += QString::number(i);
          assignmentInstrString += "]";
        }
        assignmentInstrString += ");";
        _code->push_back(assignmentInstrString);
      }

    } break;

    case GL_SPHERE_MAP:
    {
      _code->push_back("vec3 sg_vPosVS_unit = normalize(sg_vPosVS.xyz);");
      _code->push_back("vec3 sg_TexGenRefl = reflect(sg_vPosVS_unit, sg_vNormalVS);");
      _code->push_back("vec3 sg_TexGenRefl2 = sg_TexGenRefl; sg_TexGenRefl2.z += 1.0;");
      _code->push_back("float sg_TexGenMRcp = 0.5 * inversesqrt(dot(sg_TexGenRefl2, sg_TexGenRefl2));");
      for (int i = 0; i < desc_.texGenDim; ++i)
      {
        QString assignmentInstrString;
        assignmentInstrString.sprintf("sg_vTexCoord.%s = sg_TexGenRefl.%s * sg_TexGenMRcp + 0.5;", texGenCoordString[i], texGenCoordString[i]);
        _code->push_back(assignmentInstrString);
      }
    } break;

    case GL_NORMAL_MAP:
    {
      for (int i = 0; i < desc_.texGenDim; ++i)
      {
        QString assignmentInstrString;
        assignmentInstrString.sprintf("sg_vTexCoord.%s = sg_vNormalVS.%s;", texGenCoordString[i], texGenCoordString[i]);
        _code->push_back(assignmentInstrString);
      }
    } break;

    case GL_REFLECTION_MAP:
    {
      _code->push_back("vec3 sg_vPosVS_unit = normalize(sg_vPosVS.xyz);");
      _code->push_back("vec3 sg_TexGenRefl = reflect(sg_vPosVS_unit, sg_vNormalVS);");
      for (int i = 0; i < desc_.texGenDim; ++i)
      {
        QString assignmentInstrString;
        assignmentInstrString.sprintf("sg_vTexCoord.%s = sg_TexGenRefl.%s;", texGenCoordString[i], texGenCoordString[i]);
        _code->push_back(assignmentInstrString);
      }
    } break;

    default: break;
    }
  }
}


void ShaderProgGenerator::generateShaders()
{
  // import template source from files
  loadShaderTemplateFromFile();

  // check what needs to be passed down from vertex shader

  if (desc_.shadeMode != SG_SHADE_UNLIT)
    ioDesc_.inputNormal_ = true;

  if (desc_.textured())
  {
    ioDesc_.inputTexCoord_ = true;
    ioDesc_.passTexCoord_ = true;
  }

  // clamp generated texcoord dimension
  int maxTexGenDim = 4;

  switch (desc_.texGenMode)
  {
  case GL_EYE_LINEAR:
  case GL_OBJECT_LINEAR: maxTexGenDim = 4; break;
    
  case GL_SPHERE_MAP: maxTexGenDim = 2; break;
  
  case GL_NORMAL_MAP:
  case GL_REFLECTION_MAP: maxTexGenDim = 3; break;
  
  default: maxTexGenDim = 0; break;
  }

  desc_.texGenDim = std::max(std::min(desc_.texGenDim, maxTexGenDim), 0);


  if (desc_.texGenDim && desc_.texGenMode)
  {
    // pass generated texcoord from vertex to fragment shader
    if (!desc_.texGenPerFragment)
      ioDesc_.passTexCoord_ = true;

    // some modes require normal vectors
    if (desc_.texGenMode == GL_REFLECTION_MAP || desc_.texGenMode == GL_SPHERE_MAP || desc_.texGenMode == GL_NORMAL_MAP)
      ioDesc_.inputNormal_ = true;

    // pass data to the fragment shader as required for the generation
    if (desc_.texGenPerFragment)
    {
      switch (desc_.texGenMode)
      {
      case GL_OBJECT_LINEAR: ioDesc_.passPosOS_ = true; break;
      case GL_EYE_LINEAR: ioDesc_.passPosVS_ = true; break;
      case GL_SPHERE_MAP: ioDesc_.passPosVS_ = ioDesc_.passNormalVS_ = true; break;
      case GL_NORMAL_MAP: ioDesc_.passNormalVS_ = true; break;
      case GL_REFLECTION_MAP: ioDesc_.passPosVS_ = ioDesc_.passNormalVS_ = true; break;
      default: break;
      }
    }
  }


  if (desc_.vertexColors)
    ioDesc_.inputColor_ = true;

  if (desc_.shadeMode == SG_SHADE_PHONG)
  {
    ioDesc_.passNormalVS_ = true;
    ioDesc_.passPosVS_ = true;
  }

  if (desc_.shadeMode == SG_SHADE_FLAT || desc_.shadeMode == SG_SHADE_GOURAUD || desc_.vertexColors)
    ioDesc_.passColor_ = true;


  // scan macros of modifiers for attribute requests,
  // done by adding modifier io to an empty dummy
  ShaderGenerator dummy;

  for (size_t i = 0; i < activeMods_.size(); ++i)
  {
    ShaderModifier* mod = activeMods_[i];

    mod->modifyVertexIO(&dummy);
    mod->modifyTessControlIO(&dummy);
    mod->modifyTessEvalIO(&dummy);
    mod->modifyGeometryIO(&dummy);
    mod->modifyFragmentIO(&dummy);
  }
  // scan requested inputs from modifiers

  if (dummy.hasDefine(ShaderGenerator::keywords.macro_requestPosVS))
    ioDesc_.passPosVS_ = true;
  if (dummy.hasDefine(ShaderGenerator::keywords.macro_requestTexcoord))
  {
    ioDesc_.inputTexCoord_ = true;
    ioDesc_.passTexCoord_ = true;
  }
  if (dummy.hasDefine(ShaderGenerator::keywords.macro_requestVertexColor))
  {
    ioDesc_.inputColor_ = true;
    ioDesc_.passColor_ = true;
  }
  if (dummy.hasDefine(ShaderGenerator::keywords.macro_requestNormalVS))
  {
    ioDesc_.inputNormal_ = true;
    ioDesc_.passNormalVS_ = true;
  }
  if (dummy.hasDefine(ShaderGenerator::keywords.macro_requestNormalOS))
  {
    ioDesc_.inputNormal_ = true;
    ioDesc_.passNormalOS_ = true;
  }
  if (dummy.hasDefine(ShaderGenerator::keywords.macro_requestPosOS))
    ioDesc_.passPosOS_ = true;
  




  // assemble shader codes

  buildVertexShader();
  buildTessControlShader();
  buildTessEvalShader();
  buildGeometryShader();
  buildFragmentShader();
}


const QStringList& ShaderProgGenerator::getVertexShaderCode()
{
  return vertex_->getShaderCode();
}

const QStringList& ShaderProgGenerator::getTessControlShaderCode()
{
  return tessControl_->getShaderCode();
}

const QStringList& ShaderProgGenerator::getTessEvaluationShaderCode()
{
  return tessEval_->getShaderCode();
}

const QStringList& ShaderProgGenerator::getGeometryShaderCode()
{
  return geometry_->getShaderCode();
}

const QStringList& ShaderProgGenerator::getFragmentShaderCode()
{
  return fragment_->getShaderCode();
}


void ShaderProgGenerator::saveVertexShToFile(const char* _fileName)
{
  vertex_->saveToFile(_fileName);
}

void ShaderProgGenerator::saveGeometryShToFile(const char* _fileName)
{
  geometry_->saveToFile(_fileName);
}

void ShaderProgGenerator::saveFragmentShToFile(const char* _fileName)
{
  fragment_->saveToFile(_fileName);
}


void ShaderProgGenerator::loadShaderTemplateFromFile()
{
  if (!desc_.vertexTemplateFile.isEmpty())
  {
    loadStringListFromFile(desc_.vertexTemplateFile, &vertexTemplate_);
    scanShaderTemplate(vertexTemplate_, desc_.vertexTemplateFile);
  }
  if (!desc_.fragmentTemplateFile.isEmpty())
  {
    loadStringListFromFile(desc_.fragmentTemplateFile, &fragmentTemplate_);
    scanShaderTemplate(fragmentTemplate_, desc_.fragmentTemplateFile);
  }
  if (!desc_.geometryTemplateFile.isEmpty())
  {
    loadStringListFromFile(desc_.geometryTemplateFile, &geometryTemplate_);
    scanShaderTemplate(geometryTemplate_, desc_.geometryTemplateFile);
  }
  if (!desc_.tessControlTemplateFile.isEmpty())
  {
    loadStringListFromFile(desc_.tessControlTemplateFile, &tessControlTemplate_);
    scanShaderTemplate(tessControlTemplate_, desc_.tessControlTemplateFile, &tessControlLayout_);
  }
  if (!desc_.tessEvaluationTemplateFile.isEmpty())
  {
    loadStringListFromFile(desc_.tessEvaluationTemplateFile, &tessEvalTemplate_);
    scanShaderTemplate(tessEvalTemplate_, desc_.tessEvaluationTemplateFile, &tessEvalLayout_);
  }


  vertexShaderFile_   = desc_.vertexTemplateFile;
  tessControlShaderFile_ = desc_.tessControlTemplateFile;
  tessEvalShaderFile_ = desc_.tessEvaluationTemplateFile;
  geometryShaderFile_ = desc_.geometryTemplateFile;
  fragmentShaderFile_ = desc_.fragmentTemplateFile;
}

void ShaderProgGenerator::scanShaderTemplate(QStringList& _templateSrc, QString _templateFilename, QStringList* _outLayoutDirectives)
{
  // interpret loaded shader template:
  //  import #includes

  QString filePath = getPathName(_templateFilename);

  QStringList::iterator it;
  for (it = _templateSrc.begin(); it != _templateSrc.end(); ++it)
  {
    QStringList import;

    if (checkForIncludes(*it, &import, filePath))
    {
      // line is include directive

      // remove line from source
      it = _templateSrc.erase(it);

      int offset = it - _templateSrc.begin();

      // insert imported file

      QString importLine;
      foreach(importLine, import)
      {
        it = _templateSrc.insert(it, importLine);
        ++it;
      }

      // included file might recursively include something again
      // -> scan included file
      it = _templateSrc.begin() + offset;
    }
    else
    {
      QString trimmedLine = it->trimmed();

      // scan and adjust glsl version
      QByteArray lineBytes = trimmedLine.toUtf8();

      if (trimmedLine.startsWith("#version "))
      {
        QStringList tokens = trimmedLine.split(' ');

        if (tokens.size() > 1)
        {
          // templateVersion
          bool convOk = false;
Jan Möbius's avatar
Jan Möbius committed
2358
          int templateVersion = tokens.at(1).toInt(&convOk);
Jan Möbius's avatar
Jan Möbius committed
2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740

          if (convOk)
          {
            desc_.version = std::max(templateVersion, desc_.version);

            // remove version line from template since this is added later in the build functions
            it = _templateSrc.erase(it);
          }
        }
      }
      // scan layout() directive
      else if (trimmedLine.startsWith("layout(") || trimmedLine.startsWith("layout ("))
      {
        if (_outLayoutDirectives)
        {
          _outLayoutDirectives->push_back(trimmedLine);
          // layout() will be inserted later at the correct position in the build functions
          // - must be placed before shader IO declaration to make tess-control shaders compilable on ati
          it = _templateSrc.erase(it);
        }
      }
      else
      {
        // scan requested inputs

        if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestPosVS))
          ioDesc_.passPosVS_ = true;
        else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestTexcoord))
        {
          ioDesc_.inputTexCoord_ = true;
          ioDesc_.passTexCoord_ = true;
        }
        else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestVertexColor))
        {
          ioDesc_.inputColor_ = true;
          ioDesc_.passColor_ = true;
        }
        else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestNormalVS))
        {
          ioDesc_.inputNormal_ = true;
          ioDesc_.passNormalVS_ = true;
        }
        else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestNormalOS))
        {
          ioDesc_.inputNormal_ = true;
          ioDesc_.passNormalOS_ = true;
        }
        else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestPosOS))
          ioDesc_.passPosOS_ = true;
        else if (trimmedLine.startsWith("SG_FRAGMENT_LIGHTING"))
        {
          // shader template performs lighting in fragment shader
          // -> forced phong shading
          desc_.shadeMode = SG_SHADE_PHONG;
        }
      }

    }
  }

}

QString ShaderProgGenerator::getPathName(QString _strFileName)
{
  QFileInfo fileInfo(getAbsFilePath(_strFileName));
  return fileInfo.absolutePath();
}

QString ShaderProgGenerator::getAbsFilePath(QString _strFileName)
{
  QString absFilename;
  if ( QDir(_strFileName).isRelative() )
    absFilename = getShaderDir() + QDir::separator() + _strFileName;
  else
    absFilename = _strFileName;

  return QDir::cleanPath(absFilename);
}

void ShaderProgGenerator::setShaderDir( QString _dir )
{
  shaderDir_ = _dir;
}

QString ShaderProgGenerator::getShaderDir()
{
  return shaderDir_ + QString("/");
}


unsigned int ShaderProgGenerator::registerModifier( ShaderModifier* _modifier )
{
  if (!_modifier) return 0;

  // redundancy check
  for (int i = 0; i < numRegisteredModifiers_; ++i)
  {
    if (registeredModifiers_[i] == _modifier) 
    {
//      std::cout << "warning: trying to re-register shader modifier " << _modifier->getID() << std::endl;
      return registeredModifiers_[i]->getID();
    }
  }

  _modifier->modifierID_ = (unsigned int)(numRegisteredModifiers_++);

  registeredModifiers_.push_back(_modifier);
  return _modifier->modifierID_;
}

ShaderModifier* ShaderProgGenerator::getActiveModifier( int _i )
{
  if (_i >= 0 && _i <= int(activeMods_.size()))
    return activeMods_[_i];

  // invalid _i
  return 0;
}

int ShaderProgGenerator::getNumActiveModifiers() const
{
  return int(activeMods_.size());
}


bool ShaderProgGenerator::hasGeometryShader() const
{
  return !desc_.geometryTemplateFile.isEmpty();
}

bool ShaderProgGenerator::hasTessControlShader() const
{
  return !desc_.tessControlTemplateFile.isEmpty();
}

bool ShaderProgGenerator::hasTessEvaluationShader() const
{
  return !desc_.tessEvaluationTemplateFile.isEmpty();
}


//=============================================================================

ShaderModifier::ShaderModifier( void )
: modifierID_(0)
{}

ShaderModifier::~ShaderModifier( void )
{}


class ShaderModifierFile : public ShaderModifier
{
public:

  ShaderModifierFile()
    : version_(0) 
  {}

  virtual ~ShaderModifierFile() 
  {}

  void modifyVertexIO(ShaderGenerator* _shader) { modifyIO(0, _shader); }
  void modifyTessControlIO(ShaderGenerator* _shader) { modifyIO(1, _shader); }
  void modifyTessEvalIO(ShaderGenerator* _shader) { modifyIO(2, _shader); }
  void modifyGeometryIO(ShaderGenerator* _shader) { modifyIO(3, _shader); }
  void modifyFragmentIO(ShaderGenerator* _shader) { modifyIO(4, _shader); }


  void modifyVertexBeginCode(QStringList* _code) { _code->append(vertexBeginCode_); }
  void modifyVertexEndCode(QStringList* _code) { _code->append(vertexEndCode_); }
  void modifyFragmentBeginCode(QStringList* _code) { _code->append(fragmentBeginCode_); }
  void modifyFragmentEndCode(QStringList* _code) { _code->append(fragmentEndCode_); }

  const QString& filename() const {return filename_;}
  const QDateTime& filetime() const {return filetime_;}
  void filetime(const QDateTime& _newtime) {filetime_ = _newtime;}

  void clear()
  {
    version_ = 0;

    for (int i = 0; i < 5; ++i)
      io_[i].clear();

    vertexBeginCode_.clear();
    vertexEndCode_.clear();
    fragmentBeginCode_.clear();
    fragmentEndCode_.clear();
  }

  static ShaderModifierFile* loadFromFile(QString _filename)
  {
    ShaderModifierFile* res = 0;

    // get timestamp
    QString absFilename = ShaderProgGenerator::getAbsFilePath(_filename);
    QDateTime lastmod = QFileInfo(absFilename).lastModified();

    // check cache
    QHash<QString, ShaderModifierFile>::iterator cacheEntry = fileCache_.find(_filename);

    bool reload = false;
    bool firstLoad = false;

    if (cacheEntry != fileCache_.end())
    {
      // fetch from cache
      res = &cacheEntry.value();

      if (lastmod != res->filetime())
      {
        res->clear();
        reload = true;
      }
    }
    else
    {
      // load new modifier
      reload = true;
      firstLoad = true;
    }

    if (reload)
    {
      QStringList lines;
      if (ShaderProgGenerator::loadStringListFromFile(_filename, &lines))
      {
        // new cache entry
        if (firstLoad)
          res = &fileCache_[_filename];

        res->loadBlocks(lines);
        res->filetime(lastmod);

        // also register to generator
        if (firstLoad)
          ShaderProgGenerator::registerModifier(res);
      }
    }

    return res;
  }

private:


  void loadBlocks(const QStringList& _lines)
  {
    static const char* markers [] = 
    {
      "VertexIO:",
      "TessControlIO:",
      "TessEvalIO:",
      "GeometryIO:",
      "FragmentIO:",
      "VertexBeginCode:",
      "VertexEndCode:",
      "FragmentBeginCode:",
      "FragmentEndCode:"
    };
    const int numMarkers = sizeof(markers) / sizeof(markers[0]);

    QStringList* blockTargets [] = 
    {
      io_ + 0,
      io_ + 1,
      io_ + 2,
      io_ + 3,
      io_ + 4,
      &vertexBeginCode_,
      &vertexEndCode_,
      &fragmentBeginCode_,
      &fragmentEndCode_
    };

    assert(sizeof(blockTargets) / sizeof(blockTargets[0]) == numMarkers);


    // current block in file, points to one of io_[idx], vertexBeginCode_, ...
    QStringList* curBlock_ = 0;


    int curLine = 0;

    for (QStringList::const_iterator it = _lines.begin(); it != _lines.end(); ++it, ++curLine)
    {
      if (it->isEmpty())
        continue;

      // read glsl version
      if (version_ <= 0 && it->startsWith("#version "))
      {
        const int offset = strlen("#version ");
        version_ = atoi(it->toLatin1().data() + offset);
      }
      else
      {
        // read code blocks

        bool blockMarker = false;

        for (int i = 0; i < numMarkers && !blockMarker; ++i)
        {
          if ( it->startsWith(markers[i]) ) 
          {
            // new block start
            curBlock_ = blockTargets[i];
            blockMarker = true;
          }
        }

        if (!blockMarker)
        {
          if (curBlock_) // code belongs to some block
            curBlock_->push_back(*it);
          else // wrong file structure
            std::cerr << "ShaderModifierFile::loadBlocks - line belongs to unknown block in file " << filename_.toLatin1().data() << " at line " << curLine << std::endl;
        }
      }
    }
  }

  void modifyIO(int _stage, ShaderGenerator* _shader)
  {
    if (version_ > 0)
      _shader->setGLSLVersion(version_);

    _shader->addRawIOBlock(io_[_stage]);
  }

private:

  QString filename_;

  QDateTime filetime_; 

  // glsl version
  int version_;

  // io mods
  QStringList io_[5];

  // code mods
  QStringList vertexBeginCode_,
    vertexEndCode_,
    fragmentBeginCode_,
    fragmentEndCode_;


  // loaded modifiers
  static QHash<QString, ShaderModifierFile> fileCache_;
};

QHash<QString, ShaderModifierFile> ShaderModifierFile::fileCache_;


ShaderModifier* ShaderModifier::loadFromFile(QString _filename)
{
  return ShaderModifierFile::loadFromFile(_filename);
}


//=============================================================================


QString ShaderGenDesc::toString() const
{
  // mapping (int)ShaderGenMode -> string
  const char* shadeModeString[] = 
  {
    "SG_SHADE_UNLIT",
    "SG_SHADE_FLAT",
    "SG_SHADE_GOURAUD",
    "SG_SHADE_PHONG"
  };

  QString res;
  QTextStream resStrm(&res);

  resStrm << "version: " << version;

Christopher Tenter's avatar
Christopher Tenter committed
2741
  resStrm << "\nshaderDesc.numLights: " << numLights;
Jan Möbius's avatar
Jan Möbius committed
2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836

  if (numLights)
  {
    resStrm << "\nshaderDesc.lightTypes[]: {";

    for (int i = 0; i < numLights; ++i)
    {
      switch (lightTypes[i]) 
      {
      case SG_LIGHT_DIRECTIONAL: resStrm << "DIRECTIONAL"; break;
      case SG_LIGHT_POINT: resStrm << "POINT"; break;
      case SG_LIGHT_SPOT: resStrm << "SPOT"; break;
      default: resStrm << "UNDEFINED"; break;
      }

      if (i + 1 < numLights)
        resStrm << ", ";
      else
        resStrm << "}";
    }
  }


  resStrm << "\nshaderDesc.shadeMode: " << shadeModeString[shadeMode];
  resStrm << "\nshaderDesc.vertexColors: " << vertexColors;
  resStrm << "\nshaderDesc.textured(): " << textured();
  for (std::map<size_t,TextureType>::const_iterator iter = textureTypes_.begin(); iter != textureTypes_.end();++iter)
  {
    resStrm << "\nTexture stage: " << iter->first;
    resStrm << "\nTexture Type: ";
    switch (iter->second.type)
    {
        case GL_TEXTURE_1D: resStrm << "GL_TEXTURE_1D"; break;
        case GL_TEXTURE_2D: resStrm << "GL_TEXTURE_2D"; break;
        case GL_TEXTURE_3D: resStrm << "GL_TEXTURE_3D"; break;
        case GL_TEXTURE_CUBE_MAP: resStrm << "GL_TEXTURE_CUBE_MAP"; break;
#ifdef GL_ARB_texture_rectangle //ARCH_DARWIN doesn't support all texture defines with all xcode version (xcode 5.0 seems to support all)
        case GL_TEXTURE_RECTANGLE_ARB: resStrm << "GL_TEXTURE_RECTANGLE"; break;
#endif
#ifdef GL_ARB_texture_buffer_object
        case GL_TEXTURE_BUFFER_ARB: resStrm << "GL_TEXTURE_BUFFER"; break;
#endif
#ifdef GL_EXT_texture_array
        case GL_TEXTURE_1D_ARRAY_EXT: resStrm << "GL_TEXTURE_1D_ARRAY"; break;
        case GL_TEXTURE_2D_ARRAY_EXT: resStrm << "GL_TEXTURE_2D_ARRAY"; break;
#endif
#ifdef GL_ARB_texture_cube_map_array
        case GL_TEXTURE_CUBE_MAP_ARRAY_ARB: resStrm << "GL_TEXTURE_CUBE_MAP_ARRAY"; break;
#endif
#ifdef GL_ARB_texture_multisample
        case GL_TEXTURE_2D_MULTISAMPLE: resStrm << "GL_TEXTURE_2D_MULTISAMPLE"; break;
        case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: resStrm << "GL_TEXTURE_2D_MULTISAMPLE_ARRAY"; break;
#endif
        default: std::cerr << "Texture Type with number "<< iter->second.type << " on stage "<< iter->first << " is not supported "  << std::endl; break;
    }

    resStrm  << "\nShadowTexture: " <<  iter->second.shadow;
  }

  resStrm << "\nshaderDesc.texGenDim: " << texGenDim;

  switch (texGenMode)
  {
  case GL_OBJECT_LINEAR: resStrm << "\nshaderDesc.texGenMode: GL_OBJECT_LINEAR"; break;
  case GL_EYE_LINEAR: resStrm << "\nshaderDesc.texGenMode: GL_EYE_LINEAR"; break;
  case GL_SPHERE_MAP: resStrm << "\nshaderDesc.texGenMode: GL_SPHERE_MAP"; break;
  case GL_NORMAL_MAP: resStrm << "\nshaderDesc.texGenMode: GL_NORMAL_MAP"; break;
  case GL_REFLECTION_MAP: resStrm << "\nshaderDesc.texGenMode: GL_REFLECTION_MAP"; break;
  default: resStrm << "\nshaderDesc.texGenMode: unknown"; break;
  }
  
  resStrm << "\nshaderDesc.texGenPerFragment: " << texGenPerFragment;

  if (!vertexTemplateFile.isEmpty())
    resStrm << "\nshaderDesc.vertexTemplateFile: " << vertexTemplateFile;

  if (!tessControlTemplateFile.isEmpty())
    resStrm << "\nshaderDesc.tessControlTemplateFile: " << tessControlTemplateFile;

  if (!tessEvaluationTemplateFile.isEmpty())
    resStrm << "\nshaderDesc.tessEvaluationTemplateFile: " << tessEvaluationTemplateFile;

  if (!geometryTemplateFile.isEmpty())
    resStrm << "\nshaderDesc.geometryTemplateFile: " << geometryTemplateFile;

  if (!fragmentTemplateFile.isEmpty())
    resStrm << "\nshaderDesc.fragmentTemplateFile: " << fragmentTemplateFile;

  return res;
}



} // namespace ACG
//=============================================================================