Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
- #include "VizGame.h"
- #include "Windows/WindowsWindow.h"
- #include "Player/VizPlayerController.h"
- #include "VizCreateEditPawn.h"
- #include "Player/VizPlayerCameraManager.h"
- #include "Player/VizCheatManager.h"
- #include "Player/VizLocalPlayer.h"
- #include "Online/VizPlayerState.h"
- #include "Inventory/VizInventoryContainerActor.h"
- //#include "Weapons/VizWeapon.h"
- #include "UI/Menu/VizIngameMenu.h"
- #include "UI/Style/VizStyle.h"
- #include "UI/VizHUD.h"
- #include "Online.h"
- #include "OnlineAchievementsInterface.h"
- #include "OnlineEventsInterface.h"
- #include "OnlineIdentityInterface.h"
- #include "OnlineSessionInterface.h"
- #include "VizGameInstance.h"
- #include "VizLeaderboards.h"
- #include "VizGameViewportClient.h"
- #include "WidgetManagers/VizWidgetManager.h"
- #include "Inventory/VizInventoryPreview.h"
- #include "../../Inventory/VizEquipmentContainer.h"
- #include "VizGameMode.h"
- #include "VizTypes.h"
- #include "Actors/VizPathManager.h"
- #include "Environment/VizSnowClassificationManager.h"
- #include "../../Inventory/VizPlayerInventory.h"
- #include "../../Inventory/VizInventoryContainerActor.h"
- #define ACH_FRAG_SOMEONE TEXT("ACH_FRAG_SOMEONE")
- #define ACH_SOME_KILLS TEXT("ACH_SOME_KILLS")
- #define ACH_LOTS_KILLS TEXT("ACH_LOTS_KILLS")
- #define ACH_FINISH_MATCH TEXT("ACH_FINISH_MATCH")
- #define ACH_LOTS_MATCHES TEXT("ACH_LOTS_MATCHES")
- #define ACH_FIRST_WIN TEXT("ACH_FIRST_WIN")
- #define ACH_LOTS_WIN TEXT("ACH_LOTS_WIN")
- #define ACH_MANY_WIN TEXT("ACH_MANY_WIN")
- #define ACH_SHOOT_BULLETS TEXT("ACH_SHOOT_BULLETS")
- #define ACH_SHOOT_ROCKETS TEXT("ACH_SHOOT_ROCKETS")
- #define ACH_GOOD_SCORE TEXT("ACH_GOOD_SCORE")
- #define ACH_GREAT_SCORE TEXT("ACH_GREAT_SCORE")
- #define ACH_PLAY_SANCTUARY TEXT("ACH_PLAY_SANCTUARY")
- #define ACH_PLAY_HIGHRISE TEXT("ACH_PLAY_HIGHRISE")
- static const int32 SomeKillsCount = 10;
- static const int32 LotsKillsCount = 20;
- static const int32 LotsMatchesCount = 5;
- static const int32 LotsWinsCount = 3;
- static const int32 ManyWinsCount = 5;
- static const int32 LotsBulletsCount = 100;
- static const int32 LotsRocketsCount = 10;
- static const int32 GoodScoreCount = 10;
- static const int32 GreatScoreCount = 15;
- AVizPlayerController::AVizPlayerController(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
- {
- PlayerCameraManagerClass = AVizPlayerCameraManager::StaticClass();
- CheatClass = UVizCheatManager::StaticClass();
- bAllowGameActions = true;
- bGameEndedFrame = false;
- LastDeathLocation = FVector::ZeroVector;
- ServerSayString = TEXT("Say");
- VizFriendUpdateTimer = 0.0f;
- bHasSentStartEvents = false;
- }
- void AVizPlayerController::SetupInputComponent()
- {
- Super::SetupInputComponent();
- // UI input
- InputComponent->BindAction("InGameMenu", IE_Pressed, this, &AVizPlayerController::OnToggleInGameMenu);
- InputComponent->BindAction("Scoreboard", IE_Pressed, this, &AVizPlayerController::OnShowScoreboard);
- InputComponent->BindAction("Scoreboard", IE_Released, this, &AVizPlayerController::OnHideScoreboard);
- InputComponent->BindAction("ConditionalCloseScoreboard", IE_Pressed, this, &AVizPlayerController::OnConditionalCloseScoreboard);
- InputComponent->BindAction("ToggleScoreboard", IE_Pressed, this, &AVizPlayerController::OnToggleScoreboard);
- InputComponent->BindAction("TraineeMap", IE_Pressed, this, &AVizPlayerController::ToggleTraineeMap);
- InputComponent->BindAction("TraineeSnowTests", IE_Pressed, this, &AVizPlayerController::ToggleTraineeSnowTests);
- InputComponent->BindAction("TraineeInventory", IE_Pressed, this, &AVizPlayerController::ToggleTraineeInventory);
- InputComponent->BindAction("SpawnInventory", IE_Released, this, &AVizPlayerController::SpawnAllInventory);
- InputComponent->BindAction("ClearInventory", IE_Released, this, &AVizPlayerController::ClearAllInventory);
- // voice chat
- InputComponent->BindAction("PushToTalk", IE_Pressed, this, &APlayerController::StartTalking);
- InputComponent->BindAction("PushToTalk", IE_Released, this, &APlayerController::StopTalking);
- InputComponent->BindAction("ToggleChat", IE_Pressed, this, &AVizPlayerController::ToggleChatWindow);
- //Mouse Click
- InputComponent->BindAction("LeftMouseUp", IE_Released, this, &AVizPlayerController::OnLeftMouseUp);
- //Debug
- InputComponent->BindAction("DebugKey", IE_Released, this, &AVizPlayerController::DebugTest);
- InputComponent->BindAction("EnableTrainerUI", IE_Released, this, &AVizPlayerController::TestNetworkCommunication);
- InputComponent->BindAction("CallDog", IE_Pressed, this, &AVizPlayerController::OnCallDog);
- }
- void AVizPlayerController::TestNetworkCommunication()
- {
- // UpdateQuestionID_OnServer(QuestionID);
- }
- void AVizPlayerController::SendQuestionIDtoClient(int32 QuesID)
- {
- QuestionID = QuesID;
- UpdateQuestionID_OnServer(QuesID);
- V_LOGM(LogViz, "In Trainer Question ID is: %s", *FString::FromInt((QuestionID)));
- }
- void AVizPlayerController::SendQuestionIDtoTrainer(int32 answerString)
- {
- // FString *str = answerString;
- SendAnswerToTrainer_OnServer(answerString);
- V_LOGM(LogViz, "In Trainee Question Answer is: %s", *FString::FromInt((answerString)));
- }
- void AVizPlayerController::SendAnswerToTrainer_OnServer_Implementation(int32 answer)
- {
- AVizGameMode* gm = Cast<AVizGameMode>(GetWorld()->GetAuthGameMode());
- V_LOGM(LogViz, "Server looking for Trainer");
- gm->SendToTrainer(answer);
- }
- bool AVizPlayerController::SendAnswerToTrainer_OnServer_Validate(int32 answer)
- {
- return true;
- }
- void AVizPlayerController::UpdateQuestionID_OnServer_Implementation(int32 id)
- {
- AVizGameMode* gm = Cast<AVizGameMode>(GetWorld()->GetAuthGameMode());
- V_LOGM(LogViz, "Server looking for Trainee");
- gm->AskTrainee(id);
- }
- bool AVizPlayerController::UpdateQuestionID_OnServer_Validate(int32 id)
- {
- return true;
- }
- void AVizPlayerController::QuestionAsked_Implementation(int32 id)
- {
- QuestionID = id;
- V_LOGM(LogViz, "Trainee got the Question ID! Its is %s", *FString::FromInt((QuestionID)));
- UpdateCharacterUI();
- TraineeFirstPersonPawn = Cast<AVizCharacter>(GetPawn());
- //TraineeFirstPersonPawn->SetScoringWidgetIndex(QuestionID);
- TraineeFirstPersonPawn->UpdateQuestionFromCharacter(QuestionID);
- }
- void AVizPlayerController::AnswerSent_Implementation(int32 answer)
- {
- V_LOGM(LogViz, "Trainer got the Answer! Its is %s", *FString::FromInt((answer)));
- trainerUIMultiWidget->TrainerTraineeScoreTabWidget->ShowAnswer(answer);
- trainerUIMultiWidget->TrainerUIMultiWidget->ShowAnswer(answer);
- // UpdateCharacterUI( widget , answer);
- }
- void AVizPlayerController::SetTrainerUIWidget() {
- trainerUIMultiWidget = CreateWidget<UVizTrainerMenuMultiUIWidget>(this, TrainerUIBP);
- AVizCreateEditPawn * pawn = Cast<AVizCreateEditPawn>(GetPawn());
- pawn->SetTrainerUI(trainerUIMultiWidget);
- }
- void AVizPlayerController::PostInitializeComponents()
- {
- Super::PostInitializeComponents();
- FVizStyle::Initialize();
- VizFriendUpdateTimer = 0;
- //Find snow classification
- TArray<AActor*> FoundActors;
- UGameplayStatics::GetAllActorsOfClass(GetWorld(), AVizSnowClassificationManager::StaticClass(), FoundActors);
- if(FoundActors.Num() > 0)
- {
- m_pSnowProperty = Cast<AVizSnowClassificationManager>(FoundActors[0]);
- }
- }
- void AVizPlayerController :: MapScrolling(float ScrollDirection)
- {
- float newWidth = m_scenemap->GetCaptureComponent2D()->OrthoWidth;
- float maxOrthoWidth = 1000000.0; // xxxx to be based on landscape maximum extents; same size as width/length
- float minOrthoWidth = 1000.0;
- float zoomDelta = 0.2;
- newWidth = newWidth - ScrollDirection * newWidth* zoomDelta;
- newWidth = (newWidth >= maxOrthoWidth) ? maxOrthoWidth : newWidth;
- newWidth = (newWidth <= minOrthoWidth) ? minOrthoWidth : newWidth;
- m_scenemap->GetCaptureComponent2D()->OrthoWidth = newWidth;
- }
- void AVizPlayerController :: MapPan(FVector2D PanMap, float deltatime)
- {
- FVector camLocaton = m_scenemap->GetActorLocation();
- float maxOrthoWidth = 1000000.0; // xxxx to be based on landscape maximum extents; same size as width/length
- float panRate = 30000.0;
- float currentWidth = m_scenemap->GetCaptureComponent2D()->OrthoWidth;
- float camMaxOffset = maxOrthoWidth - 0.5*currentWidth;
- float camMinOffset = currentWidth*0.5;
- camLocaton -= FVector(PanMap.Y, 0, 0) * deltatime * panRate;
- camLocaton += FVector(0, PanMap.X, 0) * deltatime * panRate;
- camLocaton.X = (camLocaton.X >= camMaxOffset) ? camMaxOffset : camLocaton.X;
- camLocaton.X = (camLocaton.X <= camMinOffset) ? camMinOffset : camLocaton.X;
- camLocaton.Y = (camLocaton.Y >= camMaxOffset) ? camMaxOffset : camLocaton.Y;
- camLocaton.Y = (camLocaton.Y <= camMinOffset) ? camMinOffset : camLocaton.Y;
- m_scenemap->SetActorLocation(camLocaton);
- }
- FVector AVizPlayerController::FetchCamLoc()
- {
- if (m_scenemap)
- {
- return m_scenemap->GetActorLocation();
- }
- return FVector::ZeroVector;
- }
- float AVizPlayerController::FetchcamOrthoWidth()
- {
- if (m_scenemap)
- {
- return m_scenemap->GetCaptureComponent2D()->OrthoWidth;
- }
- return 0.0;
- }
- void AVizPlayerController::BeginPlay()
- {
- Super::BeginPlay();
- // Read all equipment data
- m_pInventoryManager = NewObject<UVizInventoryManager>();
- m_pInventoryManager->ReadInventoryData(EquipmentData, EquipmentDetailsData);
- // Initialize EquipmentContainer and GameInventory
- m_pEquipmentContainer = NewObject<UVizEquipmentContainer>();
- m_pEquipmentContainer->Initialize(m_pInventoryManager);
- m_pGameInventory = NewObject<UVizGameInventory>();
- m_pGameInventory->Initialize(m_pInventoryManager);
- if (SceneMapBP)
- {
- m_scenemap = (ASceneCapture2D*)GetWorld()->SpawnActor(SceneMapBP);
- m_scenemap->SetActorLocation(MapScenceCamPosition);
- FRotator MapRotator;
- MapRotator.Roll = 0.0f;
- MapRotator.Pitch = -90.0f;
- MapRotator.Yaw = -90.0f;
- m_scenemap->SetActorRotation(MapRotator);
- m_scenemap->GetCaptureComponent2D()->ProjectionType = ECameraProjectionMode::Orthographic;
- m_scenemap->GetCaptureComponent2D()->OrthoWidth = 1000000.0f;
- // m_scenemap->GetCaptureComponent2D()->bCaptureEveryFrame = false;
- m_scenemap->GetCaptureComponent2D()->TextureTarget = MapTexture;
- GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, FString::SanitizeFloat(m_scenemap->GetCaptureComponent2D()->OrthoWidth));
- //FString::SanitizeFloat(m_scenemap->GetCaptureComponent2D()->OrthoWidth);
- // m_scenemap->GetCaptureComponent2D()->OrthoWidth
- }
- //! TODO: Store and retrieve this information from the LocalPlayer.
- UGameInstance* gameInstance = GetWorld()->GetGameInstance();
- UVizGameInstance* vizgameinstance = Cast<UVizGameInstance>(gameInstance);
- bool trainerB = vizgameinstance->IsTrainer;
- bool bHMD;
- //Check for Head Mounting Device
- if (GEngine->HMDDevice.Get())
- {
- bHMD = true;
- }
- else
- {
- bHMD = false;
- }
- //Make sure that controller has data before creating widgets
- if (!IsRunningDedicatedServer())
- {
- V_LOG(LogViz, "Calling Update Pawn Possession");
- V_LOGVALUEB(LogViz, trainerB);
- V_LOGVALUEB(LogViz, bHMD);
- UpdatePawnPossession(trainerB, bHMD);
- RequestForMapInfo_Server();
- RequestForObjectives_Server();
- RequestForQuestionData_Server();
- RequestForSnowTests_Server();
- RequestForGameInventoryData_Server();
- RequestForBindingWeatherParticleLocation();
- if(m_pWidgetManager)
- {
- // m_pWidgetManager->ShowSelectionMenu();
- /*if(GEngine->HMDDevice.Get())
- {
- DisableHMD();
- }*/
- }
- }
- if (InventoryPreviewBP)
- {
- m_pInventoryPreview = (AVizInventoryPreview*)GetWorld()->SpawnActor(InventoryPreviewBP);
- m_pInventoryPreview->SetActorLocation(PreviewLocation);
- }
- if(InventoryContainerBP)
- {
- m_pInventoryContainer = (AVizInventoryContainerActor*)GetWorld()->SpawnActor(InventoryContainerBP);
- }
- //if (DogAICharaterBP)
- //{
- // m_pDogCharacterBP = (ACharacter*)GetWorld()->SpawnActor(DogAICharaterBP);
- // m_pDogCharacterBP->SetActorLocation(TraineeFPPawn->GetActorLocation());
- // //m_pDogCharacterBP->SimulatePhysics = true;
- //}
- //
- // m_pAIManager = NewObject<UVizAIManager>();
- // m_pAIManager->Start(m_pDogCharacterBP, GEngine->GetWorld());
- //If VR is detected , switch to VR Pawn
- /*if(GEngine->HMDDevice.Get())
- {
- PossesCharacter(1);
- }*/
- }
- void AVizPlayerController::UpdatePawnPossession_Implementation(bool bTrainer,bool bHMD)
- {
- V_LOG_LINE(LogViz);
- V_LOGVALUEB(LogViz, bTrainer);
- V_LOGVALUEB(LogViz, bHMD);
- // bTrainer = false;
- AVizCharacter* myPawn = Cast<AVizCharacter>(GetPawn());
- if (myPawn)
- {
- // V_LOG(LogViz, "Pawn is valid.");
- // V_LOG(LogViz, myPawn->GetClass()->GetName());
- // if (!bTrainer)
- // {
- // myPawn->GetPlayerInventory()->Initialize(m_pInventoryManager);
- // this->Possess(myPawn);
- // TraineeFirstPersonPawn = myPawn;
- // V_LOG(LogViz, "Possessing VizCharacter");
- //
- //// if (bHMD)
- // {
- // V_LOG(LogViz, "Possessing VR Pawn");
- // PossesCharacter(1);
- // if (myPawn->Destroy())
- // {
- // V_LOG(LogViz, "Trainee pawn destroyed");
- // }
- // else
- // {
- // V_LOG(LogViz, "Trainee pawn could not be destroyed");
- // }
- //
- // }
- //
- //Spawn the Dog AI Companion from Code
- if (DogAICharaterBP)
- {
- m_pDogCharacterBP = (AAIDogCharacter*)GetWorld()->SpawnActor(DogAICharaterBP);
- m_pDogCharacterBP->SetActorLocation(myPawn->GetActorLocation());
- //m_pDogCharacterBP->CallDog();
- }
- //
- // }
- }
- if (bTrainer)
- {
- V_LOG(LogViz, "Creating AVizCreateEditPawn");
- this->GetPawn()->bHidden = true;
- this->UnPossess();
- FVector Pos(603921.4,303261.4,69713.7);
- FRotator Rotation(0, 0, 0);
- FActorSpawnParameters params;
- trainerPawn = GetWorld()->SpawnActor<AVizCreateEditPawn>(TrainerPawn , Pos, Rotation, params);
- trainerPawn->SetReplicates(true);
- trainerPawn->SetReplicateMovement(true);
- if (trainerPawn)
- {
- this->Possess(trainerPawn);
- if (myPawn->Destroy())
- {
- V_LOG(LogViz, "Trainee pawn destroyed");
- }
- else
- {
- V_LOG(LogViz, "Trainee pawn could not be destroyed");
- }
- }
- }
- TraineeFirstPersonPawn = nullptr;
- if (DogAICharaterBP)
- {
- //m_pDogCharacterBP = (ACharacter*)GetWorld()->SpawnActor(DogAICharaterBP);
- //m_pDogCharacterBP->SetActorLocation(TraineeFPPawn->GetActorLocation());
- //m_pDogCharacterBP->SimulatePhysics = true;
- }
- //m_pAIManager = NewObject<UVizAIManager>();
- //m_pAIManager->Start(m_pDogCharacterBP, GEngine->GetWorld());
- }
- void AVizPlayerController::OnCallDog()
- {
- m_pDogCharacterBP->CallDog();
- }
- bool AVizPlayerController::UpdatePawnPossession_Validate(bool bTrainer,bool bHMD)
- {
- return true;
- }
- void AVizPlayerController::Tick(float DeltaSeconds)
- {
- Super::Tick(DeltaSeconds);
- if (!IsRunningDedicatedServer())
- {
- GetAllPlayerPosition();
- }
- if (IsGameMenuVisible())
- {
- if (VizFriendUpdateTimer > 0)
- {
- VizFriendUpdateTimer -= DeltaSeconds;
- }
- else
- {
- TSharedPtr<class FVizFriends> VizFriends = VizIngameMenu->GetVizFriends();
- ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(Player);
- if (VizFriends.IsValid() && LocalPlayer && LocalPlayer->GetControllerId() >= 0)
- {
- VizFriends->UpdateFriends(LocalPlayer->GetControllerId());
- }
- VizFriendUpdateTimer = 4; //make sure the time between calls is long enough that we won't trigger (0x80552C81) and not exceed the web api rate limit
- }
- }
- // Is this the first frame after the game has ended
- if (bGameEndedFrame)
- {
- bGameEndedFrame = false;
- // ONLY PUT CODE HERE WHICH YOU DON'T WANT TO BE DONE DUE TO HOST LOSS
- // Do we need to show the end of round scoreboard?
- if (IsPrimaryPlayer())
- {
- AVizHUD* VizHUD = GetVizHUD();
- if (VizHUD)
- {
- VizHUD->ShowScoreboard(true, true);
- }
- }
- }
- //Update Minimap
- if (m_bIsMinimapEnabled || m_bIsGameMapEnabled)
- {
- m_pWidgetManagerBase->UpdateMapObjects(m_aMiniMapObjects);
- }
- }
- void AVizPlayerController::QueryAchievements()
- {
- // precache achievements
- ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(Player);
- if (LocalPlayer && LocalPlayer->GetControllerId() != -1)
- {
- IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
- if(OnlineSub)
- {
- IOnlineIdentityPtr Identity = OnlineSub->GetIdentityInterface();
- if (Identity.IsValid())
- {
- TSharedPtr<const FUniqueNetId> UserId = Identity->GetUniquePlayerId(LocalPlayer->GetControllerId());
- if (UserId.IsValid())
- {
- IOnlineAchievementsPtr Achievements = OnlineSub->GetAchievementsInterface();
- if (Achievements.IsValid())
- {
- Achievements->QueryAchievements( *UserId.Get(), FOnQueryAchievementsCompleteDelegate::CreateUObject( this, &AVizPlayerController::OnQueryAchievementsComplete ));
- }
- }
- else
- {
- UE_LOG(LogOnline, Warning, TEXT("No valid user id for this controller."));
- }
- }
- else
- {
- UE_LOG(LogOnline, Warning, TEXT("No valid identity interface."));
- }
- }
- else
- {
- UE_LOG(LogOnline, Warning, TEXT("No default online subsystem."));
- }
- }
- else
- {
- UE_LOG(LogOnline, Warning, TEXT("No local player, cannot read achievements."));
- }
- }
- void AVizPlayerController::OnQueryAchievementsComplete(const FUniqueNetId& PlayerId, const bool bWasSuccessful )
- {
- UE_LOG(LogOnline, Display, TEXT("AVizPlayerController::OnQueryAchievementsComplete(bWasSuccessful = %s)"), bWasSuccessful ? TEXT("TRUE") : TEXT("FALSE"));
- }
- void AVizPlayerController::UnFreeze()
- {
- ServerRestartPlayer();
- }
- void AVizPlayerController::FailedToSpawnPawn()
- {
- if(StateName == NAME_Inactive)
- {
- BeginInactiveState();
- }
- Super::FailedToSpawnPawn();
- }
- void AVizPlayerController::PawnPendingDestroy(APawn* P)
- {
- LastDeathLocation = P->GetActorLocation();
- FVector CameraLocation = LastDeathLocation + FVector(0, 0, 300.0f);
- FRotator CameraRotation(-90.0f, 0.0f, 0.0f);
- FindDeathCameraSpot(CameraLocation, CameraRotation);
- Super::PawnPendingDestroy(P);
- ClientSetSpectatorCamera(CameraLocation, CameraRotation);
- }
- void AVizPlayerController::GameHasEnded(class AActor* EndGameFocus, bool bIsWinner)
- {
- UpdateSaveFileOnGameEnd(bIsWinner);
- UpdateAchievementsOnGameEnd();
- UpdateLeaderboardsOnGameEnd();
- Super::GameHasEnded(EndGameFocus, bIsWinner);
- }
- void AVizPlayerController::ClientSetSpectatorCamera_Implementation(FVector CameraLocation, FRotator CameraRotation)
- {
- SetInitialLocationAndRotation(CameraLocation, CameraRotation);
- SetViewTarget(this);
- }
- bool AVizPlayerController::FindDeathCameraSpot(FVector& CameraLocation, FRotator& CameraRotation)
- {
- const FVector PawnLocation = GetPawn()->GetActorLocation();
- FRotator ViewDir = GetControlRotation();
- ViewDir.Pitch = -45.0f;
- const float YawOffsets[] = { 0.0f, -180.0f, 90.0f, -90.0f, 45.0f, -45.0f, 135.0f, -135.0f };
- const float CameraOffset = 600.0f;
- FCollisionQueryParams TraceParams(TEXT("DeathCamera"), true, GetPawn());
- FHitResult HitResult;
- for (int32 i = 0; i < ARRAY_COUNT(YawOffsets); i++)
- {
- FRotator CameraDir = ViewDir;
- CameraDir.Yaw += YawOffsets[i];
- CameraDir.Normalize();
- const FVector TestLocation = PawnLocation - CameraDir.Vector() * CameraOffset;
- const bool bBlocked = GetWorld()->LineTraceSingleByChannel(HitResult, PawnLocation, TestLocation, ECC_Camera, TraceParams);
- if (!bBlocked)
- {
- CameraLocation = TestLocation;
- CameraRotation = CameraDir;
- return true;
- }
- }
- return false;
- }
- bool AVizPlayerController::ServerCheat_Validate(const FString& Msg)
- {
- return true;
- }
- void AVizPlayerController::ServerCheat_Implementation(const FString& Msg)
- {
- if (CheatManager)
- {
- ClientMessage(ConsoleCommand(Msg));
- }
- }
- void AVizPlayerController::SimulateInputKey(FKey Key, bool bPressed)
- {
- InputKey(Key, bPressed ? IE_Pressed : IE_Released, 1, false);
- }
- void AVizPlayerController::OnDeathMessage(class AVizPlayerState* KillerPlayerState, class AVizPlayerState* KilledPlayerState, const UDamageType* KillerDamageType)
- {
- AVizHUD* VizHUD = GetVizHUD();
- if (VizHUD)
- {
- VizHUD->ShowDeathMessage(KillerPlayerState, KilledPlayerState, KillerDamageType);
- }
- ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(Player);
- if (LocalPlayer && LocalPlayer->GetCachedUniqueNetId().IsValid() && KilledPlayerState->UniqueId.IsValid())
- {
- // if this controller is the player who died, update the hero stat.
- if (*LocalPlayer->GetCachedUniqueNetId() == *KilledPlayerState->UniqueId)
- {
- const auto Events = Online::GetEventsInterface();
- const auto Identity = Online::GetIdentityInterface();
- if (Events.IsValid() && Identity.IsValid())
- {
- const int32 UserIndex = LocalPlayer->GetControllerId();
- TSharedPtr<const FUniqueNetId> UniqueID = Identity->GetUniquePlayerId(UserIndex);
- if (UniqueID.IsValid())
- {
- AVizCharacter* pPawn = Cast<AVizCharacter>(GetCharacter());
- //AVizWeapon* Weapon = Pawn ? Pawn->GetWeapon() : NULL;
- FVector Location = pPawn ? pPawn->GetActorLocation() : FVector::ZeroVector;
- //int32 WeaponType = Weapon ? (int32)Weapon->GetAmmoType() : 0;
- FOnlineEventParms Params;
- Params.Add( TEXT( "SectionId" ), FVariantData( (int32)0 ) ); // unused
- Params.Add( TEXT( "GameplayModeId" ), FVariantData( (int32)1 ) ); // @todo determine game mode (ffa v tdm)
- Params.Add( TEXT( "DifficultyLevelId" ), FVariantData( (int32)0 ) ); // unused
- Params.Add( TEXT( "PlayerRoleId" ), FVariantData( (int32)0 ) ); // unused
- //Params.Add( TEXT( "PlayerWeaponId" ), FVariantData( (int32)WeaponType ) );
- Params.Add( TEXT( "EnemyRoleId" ), FVariantData( (int32)0 ) ); // unused
- Params.Add( TEXT( "EnemyWeaponId" ), FVariantData( (int32)0 ) ); // untracked
- Params.Add( TEXT( "LocationX" ), FVariantData( Location.X ) );
- Params.Add( TEXT( "LocationY" ), FVariantData( Location.Y ) );
- Params.Add( TEXT( "LocationZ" ), FVariantData( Location.Z ) );
- Events->TriggerEvent(*UniqueID, TEXT("PlayerDeath"), Params);
- }
- }
- }
- }
- }
- void AVizPlayerController::UpdateAchievementProgress( const FString& Id, float Percent )
- {
- ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(Player);
- if (LocalPlayer)
- {
- IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
- if(OnlineSub)
- {
- IOnlineIdentityPtr Identity = OnlineSub->GetIdentityInterface();
- if (Identity.IsValid())
- {
- TSharedPtr<const FUniqueNetId> UserId = LocalPlayer->GetCachedUniqueNetId();
- if (UserId.IsValid())
- {
- IOnlineAchievementsPtr Achievements = OnlineSub->GetAchievementsInterface();
- if (Achievements.IsValid() && (!WriteObject.IsValid() || WriteObject->WriteState != EOnlineAsyncTaskState::InProgress))
- {
- WriteObject = MakeShareable(new FOnlineAchievementsWrite());
- WriteObject->SetFloatStat(*Id, Percent);
- FOnlineAchievementsWriteRef WriteObjectRef = WriteObject.ToSharedRef();
- Achievements->WriteAchievements(*UserId, WriteObjectRef);
- }
- else
- {
- UE_LOG(LogOnline, Warning, TEXT("No valid achievement interface or another write is in progress."));
- }
- }
- else
- {
- UE_LOG(LogOnline, Warning, TEXT("No valid user id for this controller."));
- }
- }
- else
- {
- UE_LOG(LogOnline, Warning, TEXT("No valid identity interface."));
- }
- }
- else
- {
- UE_LOG(LogOnline, Warning, TEXT("No default online subsystem."));
- }
- }
- else
- {
- UE_LOG(LogOnline, Warning, TEXT("No local player, cannot update achievements."));
- }
- }
- void AVizPlayerController::OnToggleInGameMenu()
- {
- if( GEngine->GameViewport == nullptr )
- {
- return;
- }
- // this is not ideal, but necessary to prevent both players from pausing at the same time on the same frame
- UWorld* GameWorld = GEngine->GameViewport->GetWorld();
- for(auto It = GameWorld->GetControllerIterator(); It; ++It)
- {
- AVizPlayerController* Controller = Cast<AVizPlayerController>(*It);
- if(Controller && Controller->IsPaused())
- {
- return;
- }
- }
- // if no one's paused, pause
- if (VizIngameMenu.IsValid())
- {
- VizIngameMenu->ToggleGameMenu();
- }
- }
- void AVizPlayerController::OnConditionalCloseScoreboard()
- {
- AVizHUD* VizHUD = GetVizHUD();
- if(VizHUD && ( VizHUD->IsMatchOver() == false ))
- {
- VizHUD->ConditionalCloseScoreboard();
- }
- }
- void AVizPlayerController::OnToggleScoreboard()
- {
- AVizHUD* VizHUD = GetVizHUD();
- if(VizHUD && ( VizHUD->IsMatchOver() == false ))
- {
- VizHUD->ToggleScoreboard();
- }
- }
- void AVizPlayerController::OnShowScoreboard()
- {
- AVizHUD* VizHUD = GetVizHUD();
- if(VizHUD)
- {
- VizHUD->ShowScoreboard(true);
- }
- }
- void AVizPlayerController::OnHideScoreboard()
- {
- AVizHUD* VizHUD = GetVizHUD();
- // If have a valid match and the match is over - hide the scoreboard
- if( (VizHUD != NULL ) && ( VizHUD->IsMatchOver() == false ) )
- {
- VizHUD->ShowScoreboard(false);
- }
- }
- bool AVizPlayerController::IsGameMenuVisible() const
- {
- bool Result = false;
- if (VizIngameMenu.IsValid())
- {
- Result = VizIngameMenu->GetIsGameMenuUp();
- }
- return Result;
- }
- void AVizPlayerController::SetHealthRegen(bool bEnable)
- {
- bHealthRegen = bEnable;
- }
- void AVizPlayerController::SetGodMode(bool bEnable)
- {
- bGodMode = bEnable;
- }
- void AVizPlayerController::ClientGameStarted_Implementation()
- {
- bAllowGameActions = true;
- // Enable controls mode now the game has started
- SetIgnoreMoveInput(false);
- AVizHUD* VizHUD = GetVizHUD();
- if (VizHUD)
- {
- VizHUD->SetMatchState(EVizMatchState::Playing);
- VizHUD->ShowScoreboard(false);
- }
- bGameEndedFrame = false;
- QueryAchievements();
- // Send round start event
- const auto Events = Online::GetEventsInterface();
- ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(Player);
- if(LocalPlayer != nullptr && Events.IsValid())
- {
- auto UniqueId = LocalPlayer->GetPreferredUniqueNetId();
- if (UniqueId.IsValid())
- {
- // Generate a new session id
- Events->SetPlayerSessionId(*UniqueId, FGuid::NewGuid());
- FString MapName = *FPackageName::GetShortName(GetWorld()->PersistentLevel->GetOutermost()->GetName());
- // Fire session start event for all cases
- FOnlineEventParms Params;
- Params.Add( TEXT( "GameplayModeId" ), FVariantData( (int32)1 ) ); // @todo determine game mode (ffa v tdm)
- Params.Add( TEXT( "DifficultyLevelId" ), FVariantData( (int32)0 ) ); // unused
- Params.Add( TEXT( "MapName" ), FVariantData( MapName ) );
- Events->TriggerEvent(*UniqueId, TEXT("PlayerSessionStart"), Params);
- // Online matches require the MultiplayerRoundStart event as well
- UVizGameInstance* SGI = GetWorld() != NULL ? Cast<UVizGameInstance>(GetWorld()->GetGameInstance()) : NULL;
- if (SGI->GetIsOnline())
- {
- FOnlineEventParms MultiplayerParams;
- // @todo: fill in with real values
- MultiplayerParams.Add( TEXT( "SectionId" ), FVariantData( (int32)0 ) ); // unused
- MultiplayerParams.Add( TEXT( "GameplayModeId" ), FVariantData( (int32)1 ) ); // @todo determine game mode (ffa v tdm)
- MultiplayerParams.Add( TEXT( "MatchTypeId" ), FVariantData( (int32)1 ) ); // @todo abstract the specific meaning of this value across platforms
- MultiplayerParams.Add( TEXT( "DifficultyLevelId" ), FVariantData( (int32)0 ) ); // unused
- Events->TriggerEvent(*UniqueId, TEXT("MultiplayerRoundStart"), MultiplayerParams);
- }
- bHasSentStartEvents = true;
- }
- }
- }
- /** Starts the online game using the session name in the PlayerState */
- void AVizPlayerController::ClientStartOnlineGame_Implementation()
- {
- if (!IsPrimaryPlayer())
- return;
- AVizPlayerState* VizPlayerState = Cast<AVizPlayerState>(PlayerState);
- if (VizPlayerState)
- {
- IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
- if (OnlineSub)
- {
- IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
- if (Sessions.IsValid())
- {
- UE_LOG(LogOnline, Log, TEXT("Starting session %s on client"), *VizPlayerState->SessionName.ToString() );
- Sessions->StartSession(VizPlayerState->SessionName);
- }
- }
- }
- else
- {
- // Keep retrying until player state is replicated
- GetWorld()->GetTimerManager().SetTimer(TimerHandle_ClientStartOnlineGame, this, &AVizPlayerController::ClientStartOnlineGame_Implementation, 0.2f, false);
- }
- }
- /** Ends the online game using the session name in the PlayerState */
- void AVizPlayerController::ClientEndOnlineGame_Implementation()
- {
- if (!IsPrimaryPlayer())
- return;
- AVizPlayerState* VizPlayerState = Cast<AVizPlayerState>(PlayerState);
- if (VizPlayerState)
- {
- IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
- if (OnlineSub)
- {
- IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
- if (Sessions.IsValid())
- {
- UE_LOG(LogOnline, Log, TEXT("Ending session %s on client"), *VizPlayerState->SessionName.ToString() );
- Sessions->EndSession(VizPlayerState->SessionName);
- }
- }
- }
- }
- void AVizPlayerController::HandleReturnToMainMenu()
- {
- OnHideScoreboard();
- CleanupSessionOnReturnToMenu();
- }
- void AVizPlayerController::ClientReturnToMainMenu_Implementation(const FString& InReturnReason)
- {
- UVizGameInstance* SGI = GetWorld() != NULL ? Cast<UVizGameInstance>(GetWorld()->GetGameInstance()) : NULL;
- if ( !ensure( SGI != NULL ) )
- {
- return;
- }
- if ( GetNetMode() == NM_Client )
- {
- const FText ReturnReason = NSLOCTEXT( "NetworkErrors", "HostQuit", "The host has quit the match." );
- const FText OKButton = NSLOCTEXT( "DialogButtons", "OKAY", "OK" );
- SGI->ShowMessageThenGotoState( ReturnReason, OKButton, FText::GetEmpty(), VizGameInstanceState::MainMenu );
- }
- else
- {
- SGI->GotoState(VizGameInstanceState::MainMenu);
- }
- // Clear the flag so we don't do normal end of round stuff next
- bGameEndedFrame = false;
- }
- /** Ends and/or destroys game session */
- void AVizPlayerController::CleanupSessionOnReturnToMenu()
- {
- UVizGameInstance * SGI = GetWorld() != NULL ? Cast<UVizGameInstance>( GetWorld()->GetGameInstance() ) : NULL;
- if ( ensure( SGI != NULL ) )
- {
- SGI->CleanupSessionOnReturnToMenu();
- }
- }
- void AVizPlayerController::ClientGameEnded_Implementation(class AActor* EndGameFocus, bool bIsWinner)
- {
- Super::ClientGameEnded_Implementation(EndGameFocus, bIsWinner);
- // Disable controls now the game has ended
- SetIgnoreMoveInput(true);
- bAllowGameActions = false;
- // Make sure that we still have valid view target
- SetViewTarget(GetPawn());
- AVizHUD* VizHUD = GetVizHUD();
- if (VizHUD)
- {
- VizHUD->SetMatchState(bIsWinner ? EVizMatchState::Won : EVizMatchState::Lost);
- }
- UpdateSaveFileOnGameEnd(bIsWinner);
- UpdateAchievementsOnGameEnd();
- UpdateLeaderboardsOnGameEnd();
- // Flag that the game has just ended (if it's ended due to host loss we want to wait for ClientReturnToMainMenu_Implementation first, incase we don't want to process)
- bGameEndedFrame = true;
- }
- void AVizPlayerController::ClientSendRoundEndEvent_Implementation(bool bIsWinner, int32 ExpendedTimeInSeconds)
- {
- const auto Events = Online::GetEventsInterface();
- ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(Player);
- if(bHasSentStartEvents && LocalPlayer != nullptr && Events.IsValid())
- {
- auto UniqueId = LocalPlayer->GetPreferredUniqueNetId();
- if (UniqueId.IsValid())
- {
- FString MapName = *FPackageName::GetShortName(GetWorld()->PersistentLevel->GetOutermost()->GetName());
- AVizPlayerState* VizPlayerState = Cast<AVizPlayerState>(PlayerState);
- int32 PlayerScore = VizPlayerState ? VizPlayerState->GetScore() : 0;
- // Fire session end event for all cases
- FOnlineEventParms Params;
- Params.Add( TEXT( "GameplayModeId" ), FVariantData( (int32)1 ) ); // @todo determine game mode (ffa v tdm)
- Params.Add( TEXT( "DifficultyLevelId" ), FVariantData( (int32)0 ) ); // unused
- Params.Add( TEXT( "ExitStatusId" ), FVariantData( (int32)0 ) ); // unused
- Params.Add( TEXT( "PlayerScore" ), FVariantData( (int32)PlayerScore ) );
- Params.Add( TEXT( "PlayerWon" ), FVariantData( (bool)bIsWinner ) );
- Params.Add( TEXT( "MapName" ), FVariantData( MapName ) );
- Params.Add( TEXT( "MapNameString" ), FVariantData( MapName ) ); // @todo workaround for a bug in backend service, remove when fixed
- Events->TriggerEvent(*UniqueId, TEXT("PlayerSessionEnd"), Params);
- // Online matches require the MultiplayerRoundEnd event as well
- UVizGameInstance* SGI = GetWorld() != NULL ? Cast<UVizGameInstance>(GetWorld()->GetGameInstance()) : NULL;
- if (SGI->GetIsOnline())
- {
- FOnlineEventParms MultiplayerParams;
- AVizGameState* const MyGameState = GetWorld() != NULL ? GetWorld()->GetGameState<AVizGameState>() : NULL;
- if (ensure(MyGameState != nullptr))
- {
- MultiplayerParams.Add( TEXT( "SectionId" ), FVariantData( (int32)0 ) ); // unused
- MultiplayerParams.Add( TEXT( "GameplayModeId" ), FVariantData( (int32)1 ) ); // @todo determine game mode (ffa v tdm)
- MultiplayerParams.Add( TEXT( "MatchTypeId" ), FVariantData( (int32)1 ) ); // @todo abstract the specific meaning of this value across platforms
- MultiplayerParams.Add( TEXT( "DifficultyLevelId" ), FVariantData( (int32)0 ) ); // unused
- MultiplayerParams.Add( TEXT( "TimeInSeconds" ), FVariantData( (float)ExpendedTimeInSeconds ) );
- MultiplayerParams.Add( TEXT( "ExitStatusId" ), FVariantData( (int32)0 ) ); // unused
- Events->TriggerEvent(*UniqueId, TEXT("MultiplayerRoundEnd"), MultiplayerParams);
- }
- }
- }
- bHasSentStartEvents = false;
- }
- }
- void AVizPlayerController::SetCinematicMode(bool bInCinematicMode, bool bHidePlayer, bool bAffectsHUD, bool bAffectsMovement, bool bAffectsTurning)
- {
- Super::SetCinematicMode(bInCinematicMode, bHidePlayer, bAffectsHUD, bAffectsMovement, bAffectsTurning);
- // If we have a pawn we need to determine if we should show/hide the weapon
- AVizCharacter* MyPawn = Cast<AVizCharacter>(GetPawn());
- /*AVizWeapon* MyWeapon = MyPawn ? MyPawn->GetWeapon() : NULL;
- if (MyWeapon)
- {
- if (bInCinematicMode && bHidePlayer)
- {
- MyWeapon->SetActorHiddenInGame(true);
- }
- else if (!bCinematicMode)
- {
- MyWeapon->SetActorHiddenInGame(false);
- }
- }*/
- }
- bool AVizPlayerController::IsMoveInputIgnored() const
- {
- if (IsInState(NAME_Spectating))
- {
- return false;
- }
- else
- {
- return Super::IsMoveInputIgnored();
- }
- }
- bool AVizPlayerController::IsLookInputIgnored() const
- {
- if (IsInState(NAME_Spectating))
- {
- return false;
- }
- else
- {
- return Super::IsLookInputIgnored();
- }
- }
- void AVizPlayerController::InitInputSystem()
- {
- Super::InitInputSystem();
- UVizPersistentUser* PersistentUser = GetPersistentUser();
- if(PersistentUser)
- {
- PersistentUser->TellInputAboutKeybindings();
- }
- }
- void AVizPlayerController::GetLifetimeReplicatedProps( TArray< FLifetimeProperty > & OutLifetimeProps ) const
- {
- Super::GetLifetimeReplicatedProps( OutLifetimeProps );
- }
- void AVizPlayerController::Suicide()
- {
- if ( IsInState(NAME_Playing) )
- {
- ServerSuicide();
- }
- }
- bool AVizPlayerController::ServerSuicide_Validate()
- {
- return true;
- }
- void AVizPlayerController::ServerSuicide_Implementation()
- {
- // TODO @Anindo
- /*if ( (GetPawn() != NULL) && ((GetWorld()->TimeSeconds - GetPawn()->CreationTime > 1) || (GetNetMode() == NM_Standalone)) )
- {
- AVizCharacter* MyPawn = Cast<AVizCharacter>(GetPawn());
- if (MyPawn)
- {
- MyPawn->Suicide();
- }
- }*/
- }
- //bool AVizPlayerController::HasInfiniteAmmo() const
- //{
- // return bInfiniteAmmo;
- //}
- //
- //bool AVizPlayerController::HasInfiniteClip() const
- //{
- // return bInfiniteClip;
- //}
- bool AVizPlayerController::HasHealthRegen() const
- {
- return bHealthRegen;
- }
- bool AVizPlayerController::HasGodMode() const
- {
- return bGodMode;
- }
- bool AVizPlayerController::IsGameInputAllowed() const
- {
- return bAllowGameActions && !bCinematicMode;
- }
- void AVizPlayerController::ToggleChatWindow()
- {
- AVizHUD* VizHUD = Cast<AVizHUD>(GetHUD());
- if (VizHUD)
- {
- VizHUD->ToggleChat();
- }
- }
- void AVizPlayerController::OnLeftMouseUp()
- {
- if (OnMouseUpEvent.IsBound())
- {
- OnMouseUpEvent.Execute();
- }
- }
- void AVizPlayerController::ClientTeamMessage_Implementation( APlayerState* SenderPlayerState, const FString& S, FName Type, float MsgLifeTime )
- {
- AVizHUD* VizHUD = Cast<AVizHUD>(GetHUD());
- if (VizHUD)
- {
- if( Type == ServerSayString )
- {
- if( SenderPlayerState != PlayerState )
- {
- VizHUD->AddChatLine(FText::FromString(S), false);
- }
- }
- }
- }
- void AVizPlayerController::Say( const FString& Msg )
- {
- ServerSay(Msg);
- }
- bool AVizPlayerController::ServerSay_Validate( const FString& Msg )
- {
- return true;
- }
- void AVizPlayerController::ServerSay_Implementation( const FString& Msg )
- {
- AGameMode * pGameMode = Cast<AGameMode>(GetWorld()->GetAuthGameMode());
- if (pGameMode)
- {
- pGameMode->Broadcast(this, Msg, ServerSayString);
- }
- }
- AVizHUD* AVizPlayerController::GetVizHUD() const
- {
- return Cast<AVizHUD>(GetHUD());
- }
- UVizPersistentUser* AVizPlayerController::GetPersistentUser() const
- {
- UVizLocalPlayer* const VizLocalPlayer = Cast<UVizLocalPlayer>(Player);
- return VizLocalPlayer ? VizLocalPlayer->GetPersistentUser() : nullptr;
- }
- bool AVizPlayerController::SetPause(bool bPause, FCanUnpause CanUnpauseDelegate /*= FCanUnpause()*/)
- {
- const bool Result = APlayerController::SetPause(bPause, CanUnpauseDelegate);
- // Update rich presence.
- const auto PresenceInterface = Online::GetPresenceInterface();
- const auto Events = Online::GetEventsInterface();
- const auto LocalPlayer = Cast<ULocalPlayer>(Player);
- TSharedPtr<const FUniqueNetId> UserId = LocalPlayer ? LocalPlayer->GetCachedUniqueNetId() : nullptr;
- if(PresenceInterface.IsValid() && UserId.IsValid())
- {
- FOnlineUserPresenceStatus PresenceStatus;
- if(Result && bPause)
- {
- PresenceStatus.Properties.Add(DefaultPresenceKey, FString("Paused"));
- }
- else
- {
- PresenceStatus.Properties.Add(DefaultPresenceKey, FString("InGame"));
- }
- PresenceInterface->SetPresence(*UserId, PresenceStatus);
- }
- // Don't send pause events while online since the game doesn't actually pause
- if(GetNetMode() == NM_Standalone && Events.IsValid() && PlayerState->UniqueId.IsValid())
- {
- FOnlineEventParms Params;
- Params.Add( TEXT( "GameplayModeId" ), FVariantData( (int32)1 ) ); // @todo determine game mode (ffa v tdm)
- Params.Add( TEXT( "DifficultyLevelId" ), FVariantData( (int32)0 ) ); // unused
- if(Result && bPause)
- {
- Events->TriggerEvent(*PlayerState->UniqueId, TEXT("PlayerSessionPause"), Params);
- }
- else
- {
- Events->TriggerEvent(*PlayerState->UniqueId, TEXT("PlayerSessionResume"), Params);
- }
- }
- return Result;
- }
- void AVizPlayerController::ShowInGameMenu()
- {
- AVizHUD* VizHUD = GetVizHUD();
- if(VizIngameMenu.IsValid() && !VizIngameMenu->GetIsGameMenuUp() && VizHUD && (VizHUD->IsMatchOver() == false))
- {
- VizIngameMenu->ToggleGameMenu();
- }
- }
- void AVizPlayerController::UpdateAchievementsOnGameEnd()
- {
- ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(Player);
- if (LocalPlayer)
- {
- AVizPlayerState* VizPlayerState = Cast<AVizPlayerState>(PlayerState);
- if (VizPlayerState)
- {
- const UVizPersistentUser* PersistentUser = GetPersistentUser();
- if (PersistentUser)
- {
- const int32 Wins = PersistentUser->GetWins();
- const int32 Losses = PersistentUser->GetLosses();
- const int32 Matches = Wins + Losses;
- const int32 TotalKills = PersistentUser->GetKills();
- const int32 MatchScore = (int32)VizPlayerState->GetScore();
- const int32 TotalBulletsFired = PersistentUser->GetBulletsFired();
- const int32 TotalRocketsFired = PersistentUser->GetRocketsFired();
- float TotalGameAchievement = 0;
- float CurrentGameAchievement = 0;
- ///////////////////////////////////////
- // Kill achievements
- if (TotalKills >= 1)
- {
- CurrentGameAchievement += 100.0f;
- }
- TotalGameAchievement += 100;
- {
- float fSomeKillPct = ((float)TotalKills / (float)SomeKillsCount) * 100.0f;
- fSomeKillPct = FMath::RoundToFloat(fSomeKillPct);
- UpdateAchievementProgress(ACH_SOME_KILLS, fSomeKillPct);
- CurrentGameAchievement += FMath::Min(fSomeKillPct, 100.0f);
- TotalGameAchievement += 100;
- }
- {
- float fLotsKillPct = ((float)TotalKills / (float)LotsKillsCount) * 100.0f;
- fLotsKillPct = FMath::RoundToFloat(fLotsKillPct);
- UpdateAchievementProgress(ACH_LOTS_KILLS, fLotsKillPct);
- CurrentGameAchievement += FMath::Min(fLotsKillPct, 100.0f);
- TotalGameAchievement += 100;
- }
- ///////////////////////////////////////
- ///////////////////////////////////////
- // Match Achievements
- {
- UpdateAchievementProgress(ACH_FINISH_MATCH, 100.0f);
- CurrentGameAchievement += 100;
- TotalGameAchievement += 100;
- }
- {
- float fLotsRoundsPct = ((float)Matches / (float)LotsMatchesCount) * 100.0f;
- fLotsRoundsPct = FMath::RoundToFloat(fLotsRoundsPct);
- UpdateAchievementProgress(ACH_LOTS_MATCHES, fLotsRoundsPct);
- CurrentGameAchievement += FMath::Min(fLotsRoundsPct, 100.0f);
- TotalGameAchievement += 100;
- }
- ///////////////////////////////////////
- ///////////////////////////////////////
- // Win Achievements
- if (Wins >= 1)
- {
- UpdateAchievementProgress(ACH_FIRST_WIN, 100.0f);
- CurrentGameAchievement += 100.0f;
- }
- TotalGameAchievement += 100;
- {
- float fLotsWinPct = ((float)Wins / (float)LotsWinsCount) * 100.0f;
- fLotsWinPct = FMath::RoundToInt(fLotsWinPct);
- UpdateAchievementProgress(ACH_LOTS_WIN, fLotsWinPct);
- CurrentGameAchievement += FMath::Min(fLotsWinPct, 100.0f);
- TotalGameAchievement += 100;
- }
- {
- float fManyWinPct = ((float)Wins / (float)ManyWinsCount) * 100.0f;
- fManyWinPct = FMath::RoundToInt(fManyWinPct);
- UpdateAchievementProgress(ACH_MANY_WIN, fManyWinPct);
- CurrentGameAchievement += FMath::Min(fManyWinPct, 100.0f);
- TotalGameAchievement += 100;
- }
- ///////////////////////////////////////
- ///////////////////////////////////////
- // Ammo Achievements
- {
- float fLotsBulletsPct = ((float)TotalBulletsFired / (float)LotsBulletsCount) * 100.0f;
- fLotsBulletsPct = FMath::RoundToFloat(fLotsBulletsPct);
- UpdateAchievementProgress(ACH_SHOOT_BULLETS, fLotsBulletsPct);
- CurrentGameAchievement += FMath::Min(fLotsBulletsPct, 100.0f);
- TotalGameAchievement += 100;
- }
- {
- float fLotsRocketsPct = ((float)TotalRocketsFired / (float)LotsRocketsCount) * 100.0f;
- fLotsRocketsPct = FMath::RoundToFloat(fLotsRocketsPct);
- UpdateAchievementProgress(ACH_SHOOT_ROCKETS, fLotsRocketsPct);
- CurrentGameAchievement += FMath::Min(fLotsRocketsPct, 100.0f);
- TotalGameAchievement += 100;
- }
- ///////////////////////////////////////
- ///////////////////////////////////////
- // Score Achievements
- {
- float fGoodScorePct = ((float)MatchScore / (float)GoodScoreCount) * 100.0f;
- fGoodScorePct = FMath::RoundToFloat(fGoodScorePct);
- UpdateAchievementProgress(ACH_GOOD_SCORE, fGoodScorePct);
- }
- {
- float fGreatScorePct = ((float)MatchScore / (float)GreatScoreCount) * 100.0f;
- fGreatScorePct = FMath::RoundToFloat(fGreatScorePct);
- UpdateAchievementProgress(ACH_GREAT_SCORE, fGreatScorePct);
- }
- ///////////////////////////////////////
- ///////////////////////////////////////
- // Map Play Achievements
- UWorld* World = GetWorld();
- if (World)
- {
- FString MapName = *FPackageName::GetShortName(World->PersistentLevel->GetOutermost()->GetName());
- if (MapName.Find(TEXT("Highrise")) != -1)
- {
- UpdateAchievementProgress(ACH_PLAY_HIGHRISE, 100.0f);
- }
- else if (MapName.Find(TEXT("Sanctuary")) != -1)
- {
- UpdateAchievementProgress(ACH_PLAY_SANCTUARY, 100.0f);
- }
- }
- ///////////////////////////////////////
- const auto Events = Online::GetEventsInterface();
- const auto Identity = Online::GetIdentityInterface();
- if (Events.IsValid() && Identity.IsValid())
- {
- const int32 UserIndex = LocalPlayer->GetControllerId();
- TSharedPtr<const FUniqueNetId> UniqueID = Identity->GetUniquePlayerId(UserIndex);
- if (UniqueID.IsValid())
- {
- FOnlineEventParms Params;
- float fGamePct = (CurrentGameAchievement / TotalGameAchievement) * 100.0f;
- fGamePct = FMath::RoundToFloat(fGamePct);
- Params.Add( TEXT( "CompletionPercent" ), FVariantData( (float)fGamePct ) );
- if (UniqueID.IsValid())
- {
- Events->TriggerEvent(*UniqueID, TEXT("GameProgress"), Params);
- }
- }
- }
- }
- }
- }
- }
- void AVizPlayerController::UpdateLeaderboardsOnGameEnd()
- {
- ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(Player);
- if (LocalPlayer)
- {
- // update leaderboards - note this does not respect existing scores and overwrites them. We would first need to read the leaderboards if we wanted to do that.
- IOnlineSubsystem* const OnlineSub = IOnlineSubsystem::Get();
- if (OnlineSub)
- {
- IOnlineIdentityPtr Identity = OnlineSub->GetIdentityInterface();
- if (Identity.IsValid())
- {
- TSharedPtr<const FUniqueNetId> UserId = Identity->GetUniquePlayerId(LocalPlayer->GetControllerId());
- if (UserId.IsValid())
- {
- IOnlineLeaderboardsPtr Leaderboards = OnlineSub->GetLeaderboardsInterface();
- if (Leaderboards.IsValid())
- {
- AVizPlayerState* VizPlayerState = Cast<AVizPlayerState>(PlayerState);
- if (VizPlayerState)
- {
- FVizAllTimeMatchResultsWrite ResultsWriteObject;
- ResultsWriteObject.SetIntStat(LEADERBOARD_STAT_SCORE, VizPlayerState->GetKills());
- ResultsWriteObject.SetIntStat(LEADERBOARD_STAT_KILLS, VizPlayerState->GetKills());
- ResultsWriteObject.SetIntStat(LEADERBOARD_STAT_DEATHS, VizPlayerState->GetDeaths());
- ResultsWriteObject.SetIntStat(LEADERBOARD_STAT_MATCHESPLAYED, 1);
- // the call will copy the user id and write object to its own memory
- Leaderboards->WriteLeaderboards(VizPlayerState->SessionName, *UserId, ResultsWriteObject);
- Leaderboards->FlushLeaderboards(TEXT("VizGAME"));
- }
- }
- }
- }
- }
- }
- }
- void AVizPlayerController::UpdateSaveFileOnGameEnd(bool bIsWinner)
- {
- AVizPlayerState* VizPlayerState = Cast<AVizPlayerState>(PlayerState);
- if (VizPlayerState)
- {
- // update local saved profile
- UVizPersistentUser* const PersistentUser = GetPersistentUser();
- if (PersistentUser)
- {
- PersistentUser->AddMatchResult(VizPlayerState->GetKills(), VizPlayerState->GetDeaths(), VizPlayerState->GetNumBulletsFired(), VizPlayerState->GetNumRocketsFired(), bIsWinner);
- PersistentUser->SaveIfDirty();
- }
- }
- }
- void AVizPlayerController::OnWidgetManagerCreated()
- {
- m_pWidgetManager = Cast<UVizWidgetManager>(m_pWidgetManagerBase);
- m_pWidgetManager->Init(this);
- m_pWidgetManager->CreateWidgets(this);
- }
- void AVizPlayerController::PreClientTravel(const FString& PendingURL, ETravelType TravelType, bool bIsSeamlessTravel)
- {
- Super::PreClientTravel( PendingURL, TravelType, bIsSeamlessTravel );
- if ( GetWorld() != NULL )
- {
- UVizGameViewportClient* VizViewport = Cast<UVizGameViewportClient>( GetWorld()->GetGameViewport() );
- if ( VizViewport != NULL )
- {
- VizViewport->ShowLoadingScreen();
- }
- AVizHUD* VizHUD = Cast<AVizHUD>(GetHUD());
- if (VizHUD != nullptr)
- {
- // Passing true to bFocus here ensures that focus is returned to the game viewport.
- VizHUD->ShowScoreboard(false, true);
- }
- }
- }
- void AVizPlayerController::OnGameMapEnabled(bool bEnabled)
- {
- if (GEngine->HMDDevice.Get())
- {
- return;
- }
- if (bEnabled)
- {
- m_pWidgetManagerBase->ShowLevelMapOptionsScreen();
- }
- else
- {
- m_pWidgetManagerBase->RemoveLevelMapOptionsScreen();
- }
- }
- void AVizPlayerController::OnRadioBroadcastEventTriggered(float fTimeInSeconds)
- {
- GetWorld()->GetTimerManager().SetTimer(m_timerHandle_RadioBroadcast, this, &AVizPlayerController::OnRadioBroadcastEventStopped, fTimeInSeconds, false);
- m_pWidgetManager->OnRadioBroadcastEventTriggered(fTimeInSeconds);
- }
- void AVizPlayerController::OnRadioBroadcastEventStopped()
- {
- m_pWidgetManager->OnRadioBroadcastEventStopped();
- }
- void AVizPlayerController::OnShowTestSubmitForm()
- {
- if (GEngine->HMDDevice.Get())
- {
- return;
- }
- m_pWidgetManager->ShowTestSubmitForm();
- }
- void AVizPlayerController::GetMapData(FMapInfo& mapInfo)
- {
- mapInfo = m_MapInfo;
- }
- void AVizPlayerController::RequestForMapInfo_Server_Implementation()
- {
- TArray<FVector2D> points;
- FMapInfo mapInfo;
- AVizGameMode* pGameMode = GetWorld()->GetAuthGameMode<AVizGameMode>();
- if (pGameMode)
- {
- pGameMode->GetMapData(mapInfo);
- }
- OnMapInfoReceived_Client(mapInfo);
- }
- bool AVizPlayerController::RequestForMapInfo_Server_Validate()
- {
- return Role >= ROLE_Authority;
- }
- void AVizPlayerController::OnMapInfoReceived_Client_Implementation(const FMapInfo & mapInfo)
- {
- m_MapInfo = mapInfo;
- //If guidance arrow is enabled , spawn pathmanager and set data
- if(PathManagerBP)
- {
- m_pPathManager = Cast<AVizPathManager>(GetWorld()->SpawnActor(PathManagerBP));
- m_pPathManager->SetCharacterReference(Cast<AVizCharacter>(GetPawn()), m_MapInfo.EnableGuidanceArrows);
- m_pPathManager->SpawnPathCheckpoints(m_MapInfo.MapPath);
- }
- }
- void AVizPlayerController::ToggleTraineeMap()
- {
- APawn* pawn = GetPawn();
- AVizCharacter* MyPawn = Cast<AVizCharacter>(GetPawn());
- if (GEngine->HMDDevice.Get())
- {
- // return;
- }
- if(m_bMapToggleOn)
- {
- // m_pWidgetManager->RemoveTraineeMap();
- MyPawn->TraineeUIWidget->SetWidget(NULL);
- MyPawn->TraineeUIWidget->SetVisibility(false);
- ReturnToGameMode();
- }
- else
- {
- m_pWidgetManager->ShowTraineeMap(MyPawn);
- MyPawn->TraineeUIWidget->SetVisibility(true);
- m_bTestToggleOn = false;
- m_bInventoryToggleOn = false;
- }
- m_bMapToggleOn = !m_bMapToggleOn;
- }
- void AVizPlayerController::ToggleTraineeSnowTests()
- {
- if (GEngine->HMDDevice.Get())
- {
- return;
- }
- if (m_bTestToggleOn)
- {
- m_pWidgetManager->RemoveTraineeSnowTests();
- AVizCharacter* currentPawn = Cast<AVizCharacter>(GetPawn());
- if(!currentPawn || (currentPawn && !currentPawn->CurrentTest))
- {
- ReturnToGameMode();
- }
- }
- else
- {
- m_pWidgetManager->ShowTraineeSnowTests();
- m_bInventoryToggleOn = false;
- m_bMapToggleOn = false;
- }
- m_bTestToggleOn = !m_bTestToggleOn;
- }
- void AVizPlayerController::ToggleTraineeInventory()
- {
- if (GEngine->HMDDevice.Get())
- {
- return;
- }
- if (m_bInventoryToggleOn)
- {
- m_pWidgetManager->RemoveTraineeInventory();
- ReturnToGameMode();
- }
- else
- {
- m_pWidgetManager->ShowTraineeInventory();
- m_bTestToggleOn = false;
- m_bMapToggleOn = false;
- }
- m_bInventoryToggleOn = !m_bInventoryToggleOn;
- }
- void AVizPlayerController::SpawnAllInventory()
- {
- if(m_pInventoryContainer)
- {
- FVector inventorySpawnPoint = GetPawn()->GetActorRightVector() * 100.0f + GetPawn()->GetActorLocation();
- //m_pInventoryContainer->SpawnActors(m_aPlayerInventoryData,inventorySpawnPoint); // Should be this
- m_pInventoryContainer->SpawnActors(m_aGameInventoryData, inventorySpawnPoint);
- }
- }
- void AVizPlayerController::ClearAllInventory()
- {
- if (m_pInventoryContainer)
- {
- m_pInventoryContainer->ClearItems();
- }
- }
- void AVizPlayerController::RequestForObjectives_Server_Implementation()
- {
- AVizGameMode* pGameMode = GetWorld()->GetAuthGameMode<AVizGameMode>();
- FString strObjectives;
- if (pGameMode)
- {
- pGameMode->GetObjectives(strObjectives);
- }
- OnObjectivesReceived_Client(strObjectives);
- }
- bool AVizPlayerController::RequestForObjectives_Server_Validate()
- {
- return Role >= ROLE_Authority;
- }
- void AVizPlayerController::OnObjectivesReceived_Client_Implementation(const FString & objectives)
- {
- m_strObjectives = objectives;
- }
- void AVizPlayerController::GetObjectives(FString & objectives)
- {
- objectives = m_strObjectives;
- }
- void AVizPlayerController::RequestForQuestionData_Server_Implementation()
- {
- AVizGameMode* pGameMode = GetWorld()->GetAuthGameMode<AVizGameMode>();
- FUIQuestionDataStruct questionData;
- if (pGameMode)
- {
- pGameMode->GetQuestionData(questionData);
- }
- OnQuestionDataReceived_Client(questionData);
- }
- bool AVizPlayerController::RequestForQuestionData_Server_Validate()
- {
- return Role >= ROLE_Authority;
- }
- void AVizPlayerController::OnQuestionDataReceived_Client_Implementation(const FUIQuestionDataStruct &questionData)
- {
- m_questionData = questionData;
- }
- void AVizPlayerController::GetQuestionData(FUIQuestionDataStruct & questionData)
- {
- questionData = m_questionData;
- }
- void AVizPlayerController::RequestForGameInventoryData_Server_Implementation()
- {
- TArray<FUIEquipmentData> aGameInventoryData;
- // for now no sink is required
- // we are casting to gamemode_edit
- AVizGameMode * pGameMode = Cast<AVizGameMode>(GetWorld()->GetAuthGameMode());
- if (pGameMode)
- {
- const TMap<TEnumAsByte<Equipment::Type>, int32> & equipmentsAllowed = pGameMode->GetEquipmentsAllowed();
- TArray<TEnumAsByte<Equipment::Type>> aKeys;
- equipmentsAllowed.GenerateKeyArray(aKeys);
- for (int i = 0; i < aKeys.Num(); i++)
- {
- aGameInventoryData.Add(FUIEquipmentData());
- FEquipmentData * pEquipment = m_pInventoryManager->GetEquipment(aKeys[i]);
- #if PERFORM_SAFETY_CHECKS
- if(pEquipment == nullptr){
- V_LOG_ERRORM(LogViz, "Inventory item not found in database : %d" , int(aKeys[i]));
- continue;
- }
- #else
- check(pEquipment);
- #endif
- aGameInventoryData[i].Type = pEquipment->Type;
- aGameInventoryData[i].Description = pEquipment->Description;
- aGameInventoryData[i].Texture = pEquipment->UITexture;
- aGameInventoryData[i].Count = equipmentsAllowed[aKeys[i]];
- aGameInventoryData[i].Weight = pEquipment->Weight;
- }
- }
- OnGameInventoryDataReceived_Client(aGameInventoryData);
- }
- bool AVizPlayerController::RequestForGameInventoryData_Server_Validate()
- {
- return Role >= ROLE_Authority;
- }
- void AVizPlayerController::OnGameInventoryDataReceived_Client_Implementation(const TArray<FUIEquipmentData> & aGameInventoryData)
- {
- m_aGameInventoryData = aGameInventoryData;
- }
- void AVizPlayerController::RequestForSnowTests_Server_Implementation()
- {
- TArray<Test::Type> aSnowTests;
- AVizGameMode* pGameMode = GetWorld()->GetAuthGameMode<AVizGameMode>();
- if (pGameMode)
- {
- pGameMode->GetSnowTests(aSnowTests);
- }
- TArray<TEnumAsByte<Test::Type>> snowTests;
- for (int32 i = 0; i < aSnowTests.Num(); i++)
- {
- snowTests.Add((TEnumAsByte<Test::Type>)aSnowTests[i]);
- }
- OnSnowTestsReceived_Client(snowTests);
- }
- bool AVizPlayerController::RequestForSnowTests_Server_Validate()
- {
- return Role >= ROLE_Authority;
- }
- void AVizPlayerController::OnSnowTestsReceived_Client_Implementation(const TArray<TEnumAsByte<Test::Type>> & aSnowTests)
- {
- m_aSnowTests = aSnowTests;
- }
- void AVizPlayerController::GetSnowTests(TArray<TEnumAsByte<Test::Type>> & aSnowTests)
- {
- aSnowTests = m_aSnowTests;
- }
- void AVizPlayerController::OnGameEnd()
- {
- if(m_pWidgetManager)
- {
- m_pWidgetManager->ShowEndGameWidget();
- }
- }
- void AVizPlayerController::PerformTest(int32 testIndex)
- {
- AVizCharacter* currentPawn = Cast<AVizCharacter>(GetPawn());
- if(currentPawn)
- {
- switch (testIndex)
- {
- case 0 :
- {
- currentPawn->CreateSnowTestGeneric(Test::TT_SKI_TEST);
- }
- break;
- case 1:
- {
- currentPawn->CreateSnowTestGeneric(Test::TT_RUTSCHBLOCK_TEST);
- }
- break;
- case 2:
- {
- currentPawn->CreateSnowTestGeneric(Test::TT_SHOVEL_SHEAR_TEST);
- }
- break;
- case 3:
- {
- currentPawn->CreateSnowTestGeneric(Test::TT_COLLAPSE_TEST);
- }
- break;
- case 4:
- {
- currentPawn->CreateSnowTestGeneric(Test::TT_TILT_BOARD_TEST);
- }
- break;
- case 5:
- {
- currentPawn->CreateSurfaceAnalysisTest(SurfaceAnalysisType::SA_WIND_DIRECTION);
- }
- break;
- case 6:
- {
- currentPawn->CreateSurfaceAnalysisTest(SurfaceAnalysisType::SA_SNOW_SOFTNESS);
- }
- break;
- default:
- break;
- }
- }
- ToggleTraineeSnowTests(); // To close window
- bShowMouseCursor = true;
- }
- void AVizPlayerController::DebugTest()
- {
- AVizCharacter* currentPawn = Cast<AVizCharacter>(GetPawn());
- if (currentPawn)
- {
- currentPawn->CreateSnowTestGeneric(Test::TT_SHOVEL_SHEAR_TEST);
- }
- }
- void AVizPlayerController::OnReadyClicked()
- {
- if (m_pWidgetManager)
- {
- m_pWidgetManager->RemoveSelectionMenu();
- // EnableHMD();
- }
- }
- void AVizPlayerController::CheckForGameInventoryItem_Server_Implementation(Equipment::Type pType)
- {
- TArray<FUIEquipmentData> aGameInventoryData;
- bool itemFound = false;
- AVizGameMode * pGameMode = Cast<AVizGameMode>(GetWorld()->GetAuthGameMode());
- if (pGameMode)
- {
- itemFound = pGameMode->CheckAndRemoveAllowedEquipment(pType);
- UpdateGameInventory_Client(pType, itemFound);
- pGameMode->BroadcastEquipmentChange();
- }
- }
- bool AVizPlayerController::CheckIfItemCanBeAdded(TEnumAsByte<Equipment::Type> pType)
- {
- for (int i = 0; i < m_aGameInventoryData.Num(); i++)
- {
- if (m_aGameInventoryData[i].Type == pType)
- {
- AVizCharacter* myChar = Cast<AVizCharacter>(GetPawn());
- if (myChar)
- {
- return myChar->CanCarryLoad(m_aGameInventoryData[i].Weight);
- }
- break;
- }
- }
- return false;
- }
- bool AVizPlayerController::CheckForGameInventoryItem_Server_Validate(Equipment::Type pType)
- {
- return Role >= ROLE_Authority;
- }
- void AVizPlayerController::AddGameInventoryItem_Server_Implementation()
- {
- AVizGameMode * pGameMode = Cast<AVizGameMode>(GetWorld()->GetAuthGameMode());
- if (pGameMode)
- {
- pGameMode->AddEquipmentAllowed(m_PendingEquipmentToRemove.Type);
- pGameMode->BroadcastEquipmentChange();
- }
- }
- bool AVizPlayerController::AddGameInventoryItem_Server_Validate()
- {
- return Role >= ROLE_Authority;
- }
- void AVizPlayerController::UpdateGameInventory_Client_Implementation(Equipment::Type pType, bool itemFound)
- {
- m_ItemExistsOnServer = itemFound;
- if(itemFound)
- {
- for(int i = 0 ; i < m_aGameInventoryData.Num(); i++)
- {
- if(m_aGameInventoryData[i].Type == pType)
- {
- m_PendingEquipmentToAdd = m_aGameInventoryData[i];
- m_aGameInventoryData[i].Count--;
- if (m_aGameInventoryData[i].Count == 0)
- {
- m_aGameInventoryData.Swap(i, m_aGameInventoryData.Num() - 1);
- m_aGameInventoryData.RemoveAt(m_aGameInventoryData.Num() - 1, 1, true);
- }
- break;
- }
- }
- }
- }
- void AVizPlayerController::OnItemActionPerformed(TEnumAsByte<Equipment::Type> pType, TEnumAsByte<ItemAction::Type> pAction)
- {
- //Do nothing
- GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, "Inventory Action Goes here");
- }
- bool AVizPlayerController::CheckForGameInventoryItem(TEnumAsByte<Equipment::Type> pType)
- {
- CheckForGameInventoryItem_Server(pType);
- bool oldValue = m_ItemExistsOnServer;
- m_ItemExistsOnServer = false;
- return oldValue;
- }
- void AVizPlayerController::OnGameInventoryClicked(TEnumAsByte<Equipment::Type> pType)
- {
- // Add Item to character
- AVizCharacter* myChar = Cast<AVizCharacter>(GetPawn());
- if(myChar)
- {
- myChar->GetPlayerInventory()->AddItem(m_PendingEquipmentToAdd.Type);
- m_aPlayerInventoryData.Add(m_PendingEquipmentToAdd);
- //Weight Changed
- OnWeightChanged.Broadcast(myChar->GetCurrentLoad(), myChar->GetMaxLoad());
- }
- }
- void AVizPlayerController::OnPlayerInventoryClicked(TEnumAsByte<Equipment::Type> pType)
- {
- // Remove from character
- AVizCharacter* myChar = Cast<AVizCharacter>(GetPawn());
- if (myChar)
- {
- myChar->GetPlayerInventory()->RemoveItem(pType);
- //Local changes
- for(int i = 0 ; i < m_aPlayerInventoryData.Num() ; i++)
- {
- if(m_aPlayerInventoryData[i].Type == pType)
- {
- m_PendingEquipmentToRemove = m_aPlayerInventoryData[i];
- m_aPlayerInventoryData[i].Count--;
- if (m_aPlayerInventoryData[i].Count == 0)
- {
- m_aPlayerInventoryData.Swap(i, m_aPlayerInventoryData.Num() - 1);
- m_aPlayerInventoryData.RemoveAt(m_aPlayerInventoryData.Num() - 1, 1, true);
- break;
- }
- }
- }
- //Add to server
- AddGameInventoryItem_Server();
- //Weight Changed
- OnWeightChanged.Broadcast(myChar->GetCurrentLoad(), myChar->GetMaxLoad());
- }
- //RequestForGameInventoryData_Server();
- }
- void AVizPlayerController::BindWidgetToDelegate(UVizBaseWidget* widgetObject)
- {
- UVizTraineeEquipmentWidget* equipmentWidget = Cast<UVizTraineeEquipmentWidget>(widgetObject);
- if(equipmentWidget)
- {
- //Bind events for Game Equipment Update
- TScriptDelegate<FWeakObjectPtr> updateEquipment;
- updateEquipment.BindUFunction(equipmentWidget, "UpdateInventoryContent");
- UpdateGameEquipment.Add(updateEquipment);
- //Weight Change
- TScriptDelegate<FWeakObjectPtr> weightChange;
- weightChange.BindUFunction(equipmentWidget, "OnPlayerLoadIncreased");
- OnWeightChanged.AddUnique(weightChange);
- AVizCharacter* myChar = Cast<AVizCharacter>(GetPawn());
- if(myChar)
- {
- OnWeightChanged.Broadcast(myChar->GetCurrentLoad(), myChar->GetMaxLoad());
- }
- UpdateGameEquipment.Broadcast();
- }
- UVizTraineeItemSelectionWidget* inventoryWidget = Cast<UVizTraineeItemSelectionWidget>(widgetObject);
- if(inventoryWidget)
- {
- //Weight Change
- TScriptDelegate<FWeakObjectPtr> weightChange;
- weightChange.BindUFunction(inventoryWidget, "OnPlayerLoadIncreased");
- OnWeightChanged.AddUnique(weightChange);
- AVizCharacter* myChar = Cast<AVizCharacter>(GetPawn());
- if (myChar)
- {
- OnWeightChanged.Broadcast(myChar->GetCurrentLoad(), myChar->GetMaxLoad());
- }
- }
- }
- void AVizPlayerController::GetInventorySize(FIntPoint & InventorySize)
- {
- // TODO @ Vamshi
- // Temp
- InventorySize.X = 5;
- InventorySize.Y = 5;
- }
- void AVizPlayerController::GetUIGameInventoryData(TArray<FUIEquipmentData> & aUIGameInventoryData)
- {
- aUIGameInventoryData.Empty();
- aUIGameInventoryData = m_aGameInventoryData;
- }
- void AVizPlayerController::GetUIPlayerInventoryData(TArray<FUIEquipmentData> & aUIGameInventoryData)
- {
- AVizCharacter * pCharacter = Cast<AVizCharacter>(GetPawn());
- if (pCharacter)
- {
- const TMap<TEnumAsByte<Equipment::Type>, int32> & equipmentsAllowed = pCharacter->GetPlayerInventory()->GetAllEquipmentsWithCount();
- TArray<TEnumAsByte<Equipment::Type>> aKeys;
- equipmentsAllowed.GenerateKeyArray(aKeys);
- for (int i = 0; i < aKeys.Num(); i++)
- {
- aUIGameInventoryData.Add(FUIEquipmentData());
- FEquipmentData * pEquipment = m_pInventoryManager->GetEquipment(aKeys[i]);
- check(pEquipment);
- aUIGameInventoryData[i].Type = pEquipment->Type;
- aUIGameInventoryData[i].Description = pEquipment->Description;
- aUIGameInventoryData[i].Texture = pEquipment->UITexture;
- aUIGameInventoryData[i].Count = equipmentsAllowed[aKeys[i]];
- aUIGameInventoryData[i].Weight = pEquipment->Weight;
- }
- }
- }
- void AVizPlayerController::UpdateInventory()
- {
- RequestForGameInventoryData_Server();
- UpdateGameEquipment.Broadcast();
- }
- UVizInventoryManager * AVizPlayerController::GetInventoryManager() const
- {
- return m_pInventoryManager;
- }
- AVizInventoryPreview* AVizPlayerController::GetInventoryPreview() const
- {
- return m_pInventoryPreview;
- }
- void AVizPlayerController::ReturnToGameMode()
- {
- FInputModeGameOnly GameOnlyMode;
- SetInputMode(GameOnlyMode);
- bShowMouseCursor = false;
- }
- AVizSnowClassificationManager* AVizPlayerController::GetSnowClassificationManager() const
- {
- return m_pSnowProperty;
- }
- void AVizPlayerController::RequestForBindingWeatherParticleLocation()
- {
- //! Turn the flag on with the request. Will be turned off when request is completed.
- m_boundParticleLocationRequested = true;
- RequestForBindingWeatherParticleLocation_Server();
- }
- void AVizPlayerController::RequestForBindingWeatherParticleLocation_Server_Implementation()
- {
- AVizGameMode * pGameMode = Cast<AVizGameMode>(GetWorld()->GetAuthGameMode());
- if (pGameMode)
- {
- BindParticleLocation(pGameMode->GetWeatherManager());
- }
- }
- bool AVizPlayerController::RequestForBindingWeatherParticleLocation_Server_Validate()
- {
- return Role >= ROLE_Authority;
- }
- void AVizPlayerController::BindParticleLocation_Implementation(AVizWeatherManager* weatherManager)
- {
- IVizPlayerMovement* currentPawn = Cast<AVizCharacter>(GetPawn());
- if (!currentPawn)
- {
- currentPawn = Cast<AVizCreateEditPawn>(GetPawn());
- }
- if (currentPawn)
- {
- if (weatherManager)
- {
- weatherManager->BindParticleLocation(currentPawn);
- }
- //! Particle location bound request is successful ,
- m_boundParticleLocationRequested = false;
- }
- }
- void AVizPlayerController::OnRep_Pawn()
- {
- Super::OnRep_Pawn();
- V_LOG_LINE(LogViz);
- GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("Pawn updated"));
- //! Check if particle location bound was requested but could not be completed.
- //! Try again now as the pawn have been replicated
- if(m_boundParticleLocationRequested)
- {
- RequestForBindingWeatherParticleLocation_Server();
- }
- }
- void AVizPlayerController::GetAllPlayerPosition()
- {
- int32 i = 0;
- for (TActorIterator<APawn> ActorItr(GetWorld()); ActorItr; ++ActorItr)
- {
- APawn* pwn = *ActorItr;
- AVizCreateEditPawn* trainer_pwn = Cast<AVizCreateEditPawn>(pwn);
- AVizVRCharacter* trainee_pwn = Cast<AVizVRCharacter>(pwn);
- if (trainer_pwn)
- {
- FVector trainer_position;
- trainer_position = trainer_pwn->GetActorLocation();
- V_LOGM(LogViz, "Trainer Pawn Found. Position is = %s", *trainer_position.ToString());
- }
- i++;
- /*else if(trainee_pwn)
- {
- FVector trainer_position;
- trainer_position = trainer_pwn->K2_GetActorLocation();
- V_LOGM(LogViz, "Trainee Pawn Found. Position is = %s", *trainer_position.ToString());
- }*/
- }
- V_LOGM(LogViz, "No of Clients = %d", i);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement