-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathWorld.cpp
More file actions
executable file
·2194 lines (1977 loc) · 102 KB
/
Copy pathWorld.cpp
File metadata and controls
executable file
·2194 lines (1977 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Created by Engin Manap on 13.02.2016.
//
#include "World.h"
#include "Graphics/TransformTextureRing.h"
#include "WorldAPIAccessor.h"
#include <Graphics/GraphicsPipeline.h>
#include "NodeEditorExtensions/PipelineStageExtension.h"
#include "Material.h"
#include "Camera/PerspectiveCamera.h"
#include "Camera/OrthographicCamera.h"
#include "limonAPI/CameraExtensionInterface.h"
#include "GameObjects/CameraRig.h"
#include "BulletDebugDrawer.h"
#include "AI/AIMovementGrid.h"
#include "GameObjects/Players/FreeCursorPlayer.h"
#include "GameObjects/Players/FreeMovingPlayer.h"
#include "GameObjects/Players/PhysicalPlayer.h"
#include "GameObjects/Players/MenuPlayer.h"
#include "GameObjects/Players/EditorPlayer.h"
#include "GameObjects/Light.h"
#include "GUI/GUILayer.h"
#include "GUI/GUITextBase.h"
#include "GUI/GUITextDynamic.h"
#include "ImGuiHelper.h"
#include "GameObjects/TriggerObject.h"
#include "Assets/Animations/AnimationCustom.h"
#include "AnimationSequencer.h"
#include "GUI/GUICursor.h"
#include "GameObjects/GUIText.h"
#include "GameObjects/GUIButton.h"
#include "GameObjects/ModelGroup.h"
#include "Graphics/PostProcess/QuadRender.h"
#include "Editor/Editor.h"
#include "Editor/ProfilerUI.h"
#include "Occlusion/RenderList.h"
#include "Occlusion/VisibilityManager.h"
#include "Profiler/ProfilerMacros.h"
#include "Profiler/RenderProfileScope.h"
#include "Utils/FrameTimeTracker.h"
#include "XMLHelper.h"
#include "GamePlay/APISerializer.h"
const std::map<World::PlayerInfo::Types, std::string> World::PlayerInfo::typeNames =
{
{ Types::PHYSICAL_PLAYER, "Physical"},
{ Types::DEBUG_PLAYER, "Debug"},
{ Types::EDITOR_PLAYER, "Editor"},
{ Types::MENU_PLAYER, "Menu" }
};
void World::PlayerInfo::serialize(tinyxml2::XMLDocument &document, tinyxml2::XMLNode *worldNode) const {
tinyxml2::XMLElement *playerNode = document.NewElement("Player");
tinyxml2::XMLElement *playerType = document.NewElement("Type");
playerType->SetText(typeToString().c_str());
playerNode->InsertEndChild(playerType);
tinyxml2::XMLElement *playerPosition = document.NewElement("Position");
XMLHelper::writeVec3(document, playerPosition, position);
playerNode->InsertEndChild(playerPosition);
tinyxml2::XMLElement *playerOrientation = document.NewElement("Orientation");
XMLHelper::writeVec3(document, playerOrientation, orientation);
playerNode->InsertEndChild(playerOrientation);
tinyxml2::XMLElement *playerExtension = document.NewElement("ExtensionName");
playerExtension->SetText(extensionName.c_str());
playerNode->InsertEndChild(playerExtension);
tinyxml2::XMLElement *playerExtensionParameters = document.NewElement("ExtensionParameters");
for (size_t i = 0; i < parameters.size(); ++i) {
APISerializer::serializeParameterRequest(parameters[i], document, playerExtensionParameters, i);
}
playerNode->InsertEndChild(playerExtensionParameters);
worldNode->InsertEndChild(playerNode);
}
void World::setupRenderForPipeline() const {
}
/**
* We don't want attachments to an object, to try to collide with the parent. We use this method to prevent it.
* We are setting the userIndex for marking the objects, then we filter those in the broad phase
*/
struct HierarchyFilterCallback : public btOverlapFilterCallback {
bool needBroadphaseCollision(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) const override {
bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
if (!collides) {
return false;
}
//group/mask first, so the common reject never touches the collision objects
int rootIndex0 = static_cast<const btCollisionObject*>(proxy0->m_clientObject)->getUserIndex();
int rootIndex1 = static_cast<const btCollisionObject*>(proxy1->m_clientObject)->getUserIndex();
return rootIndex0 <= 0 || rootIndex0 != rootIndex1;
}
};
World::World(const std::string &name, PlayerInfo startingPlayerType, InputHandler *inputHandler,
std::shared_ptr<AssetManager> assetManager, OptionsUtil::Options *options, ProfilerSystem* profilerSystem, FrameTimeTracker* frameTimeTracker,
TransformTextureRing* modelTransformRing, TransformTextureRing* boneTransformRing,
LimonAPI *limonAPI)
: assetManager(assetManager), options(options), profilerSystem(profilerSystem), frameTimeTracker(frameTimeTracker),
modelTransformRing(modelTransformRing), boneTransformRing(boneTransformRing),
graphicsWrapper(assetManager->getGraphicsWrapper()), alHelper(assetManager->getAlHelper()), name(name),
fontManager(graphicsWrapper), startingPlayer(startingPlayerType) {
// apiAccessor is an indirection, in case someone wants to use it while construction, we need it first
apiAccessor = new WorldAPIAccessor(this, limonAPI);
editor = std::make_unique<Editor>(this);
// physics init
broadphase = new btDbvtBroadphase();
ghostPairCallback = new btGhostPairCallback();
broadphase->getOverlappingPairCache()->setInternalGhostPairCallback(
ghostPairCallback); // Needed once to enable ghost objects inside Bullet
collisionConfiguration = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collisionConfiguration);
solver = new btSequentialImpulseConstraintSolver;
dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
hierarchyFilterCallback = new HierarchyFilterCallback();
dynamicsWorld->getPairCache()->setOverlapFilterCallback(hierarchyFilterCallback);
dynamicsWorld->setGravity(btVector3(0, -10, 0));
debugDrawer = new BulletDebugDrawer(assetManager, options);
dynamicsWorld->setDebugDrawer(debugDrawer);
dynamicsWorld->getDebugDrawer()->setDebugMode(dynamicsWorld->getDebugDrawer()->DBG_NoDebug);
//dynamicsWorld->getDebugDrawer()->setDebugMode(dynamicsWorld->getDebugDrawer()->DBG_MAX_DEBUG_DRAW_MODE);
apiGUILayer = new GUILayer(graphicsWrapper, debugDrawer, 1);
apiGUILayer->setDebug(false);
renderCounts = new GUIText(graphicsWrapper, getNextObjectID(), "Render Counts",
fontManager.getFont("./Data/Fonts/Cousine-Regular.ttf", 16), "0", glm::vec3(204, 204, 0));
renderCounts->set2dWorldTransform(glm::vec2(options->getScreenWidth() - 170, options->getScreenHeight() - 36), 0);
cursor = new GUICursor(graphicsWrapper, assetManager, "./Data/Textures/crosshair.png");
cursor->set2dWorldTransform(glm::vec2(options->getScreenWidth()/2.0f, options->getScreenHeight()/2.0f), 0);
debugOutputGUI = new GUITextDynamic(graphicsWrapper, fontManager.getFont("./Data/Fonts/Helvetica-Normal.ttf", 16),
glm::vec3(0, 0, 0), 640, 380, options);
debugOutputGUI->set2dWorldTransform(glm::vec2(320, options->getScreenHeight()-200), 0.0f);
//the starting player is the one that owns the ID and carries the attachments, the modes switched into don't
switch(startingPlayer.type) {
case PlayerInfo::Types::PHYSICAL_PLAYER:
physicalPlayer = new PhysicalPlayer(options, cursor, startingPlayer.position, startingPlayer.orientation, LimonAPI::PLAYER_OBJECT_ID);
currentPlayer = physicalPlayer;
break;
case PlayerInfo::Types::DEBUG_PLAYER:
debugPlayer = new FreeMovingPlayer(options, cursor, startingPlayer.position, startingPlayer.orientation, LimonAPI::PLAYER_OBJECT_ID);
currentPlayer = debugPlayer;
break;
case PlayerInfo::Types::EDITOR_PLAYER:
editorPlayer = new EditorPlayer(options, cursor, startingPlayer.position, startingPlayer.orientation, inputHandler, LimonAPI::PLAYER_OBJECT_ID);
currentPlayer = editorPlayer;
break;
case PlayerInfo::Types::MENU_PLAYER:
menuPlayer = new MenuPlayer(options, cursor, startingPlayer.position, startingPlayer.orientation, LimonAPI::PLAYER_OBJECT_ID);
currentPlayer = menuPlayer;
break;
}
currentPlayer->updateTransformation();
quadRender = std::make_shared<QuadRender>(graphicsWrapper);
visibilityManager = std::make_unique<VisibilityManager>(this);
//FIXME adding camera after dynamic world because static only world is needed for ai movement grid generation
activateCameraAttachment(currentPlayer->getCameraAttachment());//creates playerCamera + registers it
currentPlayer->registerToPhysicalWorld(dynamicsWorld, COLLIDE_PLAYER,
COLLIDE_MODELS | COLLIDE_TRIGGER_VOLUME | COLLIDE_EVERYTHING,
COLLIDE_MODELS | COLLIDE_EVERYTHING, worldAABBMin,
worldAABBMax);
switchPlayer(currentPlayer, *inputHandler); //switching to itself, to set the states properly. It uses camera so done after camera creation
OptionsUtil::Options::Option<std::string> renderPipelineOption = options->getOption<std::string>(HASH("render_pipeline"));
std::vector<std::string> pipelineLoadErrors;
renderPipeline = GraphicsPipeline::deserialize(renderPipelineOption.getOrDefault(""), graphicsWrapper, assetManager, options, buildRenderMethods(), pipelineLoadErrors);
if(renderPipeline == nullptr) {
//use default if no custom is found
std::cerr << "Render pipeline can't be used, loading default." << std::endl;
renderPipeline = GraphicsPipeline::deserialize("./Engine/renderPipeline.xml", graphicsWrapper, assetManager, options, buildRenderMethods(), pipelineLoadErrors);
}
if(renderPipeline == nullptr) {
//only draws ImGui, so the editor is still there to fix the pipeline
std::cerr << "Default render pipeline can't be used either, loading the editor only pipeline." << std::endl;
renderPipeline = GraphicsPipeline::deserialize("./Engine/imguiOnlyRenderPipeline.xml", graphicsWrapper, assetManager, options, buildRenderMethods(), pipelineLoadErrors);
if (renderPipeline == nullptr) {
std::cerr << "Editor only render pipeline can't be loaded, please check if your installation is correct. Exiting" << std::endl;
std::exit(-1);
}
setupRenderForPipeline();
createEditorPlayerIfMissing(*inputHandler);
switchPlayer(editorPlayer, *inputHandler);
editor->showPipelineFallback(renderPipeline, pipelineLoadErrors);
} else {
setupRenderForPipeline();
}
onLoadActions.push_back(new ActionForOnload());//this is here for editor, as if no action is added, editor would fail to allow setting the first one.
modelIndicesBuffer.reserve(NR_MAX_MODELS);
tempRenderedObjectsSet.reserve(NR_MAX_MODELS);
renderInformationsOption = options->getOption<bool>(HASH("debug_renderInformations"));
maxLightsOption = options->getOption<long>(HASH("performance_maximumLights"));
activeLights.reserve(maxLightsOption.getOrDefault(4));
soundVolumeOptions[(size_t)LimonTypes::AudioChannel::MASTER] = options->getOption<double>(HASH("audio_volumeMaster"));
soundVolumeOptions[(size_t)LimonTypes::AudioChannel::MUSIC] = options->getOption<double>(HASH("audio_volumeMusic"));
soundVolumeOptions[(size_t)LimonTypes::AudioChannel::SFX] = options->getOption<double>(HASH("audio_volumeSFX"));
soundVolumeOptions[(size_t)LimonTypes::AudioChannel::SPEECH] = options->getOption<double>(HASH("audio_volumeSpeech"));
soundVolumeOptions[(size_t)LimonTypes::AudioChannel::AMBIENT] = options->getOption<double>(HASH("audio_volumeAmbient"));
}
void World::applyAudioVolumeOptionsIfChanged() {
// Options are the source of truth; push any changes down to the audio mixer. Cheap no-op when unchanged.
for (size_t channel = 0; channel < (size_t)LimonTypes::AudioChannel::COUNT; ++channel) {
float volume = (float)soundVolumeOptions[channel].getOrDefault(1.0);
if (volume != appliedChannelVolumes[channel]) {
alHelper->setChannelGain((LimonTypes::AudioChannel)channel, volume);
appliedChannelVolumes[channel] = volume;
}
}
}
RenderMethods World::buildRenderMethods() {
RenderMethods renderMethods;
renderMethods.renderParticleEmitters = std::bind(&World::renderParticleEmitters, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
renderMethods.renderGPUParticleEmitters = std::bind(&World::renderGPUParticleEmitters, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
renderMethods.renderGUITexts = std::bind(&World::renderGUITexts, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
renderMethods.renderGUIImages = std::bind(&World::renderGUIImages, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
renderMethods.renderEditor = std::bind(&World::ImGuiFrameSetup, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
renderMethods.renderSky = std::bind(&World::renderSky, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
renderMethods.renderDebug = std::bind(&World::renderDebug, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
renderMethods.renderCameraByTag = std::bind(&World::renderCameraByTag, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
renderMethods.renderQuad = std::bind(&QuadRender::render, this->quadRender, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
renderMethods.getLightsByType = std::bind(&World::getLightIndexes, this, std::placeholders::_1);
renderMethods.renderLight = std::bind(&World::renderLight, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
return renderMethods;
}
bool World::checkPlayerVisibility(const glm::vec3 &from, const std::string &fromName) {
//FIXME this debug draw creates a flicker, because we redraw frames that surpass 60. we need duration for debug draw to prevent it
//debugDrawer->drawLine(GLMConverter::GLMToBlt(from), camera.getRigidBody()->getCenterOfMassPosition(), btVector3(1,0,0));
btCollisionWorld::AllHitsRayResultCallback RayCallback(GLMConverter::GLMToBlt(from), GLMConverter::GLMToBlt(currentPlayer->getPosition()));
dynamicsWorld->rayTest(
GLMConverter::GLMToBlt(from),
GLMConverter::GLMToBlt(currentPlayer->getPosition()),
RayCallback
);
if (RayCallback.hasHit()) {
btVector3 closestDistance = btVector3(std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
bool hasSeen = false;
for (int i = 0; i < RayCallback.m_collisionObjects.size(); ++i) {//it turns out, the hits are not ordered, so keep what we see
btVector3 distance = RayCallback.m_hitPointWorld[i] - RayCallback.m_rayFromWorld;
if(distance.length2() < closestDistance.length2()) {//length2 doesn't invoke sqtr, so it should be faster
GameObject *gameObject = static_cast<GameObject *>(RayCallback.m_collisionObjects[i]->getUserPointer());
if(gameObject->getName() == fromName) {
continue; //self should not change closest hit
}
closestDistance = distance;
if (gameObject->getTypeID() != GameObject::ObjectTypes::PLAYER && gameObject->getTypeID() != GameObject::ObjectTypes::TRIGGER ) { //trigger is ghost, so it should not block
if(hasSeen) {
//means we saw the player, and this is closer than player
return false;
}
}
if (gameObject->getTypeID() == GameObject::ObjectTypes::PLAYER) {
hasSeen = true;
}
}
}
return hasSeen;
}
return false;//if ray did not hit anything, return false. This should never happen
}
/**
* Simulates given time (it should be constantant), reads input, animates models etc.
* Returns true if quit requested.
* @param simulationTimeFrame
* @param inputHandler
* @return
*/
void World::play(InputHandler &inputHandler, uint32_t wallTimeMs) {
// we need to apply the defferred aseet changes, like convertion to limonmodel, or LOD overrides.
// If we put it after the editor update, quit request would have skipped the limonModel conversion, so in the beginning.
editor->applyDeferredAssetChanges();
PROFILE_SIMULATION("World::play");
{
PROFILE_SIMULATION("World::play::PlayerInput");
editor->update(inputHandler);
}
this->wallTime = wallTimeMs;
//Seperating physics step and visibility, because physics is used by camera, and camera is used by visibility
if(currentPlayersSettings->worldSimulation) {
++simulatedTicks;
//we used 1000 but that causes calculation to overflow around 20 hours. using ULL so calculation itself will be 64 bits, then 60*20 hours is like 2 months, so we don't care
gameTime = (uint32_t)(simulatedTicks * 1000ULL / TICK_PER_SECOND);
{
PROFILE_SIMULATION("World::play::PhysicsSimulation");
dynamicsWorld->stepSimulation(1.0f / TICK_PER_SECOND, 0);
}
{
PROFILE_SIMULATION("World::play::PlayerPhysicsSync");
currentPlayer->processPhysicsWorld(dynamicsWorld);
}
}
{
PROFILE_SIMULATION("World::play::TimedEvents");
checkAndRunTimedEvents();//no londer requires to be in world simulation, because it checks both game time and wall time now
}
applyAudioVolumeOptionsIfChanged();
currentPlayer->updateTransformation();
// Feed the active rig its attachment-target transform, or sync the player's default camera if no rig is active.
feedActiveCameraRig();
if(currentPlayersSettings->worldSimulation) {
{
PROFILE_SIMULATION("World::play::Emitters");
for(const auto& emitter:emitters) {
emitter.second->setupForTime(gameTime);
}
for(const auto& gpuEmitter:gpuParticleEmitters) {
gpuEmitter.second->setupForTime(gameTime);
}
}
{
PROFILE_SIMULATION("World::play::Triggers");
for(auto trigger = triggers.begin(); trigger != triggers.end(); trigger++) {
trigger->second->checkAndTrigger();
}
}
animateCustomAnimations();
{
PROFILE_SIMULATION("World::play::Actors");//self time here is the actor code, fillActorInformation has its own zone
for(auto actorIt = actors.begin(); actorIt != actors.end(); ++actorIt) {
ActorInterface::ActorInformation information = fillActorInformation(actorIt->second);
actorIt->second->play(gameTime, information);
}
}
{
PROFILE_SIMULATION("World::play::TransformFromPhysics");
for (auto it = objects.begin(); it != objects.end(); ++it) {
if (!it->second->getRigidBody()->isStaticOrKinematicObject() && it->second->getRigidBody()->isActive()) {
it->second->updateTransformFromPhysics();
}
}
}
{
PROFILE_SIMULATION("World::play::AnimationClocks");
for (auto it = objects.begin(); it != objects.end(); ++it) {
if (it->second->isAnimated()) {
it->second->advanceAnimationClock(gameTime);
}
}
}
{
PROFILE_SIMULATION("World::play::PhysicsActivation");
collectPhysicsActivatedModels();
}
{
PROFILE_SIMULATION("World::play::EvaluatePoses");
tempRenderedObjectsSet.clear();//models whose pose is already evaluated this tick
for (const auto &visibility: visibilityManager->getCullingResults()) {
for (auto &visibleTags: *visibility.second){
for (auto it = visibleTags.second.getIterator(); !it.isEnd(); ++it) {
for (glm::uvec4 meshRenderInfo:it.get().indices) {
evaluatePoseOnce(meshRenderInfo.x);
}
}
}
}
for (uint32_t modelID : physicsSimulationActiveModels) {
evaluatePoseOnce(modelID);
}
for (uint32_t modelID : physicsActivatedModels) {
evaluatePoseOnce(modelID);
}
}
{
PROFILE_SIMULATION("World::play::AnimatedSleepStates");
updateAnimatedSleepStates();
}
}
{
PROFILE_SIMULATION("World::play::GUI");//menu interaction raycasts every tick
for (unsigned int i = 0; i < guiLayers.size(); ++i) {
guiLayers[i]->setupForTime(gameTime);
}
debugOutputGUI->setupForTime(wallTime);//logger is global, so no game time for it
if(currentPlayersSettings->menuInteraction) {
GUIButton* button = nullptr;
GameObject* pointed = this->getPointedObject(COLLIDE_EVERYTHING, ~(COLLIDE_NOTHING));
if(pointed != nullptr && pointed->getTypeID() == GameObject::ObjectTypes::GUI_BUTTON) {
button = dynamic_cast<GUIButton*>(pointed);
}
if(button != nullptr) {
if(this->hoveringButton != button) {
if(this->hoveringButton != nullptr) {
this->hoveringButton->setOnHover(false);
this->hoveringButton->setOnClick(false);
}
}
this->hoveringButton = button;
button->setOnHover(true);
if(inputHandler.getInputStates().getInputStatus(InputActions::MOUSE_BUTTON_LEFT)) {
if(inputHandler.getInputStates().getInputEvents(InputActions::MOUSE_BUTTON_LEFT)) {
button->setOnClick(true);
}
} else {
button->setOnClick(false);
}
} else {
if(this->hoveringButton != nullptr) {
this->hoveringButton->setOnHover(false);
this->hoveringButton->setOnClick(false);
}
}
}
}
}
void World::prepareFrame() {
PROFILE_VISIBILITY("World::prepareFrame");
CameraAttachment* playerCameraAttachment = currentPlayer->getCameraAttachment();
if (playerCameraAttachment->isDirty() && playerCameraAttachment->getProjection() != activeProjectionParameters) {
activateCameraAttachment(playerCameraAttachment);//otherwise fov/zoom/type changes are only seen when a rig is activated
}
if(playerCamera->isDirty()) {
// update player camera and upload the ubo
const glm::mat4& cameraMatrix = playerCamera->getCameraMatrix();
graphicsWrapper->setPlayerMatrices(playerCamera->getPosition(), cameraMatrix, playerCamera->getProjectionMatrix(), gameTime);//this is required for any render
alHelper->setListenerPositionAndOrientation(playerCamera->getPosition(), playerCamera->getCenter(), playerCamera->getUp());
} else {
graphicsWrapper->setCurrentTime(gameTime);//setPlayerMatrices pushes everything, this one pushes time only
}
bool lightsRemoved = applyPendingLightRemovals();
updateActiveLights(lightsRemoved);//adds and removes light cameras, so it has to run before the culling pass
for (size_t j = 0; j < activeLights.size(); ++j) {
activeLights[j]->step(gameTime, playerCamera);
}
uploadActiveLightsToGPU();
visibilityManager->update();
playerCamera->clearDirty();
if(sky != nullptr) { // menu worlds don't have sky set, and WIP levels can miss it too.
sky->step(playerCamera);
}
uploadChangedTransforms();
}
void World::uploadChangedTransforms() {
for (Model* model : pendingTransformUploads) {
setModelTransform(model->getWorldObjectID(), model->getTransformation()->getWorldTransform());
}
pendingTransformUploads.clear();
//the culling pass filled changedBoneTransforms, only rigs that passed culling are in it
for (auto& boneTransformPair: changedBoneTransforms) {
setBoneTransforms(boneTransformPair.first, *(boneTransformPair.second));
}
changedBoneTransforms.clear();
uploadTransformTextures();
}
void World::setModelTransform(uint32_t modelID, const glm::mat4& worldTransform) {
if (modelID >= NR_MAX_MODELS) {
std::cerr << "Model ID " << modelID << " is past the model transform texture, it can't be rendered." << std::endl;
return;
}
const uint32_t rowWidth = 4 * NR_MAX_MODELS;
const glm::mat4 normalMatrix = glm::transpose(glm::inverse(worldTransform));
for (uint32_t column = 0; column < 4; ++column) {
modelTransformTexels[4 * modelID + column] = worldTransform[column];
modelTransformTexels[rowWidth + 4 * modelID + column] = column < 3 ? normalMatrix[column] : glm::vec4(0.0f);
}
usedModelTransformColumns = std::max(usedModelTransformColumns, 4 * (modelID + 1));
}
void World::setBoneTransforms(uint32_t rigID, const std::vector<glm::mat4>& boneTransforms) {
if (rigID >= NR_MAX_MODELS) {
std::cerr << "Rig ID " << rigID << " is past the bone transform texture, it can't be rendered." << std::endl;
return;
}
if (boneTransforms.size() > NR_BONE) {
std::cerr << "Too many bones, can't upload more than " << NR_BONE << " ignoring the rest." << std::endl;
}
const uint32_t rowWidth = 4 * NR_BONE;
if (boneTransformTexels.size() < (rigID + 1) * rowWidth) {
boneTransformTexels.resize((rigID + 1) * rowWidth);
}
const size_t copiedBoneCount = std::min(boneTransforms.size(), static_cast<size_t>(NR_BONE));
for (size_t boneIndex = 0; boneIndex < NR_BONE; ++boneIndex) {
for (uint32_t column = 0; column < 4; ++column) {
boneTransformTexels[rigID * rowWidth + 4 * boneIndex + column] = boneIndex < copiedBoneCount ? boneTransforms[boneIndex][column] : glm::vec4(0.0f);
}
}
usedBoneTransformRows = std::max(usedBoneTransformRows, rigID + 1);
}
//the rings are shared with other worlds, so this always sends everything we have, not only what changed
void World::uploadTransformTextures() {
modelTransformRing->upload(modelTransformTexels, usedModelTransformColumns, 2);
boneTransformRing->upload(boneTransformTexels, 4 * NR_BONE, usedBoneTransformRows);
}
void World::animateCustomAnimations() {
PROFILE_SIMULATION("World::animateCustomAnimations");
// ATTENTION iterator is not increased in for, it is done manually.
for(auto animIt = activeAnimations.begin(); animIt != activeAnimations.end();) {
AnimationStatus* animationStatus = animIt->second;
if(animationStatus->originChange) {
//this means the origin has changed in editor mode, so we should update our origin of transformation.
// First change the original transform to current, since user updated it
//composed in local space, the original may sit on a real parent and world values would apply it twice
glm::vec3 originTranslate, originScale;
glm::quat originOrientation;
composeAnimationLocal(animationStatus->originalTransformation, *animationStatus->object->getTransformation(),
originTranslate, originScale, originOrientation);
animationStatus->originalTransformation.setTransformations(originTranslate, originScale, originOrientation);
//then remove the change from object transform.
animationStatus->object->getTransformation()->setTransformations(glm::vec3(0.0f,0.0f,0.0f)
, glm::vec3(1.0f,1.0f,1.0f)
, glm::quat(1.0f,0.0f,0.0f, 0.0f));
animationStatus->originChange = false;
}
const AnimationCustom* animationCustom = &loadedAnimations[animationStatus->animationIndex];
if((animationStatus->loop ) || animationCustom->getDuration() / animationCustom->getTicksPerSecond() * 1000 + animationStatus->startTime >
gameTime) {
float ticksPerSecond;
if (animationCustom->getTicksPerSecond() != 0) {
ticksPerSecond = animationCustom->getTicksPerSecond();
} else {
ticksPerSecond = TICK_PER_SECOND;
}
float animationTime = fmod(((gameTime - animationStatus->startTime) / 1000.0f) * ticksPerSecond, animationCustom->getDuration());
animationCustom->calculateTransform("", animationTime, *animationStatus->object->getTransformation());
if(animationStatus->sound) {
animationStatus->sound->setWorldPosition(
animationStatus->object->getTransformation()->getTranslate());
}
animIt++;
} else {
//animation finish case, set final transform and remove
float animationTime = animationCustom->getDuration();
animationCustom->calculateTransform("", animationTime, *animationStatus->object->getTransformation());
if(animationStatus->sound) {
animationStatus->sound->stop();
}
finishCustomAnimation(animationStatus);
options->getLogger()->log(Logger::log_Subsystem_ANIMATION, Logger::log_level_DEBUG, "Animation " + animationCustom->getName() + " finished, removing. ");
delete animIt->second;
animIt = activeAnimations.erase(animIt);
}
}
}
void World::collectPhysicsActivatedModels() {
physicsActivatedModels.clear();
//pairs exist on AABB overlap whatever the activation state, so this can't feed back through our own wake ups
btBroadphasePairArray& pairs = dynamicsWorld->getPairCache()->getOverlappingPairArray();
for (int pairIndex = 0; pairIndex < pairs.size(); ++pairIndex) {
const btCollisionObject* object0 = static_cast<const btCollisionObject*>(pairs[pairIndex].m_pProxy0->m_clientObject);
const btCollisionObject* object1 = static_cast<const btCollisionObject*>(pairs[pairIndex].m_pProxy1->m_clientObject);
markActivatedByPair(object0, object1);
markActivatedByPair(object1, object0);
}
}
void World::markActivatedByPair(const btCollisionObject *candidate, const btCollisionObject *other) {
const btRigidBody* otherBody = btRigidBody::upcast(other);
if (otherBody == nullptr || otherBody->isStaticOrKinematicObject() || !otherBody->isActive() || !otherBody->hasContactResponse()) {
return;
}
if (candidate->getUserPointer() == nullptr) {
return;
}
Model* model = dynamic_cast<Model*>(static_cast<GameObject*>(candidate->getUserPointer()));
if (model != nullptr && model->isAnimated()) {
physicsActivatedModels.push_back(model->getWorldObjectID());
}
}
void World::evaluatePoseOnce(uint32_t modelID) {
if (tempRenderedObjectsSet.find(modelID) != tempRenderedObjectsSet.end()) {
return;
}
objects.at(modelID)->evaluatePose();
tempRenderedObjectsSet.insert(modelID);
}
void World::updateAnimatedSleepStates() {
for (auto it = objects.begin(); it != objects.end(); ++it) {
Model* model = it->second;
//parented or custom animated bodies move without their pose being evaluated, asleep they would pass through sleeping bodies
if (!model->isAnimated() || model->getParentObject() != nullptr || model->getCustomAnimation() || model->isDisconnected()) {
continue;
}
btRigidBody* body = model->getRigidBody();
//a kinematic body that isn't sleeping wakes everything it shares a manifold with, even a frozen one
const bool poseEvaluated = tempRenderedObjectsSet.find(it->first) != tempRenderedObjectsSet.end();
if (poseEvaluated && body->getActivationState() == ISLAND_SLEEPING) {
body->forceActivationState(DISABLE_DEACTIVATION);
} else if (!poseEvaluated && body->getActivationState() != ISLAND_SLEEPING) {
body->forceActivationState(ISLAND_SLEEPING);
}
}
}
void World::composeAnimationLocal(const Transformation &originalTransformation, const Transformation &animatedTransformation,
glm::vec3 &translate, glm::vec3 &scale, glm::quat &orientation) {
glm::mat4 originalLocal = glm::translate(glm::mat4(1.0f), originalTransformation.getTranslateSingle()) *
glm::mat4_cast(originalTransformation.getOrientationSingle()) *
glm::scale(glm::mat4(1.0f), originalTransformation.getScaleSingle());
glm::mat4 animatedLocal = glm::translate(glm::mat4(1.0f), animatedTransformation.getTranslateSingle()) *
glm::mat4_cast(animatedTransformation.getOrientationSingle()) *
glm::scale(glm::mat4(1.0f), animatedTransformation.getScaleSingle());
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(originalLocal * animatedLocal, scale, orientation, translate, skew, perspective);
orientation = glm::normalize(orientation);
}
void World::finishCustomAnimation(AnimationStatus *animationStatus) {
Transformation* objectTransformation = animationStatus->object->getTransformation();
glm::vec3 translate, scale;
glm::quat orientation;
composeAnimationLocal(animationStatus->originalTransformation, *objectTransformation, translate, scale, orientation);
//the original is a copy of the object's transform, so it holds the link to the real parent
Transformation* realParent = animationStatus->originalTransformation.getParentTransform();
objectTransformation->removeParentTransform();
if (realParent != nullptr) {
objectTransformation->setParentTransform(realParent);
}
objectTransformation->setTransformations(translate, scale, orientation);
animationStatus->object->setCustomAnimation(false);
PhysicalRenderable* physicalRenderable = dynamic_cast<PhysicalRenderable*>(animationStatus->object);
if (physicalRenderable != nullptr) {
//the animation ending is in World class, because it is happening without API or Editor requesting it. but the body type it forced is the accessor's to undo
apiAccessor->applyBodyType(physicalRenderable);
}
}
ActorInterface::ActorInformation World::fillActorInformation(ActorInterface *actor) {
PROFILE_SIMULATION("World::fillActorInformation");
ActorInterface::ActorInformation information;
Model* actorModel = objects[actor->getModelID()];
if(actorModel != nullptr) {
information.canSeePlayerDirectly = checkPlayerVisibility(
actor->getPosition() + glm::vec3(0, AIMovementGrid::floatingHeight+1.0f, 0),
actorModel->getName());
if (currentPlayer->isDead()) {
information.playerDead = true;
}
glm::vec3 front = actor->getFrontVector();
glm::vec3 rayDir = currentPlayer->getPosition() - actor->getPosition();
float cosBetween = glm::dot(normalize(front), normalize(rayDir));
information.playerDistance = glm::length(rayDir);
information.playerDirection = normalize(rayDir);
information.cosineBetweenPlayer = cosBetween;
if (cosBetween > 0) {
information.isPlayerFront = true;
information.isPlayerBack = false;
} else {
information.isPlayerFront = false;
information.isPlayerBack = true;
}
//now we know if it is front or back. we can check up, down, left, right
//remove the y component, and test for left, right
glm::vec3 rayDirWithoutY = rayDir;
rayDirWithoutY.y = 0;
glm::vec3 frontWithoutY = front;
frontWithoutY.y = 0;
glm::vec3 crossBetween = cross(normalize(frontWithoutY), normalize(rayDirWithoutY));
float cosineForSide = glm::dot(normalize(frontWithoutY), normalize(rayDirWithoutY));
information.cosineBetweenPlayerForSide = cosineForSide;
if (crossBetween.y > 0) {
information.isPlayerRight = false;
information.isPlayerLeft = true;
} else {
information.isPlayerRight = true;
information.isPlayerLeft = false;
}
//now we need up and down. For that, normally we can remove z or x, but since camera is z alone at start, I will use x
rayDir.x = 0;
front.x = 0;
crossBetween = glm::cross(normalize(front), normalize(rayDir));
if (crossBetween.x > 0) {
information.isPlayerUp = false;
information.isPlayerDown = true;
} else {
information.isPlayerUp = true;
information.isPlayerDown = false;
}
ActorInterface::InformationRequest requests = actor->getRequests();
if ((requests.routeToPlayer || requests.routeToCustomPosition) && routeThreads.find(actor->getWorldID()) == routeThreads.end()) {
glm::vec3 destination = requests.routeToPlayer
? currentPlayer->getPosition()
: requests.customPosition;
std::vector<LimonTypes::GenericParameter> parameters;
parameters.push_back(LimonTypes::GenericParameter());
parameters[0].value.vectorValue = GLMConverter::GLMToLimon(
actor->getPosition() + glm::vec3(0, AIMovementGrid::floatingHeight, 0));
parameters.push_back(LimonTypes::GenericParameter());
parameters[1].value.longValues[0] = 2;
parameters[1].value.longValues[1] = actor->getWorldID();
parameters[1].value.longValues[2] = requests.maximumRouteNodeCount;
parameters.push_back(LimonTypes::GenericParameter());
parameters[2].value.vectorValue = GLMConverter::GLMToLimon(destination);
std::function<std::vector<LimonTypes::GenericParameter>(
std::vector<LimonTypes::GenericParameter>)> functionToRun =
std::bind(&World::fillRouteInformation, this, std::placeholders::_1);
routeThreads[actor->getWorldID()] = new SDL2MultiThreading::Thread("FillRouteForActor", functionToRun, parameters);
routeThreads[actor->getWorldID()]->run();
}
if (routeThreads.find(actor->getWorldID()) != routeThreads.end() && routeThreads[actor->getWorldID()]->isThreadDone()) {
const std::vector<LimonTypes::GenericParameter>* route = routeThreads[actor->getWorldID()]->getResult();
for (size_t i = 0; i < route->size(); ++i) {
information.routeToRequest.push_back(glm::vec3(GLMConverter::LimonToGLM(route->at(i).value.vectorValue)));
}
delete routeThreads[actor->getWorldID()];
routeThreads.erase(actor->getWorldID());
if (information.routeToRequest.empty()) {
information.routeFound = false;
} else {
information.routeFound = true;
}
information.routeReady = true;
}
}
return information;
}
//std::function<std::vector<LimonTypes::ParameterRequest>(std::vector<LimonTypes::ParameterRequest>)> functionToRun
std::vector<LimonTypes::GenericParameter>
World::fillRouteInformation(std::vector<LimonTypes::GenericParameter> parameters) const {
PROFILE_SIMULATION("World::fillRouteInformation");
glm::vec3 fromPosition = glm::vec3(GLMConverter::LimonToGLM(parameters[0].value.vectorValue));
uint32_t actorID = (uint32_t)parameters[1].value.longValues[1];
uint32_t maximumDistance = (uint32_t)parameters[1].value.longValues[2];
std::vector<glm::vec3> route;
glm::vec3 destinationWithGrid = glm::vec3(GLMConverter::LimonToGLM(parameters[2].value.vectorValue));
bool isDestinationReachable = grid->setProperHeight(&destinationWithGrid, AIMovementGrid::floatingHeight, 0.0f,
dynamicsWorld);
if (isDestinationReachable && grid->coursePath(fromPosition, destinationWithGrid, actorID, maximumDistance, &route)) {
if (!route.empty()) {
//Normally, this information should be used for straightening the path, but not yet.
reverse(std::begin(route), std::end(route));
}
}
std::vector<LimonTypes::GenericParameter> routeList;
for (size_t i = 0; i < route.size(); ++i) {
LimonTypes::GenericParameter pr;
pr.value.vectorValue = GLMConverter::GLMToLimon(route[i]);
routeList.push_back(pr);
}
return routeList;
}
bool World::handlePlayerInput(InputHandler &inputHandler) {
if(inputHandler.getInputStates().getInputEvents(InputActions::MOUSE_BUTTON_LEFT)) {
if(inputHandler.getInputStates().getInputStatus(InputActions::MOUSE_BUTTON_LEFT)) {
GameObject *gameObject = getPointedObject(COLLIDE_EVERYTHING, ~(COLLIDE_NOTHING));
editor->pendingPickedObject = gameObject; // nullptr if nothing was hit
editor->hasPendingPick = true;
}
}
if(inputHandler.getInputStates().getInputEvents(InputActions::F4)) {
OptionsUtil::Options::Option<bool> debugDrawLinesOption = options->getOption<bool>(HASH("debug_drawLines"));
bool debugDrawLines = debugDrawLinesOption.getOrDefault(false);
if(inputHandler.getInputStates().getInputStatus(InputActions::F4)) {
debugDrawLines = !debugDrawLines;
}
debugDrawLinesOption.set(debugDrawLines);
/*
long cascadeCount;
OptionsUtil::Options::Option<long> cascadeCountOption = options->getOption<long>(HASH("shadow_cascadeCount"));
cascadeCount = cascadeCountOption.getOrDefault(4);
if(inputHandler.getInputStates().getInputStatus(InputActions::F4)) {
cascadeCount--;
if(cascadeCount < 0) {
cascadeCount = cascadeCountOption.getOrDefault(4);
}
}
*/
}
if (inputHandler.getInputStates().getInputEvents(InputActions::F5) &&
inputHandler.getInputStates().getInputStatus(InputActions::F5)) {
if (profilerSystem) {
profilerSystem->togglePause();
}
}
if (inputHandler.getInputStates().getInputEvents(InputActions::EDITOR) && inputHandler.getInputStates().getInputStatus(InputActions::EDITOR)) {
createEditorPlayerIfMissing(inputHandler);
if(!currentPlayersSettings->editorShown) {
switchPlayer(editorPlayer, inputHandler);
} else {
switchPlayer(beforePlayer, inputHandler);
}
}
//if not in editor mode and press debug
if (!currentPlayersSettings->editorShown && inputHandler.getInputStates().getInputEvents(InputActions::DEBUG_MODE) && inputHandler.getInputStates().getInputStatus(InputActions::DEBUG_MODE)) {
if(currentPlayersSettings->debugMode != Player::DEBUG_ENABLED) {
if(debugPlayer == nullptr) {
debugPlayer = new FreeMovingPlayer(options, cursor, startingPlayer.position, startingPlayer.orientation, 0);
debugPlayer->registerToPhysicalWorld(dynamicsWorld, COLLIDE_PLAYER,
COLLIDE_MODELS | COLLIDE_TRIGGER_VOLUME | COLLIDE_EVERYTHING,
COLLIDE_MODELS | COLLIDE_EVERYTHING,
worldAABBMin, worldAABBMax);
}
switchPlayer(debugPlayer, inputHandler);
} else {
if(physicalPlayer == nullptr) {
physicalPlayer = new PhysicalPlayer(options, cursor, startingPlayer.position, startingPlayer.orientation, 0);
physicalPlayer->registerToPhysicalWorld(dynamicsWorld, COLLIDE_PLAYER,
COLLIDE_MODELS | COLLIDE_TRIGGER_VOLUME | COLLIDE_EVERYTHING,
COLLIDE_MODELS | COLLIDE_EVERYTHING,
worldAABBMin, worldAABBMax);
}
switchPlayer(physicalPlayer, inputHandler);
}
}
currentPlayer->processInput(inputHandler.getInputStates(), gameTime);
if(inputHandler.getInputStates().getInputEvents(InputActions::QUIT) && inputHandler.getInputStates().getInputStatus(InputActions::QUIT)) {
return true;
} else {
return false;
}
}
void World::render() {
PROFILE_RENDERING("World::render");
renderPipeline->render();
}
void World::renderGUIImages(const std::shared_ptr<GraphicsProgram>& renderProgram, const std::string &cameraName [[gnu::unused]], const std::vector<HashUtil::HashedString> &tags [[gnu::unused]]) const {
PROFILE_RENDERING("World::renderGUIImages");
// We are assuming depth 0 - 0,019 would be close enough for GUI layers occupy the reserved depth zone [0, 0.019]; level 0 is furthest back.
// 0 is the furthest back
// This would work for perspective camera anyways, but for ortho,
// you need to limit it to -20 (which means ortho can use roughly 98% of the depth
for (auto it = guiLayers.begin(); it != guiLayers.end(); ++it) {
float layerDepth = 0.019f * (1.0f - static_cast<float>((*it)->getLevel()) / 512.0f);
renderProgram->setUniform("layerDepth", layerDepth);
(*it)->renderImageWithProgram(renderProgram);
}
renderProgram->setUniform("layerDepth", 0.019f / 256.0f);
apiGUILayer->renderImageWithProgram(renderProgram);
renderProgram->setUniform("layerDepth", 0.019f / 512.0f);
cursor->renderWithProgram(renderProgram, 0);
}
void World::renderGUITexts(const std::shared_ptr<GraphicsProgram>& renderProgram, const std::string &cameraName [[gnu::unused]], const std::vector<HashUtil::HashedString> &tags [[gnu::unused]]) const {
PROFILE_RENDERING("World::renderGUITexts");
for (auto it = guiLayers.begin(); it != guiLayers.end(); ++it) {
float layerDepth = 0.019f * (1.0f - static_cast<float>((*it)->getLevel()) / 512.0f);
renderProgram->setUniform("layerDepth", layerDepth);
(*it)->renderTextWithProgram(renderProgram);
}
renderProgram->setUniform("layerDepth", 0.019f / 256.0f);
apiGUILayer->renderTextWithProgram(renderProgram);
bool renderInformations =renderInformationsOption.getOrDefault(false);
renderProgram->setUniform("layerDepth", 0.019f / 512.0f);
if (renderInformations) {
char renderCountsText[32];
snprintf(renderCountsText, sizeof(renderCountsText), "%4d fps, %8u tris",
(int)frameTimeTracker->getFramesPerSecond(), graphicsWrapper->getFrameStats().triangleCount);
renderCounts->updateText(renderCountsText);
renderCounts->renderWithProgram(renderProgram, 0);
debugOutputGUI->renderWithProgram(renderProgram, 0);
}
}
void World::renderParticleEmitters(const std::shared_ptr<GraphicsProgram>& renderProgram, const std::string &cameraName [[gnu::unused]], const std::vector<HashUtil::HashedString> &tags [[gnu::unused]]) const {
PROFILE_RENDERING("World::renderParticleEmitters");
for(const auto& emitter:emitters) {
emitter.second->renderWithProgram(renderProgram, 0);
}
}
void World::renderGPUParticleEmitters(const std::shared_ptr<GraphicsProgram>& renderProgram, const std::string &cameraName [[gnu::unused]], const std::vector<HashUtil::HashedString> &tags [[gnu::unused]]) const {
PROFILE_RENDERING("World::renderGPUParticleEmitters");
for(const auto& gpuParticleEmitter:gpuParticleEmitters) {
gpuParticleEmitter.second->renderWithProgram(renderProgram, 0);
}
}
void World::renderDebug(const std::shared_ptr<GraphicsProgram>& renderProgram [[gnu::unused]], const std::string &cameraName [[gnu::unused]], const std::vector<HashUtil::HashedString> &tags [[gnu::unused]]) const {
PROFILE_RENDERING("World::renderDebug");
dynamicsWorld->debugDrawWorld();
for (const auto &drawLinePair: options->getLogger()->getDrawLines()) {
if(!drawLinePair.second.empty()) {
for (const auto &line: drawLinePair.second) {
debugDrawer->drawLine(GLMConverter::GLMToBlt(line.from), GLMConverter::GLMToBlt(line.to), GLMConverter::GLMToBlt(line.fromColor), GLMConverter::GLMToBlt(line.toColor));
}
}
}
if (dynamicsWorld->getDebugDrawer()->getDebugMode() != btIDebugDraw::DBG_NoDebug) {
debugDrawer->drawLine(btVector3(0, 0, 0), btVector3(0, 250, 0), btVector3(1, 1, 1));
//draw the ai-grid
if (grid != nullptr) {
grid->debugDraw(debugDrawer);
}
}
debugDrawer->flushDraws();
}
void World::renderCameraByTag(const std::shared_ptr<GraphicsProgram> &renderProgram, const std::string &cameraName, const std::vector<HashUtil::HashedString> &tags) const {
PROFILE_RENDERING("World::renderCameraByTag");
uint64_t hashedCameraTag = HashUtil::hashString(cameraName);
for (const auto &visibilityEntry: visibilityManager->getCullingResults()) {
if (visibilityEntry.first->hasTag(hashedCameraTag)) { //This is a request for this camera
std::unordered_map<std::vector<uint64_t>, RenderList, VisibilityRequest::uint64_vector_hasher>& renderLists = *visibilityEntry.second;
for (auto& renderListEntry: renderLists) {
if (!VisibilityRequest::vectorComparator(renderListEntry.first, tags)) {
continue;
}
const RenderList& renderList = renderListEntry.second;
renderList.render(graphicsWrapper, renderProgram);
}
}
}
}
void World::renderSky(const std::shared_ptr<GraphicsProgram>& renderProgram, const std::string &cameraName [[gnu::unused]], const std::vector<HashUtil::HashedString> &tags [[gnu::unused]]) const {
PROFILE_RENDERING("World::renderSky");
if (sky != nullptr) {
sky->renderWithProgram(renderProgram, 0);
}
}
void World::renderLight(unsigned int lightIndex, unsigned int renderLayer, const std::shared_ptr<GraphicsProgram> &renderProgram, const std::vector<HashUtil::HashedString> &tags) const {
PROFILE_RENDERING("World::renderLight");
Light* selectedLight = activeLights[lightIndex];
Camera* lightCamera = selectedLight->getCameras()[renderLayer];
if (lightCamera->isDirty()) {
RenderProfileScope lightScope(graphicsWrapper, *selectedLight, renderLayer);
//TODO: following check fixes the point lights, but it is a hack, meaning we need to handle this properly.
if (lightCamera->getType() == Camera::CameraTypes::ORTHOGRAPHIC) {
graphicsWrapper->clearDepthBuffer();
}
renderProgram->setUniform("renderLightIndex", (int) lightIndex);
renderProgram->setUniform("renderLightLayer", (int) renderLayer);
std::unordered_map<std::vector<uint64_t>, RenderList, VisibilityRequest::uint64_vector_hasher>* cullingResult = visibilityManager->getCullingResults().at(lightCamera);
for (const auto& iterator:*cullingResult) {
if (!VisibilityRequest::vectorComparator(iterator.first, tags)) {
continue;
}
const RenderList& renderList = iterator.second;
renderList.render(graphicsWrapper, renderProgram);
}
lightCamera->clearDirty();
}
}
/**
* This method checks if we are in editor mode, and if we are, enables ImGui windows