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
#include "Headers/GLWrapper.h"
#include "Headers/glIMPrimitive.h"

#include "Platform/Video/Headers/GFXDevice.h"
#include "Platform/Video/OpenGL/glsw/Headers/glsw.h"
#include "Platform/Video/OpenGL/Buffers/RenderTarget/Headers/glFramebuffer.h"
#include "Platform/Video/OpenGL/Buffers/PixelBuffer/Headers/glPixelBuffer.h"
#include "Platform/Video/OpenGL/Buffers/VertexBuffer/Headers/glVertexArray.h"
#include "Platform/Video/OpenGL/Buffers/VertexBuffer/Headers/glGenericVertexData.h"
#include "Platform/Video/OpenGL/Buffers/ShaderBuffer/Headers/glUniformBuffer.h"
#include "Platform/Video/OpenGL/Buffers/Headers/glMemoryManager.h"

#include "GUI/Headers/GUIText.h"
#include "Core/Headers/Application.h"
#include "Core/Headers/ParamHandler.h"
#include "Core/Time/Headers/ProfileTimer.h"
#include "Geometry/Material/Headers/Material.h"
#include "Rendering/Lighting/Headers/LightPool.h"

#ifndef GLFONTSTASH_IMPLEMENTATION
#define GLFONTSTASH_IMPLEMENTATION
#define FONTSTASH_IMPLEMENTATION
#include "Text/Headers/fontstash.h"
#include "Text/Headers/glfontstash.h"
#endif

#include <SDL_video.h>

#ifndef CEGUI_STATIC
#define CEGUI_STATIC
#endif //CEGUI_STATIC

#include <CEGUI/CEGUI.h>

namespace Divide {

namespace {
    /// How many frames of delay do we allow between the current read and write queries
    /// The longer the delay, the better the performance but the more out of sync the results
    const U32 g_performanceQueryRingLength = 2;
    /// Number of queries
    const U32 g_performanceQueryCount = 1;
    /// ID of the frame duration query
    const U32 g_performanceQueryFrameDurationIndex = 0;
};

GL_API::GL_API()
    : RenderAPIWrapper(),
      _prevSizeNode(0),
      _prevSizeString(0),
      _prevWidthNode(0),
      _prevWidthString(0),
      _lineWidthLimit(1),
      _dummyVAO(0),
      _fonsContext(nullptr),
      _GUIGLrenderer(nullptr),
      _swapBufferTimer(Time::ADD_TIMER("Swap Buffer Timer"))
{
    // Only updated in Debug builds
    FRAME_DURATION_GPU = 0;
    // All clip planes are disabled at first (default OpenGL state)
    _activeClipPlanes.fill(false);
    _fontCache.second = -1;
    _samplerBoundMap.fill(0);
    _textureBoundMap.fill(std::make_pair(0, GL_NONE));

    _hardwareQueries.reserve(g_performanceQueryCount);
    for (U32 i = 0; i < g_performanceQueryCount; ++i) {
        _hardwareQueries.emplace_back(MemoryManager_NEW glHardwareQueryRing(g_performanceQueryRingLength));
    }
}

GL_API::~GL_API()
{
    MemoryManager::DELETE_VECTOR(_hardwareQueries);
}

/// FontStash library initialization
bool GL_API::createFonsContext() {
    // 512x512 atlas with bottom-left origin
    _fonsContext = glfonsCreate(512, 512, FONS_ZERO_BOTTOMLEFT);
    return _fonsContext != nullptr;
}

/// FontStash library deinitialization
void GL_API::deleteFonsContext() {
    glfonsDelete(_fonsContext);
    _fonsContext = nullptr;
}

/// Prepare the GPU for rendering a frame
void GL_API::beginFrame() {
// Start a duration query in debug builds
#if defined(ENABLE_GPU_VALIDATION)
    glBeginQuery(GL_TIME_ELAPSED, _hardwareQueries[g_performanceQueryFrameDurationIndex]->writeQuery().getID());
#endif
    // Clear our buffers
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT /* | GL_STENCIL_BUFFER_BIT*/);
    // Clears are registered as draw calls by most software, so we do the same
    // to stay in sync with third party software
    GFX_DEVICE.registerDrawCall();
    GL_API::setActiveBuffer(GL_DRAW_INDIRECT_BUFFER, _indirectDrawBuffer);
}

/// Finish rendering the current frame
void GL_API::endFrame(bool swapBuffers) {
    // Revert back to the default OpenGL states
    clearStates();
    // Swap buffers
    if (swapBuffers) {
        Time::ScopedTimer time(_swapBufferTimer);
        SDL_GL_SwapWindow(Application::instance()
                          .windowManager()
                          .getActiveWindow()
                          .getRawWindow());
    }

    // End the timing query started in beginFrame() in debug builds
#if defined(ENABLE_GPU_VALIDATION)
    glEndQuery(GL_TIME_ELAPSED);
    _hardwareQueries[g_performanceQueryFrameDurationIndex]->incQueue();
#endif
}

GLuint64 GL_API::getFrameDurationGPU() {
#if defined(ENABLE_GPU_VALIDATION)
    // The returned results are 'g_performanceQueryFrameDurationIndex' frames old!
    glGetQueryObjectui64v(_hardwareQueries[g_performanceQueryFrameDurationIndex]->readQuery().getID(),
                          GL_QUERY_RESULT,
                          &FRAME_DURATION_GPU);
#endif

    return FRAME_DURATION_GPU;
}

void GL_API::appendToShaderHeader(ShaderType type, const stringImpl& entry,
                                  ShaderOffsetArray& inOutOffset) {
    GLuint index = to_uint(type);
    stringImpl stage;

    switch (type) {

        case ShaderType::VERTEX:
            stage = "Vertex";
            break;

        case ShaderType::FRAGMENT:
            stage = "Fragment";
            break;

        case ShaderType::GEOMETRY:
            stage = "Geometry";
            break;

        case ShaderType::TESSELATION_CTRL:
            stage = "TessellationC";
            break;

        case ShaderType::TESSELATION_EVAL:
            stage = "TessellationE";
            break;
        case ShaderType::COMPUTE:
            stage = "Compute";
            break;

        case ShaderType::COUNT:
            stage.clear();
            break;

        default:
            return;
    }

    glswAddDirectiveToken(stage.c_str(), entry.c_str());
    inOutOffset[index]++;
}

/// Prepare our shader loading system
bool GL_API::initShaders() {
    static const stringImpl shaderVaryings[] = { "flat uint dvd_drawID;",
                                                 "vec2 _texCoord;",
                                                 "vec4 _vertexW;",
                                                 "vec4 _vertexWV;",
                                                 "vec3 _normalWV;",
                                                 "vec3 _tangentWV;",
                                                 "vec3 _bitangentWV;"
                                                };
    // Initialize GLSW
    GLint glswState = glswInit();

    ShaderOffsetArray lineOffsets = {0};
  
    // Add our engine specific defines and various code pieces to every GLSL shader
    // Add version as the first shader statement, followed by copyright notice
    appendToShaderHeader(ShaderType::COUNT, "#version 450 core", lineOffsets);

    appendToShaderHeader(ShaderType::COUNT,
                         "/*Copyright 2009-2016 DIVIDE-Studio*/", lineOffsets);
    appendToShaderHeader(ShaderType::COUNT,
                         "#extension GL_ARB_shader_draw_parameters : require",
                         lineOffsets);
    appendToShaderHeader(ShaderType::COUNT,
                         "#extension GL_ARB_gpu_shader5 : require",
                         lineOffsets);
    appendToShaderHeader(ShaderType::COUNT,
                         Util::StringFormat("#define GPU_VENDOR_AMD %d", to_const_uint(GPUVendor::AMD)),
                         lineOffsets);
    appendToShaderHeader(ShaderType::COUNT,
                         Util::StringFormat("#define GPU_VENDOR_NVIDIA %d", to_const_uint(GPUVendor::NVIDIA)),
                         lineOffsets);
    appendToShaderHeader(ShaderType::COUNT,
                         Util::StringFormat("#define GPU_VENDOR_INTEL %d", to_const_uint(GPUVendor::INTEL)),
                         lineOffsets);
    appendToShaderHeader(ShaderType::COUNT,
                         Util::StringFormat("#define GPU_VENDOR_OTHER %d", to_const_uint(GPUVendor::OTHER)),
                         lineOffsets);
    appendToShaderHeader(ShaderType::COUNT,
                         Util::StringFormat("#define GPU_VENDOR %d", to_uint(GFX_DEVICE.getGPUVendor())),
                         lineOffsets);

    // Add current build environment information to the shaders
#if defined(_DEBUG)
    appendToShaderHeader(ShaderType::COUNT, "#define _DEBUG", lineOffsets);
#elif defined(_PROFILE)
    appendToShaderHeader(ShaderType::COUNT, "#define _PROFILE", lineOffsets);
#else
    appendToShaderHeader(ShaderType::COUNT, "#define _RELEASE", lineOffsets);
#endif

    // Shader stage level reflection system. A shader stage must know what stage
    // it's used for
    appendToShaderHeader(ShaderType::VERTEX, "#define VERT_SHADER",
                         lineOffsets);
    appendToShaderHeader(ShaderType::FRAGMENT, "#define FRAG_SHADER",
                         lineOffsets);
    appendToShaderHeader(ShaderType::GEOMETRY, "#define GEOM_SHADER",
                         lineOffsets);
    appendToShaderHeader(ShaderType::TESSELATION_EVAL,
                         "#define TESS_EVAL_SHADER", lineOffsets);
    appendToShaderHeader(ShaderType::TESSELATION_CTRL,
                         "#define TESS_CTRL_SHADER", lineOffsets);
    appendToShaderHeader(ShaderType::COMPUTE, "#define COMPUTE_SHADER",
                         lineOffsets);

    // This line gets replaced in every shader at load with the custom list of
    // defines specified by the material
    appendToShaderHeader(ShaderType::COUNT, "//__CUSTOM_DEFINES__",
                         lineOffsets);

    // Add some nVidia specific pragma directives
    if (GFX_DEVICE.getGPUVendor() == GPUVendor::NVIDIA) {
        appendToShaderHeader(ShaderType::COUNT,
                             "//#pragma optionNV(fastmath on)", lineOffsets);
        appendToShaderHeader(ShaderType::COUNT,
                             "//#pragma optionNV(fastprecision on)",
                             lineOffsets);
        appendToShaderHeader(ShaderType::COUNT,
                             "//#pragma optionNV(inline all)", lineOffsets);
        appendToShaderHeader(ShaderType::COUNT,
                             "//#pragma optionNV(ifcvt none)", lineOffsets);
        appendToShaderHeader(ShaderType::COUNT, "//#pragma optionNV(strict on)",
                             lineOffsets);
        appendToShaderHeader(ShaderType::COUNT,
                             "//#pragma optionNV(unroll all)", lineOffsets);
    }

    if (Config::USE_HIZ_CULLING) {
        appendToShaderHeader(ShaderType::COUNT, "#define USE_HIZ_CULLING", lineOffsets);
    }

    if (Config::DEBUG_HIZ_CULLING) {
        appendToShaderHeader(ShaderType::COUNT, "#define DEBUG_HIZ_CULLING", lineOffsets);
    }

    appendToShaderHeader(
        ShaderType::COUNT,
        "const uint MAX_SPLITS_PER_LIGHT = " +
        to_stringImpl(Config::Lighting::MAX_SPLITS_PER_LIGHT) + ";",
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "const uint MAX_POSSIBLE_LIGHTS = " +
        to_stringImpl(Config::Lighting::MAX_POSSIBLE_LIGHTS) + ";",
        lineOffsets);

    appendToShaderHeader(ShaderType::COUNT,
        "const int MAX_VISIBLE_NODES = " +
        to_stringImpl(Config::MAX_VISIBLE_NODES) + ";",
        lineOffsets);

    appendToShaderHeader(ShaderType::COUNT, "const float Z_TEST_SIGMA = 0.0001;", lineOffsets);

    appendToShaderHeader(ShaderType::COUNT, "const float ALPHA_DISCARD_THRESHOLD = 0.05;", lineOffsets);

    appendToShaderHeader(ShaderType::FRAGMENT, "const uint DEPTH_EXP_WARP = 32;", lineOffsets);

    if (Config::USE_HIZ_CULLING) {
        appendToShaderHeader(ShaderType::COUNT, "#define USE_HIZ_CULLING", lineOffsets);
    }
    if (Config::DEBUG_HIZ_CULLING) {
        appendToShaderHeader(ShaderType::COUNT, "#define DEBUG_HIZ_CULLING", lineOffsets);
    }

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define MAX_CLIP_PLANES " + to_stringImpl(Config::MAX_CLIP_PLANES),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define MAX_SHADOW_CASTING_LIGHTS " +
        to_stringImpl(
        Config::Lighting::MAX_SHADOW_CASTING_LIGHTS),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define MAX_LIGHT_TYPES " +
        to_stringImpl(to_const_uint(LightType::COUNT)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define BUFFER_GPU_BLOCK " +
        to_stringImpl(to_const_uint(ShaderBufferLocation::GPU_BLOCK)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define BUFFER_GPU_COMMANDS " +
        to_stringImpl(to_const_uint(ShaderBufferLocation::GPU_COMMANDS)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define BUFFER_LIGHT_NORMAL " +
        to_stringImpl(to_const_uint(ShaderBufferLocation::LIGHT_NORMAL)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define BUFFER_LIGHT_SHADOW " +
        to_stringImpl(to_const_uint(ShaderBufferLocation::LIGHT_SHADOW)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define BUFFER_LIGHT_INDICES " +
        to_stringImpl(to_const_uint(ShaderBufferLocation::LIGHT_INDICES)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define BUFFER_NODE_INFO " +
        to_stringImpl(to_const_uint(ShaderBufferLocation::NODE_INFO)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define BUFFER_SCENE_DATA " +
        to_stringImpl(to_const_uint(ShaderBufferLocation::SCENE_DATA)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define FORWARD_PLUS_TILE_RES " + to_stringImpl(Config::Lighting::FORWARD_PLUS_TILE_RES),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define MAX_NUM_LIGHTS_PER_TILE " + to_stringImpl(Config::Lighting::FORWARD_PLUS_MAX_LIGHTS_PER_TILE),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define LIGHT_INDEX_BUFFER_SENTINEL " + to_stringImpl(Config::Lighting::FORWARD_PLUS_LIGHT_INDEX_BUFFER_SENTINEL),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::FRAGMENT,
        "#define MAX_TEXTURE_SLOTS " + to_stringImpl(GL_API::_maxTextureUnits),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define TEXTURE_UNIT0 " +
            to_stringImpl(to_const_uint(ShaderProgram::TextureUsage::UNIT0)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::FRAGMENT,
        "#define TEXTURE_UNIT1 " +
            to_stringImpl(to_const_uint(ShaderProgram::TextureUsage::UNIT1)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::FRAGMENT,
        "#define TEXTURE_NORMALMAP " +
            to_stringImpl(to_const_uint(ShaderProgram::TextureUsage::NORMALMAP)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::FRAGMENT,
        "#define TEXTURE_OPACITY " +
            to_stringImpl(to_const_uint(ShaderProgram::TextureUsage::OPACITY)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::FRAGMENT,
        "#define TEXTURE_SPECULAR " +
            to_stringImpl(to_const_uint(ShaderProgram::TextureUsage::SPECULAR)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::FRAGMENT,
        "#define TEXTURE_PROJECTION " +
            to_stringImpl(to_const_uint(ShaderProgram::TextureUsage::PROJECTION)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::COUNT,
        "#define TEXTURE_DEPTH_MAP " +
        to_stringImpl(to_const_uint(ShaderProgram::TextureUsage::DEPTH)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::FRAGMENT,
        "#define TEXTURE_REFLECTION " +
            to_stringImpl(to_const_uint(ShaderProgram::TextureUsage::REFLECTION)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::FRAGMENT,
        "#define TEXTURE_REFRACTION " +
            to_stringImpl(to_const_uint(ShaderProgram::TextureUsage::REFRACTION)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::FRAGMENT,
        "#define SHADOW_CUBE_MAP_ARRAY " +
            to_stringImpl(
                to_uint(LightPool::getShadowBindSlotOffset(ShadowType::CUBEMAP))),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::FRAGMENT,
        "#define SHADOW_SINGLE_MAP_ARRAY " +
            to_stringImpl(
                to_uint(LightPool::getShadowBindSlotOffset(ShadowType::SINGLE))),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::FRAGMENT,
        "#define SHADOW_LAYERED_MAP_ARRAY " +
            to_stringImpl(
                to_uint(LightPool::getShadowBindSlotOffset(ShadowType::LAYERED))),
        lineOffsets);

    appendToShaderHeader(ShaderType::VERTEX, "invariant gl_Position;", lineOffsets);

    // GLSL <-> VBO intercommunication
    appendToShaderHeader(ShaderType::VERTEX,
                         "const uint MAX_BONE_COUNT_PER_NODE = " +
                             to_stringImpl(Config::MAX_BONE_COUNT_PER_NODE) +
                             ";",
                         lineOffsets);

    appendToShaderHeader(
        ShaderType::VERTEX,
        "#define BUFFER_BONE_TRANSFORMS " +
            to_stringImpl(to_const_uint(ShaderBufferLocation::BONE_TRANSFORMS)),
        lineOffsets);

    appendToShaderHeader(
        ShaderType::VERTEX,
        "#define DIRECTIONAL_LIGHT_DISTANCE_FACTOR " +
        to_stringImpl(to_const_uint(Config::Lighting::DIRECTIONAL_LIGHT_DISTANCE)),
        lineOffsets);

    // Vertex data has a fixed format
    appendToShaderHeader(
        ShaderType::VERTEX,
        "layout(location = " +
            to_stringImpl(to_const_uint(AttribLocation::VERTEX_POSITION)) +
            ") in vec3 inVertexData;",
        lineOffsets);

    appendToShaderHeader(
        ShaderType::VERTEX,
        "layout(location = " +
            to_stringImpl(to_const_uint(AttribLocation::VERTEX_COLOR)) +
            ") in vec4 inColourData;",
        lineOffsets);

    appendToShaderHeader(
        ShaderType::VERTEX,
        "layout(location = " +
            to_stringImpl(to_const_uint(AttribLocation::VERTEX_NORMAL)) +
            ") in float inNormalData;",
        lineOffsets);

    appendToShaderHeader(
        ShaderType::VERTEX,
        "layout(location = " +
            to_stringImpl(to_const_uint(AttribLocation::VERTEX_TEXCOORD)) +
            ") in vec2 inTexCoordData;",
        lineOffsets);

    appendToShaderHeader(
        ShaderType::VERTEX,
        "layout(location = " +
            to_stringImpl(to_const_uint(AttribLocation::VERTEX_TANGENT)) +
            ") in float inTangentData;",
        lineOffsets);

    appendToShaderHeader(
        ShaderType::VERTEX,
        "layout(location = " +
            to_stringImpl(to_const_uint(AttribLocation::VERTEX_BONE_WEIGHT)) +
            ") in vec4 inBoneWeightData;",
        lineOffsets);

    appendToShaderHeader(
        ShaderType::VERTEX,
        "layout(location = " +
            to_stringImpl(to_const_uint(AttribLocation::VERTEX_BONE_INDICE)) +
            ") in uvec4 inBoneIndiceData;",
        lineOffsets);
    
    appendToShaderHeader(
        ShaderType::VERTEX,
        "layout(location = " +
            to_stringImpl(to_const_uint(AttribLocation::VERTEX_WIDTH)) +
            ") in uint inLineWidthData;",
        lineOffsets);

    // INTERFACE BLOCKS BEGIN
    appendToShaderHeader(ShaderType::COUNT, "", lineOffsets);
    appendToShaderHeader(ShaderType::VERTEX, "out PerVertexData{", lineOffsets);
    appendToShaderHeader(ShaderType::FRAGMENT, "in  PerVertexData{", lineOffsets);
    appendToShaderHeader(ShaderType::GEOMETRY, "in  PerVertexData{", lineOffsets);
    for (const stringImpl& entry : shaderVaryings) {
        appendToShaderHeader(ShaderType::VERTEX, "    " + entry, lineOffsets);
        appendToShaderHeader(ShaderType::FRAGMENT, "    " + entry, lineOffsets);
        appendToShaderHeader(ShaderType::GEOMETRY, "    " + entry, lineOffsets);
    }
    appendToShaderHeader(ShaderType::GEOMETRY, "} v_in[];", lineOffsets);
    appendToShaderHeader(ShaderType::GEOMETRY, "out  PerVertexData{", lineOffsets);
    for (const stringImpl& entry : shaderVaryings) {
        appendToShaderHeader(ShaderType::GEOMETRY, "    " + entry, lineOffsets);
    }
    appendToShaderHeader(ShaderType::GEOMETRY, "} g_out;", lineOffsets);
    appendToShaderHeader(ShaderType::FRAGMENT, "} f_in;", lineOffsets);
    appendToShaderHeader(ShaderType::VERTEX, "} v_out;", lineOffsets);
    appendToShaderHeader(ShaderType::VERTEX, "#define VAR v_out", lineOffsets);
    appendToShaderHeader(ShaderType::GEOMETRY, "#define VAR v_in", lineOffsets);
    appendToShaderHeader(ShaderType::FRAGMENT, "#define VAR f_in", lineOffsets);
    appendToShaderHeader(ShaderType::COUNT, "", lineOffsets);
    // INTERFACE BLOCKS END

    appendToShaderHeader(ShaderType::GEOMETRY,
                         "#include \"inOut.geom\"",
                         lineOffsets);
    lineOffsets[to_const_uint(ShaderType::GEOMETRY)] += 18;

    // GPU specific data, such as GFXDevice's main uniform block and clipping
    // planes are defined in an external file included in every shader
    appendToShaderHeader(ShaderType::COUNT,
                        "#include \"nodeDataInput.cmn\"",
                         lineOffsets);
    lineOffsets[to_const_uint(ShaderType::COUNT)] += 55;

    Attorney::GLAPIShaderProgram::setGlobalLineOffset(
        lineOffsets[to_const_uint(ShaderType::COUNT)]);

    Attorney::GLAPIShaderProgram::addLineOffset(
        ShaderType::VERTEX, lineOffsets[to_const_uint(ShaderType::VERTEX)]);

    Attorney::GLAPIShaderProgram::addLineOffset(
        ShaderType::FRAGMENT, lineOffsets[to_const_uint(ShaderType::FRAGMENT)]);

    Attorney::GLAPIShaderProgram::addLineOffset(
        ShaderType::GEOMETRY, lineOffsets[to_const_uint(ShaderType::GEOMETRY)]);

    Attorney::GLAPIShaderProgram::addLineOffset(
        ShaderType::TESSELATION_CTRL,
        lineOffsets[to_const_uint(ShaderType::TESSELATION_CTRL)]);

    Attorney::GLAPIShaderProgram::addLineOffset(
        ShaderType::TESSELATION_EVAL,
        lineOffsets[to_const_uint(ShaderType::TESSELATION_EVAL)]);

    Attorney::GLAPIShaderProgram::addLineOffset(
        ShaderType::COMPUTE, lineOffsets[to_const_uint(ShaderType::COMPUTE)]);

    // Check initialization status for GLSL and glsl-optimizer
    return glswState == 1;
}

/// Revert everything that was set up in "initShaders()"
bool GL_API::deInitShaders() {
    // Shutdown GLSW
    return (glswShutdown() == 1);
}

/// Try to find the requested font in the font cache. Load on cache miss.
I32 GL_API::getFont(const stringImpl& fontName) {
    if (_fontCache.first.compare(fontName) != 0) {
        _fontCache.first = fontName;
        ULL fontNameHash = _ID_RT(fontName);
        // Search for the requested font by name
        FontCache::const_iterator it = _fonts.find(fontNameHash);
        // If we failed to find it, it wasn't loaded yet
        if (it == std::cend(_fonts)) {
            // Fonts are stored in the general asset directory -> in the GUI
            // subfolder -> in the fonts subfolder
            stringImpl fontPath(
                ParamHandler::instance().getParam<stringImpl>(
                    _ID("assetsLocation"), "assets") +
                "/GUI/fonts/");
            fontPath += fontName;
            // We use FontStash to load the font file
            _fontCache.second =
                fonsAddFont(_fonsContext, fontName.c_str(), fontPath.c_str());
            // If the font is invalid, inform the user, but map it anyway, to avoid
            // loading an invalid font file on every request
            if (_fontCache.second == FONS_INVALID) {
                Console::errorfn(Locale::get(_ID("ERROR_FONT_FILE")), fontName.c_str());
            }
            // Save the font in the font cache
            hashAlg::emplace(_fonts, fontNameHash, _fontCache.second);
            
        } else {
            _fontCache.second = it->second;
        }

    }

    // Return the font
    return _fontCache.second;
}

/// Text rendering is handled exclusively by Mikko Mononen's FontStash library
/// (https://github.com/memononen/fontstash)
/// with his OpenGL frontend adapted for core context profiles
void GL_API::drawText(const TextLabel& textLabel, const vec2<F32>& position) {
    /*glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 2, -1,
                    "OpenGL render text start!");*/
    // Retrieve the font from the font cache
    I32 font = getFont(textLabel._font);
    // The font may be invalid, so skip this text label
    if (font == FONS_INVALID) {
        return;
    }
    // See FontStash documentation for the following block
    {
        fonsClearState(_fonsContext);

        F32 lh = 0;
        fonsVertMetrics(_fonsContext, nullptr, nullptr, &lh);
        fonsSetBlur(_fonsContext, textLabel._blurAmount);
        fonsSetBlur(_fonsContext, textLabel._spacing);
        fonsSetAlign(_fonsContext, textLabel._alignFlag);
        fonsSetSize(_fonsContext, to_float(textLabel._fontSize));
        fonsSetFont(_fonsContext, font);

        fonsSetColour(_fonsContext,
                     textLabel._colour.r,
                     textLabel._colour.g,
                     textLabel._colour.b,
                     textLabel._colour.a);

      
        const vectorImpl<stringImpl>& text = textLabel.text();
        vectorAlg::vecSize lineCount = text.size();
        for (vectorAlg::vecSize i = 0; i < lineCount; ++i) {
            fonsDrawText(_fonsContext,
                         position.x,
                         position.y - (lh * i),
                         text[i].c_str(),
                         nullptr);
            // Register each label rendered as a draw call
            GFX_DEVICE.registerDrawCall();
        }
    }
    // glPopDebugGroup();
}

void GL_API::draw(const GenericDrawCommand& cmd) {
    if (cmd.sourceBuffer() == nullptr) {
        GL_API::setActiveVAO(_dummyVAO);
        
        U32 indexCount = 0;
        switch(cmd.primitiveType()) {
            case PrimitiveType::TRIANGLES : indexCount = cmd.drawCount() * 3; break;
            case PrimitiveType::API_POINTS: indexCount = cmd.drawCount(); break;
            default: indexCount = cmd.cmd().indexCount; break;
        }

        glDrawArrays(GLUtil::glPrimitiveTypeTable[to_uint(cmd.primitiveType())], cmd.cmd().firstIndex, indexCount);
    } else {
        cmd.sourceBuffer()->draw(cmd, false);
    }
}


void GL_API::registerCommandBuffer(const ShaderBuffer& commandBuffer) const {
    _indirectDrawBuffer = static_cast<const glUniformBuffer&>(commandBuffer).bufferID();
    GL_API::setActiveBuffer(GL_DRAW_INDIRECT_BUFFER, _indirectDrawBuffer);
}

bool GL_API::makeTexturesResident(const TextureDataContainer& textureData) {
    for (const TextureData& data : textureData) {
        makeTextureResident(data);
    }

    return true;
}

bool GL_API::makeTextureResident(const TextureData& textureData) {
    return bindTexture(
        static_cast<GLushort>(textureData.getHandleLow()),
        textureData.getHandleHigh(),
        GLUtil::glTextureTypeTable[to_uint(textureData._textureType)],
        textureData._samplerHash);
}

/// Verify if we have a sampler object created and available for the given
/// descriptor
size_t GL_API::getOrCreateSamplerObject(const SamplerDescriptor& descriptor) {
    // Get the descriptor's hash value
    size_t hashValue = descriptor.getHash();
    // Try to find the hash value in the sampler object map
    UpgradableReadLock ur_lock(_samplerMapLock);
    samplerObjectMap::const_iterator it = _samplerMap.find(hashValue);
    // If we fail to find it, we need to create a new sampler object
    if (it == std::end(_samplerMap)) {
        UpgradeToWriteLock w_lock(ur_lock);
        // Create and store the newly created sample object. GL_API is
        // responsible for deleting these!
        hashAlg::emplace(_samplerMap, hashValue, MemoryManager_NEW glSamplerObject(descriptor));
    }
    // Return the sampler object's hash value
    return hashValue;
}

/// Return the OpenGL sampler object's handle for the given hash value
GLuint GL_API::getSamplerHandle(size_t samplerHash) {
    // If the hash value is 0, we assume the code is trying to unbind a sampler object
    GLuint samplerHandle = 0;
    if (samplerHash > 0) {
        // If we fail to find the sampler object for the given hash, we print an
        // error and return the default OpenGL handle
        ReadLock r_lock(_samplerMapLock);
        samplerObjectMap::const_iterator it = _samplerMap.find(samplerHash);
        if (it != std::cend(_samplerMap)) {
            // Return the OpenGL handle for the sampler object matching the specified hash value
            samplerHandle = it->second->getObjectHandle();
        } else {
            Console::errorfn(Locale::get(_ID("ERROR_NO_SAMPLER_OBJECT_FOUND")), samplerHash);
        }
    }

    return samplerHandle;
}

};

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

Diff revisions: vs.
Revision Author Commited Message
750 Diff Diff IonutCava picture IonutCava Thu 07 Jul, 2016 16:02:03 +0000

[IonutCava]
- Static analysis based fixes and improvements

743 Diff Diff IonutCava picture IonutCava Tue 28 Jun, 2016 15:55:50 +0000

[IonutCava]
- More performance tuning:
— Move billboarding related camera variable calculation to shaders instead of CPU
— Replace some DIVIDE_ASSERT calls with regular assert calls in really low level code.
— Some cleanup of the GenericDrawCommand class
— glRegularBuffer does an invalidation call before updating
— Misc changes

741 Diff Diff IonutCava picture IonutCava Sun 26 Jun, 2016 18:01:25 +0000

[IonutCava]
- Properly wait for all pending tasks to finish before shutdown
- Add a reset method to the FrameRateHandler
- Rework glQuery system.
- Avoid mipmap generation on the current luma render target

737 Diff Diff IonutCava picture IonutCava Thu 23 Jun, 2016 16:20:05 +0000

[IonutCava]
- Improved GenericVertexData structure (separate buffer data from attribute data entirely)
- Added a VAO pool for OpenGL so that all requested VAOs are allocated on the main thread
- Added a mainThreadTask system to queue a task to run on the main thread and optionally wait for it to complete
- Added the option to specify generic geometry for the particle system with an optional index buffer

734 Diff Diff IonutCava picture IonutCava Tue 21 Jun, 2016 16:28:11 +0000

[IonutCava]
- Added a render target pool:
— All render targets are now allocated (and tracked) by the GFXDevice.
— Allocation routines return a slim RenderTargetHandle object that will be used later on in draw commands.

- Added a refraction render pass that will handle translucent objects that need refracted textures instead of clear transparency
— Both reflective nodes and refractive nodes are not gathered properly at this point

- All API specific objects (buffers, textures, etc) are now initialized in the GFXDevice class (see GFXDeviceObjects.cpp)
— This allowed for the slimming of the RenderAPIWrapper interface

- Improved ENABLE_GPU_VALIDATION macro utilization:
— It enabled shadow map split plane debugging
— It bypasses loading shaders from text cache

732 Diff Diff IonutCava picture IonutCava Fri 17 Jun, 2016 14:46:33 +0000

[IonutCava]
- Fixed visibility issues with empty GUIText elements.
- Update GLSL copyright notice
- Small corrections to selection code

727 Diff Diff IonutCava picture IonutCava Tue 14 Jun, 2016 16:01:38 +0000

[IonutCava]
- Remove node and cmd buffers from GFXDevice and add them as a new BufferData struct to RenderPass class.
— Each render pass holds its own buffers
- Improvements / fixes to the CSM code
- Added a global toggle to enable/disable custom memory allocators

726 Diff Diff IonutCava picture IonutCava Fri 10 Jun, 2016 16:13:52 +0000

[IonutCava]
- More static analysis based corrections
- Added initial stub code for a command pool system for GenericDrawCommands

725 Diff Diff IonutCava picture IonutCava Fri 10 Jun, 2016 12:44:46 +0000

[IonutCava]
- Removed GFX drawPoints and drawTriangle calls and replaced them with a single draw command that takes a GenericDrawCommand parameter.
- Updated CSM code. Shadows now render in the correct position again. Still has issues.

721 IonutCava picture IonutCava Wed 08 Jun, 2016 15:47:49 +0000

[IonutCava]
- Spelling: change all references from our code of “color” to the PROPER British version of “colour” because it sounds 100x better