ShaderGenerator.cc 21.5 KB
Newer Older
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
/*===========================================================================*\
 *                                                                           *
 *                              OpenFlipper                                  *
 *      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen      *
 *                           www.openflipper.org                             *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenFlipper.                                        *
 *                                                                           *
 *  OpenFlipper is free software: you can redistribute it and/or modify      *
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenFlipper is distributed in the hope that it will be useful,           *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
 *  GNU Lesser General Public License for more details.                      *
 *                                                                           *
 *  You should have received a copy of the GNU LesserGeneral Public          *
 *  License along with OpenFlipper. If not,                                  *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

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

Christopher Tenter's avatar
Christopher Tenter committed
43
44
45
46
47
48
#include "ShaderGenerator.hh"
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

49
#include <QFile>
50
51
#include <QFileInfo>
#include <QDir>
52
53
#include <QTextStream>

Christopher Tenter's avatar
Christopher Tenter committed
54
55
56
57

namespace ACG
{

58
#define LIGHTING_CODE_FILE "ShaderGen/SG_LIGHTING.GLSL"
Christopher Tenter's avatar
Christopher Tenter committed
59

Christopher Tenter's avatar
Christopher Tenter committed
60

61
62
63
64
65
66



int ShaderProgGenerator::numModifiers_ = 0;
ShaderModifier* ShaderProgGenerator::modifiers_[32] = {0};

Christopher Tenter's avatar
Christopher Tenter committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82


ShaderGenerator::ShaderGenerator()
{
  version_ = "#version 150"; 
}

ShaderGenerator::~ShaderGenerator()
{

}


void ShaderGenerator::initVertexShaderIO(const ShaderGenDesc* _desc)
{
  addInput("vec4 inPosition");
83
84
  addOutput("vec4 outPosCS");

Christopher Tenter's avatar
Christopher Tenter committed
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

  if (_desc->shadeMode != SG_SHADE_UNLIT)
    addInput("vec3 inNormal");

  if (_desc->textured)
  {
    addInput("vec2 inTexCoord");
    addOutput("vec2 outTexCoord");
  }
  if (_desc->vertexColors)
    addInput("vec4 inColor");


  if (_desc->shadeMode == SG_SHADE_PHONG)
  {
    addOutput("vec3 outNormal");
    addOutput("vec4 outPosVS");
  }


  std::string strColorOut = "";

  if (_desc->shadeMode == SG_SHADE_FLAT)
    strColorOut = "flat out vec4 outColor;";
  else
  {
    if (_desc->shadeMode == SG_SHADE_GOURAUD ||
      _desc->vertexColors)
      strColorOut = "vec4 outColor";
  }

  if (strColorOut.size())
    addOutput(strColorOut.c_str());
}



void ShaderGenerator::initFragmentShaderIO(const ShaderGenDesc* _desc)
{
  if (_desc->textured)
    addInput("vec2 outTexCoord");

127
  addInput("vec4 outPosCS");
Christopher Tenter's avatar
Christopher Tenter committed
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

  std::string strColorOut = "";

  if (_desc->shadeMode == SG_SHADE_FLAT)
    strColorOut = "flat in vec4 outColor;";
  else
  {
    if (_desc->shadeMode == SG_SHADE_GOURAUD ||
      _desc->vertexColors)
      strColorOut = "vec4 outColor";
  }

  if (strColorOut.size())
    addInput(strColorOut.c_str());


  if (_desc->shadeMode == SG_SHADE_PHONG)
  {
    addInput("vec3 outNormal");
    addInput("vec4 outPosVS");
  }

  addOutput("vec4 outFragment");
}




void ShaderGenerator::initDefaultUniforms()
{
  addUniform("mat4 g_mWVP");
  addUniform("mat4 g_mWV");
  addUniform("mat3 g_mWVIT");
  addUniform("mat4 g_mP");

  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");
}


174
#define ADDLIGHT(x) (sz.sprintf(x"_%d", lightIndex_), addUniform(sz))
Christopher Tenter's avatar
Christopher Tenter committed
175
176
177

void ShaderGenerator::addLight(int lightIndex_, ShaderGenLightType _light)
{
178
  QString sz;
Christopher Tenter's avatar
Christopher Tenter committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204

  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");
}






205
void ShaderGenerator::addStringToList(QString _str, 
206
207
208
                                      QStringList* _arr,
                                      const char* _prefix,
                                      const char* _postfix)
Christopher Tenter's avatar
Christopher Tenter committed
209
{
210
  QString tmp;
Christopher Tenter's avatar
Christopher Tenter committed
211
212
213
214
215


  if (_prefix)
  {
    // set prefix, if wanted
216
    if (!_str.contains(_prefix))
Christopher Tenter's avatar
Christopher Tenter committed
217
218
219
220
221
222
223
      tmp += _prefix;

    tmp += _str;
  }

  if (_postfix)
  {
224
    if (!_str.contains(_postfix))
Christopher Tenter's avatar
Christopher Tenter committed
225
226
227
228
229
      tmp += _postfix;
  }

  // normalize string
  //  remove tabs, double whitespace
230
  tmp = tmp.simplified();
Christopher Tenter's avatar
Christopher Tenter committed
231
232
233
234



  // avoid duplicates
235
236
  if (!_arr->contains(tmp))
    _arr->push_back(tmp);
Christopher Tenter's avatar
Christopher Tenter committed
237
238
239
240

}


241
void ShaderGenerator::addInput(QString _input)
Christopher Tenter's avatar
Christopher Tenter committed
242
243
244
245
246
247
{
  addStringToList(_input, &inputs_, "in ", ";");
}



248
void ShaderGenerator::addOutput(QString _output)
Christopher Tenter's avatar
Christopher Tenter committed
249
250
251
252
253
{
  addStringToList(_output, &outputs_, "out ", ";");
}


254
void ShaderGenerator::addDefine(QString _def)
Christopher Tenter's avatar
Christopher Tenter committed
255
256
257
258
259
260
261
{
  addStringToList(_def, &genDefines_, "#define ");
}




262
void ShaderGenerator::addUniform(QString _uniform)
Christopher Tenter's avatar
Christopher Tenter committed
263
264
265
266
267
268
{
  addStringToList(_uniform, &uniforms_, "uniform ", ";");
}



269
void ShaderGenerator::addIOToCode(const QStringList& _cmds)
Christopher Tenter's avatar
Christopher Tenter committed
270
{
271
272
  QString it;
  foreach(it, _cmds)
Christopher Tenter's avatar
Christopher Tenter committed
273
  {
274
    code_.push_back(it);
Christopher Tenter's avatar
Christopher Tenter committed
275
276
    // append ; eventually

277
    if (!it.contains(";"))
Christopher Tenter's avatar
Christopher Tenter committed
278
279
280
281
282
283
      code_.back().append(";");
  }
}



284
void ShaderGenerator::buildShaderCode(QStringList* _pMainCode)
Christopher Tenter's avatar
Christopher Tenter committed
285
286
287
288
{
  code_.push_back(version_);

  // provide defines
289
  QString it;
Christopher Tenter's avatar
Christopher Tenter committed
290

291
292
  foreach(it, genDefines_)
    code_.push_back(it);
Christopher Tenter's avatar
Christopher Tenter committed
293

294
295
296
  // provide imports
  foreach(it, imports_)
    code_.push_back(it);
Christopher Tenter's avatar
Christopher Tenter committed
297

298
  // IO
Christopher Tenter's avatar
Christopher Tenter committed
299
300
301
302
303
  addIOToCode(inputs_);
  addIOToCode(outputs_);
  addIOToCode(uniforms_);

  // main function
304
305
  foreach(it, (*_pMainCode))
    code_.push_back(it);
Christopher Tenter's avatar
Christopher Tenter committed
306
307
308
309
310
311


}



312
void ShaderGenerator::addIncludeFile(QString _fileName)
Christopher Tenter's avatar
Christopher Tenter committed
313
{
314
  QFile file(_fileName);
Christopher Tenter's avatar
Christopher Tenter committed
315

Christopher Tenter's avatar
Christopher Tenter committed
316
  if (file.open(QIODevice::ReadOnly | QIODevice::Text))
Christopher Tenter's avatar
Christopher Tenter committed
317
  {
Christopher Tenter's avatar
Christopher Tenter committed
318
319
320
321
322
    QTextStream fileStream(&file);

    while (!fileStream.atEnd())
    {
      QString tmpLine = fileStream.readLine();
Christopher Tenter's avatar
Christopher Tenter committed
323

Christopher Tenter's avatar
Christopher Tenter committed
324
325
      imports_.push_back(tmpLine.simplified());
    }
Christopher Tenter's avatar
Christopher Tenter committed
326
327
328
329
330
331
332
333
  }

}



void ShaderGenerator::saveToFile(const char* _fileName)
{
334
  QFile file(_fileName);
Christopher Tenter's avatar
Christopher Tenter committed
335
336
337
  if (file.open(QIODevice::WriteOnly | QIODevice::Text))
  {
    QTextStream fileStream(&file);
Christopher Tenter's avatar
Christopher Tenter committed
338

Christopher Tenter's avatar
Christopher Tenter committed
339
340
341
342
    QString it;
    foreach(it, code_)
      fileStream << it << '\n';
  }
Christopher Tenter's avatar
Christopher Tenter committed
343
344
345
346
}



347
const QStringList& ShaderGenerator::getShaderCode()
Christopher Tenter's avatar
Christopher Tenter committed
348
349
350
351
352
353
354
{
  return code_;
}




355
QString ShaderProgGenerator::shaderDir_;
356
QStringList ShaderProgGenerator::lightingCode_;
Christopher Tenter's avatar
Christopher Tenter committed
357

358
359
360
ShaderProgGenerator::ShaderProgGenerator(const ShaderGenDesc* _desc,
                                         unsigned int _usage)
: vertex_(0), fragment_(0), usage_(_usage)
Christopher Tenter's avatar
Christopher Tenter committed
361
{
362
363
364
365
366
  if (shaderDir_.isEmpty())
    std::cout << "error: call ShaderProgGenerator::setShaderDir() first!" << std::endl;
  else
  {
    memcpy(&desc_, _desc, sizeof(ShaderGenDesc));
Christopher Tenter's avatar
Christopher Tenter committed
367

368
    loadLightingFunctions();
Christopher Tenter's avatar
Christopher Tenter committed
369

370
371
    generateShaders();
  }
Christopher Tenter's avatar
Christopher Tenter committed
372
373
374
375
376
377
378
379
380
381
}

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



Christopher Tenter's avatar
Christopher Tenter committed
382
void ShaderProgGenerator::loadStringListFromFile(QString _fileName, QStringList* _out)
Christopher Tenter's avatar
Christopher Tenter committed
383
{
384
  QFile file(_fileName);
Christopher Tenter's avatar
Christopher Tenter committed
385

386
387
388
  file.open(QIODevice::ReadOnly | QIODevice::Text);

  if (!file.isReadable())
Christopher Tenter's avatar
Christopher Tenter committed
389
    std::cout << "error: file missing -> \"" << (const char*)_fileName.toAscii() << "\"" << std::endl;
Christopher Tenter's avatar
Christopher Tenter committed
390
391
392

  else
  {
393
    QTextStream filestream(&file);
Christopher Tenter's avatar
Christopher Tenter committed
394

395
    while (!filestream.atEnd())
Christopher Tenter's avatar
Christopher Tenter committed
396
    {
397
398
      QString szLine = filestream.readLine();
      _out->push_back(szLine.trimmed());
Christopher Tenter's avatar
Christopher Tenter committed
399
400
401
402
403
404
405
406
407
408
    }
  }
}


void ShaderProgGenerator::loadLightingFunctions()
{
  if (lightingCode_.size()) return;

  // load shader code from file
409
  loadStringListFromFile(shaderDir_ + QDir::separator() + QString(LIGHTING_CODE_FILE), &lightingCode_);
Christopher Tenter's avatar
Christopher Tenter committed
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
}



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");

  // # lights define
438
439
440
  QString strNumLights;
  strNumLights.sprintf("SG_NUM_LIGHTS %d", desc_.numLights);
  _gen->addDefine(strNumLights);
Christopher Tenter's avatar
Christopher Tenter committed
441
442
443
444
445
446
447
448
449
450
451

  // 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)
  {
452
453
454
    QString strLightType;
    strLightType.sprintf("SG_LIGHT_TYPE_%d %s", i, lightTypeNames[desc_.lightTypes[i]]);
    _gen->addDefine(strLightType);
Christopher Tenter's avatar
Christopher Tenter committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
  }
}




void ShaderProgGenerator::buildVertexShader()
{
  delete vertex_;

  vertex_  = new ShaderGenerator();


//  vertex_->initDefaultVertexShaderIO();
  vertex_->initVertexShaderIO(&desc_);
470

Christopher Tenter's avatar
Christopher Tenter committed
471
472
  vertex_->initDefaultUniforms();

473
474
  vertex_->addUniform("float g_PointSize");

Christopher Tenter's avatar
Christopher Tenter committed
475

476
477
478
479
480
481
482
483
  // apply i/o modifiers
  for (int i = 0; i < numModifiers_; ++i)
  {
    if (usage_ & (1 << i))
      modifiers_[i]->modifyVertexIO(vertex_);
  }


Christopher Tenter's avatar
Christopher Tenter committed
484
485
486
487
  initGenDefines(vertex_);



488
  // IO
Christopher Tenter's avatar
Christopher Tenter committed
489
490
491
492
493
494
495
496
497
498
499

  // 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
500
  QStringList mainCode;
Christopher Tenter's avatar
Christopher Tenter committed
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518

  addLightingFunctions(&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

519
520
    QString it;
    foreach(it,vertexTemplate_)
Christopher Tenter's avatar
Christopher Tenter committed
521
    {
522
      if (!checkForIncludes(it, vertex_, getPathName(vertexShaderFile_)))
Christopher Tenter's avatar
Christopher Tenter committed
523
524
525
526
      {
        // str line is no include directive
        // check for SG_ markers

527
        if (it.contains("SG_VERTEX_BEGIN"))
Christopher Tenter's avatar
Christopher Tenter committed
528
529
530
          addVertexBeginCode(&mainCode);
        else
        {
531
          if (it.contains("SG_VERTEX_END"))
Christopher Tenter's avatar
Christopher Tenter committed
532
533
534
535
            addVertexEndCode(&mainCode);
          else
          {
            // no SG marker
536
            mainCode.push_back(it);
Christopher Tenter's avatar
Christopher Tenter committed
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
          }
        }

      }
    }

  }



  vertex_->buildShaderCode(&mainCode);

}


552
void ShaderProgGenerator::addVertexBeginCode(QStringList* _code)
Christopher Tenter's avatar
Christopher Tenter committed
553
{
554
555
556
  // size in pixel of rendered point-lists, set by user via uniform
  _code->push_back("gl_PointSize = g_PointSize;");

Christopher Tenter's avatar
Christopher Tenter committed
557
558
559
560
  _code->push_back("vec4 sg_vPosPS = g_mWVP * inPosition;");
  _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("vec2 sg_vTexCoord = vec2(0.0, 0.0);");
561
  _code->push_back("vec4 sg_cColor = vec4(g_cEmissive, ALPHA);");
Christopher Tenter's avatar
Christopher Tenter committed
562
563

  if (desc_.shadeMode != SG_SHADE_UNLIT)
564
    _code->push_back("sg_vNormalVS = normalize(g_mWVIT * inNormal);");
Christopher Tenter's avatar
Christopher Tenter committed
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580

  if (desc_.textured)
    _code->push_back("sg_vTexCoord = inTexCoord;");

  if (desc_.vertexColors)
    _code->push_back("sg_cColor = inColor;");

  if (desc_.shadeMode == SG_SHADE_GOURAUD ||
    desc_.shadeMode == SG_SHADE_FLAT)
  {
    // add lighting code here

    addLightingCode(_code);
  }


581
582
583
584
585
586
587

  // apply modifiers
  for (int i = 0; i < numModifiers_; ++i)
  {
    if (usage_ & (1 << i))
      modifiers_[i]->modifyVertexBeginCode(_code);
  }
Christopher Tenter's avatar
Christopher Tenter committed
588
589
590
}


591
void ShaderProgGenerator::addVertexEndCode(QStringList* _code)
Christopher Tenter's avatar
Christopher Tenter committed
592
593
{
  _code->push_back("gl_Position = sg_vPosPS;");
594
  _code->push_back("outPosCS = sg_vPosPS;");
Christopher Tenter's avatar
Christopher Tenter committed
595
596
597
598
599
600
601
602
603
604
605
606
607
608

  if (desc_.textured)
    _code->push_back("outTexCoord = sg_vTexCoord;");

  if (desc_.shadeMode == SG_SHADE_GOURAUD ||
    desc_.shadeMode == SG_SHADE_FLAT ||
    desc_.vertexColors)
    _code->push_back("outColor = sg_cColor;");

  if (desc_.shadeMode == SG_SHADE_PHONG)
  {
    _code->push_back("outNormal = sg_vNormalVS;");
    _code->push_back("outPosVS = sg_vPosVS;");
  }
609
610
611
612
613
614
615
616
617



  // apply modifiers
  for (int i = 0; i < numModifiers_; ++i)
  {
    if (usage_ & (1 << i))
      modifiers_[i]->modifyVertexEndCode(_code);
  }
Christopher Tenter's avatar
Christopher Tenter committed
618
619
620
}


621
int ShaderProgGenerator::checkForIncludes(QString _str, ShaderGenerator* _gen, QString _includePath)
Christopher Tenter's avatar
Christopher Tenter committed
622
{
623
  if (_str.contains("#include "))
Christopher Tenter's avatar
Christopher Tenter committed
624
  {
625
    QString strIncludeFile = _str.remove("#include ").remove('\"').remove('<').remove('>').trimmed();
Christopher Tenter's avatar
Christopher Tenter committed
626

627
628
    if (strIncludeFile.isEmpty())
      std::cout << "wrong include syntax: " << (const char*)_str.toAscii() << std::endl;
Christopher Tenter's avatar
Christopher Tenter committed
629
630
    else
    {
631
      QString fullPathToIncludeFile = _includePath + QDir::separator() + strIncludeFile;
Christopher Tenter's avatar
Christopher Tenter committed
632

633
      _gen->addIncludeFile(fullPathToIncludeFile);
Christopher Tenter's avatar
Christopher Tenter committed
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
    }

    return 1;
  }

  return 0;
}

void ShaderProgGenerator::buildFragmentShader()
{
  delete fragment_;

  fragment_  = new ShaderGenerator();


  fragment_->initFragmentShaderIO(&desc_);

651

Christopher Tenter's avatar
Christopher Tenter committed
652
653
654
655
656
657
658
  fragment_->initDefaultUniforms();


  // texture sampler id
  if (desc_.textured)
    fragment_->addUniform("sampler2D g_Texture0");

659
660
661
662
663
664
665
  // apply i/o modifiers
  for (int i = 0; i < numModifiers_; ++i)
  {
    if (usage_ & (1 << i))
      modifiers_[i]->modifyFragmentIO(fragment_);
  }

Christopher Tenter's avatar
Christopher Tenter committed
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683

  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
684
  QStringList mainCode;
Christopher Tenter's avatar
Christopher Tenter committed
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702

  addLightingFunctions(&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
703
704
    QString it;
    foreach(it,fragmentTemplate_)
Christopher Tenter's avatar
Christopher Tenter committed
705
    {
706
      if (!checkForIncludes(it, fragment_, getPathName(fragmentShaderFile_)))
Christopher Tenter's avatar
Christopher Tenter committed
707
708
709
710
      {
        // str line is no include directive
        // check for SG_ markers

711
        if (it.contains("SG_FRAGMENT_BEGIN"))
Christopher Tenter's avatar
Christopher Tenter committed
712
713
714
          addFragmentBeginCode(&mainCode);
        else
        {
715
          if (it.contains("SG_FRAGMENT_END"))
Christopher Tenter's avatar
Christopher Tenter committed
716
717
718
719
            addFragmentEndCode(&mainCode);
          else
          {
            // no SG marker
720
            mainCode.push_back(it);
Christopher Tenter's avatar
Christopher Tenter committed
721
722
723
724
          }
        }

      }
725
726

      
Christopher Tenter's avatar
Christopher Tenter committed
727
728
729
730
731
732
733
734
735
736
    }

  }



  fragment_->buildShaderCode(&mainCode);
}


737
void ShaderProgGenerator::addFragmentBeginCode(QStringList* _code)
Christopher Tenter's avatar
Christopher Tenter committed
738
{
739
740
741
  // support for projective texture mapping
  _code->push_back("vec2 sg_vScreenPos = outPosCS.xy / outPosCS.w * 0.5 + vec2(0.5, 0.5);");

742
  _code->push_back("vec4 sg_cColor = vec4(g_cEmissive, ALPHA);");
Christopher Tenter's avatar
Christopher Tenter committed
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762

  if (desc_.shadeMode == SG_SHADE_GOURAUD ||
    desc_.shadeMode == SG_SHADE_FLAT ||
    desc_.vertexColors)
    _code->push_back("sg_cColor = outColor;");


  if (desc_.shadeMode == SG_SHADE_PHONG)
  {
    _code->push_back("vec4 sg_vPosVS = outPosVS;");
    _code->push_back("vec3 sg_vNormalVS = outNormal;");

    addLightingCode(_code);
  }

  if (desc_.textured)
  {
    _code->push_back("vec4 sg_cTex = texture(g_Texture0, outTexCoord);");
    _code->push_back("sg_cColor *= sg_cTex;");
  }
763
764
765
766
767
768
769
770

  
  // apply modifiers
  for (int i = 0; i < numModifiers_; ++i)
  {
    if (usage_ & (1 << i))
      modifiers_[i]->modifyFragmentBeginCode(_code);
  }
Christopher Tenter's avatar
Christopher Tenter committed
771
772
}

773
void ShaderProgGenerator::addFragmentEndCode(QStringList* _code)
Christopher Tenter's avatar
Christopher Tenter committed
774
775
{
  _code->push_back("outFragment = sg_cColor;");
776
777
778
779
780
781
782

  // apply modifiers
  for (int i = 0; i < numModifiers_; ++i)
  {
    if (usage_ & (1 << i))
      modifiers_[i]->modifyFragmentEndCode(_code);
  }
Christopher Tenter's avatar
Christopher Tenter committed
783
784
785
786
}



787
void ShaderProgGenerator::addLightingCode(QStringList* _code)
Christopher Tenter's avatar
Christopher Tenter committed
788
{
789
  QString buf;
790
  
Christopher Tenter's avatar
Christopher Tenter committed
791
792
793
794
795
796
797
798
  for (int i = 0; i < desc_.numLights; ++i)
  {
    ShaderGenLightType lgt = desc_.lightTypes[i];


    switch (lgt)
    {
    case SG_LIGHT_DIRECTIONAL:
799
      buf.sprintf("sg_cColor.xyz += LitDirLight(sg_vNormalVS, g_vLightDir_%d,  g_cLightAmbient_%d,  g_cLightDiffuse_%d,  g_cLightSpecular_%d);", i, i, i, i);
Christopher Tenter's avatar
Christopher Tenter committed
800
801
802
      break;

    case SG_LIGHT_POINT:
803
      buf.sprintf("sg_cColor.xyz += LitPointLight(sg_vPosVS.xyz, sg_vNormalVS,  g_vLightPos_%d,  g_cLightAmbient_%d,  g_cLightDiffuse_%d,  g_cLightSpecular_%d,  g_vLightAtten_%d);", i, i, i, i, i);
Christopher Tenter's avatar
Christopher Tenter committed
804
805
806
      break;

    case SG_LIGHT_SPOT:
807
      buf.sprintf("sg_cColor.xyz += LitSpotLight(sg_vPosVS.xyz,  sg_vNormalVS,  g_vLightPos_%d,  g_vLightDir_%d,  g_cLightAmbient_%d,  g_cLightDiffuse_%d,  g_cLightSpecular_%d,  g_vLightAtten_%d,  g_vLightAngleExp_%d);", i, i, i, i, i, i, i);
Christopher Tenter's avatar
Christopher Tenter committed
808
809
810
811
812
813
814
815
816
817
818
819
      break;

    default: break;
    }

    _code->push_back(buf);
  }

}



820
void ShaderProgGenerator::addLightingFunctions(QStringList* _code)
Christopher Tenter's avatar
Christopher Tenter committed
821
{
822
823
824
  QString it;
  foreach(it,lightingCode_)
    _code->push_back(it);
Christopher Tenter's avatar
Christopher Tenter committed
825
826
827
828
}

void ShaderProgGenerator::generateShaders()
{
Christopher Tenter's avatar
Christopher Tenter committed
829
  loadShaderTemplateFromFile();
Christopher Tenter's avatar
Christopher Tenter committed
830
831
832
833
834
  buildVertexShader();
  buildFragmentShader();
}


Christopher Tenter's avatar
Christopher Tenter committed
835
836
837
838
839
840
841
842
843
844
const QStringList& ShaderProgGenerator::getVertexShaderCode()
{
  return vertex_->getShaderCode();
}

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

Christopher Tenter's avatar
Christopher Tenter committed
845
846
847
848
849
850
851
852
853
854
855
856

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

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


Christopher Tenter's avatar
Christopher Tenter committed
857
void ShaderProgGenerator::loadShaderTemplateFromFile()
Christopher Tenter's avatar
Christopher Tenter committed
858
{
859
  if (desc_.vertexTemplateFile)
Christopher Tenter's avatar
Christopher Tenter committed
860
    loadStringListFromFile(desc_.vertexTemplateFile, &vertexTemplate_);
861
  if (desc_.fragmentTemplateFile)
Christopher Tenter's avatar
Christopher Tenter committed
862
    loadStringListFromFile(desc_.fragmentTemplateFile, &fragmentTemplate_);
Christopher Tenter's avatar
Christopher Tenter committed
863

Christopher Tenter's avatar
Christopher Tenter committed
864
865
  vertexShaderFile_ = desc_.vertexTemplateFile;
  fragmentShaderFile_ = desc_.fragmentTemplateFile;
Christopher Tenter's avatar
Christopher Tenter committed
866
867
}

868
QString ShaderProgGenerator::getPathName(QString _strFileName)
Christopher Tenter's avatar
Christopher Tenter committed
869
{
870
871
  QFileInfo fileInfo(_strFileName);
  return fileInfo.absolutePath();
Christopher Tenter's avatar
Christopher Tenter committed
872
}
Christopher Tenter's avatar
Christopher Tenter committed
873

874
875
876
877
878
void ShaderProgGenerator::setShaderDir( QString _dir )
{
  shaderDir_ = _dir;
}

879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
unsigned int ShaderProgGenerator::registerModifier( ShaderModifier* _modifier )
{
  if (!_modifier) return 0;

  // redundancy check
  for (unsigned int i = 0; i < 32; ++i)
  {
    if (modifiers_[i] == _modifier) 
      return i;
  }

  if (numModifiers_ == 32) 
    return 0;

  modifiers_[numModifiers_++] = _modifier;

  _modifier->modifierID_ = (unsigned int)numModifiers_;
  return _modifier->modifierID_;
}

Christopher Tenter's avatar
Christopher Tenter committed
899

Jan Möbius's avatar
Jan Möbius committed
900
//=============================================================================
901
902
903
904
905
906
907
908

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

ShaderModifier::~ShaderModifier( void )
{}

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
//=============================================================================


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 << "shaderDesc.numLights: " << numLights;

  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;

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

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

  return res;
}

963

Jan Möbius's avatar
Jan Möbius committed
964
965
} // namespace ACG
//=============================================================================