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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
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
#include "stdafx.h"

#include "config.h"

#include "Headers/GLWrapper.h"

#include "Core/Headers/Kernel.h"
#include "Core/Headers/Configuration.h"
#include "Core/Headers/PlatformContext.h"
#include "Rendering/Lighting/Headers/Light.h"
#include "Platform/Video/Headers/GFXDevice.h"
#include "Platform/Video/Headers/RenderStateBlock.h"
#include "Platform/Video/OpenGL/Buffers/VertexBuffer/Headers/glVertexArray.h"
#include "Platform/Video/OpenGL/Buffers/ShaderBuffer/Headers/glUniformBuffer.h"

namespace Divide {

/// The following static variables are used to remember the current OpenGL state
GLuint GL_API::s_UBOffsetAlignment = 0;
GLuint GL_API::s_UBMaxSize = 0;
GLuint GL_API::s_SSBOffsetAlignment = 0;
GLuint GL_API::s_SSBMaxSize = 0;
GLint  GL_API::s_lineWidthLimit = 1;
GLuint GL_API::s_dummyVAO = 0;
GLint  GL_API::s_maxTextureUnits = 0;
GLint  GL_API::s_maxAttribBindings = 0;
GLint  GL_API::s_maxFBOAttachments = 0;
GLuint GL_API::s_activeShaderProgram = 0;
GLuint GL_API::s_anisoLevel = 0;
GLint  GL_API::s_activePackUnpackAlignments[] = {1, 1};
GLint  GL_API::s_activePackUnpackRowLength[] = {0, 0};
GLint  GL_API::s_activePackUnpackSkipPixels[] = {0, 0};
GLint  GL_API::s_activePackUnpackSkipRows[] = {0, 0};
GLuint GL_API::s_activeVAOID = GLUtil::_invalidObjectID;
GLuint GL_API::s_activeTransformFeedback = GLUtil::_invalidObjectID;
GLuint GL_API::s_activeFBID[] = {GLUtil::_invalidObjectID,
                                 GLUtil::_invalidObjectID,
                                 GLUtil::_invalidObjectID};
GLuint GL_API::s_activeBufferID[] = {GLUtil::_invalidObjectID,
                                     GLUtil::_invalidObjectID,
                                     GLUtil::_invalidObjectID,
                                     GLUtil::_invalidObjectID,
                                     GLUtil::_invalidObjectID,
                                     GLUtil::_invalidObjectID,
                                     GLUtil::_invalidObjectID};
VAOBindings GL_API::s_vaoBufferData;
GLfloat GL_API::s_depthNearVal = 0.0f;
I64 GL_API::s_activeWindowGUID = -1;
Pipeline const* GL_API::s_activePipeline = nullptr;
glFramebuffer* GL_API::s_activeRenderTarget = nullptr;
glPixelBuffer* GL_API::s_activePixelBuffer = nullptr;

UColour GL_API::s_blendColour = UColour(0u);
Rect<I32> GL_API::s_activeViewport = Rect<I32>(-1);
Rect<I32> GL_API::s_previousViewport = Rect<I32>(-1);
Rect<I32> GL_API::s_activeScissor = Rect<I32>(-1);
FColour GL_API::s_activeClearColour = DefaultColours::DIVIDE_BLUE;
GLfloat GL_API::s_depthFarVal = 1.0f;
bool GL_API::s_primitiveRestartEnabled = false;
bool GL_API::s_rasterizationEnabled = true;
bool GL_API::s_opengl46Supported = false;
U32 GL_API::s_patchVertexCount = 0;
size_t GL_API::s_currentStateBlockHash = 0;
size_t GL_API::s_previousStateBlockHash = 0;
GL_API::textureBoundMapDef GL_API::s_textureBoundMap;
GL_API::imageBoundMapDef GL_API::s_imageBoundMap;
SharedLock GL_API::s_mipmapQueueLock;
std::unordered_set<GLuint> GL_API::s_mipmapQueue;
GL_API::samplerBoundMapDef GL_API::s_samplerBoundMap;
GL_API::samplerObjectMap GL_API::s_samplerMap;
SharedLock GL_API::s_samplerMapLock;
GLUtil::glVAOPool GL_API::s_vaoPool;
glHardwareQueryPool* GL_API::s_hardwareQueryPool = nullptr;
BlendingProperties GL_API::s_blendPropertiesGlobal;
GLboolean GL_API::s_blendEnabledGlobal;
vectorImpl<BlendingProperties> GL_API::s_blendProperties;
vectorImpl<GLboolean> GL_API::s_blendEnabled;

namespace {
    GLint getBufferTargetIndex(GLenum target) {
        GLint index = -1;
        // Select the appropriate index in the array based on the buffer target
        switch (target) {
            case GL_ARRAY_BUFFER: {
                index = 0;
            }break;
            case GL_TEXTURE_BUFFER: {
                index = 1;
            }break;
            case GL_UNIFORM_BUFFER: {
                index = 2;
            }break;
            case GL_SHADER_STORAGE_BUFFER: {
                index = 3;
            }break;
            case GL_ELEMENT_ARRAY_BUFFER: {
                index = 4;
            }break;
            case GL_PIXEL_UNPACK_BUFFER: {
                index = 5;
            }break;
            case GL_DRAW_INDIRECT_BUFFER: {
                index = 6;
            }break;
            default: {
                // Make sure the target is available. Assert if it isn't as this
                // means that a non-supported feature is used somewhere
                DIVIDE_ASSERT(IS_IN_RANGE_INCLUSIVE(index, 0, 6),
                              "GLStates error: attempted to bind an invalid buffer target!");
                return -1;
            }
        };
        return index;
    }
}; //namespace 

/// Reset as much of the GL default state as possible within the limitations given
void GL_API::clearStates() {
    GL_API::bindTextures(0, GL_API::s_maxTextureUnits, nullptr, nullptr);
    setPixelPackUnpackAlignment();
    setActiveVAO(0);
    setActiveFB(RenderTarget::RenderTargetUsage::RT_READ_WRITE, 0);
    setActiveBuffer(GL_ARRAY_BUFFER, 0);
    setActiveBuffer(GL_TEXTURE_BUFFER, 0);
    setActiveBuffer(GL_UNIFORM_BUFFER, 0);
    setActiveBuffer(GL_SHADER_STORAGE_BUFFER, 0);
    setActiveBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    setActiveBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
    setActiveBuffer(GL_DRAW_INDIRECT_BUFFER, 0);
    setActiveTransformFeedback(0);

    for (vectorAlg::vecSize i = 0; i < GL_API::s_blendEnabled.size(); ++i) {
        setBlending((GLuint)i, false, BlendingProperties(), true);
    }
    GL_API::setBlendColour(UColour(0u), true);

    s_activeWindowGUID = -1;
    s_activePipeline = nullptr;
    s_activeRenderTarget = nullptr;
    s_activePixelBuffer = nullptr;
    s_activeViewport.set(-1);
    s_previousViewport.set(-1);
    s_activeScissor.set(-1);
    s_activeClearColour.set(DefaultColours::DIVIDE_BLUE);

    Attorney::GLAPIShaderProgram::unbind();
}

/// Pixel pack alignment is usually changed by textures, PBOs, etc
bool GL_API::setPixelPackAlignment(GLint packAlignment,
                                   GLint rowLength,
                                   GLint skipRows,
                                   GLint skipPixels) {
    // Keep track if we actually affect any OpenGL state
    bool changed = false;
    if (s_activePackUnpackAlignments[0] != packAlignment) {
        glPixelStorei(GL_PACK_ALIGNMENT, packAlignment);
        s_activePackUnpackAlignments[0] = packAlignment;
        changed = true;
    }

    if (s_activePackUnpackRowLength[0] != rowLength) {
        glPixelStorei(GL_PACK_ROW_LENGTH, rowLength);
        s_activePackUnpackRowLength[0] = rowLength;
        changed = true;
    }

    if (s_activePackUnpackSkipRows[0] != skipRows) {
        glPixelStorei(GL_PACK_SKIP_ROWS, skipRows);
        s_activePackUnpackSkipRows[0] = skipRows;
        changed = true;
    }

    if (s_activePackUnpackSkipPixels[0] != skipPixels) {
        glPixelStorei(GL_PACK_SKIP_PIXELS, skipPixels);
        s_activePackUnpackSkipPixels[0] = skipPixels;
        changed = true;
    }

    // We managed to change at least one entry
    return changed;
}

size_t GL_API::setStateBlockInternal(size_t stateBlockHash) {
    // If the new state hash is different from the previous one
    if (stateBlockHash != s_currentStateBlockHash) {
        // Remember the previous state hash
        s_previousStateBlockHash = s_currentStateBlockHash;
        // Update the current state hash
        s_currentStateBlockHash = stateBlockHash;

        bool currentStateValid = false;
        const RenderStateBlock& currentState = RenderStateBlock::get(s_currentStateBlockHash, currentStateValid);
        if (s_previousStateBlockHash != 0) {
            bool previousStateValid = false;
            const RenderStateBlock& previousState = RenderStateBlock::get(s_previousStateBlockHash, previousStateValid);

            DIVIDE_ASSERT(currentStateValid && previousStateValid &&
                          currentState != previousState,
                          "GL_API error: Invalid state blocks detected on activation!");

            // Activate the new render state block in an rendering API dependent way
            activateStateBlock(currentState, previousState);
        } else {
            DIVIDE_ASSERT(currentStateValid, "GL_API error: Invalid state blocks detected on activation!");
            activateStateBlock(currentState);
        }
    }

    // Return the previous state hash
    return s_previousStateBlockHash;
}
/// Pixel unpack alignment is usually changed by textures, PBOs, etc
bool GL_API::setPixelUnpackAlignment(GLint unpackAlignment,
                                     GLint rowLength,
                                     GLint skipRows,
                                     GLint skipPixels) {
    // Keep track if we actually affect any OpenGL state
    bool changed = false;
    if (s_activePackUnpackAlignments[1] != unpackAlignment) {
        glPixelStorei(GL_UNPACK_ALIGNMENT, unpackAlignment);
        s_activePackUnpackAlignments[1] = unpackAlignment;
        changed = true;
    }

    if (rowLength != -1 && s_activePackUnpackRowLength[1] != rowLength) {
        glPixelStorei(GL_UNPACK_ROW_LENGTH, rowLength);
        s_activePackUnpackRowLength[1] = rowLength;
        changed = true;
    }

    if (skipRows != -1 && s_activePackUnpackSkipRows[1] != skipRows) {
        glPixelStorei(GL_UNPACK_SKIP_ROWS, skipRows);
        s_activePackUnpackSkipRows[1] = skipRows;
        changed = true;
    }

    if (skipPixels != -1 && s_activePackUnpackSkipPixels[1] != skipPixels) {
        glPixelStorei(GL_UNPACK_SKIP_PIXELS, skipPixels);
        s_activePackUnpackSkipPixels[1] = skipPixels;
        changed = true;
    }

    // We managed to change at least one entry
    return changed;
}

/// Enable or disable primitive restart and ensure that the correct index size
/// is used
void GL_API::togglePrimitiveRestart(bool state) {
    // Toggle primitive restart on or off
    if (s_primitiveRestartEnabled != state) {
        s_primitiveRestartEnabled = state;
        state ? glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX)
              : glDisable(GL_PRIMITIVE_RESTART_FIXED_INDEX);
    }
}

void GL_API::setPatchVertexCount(U32 count) {
    if (s_patchVertexCount != count) {
        s_patchVertexCount = count;
        glPatchParameteri(GL_PATCH_VERTICES, s_patchVertexCount);
    }
}
/// Enable or disable primitive rasterization
void GL_API::toggleRasterization(bool state) {
    // Toggle primitive restart on or off
    if (s_rasterizationEnabled != state) {
        s_rasterizationEnabled = state;
        state ? glDisable(GL_RASTERIZER_DISCARD)
              : glEnable(GL_RASTERIZER_DISCARD);
    }
}

/// Clipping planes are only enabled/disabled if they differ from the current
/// state
void GL_API::updateClipPlanes() {
    // Get the clip planes from the GFXDevice object
    const FrustumClipPlanes& list = Attorney::GFXDeviceAPI::getClippingPlanes(_context);
    
    // For every clip plane that we support (usually 6)
    for (U32 i = 0; i < to_base(ClipPlaneIndex::COUNT); ++i) {
        // Check its state and compare it with OpenGL's current state
        bool& activePlane = _activeClipPlanes[i];
        if (activePlane != list._active[i]) {
            // Update the clip plane if it differs internally
            activePlane = !activePlane;
            activePlane ? glEnable(GLenum((U32)GL_CLIP_DISTANCE0 + i))
                        : glDisable(GLenum((U32)GL_CLIP_DISTANCE0 + i));
        }
    }
}

bool GL_API::deleteBuffers(GLuint count, GLuint* buffers) {
    if (count > 0 && buffers != nullptr) {
        for (GLuint i = 0; i < count; ++i) {
            GLuint crtBuffer = buffers[i];
            for (GLuint& boundBuffer : s_activeBufferID) {
                if (crtBuffer != 0 && boundBuffer == crtBuffer) {
                    boundBuffer = 0;
                }
            }
        }

        glDeleteBuffers(count, buffers);
        memset(buffers, 0, count * sizeof(GLuint));
        return true;
    }

    return false;
}

bool GL_API::deleteVAOs(GLuint count, GLuint* vaos) {
    if (count > 0 && vaos != nullptr) {
        for (GLuint i = 0; i < count; ++i) {
            if (s_activeVAOID == vaos[i]) {
                s_activeVAOID = 0;
                break;
            }
        }
        glDeleteVertexArrays(count, vaos);
        memset(vaos, 0, count * sizeof(GLuint));
        return true;
    }
    return false;
}

bool GL_API::deleteFramebuffers(GLuint count, GLuint* framebuffers) {
    if (count > 0 && framebuffers != nullptr) {
        for (GLuint i = 0; i < count; ++i) {
            GLuint crtFB = framebuffers[i];
            for (GLuint& activeFB : s_activeFBID) {
                if (activeFB == crtFB) {
                    activeFB = 0;
                }
            }
        }
        glDeleteFramebuffers(count, framebuffers);
        memset(framebuffers, 0, count * sizeof(GLuint));
        return true;
    }
    return false;
}

bool GL_API::deleteShaderPrograms(GLuint count, GLuint* programs) {
    if (count > 0 && programs != nullptr) {
        for (GLuint i = 0; i < count; ++i) {
            if (s_activeShaderProgram == programs[i]) {
                s_activeShaderProgram = 0;
                break;
            }
            glDeleteProgram(programs[i]);
        }
        
        memset(programs, 0, count * sizeof(GLuint));
        return true;
    }
    return false;
}

bool GL_API::deleteTextures(GLuint count, GLuint* textures) {
    if (count > 0 && textures != nullptr) {
        
        for (GLuint i = 0; i < count; ++i) {
            GLuint crtTex = textures[i];
            if (crtTex != 0) {
                for (GLuint& boundTex : s_textureBoundMap) {
                    if (boundTex == crtTex) {
                        boundTex = 0;
                    }
                }
                for (ImageBindSettings& settings : s_imageBoundMap) {
                    if (settings._texture == crtTex) {
                        settings.reset();
                    }
                }
            }
        }
        glDeleteTextures(count, textures);
        memset(textures, 0, count * sizeof(GLuint));
        return true;
    }

    return false;
}

bool GL_API::deleteSamplers(GLuint count, GLuint* samplers) {
    if (count > 0 && samplers != nullptr) {

        for (GLuint i = 0; i < count; ++i) {
            GLuint crtSampler = samplers[i];
            if (crtSampler != 0) {
                for (GLuint& boundSampler : s_samplerBoundMap) {
                    if (boundSampler == crtSampler) {
                        boundSampler = 0;
                    }
                }
            }
        }
        glDeleteSamplers(count, samplers);
        memset(samplers, 0, count * sizeof(GLuint));
        return true;
    }

    return false;
}

bool GL_API::bindSamplers(GLushort unitOffset,
                          GLuint samplerCount,
                          GLuint* samplerHandles) {
    if (samplerCount > 0 &&
        unitOffset + samplerCount < static_cast<GLuint>(GL_API::s_maxTextureUnits))
    {
        if (samplerCount == 1) {
            GLuint& handle = s_samplerBoundMap[unitOffset];
            GLuint targetHandle = samplerHandles ? samplerHandles[0] : 0u;
            if (handle != targetHandle) {
                glBindSampler(unitOffset, targetHandle);
                handle = targetHandle;
                return true;
            }
        } else {
            glBindSamplers(unitOffset, samplerCount, samplerHandles);
            if (samplerHandles != nullptr) {
                memcpy(&s_samplerBoundMap[unitOffset], samplerHandles, sizeof(GLuint) * samplerCount);
            } else {
                memset(&s_samplerBoundMap[unitOffset], 0, sizeof(GLuint) * samplerCount);
            }
            return true;
        } 
    }

    return false;
}

bool GL_API::bindTextures(GLushort unitOffset,
                          GLuint textureCount,
                          GLuint* textureHandles,
                          GLuint* samplerHandles) {
    if (textureCount > 0 &&
        unitOffset + textureCount < static_cast<GLuint>(GL_API::s_maxTextureUnits))
    {
        GL_API::bindSamplers(unitOffset, textureCount, samplerHandles);

        if (textureHandles != nullptr) {
            UpgradableReadLock ur_lock(s_mipmapQueueLock);
            for (GLuint i = 0; i < textureCount; ++i) {
                GLuint handle = textureHandles[i];
                if (s_mipmapQueue.find(handle) != std::cend(s_mipmapQueue)) {
                    glGenerateTextureMipmap(handle);
                    UpgradeToWriteLock w_lock(ur_lock);
                    s_mipmapQueue.erase(handle);
                }
            }
        }
        if (textureCount == 1) {
            GLuint& crtHandle = s_textureBoundMap[unitOffset];
            GLuint targetHandle = textureHandles ? textureHandles[0] : 0u;

            if (crtHandle != targetHandle) {
                glBindTextureUnit(unitOffset, targetHandle);
                crtHandle = targetHandle;
                return true;
            }
        } else {
            glBindTextures(unitOffset, textureCount, textureHandles);
            if (textureHandles != nullptr) {
                memcpy(&s_textureBoundMap[unitOffset], textureHandles, sizeof(GLuint) * textureCount);
            } else {
                memset(&s_textureBoundMap[unitOffset], 0, sizeof(GLuint) * textureCount);
            }

            return true;
        }
    }

    return false;
}

void GL_API::queueComputeMipMap(GLuint textureHandle) {
    WriteLock w_lock(s_mipmapQueueLock);
    s_mipmapQueue.insert(textureHandle);
}

// Bind a texture specified by a GL handle and GL type to the specified unit
/// using the sampler object defined by hash value
bool GL_API::bindTexture(GLushort unit,
                         GLuint handle,
                         size_t samplerHash) {
    // Fail if we specified an invalid unit. Assert instead of returning false
    // because this might be related to a bad algorithm
    DIVIDE_ASSERT(unit < static_cast<GLuint>(GL_API::s_maxTextureUnits),
                  "GLStates error: invalid texture unit specified as a texture binding slot!");
    GLuint samplerHandle = getSamplerHandle(samplerHash);
    return bindTextures(unit, 1, &handle, &samplerHandle);
}

bool GL_API::bindTextureImage(GLushort unit, GLuint handle, GLint level,
                              bool layered, GLint layer, GLenum access,
                              GLenum format) {
    static ImageBindSettings tempSettings;
    tempSettings = {handle, level, layered ? GL_TRUE : GL_FALSE, layer, access, format};

    ImageBindSettings& settings = s_imageBoundMap[unit];
    if (settings != tempSettings) {
        glBindImageTexture(unit, handle, level, layered ? GL_TRUE : GL_FALSE, layer, access, format);
        settings = tempSettings;
        return true;
    }

    return false;
}

/// Single place to change buffer objects for every target available
bool GL_API::bindActiveBuffer(GLuint vaoID, GLuint location, GLuint bufferID, GLintptr offset, GLsizei stride) {
    const VAOBindings::BufferBindingParams& bindings = s_vaoBufferData.bindingParams(vaoID, location);

    VAOBindings::BufferBindingParams currentParams(bufferID, offset, stride);
    if (bindings != currentParams) {
        // Bind the specified buffer handle to the desired buffer target
        glVertexArrayVertexBuffer(vaoID, location, bufferID, offset, stride);
        // Remember the new binding for future reference
        s_vaoBufferData.bindingParams(vaoID, location, currentParams);
        return true;
    }

    return false;
}

bool GL_API::setActiveFB(RenderTarget::RenderTargetUsage usage, GLuint ID) {
    GLuint temp = 0;
    return setActiveFB(usage, ID, temp);
}

/// Switch the current framebuffer by binding it as either a R/W buffer, read
/// buffer or write buffer
bool GL_API::setActiveFB(RenderTarget::RenderTargetUsage usage, GLuint ID, GLuint& previousID) {
    // We may query the active framebuffer handle and get an invalid handle in
    // return and then try to bind the queried handle
    // This is, for example, in save/restore FB scenarios. An invalid handle
    // will just reset the buffer binding
    if (ID == GLUtil::_invalidObjectID) {
        ID = 0;
    }
    previousID = s_activeFBID[to_U32(usage)];
    // Prevent double bind
    if (s_activeFBID[to_U32(usage)] == ID) {
        if (usage == RenderTarget::RenderTargetUsage::RT_READ_WRITE) {
            if (s_activeFBID[to_base(RenderTarget::RenderTargetUsage::RT_READ_ONLY)] == ID &&
                s_activeFBID[to_base(RenderTarget::RenderTargetUsage::RT_WRITE_ONLY)] == ID) {
                return false;
            }
        } else {
            return false;
        }
    }
    // Bind the requested buffer to the appropriate target
    switch (usage) {
        case RenderTarget::RenderTargetUsage::RT_READ_WRITE: {
            // According to documentation this is equivalent to independent
            // calls to
            // bindFramebuffer(read, ID) and bindFramebuffer(write, ID)
            glBindFramebuffer(GL_FRAMEBUFFER, ID);
            // This also overrides the read and write bindings
            s_activeFBID[to_base(RenderTarget::RenderTargetUsage::RT_READ_ONLY)] = ID;
            s_activeFBID[to_base(RenderTarget::RenderTargetUsage::RT_WRITE_ONLY)] = ID;
        } break;
        case RenderTarget::RenderTargetUsage::RT_READ_ONLY: {
            glBindFramebuffer(GL_READ_FRAMEBUFFER, ID);
        } break;
        case RenderTarget::RenderTargetUsage::RT_WRITE_ONLY: {
            glBindFramebuffer(GL_DRAW_FRAMEBUFFER, ID);
        } break;
    };

    // Remember the new binding state for future reference
    s_activeFBID[to_U32(usage)] = ID;

    return true;
}

bool GL_API::setActiveVAO(GLuint ID) {
    GLuint temp = 0;
    return setActiveVAO(ID, temp);
}

/// Switch the currently active vertex array object
bool GL_API::setActiveVAO(GLuint ID, GLuint& previousID) {
    previousID = s_activeVAOID;
    // Prevent double bind
    if (s_activeVAOID != ID) {
        // Remember the new binding for future reference
        s_activeVAOID = ID;
        setActiveBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
        // Activate the specified VAO
        glBindVertexArray(ID);
        return true;
    }

    return false;
}

bool GL_API::setActiveTransformFeedback(GLuint ID) {
    GLuint temp = 0;
    return setActiveTransformFeedback(ID, temp);
}

/// Bind the specified transform feedback object
bool GL_API::setActiveTransformFeedback(GLuint ID, GLuint& previousID) {
    previousID = s_activeTransformFeedback;
    // Prevent double bind
    if (s_activeTransformFeedback != ID) {
        // Remember the new binding for future reference
        s_activeTransformFeedback = ID;
        // Activate the specified TFO
        glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, ID);
        return true;
    }

    return false;
}

/// Single place to change buffer objects for every target available
bool GL_API::setActiveBuffer(GLenum target, GLuint ID, GLuint& previousID) {
    // We map buffer targets from 0 to n in a static array
    GLint index = getBufferTargetIndex(target);

    // Prevent double bind
    previousID = s_activeBufferID[index];
    if (previousID != ID) {
        // Remember the new binding for future reference
        s_activeBufferID[index] = ID;
        // Bind the specified buffer handle to the desired buffer target
        glBindBuffer(target, ID);
        return true;
    }

    return false;
}

bool GL_API::setActiveBuffer(GLenum target, GLuint ID) {
    GLuint temp = 0;
    return setActiveBuffer(target, ID, temp);
}

/// Change the currently active shader program. Passing null will unbind shaders
/// (will use program 0)
bool GL_API::setActiveProgram(GLuint programHandle) {
    // Check if we are binding a new program or unbinding all shaders
    // Prevent double bind
    if (GL_API::s_activeShaderProgram != programHandle) {
        // Remember the new binding for future reference
        GL_API::s_activeShaderProgram = programHandle;
        // Bind the new program
        glUseProgram(programHandle);
        return true;
    }

    return false;
}

void GL_API::setDepthRange(F32 nearVal, F32 farVal) {
    CLAMP(nearVal, 0.0f, 1.0f);
    CLAMP(farVal, 0.0f, 1.0f);
    if (!COMPARE(nearVal, s_depthNearVal) && !COMPARE(farVal, s_depthFarVal)) {
        glDepthRange(nearVal, farVal);
        GL_API::s_depthNearVal = nearVal;
        GL_API::s_depthFarVal = farVal;
    }
}

void GL_API::setBlendColour(const UColour& blendColour, bool force) {
    if (GL_API::s_blendColour != blendColour || force) {
        FColour floatColour = Util::ToFloatColour(blendColour);
        glBlendColor(static_cast<GLfloat>(floatColour.r),
                     static_cast<GLfloat>(floatColour.g),
                     static_cast<GLfloat>(floatColour.b),
                     static_cast<GLfloat>(floatColour.a));

        GL_API::s_blendColour.set(blendColour);
    }
}

void GL_API::setBlending(bool enable, const BlendingProperties& blendingProperties, bool force) {
    if ((GL_API::s_blendEnabledGlobal == GL_TRUE) != enable || force) {
        enable ? glEnable(GL_BLEND) : glDisable(GL_BLEND);
        GL_API::s_blendEnabledGlobal = (enable ? GL_TRUE : GL_FALSE);
        std::fill(std::begin(GL_API::s_blendEnabled), std::end(GL_API::s_blendEnabled), GL_API::s_blendEnabledGlobal);
    }

    if (enable || force) {
        if (GL_API::s_blendPropertiesGlobal != blendingProperties || force)
        {
            if (blendingProperties._blendSrcAlpha != BlendProperty::COUNT) {
                glBlendFuncSeparate(GLUtil::glBlendTable[to_base(blendingProperties._blendSrc)],
                                    GLUtil::glBlendTable[to_base(blendingProperties._blendDest)],
                                    GLUtil::glBlendTable[to_base(blendingProperties._blendSrcAlpha)],
                                    GLUtil::glBlendTable[to_base(blendingProperties._blendDestAlpha)]);

                glBlendEquationSeparate(GLUtil::glBlendOpTable[to_base(blendingProperties._blendOp)],
                                        GLUtil::glBlendOpTable[to_base(blendingProperties._blendOpAlpha)]);
            } else {
                glBlendFunc(GLUtil::glBlendTable[to_base(blendingProperties._blendSrc)],
                            GLUtil::glBlendTable[to_base(blendingProperties._blendDest)]);
                glBlendEquation(GLUtil::glBlendOpTable[to_base(blendingProperties._blendOp)]);
            }

            GL_API::s_blendPropertiesGlobal = blendingProperties;

            std::fill(std::begin(GL_API::s_blendProperties), std::end(GL_API::s_blendProperties), GL_API::s_blendPropertiesGlobal);
        }
    }
}

void GL_API::setBlending(GLuint drawBufferIdx, bool enable, const BlendingProperties& blendingProperties, bool force) {
    assert(drawBufferIdx < (GLuint)(GL_API::s_maxFBOAttachments));

    if ((GL_API::s_blendEnabled[drawBufferIdx] == GL_TRUE) != enable || force) {
        enable ? glEnablei(GL_BLEND, drawBufferIdx) : glDisablei(GL_BLEND, drawBufferIdx);
        GL_API::s_blendEnabled[drawBufferIdx] = (enable ? GL_TRUE : GL_FALSE);
        if (!enable) {
            GL_API::s_blendEnabledGlobal = GL_FALSE;
        }
    }

    if (enable || force) {
        if (GL_API::s_blendProperties[drawBufferIdx] != blendingProperties || force) {
            if (blendingProperties._blendSrcAlpha != BlendProperty::COUNT) {
                glBlendFuncSeparatei(drawBufferIdx,
                                     GLUtil::glBlendTable[to_base(blendingProperties._blendSrc)],
                                     GLUtil::glBlendTable[to_base(blendingProperties._blendDest)],
                                     GLUtil::glBlendTable[to_base(blendingProperties._blendSrcAlpha)],
                                     GLUtil::glBlendTable[to_base(blendingProperties._blendDestAlpha)]);

                glBlendEquationSeparatei(drawBufferIdx, 
                                         GLUtil::glBlendOpTable[to_base(blendingProperties._blendOp)],
                                         GLUtil::glBlendOpTable[to_base(blendingProperties._blendOpAlpha)]);
            } else {
                glBlendFunci(drawBufferIdx,
                             GLUtil::glBlendTable[to_base(blendingProperties._blendSrc)],
                             GLUtil::glBlendTable[to_base(blendingProperties._blendDest)]);
                glBlendEquationi(drawBufferIdx,
                                 GLUtil::glBlendOpTable[to_base(blendingProperties._blendOp)]);
            }

            GL_API::s_blendProperties[drawBufferIdx] = blendingProperties;
            GL_API::s_blendPropertiesGlobal.reset();
        }
    }
}

/// Change the current viewport area. Redundancy check is performed in GFXDevice
/// class
bool GL_API::changeViewport(I32 x, I32 y, I32 width, I32 height) {
    if (Rect<I32>(x, y, width, height) != GL_API::s_activeViewport) {
        // Debugging and profiling the application may require setting a 1x1
         // viewport to exclude fill rate bottlenecks
        if (Config::Profile::USE_1x1_VIEWPORT) {
            glViewport(x, y, 1, 1);
        } else {
            glViewport(x, y, width, height);
        }
        GL_API::s_previousViewport.set(GL_API::s_activeViewport);
        GL_API::s_activeViewport.set(x, y, width, height);
        
        return true;
    }

    return false;
}

bool GL_API::restoreViewport() {
    return changeViewport(GL_API::s_previousViewport.x,
                          GL_API::s_previousViewport.y,
                          GL_API::s_previousViewport.z,
                          GL_API::s_previousViewport.w);
}

bool GL_API::setClearColour(const FColour& colour) {
    if (colour != GL_API::s_activeClearColour) {
        glClearColor(colour.r, colour.g, colour.b, colour.a);
        GL_API::s_activeClearColour.set(colour);
        return true;
    }

    return false;
}

bool GL_API::setScissor(I32 x, I32 y, I32 width, I32 height) {
    if (Rect<I32>(x, y, width, height) != GL_API::s_activeScissor) {
        glScissor(x, y, width, height);
        GL_API::s_activeScissor.set(x, y, width, height);
        return true;
    }

    return false;
}

GLuint GL_API::getBoundTextureHandle(GLuint slot) {
    return s_textureBoundMap[slot];
}

void GL_API::getActiveViewport(GLint* vp) {
    if (vp != nullptr) {
        vp = (GLint*)s_activeViewport._v;
    }
}

/// A state block should contain all rendering state changes needed for the next draw call.
/// Some may be redundant, so we check each one individually
void GL_API::activateStateBlock(const RenderStateBlock& newBlock,
                                const RenderStateBlock& oldBlock) {
    auto toggle = [](bool flag, GLenum state) {
        flag ? glEnable(state) : glDisable(state);
    };

  
    if (oldBlock.cullEnabled() != newBlock.cullEnabled()) {
        toggle(newBlock.cullEnabled(), GL_CULL_FACE);
    }
    if (oldBlock.stencilEnable() != newBlock.stencilEnable()) {
        toggle(newBlock.stencilEnable(), GL_STENCIL_TEST);
    }
    if (oldBlock.zEnable() != newBlock.zEnable()) {
        toggle(newBlock.zEnable(), GL_DEPTH_TEST);
    }
    if (oldBlock.scissorTestEnable() != newBlock.scissorTestEnable()) {
        toggle(newBlock.scissorTestEnable(), GL_SCISSOR_TEST);
    }
    // Check culling mode (back (CW) / front (CCW) by default)
    if (oldBlock.cullMode() != newBlock.cullMode()) {
        if (newBlock.cullMode() != CullMode::NONE) {
            glCullFace(GLUtil::glCullModeTable[to_U32(newBlock.cullMode())]);
        }
    }
    // Check rasterization mode
    if (oldBlock.fillMode() != newBlock.fillMode()) {
        glPolygonMode(GL_FRONT_AND_BACK,
                      GLUtil::glFillModeTable[to_U32(newBlock.fillMode())]);
    }
    // Check the depth function
    if (oldBlock.zFunc() != newBlock.zFunc()) {
        glDepthFunc(GLUtil::glCompareFuncTable[to_U32(newBlock.zFunc())]);
    }

    // Check if we need to change the stencil mask
    if (oldBlock.stencilWriteMask() != newBlock.stencilWriteMask()) {
        glStencilMask(newBlock.stencilWriteMask());
    }
    // Stencil function is dependent on 3 state parameters set together
    if (oldBlock.stencilFunc() != newBlock.stencilFunc() ||
        oldBlock.stencilRef()  != newBlock.stencilRef() ||
        oldBlock.stencilMask() != newBlock.stencilMask()) {
        glStencilFunc(GLUtil::glCompareFuncTable[to_U32(newBlock.stencilFunc())],
                      newBlock.stencilRef(),
                      newBlock.stencilMask());
    }
    // Stencil operation is also dependent  on 3 state parameters set together
    if (oldBlock.stencilFailOp() != newBlock.stencilFailOp() ||
        oldBlock.stencilZFailOp() != newBlock.stencilZFailOp() ||
        oldBlock.stencilPassOp() != newBlock.stencilPassOp()) {
        glStencilOp(GLUtil::glStencilOpTable[to_U32(newBlock.stencilFailOp())],
                    GLUtil::glStencilOpTable[to_U32(newBlock.stencilZFailOp())],
                    GLUtil::glStencilOpTable[to_U32(newBlock.stencilPassOp())]);
    }
    // Check and set polygon offset
    if (!COMPARE(oldBlock.zBias(), newBlock.zBias())) {
        if (IS_ZERO(newBlock.zBias())) {
            glDisable(GL_POLYGON_OFFSET_FILL);
        } else {
            glEnable(GL_POLYGON_OFFSET_FILL);
            if (!COMPARE(oldBlock.zUnits(), newBlock.zUnits())) {
                glPolygonOffset(newBlock.zBias(), newBlock.zUnits());
            }
        }
    }

    // Check and set colour mask
    if (oldBlock.colourWrite().i != newBlock.colourWrite().i) {
        P32 cWrite = newBlock.colourWrite();
        glColorMask(cWrite.b[0] == 1 ? GL_TRUE : GL_FALSE,   // R
                    cWrite.b[1] == 1 ? GL_TRUE : GL_FALSE,   // G
                    cWrite.b[2] == 1 ? GL_TRUE : GL_FALSE,   // B
                    cWrite.b[3] == 1 ? GL_TRUE : GL_FALSE);  // A
    }
}

void GL_API::activateStateBlock(const RenderStateBlock& newBlock) {
    auto toggle = [](bool flag, GLenum state) {
        flag ? glEnable(state) : glDisable(state);
    };

    toggle(newBlock.cullEnabled(), GL_CULL_FACE);
    toggle(newBlock.stencilEnable(), GL_STENCIL_TEST);
    toggle(newBlock.zEnable(), GL_DEPTH_TEST);

    if (newBlock.cullMode() != CullMode::NONE) {
        glCullFace(GLUtil::glCullModeTable[to_U32(newBlock.cullMode())]);
    }

    glPolygonMode(GL_FRONT_AND_BACK, GLUtil::glFillModeTable[to_U32(newBlock.fillMode())]);
    glDepthFunc(GLUtil::glCompareFuncTable[to_U32(newBlock.zFunc())]);
    glStencilMask(newBlock.stencilWriteMask());
    glStencilFunc(GLUtil::glCompareFuncTable[to_U32(newBlock.stencilFunc())],
                  newBlock.stencilRef(),
                  newBlock.stencilMask());
    glStencilOp(GLUtil::glStencilOpTable[to_U32(newBlock.stencilFailOp())],
                GLUtil::glStencilOpTable[to_U32(newBlock.stencilZFailOp())],
                GLUtil::glStencilOpTable[to_U32(newBlock.stencilPassOp())]);

    if (IS_ZERO(newBlock.zBias())) {
        glDisable(GL_POLYGON_OFFSET_FILL);
    } else {
        glEnable(GL_POLYGON_OFFSET_FILL);
        glPolygonOffset(newBlock.zBias(), newBlock.zUnits());
    }

    P32 cWrite = newBlock.colourWrite();
    glColorMask(cWrite.b[0] == 1 ? GL_TRUE : GL_FALSE,   // R
                cWrite.b[1] == 1 ? GL_TRUE : GL_FALSE,   // G
                cWrite.b[2] == 1 ? GL_TRUE : GL_FALSE,   // B
                cWrite.b[3] == 1 ? GL_TRUE : GL_FALSE);  // A
    
}

};

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

Diff revisions: vs.
Revision Author Commited Message
1004 Diff Diff IonutCava picture IonutCava Wed 20 Dec, 2017 17:16:32 +0000

[Ionut]
- More GUI cleanup (added multiple GUIButton events)
- Typedef vec4<U8> and vec4<F32> to UColour and FColour respectively for easier to read code.

999 Diff Diff IonutCava picture IonutCava Thu 14 Dec, 2017 00:27:08 +0000

[Ionut]
- Simply GenericVertexData class a lot
- Move IMGUI to GenericVertexData based rendering (still has rendering issues)
- Fix some crash issues on shutdown if the rendering API failed to initialize
- Disable some GL debugging flags as they seem to cause issues with the new 17.12.1 AMD driver

988 Diff Diff IonutCava picture IonutCava Thu 30 Nov, 2017 23:08:51 +0000

[Ionut]
- Add a Rect class (basic wrapper around a vec4)
- More work on MouseEvent system

987 Diff Diff IonutCava picture IonutCava Thu 30 Nov, 2017 17:19:21 +0000

[Ionut]
- glBlendFuncSeparate changes the blend mode for ALL buffers, so adjust code to handle this. This also fixes CEGUI rendering
- Fix CEGUI crashing on shutdown

980 Diff Diff IonutCava picture IonutCava Wed 22 Nov, 2017 17:18:46 +0000

[Ionut]
- Started porting CEGUI to RTT

976 Diff Diff IonutCava picture IonutCava Sun 19 Nov, 2017 23:10:18 +0000

[Ionut]
- Texture mipmaps are now compute before bind if they need a refresh (to avoid recalculation if they’re not used)
- More work on the editor: cleanup, load/save functionality, etc
- Input scaling: Mouse position is now relative to the scene preview position in editor mode. (the scene preview rect is used to re-map X/Y absolute and relative mouse positions)

970 Diff Diff IonutCava picture IonutCava Mon 13 Nov, 2017 17:16:44 +0000

[Ionut]
- ImWindow <-> DisplayWindow fixes

969 Diff Diff IonutCava picture IonutCava Mon 13 Nov, 2017 00:15:57 +0000

[Ionut]
- Further improve DisplayWindow <-> Input relationship
- Add Flip-Y 2D camera (D3D style projection)
- Fix IMGUI rendering
- Add IMGUI sample and IMWINDOW sample rendering at the same time
- Improve IMWINDOW multi-window support
— Bug: nothing rendering in child platform windows
- Add draw command to move render context from one window to another

963 Diff Diff IonutCava picture IonutCava Sun 05 Nov, 2017 18:31:51 +0000

[Ionut]
- More multi-window fixes
- Profile guided performance improvements

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