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
#include "Headers/WarScene.h"
#include "Headers/WarSceneAIProcessor.h"

#include "GUI/Headers/GUIMessageBox.h"
#include "Geometry/Material/Headers/Material.h"
#include "Core/Math/Headers/Transform.h"
#include "Core/Time/Headers/ApplicationTimer.h"
#include "Geometry/Material/Headers/Material.h"
#include "Geometry/Shapes/Headers/Mesh.h"
#include "Geometry/Shapes/Headers/SubMesh.h"
#include "Geometry/Shapes/Headers/Predefined/Sphere3D.h"
#include "Geometry/Shapes/Headers/Predefined/Quad3D.h"
#include "Rendering/Camera/Headers/ThirdPersonCamera.h"
#include "Rendering/Camera/Headers/FirstPersonCamera.h"
#include "Rendering/RenderPass/Headers/RenderQueue.h"
#include "Dynamics/Entities/Units/Headers/NPC.h"
#include "Managers/Headers/CameraManager.h"
#include "Managers/Headers/SceneManager.h"
#include "Platform/Video/Headers/IMPrimitive.h"

#include "Dynamics/Entities/Particles/ConcreteUpdaters/Headers/ParticleBasicTimeUpdater.h"
#include "Dynamics/Entities/Particles/ConcreteUpdaters/Headers/ParticleBasicColourUpdater.h"
#include "Dynamics/Entities/Particles/ConcreteUpdaters/Headers/ParticleEulerUpdater.h"
#include "Dynamics/Entities/Particles/ConcreteUpdaters/Headers/ParticleFloorUpdater.h"

#include "Dynamics/Entities/Particles/ConcreteGenerators/Headers/ParticleBoxGenerator.h"
#include "Dynamics/Entities/Particles/ConcreteGenerators/Headers/ParticleColourGenerator.h"
#include "Dynamics/Entities/Particles/ConcreteGenerators/Headers/ParticleVelocityGenerator.h"
#include "Dynamics/Entities/Particles/ConcreteGenerators/Headers/ParticleTimeGenerator.h"

namespace Divide {

namespace {
    vec2<F32> g_sunAngle(0.0f, Angle::DegreesToRadians(45.0f));
    bool g_direction = false;
    U64 elapsedGameTimeUs = 0;
};

WarScene::WarScene(const stringImpl& name)
    : Scene(name),
    _infoBox(nullptr),
    _sceneReady(false),
    _lastNavMeshBuildTime(0UL)
{

    for (U8 i = 0; i < 2; ++i) {
        _faction[i] = nullptr;
    }

    _resetUnits = false;

    addSelectionCallback([&]() {
        SceneGraphNode_ptr selection(_currentSelection.lock());
        if (selection) {
            _GUI->modifyText(_ID("entityState"), selection->getName().c_str());
        } else {
            _GUI->modifyText(_ID("entityState"), "");
        }
    });

    _targetLines = GFX_DEVICE.getOrCreatePrimitive(false);

    _runCount = 0;
    _timeLimitMinutes = 5;
    _scoreLimit = 3;
    _elapsedGameTime = 0;
}

WarScene::~WarScene()
{
    _targetLines->_canZombify = true;
}

void WarScene::processGUI(const U64 deltaTime) {
    D64 FpsDisplay = Time::SecondsToMilliseconds(0.3);
    if (_guiTimers[0] >= FpsDisplay) {
        const Camera& cam = renderState().getCamera();
        const vec3<F32>& eyePos = cam.getEye();
        const vec3<F32>& euler = cam.getEuler();
        _GUI->modifyText(_ID("fpsDisplay"),
                         Util::StringFormat("FPS: %3.0f. FrameTime: %3.1f",
                                            Time::ApplicationTimer::instance().getFps(),
                                            Time::ApplicationTimer::instance().getFrameTime()));
        _GUI->modifyText(_ID("RenderBinCount"),
                         Util::StringFormat("Number of items in Render Bin: %d. Number of HiZ culled items: %d",
                                            GFX_RENDER_BIN_SIZE, GFX_HIZ_CULL_COUNT));

        _GUI->modifyText(_ID("camPosition"),
                         Util::StringFormat("Position [ X: %5.2f | Y: %5.2f | Z: %5.2f ] [Pitch: %5.2f | Yaw: %5.2f]",
                                            eyePos.x, eyePos.y, eyePos.z, euler.pitch, euler.yaw));

        _guiTimers[0] = 0.0;
    }

    if (_guiTimers[1] >= Time::SecondsToMilliseconds(1)) {
        SceneGraphNode_ptr selection(_currentSelection.lock());
        if (selection) {
            AI::AIEntity* entity = findAI(selection);
            if (entity) {
                _GUI->modifyText(_ID("entityState"), entity->toString().c_str());
            }
        }
    }

    if (_guiTimers[2] >= 66) {
        U32 elapsedTimeMinutes = (Time::MicrosecondsToSeconds<U32>(_elapsedGameTime) / 60) % 60;
        U32 elapsedTimeSeconds = Time::MicrosecondsToSeconds<U32>(_elapsedGameTime) % 60;
        U32 elapsedTimeMilliseconds = Time::MicrosecondsToMilliseconds<U32>(_elapsedGameTime) % 1000;


        U32 limitTimeMinutes = _timeLimitMinutes;
        U32 limitTimeSeconds = 0;
        U32 limitTimeMilliseconds = 0;

        _GUI->modifyText(_ID("scoreDisplay"),
            Util::StringFormat("Score: A -  %d B - %d [Limit: %d]\nElapsed game time [ %d:%d:%d / %d:%d:%d]",
                               AI::WarSceneAIProcessor::getScore(0),
                               AI::WarSceneAIProcessor::getScore(1),
                               _scoreLimit,
                               elapsedTimeMinutes,
                               elapsedTimeSeconds,
                               elapsedTimeMilliseconds,
                               limitTimeMinutes,
                               limitTimeSeconds,
                               limitTimeMilliseconds));

        _guiTimers[2] = 0.0;
    }

    Scene::processGUI(deltaTime);
}

namespace {
    F32 phiLight = 0.0f;
    vec3<F32> initPosLight[16];
    vec3<F32> initPosLight2[80];
    
    bool initPosSetLight = false;
    vec2<F32> rotatePoint(vec2<F32> center, F32 angle, vec2<F32> point) {

        return vec2<F32>(std::cos(angle) * (point.x - center.x) - std::sin(angle) * (point.y - center.y) + center.x,
                         std::sin(angle) * (point.x - center.x) + std::cos(angle) * (point.y - center.y) + center.y);
    }
};

void WarScene::processTasks(const U64 deltaTime) {
    if (!_sceneReady) {
        return;
    }

    D64 SunTimer = Time::Milliseconds(33);
    D64 AnimationTimer1 = Time::SecondsToMilliseconds(5);
    D64 AnimationTimer2 = Time::SecondsToMilliseconds(10);
    D64 updateLights = Time::Milliseconds(16);

    if (_taskTimers[0] >= SunTimer) {
        g_sunAngle += 0.000125f * (g_direction ? 1.0f : -1.0f);

        if (!IS_IN_RANGE_INCLUSIVE(g_sunAngle.y, 
                                   Angle::Degrees(20.0f),
                                   Angle::Degrees(55.0f))) {
            g_direction = !g_direction;
        }

        vec3<F32> sunVector(-cosf(g_sunAngle.x) * sinf(g_sunAngle.y),
                            -cosf(g_sunAngle.y),
                            -sinf(g_sunAngle.x) * sinf(g_sunAngle.y));

        _sun.lock()->get<PhysicsComponent>()->setPosition(sunVector);
        vec4<F32> sunColour = vec4<F32>(1.0f, 1.0f, 0.2f, 1.0f);

        _sun.lock()->getNode<Light>()->setDiffuseColour(sunColour);
        _currentSky.lock()->getNode<Sky>()->setSunProperties(sunVector, _sun.lock()->getNode<Light>()->getDiffuseColour());

        _taskTimers[0] = 0.0;
    }

    if (_taskTimers[1] >= AnimationTimer1) {
        for (NPC* const npc : _armyNPCs[0]) {
            npc->playNextAnimation();
        }
        _taskTimers[1] = 0.0;
    }

    if (_taskTimers[2] >= AnimationTimer2) {
        for (NPC* const npc : _armyNPCs[1]) {
            npc->playNextAnimation();
        }
        _taskTimers[2] = 0.0;
    }

    if (!initPosSetLight) {
        for (U8 i = 0; i < 16; ++i) {
            initPosLight[i].set(_lightNodes[i].lock()->get<PhysicsComponent>()->getPosition());
        }
        for (U8 i = 0; i < 80; ++i) {
            initPosLight2[i].set(_lightNodes2[i].first.lock()->get<PhysicsComponent>()->getPosition());
        }
        initPosSetLight = true;
    }

    if (_taskTimers[3] >= updateLights) {

        phiLight += 0.01f;
        if (phiLight > 360.0f) {
            phiLight = 0.0f;
        }
        F32 s1 = std::sin(phiLight);
        F32 c1 = std::cos(phiLight);
        F32 s2 = std::sin(-phiLight);
        F32 c2 = std::cos(-phiLight);
        const F32 radius = 10;
        for (U8 i = 0; i < 16; ++i) {
            F32 c = i % 2 == 0 ? c1 : c2;
            F32 s = i % 2 == 0 ? s1 : s2;
            SceneGraphNode_ptr light = _lightNodes[i].lock();
            PhysicsComponent* pComp = light->get<PhysicsComponent>();
            pComp->setPositionX(radius * c + initPosLight[i].x);
            pComp->setPositionZ(radius * s + initPosLight[i].z);
            pComp->setPositionY((radius * 0.5f) * s + initPosLight[i].y);
        }

        for (U8 i = 0; i < 80; ++i) {
            SceneGraphNode_ptr light = _lightNodes2[i].first.lock();
            PhysicsComponent* pComp = light->get<PhysicsComponent>();
            F32 angle = _lightNodes2[i].second ? std::fmod(phiLight + 45.0f, 360.0f) : phiLight;
            vec2<F32> position(rotatePoint(vec2<F32>(0.0f), angle, initPosLight2[i].xz()));
            pComp->setPositionX(position.x);
            pComp->setPositionZ(position.y);
        }

        for (U8 i = 0; i < 40; ++i) {
            SceneGraphNode_ptr light = _lightNodes3[i].lock();
            PhysicsComponent* pComp = light->get<PhysicsComponent>();
            pComp->rotateY(phiLight);
        }
        _taskTimers[3] = 0.0;
    }

    Scene::processTasks(deltaTime);
}

namespace {
    F32 phi = 0.0f;
    vec3<F32> initPos;
    bool initPosSet = false;
};

void WarScene::updateSceneStateInternal(const U64 deltaTime) {
    if (!_sceneReady) {
        return;
    }

    if (_resetUnits) {
        resetUnits();
        _resetUnits = false;
    }

    SceneGraphNode_ptr particles = _particleEmitter.lock();
    const F32 radius = 20;
    
    if (particles.get()) {
        phi += 0.01f;
        if (phi > 360.0f) {
            phi = 0.0f;
        }

        PhysicsComponent* pComp = particles->get<PhysicsComponent>();
        if (!initPosSet) {
            initPos.set(pComp->getPosition());
            initPosSet = true;
        }

        pComp->setPositionX(radius * std::cos(phi) + initPos.x);
        pComp->setPositionZ(radius * std::sin(phi) + initPos.z);
        pComp->setPositionY((radius * 0.5f) * std::sin(phi) + initPos.y);
        pComp->rotateY(phi);
    }

    if (!_aiManager->getNavMesh(_army[0][0]->getAgentRadiusCategory())) {
        return;
    }

    // renderState().drawDebugLines(true);
    vec3<F32> tempDestination;
    vec4<U8> redLine(255,0,0,128);
    vec4<U8> blueLine(0,0,255,128);
    vectorImpl<Line> paths;
    paths.reserve(_army[0].size() + _army[1].size());
    for (U8 i = 0; i < 2; ++i) {
        for (AI::AIEntity* const character : _army[i]) {
            if (!character->getUnitRef()->getBoundNode().lock()->isActive()) {
                continue;
            }
            tempDestination.set(character->getDestination());
            if (!tempDestination.isZeroLength()) {
                vectorAlg::emplace_back(paths,
                    character->getPosition(),
                    tempDestination,
                    i == 0 ? blueLine : redLine,
                    i == 0 ? blueLine / 2 : redLine / 2);
            }
        }
    }
    _targetLines->fromLines(paths);

    if (!_aiManager->updatePaused()) {
        _elapsedGameTime += deltaTime;
        checkGameCompletion();
    }
}

bool WarScene::load(const stringImpl& name) {
    static const U32 lightMask = to_const_uint(SGNComponent::ComponentType::PHYSICS) |
                                 to_const_uint(SGNComponent::ComponentType::BOUNDS) |
                                 to_const_uint(SGNComponent::ComponentType::RENDERING);

    static const U32 normalMask = lightMask |
                                  to_const_uint(SGNComponent::ComponentType::NAVIGATION);

    // Load scene resources
    bool loadState = SCENE_LOAD(name, true, true);
    // Add a light
    _sun = addLight(LightType::DIRECTIONAL, _sceneGraph->getRoot());
    // Add a skybox
    _currentSky = addSky();
    // Position camera
    renderState().getCamera().setEye(vec3<F32>(43.13f, 147.09f, -4.41f));
    renderState().getCamera().setGlobalRotation(-90.0f /*yaw*/, 59.21f /*pitch*/);

    _sun.lock()->getNode<DirectionalLight>()->csmSplitCount(3);  // 3 splits
    _sun.lock()->getNode<DirectionalLight>()->csmSplitLogFactor(0.85f);
    _sun.lock()->getNode<DirectionalLight>()->csmNearClipOffset(25.0f);
    // Add some obstacles
    SceneGraphNode_ptr cylinder[5];
    cylinder[0] = _sceneGraph->findNode("cylinderC").lock();
    cylinder[1] = _sceneGraph->findNode("cylinderNW").lock();
    cylinder[2] = _sceneGraph->findNode("cylinderNE").lock();
    cylinder[3] = _sceneGraph->findNode("cylinderSW").lock();
    cylinder[4] = _sceneGraph->findNode("cylinderSE").lock();

    U32 temp = 0;
    for (U8 i = 0; i < 5; ++i) {
        RenderingComponent* const renderable =
            cylinder[i]->getChild(0, temp).get<RenderingComponent>();
        renderable->getMaterialInstance()->setDoubleSided(true);
        cylinder[i]->getChild(0, temp).getNode()->getMaterialTpl()->setDoubleSided(true);
    }

    // Make the center cylinder reflective
    const Material_ptr& matInstance = cylinder[0]->getChild(0, temp).get<RenderingComponent>()->getMaterialInstance();
    matInstance->setShininess(200);

    std::shared_ptr<SceneNode> cylinderMeshNW = cylinder[1]->getNode();
    std::shared_ptr<SceneNode> cylinderMeshNE = cylinder[2]->getNode();
    std::shared_ptr<SceneNode> cylinderMeshSW = cylinder[3]->getNode();
    std::shared_ptr<SceneNode> cylinderMeshSE = cylinder[4]->getNode();

    stringImpl currentName;
    std::shared_ptr<SceneNode> currentMesh;
    SceneGraphNode_ptr baseNode;

    U8 locationFlag = 0;
    std::pair<I32, I32> currentPos;
    for (U8 i = 0; i < 40; ++i) {
        if (i < 10) {
            baseNode = cylinder[1];
            currentMesh = cylinderMeshNW;
            currentName = "Cylinder_NW_" + to_stringImpl((I32)i);
            currentPos.first = -200 + 40 * i + 50;
            currentPos.second = -200 + 40 * i + 50;
        }
        else if (i >= 10 && i < 20) {
            baseNode = cylinder[2];
            currentMesh = cylinderMeshNE;
            currentName = "Cylinder_NE_" + to_stringImpl((I32)i);
            currentPos.first = 200 - 40 * (i % 10) - 50;
            currentPos.second = -200 + 40 * (i % 10) + 50;
            locationFlag = 1;
        }
        else if (i >= 20 && i < 30) {
            baseNode = cylinder[3];
            currentMesh = cylinderMeshSW;
            currentName = "Cylinder_SW_" + to_stringImpl((I32)i);
            currentPos.first = -200 + 40 * (i % 20) + 50;
            currentPos.second = 200 - 40 * (i % 20) - 50;
            locationFlag = 2;
        }
        else {
            baseNode = cylinder[4];
            currentMesh = cylinderMeshSE;
            currentName = "Cylinder_SE_" + to_stringImpl((I32)i);
            currentPos.first = 200 - 40 * (i % 30) - 50;
            currentPos.second = 200 - 40 * (i % 30) - 50;
            locationFlag = 3;
        }

        SceneGraphNode_ptr crtNode = _sceneGraph->getRoot().addNode(currentMesh, normalMask, baseNode->get<PhysicsComponent>()->physicsGroup(), currentName);
        crtNode->setSelectable(true);
        crtNode->usageContext(baseNode->usageContext());
        PhysicsComponent* pComp = crtNode->get<PhysicsComponent>();
        NavigationComponent* nComp = crtNode->get<NavigationComponent>();
        nComp->navigationContext(
            baseNode->get<NavigationComponent>()->navigationContext());
        nComp->navigationDetailOverride(
            baseNode->get<NavigationComponent>()
            ->navMeshDetailOverride());

        vec3<F32> position(to_float(currentPos.first), -0.01f, to_float(currentPos.second));
        pComp->setScale(baseNode->get<PhysicsComponent>()->getScale());
        pComp->setPosition(position);

        {
            ResourceDescriptor tempLight(Util::StringFormat("Light_point_%s_1", currentName.c_str()));
            tempLight.setEnumValue(to_const_uint(LightType::POINT));
            tempLight.setUserPtr(_lightPool);
            std::shared_ptr<Light> light = CreateResource<Light>(tempLight);
            light->setDrawImpostor(false);
            light->setRange(25.0f);
            //light->setCastShadows(i == 0 ? true : false);
            light->setCastShadows(false);
            light->setDiffuseColour(DefaultColours::RANDOM());
            SceneGraphNode_ptr lightSGN = _sceneGraph->getRoot().addNode(light, lightMask, PhysicsGroup::GROUP_IGNORE);
            lightSGN->get<PhysicsComponent>()->setPosition(position + vec3<F32>(0.0f, 8.0f, 0.0f));
            _lightNodes2.push_back(std::make_pair(lightSGN, false));
        }
        {
            ResourceDescriptor tempLight(Util::StringFormat("Light_point_%s_2", currentName.c_str()));
            tempLight.setEnumValue(to_const_uint(LightType::POINT));
            tempLight.setUserPtr(_lightPool);
            std::shared_ptr<Light> light = CreateResource<Light>(tempLight);
            light->setDrawImpostor(false);
            light->setRange(35.0f);
            light->setCastShadows(false);
            light->setDiffuseColour(DefaultColours::RANDOM());
            SceneGraphNode_ptr lightSGN = _sceneGraph->getRoot().addNode(light, lightMask, PhysicsGroup::GROUP_IGNORE);
            lightSGN->get<PhysicsComponent>()->setPosition(position + vec3<F32>(0.0f, 8.0f, 0.0f));
            _lightNodes2.push_back(std::make_pair(lightSGN, true));
        }
        {
            ResourceDescriptor tempLight(Util::StringFormat("Light_spot_%s", currentName.c_str()));
            tempLight.setEnumValue(to_const_uint(LightType::SPOT));
            tempLight.setUserPtr(_lightPool);
            std::shared_ptr<Light> light = CreateResource<Light>(tempLight);
            light->setDrawImpostor(false);
            light->setRange(55.0f);
            //light->setCastShadows(i == 1 ? true : false);
            light->setCastShadows(false);
            light->setDiffuseColour(DefaultColours::RANDOM());
            SceneGraphNode_ptr lightSGN = _sceneGraph->getRoot().addNode(light, lightMask, PhysicsGroup::GROUP_IGNORE);
            lightSGN->get<PhysicsComponent>()->setPosition(position + vec3<F32>(0.0f, 10.0f, 0.0f));
            lightSGN->get<PhysicsComponent>()->rotateX(-20);
            _lightNodes3.push_back(lightSGN);
        }
    }

    SceneGraphNode_ptr flag;
    flag = _sceneGraph->findNode("flag").lock();
    RenderingComponent* const renderable = flag->getChild(0, temp).get<RenderingComponent>();
    renderable->getMaterialInstance()->setDoubleSided(true);
    const Material_ptr& mat = flag->getChild(0, temp).getNode()->getMaterialTpl();
    mat->setDoubleSided(true);
    flag->setActive(false);
    std::shared_ptr<SceneNode> flagNode = flag->getNode();

    _flag[0] = _sceneGraph->getRoot().addNode(flagNode, normalMask, flag->get<PhysicsComponent>()->physicsGroup(), "Team1Flag");

    SceneGraphNode_ptr flag0(_flag[0].lock());
    flag0->setSelectable(false);
    flag0->usageContext(flag->usageContext());
    PhysicsComponent* flagPComp = flag0->get<PhysicsComponent>();
    NavigationComponent* flagNComp = flag0->get<NavigationComponent>();
    RenderingComponent* flagRComp = flag0->getChild(0, temp).get<RenderingComponent>();

    flagPComp->setScale(flag->get<PhysicsComponent>()->getScale());
    flagPComp->setPosition(vec3<F32>(25.0f, 0.1f, -206.0f));

    flagNComp->navigationContext(NavigationComponent::NavigationContext::NODE_IGNORE);

    flagRComp->getMaterialInstance()->setDiffuse(DefaultColours::BLUE());

    _flag[1] = _sceneGraph->getRoot().addNode(flagNode, normalMask, flag->get<PhysicsComponent>()->physicsGroup(), "Team2Flag");
    SceneGraphNode_ptr flag1(_flag[1].lock());
    flag1->setSelectable(false);
    flag1->usageContext(flag->usageContext());

    flagPComp = flag1->get<PhysicsComponent>();
    flagNComp = flag1->get<NavigationComponent>();
    flagRComp = flag1->getChild(0, temp).get<RenderingComponent>();

    flagPComp->setPosition(vec3<F32>(25.0f, 0.1f, 206.0f));
    flagPComp->setScale(flag->get<PhysicsComponent>()->getScale());

    flagNComp->navigationContext(NavigationComponent::NavigationContext::NODE_IGNORE);

    flagRComp->getMaterialInstance()->setDiffuse(DefaultColours::RED());

    SceneGraphNode_ptr firstPersonFlag = _sceneGraph->getRoot().addNode(flagNode, normalMask, PhysicsGroup::GROUP_KINEMATIC, "FirstPersonFlag");
    firstPersonFlag->lockVisibility(true);
    firstPersonFlag->onCollisionCbk(DELEGATE_BIND(&WarScene::weaponCollision, this, std::placeholders::_1));
    firstPersonFlag->usageContext(SceneGraphNode::UsageContext::NODE_DYNAMIC);
    flagPComp = firstPersonFlag->get<PhysicsComponent>();
    flagPComp->ignoreView(true, renderState().getCamera().getGUID());
    flagPComp->setScale(0.0015f);
    flagPComp->setPosition(1.25f, -1.5f, 0.15f);
    flagPComp->rotate(-20.0f, -70.0f, 50.0f);
    flagRComp = firstPersonFlag->getChild(0, temp).get<RenderingComponent>();
    flagRComp->getMaterialInstance()->setDiffuse(DefaultColours::GREEN());
    flagRComp->getMaterialInstance()->setHighPriority(true);
    _firstPersonWeapon = firstPersonFlag;
    
    AI::WarSceneAIProcessor::registerFlags(_flag[0], _flag[1]);

    AI::WarSceneAIProcessor::registerScoreCallback([&](U8 teamID, const stringImpl& unitName) {
        registerPoint(teamID, unitName);
    });

    AI::WarSceneAIProcessor::registerMessageCallback([&](U8 eventID, const stringImpl& unitName) {
        printMessage(eventID, unitName);
    });
    
#ifdef _DEBUG
    const U32 particleCount = 4000;
#else
    const U32 particleCount = 20000;
#endif
    const F32 emitRate = particleCount / 4;

    std::shared_ptr<ParticleData> particles = 
        std::make_shared<ParticleData>(particleCount,
                                       to_const_uint(ParticleData::Properties::PROPERTIES_POS) |
                                       to_const_uint(ParticleData::Properties::PROPERTIES_VEL) |
                                       to_const_uint(ParticleData::Properties::PROPERTIES_ACC) |
                                       to_const_uint(ParticleData::Properties::PROPERTIES_COLOR) |
                                       to_const_uint(ParticleData::Properties::PROPERTIES_COLOR_TRANS));
    particles->_textureFileName = "particle.DDS";

    std::shared_ptr<ParticleSource> particleSource =  std::make_shared<ParticleSource>(emitRate);

    std::shared_ptr<ParticleBoxGenerator> boxGenerator = std::make_shared<ParticleBoxGenerator>();
    boxGenerator->maxStartPosOffset(vec4<F32>(0.3f, 0.0f, 0.3f, 1.0f));
    particleSource->addGenerator(boxGenerator);

    std::shared_ptr<ParticleColourGenerator> colGenerator = std::make_shared<ParticleColourGenerator>();
    colGenerator->_minStartCol.set(Util::ToByteColour(vec4<F32>(0.7f, 0.4f, 0.4f, 1.0f)));
    colGenerator->_maxStartCol.set(Util::ToByteColour(vec4<F32>(1.0f, 0.8f, 0.8f, 1.0f)));
    colGenerator->_minEndCol.set(Util::ToByteColour(vec4<F32>(0.5f, 0.2f, 0.2f, 0.5f)));
    colGenerator->_maxEndCol.set(Util::ToByteColour(vec4<F32>(0.7f, 0.5f, 0.5f, 0.75f)));
    particleSource->addGenerator(colGenerator);

    std::shared_ptr<ParticleVelocityGenerator> velGenerator = std::make_shared<ParticleVelocityGenerator>();
    velGenerator->_minStartVel.set(-1.0f, 0.22f, -1.0f, 0.0f);
    velGenerator->_maxStartVel.set(1.0f, 3.45f, 1.0f, 0.0f);
    particleSource->addGenerator(velGenerator);

    std::shared_ptr<ParticleTimeGenerator> timeGenerator = std::make_shared<ParticleTimeGenerator>();
    timeGenerator->_minTime = 8.5f;
    timeGenerator->_maxTime = 20.5f;
    particleSource->addGenerator(timeGenerator);

    _particleEmitter = addParticleEmitter("TESTPARTICLES", particles, _sceneGraph->getRoot());
    SceneGraphNode_ptr testSGN = _particleEmitter.lock();
    std::shared_ptr<ParticleEmitter> test = testSGN->getNode<ParticleEmitter>();
    testSGN->get<PhysicsComponent>()->translateY(10);
    test->setDrawImpostor(true);
    test->enableEmitter(true);
    test->addSource(particleSource);
    boxGenerator->pos(vec4<F32>(testSGN->get<PhysicsComponent>()->getPosition()));

    std::shared_ptr<ParticleEulerUpdater> eulerUpdater = std::make_shared<ParticleEulerUpdater>();
    eulerUpdater->_globalAcceleration.set(0.0f, -20.0f, 0.0f);
    test->addUpdater(eulerUpdater);
    std::shared_ptr<ParticleFloorUpdater> floorUpdater = std::make_shared<ParticleFloorUpdater>();
    floorUpdater->_bounceFactor = 0.65f;
    test->addUpdater(floorUpdater);
    test->addUpdater(std::make_shared<ParticleBasicTimeUpdater>());
    test->addUpdater(std::make_shared<ParticleBasicColourUpdater>());
    
    state().generalVisibility(state().generalVisibility() * 2);


    for (U8 row = 0; row < 4; row++) {
        for (U8 col = 0; col < 4; col++) {
            ResourceDescriptor tempLight(Util::StringFormat("Light_point_%d_%d", row, col));
            tempLight.setEnumValue(to_const_uint(LightType::POINT));
            tempLight.setUserPtr(_lightPool);
            std::shared_ptr<Light> light = CreateResource<Light>(tempLight);
            light->setDrawImpostor(false);
            light->setRange(20.0f);
            light->setCastShadows(false);
            light->setDiffuseColour(DefaultColours::RANDOM());
            SceneGraphNode_ptr lightSGN = _sceneGraph->getRoot().addNode(light, lightMask, PhysicsGroup::GROUP_IGNORE);
            lightSGN->get<PhysicsComponent>()->setPosition(vec3<F32>(-215.0f + (115 * row), 15.0f, (-215.0f + (115 * col))));
            _lightNodes.push_back(lightSGN);
        }
    }

    Application::instance()
        .kernel()
        .getCameraMgr()
        .getActiveCamera()
        .setHorizontalFoV(110);

    _sceneReady = true;
    return loadState;
}

U16 WarScene::registerInputActions() {
    U16 actionID = Scene::registerInputActions();

    //ToDo: Move these to per-scene XML file
    PressReleaseActions actions;
    _input->actionList().registerInputAction(actionID, DELEGATE_BIND(&WarScene::toggleCamera, this));
    actions._onReleaseAction = actionID;
    _input->addKeyMapping(Input::KeyCode::KC_TAB, actions);
    actionID++;

    _input->actionList().registerInputAction(actionID, DELEGATE_BIND(&WarScene::registerPoint, this, 0, ""));
    actions._onReleaseAction = actionID;
    _input->addKeyMapping(Input::KeyCode::KC_1, actions);
    actionID++;

    _input->actionList().registerInputAction(actionID, DELEGATE_BIND(&WarScene::registerPoint, this, 1, ""));
    actions._onReleaseAction = actionID;
    _input->addKeyMapping(Input::KeyCode::KC_2, actions);
    actionID++;

    _input->actionList().registerInputAction(actionID, [](InputParams param) {DIVIDE_ASSERT(false, "Test Assert"); });
    actions._onReleaseAction = actionID;
    _input->addKeyMapping(Input::KeyCode::KC_5, actions);
    actionID++;

    _input->actionList().registerInputAction(actionID, [this](InputParams param) {
        /// TTT -> TTF -> TFF -> FFT -> FTT -> TFT -> TTT
        bool dir   = _lightPool->lightTypeEnabled(LightType::DIRECTIONAL);
        bool point = _lightPool->lightTypeEnabled(LightType::POINT);
        bool spot  = _lightPool->lightTypeEnabled(LightType::SPOT);
        if (dir && point && spot) {
            _lightPool->toggleLightType(LightType::SPOT, false);
        } else if (dir && point && !spot) {
            _lightPool->toggleLightType(LightType::POINT, false);
        } else if (dir && !point && !spot) {
            _lightPool->toggleLightType(LightType::DIRECTIONAL, false);
            _lightPool->toggleLightType(LightType::SPOT, true);
        } else if (!dir && !point && spot) {
            _lightPool->toggleLightType(LightType::POINT, true);
        } else if (!dir && point && spot) {
            _lightPool->toggleLightType(LightType::DIRECTIONAL, true);
            _lightPool->toggleLightType(LightType::POINT, false);
        } else {
            _lightPool->toggleLightType(LightType::POINT, true);
        }
    });
    actions._onReleaseAction = actionID;
    _input->addKeyMapping(Input::KeyCode::KC_L, actions);


    return actionID++;
}

void WarScene::toggleCamera() {
    static bool fpsCameraActive = false;
    static bool tpsCameraActive = false;
    static bool flyCameraActive = true;

    if (_currentSelection.lock()) {
        if (flyCameraActive) {
            if (fpsCameraActive) {
                renderState().getCameraMgr().popActiveCamera();
            }
            renderState().getCameraMgr().pushActiveCamera(_ID("tpsCamera"));
            static_cast<ThirdPersonCamera&>(renderState().getCamera())
                .setTarget(_currentSelection);
            flyCameraActive = false;
            tpsCameraActive = true;
            return;
        }
    }
    if (tpsCameraActive) {
        renderState().getCameraMgr().pushActiveCamera(_ID("defaultCamera"));
        tpsCameraActive = false;
        flyCameraActive = true;
    }
}

bool WarScene::loadResources(bool continueOnErrors) {
    // Add a first person camera
    Camera* cam = renderState().getCameraMgr().createCamera("fpsCamera", Camera::CameraType::FIRST_PERSON);
    cam->fromCamera(renderState().getCameraConst());
    cam->setMoveSpeedFactor(10.0f);
    cam->setTurnSpeedFactor(10.0f);
    // Add a third person camera
    cam = renderState().getCameraMgr().createCamera("tpsCamera", Camera::CameraType::THIRD_PERSON);
    cam->fromCamera(renderState().getCameraConst());
    cam->setMoveSpeedFactor(0.02f);
    cam->setTurnSpeedFactor(0.01f);

    _guiTimers.push_back(0.0);  // Fps
    _guiTimers.push_back(0.0);  // AI info
    _guiTimers.push_back(0.0);  // Game info
    _taskTimers.push_back(0.0); // Sun animation
    _taskTimers.push_back(0.0); // animation team 1
    _taskTimers.push_back(0.0); // animation team 2
    _taskTimers.push_back(0.0); // light timer
    return true;
}

void WarScene::postLoadMainThread() {
    const vec2<U16>& resolution = _GUI->getDisplayResolution();

    _GUI->addButton(_ID("Simulate"), "Simulate",
        vec2<I32>(resolution.width - 220, 60),
        vec2<U32>(100, 25),
        DELEGATE_BIND(&WarScene::startSimulation, this, std::placeholders::_1));

    _GUI->addText(_ID("fpsDisplay"),  // Unique ID
        vec2<I32>(60, 63),  // Position
        Font::DIVIDE_DEFAULT,  // Font
        vec4<U8>(0, 50, 255, 255), // Colour
        Util::StringFormat("FPS: %3.0f. FrameTime: %3.1f", 0.0f, 0.0f));  // Text and arguments
    _GUI->addText(_ID("RenderBinCount"),
        vec2<I32>(60, 83),
        Font::DIVIDE_DEFAULT,
        vec4<U8>(164, 50, 50, 255),
        Util::StringFormat("Number of items in Render Bin: %d", 0));
    _GUI->addText(_ID("camPosition"), vec2<I32>(60, 103),
        Font::DIVIDE_DEFAULT,
        vec4<U8>(50, 192, 50, 255),
        Util::StringFormat("Position [ X: %5.0f | Y: %5.0f | Z: %5.0f ] [Pitch: %5.2f | Yaw: %5.2f]",
            renderState().getCamera().getEye().x,
            renderState().getCamera().getEye().y,
            renderState().getCamera().getEye().z,
            renderState().getCamera().getEuler().pitch,
            renderState().getCamera().getEuler().yaw));

    _GUI->addText(_ID("scoreDisplay"),
        vec2<I32>(60, 123),  // Position
        Font::DIVIDE_DEFAULT,  // Font
        vec4<U8>(50, 192, 50, 255),// Colour
        Util::StringFormat("Score: A -  %d B - %d", 0, 0));  // Text and arguments

    _GUI->addText(_ID("entityState"), vec2<I32>(60, 163), Font::DIVIDE_DEFAULT,
        vec4<U8>(0, 0, 0, 255),
        "");

    _infoBox = _GUI->addMsgBox(_ID("infoBox"), "Info", "Blabla");

    Scene::postLoadMainThread();
}

void WarScene::weaponCollision(SceneGraphNode_cptr collider) {
    if (collider) {
        Console::d_printfn("Weapon touched [ %s ]", collider->getName().c_str());
    }
}

};

Commits for Divide-Framework/trunk/Source Code/Scenes/WarScene/WarScene.cpp

Diff revisions: vs.
Revision Author Commited Message
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

721 Diff Diff 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

718 Diff Diff IonutCava picture IonutCava Thu 02 Jun, 2016 16:02:48 +0000

[IonutCava]
- Code cleanup:
— Rename Framebuffer to RenderTarget. Only OpenGL uses the Framebuffer nomenclature.
— Remove base Shader class as only OpenGL will have separate shaders (and eventually move to pipeline objects) as Direct3D uses FX files and may end up with different structure
— Remove drawBox3D, drawSphere3D and drawLines from GFXDevice class and add them as member functions to the IMPrimitive class (renamed to fromXYZ)
— Pull some elements from SceneManager and move them to standalone classes (W.I.P.)

716 Diff Diff IonutCava picture IonutCava Tue 31 May, 2016 16:08:29 +0000

[IonutCava]
- Multithreaded scene load/unload fixes:
— Added postLoadMainThread call for scenes for thread sensitive loading steps
— GUI element adding is a thread sensitive loading step (a fast one) because CEGUI doesn’t handle threading
- Added REALTIME_WITH_CALLBACK task priority for tasks that need an immediate callback when they complete instead of using the flushCallbackQueue system.
- Some work on shadow mapping for getting it to work again
- ShaderPrograms that fail to load can cause a LockManager infinite wait. Delete the lockManager if the shader didn’t load to avoid waiting on commands that never get called.

714 Diff Diff IonutCava picture IonutCava Thu 26 May, 2016 16:26:23 +0000

[IonutCava]
- Initial code for multithreaded scene load:
— Tasks can have a “sync with gpu” flag that will cause them to use a shared context (so they can call GL functions)
- Added per scene GUI lists that get passed to the main GUI class (still need a base class to hold the map and accessors to avoid code duplication)
- Re-enabled threading unit tests

713 Diff Diff IonutCava picture IonutCava Wed 25 May, 2016 15:43:38 +0000

[IonutCava]
- Removed all unique_ptr’s from the code with classic new/delete pairs. They were seriously not needed.
- Added the concept of SceneComponent to scene specific classes: aiManager, lightPool, sceneGraph, physicsInterface etc
— This allowed the removal of the global GET_ACTIVE_SCENEGRAPH call;

711 Diff Diff IonutCava picture IonutCava Mon 23 May, 2016 14:31:55 +0000

[IonutCava]
- More scene change fixes: pending tasks, GUI elements, etc
- Singleton removal: AIManager is a per-scene member instead of a global singleton now

710 Diff Diff IonutCava picture IonutCava Fri 20 May, 2016 16:24:40 +0000

[IonutCava]
- Code cleanup
- Initial work on Scene loading and unloading with and without unloading assets:
— Need to change AIManager from a Singleton to a per-scene component

709 Diff Diff IonutCava picture IonutCava Thu 19 May, 2016 16:21:46 +0000

[IonutCava]
- Massive rewrite of the resource system:
— ResourceCache now uses a map of weak pointers and passes shared pointers to the call point of CreateResource
— RemoveResource is no longer needed, but resource based smart pointers use a custom deleter that calls unload()
— Keep a shared_ptr of the resource in the entity that needs it and pass shared_ptr references from getter methods
-— All of this removed the need for calls to RemoveResource, REGISTER_TRACKED_DEPENDENCY and UNREGISTER_TRACKED_DEPENDENCY reducing the number of mutex locks and atomic exchanges
- Singleton cleanup:
— Removed ShaderManager singleton and merged it’s data and responsibilities in static methods in both ShaderProgram and Shader classes.
Explanation: Due to the complex interdependency chains in the system, copying, updating, tracking the cache in a thread safe way became a lot more slower than a straight forward smart pointer based implementation. (e.g. scene graph nodes have 3d objects and material instances, 3d objects have materials, materials have textures and shaders, etc)

706 IonutCava picture IonutCava Fri 13 May, 2016 16:29:40 +0000

[IonutCava]
- Renamed LightManager to LightPool and changed it from a Singleton to a scene specific pointer
- More scene load / unload updates (changing scenes now works properly!)
- Allowed GUI interface to hold per-scene elements and only render relevant ones
- Reduced dependencies between nodes, scenemanager, scene, loaders and kernel
- Removed Reflector base class as it was useless and integrate Water class with the Reflection system already in place
- Extended RenderingComponent’s reflection system to allow refraction as well