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
#include "config.h"

#include "Headers/Kernel.h"
#include "Headers/PlatformContext.h"

#include "GUI/Headers/GUI.h"
#include "GUI/Headers/GUISplash.h"
#include "GUI/Headers/GUIConsole.h"
#include "Utility/Headers/XMLParser.h"
#include "Core/Headers/ParamHandler.h"
#include "Managers/Headers/SceneManager.h"
#include "Managers/Headers/RenderPassManager.h"
#include "Core/Time/Headers/ProfileTimer.h"
#include "Core/Time/Headers/ApplicationTimer.h"
#include "Rendering/Headers/Renderer.h"
#include "Rendering/PostFX/Headers/PostFX.h"
#include "Platform/Video/Headers/GFXDevice.h"
#include "Physics/Headers/PXDevice.h"
#include "Dynamics/Entities/Units/Headers/Player.h"
#include "Rendering/Camera/Headers/FreeFlyCamera.h"
#include "Platform/Input/Headers/InputInterface.h"
#include "Managers/Headers/FrameListenerManager.h"
#include "Platform/Compute/Headers/OpenCLInterface.h"

namespace Divide {

LoopTimingData::LoopTimingData() : _updateLoops(0),
                                   _previousTime(0ULL),
                                   _currentTime(0ULL),
                                   _currentTimeFrozen(0ULL),
                                   _currentTimeDelta(0ULL),
                                   _nextGameTick(0ULL),
                                   _keepAlive(true),
                                   _freezeLoopTime(false)
{
}

Kernel::Kernel(I32 argc, char** argv, Application& parentApp)
    : _argc(argc),
      _argv(argv),
      _APP(parentApp),
      _platformContext(nullptr),
      _resCache(nullptr),
      _taskPool(Config::MAX_POOLED_TASKS),
      _appLoopTimer(Time::ADD_TIMER("Main Loop Timer")),
      _frameTimer(Time::ADD_TIMER("Total Frame Timer")),
      _appIdleTimer(Time::ADD_TIMER("Loop Idle Timer")),
      _appScenePass(Time::ADD_TIMER("Loop Scene Pass Timer")),
      _physicsUpdateTimer(Time::ADD_TIMER("Physics Update Timer")),
      _sceneUpdateTimer(Time::ADD_TIMER("Scene Update Timer")),
      _sceneUpdateLoopTimer(Time::ADD_TIMER("Scene Update Loop timer")),
      _physicsProcessTimer(Time::ADD_TIMER("Physics Process Timer")),
      _cameraMgrTimer(Time::ADD_TIMER("Camera Manager Update Timer")),
      _flushToScreenTimer(Time::ADD_TIMER("Flush To Screen Timer")),
      _preRenderTimer(Time::ADD_TIMER("Pre-render Timer")),
      _postRenderTimer(Time::ADD_TIMER("Post-render Timer"))
{
    _platformContext = std::make_unique<PlatformContext>(
        std::make_unique<GFXDevice>(*this),              // Video
        std::make_unique<SFXDevice>(*this),              // Audio
        std::make_unique<PXDevice>(*this),               // Physics
        std::make_unique<GUI>(*this),                    // Graphical User Interface
        std::make_unique<Input::InputInterface>(*this)); // Input

    _renderPassManager = std::make_unique<RenderPassManager>(*this, _platformContext->gfx());

    _sceneManager = std::make_unique<SceneManager>(*this); // Scene Manager

    _appLoopTimer.addChildTimer(_appIdleTimer);
    _appLoopTimer.addChildTimer(_frameTimer);
    _frameTimer.addChildTimer(_appScenePass);
    _appScenePass.addChildTimer(_cameraMgrTimer);
    _appScenePass.addChildTimer(_physicsUpdateTimer);
    _appScenePass.addChildTimer(_physicsProcessTimer);
    _appScenePass.addChildTimer(_sceneUpdateTimer);
    _appScenePass.addChildTimer(_flushToScreenTimer);
    _flushToScreenTimer.addChildTimer(_preRenderTimer);
    _flushToScreenTimer.addChildTimer(_postRenderTimer);
    _sceneUpdateTimer.addChildTimer(_sceneUpdateLoopTimer);

    _resCache = std::make_unique<ResourceCache>(*_platformContext);

    FrameListenerManager::createInstance();
    OpenCLInterface::createInstance();
    
    ParamHandler::instance().setParam<stringImpl>(_ID("language"), Locale::currentLanguage());
}

Kernel::~Kernel()
{
}

void Kernel::idle() {
    _taskPool.flushCallbackQueue();

    _platformContext->idle();
    _sceneManager->idle();

    FrameListenerManager::instance().idle();

    ParamHandler& par = ParamHandler::instance();

    bool freezeLoopTime = par.getParam(_ID("freezeLoopTime"), false);
    if (freezeLoopTime != _timingData._freezeLoopTime) {
        _timingData._freezeLoopTime = freezeLoopTime;
        _timingData._currentTimeFrozen = _timingData._currentTime;
        _APP.mainLoopPaused(_timingData._freezeLoopTime);
    }

    const stringImpl& pendingLanguage = par.getParam<stringImpl>(_ID("language"));
    if (pendingLanguage.compare(Locale::currentLanguage()) != 0) {
        Locale::changeLanguage(pendingLanguage);
    }

}

void Kernel::onLoop() {
    if (!_timingData._keepAlive) {
        // exiting the rendering loop will return us to the last control point
        _APP.mainLoopActive(false);
        return;
    }

    // Update internal timer
    Time::ApplicationTimer::instance().update();
    {
        Time::ScopedTimer timer(_appLoopTimer);
   
        // Update time at every render loop
        _timingData._previousTime = _timingData._currentTime;
        _timingData._currentTime = Time::ElapsedMicroseconds();
        _timingData._currentTimeDelta = _timingData._currentTime - 
                                        _timingData._previousTime;

        // In case we break in the debugger
        if (_timingData._currentTimeDelta > Time::SecondsToMicroseconds(1)) {
            _timingData._currentTimeDelta = Config::SKIP_TICKS;
            _timingData._previousTime = _timingData._currentTime -
                                        _timingData._currentTimeDelta;
        }

        {
            Time::ScopedTimer timer2(_appIdleTimer);
            idle();
        }
        FrameEvent evt;
        FrameListenerManager& frameMgr = FrameListenerManager::instance();

        // Restore GPU to default state: clear buffers and set default render state
        _platformContext->sfx().beginFrame();
        _platformContext->gfx().beginFrame();
        {
            Time::ScopedTimer timer3(_frameTimer);
            // Launch the FRAME_STARTED event
            frameMgr.createEvent(_timingData._currentTime, FrameEventType::FRAME_EVENT_STARTED, evt);
            _timingData._keepAlive = frameMgr.frameEvent(evt);

            U64 deltaTime = _timingData._freezeLoopTime ? 0UL
                                                        : Config::USE_FIXED_TIMESTEP
                                                                    ? Config::SKIP_TICKS
                                                                    : _timingData._currentTimeDelta;

            // Process the current frame
            _timingData._keepAlive = mainLoopScene(evt, deltaTime) && _timingData._keepAlive;

            // Launch the FRAME_PROCESS event (a.k.a. the frame processing has ended
            // event)
            frameMgr.createEvent(_timingData._currentTime, FrameEventType::FRAME_EVENT_PROCESS, evt);

            _timingData._keepAlive = frameMgr.frameEvent(evt) && _timingData._keepAlive;
        }
        _platformContext->gfx().endFrame(_APP.mainLoopActive());
        _platformContext->sfx().endFrame();

        // Launch the FRAME_ENDED event (buffers have been swapped)
        frameMgr.createEvent(_timingData._currentTime, FrameEventType::FRAME_EVENT_ENDED, evt);
        _timingData._keepAlive = frameMgr.frameEvent(evt) && _timingData._keepAlive;

        _timingData._keepAlive = !_APP.ShutdownRequested() && _timingData._keepAlive;
    
        ErrorCode err = _APP.errorCode();

        if (err != ErrorCode::NO_ERR) {
            Console::errorfn("Error detected: [ %s ]", getErrorCodeName(err));
            _timingData._keepAlive = false;
        }
    }

if (Config::Profile::BENCHMARK_PERFORMANCE || Config::Profile::ENABLE_FUNCTION_PROFILING)
{
    U32 frameCount = _platformContext->gfx().getFrameCount();

    // Should be approximatelly 2 times a seconds
    bool print = false;
    if (Config::Build::IS_DEBUG_BUILD) {
        print = frameCount % (Config::TARGET_FRAME_RATE / 4) == 0;
    } else {
        print = frameCount % (Config::TARGET_FRAME_RATE / 2) == 0;
    }

    if (print) {
        stringImpl profileData(Util::StringFormat("Scene Update Loops: %d", _timingData._updateLoops));

        if (Config::Profile::BENCHMARK_PERFORMANCE) {
            profileData.append("\n");
            profileData.append(Time::ApplicationTimer::instance().benchmarkReport());
            profileData.append("\n");
            profileData.append(Util::StringFormat("GPU: [ %5.5f ] [DrawCalls: %d]",
                                                  Time::MicrosecondsToSeconds<F32>(_platformContext->gfx().getFrameDurationGPU()),
                                                  _platformContext->gfx().getDrawCallCount()));
        }
        if (Config::Profile::ENABLE_FUNCTION_PROFILING) {
            profileData.append("\n");
            profileData.append(Time::ProfileTimer::printAll());
        }

        Arena::Statistics stats = _platformContext->gfx().getObjectAllocStats();
        F32 gpuAllocatedKB = stats.bytes_allocated_ / 1024.0f;

        profileData.append("\n");
        profileData.append(Util::StringFormat("GPU Objects: %5.2f Kb (%5.2f Mb),\n"
                                              "             %d allocs,\n"
                                              "             %d blocks,\n"
                                              "             %d destructors",
                                              gpuAllocatedKB,
                                              gpuAllocatedKB / 1024,
                                              stats.num_of_allocs_,
                                              stats.num_of_blocks_,
                                              stats.num_of_dtros_));
        // Should equate to approximately once every 10 seconds
        if (frameCount % (Config::TARGET_FRAME_RATE * Time::Seconds(10)) == 0) {
            Console::printfn(profileData.c_str());
        }

        _platformContext->gui().modifyText(_ID("ProfileData"), profileData);
    }

    Util::RecordFloatEvent("kernel.mainLoopApp",
                           to_float(_appLoopTimer.get()),
                           _timingData._currentTime);

    if (frameCount % (Config::TARGET_FRAME_RATE * 10) == 0) {
        Util::FlushFloatEvents();
    }
}
}

bool Kernel::mainLoopScene(FrameEvent& evt, const U64 deltaTime) {
    Time::ScopedTimer timer(_appScenePass);

    // Physics system uses (or should use) its own timestep code
    U64 physicsTime 
        =  _timingData._freezeLoopTime ? 0ULL
                                       : _timingData._currentTimeDelta;
    {
        Time::ScopedTimer timer2(_cameraMgrTimer);
        // Update cameras
        Camera::update(deltaTime);
    }

    if (_APP.windowManager().getActiveWindow().minimized()) {
        idle();
        return true;
    }

    {
        Time::ScopedTimer timer2(_physicsProcessTimer);
        // Process physics
        _platformContext->pfx().process(physicsTime);
    }

    {
        Time::ScopedTimer timer2(_sceneUpdateTimer);

        const SceneManager::PlayerList& activePlayers = _sceneManager->getPlayers();
        U8 playerCount = to_ubyte(activePlayers.size());

        _timingData._updateLoops = 0;
        while (_timingData._currentTime > _timingData._nextGameTick &&
            _timingData._updateLoops < Config::MAX_FRAMESKIP) {

            if (_timingData._updateLoops == 0) {
                _sceneUpdateLoopTimer.start();
            }

            _sceneManager->processGUI(deltaTime);

            // Flush any pending threaded callbacks
            _taskPool.flushCallbackQueue();
            // Update scene based on input
            for (U8 i = 0; i < playerCount; ++i) {
                _sceneManager->processInput(i, deltaTime);
            }
            // process all scene events
            _sceneManager->processTasks(deltaTime);
            // Update the scene state based on current time (e.g. animation matrices)
            _sceneManager->updateSceneState(deltaTime);
            // Update visual effect timers as well
            PostFX::instance().update(deltaTime);
            if (_timingData._updateLoops == 0) {
                _sceneUpdateLoopTimer.stop();
            }

            _timingData._nextGameTick += deltaTime;
            _timingData._updateLoops++;

            if (Config::USE_FIXED_TIMESTEP) {
                if (_timingData._updateLoops == Config::MAX_FRAMESKIP &&
                    _timingData._currentTime > _timingData._nextGameTick) {
                    _timingData._nextGameTick = _timingData._currentTime;
                }
            } else {
                _timingData._nextGameTick = _timingData._currentTime;
            }

        }  // while
    }
    D64 interpolationFactor = 1.0;
    if (Config::USE_FIXED_TIMESTEP && !_timingData._freezeLoopTime) {
        interpolationFactor = static_cast<D64>(_timingData._currentTime + deltaTime - _timingData._nextGameTick) / deltaTime;
        assert(interpolationFactor <= 1.0 && interpolationFactor > 0.0);
    }

    GFXDevice::setFrameInterpolationFactor(interpolationFactor);
    
    // Get input events
    if (_APP.windowManager().getActiveWindow().hasFocus()) {
        _platformContext->input().update(_timingData._currentTimeDelta);
    } else {
        _sceneManager->onLostFocus();
    }
    {
        Time::ScopedTimer timer3(_physicsUpdateTimer);
        // Update physics
        _platformContext->pfx().update(physicsTime);
    }

    // Update the graphical user interface
    const OIS::MouseState& mouseState = _platformContext->input().getKeyboardMousePair(0).second->getMouseState();
    _platformContext->gui().update(_timingData._currentTimeDelta);
    _platformContext->gui().setCursorPosition(mouseState.X.abs, mouseState.Y.abs);
    return presentToScreen(evt, deltaTime);
}

void computeViewports(const vec4<I32>& mainViewport, vectorImpl<vec4<I32>>& targetViewports, U8 count) {
    
    assert(count > 0);
    I32 xOffset = mainViewport.x;
    I32 yOffset = mainViewport.y;
    I32 width = mainViewport.z;
    I32 height = mainViewport.w;

    targetViewports.resize(0);
    if (count == 1) { //Single Player
        targetViewports.push_back(mainViewport);
        return;
    } else if (count == 2) { //Split Screen
        I32 halfHeight = height / 2;
        targetViewports.emplace_back(xOffset, halfHeight + yOffset, width, halfHeight);
        targetViewports.emplace_back(xOffset, 0 + yOffset,          width, halfHeight);
        return;
    }

    // Basic idea (X - viewport):
    // Odd # of players | Even # of players
    // X X              |      X X
    //  X               |      X X
    //                  |
    // X X X            |     X X X 
    //  X X             |     X X X
    // etc
    // Always try to match last row with previous one
    // If they match, move the first viewport from the last row
    // to the previous row and add a new entry to the end of the
    // current row

    typedef vectorImpl<vec4<I32>> ViewportRow;
    typedef vectorImpl<ViewportRow> ViewportRows;
    ViewportRows rows;

    // Allocates storage for a N x N matrix of viewports that will hold numViewports
    // Returns N;
    auto resizeViewportContainer = [&rows](U32 numViewports) {
        //Try to fit all viewports into an appropriately sized matrix.
        //If the number of resulting rows is too large, drop empty rows.
        //If the last row has an odd number of elements, center them later.
        U8 matrixSize = to_ubyte(minSquareMatrixSize(numViewports));
        rows.resize(matrixSize);
        std::for_each(std::begin(rows), std::end(rows), [matrixSize](ViewportRow& row) { row.resize(matrixSize); });

        return matrixSize;
    };

    // Remove extra rows and columns, if any
    U8 columnCount = resizeViewportContainer(count);
    U8 extraColumns = (columnCount * columnCount) - count;
    U8 extraRows = extraColumns / columnCount;
    for (U8 i = 0; i < extraRows; ++i) {
        rows.pop_back();
    }
    U8 columnsToRemove = extraColumns - (extraRows * columnCount);
    for (U8 i = 0; i < columnsToRemove; ++i) {
        rows.back().pop_back();
    }

    U8 rowCount = to_ubyte(rows.size());

    // Calculate and set viewport dimensions
    // The number of columns is valid for the width;
    I32 playerWidth = width / columnCount;
    // The number of rows is valid for the height;
    I32 playerHeight = height / to_int(rowCount);

    for (U8 i = 0; i < rowCount; ++i) {
        ViewportRow& row = rows[i];
        I32 playerYOffset = playerHeight * (rowCount - i - 1);
        for (U8 j = 0; j < to_ubyte(row.size()); ++j) {
            I32 playerXOffset = playerWidth * j;
            row[j].set(playerXOffset, playerYOffset, playerWidth, playerHeight);
        }
    }

    //Slide the last row to center it
    if (extraColumns > 0) {
        ViewportRow& lastRow = rows.back();
        I32 screenMidPoint = width / 2;
        I32 rowMidPoint = to_int((lastRow.size() * playerWidth) / 2);
        I32 slideFactor = screenMidPoint - rowMidPoint;
        for (vec4<I32>& viewport : lastRow) {
            viewport.x += slideFactor;
        }
    }

    // Update the system viewports
    for (const ViewportRow& row : rows) {
        for (const vec4<I32>& viewport : row) {
            targetViewports.push_back(viewport);
        }
    }
}

Time::ProfileTimer& getTimer(Time::ProfileTimer& parentTimer, vectorImpl<Time::ProfileTimer*>& timers, U8 index, const char* name) {
    while (timers.size() < index + 1) {
        timers.push_back(&Time::ADD_TIMER(Util::StringFormat("%s %d", name, timers.size()).c_str()));
        parentTimer.addChildTimer(*timers.back());
    }

    return *timers[index];
}

bool Kernel::presentToScreen(FrameEvent& evt, const U64 deltaTime) {
    static vectorImpl<vec4<I32>> targetViewports;

    Time::ScopedTimer time(_flushToScreenTimer);

    FrameListenerManager& frameMgr = FrameListenerManager::instance();

    {
        Time::ScopedTimer time1(_preRenderTimer);
        frameMgr.createEvent(_timingData._currentTime, FrameEventType::FRAME_PRERENDER_START, evt);

        if (!frameMgr.frameEvent(evt)) {
            return false;
        }

        // perform time-sensitive shader tasks
        if (!ShaderProgram::updateAll(deltaTime)) {
            return false;
        }

        frameMgr.createEvent(_timingData._currentTime, FrameEventType::FRAME_PRERENDER_END, evt);
        if (!frameMgr.frameEvent(evt)) {
            return false;
        }
    }

    const SceneManager::PlayerList& activePlayers = _sceneManager->getPlayers();
    const vec4<I32>& mainViewport = _platformContext->gfx().getCurrentViewport();

    U8 playerCount = to_ubyte(activePlayers.size());
    computeViewports(mainViewport, targetViewports, playerCount);

    for (U8 i = 0; i < playerCount; ++i) {
        Attorney::SceneManagerKernel::currentPlayerPass(*_sceneManager, i);
        {
            Time::ScopedTimer time2(getTimer(_flushToScreenTimer, _renderTimer, i, "Render Timer"));
            _renderPassManager->render(_sceneManager->getActiveScene().renderState());
        }
        {
            Time::ScopedTimer time3(getTimer(_flushToScreenTimer, _postFxRenderTimer, i, "PostFX Timer"));
            PostFX::instance().apply(_platformContext->gfx());
        }
        {
            Time::ScopedTimer time4(getTimer(_flushToScreenTimer, _blitToDisplayTimer, i, "Blit to screen Timer"));
            Attorney::GFXDeviceKernel::flushDisplay(_platformContext->gfx(), targetViewports[i]);
        }
    }
    Camera::activeCamera(nullptr);

    for (U8 i = playerCount; i < to_ubyte(_renderTimer.size()); ++i) {
        Time::ProfileTimer::removeTimer(*_renderTimer[i]);
        Time::ProfileTimer::removeTimer(*_postFxRenderTimer[i]);
        Time::ProfileTimer::removeTimer(*_blitToDisplayTimer[i]);
        _renderTimer.erase(std::begin(_renderTimer) + i);
        _postFxRenderTimer.erase(std::begin(_postFxRenderTimer) + i);
        _blitToDisplayTimer.erase(std::begin(_blitToDisplayTimer) + i);
    }

    {
        Time::ScopedTimer time5(_postRenderTimer);
        frameMgr.createEvent(_timingData._currentTime, FrameEventType::FRAME_POSTRENDER_START, evt);

        if (!frameMgr.frameEvent(evt)) {
            return false;
        }

        frameMgr.createEvent(_timingData._currentTime, FrameEventType::FRAME_POSTRENDER_END, evt);

        if (!frameMgr.frameEvent(evt)) {
            return false;
        }
    }

    return true;
}

// The first loops compiles all the visible data, so do not render the first couple of frames
void Kernel::warmup() {
    static const U8 warmupLoopCount = 3;
    U8 loopCount = 0;

    Console::printfn(Locale::get(_ID("START_RENDER_LOOP")));
    _timingData._nextGameTick = Time::ElapsedMicroseconds(true);
    _timingData._keepAlive = true;

    ParamHandler& par = ParamHandler::instance();
    bool shadowMappingEnabled = par.getParam<bool>(_ID("rendering.enableShadows"));
    par.setParam(_ID("freezeLoopTime"), true);
    par.setParam(_ID("rendering.enableShadows"), false);

    onLoop(); loopCount++;
    if (shadowMappingEnabled) {
        par.setParam(_ID("rendering.enableShadows"), true);
        onLoop(); loopCount++;
    }

    for (U8 i = 0; i < std::max(warmupLoopCount - loopCount, 0); ++i) {
        onLoop();
    }

    par.setParam(_ID("freezeLoopTime"), false);
    Attorney::SceneManagerKernel::initPostLoadState(*_sceneManager);

    _timingData._currentTime = _timingData._nextGameTick = Time::ElapsedMicroseconds(true);
}

ErrorCode Kernel::initialize(const stringImpl& entryPoint) {
    ParamHandler& par = ParamHandler::instance();

    SysInfo& systemInfo = Application::instance().sysInfo();
    if (!CheckMemory(Config::REQUIRED_RAM_SIZE, systemInfo)) {
        return ErrorCode::NOT_ENOUGH_RAM;
    }

    // We have an A.I. thread, a networking thread, a PhysX thread, the main
    // update/rendering thread so how many threads do we allocate for tasks?
    // That's up to the programmer to decide for each app.
    if (!_taskPool.init(HARDWARE_THREAD_COUNT(), "DIVIDE_WORKER_THREAD_")) {
        return ErrorCode::CPU_NOT_SUPPORTED;
    }

    _platformContext->pfx().setAPI(PXDevice::PhysicsAPI::PhysX);
    _platformContext->sfx().setAPI(SFXDevice::AudioAPI::SDL);
    // Using OpenGL for rendering as default
    if (Config::USE_OPENGL_RENDERING) {
        _platformContext->gfx().setAPI(Config::USE_OPENGL_ES ? RenderAPI::OpenGLES
                                                             : RenderAPI::OpenGL);
    }
    // Load info from XML files
    stringImpl startupScene(XML::loadScripts(*_platformContext, entryPoint));
    // Create mem log file
    const stringImpl& mem = par.getParam<stringImpl>(_ID("memFile"));
    _APP.setMemoryLogFile(mem.compare("none") == 0 ? "mem.log" : mem);
    Console::printfn(Locale::get(_ID("START_RENDER_INTERFACE")));

    // Fulscreen is automatically calculated
    ResolutionByType initRes;
    initRes[to_const_uint(WindowType::WINDOW)].set(par.getParam<I32>(_ID("runtime.windowWidth"), 1024),
                                                   par.getParam<I32>(_ID("runtime.windowHeight"), 768));
    initRes[to_const_uint(WindowType::SPLASH)].set(par.getParam<I32>(_ID("runtime.splashWidth"), 400),
                                                   par.getParam<I32>(_ID("runtime.splashHeight"), 300));

    I32 targetDisplay = par.getParam<I32>(_ID("runtime.targetDisplay"), 0);
    bool startFullScreen = par.getParam<bool>(_ID("runtime.startFullScreen"), true);
    WindowManager& winManager = _APP.windowManager();

    ErrorCode initError = winManager.init(_platformContext->gfx(), _platformContext->gfx().getAPI(), initRes, startFullScreen, targetDisplay);
    if (initError != ErrorCode::NO_ERR) {
        return initError;
    }

    // Match initial rendering resolution to window/screen size
    const DisplayWindow& mainWindow  = winManager.getActiveWindow();
    vec2<U16> renderResolution(startFullScreen ? mainWindow.getDimensions(WindowType::FULLSCREEN)
                                               : mainWindow.getDimensions(WindowType::WINDOW));
    initError = _platformContext->gfx().initRenderingAPI(_argc, _argv, renderResolution);

    Camera::addUpdateListener([this](const Camera& cam) { Attorney::GFXDeviceKernel::onCameraUpdate(_platformContext->gfx(), cam); });
    Camera::addChangeListener([this](const Camera& cam) { Attorney::GFXDeviceKernel::onCameraChange(_platformContext->gfx(), cam); });
    // If we could not initialize the graphics device, exit
    if (initError != ErrorCode::NO_ERR) {
        return initError;
    }
    initError = OpenCLInterface::instance().init();
    if (initError != ErrorCode::NO_ERR) {
        return initError;
    }

    // Add our needed app-wide render passes. RenderPassManager is responsible for deleting these!
    _renderPassManager->init();
    _renderPassManager->addRenderPass("shadowPass",     0, RenderStage::SHADOW);
    _renderPassManager->addRenderPass("reflectionPass", 1, RenderStage::REFLECTION);
    _renderPassManager->addRenderPass("refractionPass", 2, RenderStage::REFRACTION);
    _renderPassManager->addRenderPass("displayStage",   3, RenderStage::DISPLAY);

    Console::printfn(Locale::get(_ID("SCENE_ADD_DEFAULT_CAMERA")));

    SceneManager::onStartup();
    // We start of with a forward plus renderer
    _platformContext->gfx().setRenderer(RendererType::RENDERER_TILED_FORWARD_SHADING);

    DisplayWindow& window = winManager.getActiveWindow();
    window.type(WindowType::SPLASH);
    winManager.handleWindowEvent(WindowEvent::APP_LOOP, -1, -1, -1);
    // Load and render the splash screen
    _platformContext->gfx().beginFrame();
    GUISplash(*_resCache, "divideLogo.jpg", initRes[to_const_uint(WindowType::SPLASH)]).render(_platformContext->gfx());
    _platformContext->gfx().endFrame(true);

    Console::printfn(Locale::get(_ID("START_SOUND_INTERFACE")));
    initError = _platformContext->sfx().initAudioAPI(*_platformContext);
    if (initError != ErrorCode::NO_ERR) {
        return initError;
    }

    Console::printfn(Locale::get(_ID("START_PHYSICS_INTERFACE")));
    initError = _platformContext->pfx().initPhysicsAPI(Config::TARGET_FRAME_RATE);
    if (initError != ErrorCode::NO_ERR) {
        return initError;
    }

    // Bind the kernel with the input interface
    initError = _platformContext->input().init(*this, renderResolution);
    if (initError != ErrorCode::NO_ERR) {
        return initError;
    }

    // Initialize GUI with our current resolution
    _platformContext->gui().init(*_platformContext, *_resCache, renderResolution);
    _platformContext->gui().addText(_ID("ProfileData"),                            // Unique ID
                                    vec2<I32>(renderResolution.width * 0.75, 100), // Position
                                    Font::DROID_SERIF_BOLD,                        // Font
                                    vec4<U8>(255,  50, 0, 255),                    // Colour
                                    "PROFILE DATA",                                // Text
                                    12);                                           // Font size

    Console::bindConsoleOutput([this](const char* output, bool error) {
                                   _platformContext->gui().getConsole()->printText(output, error);
                               });
    
    ShadowMap::initShadowMaps(_platformContext->gfx());
    _sceneManager->init(*_platformContext, *_resCache);
    Camera::addUpdateListener([this](const Camera& cam) {
                                   Attorney::SceneManagerKernel::onCameraUpdate(*_sceneManager, cam);
                              });
    Camera::addChangeListener([this](const Camera& cam) {
                                   Attorney::SceneManagerKernel::onCamerachange(*_sceneManager, cam);
                              });
    if (!_sceneManager->switchScene(startupScene, true, false)) {
        Console::errorfn(Locale::get(_ID("ERROR_SCENE_LOAD")), startupScene.c_str());
        return ErrorCode::MISSING_SCENE_DATA;
    }

    if (!_sceneManager->checkLoadFlag()) {
        Console::errorfn(Locale::get(_ID("ERROR_SCENE_LOAD_NOT_CALLED")),
                         startupScene.c_str());
        return ErrorCode::MISSING_SCENE_LOAD_CALL;
    }

    Console::printfn(Locale::get(_ID("INITIAL_DATA_LOADED")));

    return initError;
}

void Kernel::shutdown() {
    Console::printfn(Locale::get(_ID("STOP_KERNEL")));
    SceneManager::onShutdown();
    _sceneManager.reset();
    WaitForAllTasks(_taskPool, true, true, true);
    // release the scene
    Console::bindConsoleOutput(std::function<void(const char*, bool)>());
    _platformContext->gui().destroy();  /// Deactivate GUI 
    Camera::destroyPool();
    ShadowMap::clearShadowMaps(_platformContext->gfx());
    Console::printfn(Locale::get(_ID("STOP_ENGINE_OK")));
    Console::printfn(Locale::get(_ID("STOP_PHYSICS_INTERFACE")));
    _platformContext->pfx().closePhysicsAPI();
    Console::printfn(Locale::get(_ID("STOP_HARDWARE")));
    OpenCLInterface::instance().deinit();
    _renderPassManager.reset();
    _platformContext->sfx().closeAudioAPI();
    _platformContext->gfx().closeRenderingAPI();
    _platformContext->input().terminate();
    _resCache->clear();
    FrameListenerManager::destroyInstance();
    Camera::destroyPool();
}

void Kernel::onChangeWindowSize(U16 w, U16 h) {
    Attorney::GFXDeviceKernel::onChangeWindowSize(_platformContext->gfx(), w, h);

    if (_platformContext->input().isInit()) {
        _platformContext->input().onChangeWindowSize(w, h);
    }

    _platformContext->gui().onChangeResolution(w, h);
}

void Kernel::onChangeRenderResolution(U16 w, U16 h) const {
    Attorney::GFXDeviceKernel::onChangeRenderResolution(_platformContext->gfx(), w, h);
    _platformContext->gui().onChangeResolution(w, h);

    _sceneManager->onChangeResolution(w, h);
}

///--------------------------Input Management-------------------------------------///
bool Kernel::setCursorPosition(I32 x, I32 y) const {
    _platformContext->gui().setCursorPosition(x, y);
    return true;
}

bool Kernel::onKeyDown(const Input::KeyEvent& key) {
    if (_platformContext->gui().onKeyDown(key)) {
        return _sceneManager->onKeyDown(key);
    }
    return true;  //< InputInterface needs to know when this is completed
}

bool Kernel::onKeyUp(const Input::KeyEvent& key) {
    if (_platformContext->gui().onKeyUp(key)) {
        return _sceneManager->onKeyUp(key);
    }
    // InputInterface needs to know when this is completed
    return false;
}

bool Kernel::mouseMoved(const Input::MouseEvent& arg) {
    if (_platformContext->gui().mouseMoved(arg)) {
        return _sceneManager->mouseMoved(arg);
    }
    // InputInterface needs to know when this is completed
    return false;
}

bool Kernel::mouseButtonPressed(const Input::MouseEvent& arg,
                                Input::MouseButton button) {
    if (_platformContext->gui().mouseButtonPressed(arg, button)) {
        return _sceneManager->mouseButtonPressed(arg, button);
    }
    // InputInterface needs to know when this is completed
    return false;
}

bool Kernel::mouseButtonReleased(const Input::MouseEvent& arg,
                                 Input::MouseButton button) {
    if (_platformContext->gui().mouseButtonReleased(arg, button)) {
        return _sceneManager->mouseButtonReleased(arg, button);
    }
    // InputInterface needs to know when this is completed
    return false;
}

bool Kernel::joystickAxisMoved(const Input::JoystickEvent& arg, I8 axis) {
    if (_platformContext->gui().joystickAxisMoved(arg, axis)) {
        return _sceneManager->joystickAxisMoved(arg, axis);
    }
    // InputInterface needs to know when this is completed
    return false;
}

bool Kernel::joystickPovMoved(const Input::JoystickEvent& arg, I8 pov) {
    if (_platformContext->gui().joystickPovMoved(arg, pov)) {
        return _sceneManager->joystickPovMoved(arg, pov);
    }
    // InputInterface needs to know when this is completed
    return false;
}

bool Kernel::joystickButtonPressed(const Input::JoystickEvent& arg,
                                   Input::JoystickButton button) {
    if (_platformContext->gui().joystickButtonPressed(arg, button)) {
        return _sceneManager->joystickButtonPressed(arg, button);
    }
    // InputInterface needs to know when this is completed
    return false;
}

bool Kernel::joystickButtonReleased(const Input::JoystickEvent& arg,
                                    Input::JoystickButton button) {
    if (_platformContext->gui().joystickButtonReleased(arg, button)) {
        return _sceneManager->joystickButtonReleased(arg, button);
    }
    // InputInterface needs to know when this is completed
    return false;
}

bool Kernel::joystickSliderMoved(const Input::JoystickEvent& arg, I8 index) {
    if (_platformContext->gui().joystickSliderMoved(arg, index)) {
        return _sceneManager->joystickSliderMoved(arg, index);
    }
    // InputInterface needs to know when this is completed
    return false;
}

bool Kernel::joystickVector3DMoved(const Input::JoystickEvent& arg, I8 index) {
    if (_platformContext->gui().joystickVector3DMoved(arg, index)) {
        return _sceneManager->joystickVector3DMoved(arg, index);
    }
    // InputInterface needs to know when this is completed
    return false;
}

void Attorney::KernelApplication::syncThreadToGPU(Kernel& kernel, const std::thread::id& threadID, bool beginSync) {
    Attorney::GFXDeviceKernel::syncThreadToGPU(kernel._platformContext->gfx(), threadID, beginSync);
}

};

Commits for Divide-Framework/trunk/Source Code/Core/Kernel.cpp

Diff revisions: vs.
Revision Author Commited Message
827 Diff Diff IonutCava picture IonutCava Sun 22 Jan, 2017 21:59:36 +0000

[IonutCava]
- ShaderBuffers now decide heuristically if they get persistently mapped or not (depends on size. Current limit is 512Kb for subData calls.
- Separate visible node command generation into 2 steps: onRender and getDrawPackage. onRender allows the creation of parallel tasks that should finish by the time the second call, getDrawPackage reaches the same node
- Update ParticleEmitter to take into account multiple players and increase parallelism at the cost of memory consumption and complexity.
- Add a default bounding box for Players (add extents to SceneTransform nodes)
- All buffers (ShaderBuffer, d3dConstantBuffer, glUniformBuffer, glBufferImpl, glGenericBuffer, etc) use BufferParams for creation.
— Constructor and create calls have been merged together

825 Diff Diff IonutCava picture IonutCava Fri 20 Jan, 2017 14:35:31 +0000

[IonutCava]
- Small corrections and optimizations to the TaskPool
- Fix buffer update bug in LightPool

824 Diff Diff IonutCava picture IonutCava Thu 19 Jan, 2017 17:18:03 +0000

[IonutCava]
- Prev Frame attachment system removed from RenderTargets
— Concept too high level for RT. Moved prev depth buffer to GFX class
- Other small optimizations.

821 Diff Diff IonutCava picture IonutCava Tue 17 Jan, 2017 17:15:45 +0000

[IonutCava]
- Profile guided optimizations

817 Diff Diff IonutCava picture IonutCava Sun 15 Jan, 2017 21:29:59 +0000

[IonutCava]
- Add a new Unit component to SGNs that holds NPC/Player/etc. objects
- Add support for multiple keyboard+mouse combos and joysticks and add mapping between these and players

816 Diff Diff IonutCava picture IonutCava Fri 13 Jan, 2017 17:05:20 +0000

[IonutCava]
- Allow per player scene state and input source
— Add SceneStatePerPlayer class
— Add device index to InputParams objects.
— ToDo: map players to devide indices

815 Diff Diff IonutCava picture IonutCava Thu 12 Jan, 2017 23:33:01 +0000

[IonutCava]
- Fixed viewport alignment issue
- Added per-player RenderTargets (added index support to GFXRTPool)
- Initial implementation of per-player cameras
— Removed defaultCamera
— Scenes now use a baseCamera as a template for new player cameras

813 Diff Diff IonutCava picture IonutCava Thu 12 Jan, 2017 17:18:55 +0000

[IonutCava]
- Initial split screen support:
— Add support for multiple Player objects per scene
— Compute viewport alignment for every player
— Render scene once for every viewport
- ToDo:
— Bind each player to an input method
— Add per-player camera
— Per player render pass: set player camera as default camera

811 Diff Diff IonutCava picture IonutCava Wed 11 Jan, 2017 17:26:49 +0000

[IonutCava]
- Fix some threadpool cleanup bugs
- Fix terrain rendering (except underwater caustics)
- Fix terrain loading
- Fix terrain unloading

806 IonutCava picture IonutCava Sun 08 Jan, 2017 22:00:48 +0000

[IonutCava]
- Finish implementing per-fragment velocity computation using a compute shader
— Further tuning still needed
- Add VS2017 build targets