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

#include "GUI/Headers/GUIMessageBox.h"
#include "Geometry/Material/Headers/Material.h"
#include "Core/Math/Headers/Transform.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 "Managers/Headers/AIManager.h"

namespace Divide {

REGISTER_SCENE(WarScene);

WarScene::WarScene() : Scene(),
                       _sun(nullptr),
                       _infoBox(nullptr),
                       _bobNode(nullptr),
                       _bobNodeBody(nullptr),
                       _lampLightNode(nullptr),
                       _lampTransform(nullptr),
                       _lampTransformNode(nullptr),
                       _groundPlaceholder(nullptr),
                       _sceneReady(false),
                       _lastNavMeshBuildTime(0UL)
{
    for (U8 i = 0; i < 2; ++i) {
        _flag[i] = nullptr;
        _faction[i] = nullptr;
    }
}

WarScene::~WarScene()
{
}

void WarScene::processGUI(const U64 deltaTime){
    D32 FpsDisplay = getSecToMs(0.3);
    if (_guiTimers[0] >= FpsDisplay){
        const Camera& cam = renderState().getCamera();
        const vec3<F32>& eyePos = cam.getEye();
        const vec3<F32>& euler = cam.getEuler();
        //const vec3<F32>& lampPos = _lampLightNode->getComponent<PhysicsComponent>()->getPosition();
        _GUI->modifyText("fpsDisplay", "FPS: %3.0f. FrameTime: %3.1f", 
                         ApplicationTimer::getInstance().getFps(), ApplicationTimer::getInstance().getFrameTime());
        _GUI->modifyText("RenderBinCount", "Number of items in Render Bin: %d", GFX_RENDER_BIN_SIZE);
        _GUI->modifyText("camPosition", "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);
        /*_GUI->modifyText("lampPosition","Lamp Position  [ X: %5.2f | Y: %5.2f | Z: %5.2f ]",
        lampPos.x, lampPos.y, lampPos.z);*/

        _guiTimers[0] = 0.0;
    }
    Scene::processGUI(deltaTime);
}

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

    static vec2<F32> _sunAngle = vec2<F32>(0.0f, RADIANS(45.0f));
    static bool direction = false;
    if(!direction){
        _sunAngle.y += 0.005f;
        _sunAngle.x += 0.005f;
    }else{
        _sunAngle.y -= 0.005f;
        _sunAngle.x -= 0.005f;
    }

    if(_sunAngle.y  <= RADIANS(25) || _sunAngle.y >= RADIANS(70))
        direction = !direction;

    _sunvector = vec3<F32>(	-cosf(_sunAngle.x) * sinf(_sunAngle.y),
                            -cosf(_sunAngle.y),
                            -sinf(_sunAngle.x) * sinf(_sunAngle.y));

    _sun->setDirection(_sunvector);
	_currentSky->getNode<Sky>()->setSunProperties(_sunvector, _sun->getDiffuseColor());

    D32 BobTimer = getSecToMs(5);
    D32 DwarfTimer = getSecToMs(8);
    D32 BullTimer = getSecToMs(10);

    if(_taskTimers[0] >= BobTimer){
        if(_bobNode)
            _bobNode->getComponent<AnimationComponent>()->playNextAnimation();

        _taskTimers[0] = 0.0;
    }
    if(_taskTimers[1] >= DwarfTimer){
        SceneGraphNode* dwarf = _sceneGraph->findNode("Soldier1");
         if(dwarf)
             dwarf->getComponent<AnimationComponent>()->playNextAnimation();
        _taskTimers[1] = 0.0;
    }
    if(_taskTimers[2] >= BullTimer){
        SceneGraphNode* bull = _sceneGraph->findNode("Soldier2");
         if(bull)
             bull->getComponent<AnimationComponent>()->playNextAnimation();
        _taskTimers[2] = 0.0;
    }
    Scene::processTasks(deltaTime);
}

static std::atomic_bool navMeshStarted;

void navMeshCreationCompleteCallback(AI::AIEntity::PresetAgentRadius radius,  AI::Navigation::NavigationMesh* navMesh){
    navMesh->save();
    AI::AIManager::getInstance().addNavMesh(radius, navMesh);
}

void WarScene::startSimulation() {
    AI::AIManager::getInstance().pauseUpdate(true);
    _infoBox->setTitle("NavMesh state");
    _infoBox->setMessageType(GUIMessageBox::MESSAGE_INFO);
    bool previousMesh = false;
    bool loadedFromFile = true;
    U64 currentTime = GETUSTIME(true);
    U64 diffTime = currentTime - _lastNavMeshBuildTime;
    if (diffTime > getSecToUs(10)) {
        AI::Navigation::NavigationMesh* navMesh = AI::AIManager::getInstance().getNavMesh(_army[0][0]->getAgentRadiusCategory());
        if (navMesh) {
            previousMesh = true;
            AI::AIManager::getInstance().destroyNavMesh(_army[0][0]->getAgentRadiusCategory());
        }
        navMesh = MemoryManager_NEW AI::Navigation::NavigationMesh();
        navMesh->setFileName(GET_ACTIVE_SCENE()->getName());

        if (!navMesh->load(nullptr)) {
            loadedFromFile = false;
            navMesh->build(nullptr,DELEGATE_BIND(navMeshCreationCompleteCallback,_army[0][0]->getAgentRadiusCategory(),navMesh));
        } else {
            AI::AIManager::getInstance().addNavMesh(_army[0][0]->getAgentRadiusCategory(), navMesh);
#       ifdef _DEBUG
                navMesh->debugDraw(true);
                renderState().drawDebugTargetLines(true);
#       endif
        }

        if (previousMesh) {
            if (loadedFromFile) {
                _infoBox->setMessage("Re-loaded the navigation mesh from file!");
            } else {
                _infoBox->setMessage("Re-building the navigation mesh in a background thread!");
            }
        } else {
            if (loadedFromFile) {
                _infoBox->setMessage("Navigation mesh loaded from file!");
            } else {
                _infoBox->setMessage("Navigation mesh building in a background thread!");
            }
        }
        _infoBox->show();
        navMeshStarted = true;
        _lastNavMeshBuildTime = currentTime;
        for (U8 i = 0; i < 2; ++i) {
            _faction[i]->clearOrders();
            for(AI::WarSceneOrder* order : _orders[i]) {
                _faction[i]->addOrder(order);
            }
        }
    } else {    
        stringImpl info("Can't reload the navigation mesh this soon.\n Please wait \\[ ");
        info.append(Util::toString(getUsToSec<U64>(diffTime)).c_str());
        info.append(" ] seconds more!");

        _infoBox->setMessage(info);
        _infoBox->setMessageType(GUIMessageBox::MESSAGE_WARNING);
        _infoBox->show();
    }
    AI::AIManager::getInstance().pauseUpdate(false);
}

void WarScene::processInput(const U64 deltaTime){
}

void WarScene::updateSceneStateInternal(const U64 deltaTime){
    if (!_sceneReady) {
        return;
    }
    static U64 totalTime = 0;
    
    totalTime += deltaTime;

    /*if(_lampLightNode && _bobNodeBody){
        static mat4<F32> position = _lampLightNode->getComponent<PhysicsComponent>()->getWorldMatrix(); 
        const mat4<F32>& fingerPosition = _bobNodeBody->getAnimationComponent()->getBoneTransform("fingerstip.R");
        mat4<F32> finalTransform(fingerPosition * position);
        _lampLightNode->getComponent<PhysicsComponent>()->setTransforms(finalTransform.getTranspose());
    }*/
    
#ifdef _DEBUG
    if (!AI::AIManager::getInstance().getNavMesh(_army[0][0]->getAgentRadiusCategory())) {
        return;
    }

    _lines[DEBUG_LINE_OBJECT_TO_TARGET].resize(_army[0].size() + _army[1].size());
    //renderState().drawDebugLines(true);
    U32 count = 0;
    for (U8 i = 0; i < 2; ++i) {
        for(AI::AIEntity* character : _army[i]){
            _lines[DEBUG_LINE_OBJECT_TO_TARGET][count]._startPoint.set(character->getPosition());
            _lines[DEBUG_LINE_OBJECT_TO_TARGET][count]._endPoint.set(character->getDestination());
            _lines[DEBUG_LINE_OBJECT_TO_TARGET][count]._color.set(i == 1 ? 255 : 0, 0, i == 1 ? 0 : 255, 255);
            count++;
        }
    }
#endif
}

bool WarScene::load(const stringImpl& name, CameraManager* const cameraMgr, GUI* const gui){
    navMeshStarted = false;
    //Load scene resources
    bool loadState = SCENE_LOAD(name,cameraMgr,gui,true,true);
    //Add a light
	_sun = addLight(LIGHT_TYPE_DIRECTIONAL)->getNode<DirectionalLight>();
    //Add a skybox
	_currentSky = addSky(CreateResource<Sky>(ResourceDescriptor("Default Sky")));
    //Position camera
    renderState().getCamera().setEye(vec3<F32>(54.5f, 25.5f, 1.5f));
    renderState().getCamera().setGlobalRotation(-90/*yaw*/,35/*pitch*/);
    _sun->csmSplitCount(3); // 3 splits
    _sun->csmSplitLogFactor(0.925f);
    _sun->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]->getChildren().begin()).second->getComponent<RenderingComponent>();
        renderable->getMaterialInstance()->setDoubleSided(true);
        (*cylinder[i]->getChildren().begin()).second->getNode()->getMaterialTpl()->setDoubleSided(true);
    }

    SceneNode* cylinderMeshNW = cylinder[1]->getNode();
    SceneNode* cylinderMeshNE = cylinder[2]->getNode();
    SceneNode* cylinderMeshSW = cylinder[3]->getNode();
    SceneNode* cylinderMeshSE = cylinder[4]->getNode();

    std::string currentName;
    SceneNode* currentMesh = nullptr;
    SceneGraphNode* baseNode = nullptr;
    SceneGraphNode* currentNode = nullptr;
    std::pair<I32, I32> currentPos;
    for(U8 i = 0; i < 40; ++i){
        if(i < 10){
            baseNode = cylinder[1];
            currentMesh = cylinderMeshNW;
            currentName = "Cylinder_NW_" + Util::toString((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_" + Util::toString((I32)i);
            currentPos.first  =  200 - 40 * (i%10) - 50;
            currentPos.second = -200 + 40 * (i%10) + 50;
        }else if(i >= 20 && i < 30){
            baseNode = cylinder[3];
            currentMesh = cylinderMeshSW;
            currentName = "Cylinder_SW_" + Util::toString((I32)i);
            currentPos.first  = -200 + 40 * (i%20) + 50;
            currentPos.second =  200 - 40 * (i%20) - 50;
        }else{
            baseNode = cylinder[4];
            currentMesh = cylinderMeshSE;
            currentName = "Cylinder_SE_" + Util::toString((I32)i);
            currentPos.first  = 200 - 40 * (i%30) - 50;
            currentPos.second = 200 - 40 * (i%30) - 50;
        }

        currentNode = _sceneGraph->getRoot()->addNode(currentMesh, stringAlg::toBase(currentName));
        assert(currentNode);
        currentNode->setSelectable(true);
        currentNode->usageContext(baseNode->usageContext());
        PhysicsComponent* pComp = currentNode->getComponent<PhysicsComponent>();
        NavigationComponent* nComp = currentNode->getComponent<NavigationComponent>();
        pComp->physicsGroup(baseNode->getComponent<PhysicsComponent>()->physicsGroup());
        nComp->navigationContext(baseNode->getComponent<NavigationComponent>()->navigationContext());
        nComp->navigationDetailOverride(baseNode->getComponent<NavigationComponent>()->navMeshDetailOverride());
        
        pComp->setScale(baseNode->getComponent<PhysicsComponent>()->getScale());
        pComp->setPosition(vec3<F32>(currentPos.first, -0.01f, currentPos.second));
    }
    SceneGraphNode* baseFlagNode = cylinder[1];
    _flag[0] = _sceneGraph->getRoot()->addNode(cylinderMeshNW, "Team1Flag");
    _flag[0]->setSelectable(false);
    _flag[0]->usageContext(baseFlagNode->usageContext());
    PhysicsComponent* flagPComp = _flag[0]->getComponent<PhysicsComponent>();
    NavigationComponent* flagNComp = _flag[0]->getComponent<NavigationComponent>();
    flagPComp->physicsGroup(baseFlagNode->getComponent<PhysicsComponent>()->physicsGroup());
    flagNComp->navigationContext(NavigationComponent::NODE_IGNORE);
    flagPComp->setScale(baseFlagNode->getComponent<PhysicsComponent>()->getScale() * vec3<F32>(0.05f, 1.1f, 0.05f));
    flagPComp->setPosition(vec3<F32>(25.0f, 0.1f, -206.0f));


    _flag[1] = _sceneGraph->getRoot()->addNode(cylinderMeshNW, "Team2Flag");      
    _flag[1]->setSelectable(false);
    _flag[1]->usageContext(baseFlagNode->usageContext());

    flagPComp = _flag[1]->getComponent<PhysicsComponent>();
    flagNComp = _flag[1]->getComponent<NavigationComponent>();

    flagPComp->physicsGroup(baseFlagNode->getComponent<PhysicsComponent>()->physicsGroup());
    flagNComp->navigationContext(NavigationComponent::NODE_IGNORE);
    flagPComp->setScale(baseFlagNode->getComponent<PhysicsComponent>()->getScale() * vec3<F32>(0.05f, 1.1f, 0.05f));
    flagPComp->setPosition(vec3<F32>(25.0f, 0.1f, 206.0f));

    AI::WarSceneAISceneImpl::registerFlags(_flag[0], _flag[1]);

    /*_bobNode = _sceneGraph->findNode("Soldier3");
    _bobNodeBody = _sceneGraph->findNode("Soldier3_Bob.md5mesh-submesh-0");
    _lampLightNode = nullptr;
    if(_bobNodeBody != nullptr){
        ResourceDescriptor tempLight("Light_lamp");
        tempLight.setEnumValue(LIGHT_TYPE_POINT);
        // Create a point light for Bob's lamp
        /*Light* light = CreateResource<Light>(tempLight);
        light->setDrawImpostor(true);
        // Make it small and yellow
        light->setCastShadows(false);
        light->setRange(2.0f);
        light->setDiffuseColor(vec3<F32>(1.0f, 0.5f, 0.0f));
        _lampTransform = MemoryManager_NEW SceneTransform();
        // Add it to Bob's body
        _lampTransformNode = _bobNodeBody->addNode(_lampTransform, "lampTransform");
        _lampLightNode = addLight(light, _lampTransformNode);
        // Move it to the lamp's position
        _lampTransformNode->getComponent<PhysicsComponent>()->setPosition(vec3<F32>(-75.0f, -45.0f, -5.0f));
    }*/
    //------------------------ The rest of the scene elements -----------------------------///


    ParticleEmitterDescriptor particleSystem;
#ifdef _DEBUG
    particleSystem._particleCount = 200;
#else
    particleSystem._particleCount = 20000;
#endif
    particleSystem._spread = 5.0f;

	SceneGraphNode* testSGN = addParticleEmitter( "TESTPARTICLES", particleSystem, _sceneGraph->getRoot() );
	ParticleEmitter* test = testSGN->getNode<ParticleEmitter>();
    testSGN->getComponent<PhysicsComponent>()->translateY(5);
    test->setDrawImpostor(true);
    test->enableEmitter(true);

	state().getGeneralVisibility() *= 2;
	Application::getInstance().getKernel()->getCameraMgr().getActiveCamera()->setHorizontalFoV(135);

    _sceneReady = true;
    return loadState;
}

bool WarScene::initializeAI(bool continueOnErrors){
    //----------------------------Artificial Intelligence------------------------------//
 //   _GOAPContext.setLogLevel(AI::GOAPContext::LOG_LEVEL_NONE);

    // Create 2 AI teams
    for (U8 i = 0; i < 2; ++i) {
        _faction[i] = MemoryManager_NEW AI::AITeam(i);
    }
    // Make the teams fight each other
    _faction[0]->addEnemyTeam(_faction[1]->getTeamID());
    _faction[1]->addEnemyTeam(_faction[0]->getTeamID());

    SceneGraphNode* soldierNode1 = _sceneGraph->findNode("Soldier1");
    SceneGraphNode* soldierNode2 = _sceneGraph->findNode("Soldier2");
    SceneGraphNode* soldierNode3 = _sceneGraph->findNode("Soldier3");
    SceneNode* soldierMesh1 = soldierNode1->getNode();
    SceneNode* soldierMesh2 = soldierNode2->getNode();
    SceneNode* soldierMesh3 = soldierNode3->getNode();
    assert(soldierMesh1 && soldierMesh2 && soldierMesh3);

    vec3<F32> currentScale;
    NPC* soldier = nullptr;
    std::string currentName;
    AI::AIEntity* aiSoldier = nullptr;
    SceneNode* currentMesh = nullptr;
    SceneGraphNode* currentNode = nullptr;

	AI::ApproachFlag approachEnemyFlag("ApproachEnemyFlag");
	approachEnemyFlag.setPrecondition(AI::GOAPFact(AI::AtEnemyFlagLoc), AI::GOAPValue(false));
	approachEnemyFlag.setPrecondition(AI::GOAPFact(AI::HasEnemyFlag), AI::GOAPValue(false));
	approachEnemyFlag.setEffect(AI::GOAPFact(AI::AtEnemyFlagLoc), AI::GOAPValue(true));
	approachEnemyFlag.setEffect(AI::GOAPFact(AI::AtHomeFlagLoc), AI::GOAPValue(false));

    AI::CaptureFlag captureEnemyFlag("CaptureEnemyFlag");
	captureEnemyFlag.setPrecondition(AI::GOAPFact(AI::AtEnemyFlagLoc), AI::GOAPValue(true));
	captureEnemyFlag.setPrecondition(AI::GOAPFact(AI::HasEnemyFlag), AI::GOAPValue(false));
	captureEnemyFlag.setEffect(AI::GOAPFact(AI::HasEnemyFlag), AI::GOAPValue(true));
  
	AI::ReturnHome returnHome("ReturnHome");
	returnHome.setPrecondition(AI::GOAPFact(AI::AtHomeFlagLoc), AI::GOAPValue(false));
	returnHome.setEffect(AI::GOAPFact(AI::AtHomeFlagLoc), AI::GOAPValue(true));
	returnHome.setEffect(AI::GOAPFact(AI::AtEnemyFlagLoc), AI::GOAPValue(false));

    AI::ReturnFlag returnEnemyFlag("ReturnEnemyFlag");
	returnEnemyFlag.setPrecondition(AI::GOAPFact(AI::AtHomeFlagLoc), AI::GOAPValue(true));
	returnEnemyFlag.setPrecondition(AI::GOAPFact(AI::HasEnemyFlag), AI::GOAPValue(true));
	returnEnemyFlag.setEffect(AI::GOAPFact(AI::HasEnemyFlag), AI::GOAPValue(false));

	AI::RecoverFlag recoverFlag("RecoverOwnFlag");
	recoverFlag.setPrecondition(AI::GOAPFact(AI::EnemyDead), AI::GOAPValue(true));
	recoverFlag.setPrecondition(AI::GOAPFact(AI::EnemyHasFlag), AI::GOAPValue(false));
	recoverFlag.setEffect(AI::GOAPFact(AI::HasOwnFlag), AI::GOAPValue(true));
	
	AI::KillEnemy killEnemy("KillEnemy");
	recoverFlag.setPrecondition(AI::GOAPFact(AI::EnemyDead), AI::GOAPValue(false));
	recoverFlag.setEffect(AI::GOAPFact(AI::EnemyDead), AI::GOAPValue(true));

    AI::GOAPGoal findFlag("Find enemy flag");
	findFlag.setVariable(AI::GOAPFact(AI::AtEnemyFlagLoc), AI::GOAPValue(true));

    AI::GOAPGoal captureFlag("Capture enemy flag");
	captureFlag.setVariable(AI::GOAPFact(AI::HasEnemyFlag),   AI::GOAPValue(true));

    AI::GOAPGoal returnFlag("Return enemy flag");
	captureFlag.setVariable(AI::GOAPFact(AI::HasEnemyFlag),  AI::GOAPValue(true));
	captureFlag.setVariable(AI::GOAPFact(AI::AtHomeFlagLoc), AI::GOAPValue(true));

    AI::GOAPGoal retrieveFlag("Retrieve flag");
	retrieveFlag.setVariable(AI::GOAPFact(AI::HasOwnFlag), AI::GOAPValue(true));
    retrieveFlag.setVariable(AI::GOAPFact(AI::AtHomeFlagLoc), AI::GOAPValue(true));

    for(U8 k = 0; k < 2; ++k) {
        for(U8 i = 0; i < /*15*/1; ++i){
            F32 speed = 5.5f; // 5.5 m/s
            U8 zFactor = 0;
            if(i < 5){
                currentMesh = soldierMesh1;
                currentScale = soldierNode1->getComponent<PhysicsComponent>()->getScale();
                currentName = "Soldier_1_" + Util::toString((I32)k) + "_" + Util::toString((I32)i);
            }else if(i >= 5 && i < 10){
                currentMesh = soldierMesh2;
                currentScale = soldierNode2->getComponent<PhysicsComponent>()->getScale();
                currentName = "Soldier_2_" + Util::toString((I32)k) + "_" + Util::toString((I32)i%5);
                speed = 5.75f;
                zFactor = 1;
            }else{
                currentMesh = soldierMesh3;
                currentScale = soldierNode3->getComponent<PhysicsComponent>()->getScale();
                currentName = "Soldier_3_" + Util::toString((I32)k) + "_" + Util::toString((I32)i%10);
                speed = 5.35f;
                zFactor = 2;
            }

            currentNode = _sceneGraph->getRoot()->addNode(currentMesh, stringAlg::toBase(currentName));
            currentNode->getComponent<PhysicsComponent>()->setScale(currentScale);
            DIVIDE_ASSERT(currentNode != nullptr, "WarScene error: INVALID SOLDIER NODE TEMPLATE!");
            currentNode->setSelectable(true);
            I8 side = k == 0 ? -1 : 1;

            currentNode->getComponent<PhysicsComponent>()->setPosition(vec3<F32>(-125 + 25 * (i % 5), 
                                                                                 -0.01f,
                                                                                 200 * side + 25 * zFactor * side));
            if (side == 1) {
                 currentNode->getComponent<PhysicsComponent>()->rotateY(180);
                 currentNode->getComponent<PhysicsComponent>()->translateX(100);
            }
          
            currentNode->getComponent<PhysicsComponent>()->translateX(25 * side);

            aiSoldier = MemoryManager_NEW AI::AIEntity(currentNode->getComponent<PhysicsComponent>()->getPosition(),
                                                       currentNode->getName());
            aiSoldier->addSensor(AI::VISUAL_SENSOR);
            k == 0 ? currentNode->getComponent<RenderingComponent>()->renderBoundingBox(true) : 
                     currentNode->getComponent<RenderingComponent>()->renderSkeleton(true);

            AI::WarSceneAISceneImpl* brain = MemoryManager_NEW AI::WarSceneAISceneImpl();

			//GOAP
			brain->worldState().setVariable(AI::GOAPFact(AI::AtHomeFlagLoc),   AI::GOAPValue(true));
			brain->worldState().setVariable(AI::GOAPFact(AI::AtEnemyFlagLoc),  AI::GOAPValue(false));
			brain->worldState().setVariable(AI::GOAPFact(AI::HasEnemyFlag),    AI::GOAPValue(false));
			brain->worldState().setVariable(AI::GOAPFact(AI::EnemyDead),       AI::GOAPValue(false));
			brain->worldState().setVariable(AI::GOAPFact(AI::EnemyHasFlag),    AI::GOAPValue(false));
			brain->worldState().setVariable(AI::GOAPFact(AI::HasOwnFlag),      AI::GOAPValue(false));
			brain->worldState().setVariable(AI::GOAPFact(AI::FlagCarrierDead), AI::GOAPValue(false));

			brain->registerAction(&approachEnemyFlag);
			brain->registerAction(&captureEnemyFlag);
			brain->registerAction(&returnHome);
			brain->registerAction(&returnEnemyFlag);
			brain->registerAction(&recoverFlag);
			brain->registerAction(&killEnemy);
            brain->registerGoal(captureFlag);
            brain->registerGoal(findFlag);
			brain->registerGoal(returnFlag);
            brain->registerGoal(retrieveFlag);

            aiSoldier->addAISceneImpl(brain);
            soldier = MemoryManager_NEW NPC(currentNode, aiSoldier);
            soldier->setMovementSpeed(speed * 2); 
            _armyNPCs[k].push_back(soldier);
            _army[k].push_back(aiSoldier);
        }
    }

    //----------------------- AI controlled units ---------------------//
    for (U8 i = 0; i < 2; ++i) {
        for(U8 j = 0; j < _army[i].size(); ++j){
            AI::AIManager::getInstance().registerEntity(i, _army[i][j]);
        }
    }
    bool state = !(_army[0].empty() || _army[1].empty());

    if(state || continueOnErrors) {
        Scene::initializeAI(continueOnErrors);
    }
    _sceneGraph->getRoot()->deleteNode(soldierNode1);
    _sceneGraph->getRoot()->deleteNode( soldierNode2 );
    _sceneGraph->getRoot()->deleteNode( soldierNode3 );

    for (U8 i = 0; i < 2; ++i) {
        _orders[i].push_back(MemoryManager_NEW AI::WarSceneOrder(AI::WarSceneOrder::ORDER_FIND_ENEMY_FLAG));
        _orders[i].push_back(MemoryManager_NEW AI::WarSceneOrder(AI::WarSceneOrder::ORDER_CAPTURE_ENEMY_FLAG));
        _orders[i].push_back(MemoryManager_NEW AI::WarSceneOrder(AI::WarSceneOrder::ORDER_RETURN_ENEMY_FLAG));
        _orders[i].push_back(MemoryManager_NEW AI::WarSceneOrder(AI::WarSceneOrder::ORDER_PROTECT_FLAG_CARRIER));
        _orders[i].push_back(MemoryManager_NEW AI::WarSceneOrder(AI::WarSceneOrder::ORDER_RETRIEVE_FLAG));
    }

    return state;
}

bool WarScene::deinitializeAI(bool continueOnErrors){
    AI::AIManager::getInstance().pauseUpdate(true);

    while (AI::AIManager::getInstance().updating()) {
    }
    for (U8 i = 0; i < 2; ++i) {
        for (Divide::AI::AIEntity* entity : _army[i]) {
            AI::AIManager::getInstance().unregisterEntity(entity);
        }

        MemoryManager::DELETE_VECTOR(_armyNPCs[i]);
        MemoryManager::DELETE_VECTOR(_army[i]);
        MemoryManager::DELETE_VECTOR(_orders[i]);
        MemoryManager::DELETE( _faction[i] );
    }

    return Scene::deinitializeAI(continueOnErrors);
}

bool WarScene::unload(){
    return Scene::unload();
}

bool WarScene::loadResources(bool continueOnErrors){
    _GUI->addButton("Simulate", "Simulate", vec2<I32>(renderState().cachedResolution().width-220 ,
                                                      renderState().cachedResolution().height/1.1f),
                                                      vec2<U32>(100,25),vec3<F32>(0.65f),
                                                      DELEGATE_BIND(&WarScene::startSimulation,this));

    _GUI->addText("fpsDisplay",           //Unique ID
                  vec2<I32>(60,60),          //Position
                  Font::DIVIDE_DEFAULT,    //Font
                  vec3<F32>(0.0f,0.2f, 1.0f),  //Color
                  "FPS: %s",0);    //Text and arguments
    _GUI->addText("RenderBinCount",
                  vec2<I32>(60,70),
                  Font::DIVIDE_DEFAULT,
                  vec3<F32>(0.6f,0.2f,0.2f),
                  "Number of items in Render Bin: %d",0);

    _GUI->addText("camPosition",  vec2<I32>(60,100),
                  Font::DIVIDE_DEFAULT,
                  vec3<F32>(0.2f,0.8f,0.2f),
                  "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("lampPosition",  vec2<I32>(60,120),
                  Font::DIVIDE_DEFAULT,
                  vec3<F32>(0.2f,0.8f,0.2f),
                  "Lamp Position [ X: %5.0f | Y: %5.0f | Z: %5.0f ]",
                  0.0f, 0.0f, 0.0f);
    _infoBox = _GUI->addMsgBox("infoBox", "Info", "Blabla");
    //Add a first person camera
    Camera* cam = MemoryManager_NEW FirstPersonCamera();
    cam->fromCamera(renderState().getCameraConst());
    cam->setMoveSpeedFactor(10.0f);
    cam->setTurnSpeedFactor(10.0f);
    renderState().getCameraMgr().addNewCamera("fpsCamera", cam);
    //Add a third person camera
    cam = MemoryManager_NEW ThirdPersonCamera();
    cam->fromCamera(renderState().getCameraConst());
    cam->setMoveSpeedFactor(0.02f);
    cam->setTurnSpeedFactor(0.01f);
    renderState().getCameraMgr().addNewCamera("tpsCamera", cam);

    _guiTimers.push_back(0.0); //Fps
    _taskTimers.push_back(0.0); //animation bull
    _taskTimers.push_back(0.0); //animation dwarf
    _taskTimers.push_back(0.0); //animation bob
    return true;
}

bool WarScene::onKeyUp(const Input::KeyEvent& key){
    static bool fpsCameraActive = false;
    static bool tpsCameraActive = false;
    static bool flyCameraActive = true;

    bool keyState = Scene::onKeyUp(key);
    switch(key._key)	{
        default: break;

        case Input::KeyCode::KC_TAB:{
            if(_currentSelection != nullptr){
                /*if(flyCameraActive){
                    renderState().getCameraMgr().pushActiveCamera("fpsCamera");
                    flyCameraActive = false; fpsCameraActive = true;
                }else if(fpsCameraActive){*/
                if(flyCameraActive){
                    if(fpsCameraActive) renderState().getCameraMgr().popActiveCamera();
                    renderState().getCameraMgr().pushActiveCamera("tpsCamera");
                    static_cast<ThirdPersonCamera&>(renderState().getCamera()).setTarget(_currentSelection);
                    /*fpsCameraActive*/flyCameraActive = false; tpsCameraActive = true;
                    break;
                }
            }
            if (tpsCameraActive){
                renderState().getCameraMgr().pushActiveCamera("defaultCamera");
                tpsCameraActive = false; flyCameraActive = true;
            }
//			renderState().getCamera().setTargetNode(_currentSelection);
        }break;
    }
    return keyState;
}

bool WarScene::mouseMoved(const Input::MouseEvent& key){
    return Scene::mouseMoved(key);
}

bool WarScene::mouseButtonPressed(const Input::MouseEvent& key, Input::MouseButton button){
    return Scene::mouseButtonPressed(key,button);
}

bool WarScene::mouseButtonReleased(const Input::MouseEvent& key, Input::MouseButton button){
    return Scene::mouseButtonReleased(key,button);;
}

};

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

Diff revisions: vs.
Revision Author Commited Message
331 Diff Diff IonutCava picture IonutCava Sat 06 Dec, 2014 20:53:45 +0000

[Ionut]
- Limited line length to 132 characters to improve readability and diff-comparisons
- Refactored memory allocation/deallocation functions
- Fixed a few compatibility issues with HashMap.h
- Fixed a bug in GPU Skinning shaders (cast a float to int)

330 Diff Diff IonutCava picture IonutCava Fri 10 Oct, 2014 17:19:11 +0000

[Ionut]
- New rendering algorithm :
— Perform second pass for visible nodes gathering all render commands and uploading them to an indirect draw buffer
— Render geometry with indirect draw commands
— Removed per-node range binding of the node buffer. Instead, bind the entire buffer once and index data in shaders
— Use “baseInstance” parameter from IndirectDrawCommand as a node buffer index
— Prefer DSA extensions for updating buffer data where applicable
- Moved all rendering specific code from SceneGraphNode to a new RenderingComponent
- Optimized “toString” utility function

328 Diff Diff IonutCava picture IonutCava Sat 04 Oct, 2014 18:03:36 +0000

[Ionut]
- Added per SceneGraphNode material instances. (Cloned from the SceneNode’s material)
- Improved shader loading for materials

326 Diff Diff IonutCava picture IonutCava Tue 30 Sep, 2014 21:11:32 +0000

[Ionut]
- Fixed more memory leaks
- Simplified Task interface and timing System
- Improved compatibility between Boost, STL and EASTL with random combinations of vectors, strings and maps
- Simplified Light class by removing the “slot” member
- Random optimizations

325 Diff Diff IonutCava picture IonutCava Wed 17 Sep, 2014 20:06:13 +0000

[Ionut]
- Reworked transform system:
— Parent transform chain system moved from Transform class to the PhysicsComponent
— PhysicsComponent now returns all transform values needed both global and local (still needs heavy optimization and caching)

- Reworked SceneGraph node management:
— Proper ref counting of SceneNodes and proper removing of resource (ResourceCache is now empty on destruction, as it should be)
— Removed parent transform tracking as that’s the PhysicsComponent’s responsibility
— Only nodes loaded via the ResourceCache are allowed to be added to the SceneGraph (added proper loaders for Impostors, Sky, etc)

- Optimized some of the math classes (mat4, mat3)

324 Diff Diff IonutCava picture IonutCava Sun 14 Sep, 2014 14:01:39 +0000

[Ionut]
- New memory management system (no custom allocators in this commit)
— Memory tracer to detect memory leaks on shutdown (from: https://www.relisoft.com/book/tech/9new.html)
— SAFE_DELETE_XYZ are now inline template functions not macros
— ASSERTION system now supports logging and message boxes and continue on error configurable for each build type
— Fixed a lot of memory leaks detected by the new system (some still remain)

- Added SRGB support (part 1)
— Albedo textures are loaded as SRGB (make sure resources are SRGB)
— Shaders output gamma corrected colors
— Moved terrain textures back to 2 array system (albedo and normal maps, albedo maps using a SRGB sampler)

- Sky is now loaded via the ResourceCache system
- Added include safeguards in shader atoms

322 Diff Diff IonutCava picture IonutCava Sat 06 Sep, 2014 20:33:47 +0000

[Ionut]
- Refactored most of Boost related code to be C++11 based
— Boost is only used for ThreadPool, Mutex handling, XML parsing and networking (ASIO)
— Function binds, threads, regex, NonCopyable base, Hashing algorithms and more are now using C++11 libraries
- Replaced all FOR_EACH calls with standard, range, “for” calls

321 Diff Diff IonutCava picture IonutCava Wed 03 Sep, 2014 22:05:15 +0000

[Ionut]
- Added support (and enabled by default) for the EASTL library (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html / https://github.com/paulhodge/EASTL)
— Strings, vectors and hash_maps can be combined from EASTL, STL and Boost (not all combinations work. e.g. EASTL strings with STL/Boost containers due to the lack of a proper hash function)

320 Diff Diff IonutCava picture IonutCava Sun 31 Aug, 2014 21:45:33 +0000

[Ionut]
- More AI work (entity captures flag and returns it to base)

318 IonutCava picture IonutCava Sat 30 Aug, 2014 17:35:53 +0000

[Ionut]
- Wrapped the entire code in a “Divide” namespace
- VertexBuffers now call “shrink_to_fit” on all internal data storage
- Improved some vector performance by preferring “emplace_back” instead of “push_back” + proepr usage of reserve / resize
- Wrapped OIS specific types and classes in Divide::Input namespace
- Added the messageBox.layout file (forgot it in the previous few commits)