Subversion Repository Public Repository

Divide-Framework

This repository has no backups
This repository's network speed is throttled to 100KB/sec

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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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
#include "stdafx.h"

#include "config.h"

#include "Headers/glShaderProgram.h"

#include "Platform/Video/OpenGL/glsw/Headers/glsw.h"
#include "Platform/Video/OpenGL/Headers/glLockManager.h"

#include "Platform/File/Headers/FileManagement.h"
#include "Platform/Video/Headers/GFXDevice.h"
#include "Platform/Video/OpenGL/Headers/GLWrapper.h"

#include "Core/Headers/Console.h"
#include "Core/Headers/StringHelper.h"
#include "Utility/Headers/Localization.h"

namespace Divide {

namespace {
    size_t g_validationBufferMaxSize = 4096 * 16;
};

std::array<U32, to_base(ShaderType::COUNT)> glShaderProgram::_lineOffset;

IMPLEMENT_CUSTOM_ALLOCATOR(glShaderProgram, 0, 0);

void glShaderProgram::initStaticData() {
    glShader::initStaticData();
}

void glShaderProgram::destroyStaticData() {
    glShader::destroyStaticData();
}

glShaderProgram::glShaderProgram(GFXDevice& context,
                                 size_t descriptorHash,
                                 const stringImpl& name,
                                 const stringImpl& resourceName,
                                 const stringImpl& resourceLocation,
                                 bool asyncLoad)
    : ShaderProgram(context, descriptorHash, name, resourceName, resourceLocation, asyncLoad),
      glObject(glObjectType::TYPE_SHADER_PROGRAM, context),
      _loadedFromBinary(false),
      _validated(false),
      _shaderProgramIDTemp(0),
      _lockManager(MemoryManager_NEW glLockManager()),
      _binaryFormat(GL_NONE)
{
    _validationQueued = false;
    // each API has it's own invalid id. This is OpenGL's
    _shaderProgramID = GLUtil::_invalidObjectID;
    // pointers to all of our shader stages
    _shaderStage.fill(nullptr);
}

glShaderProgram::~glShaderProgram()
{
    if (_lockManager) {
        _lockManager->Wait(true);
        MemoryManager::DELETE(_lockManager);
    }

    if (isBound()) {
        unbind();
    }

    // delete shader program
    if (_shaderProgramID > 0 && _shaderProgramID != GLUtil::_invalidObjectID) {
        GL_API::deleteShaderPrograms(1, &_shaderProgramID);
        // glDeleteProgramPipelines(1, &_shaderProgramID);
    }
}

bool glShaderProgram::unload() {
    // Remove every shader attached to this program
    for (glShader* shader : _shaderStage) {
        if (shader) {
            glShader::removeShader(shader);
        }
    }

    return ShaderProgram::unload();
}

/// Basic OpenGL shader program validation (both in debug and in release)
bool glShaderProgram::validateInternal() {
    bool shaderError = false;
    for (glShader* shader : _shaderStage) {
        // If a shader exists for said stage
        if (shader) {
            // Validate it
            if (!shader->validate()) {
                shaderError = true;
            }
        }
    }

    GLint status = 0;
    glValidateProgram(_shaderProgramID);
    glGetProgramiv(_shaderProgramID, GL_VALIDATE_STATUS, &status);
    // glValidateProgramPipeline(_shaderProgramID);
    // glGetProgramPipelineiv(_shaderProgramID, GL_VALIDATE_STATUS, &status);
    // we print errors in debug and in release, but everything else only in
    // debug
    // the validation log is only retrieved if we request it. (i.e. in release,
    // if the shader is validated, it isn't retrieved)
    if (status == 0) {
        Console::errorfn(Locale::get(_ID("GLSL_VALIDATING_PROGRAM")),
                         _shaderProgramID, getName().c_str(), getLog().c_str());
        shaderError = true;
    } else {
        Console::d_printfn(Locale::get(_ID("GLSL_VALIDATING_PROGRAM")),
                           _shaderProgramID, getName().c_str(), getLog().c_str());
    }
    _validated = true;

    return shaderError;
}

/// Called once per frame. Used to update internal state
bool glShaderProgram::update(const U64 deltaTimeUS) {
    // If we haven't validated the program but used it at lease once ...
    if (_validationQueued && _shaderProgramID != 0) {
        if (_lockManager) {
            _lockManager->Wait(true);
            MemoryManager::DELETE(_lockManager);
        }
        // Call the internal validation function
        validateInternal();

        // We dump the shader binary only if it wasn't loaded from one
        if (!_loadedFromBinary) {
            // Get the size of the binary code
            GLint binaryLength = 0;
            glGetProgramiv(_shaderProgramID, GL_PROGRAM_BINARY_LENGTH, &binaryLength);
            // allocate a big enough buffer to hold it
            char* binary = MemoryManager_NEW char[binaryLength];
            DIVIDE_ASSERT(binary != NULL,
                          "glShaderProgram error: could not allocate memory "
                          "for the program binary!");
            // and fill the buffer with the binary code
            glGetProgramBinary(_shaderProgramID, binaryLength, NULL, &_binaryFormat, binary);
            if (_binaryFormat != GL_NONE) {
                // dump the buffer to file
                stringImpl outFileName(Paths::g_cacheLocation + Paths::Shaders::g_cacheLocationBin + getName() + ".bin");
                writeFile(outFileName, binary, (size_t)binaryLength, FileType::BINARY);
                // dump the format to a separate file (highly non-optimised. Should dump formats to a database instead)
                outFileName += ".fmt";
                stringImpl binaryFormatStr = to_stringImpl(to_U32(_binaryFormat));
                writeFile(outFileName, (bufferPtr)binaryFormatStr.c_str(), binaryFormatStr.size(), FileType::BINARY);
             }
            // delete our local code buffer
            MemoryManager::DELETE(binary);
        }
        // clear validation queue flag
        _validationQueued = false;
    }

    // pass the update responsibility back to the parent class
    return ShaderProgram::update(deltaTimeUS);
}

/// Retrieve the program's validation log if we need it
stringImpl glShaderProgram::getLog() const {
    // We default to a simple OK message if the log is empty (hopefully, that
    // means validation was successful, nVidia ... )
    stringImpl validationBuffer("[OK]");
    // Query the size of the log
    GLint length = 0;
    glGetProgramiv(_shaderProgramIDTemp, GL_INFO_LOG_LENGTH, &length);
    // glGetProgramPipelineiv(_shaderProgramIDTemp, GL_INFO_LOG_LENGTH,
    // &length);
    // If we actually have something in the validation log
    if (length > 1) {
        // Delete our OK string, and start on a new line
        validationBuffer = "\n -- ";
        // This little trick avoids a "NEW/DELETE" set of calls and still gives
        // us a linear array of char's
        vectorImpl<char> shaderProgramLog(length);
        glGetProgramInfoLog(_shaderProgramIDTemp, length, NULL,
                            &shaderProgramLog[0]);
        // glGetProgramPipelineInfoLog(_shaderProgramIDTemp, length, NULL,
        //                    &shaderProgramLog[0]);
        // Append the program's log to the output message
        validationBuffer.append(&shaderProgramLog[0]);
        // To avoid overflowing the output buffers (both CEGUI and Console),
        // limit the maximum output size
        if (validationBuffer.size() > g_validationBufferMaxSize) {
            // On some systems, the program's disassembly is printed, and that can get quite large
            validationBuffer.resize(std::strlen(Locale::get(_ID("GLSL_LINK_PROGRAM_LOG"))) + g_validationBufferMaxSize);
            // Use the simple "truncate and inform user" system (a.k.a. add dots and delete the rest)
            validationBuffer.append(" ... ");
        }
    }
    // Return the final message, whatever it may contain
    return validationBuffer;
}

/// Remove a shader stage from this program
void glShaderProgram::detachShader(glShader* const shader) {
    if (!shader) {
        return;
    }

    glDetachShader(_shaderProgramID == GLUtil::_invalidObjectID
                                     ? _shaderProgramIDTemp
                                     : _shaderProgramID,
                   shader->getShaderID());
    // glUseProgramStages(_shaderProgramID,
    // GLUtil::glShaderStageTable[to_U32(shader->getType())], 0);
}

/// Add a new shader stage to this program
void glShaderProgram::attachShader(glShader* const shader) {
    if (!shader) {
        return;
    }
    // Attach the shader
    glAttachShader(_shaderProgramID == GLUtil::_invalidObjectID
                                     ? _shaderProgramIDTemp
                                     : _shaderProgramID,
                   shader->getShaderID());
    // glUseProgramStages(_shaderProgramIDTemp,
    // GLUtil::glShaderStageTable[to_U32(shader->getType())], shaderID);
    // Clear the 'linked' flag. Program must be re-linked before usage
    _linked = false;
}

/// This should be called in the loading thread, but some issues are still
/// present, and it's not recommended (yet)
void glShaderProgram::threadedLoad(DELEGATE_CBK<void, CachedResource_wptr> onLoadCallback, bool skipRegister) {
    if (_asyncLoad) {
        GL_API::createOrValidateContextForCurrentThread(_context);
    }

    // Loading from binary gives us a linked program ready for usage.
    if (!_loadedFromBinary) {
        // If this wasn't loaded from binary, we need a new API specific object
        // If we try to refresh the program, we already have a handle
        if (_shaderProgramID == GLUtil::_invalidObjectID) {
            _shaderProgramIDTemp = glCreateProgram();
            // glCreateProgramPipelines(1, &_shaderProgramIDTemp);
        } else {
            _shaderProgramIDTemp = _shaderProgramID;
        }
        // For every possible stage that the program might use
        for (glShader* shader : _shaderStage) {
            // If a shader exists for said stage
            if (shader) {
                // Attach it
                attachShader(shader);
            }
        }
        // Link the program
        link();
    }
    // This was once an atomic swap. Might still be in the future
    _shaderProgramID = _shaderProgramIDTemp;
    // Pass the rest of the loading steps to the parent class
    if (_lockManager) {
        _lockManager->Lock();
    }

    if (!skipRegister) {
        ShaderProgram::load(onLoadCallback);
    } else {
        reuploadUniforms();
    }
}

/// Linking a shader program also sets up all pre-link properties for the shader
/// (varying locations, attrib bindings, etc)
void glShaderProgram::link() {
    if (!Config::Build::IS_DEBUG_BUILD) {
        // Loading from binary is optional, but it using it does require sending the
        // driver a hint to give us access to it later
        if (Config::USE_SHADER_BINARY) {
            glProgramParameteri(_shaderProgramIDTemp, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, 1);
        }
    }

    Console::d_printfn(Locale::get(_ID("GLSL_LINK_PROGRAM")), getName().c_str(),
                       _shaderProgramIDTemp);

    /*glProgramParameteri(_shaderProgramIDTemp,
                        GL_PROGRAM_SEPARABLE,
                        1);
    */
    // Link the program
    glLinkProgram(_shaderProgramIDTemp);
    // Detach shaders after link so that the driver might free up some memory
    // remove shader stages
    for (glShader* shader : _shaderStage) {
        detachShader(shader);
    }

    _shaderVarLocation.clear();

    // And check the result
    GLint linkStatus = 0;
    glGetProgramiv(_shaderProgramIDTemp, GL_LINK_STATUS, &linkStatus);
    // If linking failed, show an error, else print the result in debug builds.
    // Same getLog() method is used
    if (linkStatus == 0) {
        Console::errorfn(Locale::get(_ID("GLSL_LINK_PROGRAM_LOG")),
                         getName().c_str(), getLog().c_str());
        if (_lockManager) {
            MemoryManager::DELETE(_lockManager);
        }
    } else {
        Console::d_printfn(Locale::get(_ID("GLSL_LINK_PROGRAM_LOG")),
                           getName().c_str(), getLog().c_str());
        // The linked flag is set to true only if linking succeeded
        _linked = true;
        if (Config::ENABLE_GPU_VALIDATION) {
            glObjectLabel(GL_PROGRAM, _shaderProgramIDTemp, -1, getName().c_str());
        }
    }
}

bool glShaderProgram::loadFromBinary() {
    _loadedFromBinary = false;

    if (!Config::Build::IS_DEBUG_BUILD) {
        // Load the program from the binary file, if available and allowed, to avoid linking.
        if (Config::USE_SHADER_BINARY && false) {
            // Only available for new programs
            assert(_shaderProgramIDTemp == 0);
            stringImpl fileName(Paths::g_cacheLocation + Paths::Shaders::g_cacheLocationBin + _resourceName + ".bin");
            // Load the program's binary format from file
            vectorImpl<Byte> data;
            bool fmtExists = readFile(fileName + ".fmt", data, FileType::BINARY);
            if (fmtExists) {
                _binaryFormat = *((GLenum const *)&data[0]);
            }

            if (fmtExists && _binaryFormat != GL_ZERO/* && _binaryFormat != GL_NONE*/) {
                data.clear();
                readFile(fileName, data, FileType::BINARY);
                   // Allocate a new handle
                _shaderProgramIDTemp = glCreateProgram();
                // glCreateProgramPipelines(1, &_shaderProgramIDTemp);
                // Load binary code on the GPU
                glProgramBinary(_shaderProgramIDTemp, _binaryFormat, data.data(), (GLint)data.size());
                // Check if the program linked successfully on load
                GLint success = 0;
                glGetProgramiv(_shaderProgramIDTemp, GL_LINK_STATUS, &success);
                // If it loaded properly set all appropriate flags (this also
                // prevents low level access to the program's shaders)
                if (success == 1) {
                    _loadedFromBinary = _linked = true;
                }
            }
        }
    }

    return _loadedFromBinary;
}

glShaderProgram::glShaderProgramLoadInfo glShaderProgram::buildLoadInfo() {
    glShaderProgramLoadInfo loadInfo;

    loadInfo._resourcePath = getResourceLocation() + "/" + Paths::Shaders::GLSL::g_parentShaderLoc;
    // Get all of the preprocessor defines and add them to the general shader header for this program
    for (U8 i = 0; i < _definesList.size(); ++i) {
        // Placeholders are ignored
        if (_definesList[i].compare("DEFINE_PLACEHOLDER") == 0) {
            continue;
        }
        // We manually add define dressing
        loadInfo._header.append("#define " + _definesList[i] + "\n");
    }

    // Split the shader name to get the effect file name and the effect properties
    // The effect file name is the part up until the first period or comma symbol
    loadInfo._programName = _resourceName.substr(0, _resourceName.find_first_of(".,"));
    // We also differentiate between general properties, and vertex properties
    // Get the position of the first "," symbol. Must be added at the end of the program's name!!
    stringAlg::stringSize propPositionVertex = _resourceName.find_first_of(",");
    // Get the position of the first "." symbol
    stringAlg::stringSize propPosition = _resourceName.find_first_of(".");
    // If we have effect properties, we extract them from the name
    // (starting from the first "." symbol to the first "," symbol)
    if (propPosition != stringImpl::npos) {
        loadInfo._programProperties = "." +
            _resourceName.substr(propPosition + 1,
                propPositionVertex - propPosition - 1);
    }
    // Vertex properties start off identically to the rest of the stages' names
    loadInfo._vertexStageProperties = loadInfo._programProperties;
    // But we also add the shader specific properties
    if (propPositionVertex != stringImpl::npos) {
        loadInfo._vertexStageProperties += "." + _resourceName.substr(propPositionVertex + 1);
    }

    return loadInfo;
}

std::pair<bool, stringImpl> glShaderProgram::loadSourceCode(ShaderType stage,
                                                            const stringImpl& stageName,
                                                            const stringImpl& header,
                                                            bool forceReParse) {
    std::pair<bool, stringImpl> sourceCode;
    sourceCode.first = false;

    if (s_useShaderTextCache && !forceReParse) {
        ShaderProgram::shaderFileRead(Paths::g_cacheLocation + 
                                      Paths::Shaders::g_cacheLocationText + stageName,
                                      true,
                                      sourceCode.second);
    }

    if (sourceCode.second.empty()) {
        sourceCode.first = true;
        // Use GLSW to read the appropriate part of the effect file
        // based on the specified stage and properties
        const char* sourceCodeStr = glswGetShader(stageName.c_str());
        sourceCode.second = sourceCodeStr ? sourceCodeStr : "";
        // GLSW may fail for various reasons (not a valid effect stage, invalid name, etc)
        if (!sourceCode.second.empty()) {
            // And replace in place with our program's headers created earlier
            Util::ReplaceStringInPlace(sourceCode.second, "//__CUSTOM_DEFINES__", header);
        }
    }

    return sourceCode;
}

/// Creation of a new shader program. Pass in a shader token and use glsw to
/// load the corresponding effects
bool glShaderProgram::load(const DELEGATE_CBK<void, CachedResource_wptr>& onLoadCallback) {
    // NULL shader means use shaderProgram(0), so bypass the normal
    // loading routine
    if (_resourceName.compare("NULL") == 0) {
        _validationQueued = false;
        _shaderProgramID = 0;
        return ShaderProgram::load(onLoadCallback);
    }

    // Reset the linked status of the program
    _linked = false;

    if (!loadFromBinary()) {
        reloadShaders(false);
    }

    // try to link the program in a separate thread
    return _context.loadInContext(
        !_loadedFromBinary && _asyncLoad
            ? CurrentContext::GFX_LOADING_CTX
            : CurrentContext::GFX_RENDERING_CTX,
        [this, onLoadCallback](const Task& parent){
            threadedLoad(std::move(onLoadCallback), false);
        });
}

void glShaderProgram::reloadShaders(bool reparseShaderSource) {
    glShaderProgramLoadInfo info = buildLoadInfo();
    registerAtomFile(info._programName + ".glsl");

    glswClearCurrentContext();
    // The program wasn't loaded from binary, so process shaders
    // Use the specified shader path
    glswSetPath(info._resourcePath.c_str(), ".glsl");

    // For every stage
    for (U32 i = 0; i < to_base(ShaderType::COUNT); ++i) {
        // Brute force conversion to an enum
        ShaderType type = static_cast<ShaderType>(i);
        stringImpl shaderCompileName(info._programName +
                                     "." +
                                     GLUtil::glShaderStageNameTable[i] +
                                     info._vertexStageProperties);
        glShader*& shader = _shaderStage[i];

        // We ask the shader manager to see if it was previously loaded elsewhere
        shader = glShader::getShader(shaderCompileName);
        // If this is the first time this shader is loaded ...
        if (!shader || reparseShaderSource) {
            std::pair<bool, stringImpl> sourceCode = loadSourceCode(type, shaderCompileName, info._header, reparseShaderSource);
            if (!sourceCode.second.empty()) {
                // Load our shader from the final string and save it in the manager in case a new Shader Program needs it
                shader = glShader::loadShader(_context,
                                              shaderCompileName,
                                              sourceCode.second,
                                              type,
                                              sourceCode.first,
                                              _lineOffset[i] + to_U32(_definesList.size()) - 1);
                if (shader) {
                    // Try to compile the shader (it doesn't double compile shaders, so it's safe to call it multiple times)
                    if (!shader->compile()) {
                        Console::errorfn(Locale::get(_ID("ERROR_GLSL_COMPILE")), shader->getShaderID(), shaderCompileName.c_str());
                    }
                }
            }
        } else {
            shader->AddRef();
            Console::d_printfn(Locale::get(_ID("SHADER_MANAGER_GET_INC")), shader->getName().c_str(), shader->GetRef());
        }

        if (shader) {
            for (const stringImpl& atoms : shader->usedAtoms()) {
                registerAtomFile(atoms);
            }
        } else {
            Console::d_printfn(Locale::get(_ID("WARN_GLSL_LOAD")), shaderCompileName.c_str());
        }
    }
}

bool glShaderProgram::recompileInternal() {
    // Remember bind state
    bool wasBound = isBound();
    if (wasBound) {
        unbind();
    }

    if (_resourceName.compare("NULL") == 0) {
        _validationQueued = false;
        _shaderProgramID = 0;
        return true;
    }
    if (_lockManager) {
        _lockManager->Wait(true);
        MemoryManager::DELETE(_lockManager);
    }

    reloadShaders(true);
    threadedLoad(DELEGATE_CBK<void, Resource_wptr>(), true);
    // Restore bind state
    if (wasBound) {
        bind();
    }
    return getState() == ResourceState::RES_LOADED;
}

/// Check every possible combination of flags to make sure this program can be used for rendering
bool glShaderProgram::isValid() const {
    // null shader is a valid shader
    return _shaderProgramID == 0 ||
           (_linked && _shaderProgramID != GLUtil::_invalidObjectID);
}

bool glShaderProgram::isBound() const {
    return GL_API::s_activeShaderProgram == _shaderProgramID;
}

/// Cache uniform/attribute locations for shader programs
/// When we call this function, we check our name<->address map to see if we queried the location before
/// If we didn't, ask the GPU to give us the variables address and save it for later use
I32 glShaderProgram::Binding(const char* name) {
    // If the shader can't be used for rendering, just return an invalid address
    if (_shaderProgramID == 0 || !isValid()) {
        return -1;
    }

    // Check the cache for the location
    U64 nameHash = _ID_RT(name);
    ShaderVarMap::const_iterator it = _shaderVarLocation.find(nameHash);
    if (it != std::end(_shaderVarLocation)) {
        return it->second;
    }

    // Cache miss. Query OpenGL for the location
    GLint location = glGetUniformLocation(_shaderProgramID, name);

    // Save it for later reference
    hashAlg::insert(_shaderVarLocation, nameHash, location);

    // Return the location
    return location;
}

/// Bind the NULL shader which should have the same effect as using no shaders at all
bool glShaderProgram::unbind() {
    return GL_API::setActiveProgram(0u);
}

/// Bind this shader program
bool glShaderProgram::bind() {
    // If the shader isn't ready or failed to link, stop here
    if (!isValid()) {
        return false;
    }

    if (_lockManager) {
        _lockManager->Wait(true);
        MemoryManager::DELETE(_lockManager);
    }

    // Set this program as the currently active one
    GL_API::setActiveProgram(_shaderProgramID);
    // After using the shader at least once, validate the shader if needed
    if (!_validated) {
        _validationQueued = true;
    }
    return true;
}

/// This is used to set all of the subroutine indices for the specified shader
/// stage for this program
void glShaderProgram::SetSubroutines(ShaderType type,
                                     const vectorImpl<U32>& indices) const {
    // The shader must be bound before calling this!
    DIVIDE_ASSERT(isBound() && isValid(),
                  "glShaderProgram error: tried to set subroutines on an "
                  "unbound or unlinked program!");
    // Validate data and send to GPU
    if (!indices.empty() && indices[0] != GLUtil::_invalidObjectID) {
        glUniformSubroutinesuiv(GLUtil::glShaderStageTable[to_U32(type)],
                                (GLsizei)indices.size(), indices.data());
    }
}

/// This works exactly like SetSubroutines, but for a single index.
/// If the shader has multiple subroutine uniforms, this will reset the rest!!!
void glShaderProgram::SetSubroutine(ShaderType type, U32 index) const {
    DIVIDE_ASSERT(isBound() && isValid(),
                  "glShaderProgram error: tried to set subroutines on an "
                  "unbound or unlinked program!");

    if (index != GLUtil::_invalidObjectID) {
        U32 value[] = {index};
        glUniformSubroutinesuiv(GLUtil::glShaderStageTable[to_U32(type)], 1,
                                value);
    }
}

/// Returns the number of subroutine uniforms for the specified shader stage
U32 glShaderProgram::GetSubroutineUniformCount(ShaderType type) const {
    DIVIDE_ASSERT(isValid(),
                  "glShaderProgram error: tried to query subroutines on an "
                  "invalid program!");

    I32 subroutineCount = 0;
    glGetProgramStageiv(_shaderProgramID,
                        GLUtil::glShaderStageTable[to_U32(type)],
                        GL_ACTIVE_SUBROUTINE_UNIFORMS, &subroutineCount);

    return std::max(subroutineCount, 0);
}

/// Get the uniform location of the specified subroutine uniform for the
/// specified stage. Not cached!
U32 glShaderProgram::GetSubroutineUniformLocation(
    ShaderType type, const char* name) const {
    DIVIDE_ASSERT(isValid(),
                  "glShaderProgram error: tried to query subroutines on an "
                  "invalid program!");

    return glGetSubroutineUniformLocation(
        _shaderProgramID, GLUtil::glShaderStageTable[to_U32(type)],
        name);
}

/// Get the index of the specified subroutine name for the specified stage. Not cached!
U32 glShaderProgram::GetSubroutineIndex(ShaderType type, const char* name) const {
    DIVIDE_ASSERT(isValid(),
                  "glShaderProgram error: tried to query subroutines on an "
                  "invalid program!");

    return glGetSubroutineIndex(_shaderProgramID,
                                GLUtil::glShaderStageTable[to_U32(type)],
                                name);
}

I32 glShaderProgram::cachedValueUpdate(const GFX::PushConstant& constant) {

    const char* location = constant._binding.c_str();
    U64 locationHash = _ID_RT(location);

    I32 binding = Binding(location);

    if (binding == -1 || _shaderProgramID == 0) {
        return -1;
    }

    UniformsByNameHash::ShaderVarMap::iterator it = _uniformsByNameHash._shaderVars.find(locationHash);
    if (it != std::end(_uniformsByNameHash._shaderVars)) {
        if (it->second == constant) {
            return -1;
        } else {
            it->second.assign(constant);
        }
    } else {
        hashAlg::emplace(_uniformsByNameHash._shaderVars, locationHash, constant);
    }

    return binding;
}

void glShaderProgram::Uniform(I32 binding, GFX::PushConstantType type, const vectorImpl<char>& values, bool flag) const {
    GLsizei byteCount = (GLsizei)values.size();
    switch (type) {
        case GFX::PushConstantType::BOOL:
            glProgramUniform1iv(_shaderProgramID, binding, byteCount / (1 * 1), (GLint*)castData<GLbyte, 1, char>(values));
            break;
        case GFX::PushConstantType::INT:
            glProgramUniform1iv(_shaderProgramID, binding, byteCount / (1 * 4), castData<GLint, 1, I32>(values));
            break;
        case GFX::PushConstantType::UINT:
            glProgramUniform1uiv(_shaderProgramID, binding, byteCount / (1 * 4), castData<GLuint, 1, U32>(values));
            break;
        case GFX::PushConstantType::DOUBLE:
            glProgramUniform1dv(_shaderProgramID, binding, byteCount / (1 * 8), castData<GLdouble, 1, D64>(values));
            break;
        case GFX::PushConstantType::FLOAT:
            glProgramUniform1fv(_shaderProgramID, binding, byteCount / (1 * 4), castData<GLfloat, 1, F32>(values));
            break;
        case GFX::PushConstantType::IVEC2:
            glProgramUniform2iv(_shaderProgramID, binding, byteCount / (2 * 4), castData<GLint, 2, vec2<I32>>(values));
            break;
        case GFX::PushConstantType::IVEC3:
            glProgramUniform3iv(_shaderProgramID, binding, byteCount / (3 * 4), castData<GLint, 3, vec3<I32>>(values));
            break;
        case GFX::PushConstantType::IVEC4:
            glProgramUniform4iv(_shaderProgramID, binding, byteCount / (4 * 4), castData<GLint, 4, vec4<I32>>(values));
            break;
        case GFX::PushConstantType::UVEC2:
            glProgramUniform2uiv(_shaderProgramID, binding, byteCount / (2 * 4), castData<GLuint, 2, vec2<U32>>(values));
            break;
        case GFX::PushConstantType::UVEC3:
            glProgramUniform3uiv(_shaderProgramID, binding, byteCount / (3 * 4), castData<GLuint, 3, vec3<U32>>(values));
            break;
        case GFX::PushConstantType::UVEC4:
            glProgramUniform4uiv(_shaderProgramID, binding, byteCount / (4 * 4), castData<GLuint, 4, vec4<U32>>(values));
            break;
        case GFX::PushConstantType::DVEC2:
            glProgramUniform2dv(_shaderProgramID, binding, byteCount / (2 * 8), castData<GLdouble, 2, vec2<D64>>(values));
            break;
        case GFX::PushConstantType::VEC2:
            glProgramUniform2fv(_shaderProgramID, binding, byteCount / (2 * 4), castData<GLfloat, 2, vec2<F32>>(values));
            break;
        case GFX::PushConstantType::DVEC3:
            glProgramUniform3dv(_shaderProgramID, binding, byteCount / (3 * 8), castData<GLdouble, 3, vec3<D64>>(values));
            break;
        case GFX::PushConstantType::VEC3:
            glProgramUniform3fv(_shaderProgramID, binding, byteCount / (3 * 4), castData<GLfloat, 3, vec3<F32>>(values));
            break;
        case GFX::PushConstantType::DVEC4:
            glProgramUniform4dv(_shaderProgramID, binding, byteCount / (4 * 8), castData<GLdouble, 4, vec4<D64>>(values));
            break;
        case GFX::PushConstantType::VEC4:
            glProgramUniform4fv(_shaderProgramID, binding, byteCount / (4 * 4), castData<GLfloat, 4, vec4<F32>>(values));
            break;
        case GFX::PushConstantType::IMAT2:
            glProgramUniformMatrix2fv(_shaderProgramID, binding, byteCount / (2 * 2 * 4), flag ? GL_TRUE : GL_FALSE, castData<GLfloat, 4, mat2<I32>>(values));
            break;
        case GFX::PushConstantType::IMAT3:
            glProgramUniformMatrix3fv(_shaderProgramID, binding, byteCount / (3 * 3 * 4), flag ? GL_TRUE : GL_FALSE, castData<GLfloat, 9, mat3<I32>>(values));
            break;
        case GFX::PushConstantType::IMAT4:
            glProgramUniformMatrix4fv(_shaderProgramID, binding, byteCount / (4 * 4 * 4), flag ? GL_TRUE : GL_FALSE, castData<GLfloat, 16, mat4<I32>>(values));
            break;
        case GFX::PushConstantType::UMAT2:
            glProgramUniformMatrix2fv(_shaderProgramID, binding, byteCount / (2 * 2 * 4), flag ? GL_TRUE : GL_FALSE, castData<GLfloat, 4, mat2<U32>>(values));
            break;
        case GFX::PushConstantType::UMAT3:
            glProgramUniformMatrix3fv(_shaderProgramID, binding, byteCount / (3 * 3 * 4), flag ? GL_TRUE : GL_FALSE, castData<GLfloat, 9, mat3<U32>>(values));
            break;
        case GFX::PushConstantType::UMAT4:
            glProgramUniformMatrix4fv(_shaderProgramID, binding, byteCount / (4 * 4 * 4), flag ? GL_TRUE : GL_FALSE, castData<GLfloat, 16, mat4<U32>>(values));
            break;
        case GFX::PushConstantType::MAT2:
            glProgramUniformMatrix2fv(_shaderProgramID, binding, byteCount / (2 * 2 * 4), flag ? GL_TRUE : GL_FALSE, castData<GLfloat, 4, mat2<F32>>(values));
            break;
        case GFX::PushConstantType::MAT3:
            glProgramUniformMatrix3fv(_shaderProgramID, binding, byteCount / (3 * 3 * 4), flag ? GL_TRUE : GL_FALSE, castData<GLfloat, 9, mat3<F32>>(values));
            break;
        case GFX::PushConstantType::MAT4:
            glProgramUniformMatrix4fv(_shaderProgramID, binding, byteCount / (4 * 4 * 4), flag ? GL_TRUE : GL_FALSE, castData<GLfloat, 16, mat4<F32>>(values));
            break;
        case GFX::PushConstantType::DMAT2:
            glProgramUniformMatrix2dv(_shaderProgramID, binding, byteCount / (2 * 2 * 8), flag ? GL_TRUE : GL_FALSE, castData<GLdouble, 4, mat2<D64>>(values));
            break;
        case GFX::PushConstantType::DMAT3:
            glProgramUniformMatrix3dv(_shaderProgramID, binding, byteCount / (3 * 3 * 8), flag ? GL_TRUE : GL_FALSE, castData<GLdouble, 9, mat3<D64>>(values));
            break;
        case GFX::PushConstantType::DMAT4:
            glProgramUniformMatrix4dv(_shaderProgramID, binding, byteCount / (4 * 4 * 8), flag ? GL_TRUE : GL_FALSE, castData<GLdouble, 16, mat4<D64>>(values));
            break;
        default:
            DIVIDE_ASSERT(false, "glShaderProgram::Uniform error: Unhandled data type!");
    }
}

void glShaderProgram::UploadPushConstant(const GFX::PushConstant& constant) {
    I32 binding = cachedValueUpdate(constant);

    if (binding != -1) {
        Uniform(binding, constant._type, constant._buffer, constant._flag);
    }
}

void glShaderProgram::UploadPushConstants(const PushConstants& constants) {
    for (const GFX::PushConstant& constant : constants.data()) {
        if (!constant._binding.empty() && constant._type != GFX::PushConstantType::COUNT) {
            UploadPushConstant(constant);
        }
    }
}

void glShaderProgram::reuploadUniforms() {
    for (UniformsByNameHash::ShaderVarMap::value_type it : _uniformsByNameHash._shaderVars) {
        UploadPushConstant(it.second);
    }
}

};

Commits for Divide-Framework/trunk/Source Code/Platform/Video/OpenGL/Shaders/glShaderProgram.cpp

Diff revisions: vs.
Revision Author Commited Message
1021 Diff Diff IonutCava picture IonutCava Sun 21 Jan, 2018 22:19:16 +0000

[Ionut]
- Performance optimizations

1020 Diff Diff IonutCava picture IonutCava Fri 19 Jan, 2018 17:51:19 +0000

[Ionut]
- Second attempt at improving PushConstant performance

1018 Diff Diff IonutCava picture IonutCava Wed 17 Jan, 2018 16:45:26 +0000

[Ionut]
- Rework caching mechanism:
— Shaders, Geometry and Terrain (and Materials soon) are cached in the cache folder in their respective sub-folders

1014 Diff Diff IonutCava picture IonutCava Tue 16 Jan, 2018 01:18:31 +0000

[Ionut]
- Attempt to pool PushConstants
— ToDo: Fix cleanup crash / heap corruption

1007 Diff Diff IonutCava picture IonutCava Fri 22 Dec, 2017 11:12:21 +0000

[Ionut]
- Fix crash due to GUIButton not unsubscribing from events on destruction
- Fixed the BoundingComponent <-> BoundingSystem coupling
- Dump shader binaries every time. Still unused for now
- Use the default shader for Terrain BBoxes
- Quad3D should always keep its vb data
- Fixed a bug with copying patch vertex count in GenericDrawCommand
- Fixed a bug with GL debug message control

996 Diff Diff IonutCava picture IonutCava Tue 12 Dec, 2017 17:16:54 +0000

[Ionut]
- Update and improve SGN creation and destruction
- Fix cleanup issues
- Fix GPU object memory leaks
- Fix duplicate GUID values being generated
- Misc cleanups and optimizations

968 Diff Diff IonutCava picture IonutCava Tue 07 Nov, 2017 17:32:31 +0000

[Ionut]
- Consistent naming between timing variables

959 Diff Diff IonutCava picture IonutCava Wed 01 Nov, 2017 15:37:22 +0000

[Ionut]
- Fixed CEGUI rendering issues and with it a huge hidden bug:
— Deleting GL objects (buffers, vao, textures, shader programs, framebuffers, sampler objects, etc) didn’t invalidate the bound object cache leading to situations suchs as the following to fail because OpenGL recycles handles:
Divide::bind(obj); glDeleteXYZ(1, &obj); glCreateXYZ(1, &obj); Divide::bind(obj);

955 Diff Diff IonutCava picture IonutCava Sun 29 Oct, 2017 20:45:04 +0000

[Ionut]
- Modify the CEGUI opengl renderer to interact with the state in GLWrapper better
- Performance optimizations

935 IonutCava picture IonutCava Tue 15 Aug, 2017 21:10:25 +0000

[IonutCava]
- Added debug scope (GL’s debug group) commands
- More bug fixes and optimizations