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

#include "Headers/WarScene.h"
#include "Headers/WarSceneAIProcessor.h"

#include "GUI/Headers/GUIButton.h"
#include "GUI/Headers/GUIMessageBox.h"
#include "Geometry/Material/Headers/Material.h"
#include "Core/Headers/PlatformContext.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/Predefined/Headers/Sphere3D.h"
#include "Geometry/Shapes/Predefined/Headers/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 "Dynamics/Entities/Units/Headers/Player.h"
#include "Managers/Headers/SceneManager.h"
#include "Managers/Headers/RenderPassManager.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::to_RADIANS(45.0f));
    bool g_direction = false;
    U64 elapsedGameTimeUs = 0;
};

WarScene::WarScene(PlatformContext& context, ResourceCache& cache, SceneManager& parent, const stringImpl& name)
   : Scene(context, cache, parent, name),
    _infoBox(nullptr),
    _sceneReady(false),
    _lastNavMeshBuildTime(0UL)
{

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

    _resetUnits = false;

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

    _targetLines = _context.gfx().newIMP();

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

WarScene::~WarScene()
{
	_targetLines->clear();
}

void WarScene::processGUI(const U64 deltaTimeUS) {
    D64 FpsDisplay = Time::SecondsToMilliseconds(0.3);
    if (_guiTimersMS[0] >= FpsDisplay) {
        const Camera& cam = _scenePlayers.front()->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",
                               _context.gfx().parent().renderPassManager().getLastTotalBinSize(RenderStage::DISPLAY),
                               _context.gfx().getLastCullCount()));

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

        _guiTimersMS[0] = 0.0;
    }

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

    if (_guiTimersMS[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));

        _guiTimersMS[2] = 0.0;
    }

    Scene::processGUI(deltaTimeUS);
}

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::debugDraw(const Camera& activeCamera, const RenderStagePass& stagePass, GFX::CommandBuffer& bufferInOut) {
    bufferInOut.add(_targetLines->toCommandBuffer());
    Scene::debugDraw(activeCamera, stagePass, bufferInOut);
}

void WarScene::processTasks(const U64 deltaTimeUS) {
    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<F32>(20.0f),
                                   Angle::DEGREES<F32>(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->get<TransformComponent>()->setPosition(sunVector);
        FColour sunColour = FColour(1.0f, 1.0f, 0.2f, 1.0f);

        _sun->getNode<Light>()->setDiffuseColour(sunColour);

        PushConstants& constants = _currentSky->get<RenderingComponent>()->pushConstants();
        constants.set("enable_sun", PushConstantType::BOOL, true);
        constants.set("sun_vector", PushConstantType::VEC3, sunVector);
        constants.set("sun_colour", PushConstantType::VEC3, _sun->getNode<Light>()->getDiffuseColour());

        _taskTimers[0] = 0.0;
    }

    if (_taskTimers[1] >= AnimationTimer1) {
        for (SceneGraphNode* npc : _armyNPCs[0]) {
            assert(npc);
            npc->get<UnitComponent>()->getUnit<NPC>()->playNextAnimation();
        }
        _taskTimers[1] = 0.0;
    }

    if (_taskTimers[2] >= AnimationTimer2) {
        for (SceneGraphNode* npc : _armyNPCs[1]) {
            assert(npc);
            npc->get<UnitComponent>()->getUnit<NPC>()->playNextAnimation();
        }
        _taskTimers[2] = 0.0;
    }

    if (!initPosSetLight) {
        for (U8 i = 0; i < 16; ++i) {
            initPosLight[i].set(_lightNodes[i]->get<TransformComponent>()->getPosition());
        }
        for (U8 i = 0; i < 80; ++i) {
            initPosLight2[i].set(_lightNodes2[i].first->get<TransformComponent>()->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* light = _lightNodes[i];
            TransformComponent* tComp = light->get<TransformComponent>();
            tComp->setPositionX(radius * c + initPosLight[i].x);
            tComp->setPositionZ(radius * s + initPosLight[i].z);
            tComp->setPositionY((radius * 0.5f) * s + initPosLight[i].y);
        }

        for (U8 i = 0; i < 80; ++i) {
            SceneGraphNode* light = _lightNodes2[i].first;
            TransformComponent* tComp = light->get<TransformComponent>();
            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()));
            tComp->setPositionX(position.x);
            tComp->setPositionZ(position.y);
        }

        for (U8 i = 0; i < 40; ++i) {
            SceneGraphNode* light = _lightNodes3[i];
            TransformComponent* tComp = light->get<TransformComponent>();
            tComp->rotateY(phiLight);
        }
        _taskTimers[3] = 0.0;
    }

    Scene::processTasks(deltaTimeUS);
}

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

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

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

    _targetLines->paused(!renderState().isEnabledOption(SceneRenderState::RenderOptions::RENDER_DEBUG_TARGET_LINES));

    SceneGraphNode* particles = _particleEmitter;
    const F32 radius = 20;
    
    if (particles) {
        phi += 0.01f;
        if (phi > 360.0f) {
            phi = 0.0f;
        }

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

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

    if (!_aiManager->getNavMesh(_armyNPCs[0][0]->get<UnitComponent>()->getUnit<NPC>()->getAIEntity()->getAgentRadiusCategory())) {
        return;
    }

    // renderState().drawDebugLines(true);
    vec3<F32> tempDestination;
    UColour redLine(255,0,0,128);
    UColour blueLine(0,0,255,128);
    vectorImpl<Line> paths;
    paths.reserve(_armyNPCs[0].size() + _armyNPCs[1].size());
    for (U8 i = 0; i < 2; ++i) {
        for (SceneGraphNode* node : _armyNPCs[i]) {
            AI::AIEntity* const character = node->get<UnitComponent>()->getUnit<NPC>()->getAIEntity();
            if (!node->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 += deltaTimeUS;
        checkGameCompletion();
    }
}

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

    static const U32 normalMask = lightMask |
                                  to_base(ComponentType::RIGID_BODY) |
                                  to_base(ComponentType::NAVIGATION) |
                                  to_base(ComponentType::NETWORKING);

    // 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
    Camera::utilityCamera(Camera::UtilityCamera::DEFAULT)->setEye(vec3<F32>(43.13f, 147.09f, -4.41f));
    Camera::utilityCamera(Camera::UtilityCamera::DEFAULT)->setGlobalRotation(-90.0f /*yaw*/, 59.21f /*pitch*/);

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

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

    // Make the center cylinder reflective
    const Material_ptr& matInstance = cylinder[0]->getChild(0).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* 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* crtNode = _sceneGraph->getRoot().addNode(currentMesh, normalMask, baseNode->get<RigidBodyComponent>()->physicsGroup(), currentName);
        crtNode->setSelectable(true);
        crtNode->usageContext(baseNode->usageContext());
        TransformComponent* tComp = crtNode->get<TransformComponent>();
        NavigationComponent* nComp = crtNode->get<NavigationComponent>();
        nComp->navigationContext(
            baseNode->get<NavigationComponent>()->navigationContext());
        nComp->navigationDetailOverride(
            baseNode->get<NavigationComponent>()
            ->navMeshDetailOverride());

        vec3<F32> position(to_F32(currentPos.first), -0.01f, to_F32(currentPos.second));
        tComp->setScale(baseNode->get<TransformComponent>()->getScale());
        tComp->setPosition(position);

        {
            ResourceDescriptor tempLight(Util::StringFormat("Light_point_%s_1", currentName.c_str()));
            tempLight.setEnumValue(to_base(LightType::POINT));
            tempLight.setUserPtr(_lightPool);
            std::shared_ptr<Light> light = CreateResource<Light>(_resCache, tempLight);
            light->setDrawImpostor(false);
            light->setRange(25.0f);
            //light->setCastShadows(i == 0 ? true : false);
            light->setCastShadows(false);
            light->setDiffuseColour(DefaultColours::RANDOM());
            SceneGraphNode* lightSGN = _sceneGraph->getRoot().addNode(light, lightMask, PhysicsGroup::GROUP_IGNORE);
            lightSGN->get<TransformComponent>()->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_base(LightType::POINT));
            tempLight.setUserPtr(_lightPool);
            std::shared_ptr<Light> light = CreateResource<Light>(_resCache, tempLight);
            light->setDrawImpostor(false);
            light->setRange(35.0f);
            light->setCastShadows(false);
            light->setDiffuseColour(DefaultColours::RANDOM());
            SceneGraphNode* lightSGN = _sceneGraph->getRoot().addNode(light, lightMask, PhysicsGroup::GROUP_IGNORE);
            lightSGN->get<TransformComponent>()->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_base(LightType::SPOT));
            tempLight.setUserPtr(_lightPool);
            std::shared_ptr<Light> light = CreateResource<Light>(_resCache, tempLight);
            light->setDrawImpostor(false);
            light->setRange(55.0f);
            //light->setCastShadows(i == 1 ? true : false);
            light->setCastShadows(false);
            light->setDiffuseColour(DefaultColours::RANDOM());
            SceneGraphNode* lightSGN = _sceneGraph->getRoot().addNode(light, lightMask, PhysicsGroup::GROUP_IGNORE);
            lightSGN->get<TransformComponent>()->setPosition(position + vec3<F32>(0.0f, 10.0f, 0.0f));
            lightSGN->get<TransformComponent>()->rotateX(-20);
            _lightNodes3.push_back(lightSGN);
        }
    }

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

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

    SceneGraphNode* flag0(_flag[0]);
    flag0->setSelectable(false);
    flag0->usageContext(flag->usageContext());
    TransformComponent* flagtComp = flag0->get<TransformComponent>();
    NavigationComponent* flagNComp = flag0->get<NavigationComponent>();
    RenderingComponent* flagRComp = flag0->getChild(0).get<RenderingComponent>();

    flagtComp->setScale(flag->get<TransformComponent>()->getScale());
    flagtComp->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<RigidBodyComponent>()->physicsGroup(), "Team2Flag");
    SceneGraphNode* flag1(_flag[1]);
    flag1->setSelectable(false);
    flag1->usageContext(flag->usageContext());

    flagtComp = flag1->get<TransformComponent>();
    flagNComp = flag1->get<NavigationComponent>();
    flagRComp = flag1->getChild(0).get<RenderingComponent>();

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

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

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

    SceneGraphNode* firstPersonFlag = _sceneGraph->getRoot().addNode(flagNode, normalMask, PhysicsGroup::GROUP_KINEMATIC, "FirstPersonFlag");
    firstPersonFlag->lockVisibility(true);
    firstPersonFlag->usageContext(SceneGraphNode::UsageContext::NODE_DYNAMIC);
    flagtComp = firstPersonFlag->get<TransformComponent>();
    flagtComp->setScale(0.0015f);
    flagtComp->setPosition(1.25f, -1.5f, 0.15f);
    flagtComp->rotate(-20.0f, -70.0f, 50.0f);
    firstPersonFlag->get<RigidBodyComponent>()->onCollisionCbk(DELEGATE_BIND(&WarScene::weaponCollision, this, std::placeholders::_1));
    flagRComp = firstPersonFlag->getChild(0).get<RenderingComponent>();
    flagRComp->getMaterialInstance()->setDiffuse(DefaultColours::GREEN);
    flagRComp->getMaterialInstance()->setHighPriority(true);
    _firstPersonWeapon = firstPersonFlag;

    //_firstPersonWeapon.lock()->get<TransformComponent>()->ignoreView(true, playerCamera()->getGUID());

    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);
    });
    
    const U32 particleCount = Config::Build::IS_DEBUG_BUILD ? 4000 : 20000;
    const F32 emitRate = particleCount / 4;

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

    std::shared_ptr<ParticleSource> particleSource =  std::make_shared<ParticleSource>(platformContext().gfx(), 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(FColour(0.7f, 0.4f, 0.4f, 1.0f)));
    colGenerator->_maxStartCol.set(Util::ToByteColour(FColour(1.0f, 0.8f, 0.8f, 1.0f)));
    colGenerator->_minEndCol.set(Util::ToByteColour(FColour(0.5f, 0.2f, 0.2f, 0.5f)));
    colGenerator->_maxEndCol.set(Util::ToByteColour(FColour(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* testSGN = _particleEmitter;
    std::shared_ptr<ParticleEmitter> test = testSGN->getNode<ParticleEmitter>();
    testSGN->get<TransformComponent>()->translateY(10);
    test->setDrawImpostor(true);
    test->enableEmitter(true);
    test->addSource(particleSource);
    boxGenerator->pos(vec4<F32>(testSGN->get<TransformComponent>()->getPosition()));

    std::shared_ptr<ParticleEulerUpdater> eulerUpdater = std::make_shared<ParticleEulerUpdater>(platformContext().gfx());
    eulerUpdater->_globalAcceleration.set(0.0f, -20.0f, 0.0f);
    test->addUpdater(eulerUpdater);
    std::shared_ptr<ParticleFloorUpdater> floorUpdater = std::make_shared<ParticleFloorUpdater>(platformContext().gfx());
    floorUpdater->_bounceFactor = 0.65f;
    test->addUpdater(floorUpdater);
    test->addUpdater(std::make_shared<ParticleBasicTimeUpdater>(platformContext().gfx()));
    test->addUpdater(std::make_shared<ParticleBasicColourUpdater>(platformContext().gfx()));
    
    state().renderState().generalVisibility(state().renderState().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_base(LightType::POINT));
            tempLight.setUserPtr(_lightPool);
            std::shared_ptr<Light> light = CreateResource<Light>(_resCache, tempLight);
            light->setDrawImpostor(false);
            light->setRange(20.0f);
            light->setCastShadows(false);
            light->setDiffuseColour(DefaultColours::RANDOM());
            SceneGraphNode* lightSGN = _sceneGraph->getRoot().addNode(light, lightMask, PhysicsGroup::GROUP_IGNORE);
            lightSGN->get<TransformComponent>()->setPosition(vec3<F32>(-215.0f + (115 * row), 15.0f, (-215.0f + (115 * col))));
            _lightNodes.push_back(lightSGN);
        }
    }

    Camera::utilityCamera(Camera::UtilityCamera::DEFAULT)->setHorizontalFoV(110);

    _envProbePool->addInfiniteProbe(vec3<F32>(0.0f, 0.0f, 0.0f));
    _envProbePool->addLocalProbe(vec3<F32>(-5.0f), vec3<F32>(-1.0f));

    _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, std::placeholders::_1));
    actions.actionID(PressReleaseActions::Action::RELEASE, actionID);
    _input->addKeyMapping(Input::KeyCode::KC_TAB, actions);
    actionID++;

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

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

    _input->actionList().registerInputAction(actionID, [](InputParams param) {DIVIDE_ASSERT(false, "Test Assert"); });
    actions.actionID(PressReleaseActions::Action::RELEASE, 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.actionID(PressReleaseActions::Action::RELEASE, actionID);
    _input->addKeyMapping(Input::KeyCode::KC_L, actions);


    return actionID++;
}

void WarScene::toggleCamera(InputParams param) {
    // None of this works with multiple players
    static bool tpsCameraActive = false;
    static bool flyCameraActive = true;
    static Camera* tpsCamera = nullptr;
    static Camera* fpsCamera = nullptr;

    if (!tpsCamera) {
        tpsCamera = Camera::findCamera(_ID("tpsCamera"));
        fpsCamera = Camera::findCamera(_ID("fpsCamera"));
    }

    PlayerIndex idx = getPlayerIndexForDevice(param._deviceIndex);
    if (_currentSelection[idx]) {
        if (flyCameraActive) {
            state().playerState(idx).overrideCamera(tpsCamera);
            static_cast<ThirdPersonCamera&>(*tpsCamera).setTarget(_currentSelection[idx]);
            flyCameraActive = false;
            tpsCameraActive = true;
            return;
        }
    }
    if (tpsCameraActive) {
        state().playerState(idx).overrideCamera(nullptr);
        tpsCameraActive = false;
        flyCameraActive = true;
    }
}

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

    _guiTimersMS.push_back(0.0);  // Fps
    _guiTimersMS.push_back(0.0);  // AI info
    _guiTimersMS.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 = _context.gfx().renderingResolution();

    GUIButton* btn = _GUI->addButton(_ID("Simulate"),
                                     "Simulate",
                                     pixelPosition(resolution.width - 220, 60),
                                     pixelScale(100, 25));
    btn->setEventCallback(GUIButton::Event::MouseClick,
                          DELEGATE_BIND(&WarScene::startSimulation, this, std::placeholders::_1));

    btn = _GUI->addButton(_ID("ShaderReload"),
                          "Shader Reload",
                          pixelPosition(resolution.width - 220, 30),
                          pixelScale(100, 25));
    btn->setEventCallback(GUIButton::Event::MouseClick,
                         [this](I64 btnID) { rebuildShaders(); });

    _GUI->addText("fpsDisplay",  // Unique ID
                  pixelPosition(60, 63),  // Position
        Font::DIVIDE_DEFAULT,  // Font
                  UColour(0, 50, 255, 255), // Colour
        Util::StringFormat("FPS: %3.0f. FrameTime: %3.1f", 0.0f, 0.0f));  // Text and arguments
    _GUI->addText("RenderBinCount",
                  pixelPosition(60, 83),
        Font::DIVIDE_DEFAULT,
                  UColour(164, 50, 50, 255),
        Util::StringFormat("Number of items in Render Bin: %d", 0));
    _GUI->addText("camPosition", pixelPosition(60, 103),
        Font::DIVIDE_DEFAULT,
                  UColour(50, 192, 50, 255),
        Util::StringFormat("Position [ X: %5.0f | Y: %5.0f | Z: %5.0f ] [Pitch: %5.2f | Yaw: %5.2f]",
            0.0f, 0.0f, 0.0f, 0.0f, 0.0f));

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

    _GUI->addText("entityState",
                  pixelPosition(60, 163),
                  Font::DIVIDE_DEFAULT,
                  UColour(0, 0, 0, 255),
                  "");

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

    Scene::postLoadMainThread();
}

void WarScene::weaponCollision(const RigidBodyComponent& collider) {
    Console::d_printfn("Weapon touched [ %s ]", collider.getSGN().getName().c_str());
}

};

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

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

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

1003 Diff Diff IonutCava picture IonutCava Tue 19 Dec, 2017 17:08:06 +0000

[Ionut]
- GUI cleanup

996 Diff Diff IonutCava picture IonutCava Tue 12 Dec, 2017 17:16:54 +0000

[Ionut]
- Update and improve SGN creation and destruction
- Fix cleanup issues
- Fix GPU object memory leaks
- Fix duplicate GUID values being generated
- Misc cleanups and optimizations

994 Diff Diff IonutCava picture IonutCava Mon 11 Dec, 2017 18:01:11 +0000

[Ionut]
- Moved remaining components to new ECS system
- Started cleaning up code that was made redundant by the ECS system

993 Diff Diff IonutCava picture IonutCava Sun 10 Dec, 2017 20:07:57 +0000

[Ionut]
- Finished initial port of the old scene graph system to the new ECS based system.
- Finished converting 2 components to the new ECS system: Transform and RigidBody
- Fixed the “Deploy” build error with the CEGUI OpenGL renderer.
- Compilation now needs C++14 support (it’s sufficiently wide-spread now)

992 Diff Diff IonutCava picture IonutCava Thu 07 Dec, 2017 18:01:51 +0000

[Ionut]
- Split PhysicsComponent into 2, ECS-based, components: TransformComponent and RigidBodyComponent
UNTESTED

990 Diff Diff IonutCava picture IonutCava Tue 05 Dec, 2017 17:20:10 +0000

[Ionut]
- Some SceneGraph and SceneGraphNode cleanup

989 Diff Diff IonutCava picture IonutCava Fri 01 Dec, 2017 16:10:10 +0000

[Ionut]
- Moved MainMenuBar out of PanelManager and modified it a bit
- Updated Imgui and addons to the latest version
- Added “Step 1 frame” and “Step 60 frames” buttons to the editor (when the simulation is paused, these advance time by the given number of frames only)
- Removed per-scene base camera and added a utility default camera, also used by the editor

979 Diff Diff IonutCava picture IonutCava Tue 21 Nov, 2017 23:24:57 +0000

[Ionut]
- W.I.P. Rework GUI element positioning and scaling
- Update ImGUI and IMGUI_ADDONS

978 IonutCava picture IonutCava Mon 20 Nov, 2017 23:42:23 +0000

[Ionut]
- More decoupling between window size and render resolution.
- Attempt to preserve render target aspect on window resize events

  • Resolution change is currently broken *