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
#include "Headers/Kernel.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/AIManager.h"
#include "Managers/Headers/LightManager.h"
#include "Managers/Headers/SceneManager.h"
#include "Core/Headers/ProfileTimer.h"
#include "Core/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 "Platform/Input/Headers/InputInterface.h"
#include "Managers/Headers/FrameListenerManager.h"
#include "Platform/Video/Headers/RenderStateBlock.h"
#include "Platform/Video/Shaders/Headers/ShaderManager.h"
#include "Rendering/Camera/Headers/FreeFlyCamera.h"

namespace Divide {

U64 Kernel::_previousTime = 0ULL;
U64 Kernel::_currentTime = 0ULL;
U64 Kernel::_currentTimeFrozen = 0ULL;
U64 Kernel::_currentTimeDelta = 0ULL;
D32 Kernel::_nextGameTick = 0.0;

bool Kernel::_keepAlive = true;
bool Kernel::_renderingPaused = false;
bool Kernel::_freezeLoopTime = false;
bool Kernel::_freezeGUITime = false;
Time::ProfileTimer* s_appLoopTimer = nullptr;

SharedLock Kernel::_threadedCallbackLock;
vectorImpl<U64> Kernel::_threadedCallbackBuffer;
hashMapImpl<U64, DELEGATE_CBK<> > Kernel::_threadedCallbackFunctions;

Util::GraphPlot2D Kernel::_appTimeGraph;

Kernel::Kernel(I32 argc, char** argv, Application& parentApp)
    : _argc(argc),
      _argv(argv),
      _APP(parentApp),
      _GFX(GFXDevice::getOrCreateInstance()),                // Video
      _SFX(SFXDevice::getOrCreateInstance()),                // Audio
      _PFX(PXDevice::getOrCreateInstance()),                 // Physics
      _input(Input::InputInterface::getOrCreateInstance()),  // Input
      _GUI(GUI::getOrCreateInstance()),  // Graphical User Interface
      _sceneMgr(SceneManager::getOrCreateInstance())  // Scene Manager

{
    ResourceCache::createInstance();
    FrameListenerManager::createInstance();
    // General light management and rendering (individual lights are handled by
    // each scene)
    // Unloading the lights is a scene level responsibility
    LightManager::createInstance();
    _cameraMgr.reset(new CameraManager(this));  // Camera manager
    assert(_cameraMgr != nullptr);
    // force all lights to update on camera change (to keep them still actually)
    _cameraMgr->addCameraUpdateListener(DELEGATE_BIND(
        &LightManager::onCameraChange, &LightManager::getInstance()));
    _cameraMgr->addCameraUpdateListener(
        DELEGATE_BIND(&SceneManagerKernelAttorney::onCameraChange));
    // 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
    // we add the A.I. thread in the same pool as it's a task. ReCast should
    // also use this ...
    _mainTaskPool = MemoryManager_NEW boost::threadpool::pool(
        Config::THREAD_LIMIT + 1 /*A.I.*/);

    ParamHandler::getInstance().setParam<stringImpl>("language",
                                                     Locale::currentLanguage());

    s_appLoopTimer = Time::ADD_TIMER("MainLoopTimer");
}

Kernel::~Kernel() {
    MemoryManager::DELETE(_mainTaskPool);
}

void Kernel::threadPoolCompleted(U64 onExitTaskID) {
    WriteLock w_lock(_threadedCallbackLock);
    _threadedCallbackBuffer.push_back(onExitTaskID);
}

Task* Kernel::AddTask(U64 tickInterval, I32 numberOfTicks,
                      const DELEGATE_CBK<>& threadedFunction,
                      const DELEGATE_CBK<>& onCompletionFunction) {
    Task* taskPtr = MemoryManager_NEW Task(getThreadPool(), tickInterval,
                                           numberOfTicks, threadedFunction);
    taskPtr->connect(DELEGATE_BIND(&Kernel::threadPoolCompleted, this,
                                   std::placeholders::_1));
    if (onCompletionFunction) {
        emplace(_threadedCallbackFunctions,
                static_cast<U64>(taskPtr->getGUID()), onCompletionFunction);
    }

    return taskPtr;
}

void Kernel::idle() {
    GFX_DEVICE.idle();
    PHYSICS_DEVICE.idle();
    SceneManager::getInstance().idle();
    LightManager::getInstance().idle();
    FrameListenerManager::getInstance().idle();

    ParamHandler& par = ParamHandler::getInstance();

    _freezeGUITime = par.getParam("freezeGUITime", false);
    bool freezeLoopTime = par.getParam("freezeLoopTime", false);
    if (freezeLoopTime != _freezeLoopTime) {
        _freezeLoopTime = freezeLoopTime;
        _currentTimeFrozen = _currentTime;
        Application::getInstance().mainLoopPaused(_freezeLoopTime);
    }

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

    UpgradableReadLock ur_lock(_threadedCallbackLock);
    if (!_threadedCallbackBuffer.empty()) {
        UpgradeToWriteLock uw_lock(ur_lock);
        const DELEGATE_CBK<>& cbk =
            _threadedCallbackFunctions[_threadedCallbackBuffer.back()];
        if (cbk) {
            cbk();
        }
        _threadedCallbackBuffer.pop_back();
    }
}

void Kernel::mainLoopApp() {
    if (!_keepAlive) {
        // exiting the rendering loop will return us to the last control point
        // (i.e. Kernel::runLogicLoop)
        Application::getInstance().mainLoopActive(false);
        return;
    }

    // Update internal timer
    Time::ApplicationTimer::getInstance().update(GFX_DEVICE.getFrameCount());

    Time::START_TIMER(s_appLoopTimer);

    // Update time at every render loop
    _previousTime = _currentTime;
    _currentTime = Time::ElapsedMicroseconds();
    _currentTimeDelta = _currentTime - _previousTime;

    FrameEvent evt;
    FrameListenerManager& frameMgr = FrameListenerManager::getInstance();
    Application& APP = Application::getInstance();

    Kernel::idle();

    // Restore GPU to default state: clear buffers and set default render state
    GFX_DEVICE.beginFrame();
    {
        // Launch the FRAME_STARTED event
        frameMgr.createEvent(_currentTime, FRAME_EVENT_STARTED, evt);
        _keepAlive = frameMgr.frameEvent(evt);

        // Process the current frame
        _keepAlive = APP.getKernel().mainLoopScene(evt) && _keepAlive;

        // Launch the FRAME_PROCESS event (a.k.a. the frame processing has ended
        // event)
        frameMgr.createEvent(_currentTime, FRAME_EVENT_PROCESS, evt);
        _keepAlive = frameMgr.frameEvent(evt) && _keepAlive;
    }
    GFX_DEVICE.endFrame();

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

    _keepAlive = !APP.ShutdownRequested() && _keepAlive;
    ErrorCode err = APP.errorCode();
    if (err != NO_ERR) {
        Console::errorfn("Error detected: [ %s ]", getErrorCodeName(err));
        _keepAlive = false;
    }
    Time::STOP_TIMER(s_appLoopTimer);

#if defined(_DEBUG) || defined(_PROFILE)
    if (GFX_DEVICE.getFrameCount() % Config::TARGET_FRAME_RATE == 0) {
        Util::plotFloatEvents("kernel.mainLoopApp", Util::getFloatEvents(), _appTimeGraph);
    }
    GFX_DEVICE.renderInViewport(
        vec4<I32>(0, 0, 256, 256),
        DELEGATE_BIND((void (GFXDevice::*)(Util::GraphPlot2D& plot2D)) &
                          GFXDevice::plot2DGraph,
                      &GFX_DEVICE, _appTimeGraph));
    if (GFX_DEVICE.getFrameCount() % (Config::TARGET_FRAME_RATE * 10) == 0) {
        Console::printfn(
            "GPU: [ %5.5f ] [DrawCalls: %d]",
            Time::MicrosecondsToSeconds<F32>(GFX_DEVICE.getFrameDurationGPU()),
            GFX_DEVICE.getDrawCallCount());

        Util::flushFloatEvents();
    }
    Util::recordFloatEvent("kernel.mainLoopApp", s_appLoopTimer->get(), _currentTime);
#endif
}

bool Kernel::mainLoopScene(FrameEvent& evt) {
    if (_renderingPaused) {
        idle();
        return true;
    }

    // Process physics
    _PFX.process(_freezeLoopTime ? 0ULL : _currentTimeDelta);

    U8 loops = 0;

    U64 deltaTime =
        Config::USE_FIXED_TIMESTEP ? Config::SKIP_TICKS : _currentTimeDelta;
    while (_currentTime > _nextGameTick && loops < Config::MAX_FRAMESKIP) {
        if (!_freezeGUITime) {
            _sceneMgr.processGUI(deltaTime);
        }

        if (!_freezeLoopTime) {
            // Update scene based on input
            _sceneMgr.processInput(_currentTimeDelta);
            // process all scene events
            _sceneMgr.processTasks(deltaTime);
        }

        _nextGameTick += deltaTime;
        loops++;

        if (Config::USE_FIXED_TIMESTEP) {
            if (loops == Config::MAX_FRAMESKIP &&
                _currentTime > _nextGameTick) {
                _nextGameTick = _currentTime;
            }
        } else {
            _nextGameTick = _currentTime;
        }
    }  // while

    if (Config::USE_FIXED_TIMESTEP) {
        _GFX.setInterpolation(std::min(
            static_cast<D32>((_currentTime + deltaTime - _nextGameTick)) /
                static_cast<D32>(deltaTime),
            1.0));
    }

    // Get input events
    _APP.hasFocus() ? _input.update(deltaTime) : _sceneMgr.onLostFocus();

    // Call this to avoid interpolating 60 bone matrices per entity every render
    // call
    // Update the scene state based on current time (e.g. animation matrices)
    _sceneMgr.updateSceneState(_freezeLoopTime ? 0ULL : _currentTimeDelta);

    // Update physics - uses own timestep implementation
    _PFX.update(_freezeLoopTime ? 0ULL : _currentTimeDelta);

    // Update the graphical user interface
    GUI::getInstance().update(_freezeGUITime ? 0ULL : _currentTimeDelta);

    return presentToScreen(evt);
}

void Kernel::renderScene() {
    RenderStage stage = (_GFX.getRenderer().getType() != RendererType::RENDERER_FORWARD_PLUS)
                            ? RenderStage::DEFERRED_STAGE
                            : RenderStage::FINAL_STAGE;
    bool postProcessing =
        (stage != RenderStage::DEFERRED_STAGE && _GFX.postProcessingEnabled());

    if (_GFX.anaglyphEnabled() && postProcessing) {
        renderSceneAnaglyph();
        return;
    }

    Framebuffer::FramebufferTarget depthPassPolicy, colorPassPolicy;
    depthPassPolicy._depthOnly = true;
    colorPassPolicy._colorOnly = true;

    /// Lock the render pass manager because the Z_PRE_PASS and the FINAL_STAGE
    /// pass must render
    /// the exact same geometry
    RenderPassManager::getInstance().lock();
    // Z-prePass
    _GFX.getRenderTarget(GFXDevice::RENDER_TARGET_DEPTH)
        ->Begin(Framebuffer::defaultPolicy());
    _sceneMgr.render(RenderStage::Z_PRE_PASS_STAGE, *this);
    _GFX.getRenderTarget(GFXDevice::RENDER_TARGET_DEPTH)->End();

    _GFX.ConstructHIZ();

    if (postProcessing) {
        _GFX.getRenderTarget(GFXDevice::RENDER_TARGET_SCREEN)
            ->Begin(Framebuffer::defaultPolicy());
    }

    _sceneMgr.render(stage, *this);

    if (postProcessing) {
        _GFX.getRenderTarget(GFXDevice::RENDER_TARGET_SCREEN)->End();
        PostFX::getInstance().displayScene();
    }

    RenderPassManager::getInstance().unlock();
}

void Kernel::renderSceneAnaglyph() {
    RenderStage stage = (_GFX.getRenderer().getType() != RendererType::RENDERER_FORWARD_PLUS)
                            ? RenderStage::DEFERRED_STAGE
                            : RenderStage::FINAL_STAGE;

    Framebuffer::FramebufferTarget depthPassPolicy, colorPassPolicy;
    depthPassPolicy._depthOnly = true;
    colorPassPolicy._colorOnly = true;

    Camera* currentCamera = _cameraMgr->getActiveCamera();

    // Render to right eye
    currentCamera->setAnaglyph(true);
    currentCamera->renderLookAt();
    RenderPassManager::getInstance().lock();
    // Z-prePass
    _GFX.getRenderTarget(GFXDevice::RENDER_TARGET_DEPTH)
        ->Begin(Framebuffer::defaultPolicy());
    SceneManager::getInstance().render(RenderStage::Z_PRE_PASS_STAGE, *this);
    _GFX.getRenderTarget(GFXDevice::RENDER_TARGET_DEPTH)->End();
    // first screen buffer
    _GFX.getRenderTarget(GFXDevice::RENDER_TARGET_SCREEN)
        ->Begin(Framebuffer::defaultPolicy());
    SceneManager::getInstance().render(stage, *this);
    _GFX.getRenderTarget(GFXDevice::RENDER_TARGET_SCREEN)->End();

    RenderPassManager::getInstance().unlock();

    // Render to left eye
    currentCamera->setAnaglyph(false);
    currentCamera->renderLookAt();
    RenderPassManager::getInstance().lock();
    // Z-prePass
    _GFX.getRenderTarget(GFXDevice::RENDER_TARGET_DEPTH)
        ->Begin(Framebuffer::defaultPolicy());
    SceneManager::getInstance().render(RenderStage::Z_PRE_PASS_STAGE, *this);
    _GFX.getRenderTarget(GFXDevice::RENDER_TARGET_DEPTH)->End();
    // second screen buffer
    _GFX.getRenderTarget(GFXDevice::RENDER_TARGET_ANAGLYPH)
        ->Begin(Framebuffer::defaultPolicy());
    SceneManager::getInstance().render(stage, *this);
    _GFX.getRenderTarget(GFXDevice::RENDER_TARGET_ANAGLYPH)->End();

    RenderPassManager::getInstance().unlock();

    PostFX::getInstance().displayScene();
}

bool Kernel::presentToScreen(FrameEvent& evt) {
    FrameListenerManager& frameMgr = FrameListenerManager::getInstance();

    frameMgr.createEvent(_currentTime, FRAME_PRERENDER_START, evt);
    if (!frameMgr.frameEvent(evt)) {
        return false;
    }

    // Prepare scene for rendering
    _sceneMgr.preRender();

    // perform time-sensitive shader tasks
    ShaderManager::getInstance().update(_currentTimeDelta);

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

    renderScene();

    frameMgr.createEvent(_currentTime, FRAME_POSTRENDER_START, evt);
    if (!frameMgr.frameEvent(evt)) {
        return false;
    }

    _sceneMgr.postRender();

    frameMgr.createEvent(_currentTime, FRAME_POSTRENDER_END, evt);
    if (!frameMgr.frameEvent(evt)) {
        return false;
    }

    return true;
}

void Kernel::firstLoop() {
    ParamHandler& par = ParamHandler::getInstance();
    bool shadowMappingEnabled = par.getParam<bool>("rendering.enableShadows");
    // Skip two frames, one without and one with shadows, so all resources can
    // be built while
    // the splash screen is displayed
    par.setParam("freezeGUITime", true);
    par.setParam("freezeLoopTime", true);
    par.setParam("rendering.enableShadows", false);
    mainLoopApp();
    if (shadowMappingEnabled) {
        par.setParam("rendering.enableShadows", true);
        mainLoopApp();
    }
    GFX_DEVICE.setWindowPos(10, 60);
    par.setParam("freezeGUITime", false);
    par.setParam("freezeLoopTime", false);
    const vec2<U16> prevRes =
        Application::getInstance().getPreviousResolution();
    GFX_DEVICE.changeResolution(prevRes.width, prevRes.height);
#if defined(_DEBUG) || defined(_PROFILE)
    Time::ApplicationTimer::getInstance().benchmark(true);
#endif
    SceneManagerKernelAttorney::initPostLoadState();

    _currentTime = _nextGameTick = Time::ElapsedMicroseconds();
}

void Kernel::submitRenderCall(const RenderStage& stage,
                              const SceneRenderState& sceneRenderState,
                              const DELEGATE_CBK<>& sceneRenderCallback) const {
    _GFX.setRenderStage(stage);
    _GFX.getRenderer().render(sceneRenderCallback, sceneRenderState);
}

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

    Console::bindConsoleOutput(
        DELEGATE_BIND(&GUIConsole::printText, GUI::getInstance().getConsole(),
                      std::placeholders::_1, std::placeholders::_2));
    _PFX.setAPI(PXDevice::PhysX);
    _SFX.setAPI(SFXDevice::SDL);
    // Using OpenGL for rendering as default
    _GFX.setAPI(GFXDevice::OpenGL);
    _GFX.setStateChangeExclusionMask(
        enum_to_uint(SceneNodeType::TYPE_LIGHT) | 
        enum_to_uint(SceneNodeType::TYPE_TRIGGER) | 
        enum_to_uint(SceneNodeType::TYPE_PARTICLE_EMITTER) | 
        enum_to_uint(SceneNodeType::TYPE_SKY) |
        enum_to_uint(SceneNodeType::TYPE_VEGETATION_GRASS) | 
        enum_to_uint(SceneNodeType::TYPE_VEGETATION_TREES));
    // Target FPS is usually 60. So all movement is capped around that value
    Time::ApplicationTimer::getInstance().init(Config::TARGET_FRAME_RATE);
    // Load info from XML files
    stringImpl startupScene(
        stringAlg::toBase(XML::loadScripts(stringAlg::fromBase(entryPoint))));
    // Create mem log file
    const stringImpl& mem = par.getParam<stringImpl>("memFile");
    _APP.setMemoryLogFile(mem.compare("none") == 0 ? "mem.log" : mem);
    Console::printfn(Locale::get("START_RENDER_INTERFACE"));
    vec2<U16> resolution = _APP.getResolution();
    F32 aspectRatio = (F32)resolution.width / (F32)resolution.height;
    ErrorCode initError =
        _GFX.initRenderingAPI(vec2<U16>(400, 300), _argc, _argv);
    // If we could not initialize the graphics device, exit
    if (initError != NO_ERR) {
        return initError;
    }

    Console::printfn(Locale::get("SCENE_ADD_DEFAULT_CAMERA"));
    Camera* camera = MemoryManager_NEW FreeFlyCamera();
    camera->setProjection(aspectRatio,
                          par.getParam<F32>("rendering.verticalFOV"),
                          vec2<F32>(par.getParam<F32>("rendering.zNear"),
                                    par.getParam<F32>("rendering.zFar")));
    camera->setFixedYawAxis(true);
    // As soon as a camera is added to the camera manager, the manager is
    // responsible for cleaning it up
    _cameraMgr->addNewCamera("defaultCamera", camera);
    _cameraMgr->pushActiveCamera(camera);

    // Load and render the splash screen
    _GFX.setRenderStage(RenderStage::FINAL_STAGE);
    _GFX.beginFrame();
    GUISplash("divideLogo.jpg", vec2<U16>(400, 300)).render();
    _GFX.endFrame();

    LightManager::getInstance().init();

    Console::printfn(Locale::get("START_SOUND_INTERFACE"));
    if ((initError = _SFX.initAudioAPI()) != NO_ERR) {
        return initError;
    }

    Console::printfn(Locale::get("START_PHYSICS_INTERFACE"));
    if ((initError = _PFX.initPhysicsAPI(Config::TARGET_FRAME_RATE)) !=
        NO_ERR) {
        return initError;
    }

    // Bind the kernel with the input interface
    Input::InputInterface::getInstance().init(
        *this, par.getParam<stringImpl>("appTitle"));

    // Initialize GUI with our current resolution
    _GUI.init(resolution);
    _sceneMgr.init(&_GUI);

    if (!_sceneMgr.load(startupScene, resolution)) {  //< Load the scene
        Console::errorfn(Locale::get("ERROR_SCENE_LOAD"), startupScene.c_str());
        return MISSING_SCENE_DATA;
    }

    if (!_sceneMgr.checkLoadFlag()) {
        Console::errorfn(Locale::get("ERROR_SCENE_LOAD_NOT_CALLED"),
                         startupScene.c_str());
        return MISSING_SCENE_LOAD_CALL;
    }

    camera->setMoveSpeedFactor(par.getParam<F32>("options.cameraSpeed.move"));
    camera->setTurnSpeedFactor(par.getParam<F32>("options.cameraSpeed.turn"));

    Console::printfn(Locale::get("INITIAL_DATA_LOADED"));
    Console::printfn(Locale::get("CREATE_AI_ENTITIES_START"));
    // Initialize and start the AI
    _sceneMgr.initializeAI(true);
    Console::printfn(Locale::get("CREATE_AI_ENTITIES_END"));

    return initError;
}

void Kernel::runLogicLoop() {
    Console::printfn(Locale::get("START_RENDER_LOOP"));
    Kernel::_nextGameTick = Time::ElapsedMicroseconds();
    // lock the scene
    GET_ACTIVE_SCENE()->state().toggleRunningState(true);
    // The first loops compiles all the visible data, so do not render the first
    // couple of frames
    firstLoop();

    _keepAlive = true;
    _APP.mainLoopActive(true);

    while (_APP.mainLoopActive()) {
        Kernel::mainLoopApp();
    }

    shutdown();
}

void Kernel::shutdown() {
    Console::printfn(Locale::get("STOP_KERNEL"));
    // release the scene
    GET_ACTIVE_SCENE()->state().toggleRunningState(false);
    Console::bindConsoleOutput(std::function<void(const char*, bool)>());
    GUI::destroyInstance();  /// Deactivate GUI
    _sceneMgr.unloadCurrentScene();
    _sceneMgr.deinitializeAI(true);
    SceneManager::destroyInstance();
    // Close CEGUI
    try {
        CEGUI::System::destroy();
    } catch (...) {
        Console::d_errorfn(Locale::get("ERROR_CEGUI_DESTROY"));
    }
    _cameraMgr.reset(nullptr);
    LightManager::destroyInstance();
    Console::printfn(Locale::get("STOP_ENGINE_OK"));
    Console::printfn(Locale::get("STOP_PHYSICS_INTERFACE"));
    _PFX.closePhysicsAPI();
    PXDevice::destroyInstance();
    Console::printfn(Locale::get("STOP_HARDWARE"));
    _SFX.closeAudioAPI();
    _GFX.closeRenderingAPI();
    _mainTaskPool->wait();
    Input::InputInterface::destroyInstance();
    SFXDevice::destroyInstance();
    GFXDevice::destroyInstance();
    ResourceCache::destroyInstance();
    // Destroy the shader manager AFTER the resource cache
    ShaderManager::destroyInstance();
    FrameListenerManager::destroyInstance();
        
    _mainTaskPool->clear();
    while (_mainTaskPool->active() > 0) {
    }
        Time::REMOVE_TIMER(s_appLoopTimer);
}

void Kernel::updateResolutionCallback(I32 w, I32 h) {
    Application& APP = Application::getInstance();
    APP.setResolution(w, h);
    // Update internal resolution tracking (used for joysticks and mouse)
    Input::InputInterface::getInstance().updateResolution(w, h);
    // Update the graphical user interface
    vec2<U16> newResolution(w, h);
    GUI::getInstance().onResize(newResolution);
    // minimized
    _renderingPaused = (w == 0 || h == 0);
    APP.isFullScreen(
        !ParamHandler::getInstance().getParam<bool>("runtime.windowedMode"));
    if (APP.mainLoopActive()) {
        // Update light manager so that all shadow maps and other render targets
        // match our needs
        LightManager::getInstance().updateResolution(w, h);
        // Cache resolution for faster access
        SceneManager::getInstance().cacheResolution(newResolution);
    }
}

///--------------------------Input
/// Management-------------------------------------///

bool Kernel::setCursorPosition(U16 x, U16 y) const {
    _GFX.setCursorPosition(x, y);
    _GUI.setCursorPosition(x, y);
    return true;
}

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

bool Kernel::onKeyUp(const Input::KeyEvent& key) {
    if (_GUI.onKeyUp(key)) {
        return _sceneMgr.onKeyUp(key);
    }
    // InputInterface needs to know when this is completed
    return false;
}

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

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

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

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

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

bool Kernel::joystickButtonPressed(const Input::JoystickEvent& arg, I8 button) {
    if (_GUI.joystickButtonPressed(arg, button)) {
        return _sceneMgr.joystickButtonPressed(arg, button);
    }
    // InputInterface needs to know when this is completed
    return false;
}

bool Kernel::joystickButtonReleased(const Input::JoystickEvent& arg,
                                    I8 button) {
    if (_GUI.joystickButtonReleased(arg, button)) {
        return _sceneMgr.joystickButtonReleased(arg, button);
    }
    // InputInterface needs to know when this is completed
    return false;
}

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

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

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

Diff revisions: vs.
Revision Author Commited Message
365 Diff Diff IonutCava picture IonutCava Sun 08 Mar, 2015 21:26:10 +0000

[Ionut]
- More enum-related type safety changes

360 Diff Diff IonutCava picture IonutCava Tue 03 Mar, 2015 16:51:21 +0000

[Ionut]
- More bug fixes (mostly the ones resulting from switching to smart pointers)

358 Diff Diff IonutCava picture IonutCava Sun 01 Mar, 2015 22:44:38 +0000

[Ionut]
- Fixed some OpenGL initialization issues and function calls (no proper support for DSA yet)
- Cleanup up the Sound and Physics Wrappers
- Some readability improvements here and there

354 Diff Diff IonutCava picture IonutCava Fri 20 Feb, 2015 17:17:37 +0000

[Ionut]
- Replaced GLEW with glbinding (requires a CEGUI recompile. It currently crashes)
- Replaced most “SceneGraphNode* const sgn” expressions with "SceneGraphNode& sgn"
- Replaced some pointers to kernel to references to kernel
- Fixed compilation issues with EASTL
- Removed NPOT -> POT texture conversion code. Modern GPUs handle NPOT textures perfectly fine

352 Diff Diff IonutCava picture IonutCava Thu 12 Feb, 2015 17:10:21 +0000

[Ionut]
- Moved per-frame-per-animation bounding boxes back to SkinnedSubMesh class with better multithreading support
- Fixed a Util::Mat4::multiply related crash
- Added a basic framework (non-functional yet) for registering events with floating point data and a basic plotting system
- Removed custom M_PI define and changed code to use the one in math.h
- Added Scoped classes for rendering (they revert state back to what it was upon destruction)
— Scoped classes for 2D rendering, toggling the rasterizer on/off, changing viewport and changing line width

351 Diff Diff IonutCava picture IonutCava Wed 11 Feb, 2015 16:39:15 +0000

[Ionut]
- Large amount of decoupling between classes by using Attorney-style classes where friendship was required.

350 Diff Diff IonutCava picture IonutCava Tue 10 Feb, 2015 16:25:39 +0000

[Ionut]
- Simplified some Util-namespace level functions by using STL algorithms where possible
- Formatted the entire codebase using clang-format with the following style: "{BasedOnStyle: Google, IndentWidth: 4}"
- Attempted to make ProfileTimer thread-safe (temp fix until std::chrono works properly in Visual Studio)

349 Diff Diff IonutCava picture IonutCava Fri 06 Feb, 2015 17:11:39 +0000

[Ionut]
- More raw pointer replacements
- Removed some redundant parameters to a few scene and application functions

348 Diff Diff IonutCava picture IonutCava Thu 05 Feb, 2015 17:13:01 +0000

[Ionut]
- Replaced some raw pointers with smart pointers or direct data members
- Removed redundant SceneGraph pointer from SceneGraphNode

343 IonutCava picture IonutCava Thu 15 Jan, 2015 17:30:12 +0000

[Ionut]
- Refactored 2 singletons into static classes (Console and TerrainLoader)
- Changed some C-casts to static_casts
- Updated copyright notices