From 8d059ab1c83156c54e76ab07f3de82a3c0dae85d Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Fri, 27 Nov 2026 21:35:03 -0600 Subject: [PATCH] feat(scripts): shooting gallery cannon and zone re-ported from the original SG_CANNON.lua and L_GF_SG.lua line for line, as a shared cannon and zone script (ShootingGallery folder) that a gallery fills with its constants and targets; GF's (SGCannon, ZoneSGServer) is now that data. The cannon gets the zone control's ActivityStateChangeRequest, MessageBoxRespond and ObjectLoaded from the zone script, as the original asked to be told of them. As the original: waves end through their own EndWave timer and the last one through GameOver; targets spawn 1 s or more after their timer starts; scores are counted at the shot's end and can go below 0; the super charge is the shot of its cannon ball; one activity reward roll, rated by the score; the wave, fire and preload animations and effects; GF's spawn table as the original's. Co-Authored-By: Claude Opus 5.5 --- dScripts/ai/MINIGAME/SG_GF/CMakeLists.txt | 3 +- .../MINIGAME/SG_GF/GfShootingGalleryData.cpp | 135 ++ .../ai/MINIGAME/SG_GF/GfShootingGalleryData.h | 12 + .../ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp | 1241 +---------------- dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.h | 166 +-- .../ai/MINIGAME/SG_GF/SERVER/SgTarget.cpp | 16 +- dScripts/ai/MINIGAME/SG_GF/SERVER/SgTarget.h | 2 +- dScripts/ai/MINIGAME/SG_GF/ZoneSGServer.cpp | 27 +- dScripts/ai/MINIGAME/SG_GF/ZoneSGServer.h | 16 +- .../MINIGAME/ShootingGallery/CMakeLists.txt | 2 + .../ShootingGallery/ShootingGalleryCannon.cpp | 1138 +++++++++++++++ .../ShootingGallery/ShootingGalleryCannon.h | 144 ++ .../ShootingGallery/ShootingGalleryZone.cpp | 97 ++ .../ShootingGallery/ShootingGalleryZone.h | 46 + .../MovingPlatformComponentTests.cpp | 20 +- 15 files changed, 1619 insertions(+), 1446 deletions(-) create mode 100644 dScripts/ai/MINIGAME/SG_GF/GfShootingGalleryData.cpp create mode 100644 dScripts/ai/MINIGAME/SG_GF/GfShootingGalleryData.h create mode 100644 dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryCannon.cpp create mode 100644 dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryCannon.h create mode 100644 dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryZone.cpp create mode 100644 dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryZone.h diff --git a/dScripts/ai/MINIGAME/SG_GF/CMakeLists.txt b/dScripts/ai/MINIGAME/SG_GF/CMakeLists.txt index 87bd879a7..0076be425 100644 --- a/dScripts/ai/MINIGAME/SG_GF/CMakeLists.txt +++ b/dScripts/ai/MINIGAME/SG_GF/CMakeLists.txt @@ -1,5 +1,6 @@ set(DSCRIPTS_SOURCES_AI_MINIGAME_SG_GF - "ZoneSGServer.cpp") + "ZoneSGServer.cpp" + "GfShootingGalleryData.cpp") add_subdirectory(SERVER) diff --git a/dScripts/ai/MINIGAME/SG_GF/GfShootingGalleryData.cpp b/dScripts/ai/MINIGAME/SG_GF/GfShootingGalleryData.cpp new file mode 100644 index 000000000..2a085011d --- /dev/null +++ b/dScripts/ai/MINIGAME/SG_GF/GfShootingGalleryData.cpp @@ -0,0 +1,135 @@ +#include "GfShootingGalleryData.h" + +namespace { + // o_ShootingGallery.lua AddSpawn: [Template ID], [Initial Spawn Time Min], [Initial Spawn Time Max], [Does Respawn], + // [Respawn Time Min], [Respawn Time Max], [Initial Speed], [Score], [Change Speed at Waypoints], + // [Chance to Change Speed], [Min Speed], [Max Speed], [Is Moving Platform], [Despawn On Last Waypoint], [Time Score] + ShootingGallery::Spawn AddSpawn(std::vector paths, const LOT id, const float initSpawnTimeMin, const float initSpawnTimeMax, + const bool bRespawn, const float mintime, const float maxtime, const float speed, const int32_t score, const bool bChangeSpeed, + const float chanceChangeSpeed, const float minSpeed, const float maxSpeed, const bool bMovingPlatform, const bool despawnTime, + const float timeScore) { + ShootingGallery::Spawn spawn; + spawn.path = std::move(paths); + spawn.id = id; + spawn.initSpawnTimeMin = initSpawnTimeMin; + spawn.initSpawnTimeMax = initSpawnTimeMax; + spawn.bRespawn = bRespawn; + spawn.minTime = mintime; + spawn.maxTime = maxtime; + spawn.speed = speed; + spawn.score = score; + spawn.bChangeSpeed = bChangeSpeed; + spawn.speedChangeChance = chanceChangeSpeed; + spawn.minSpeed = minSpeed; + spawn.maxSpeed = maxSpeed; + spawn.bMovingPlatform = bMovingPlatform; + spawn.despawnTime = despawnTime; + spawn.timeScore = timeScore; + return spawn; + } + + ShootingGallery::Constants MakeConstants() { + ShootingGallery::Constants constants; + // cannon constants + constants.CANNON_TEMPLATEID = 1864; + constants.IMPACT_SKILLID = 34; + constants.PROJECTILE_TEMPLATEID = 1822; + constants.CANNON_PLAYER_OFFSET = NiPoint3(6.652f, -2.0f, 1.5f); + constants.Reward_Model_Matrix = 157; + constants.CANNON_VELOCITY = 129.0f; + constants.CANNON_MIN_DISTANCE = 30.0f; + constants.CANNON_REFIRE_RATE = 800.0f; + constants.CANNON_BARREL_OFFSET = NiPoint3(0.0f, 4.3f, 9.0f); + constants.CANNON_SUPER_CHARGE = 6297; + constants.CANNON_PROJECTILE = 1822; + constants.CANNON_SUPERCHARGE_SKILL = 249; + constants.CANNON_SKILL = 228; + constants.CANNON_TIMEOUT = -1.0f; + constants.CANNON_FOV = 58.6f; + constants.CANNON_USE_LEADERBOARDS = true; + constants.STREAK_MOD = 2; + // Super Charger is charged for this amount of time + constants.ChargedTime = 10.0f; + // The amount of points needed to super charge + constants.ChargedPoints = 25000; + // Model reward group name + constants.Reward_Model_GrpName = "QBRewardGroup"; + constants.ActivityID = 1864; + // Reward Score and Loot Matrix 1 to 5 + constants.Score_Reward = { 50000, 100000, 200000, 400000, 800000 }; + constants.Score_LootMatrix = { 157, 187, 188, 189, 190 }; + // Wave Data: AddWave(waves, 30.0, "Wave;One") and so on + constants.waveTimeLimits = { 30.0f, 30.0f, 30.0f }; + constants.FIRST_WAVE_START_TIME = 4.0f; + constants.IN_BETWEEN_WAVE_PAUSE = 7.0f; + return constants; + } +}; + +const ShootingGallery::Constants& GfShootingGalleryData::GetConstants() { + static const auto constants = MakeConstants(); + return constants; +} + +// SG_CANNON.lua: targetSettings +ShootingGallery::SpawnTable GfShootingGalleryData::GetTargetSettings() { + return { + // Wave 1 Spawns + { + // Ship 1 + AddSpawn({ "Wave_1_Ship_1", "Wave_1_Ship_3" }, 6015, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 1500, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + // Ship 2 + AddSpawn({ "Wave_1_Ship_2", "Wave_1_Ship_4" }, 6300, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 500, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + // Sub + AddSpawn({ "Wave_1_Sub_1", "Wave_1_Sub_2" }, 6016, 0.0f, 2.0f, true, 0.0f, 2.0f, 10.0f, 1000, false, 0.0f, 1.0f, 1.0f, true, true, 0.0f), + // Sub 2 + AddSpawn({ "Wave_2_Sub_1", "Wave_2_Sub_2" }, 6016, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 1000, false, 0.0f, 1.0f, 1.0f, true, true, 0.0f), + // Friendly + AddSpawn({ "Wave_3_FShip_1", "Wave_3_FShip_2" }, 2168, 0.0f, 5.0f, true, 2.0f, 5.0f, 1.0f, -1000, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + }, + // Wave 2 Spawns + { + // Ship 1 + AddSpawn({ "Wave_1_Ship_1", "Wave_1_Ship_3" }, 6015, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 1500, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + // Ship 2 + AddSpawn({ "Wave_1_Ship_2", "Wave_1_Ship_4" }, 6300, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 500, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + // Ship 3 + AddSpawn({ "Wave_2_Ship_1" }, 6300, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 500, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + // Ship 4 + AddSpawn({ "Wave_2_Ship_2" }, 6015, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 1500, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + // Sub 1 + AddSpawn({ "Wave_1_Sub_1", "Wave_1_Sub_2" }, 6016, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 1000, false, 0.0f, 1.0f, 1.0f, true, true, 0.0f), + // Sub 2 + AddSpawn({ "Wave_2_Sub_1", "Wave_2_Sub_2" }, 6016, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 1000, false, 0.0f, 1.0f, 1.0f, true, true, 0.0f), + // Duck + AddSpawn({ "Wave_1_Duck_1", "Wave_1_Duck_2" }, 5946, 5.0f, 10.0f, true, 5.0f, 10.0f, 4.0f, 5000, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + // Friendly + AddSpawn({ "Wave_3_FShip_1", "Wave_3_FShip_2" }, 2168, 0.0f, 5.0f, true, 2.0f, 5.0f, 1.0f, -1000, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + }, + // Wave 3 Spawns + { + // Ship 1 + AddSpawn({ "Wave_1_Ship_1", "Wave_1_Ship_3" }, 6015, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 1500, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + // Ship 2 + AddSpawn({ "Wave_1_Ship_2", "Wave_1_Ship_4" }, 6300, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 500, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + // Ship 3 + AddSpawn({ "Wave_2_Ship_1", "Wave_2_Ship_2" }, 6015, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 500, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + // Ship 4 + AddSpawn({ "Wave_3_Ship_1", "Wave_3_Ship_2" }, 6300, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 1500, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + // Sub 1 + AddSpawn({ "Wave_1_Sub_1", "Wave_1_Sub_2" }, 6016, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 1000, false, 0.0f, 1.0f, 1.0f, true, true, 0.0f), + // Sub 2 + AddSpawn({ "Wave_2_Sub_1", "Wave_2_Sub_2" }, 6016, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 1000, false, 0.0f, 1.0f, 1.0f, true, true, 0.0f), + // Sub 3 + AddSpawn({ "Wave_3_Sub_1", "Wave_3_Sub_2" }, 6016, 0.0f, 2.0f, true, 0.0f, 2.0f, 2.0f, 1000, false, 0.0f, 1.0f, 1.0f, true, true, 0.0f), + // Duck + AddSpawn({ "Wave_1_Duck_1", "Wave_1_Duck_2" }, 5946, 5.0f, 10.0f, true, 5.0f, 10.0f, 4.0f, 5000, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + // Ness + AddSpawn({ "Wave_1_Ness_1", "Wave_1_Ness_2", "Wave_2_Ness_1" }, 2565, 10.0f, 15.0f, true, 10.0f, 15.0f, 2.0f, 10000, false, 0.0f, 1.0f, 1.0f, true, true, 0.0f), + // Friendly + AddSpawn({ "Wave_3_FShip_1", "Wave_3_FShip_2" }, 2168, 0.0f, 5.0f, true, 2.0f, 5.0f, 1.0f, -1000, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + // Friendly 2 + AddSpawn({ "Wave_3_FShip_3", "Wave_3_FShip_4" }, 2168, 0.0f, 5.0f, true, 2.0f, 5.0f, 1.0f, -1000, false, 0.0f, 1.0f, 1.0f, false, true, 0.0f), + }, + }; +} diff --git a/dScripts/ai/MINIGAME/SG_GF/GfShootingGalleryData.h b/dScripts/ai/MINIGAME/SG_GF/GfShootingGalleryData.h new file mode 100644 index 000000000..5ef7c806f --- /dev/null +++ b/dScripts/ai/MINIGAME/SG_GF/GfShootingGalleryData.h @@ -0,0 +1,12 @@ +#pragma once + +#include "../ShootingGallery/ShootingGalleryTypes.h" + +/** + * Gnarled Forest's shooting gallery (Cannon Cove, zone 1302): the zone script's CONSTANTS (L_ZONE_SG_SERVER.lua) and + * the cannon's targetSettings (SG_CANNON.lua). + */ +namespace GfShootingGalleryData { + const ShootingGallery::Constants& GetConstants(); + ShootingGallery::SpawnTable GetTargetSettings(); +}; diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp index 380aa5f8d..a5dc34293 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp @@ -1,1242 +1,11 @@ #include "SGCannon.h" -#include "SgTarget.h" -#include "EntityManager.h" -#include "GameMessages.h" -#include "EffectsMessages.h" -#include "ActivityMessages.h" -#include "MovementMessages.h" -#include "dZoneManager.h" -#include "Character.h" -#include "ShootingGalleryComponent.h" -#include "PossessorComponent.h" -#include "CharacterComponent.h" -#include "SimplePhysicsComponent.h" -#include "MovementAIComponent.h" -#include "MovingPlatformComponent.h" -#include "MissionComponent.h" -#include "Loot.h" -#include "InventoryComponent.h" -#include "eMissionTaskType.h" -#include "eReplicaComponentType.h" -#include "RenderComponent.h" -#include "eGameActivity.h" -#include "Item.h" -#include -#include "BuildingMessages.h" -void SGCannon::OnStartup(Entity* self) { - LOG("OnStartup"); +#include "GfShootingGalleryData.h" - m_Waves = GetWaves(); - constants = GetConstants(); - - ResetVars(self); - - self->SetVar(GameStartedVariable, false); - self->SetVar(InitialVelocityVariable, {}); - self->SetVar(ImpactSkillVariale, constants.impactSkillID); - - auto* shootingGalleryComponent = self->GetComponent(); - if (shootingGalleryComponent != nullptr) { - shootingGalleryComponent->SetStaticParams({ - Vector3 { -327.8609924316406, 256.8999938964844, 1.6482199430465698 }, - Vector3 { -181.4320068359375, 212.39999389648438, 2.5182199478149414 } - }); - - shootingGalleryComponent->SetDynamicParams({ - Vector3 { 0.0, 4.3, 9.0 }, - Vector3 { }, - 129.0, - 800.0, - 30.0, - 0.0, - -1.0, - 58.6 - }); - } - - self->SetVar(TimeLimitVariable, 30); - self->SetVar>(ValidActorsVariable, { 3109, 3110, 3111, 3112, 3125, 3126 }); - self->SetVar>(ValidEffectsVariable, { 3122 }); - self->SetVar>(StreakBonusVariable, { 1, 2, 5, 10 }); - self->SetVar(SuperChargeActiveVariable, false); - self->SetVar(MatrixVariable, 1); - self->SetVar(InitVariable, true); - - auto* simplePhysicsComponent = self->GetComponent(); - - if (simplePhysicsComponent != nullptr) { - simplePhysicsComponent->SetPhysicsMotionState(5); - } - Game::entityManager->SerializeEntity(self); +const ShootingGallery::Constants& SGCannon::GetConstants() const { + return GfShootingGalleryData::GetConstants(); } -void SGCannon::OnPlayerLoaded(Entity* self, Entity* player) { - LOG("Player loaded"); - self->SetVar(PlayerIDVariable, player->GetObjectID()); -} - -void SGCannon::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { - Script::OnFireEventServerSide(self, sender, args, param1, param2, param3); -} - -void SGCannon::OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int32_t value1, int32_t value2, - const std::u16string& stringValue) { - LOG("Got activity state change request: %s", GeneralUtils::UTF16ToWTF8(stringValue).c_str()); - if (stringValue == u"clientready") { - auto* player = Game::entityManager->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - LOG("Player is ready"); - - GameMessages::ActivityEnter activityEnter; - activityEnter.target = self->GetObjectID(); - activityEnter.Send(player->GetSystemAddress()); - - auto* shootingGalleryComponent = self->GetComponent(); - - if (shootingGalleryComponent != nullptr) { - shootingGalleryComponent->SetCurrentPlayerID(player->GetObjectID()); - - LOG("Setting player ID"); - - Game::entityManager->SerializeEntity(self); - } else { - LOG("Shooting gallery component is null"); - } - - auto* characterComponent = player->GetComponent(); - - if (characterComponent != nullptr) { - characterComponent->SetCurrentActivity(eGameActivity::SHOOTING_GALLERY); - auto possessor = player->GetComponent(); - if (possessor) { - possessor->SetPossessable(self->GetObjectID()); - possessor->SetPossessableType(ePossessionType::NO_POSSESSION); - } - - Game::entityManager->SerializeEntity(player); - } - - self->AddCallbackTimer(1.0f, [self, this]() { - self->SetNetworkVar(HideScoreBoardVariable, true); - self->SetNetworkVar(ReSetSuperChargeVariable, true); - self->SetNetworkVar(ShowLoadingUI, true); - }); - - } else { - LOG("Player not found"); - } - } else if (value1 == 1200) { - StartGame(self); - } -} - -void SGCannon::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { - auto* player = Game::entityManager->GetEntity(self->GetVar(PlayerIDVariable)); - if (!player) return; - - if (identifier == u"Scoreboardinfo") { - GameMessages::DisplayMessageBox messageBox; - messageBox.target = player->GetObjectID(); - messageBox.bShow = true; - messageBox.callbackClient = Game::zoneManager->GetZoneControlObject()->GetObjectID(); - messageBox.identifier = u"Shooting_Gallery_Retry"; - messageBox.imageID = 2; - messageBox.text = u"Retry?"; - messageBox.userData = u""; - messageBox.Send(player->GetSystemAddress()); - } else { - if ((button == 1 && (identifier == u"Shooting_Gallery_Retry" || identifier == u"RePlay")) || identifier == u"SG1" || button == 0) { - if (IsPlayerInActivity(self, player->GetObjectID())) return; - self->SetNetworkVar(ClearVariable, true); - StartGame(self); - } else if (button == 0 && ((identifier == u"Shooting_Gallery_Retry" || identifier == u"RePlay"))) { - RemovePlayer(player->GetObjectID()); - UpdatePlayer(self, player->GetObjectID(), true); - } else if (button == 1 && identifier == u"Shooting_Gallery_Exit") { - UpdatePlayer(self, player->GetObjectID(), true); - RemovePlayer(player->GetObjectID()); - } - } -} - -void SGCannon::SuperChargeTimerFunc(Entity* self) { - if (self->GetVar(WaveStatusVariable) || self->GetVar(CurrentSuperChargedTimeVariable) < 1) { - self->SetNetworkVar(ChargeCountingVariable, 99); - self->SetNetworkVar(SuperChargeBarVariable, 0); - ToggleSuperCharge(self, false); - } -} - -void SGCannon::SpawnWaveTimerFunc(Entity* self) { - if (self->GetVar(GameStartedVariable)) { - self->SetVar(WaveStatusVariable, true); - const auto wave = static_cast(self->GetVar(ThisWaveVariable)); - - if (wave != 0 && self->GetVar(SuperChargePausedVariable)) { - StartChargedCannon(self, self->GetVar(CurrentSuperChargedTimeVariable)); - self->SetVar(CurrentSuperChargedTimeVariable, 0); - } - - TimerToggle(self, true); - - for (const auto& enemyToSpawn : m_Waves.at(self->GetVar(ThisWaveVariable))) { - SpawnObject(self, enemyToSpawn, true); - } - - LOG("Current wave spawn: %i/%i", wave, m_Waves.size()); - - // All waves completed - const auto timeLimit = static_cast(self->GetVar(TimeLimitVariable)); - if (wave >= m_Waves.size()) { - ActivityTimerStart(self, GameOverTimer, timeLimit, timeLimit); - } else { - ActivityTimerStart(self, EndWaveTimer, timeLimit, timeLimit); - } - - const auto* player = Game::entityManager->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - GameMessages::PlayFXEffect(player->GetObjectID(), -1, u"SG-start", "").Send(UNASSIGNED_SYSTEM_ADDRESS); - - GameMessages::StartActivityTime startActivityTime; - startActivityTime.target = self->GetObjectID(); - startActivityTime.startTime = timeLimit; - startActivityTime.Send(player->GetSystemAddress()); - LOG("Sending ActivityPause false"); - - GameMessages::ActivityPause activityPause; - activityPause.target = self->GetObjectID(); - activityPause.bPause = false; - activityPause.Send(player->GetSystemAddress()); - } - } -} - -void SGCannon::EndWaveTimerFunc(Entity* self) { - self->SetVar(WaveStatusVariable, false); - TimerToggle(self); - RecordPlayerScore(self); - - GameMessages::ActivityPause activityPause; - activityPause.target = self->GetObjectID(); - activityPause.bPause = true; - - if (self->GetVar(ThisWaveVariable) >= 2) { - activityPause.Send(UNASSIGNED_SYSTEM_ADDRESS); - ActivityTimerStart(self, GameOverTimer, 0.1, 0.1); - return; - } - - self->SetVar(ThisWaveVariable, self->GetVar(ThisWaveVariable) + 1); - PlaySceneAnimation(self, u"wave" + GeneralUtils::to_u16string(self->GetVar(ThisWaveVariable)), true, true, 1.7f); - self->SetNetworkVar(WaveNumVariable, self->GetVar(ThisWaveVariable) + 1); - self->SetNetworkVar(WaveStrVariable, self->GetVar(TimeLimitVariable)); - - LOG("Current wave: %i/%i", self->GetVar(ThisWaveVariable), m_Waves.size()); - - if (self->GetVar(ThisWaveVariable) >= m_Waves.size()) { - ActivityTimerStart(self, GameOverTimer, 0.1, 0.1); - } else { - ActivityTimerStart(self, SpawnWaveTimer, constants.inBetweenWavePause, constants.inBetweenWavePause); - } - - LOG("Sending ActivityPause true"); - - activityPause.Send(UNASSIGNED_SYSTEM_ADDRESS); - if (self->GetVar(SuperChargeActiveVariable) && !self->GetVar(SuperChargePausedVariable)) { - PauseChargeCannon(self); - } -} - -void SGCannon::GameOverTimerFunc(Entity* self) { - auto* player = Game::entityManager->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - LOG_DEBUG("Sending ActivityPause true"); - - GameMessages::ActivityPause activityPause; - activityPause.target = self->GetObjectID(); - activityPause.bPause = true; - activityPause.Send(player->GetSystemAddress()); - - ActivityTimerStart(self, EndGameBufferTimer, 1, 1); - - TimerToggle(self); - } -} - -void SGCannon::DoSpawnTimerFunc(Entity* self, const std::string& name) { - if (self->GetVar(GameStartedVariable)) { - const auto spawnNumber = GeneralUtils::TryParse(name.substr(7), 0); - const auto& activeSpawns = self->GetVar>(ActiveSpawnsVariable); - if (activeSpawns.size() <= spawnNumber) { - LOG_DEBUG("Trying to spawn %i when spawns size is only %i", spawnNumber, activeSpawns.size()); - return; - } - - const auto& toSpawn = activeSpawns.at(spawnNumber); - const auto pathIndex = GeneralUtils::GenerateRandomNumber(0, toSpawn.spawnPaths.size() - 1); - const auto* path = Game::zoneManager->GetZone()->GetPath(toSpawn.spawnPaths.at(pathIndex)); - if (!path || path->pathWaypoints.empty()) { - LOG_DEBUG("Path %s at index %i or has 0 waypoints", toSpawn.spawnPaths.at(pathIndex).c_str(), pathIndex); - return; - } - - auto info = EntityInfo{}; - info.lot = toSpawn.lot; - info.spawnerID = self->GetObjectID(); - info.pos = path->pathWaypoints[0].position; - - info.settings.Insert(u"SpawnData", toSpawn); - info.settings.Insert(u"custom_script_server", "scripts/ai/ACT/SG_TARGET.lua"); - info.settings.Insert(u"custom_script_client", "scripts/client/ai/SG_TARGET_CLIENT.lua"); - info.settings.Insert(u"attached_path", path->pathName); - info.settings.Insert(u"attached_path_start", 0); - info.settings.Insert(u"groupID", u"SGEnemy"); - info.settings.Insert(u"wave", self->GetVar(ThisWaveVariable)); - - auto* enemy = Game::entityManager->CreateEntity(info, nullptr, self); - // sg_cannon.lua (onChildLoaded) stores itself as the target's parent, which the target tells at the end of its - // path; the spawn timer is the one that spawns the next - enemy->SetVar(u"My_Parent_ID", self->GetObjectID()); - enemy->SetVar(u"SpawnTimerName", name); - - // sg_cannon.lua (onChildLoaded): a moving platform target gets SetPathingSpeed, which nothing on a moving platform - // reads, and SetCurrentPath{ pathName, startPoint = 0 }: its mover runs the path at the waypoints' speeds, as the - // client's does. Live constructed these targets with the path and the mover waiting at waypoint 0 (9), and - // serialized the mover at each waypoint. The other targets follow their waypoints. - auto* const movingPlatform = toSpawn.isMovingPlatform ? enemy->GetComponent() : nullptr; - MovementAIComponent* movementAI = nullptr; - if (movingPlatform) { - movingPlatform->SetCurrentPath(path->pathName, 0); - } else { - movementAI = enemy->AddComponent(-1, MovementAIInfo{}); - } - auto* simplePhysicsComponent = enemy->GetComponent(); - if (simplePhysicsComponent) { - simplePhysicsComponent->SetPhysicsMotionState(4); - } - - Game::entityManager->ConstructEntity(enemy); - - if (movementAI) { - movementAI->SetMaxSpeed(toSpawn.initialSpeed); - movementAI->SetCurrentSpeed(toSpawn.initialSpeed); - movementAI->SetHaltDistance(0.0f); - - movementAI->SetPath(path->pathWaypoints); - } - - // A hit target scores (live's cannon ball tells the cannon of its kills). One that got to the end of its path - // tells the cannon and dies silently a moment later (its script, SG_TARGET.lua), which is no hit. - enemy->AddDieCallback([this, self, enemy, name]() { - if (!SgTarget::DiedSilently(enemy)) RegisterHit(self, enemy, name); - }); - - // Save the enemy - if (enemy != nullptr) { - const_cast&>(self->GetVar>(SpawnedObjects)).push_back(enemy->GetObjectID()); - } - } -} - -void SGCannon::EndGameBufferTimerFunc(Entity* self) { - RecordPlayerScore(self); - StopGame(self, false); -} - -void SGCannon::OnActivityTimerDone(Entity* self, const std::string& name) { - if (name == SuperChargeTimer && !self->GetVar(SuperChargePausedVariable)) { - SuperChargeTimerFunc(self); - } else if (name == SpawnWaveTimer) { - SpawnWaveTimerFunc(self); - } else if (name == EndWaveTimer) { - EndWaveTimerFunc(self); - } else if (name == GameOverTimer) { - GameOverTimerFunc(self); - } else if (name.rfind(DoSpawnTimer, 0) == 0) { - DoSpawnTimerFunc(self, name); - } else if (name == EndGameBufferTimer) { - EndGameBufferTimerFunc(self); - } -} - -void -SGCannon::OnActivityTimerUpdate(Entity* self, const std::string& name, float_t timeRemaining, float_t elapsedTime) { - ActivityManager::OnActivityTimerUpdate(self, name, timeRemaining, elapsedTime); -} - -void SGCannon::StartGame(Entity* self) { - if (self->GetVar(GameStartedVariable)) return; - self->SetNetworkVar(TimeLimitVariable, self->GetVar(TimeLimitVariable)); - self->SetNetworkVar(AudioStartIntroVariable, true); - self->SetVar(CurrentRewardVariable, LOT_NULL); - - auto rewardObjects = Game::entityManager->GetEntitiesInGroup(constants.rewardModelGroup); - for (auto* reward : rewardObjects) { - GameMessages::SetModelToBuild modelToBuild{}; - modelToBuild.modelLot = LOT_NULL; - modelToBuild.target = reward->GetObjectID(); - modelToBuild.Send(UNASSIGNED_SYSTEM_ADDRESS); - } - - auto* player = Game::entityManager->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - // The client cant accept more than 10 results. - GetLeaderboardData(self, player->GetObjectID(), GetConstants().activityID, 10); - LOG("Sending ActivityStart"); - GameMessages::ActivityStart activityStart; - activityStart.target = self->GetObjectID(); - activityStart.Send(player->GetSystemAddress()); - - GameMessages::PlayFXEffect(self->GetObjectID(), -1, u"start", "").Send(UNASSIGNED_SYSTEM_ADDRESS); - - self->SetNetworkVar(ClearVariable, true); - DoGameStartup(self); - - if (!self->GetVar(FirstTimeDoneVariable)) { - TakeActivityCost(self, player->GetObjectID()); - } - - self->SetVar(FirstTimeDoneVariable, true); - } - - SpawnNewModel(self); -} - -void SGCannon::DoGameStartup(Entity* self) { - ResetVars(self); - self->SetVar(GameStartedVariable, true); - self->SetNetworkVar(ClearVariable, true); - self->SetVar(ThisWaveVariable, 0); - - if (constants.firstWaveStartTime < 1) { - constants.firstWaveStartTime = 1; - } - - ActivityTimerStart(self, SpawnWaveTimer, constants.firstWaveStartTime, - constants.firstWaveStartTime); -} - -void SGCannon::OnShootingGalleryFire(Entity& self, GameMessages::ShootingGalleryFire& fire) { - self.SetVar(ShotsFiredVariable, self.GetVar(ShotsFiredVariable) + 1); -} - -void SGCannon::SpawnNewModel(Entity* self) { - - // Add a new reward to the existing rewards - const auto currentReward = self->GetVar(CurrentRewardVariable); - if (currentReward != -1) { - auto rewards = self->GetVar>(RewardsVariable); - rewards.push_back(currentReward); - self->SetVar>(RewardsVariable, rewards); - self->SetNetworkVar(RewardAddedVariable, currentReward); - } - - auto* player = Game::entityManager->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - for (auto* rewardModel : Game::entityManager->GetEntitiesInGroup(constants.rewardModelGroup)) { - uint32_t lootMatrix; - switch (self->GetVar(MatrixVariable)) { - case 1: - lootMatrix = constants.scoreLootMatrix1; - break; - case 2: - lootMatrix = constants.scoreLootMatrix2; - break; - case 3: - lootMatrix = constants.scoreLootMatrix3; - break; - case 4: - lootMatrix = constants.scoreLootMatrix4; - break; - case 5: - lootMatrix = constants.scoreLootMatrix5; - break; - default: - lootMatrix = 0; - } - - if (lootMatrix != 0) { - const auto toDrop = Loot::RollLootMatrix(player, lootMatrix); - for (const auto [lot, count] : toDrop) { - GameMessages::SetModelToBuild modelToBuild{}; - modelToBuild.modelLot = lot; - modelToBuild.target = rewardModel->GetObjectID(); - modelToBuild.Send(player->GetSystemAddress()); - - self->SetVar(CurrentRewardVariable, lot); - } - } - } - } -} - -void SGCannon::RemovePlayer(LWOOBJID playerID) { - auto* player = Game::entityManager->GetEntity(playerID); - if (!player) return; - - auto* character = player->GetCharacter(); - auto* characterComponent = player->GetComponent(); - if (characterComponent && character) { - characterComponent->SendToZone(character->GetLastNonInstanceZoneID()); - } -} - -void SGCannon::OnRequestActivityExit(Entity* self, LWOOBJID player, bool canceled) { - if (canceled) { - StopGame(self, canceled); - RemovePlayer(player); - } -} - - -void SGCannon::StartChargedCannon(Entity* self, uint32_t optionalTime) { - optionalTime = optionalTime == 0 ? constants.chargedTime : optionalTime; - self->SetVar(SuperChargePausedVariable, false); - ToggleSuperCharge(self, true); - ActivityTimerStart(self, SuperChargeTimer, 1, optionalTime); - - if (!self->GetVar(WaveStatusVariable)) { - PauseChargeCannon(self); - } -} - -void SGCannon::TimerToggle(Entity* self, bool start) { - if (start) { - self->SetNetworkVar(CountVariable, self->GetVar(TimeLimitVariable)); - self->SetVar(GameStartedVariable, true); - } else { - self->SetNetworkVar(StopVariable, true); - } -} - -void SGCannon::SpawnObject(Entity* self, const SGEnemy& toSpawn, bool spawnNow) { - auto activeSpawns = self->GetVar>(ActiveSpawnsVariable); - activeSpawns.push_back(toSpawn); - self->SetVar>(ActiveSpawnsVariable, activeSpawns); - - self->SetVar(SpawnNumberVariable, activeSpawns.size() - 1); - const auto timerName = DoSpawnTimer + std::to_string(activeSpawns.size() - 1); - - if (spawnNow) { - if (toSpawn.minSpawnTime > 0 && toSpawn.maxSpawnTime > 0) { - const auto spawnTime = GeneralUtils::GenerateRandomNumber(toSpawn.minSpawnTime, toSpawn.maxSpawnTime); - - ActivityTimerStart(self, timerName, spawnTime, spawnTime); - } else { - ActivityTimerStart(self, timerName, 1, 1); - } - } else if (toSpawn.respawns) { - const auto spawnTime = GeneralUtils::GenerateRandomNumber(toSpawn.minRespawnTime, toSpawn.maxRespawnTime); - - ActivityTimerStart(self, timerName, spawnTime, spawnTime); - } -} - -void SGCannon::RecordPlayerScore(Entity* self) { - const auto totalScore = self->GetVar(TotalScoreVariable); - const auto currentWave = self->GetVar(ThisWaveVariable); - - if (currentWave > 0) { - auto totalWaveScore = totalScore; - auto playerScores = self->GetVar>(PlayerScoresVariable); - - for (const auto& waveScore : playerScores) { - totalWaveScore -= waveScore; - } - - if (currentWave >= playerScores.size()) { - playerScores.push_back(totalWaveScore); - } else { - playerScores[currentWave] = totalWaveScore; - } - self->SetVar>(PlayerScoresVariable, playerScores); - } -} - -void SGCannon::PlaySceneAnimation(Entity* self, const std::u16string& animationName, bool onCannon, bool onPlayer, float_t priority) { - for (auto* cannon : Game::entityManager->GetEntitiesInGroup("cannongroup")) { - RenderComponent::PlayAnimation(cannon, animationName, priority); - } - - if (onCannon) { - RenderComponent::PlayAnimation(self, animationName, priority); - } - - if (onPlayer) { - auto* player = Game::entityManager->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - RenderComponent::PlayAnimation(player, animationName, priority); - } - } -} - -void SGCannon::PauseChargeCannon(Entity* self) { - const auto time = std::max(static_cast(std::ceil(ActivityTimerGetRemainingTime(self, SuperChargeTimer))), static_cast(1)); - - self->SetVar(SuperChargePausedVariable, true); - self->SetVar(CurrentSuperChargedTimeVariable, time); - self->SetNetworkVar(ChargeCountingVariable, time); - ActivityTimerStop(self, SuperChargeTimer); -} - -void SGCannon::StopGame(Entity* self, bool cancel) { - self->SetNetworkVar(ReSetSuperChargeVariable, true); - self->SetNetworkVar(HideSuperChargeVariable, true); - - auto* player = Game::entityManager->GetEntity(self->GetVar(PlayerIDVariable)); - if (player == nullptr) - return; - - ToggleSuperCharge(self, false); - - // The player won, store all the score and send rewards - if (!cancel) { - float percentage = 0.0f; - float misses = self->GetVar(MissesVariable); - float fired = self->GetVar(ShotsFiredVariable); - - if (fired > 0.0f) { - percentage = misses / fired; - } - - percentage = 1.0f - percentage; - percentage = std::max(percentage, 0.0f); - - auto* missionComponent = player->GetComponent(); - - if (missionComponent != nullptr) { - missionComponent->Progress(eMissionTaskType::PERFORM_ACTIVITY, self->GetVar(TotalScoreVariable), self->GetObjectID(), "performact_score"); - missionComponent->Progress(eMissionTaskType::PERFORM_ACTIVITY, self->GetVar(MaxStreakVariable), self->GetObjectID(), "performact_streak"); - missionComponent->Progress(eMissionTaskType::ACTIVITY, m_CannonLot, 0, "", self->GetVar(TotalScoreVariable)); - } - - Loot::GiveActivityLoot(player, self->GetObjectID(), GetGameID(self), self->GetVar(TotalScoreVariable)); - - SaveScore(self, player->GetObjectID(), - static_cast(self->GetVar(TotalScoreVariable)), static_cast(self->GetVar(MaxStreakVariable)), percentage); - - StopActivity(self, player->GetObjectID(), self->GetVar(TotalScoreVariable), self->GetVar(MaxStreakVariable), percentage); - self->SetNetworkVar(AudioFinalWaveDoneVariable, true); - - // Give the player the model rewards they earned - auto* inventory = player->GetComponent(); - if (inventory != nullptr) { - for (const auto rewardLot : self->GetVar>(RewardsVariable)) { - inventory->AddItem(rewardLot, 1, eLootSourceType::NONE, eInventoryType::MODELS); - } - } - - const auto& waveScores = self->GetVar>(PlayerScoresVariable); - std::stringstream stream; - - stream << self->GetVar(TotalScoreVariable) << "_"; - - // technically unused in shooting gallery but serialize it regardless. - for (const auto& score : waveScores) { - stream << score << "_"; - } - auto totalmissed = fired - misses; - if (totalmissed < 0) { - totalmissed = 0; - } - - stream << fired << "_" << totalmissed << "_" << self->GetVar(MaxStreakVariable); - - self->SetNetworkVar(u"UI_Rewards", GeneralUtils::ASCIIToUTF16(stream.str())); - } - - GameMessages::ActivityStop activityStop; - activityStop.target = self->GetObjectID(); - activityStop.bExit = false; - activityStop.bUserCancel = cancel; - activityStop.Send(player->GetSystemAddress()); - self->SetVar(GameStartedVariable, false); - ActivityTimerStopAllTimers(self); - - // Destroy all spawners - for (auto* entity : Game::entityManager->GetEntitiesInGroup("SGEnemy")) { - entity->Smash(LWOOBJID_EMPTY, eKillType::SILENT); - } - - ResetVars(self); -} - - -void SGCannon::OnActivityNotify(Entity* self, GameMessages::ActivityNotify& notify) { - if (!self->GetVar(GameStartedVariable)) return; - - const auto& params = notify.notification; - const auto itr = params.values.find(u"shot_done"); - if (itr == params.values.end()) return; - - const auto& param = itr->second; - if (param->GetValueType() != LDF_TYPE_S32) return; - - const auto superChargeShotDone = static_cast*>(param.get())->GetValue() == GetConstants().cannonSuperChargeSkill; - - const auto& hitTargets = self->GetVar>(u"CannonBallKills"); - - if (hitTargets.empty() && !superChargeShotDone) { - self->SetVar(u"m_curStreak", 0); - self->SetVar(MissesVariable, self->GetVar(MissesVariable) + 1); - self->SetNetworkVar(u"HideStreak", true); - self->SetNetworkVar(u"UnMarkAll", true); - UpdateStreak(self); - } else if (hitTargets.size() > 1) { - self->SetNetworkVar(u"mHit", true); - } - - self->SetVar>(u"CannonBallKills", {}); -} - -void SGCannon::CheckSpawn(Entity* self, Entity* target, const std::string& timerName) { - if (!self->GetVar(GameStartedVariable)) return; - const auto& spawnInfo = target->GetVar(u"SpawnData"); - - if (spawnInfo.respawns && target->GetVar(u"wave") == self->GetVar(ThisWaveVariable)) { - const auto respawnTime = GeneralUtils::GenerateRandomNumber(spawnInfo.minRespawnTime, spawnInfo.maxRespawnTime); - - ActivityTimerStart(self, timerName, respawnTime, respawnTime); - } -} - -// sg_cannon.lua: a target at the end of its path (SG_TARGET.lua) has the next one spawned, as after a hit -void SGCannon::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) { - if (name == "FinishedPath" && sender != nullptr) CheckSpawn(self, sender, sender->GetVar(u"SpawnTimerName")); -} - -void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& timerName) { - if (!self->GetVar(GameStartedVariable)) return; - - auto cannonBallKills = self->GetVar>(u"CannonBallKills"); - cannonBallKills.push_back(target->GetObjectID()); - self->SetVar>(u"CannonBallKills", cannonBallKills); - const auto& spawnInfo = target->GetVar(u"SpawnData"); - - CheckSpawn(self, target, timerName); - - int32_t score = SgTarget::GetActivityPoints(target); - - if (score > 0) { - score += score * GetCurrentBonus(self); - - if (!self->GetVar(SuperChargeActiveVariable)) { - self->SetVar(u"m_curStreak", self->GetVar(u"m_curStreak") + 1); - } - } else { - if (!self->GetVar(SuperChargeActiveVariable)) { - self->SetVar(u"m_curStreak", 0); - self->SetVar(MissesVariable, self->GetVar(MissesVariable) + 1); - } - - self->SetNetworkVar(u"hitFriend", true); - } - - auto lastSuperTotal = self->GetVar(u"LastSuperTotal"); - - auto scScore = self->GetVar(TotalScoreVariable) - lastSuperTotal; - - if (!self->GetVar(SuperChargeActiveVariable) && scScore >= constants.chargedPoints && score >= 0) { - StartChargedCannon(self); - self->SetNetworkVar(u"SuperChargeBar", 100.0f); - self->SetVar(u"LastSuperTotal", self->GetVar(TotalScoreVariable)); - } - - UpdateStreak(self); - - GameMessages::NotifyClientShootingGalleryScore galleryScore; - galleryScore.target = self->GetObjectID(); - galleryScore.addTime = 0.0f; - galleryScore.score = score; - galleryScore.targetID = target->GetObjectID(); - galleryScore.targetPos = target->GetPosition(); - galleryScore.Send(UNASSIGNED_SYSTEM_ADDRESS); - - auto newScore = self->GetVar(TotalScoreVariable) + score; - - if (newScore < 0) { - newScore = 0; - } - - self->SetVar(TotalScoreVariable, newScore); - - self->SetNetworkVar(u"updateScore", newScore); - - self->SetNetworkVar(u"beatHighScore", GeneralUtils::to_u16string(newScore)); - - auto* player = Game::entityManager->GetEntity(self->GetVar(PlayerIDVariable)); - if (player == nullptr) return; - - auto missionComponent = player->GetComponent(); - if (missionComponent == nullptr) return; - - missionComponent->Progress(eMissionTaskType::SMASH, spawnInfo.lot, self->GetObjectID()); - - auto matrix = self->GetVar(MatrixVariable); - - float rewardS = 0.0f; - float rewardF = 0.0f; - if (matrix <= 5) { - const auto scoreRewardNum = "Score_Reward_" + std::to_string(matrix); - const auto rewardAmountItr = constants.scoreRewards.find(scoreRewardNum); - if (rewardAmountItr != constants.scoreRewards.end()) { - const float rewardAmount = rewardAmountItr->second / 100 * 3; - rewardS = newScore / rewardAmount; - rewardF = std::round(rewardS * 3); - - if (rewardF > 100.0f) rewardF = 100.0f; - - self->SetNetworkVar(ModelPercentVariable, rewardF); - } - } - - if (rewardF > 0.0f && rewardF < 200.0f && matrix <= 5) { - const auto rewardModelGroup = Game::entityManager->GetEntitiesInGroup(constants.rewardModelGroup); - if (!rewardModelGroup.empty()) { - auto* rewardModel = rewardModelGroup[0]; - GameMessages::SpawnModelBricks spawnBricks{}; - spawnBricks.target = rewardModel->GetObjectID(); - spawnBricks.amount = rewardF / 100.0f; - spawnBricks.position = target->GetPosition(); - spawnBricks.Send(player->GetSystemAddress()); - if (rewardF >= 100.0f) { - SpawnNewModel(self); - self->SetVar(MatrixVariable, matrix + 1); - } - } - } -} - -void SGCannon::UpdateStreak(Entity* self) { - const auto streakBonus = GetCurrentBonus(self); - - const auto curStreak = self->GetVar(u"m_curStreak"); - - const auto marks = curStreak % 3; - - self->SetNetworkVar(u"cStreak", curStreak); - - if (curStreak >= 0 && curStreak < 13) { - if (marks == 1) { - self->SetNetworkVar(u"Mark1", true); - } else if (marks == 2) { - self->SetNetworkVar(u"Mark2", true); - } else if (marks == 0 && curStreak > 0) { - self->SetVar(u"StreakBonus", streakBonus); - self->SetNetworkVar(u"ShowStreak", streakBonus + 1); - self->SetNetworkVar(u"Mark3", true); - } else { - self->SetVar(u"StreakBonus", streakBonus); - self->SetNetworkVar(u"UnMarkAll", true); - } - } - auto maxStreak = self->GetVar(MaxStreakVariable); - if (maxStreak < curStreak) self->SetVar(MaxStreakVariable, curStreak); -} - -float_t SGCannon::GetCurrentBonus(Entity* self) { - auto streak = self->GetVar(u"m_curStreak"); - - if (streak > 12) { - streak = 12; - } - - return streak / 3; -} - -void SGCannon::ToggleSuperCharge(Entity* self, bool enable) { - if (enable && self->GetVar(SuperChargeActiveVariable)) - return; - - auto* player = Game::entityManager->GetEntity(self->GetVar(PlayerIDVariable)); - - if (player == nullptr) { - LOG("Player not found in toggle super charge"); - return; - } - - auto* inventoryComponent = player->GetComponent(); - - auto equippedItems = inventoryComponent->GetEquippedItems(); - - LOG("Player has %d equipped items", equippedItems.size()); - - auto skillID = constants.cannonSkill; - auto cooldown = constants.cannonRefireRate; - - auto* selfInventoryComponent = self->GetComponent(); - - // This is a gm in the original script - Item* meItem1{}; - Item* meItem2{}; - for (const auto item : selfInventoryComponent->GetInventory(eInventoryType::ITEMS)->GetItems() | std::views::values) { - if (item->GetSlot() == 0) meItem1 = item; - else if (item->GetSlot() == 1) meItem2 = item; - } - - if (!meItem1 || !meItem2) { - LOG("Cannon does not have the required items equipped"); - return; - } - - if (enable) { - LOG("Player is activating super charge"); - selfInventoryComponent->EquipItem(meItem1); - selfInventoryComponent->EquipItem(meItem2); - - skillID = constants.cannonSuperChargeSkill; - cooldown = 400; - } else { - selfInventoryComponent->UnEquipItem(meItem1); - selfInventoryComponent->UnEquipItem(meItem2); - - self->SetNetworkVar(u"SuperChargeBar", 0); - - LOG("Player disables super charge"); - - cooldown = 800; - self->SetVar(NumberOfChargesVariable, 0); - } - - const auto& constants = GetConstants(); - - auto* shootingGalleryComponent = self->GetComponent(); - - if (shootingGalleryComponent == nullptr) { - return; - } - - DynamicShootingGalleryParams properties = shootingGalleryComponent->GetDynamicParams(); - - properties.cannonFOV = constants.cannonFOV; - properties.cannonVelocity = constants.cannonVelocity; - properties.cannonRefireRate = cooldown; - properties.cannonMinDistance = constants.cannonMinDistance; - properties.cannonTimeout = -1; - - shootingGalleryComponent->SetDynamicParams(properties); - - Game::entityManager->SerializeEntity(self); - Game::entityManager->SerializeEntity(player); - - self->SetNetworkVar(CannonBallSkillIDVariable, skillID); - self->SetVar(SuperChargeActiveVariable, enable); -} - -std::vector> SGCannon::GetWaves() { - return { - // Wave 1 - { - // Ship 1 - { - std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1500, false, 0.0, 1.0, - 1.0, false, true - }, - - // Ship 2 - { - std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, - - // Sub 1 but for dlu - { - std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, - - //// Sub 1 - //{ - // std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, - // 6016, 0.0, 2.0, true, 0.0, 2.0, - // 10.0, 1000, false, 0.0, 1.0, - // 1.0, true, true - //}, - - // Sub 2 but for dlu - { - std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 3.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, - - // Sub 2 - //{ - // std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, - // 6016, 0.0, 2.0, true, 0.0, 2.0, - // 2.0, 1000, false, 0.0, 1.0, - // 1.0, true, true - //}, - - // Friendly - { - std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, - 2168,0.0,5.0,true, 2.0, 5.0, - 1.0, -1000, false, 0.0, 1.0, - 1.0, false,true - } - }, - - // Wave 2 - { - // Ship 1 - { - std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1500, false, 0.0, 1.0, - 1.0, false, true - }, - - // Ship 2 - { - std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, - - // Ship 3 - { - std::vector { "Wave_2_Ship_1" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, - - // Ship 4 - { - std::vector { "Wave_2_Ship_2" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, - - // Sub 1 - { - std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, - - // Sub 2 - //{ - // std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, - // 6016, 0.0, 2.0, true, 0.0, 2.0, - // 2.0, 1000, false, 0.0, 1.0, - // 1.0, true, true - //}, - - // Sub 2 but for dlu - { - std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 3.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, - - // Duck - { - std::vector { "Wave_1_Duck_1", "Wave_1_Duck_2" }, - 5946, 5.0, 10.0, true, 5.0, 10.0, - 4.0, 5000, false, 0.0, 1.0, - 1.0, false, true - }, - - // Friendly - { - std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, - 2168,0.0,5.0,true, 2.0, 5.0, - 1.0, -1000, false, 0.0, 1.0, - 1.0, false,true - } - }, - - // Wave 3 - { - // Ship 1 - { - std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1500, false, 0.0, 1.0, - 1.0, false, true - }, - - // Ship 2 - { - std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, - - // Ship 3 - { - std::vector { "Wave_2_Ship_1", "Wave_2_Ship_2" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, - - // Ship 4 - { - std::vector { "Wave_3_Ship_1", "Wave_3_Ship_2" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1500, false, 0.0, 1.0, - 1.0, false, true - }, - - // Sub 1 - { - std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, - - // Sub 2 - //{ - // std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, - // 6016, 0.0, 2.0, true, 0.0, 2.0, - // 2.0, 1000, false, 0.0, 1.0, - // 1.0, true, true - //}, - - // Sub 2 - { - std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 3.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, - - // Sub 3 - { - std::vector { "Wave_3_Sub_1", "Wave_3_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, - - // Duck - { - std::vector { "Wave_1_Duck_1", "Wave_1_Duck_2" }, - 5946, 5.0, 10.0, true, 5.0, 10.0, - 4.0, 5000, false, 0.0, 1.0, - 1.0, false, true - }, - - // Ness - { - std::vector { "Wave_1_Ness_1", "Wave_1_Ness_2", "Wave_2_Ness_1" }, - 2565, 10.0, 15.0, true, 10.0, 15.0, - 2.0, 10000, false, 0.0, 1.0, - 1.0, true, true - }, - - // Friendly 1 - { - std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, - 2168,0.0,5.0,true, 2.0, 5.0, - 1.0, -1000, false, 0.0, 1.0, - 1.0, false,true - }, - - // Friendly 2 - { - std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, - 2168,0.0,5.0,true, 2.0, 5.0, - 1.0, -1000, false, 0.0, 1.0, - 1.0, false,true - } - } - }; -} - -void SGCannon::ResetVars(Entity* self) { - self->SetVar(SpawnNumberVariable, 0); - self->SetVar(CurrentSpawnNumberVariable, 0); - self->SetVar(ThisWaveVariable, 0); - self->SetVar(GameScoreVariable, 0); - self->SetVar(GameTimeVariable, 0); - self->SetVar(GameStartedVariable, false); - self->SetVar(ShotsFiredVariable, 0); - self->SetVar(MaxStreakVariable, 0); - self->SetVar(MissesVariable, 0); - self->SetVar(CurrentStreakVariable, 0); - self->SetVar(CurrentSuperChargedTimeVariable, 0); - self->SetVar>(StreakBonusVariable, {}); - self->SetVar(LastSuperTotalVariable, 0); - self->SetVar(CurrentRewardVariable, LOT_NULL); - self->SetVar>(RewardsVariable, {}); - self->SetVar(TotalScoreVariable, 0); - - self->SetVar(u"m_curStreak", 0); - self->SetVar(u"LastSuperTotal", 0); - self->SetVar>(u"LastHitTarget", {}); - - const_cast&>(self->GetVar>(ActiveSpawnsVariable)).clear(); - self->SetVar>(ActiveSpawnsVariable, {}); - - const_cast&>(self->GetVar>(SpawnedObjects)).clear(); - self->SetVar>(SpawnedObjects, {}); - - if (self->GetVar(InitVariable)) { - ToggleSuperCharge(self, false); - } - - self->SetVar(ImpactSkillVariale, constants.impactSkillID); - self->SetVar>(PlayerScoresVariable, {}); - ActivityTimerStopAllTimers(self); -} - -SGConstants SGCannon::GetConstants() { - return { - .playerStartPosition = Vector3 { -908.542480, 229.773178, -908.542480 }, - .playerStartRotation = Quaternion { 0.91913521289825, 0, 0.39394217729568, 0 }, - .cannonLot = 1864, - .impactSkillID = 34, - .projectileLot = 1822, - .playerOffset = Vector3 { 6.652, -2, 1.5 }, - .rewardModelMatrix = 157, - .cannonVelocity = 129.0, - .cannonMinDistance = 30.0, - .cannonRefireRate = 800.0, - .cannonBarrelOffset = Vector3 { 0, 4.3, 9 }, - .cannonSuperchargedProjectileLot = 6297, - .cannonProjectileLot = 1822, - .cannonSuperChargeSkill = 249, - .cannonSkill = 228, - .cannonTimeout = -1, - .cannonFOV = 58.6, - .useLeaderboards = true, - .streakModifier = 2, - .chargedTime = 10, - .chargedPoints = 25000, - .rewardModelGroup = "QBRewardGroup", - .activityID = 1864, - .scoreRewards = { - {"Score_Reward_1", 50000}, - {"Score_Reward_2", 100000}, - {"Score_Reward_3", 200000}, - {"Score_Reward_4", 400000}, - {"Score_Reward_5", 800000}, - }, - .scoreLootMatrix1 = 157, - .scoreLootMatrix2 = 187, - .scoreLootMatrix3 = 188, - .scoreLootMatrix4 = 189, - .scoreLootMatrix5 = 190, - .firstWaveStartTime = 4.0, - .inBetweenWavePause = 7.0 - }; +ShootingGallery::SpawnTable SGCannon::TargetSettings() const { + return GfShootingGalleryData::GetTargetSettings(); } diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.h b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.h index 735fa91df..ba8929dbc 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.h +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.h @@ -1,162 +1,12 @@ #pragma once -#include -#include -#include "ActivityManager.h" +#include "../../ShootingGallery/ShootingGalleryCannon.h" -struct SGEnemy { - std::vector spawnPaths{}; - LOT lot; - float_t minSpawnTime; - float_t maxSpawnTime; - bool respawns; - float_t minRespawnTime; - float_t maxRespawnTime; - float_t initialSpeed; - int32_t score; - bool changeSpeedAtWaypoint; - float_t speedChangeChance; - float_t minSpeed; - float_t maxSpeed; - bool isMovingPlatform; - bool despawnOnLastWaypoint; -}; - -struct SGConstants { - Vector3 playerStartPosition; - Quaternion playerStartRotation = QuatUtils::IDENTITY; - LOT cannonLot; - uint32_t impactSkillID; - LOT projectileLot; - Vector3 playerOffset; - uint32_t rewardModelMatrix; - float_t cannonVelocity; - float_t cannonMinDistance; - float_t cannonRefireRate; - Vector3 cannonBarrelOffset; - LOT cannonSuperchargedProjectileLot; - LOT cannonProjectileLot; - uint32_t cannonSuperChargeSkill; - uint32_t cannonSkill; - int32_t cannonTimeout; - float_t cannonFOV; - bool useLeaderboards; - uint32_t streakModifier; - uint32_t chargedTime; - uint32_t chargedPoints; - std::string rewardModelGroup; - uint32_t activityID; - std::map scoreRewards; - uint32_t scoreLootMatrix1; - uint32_t scoreLootMatrix2; - uint32_t scoreLootMatrix3; - uint32_t scoreLootMatrix4; - uint32_t scoreLootMatrix5; - float_t firstWaveStartTime; - float_t inBetweenWavePause; -}; - -class SGCannon : public ActivityManager { +/** + * Gnarled Forest's shooting gallery cannon (SG_CANNON.lua, LOT 1864): the shared cannon with GF's constants and + * targets. + */ +class SGCannon : public ShootingGalleryCannon { public: - void OnStartup(Entity* self) override; - void OnPlayerLoaded(Entity* self, Entity* player) override; - void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; - void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; - void OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int32_t value1, int32_t value2, const std::u16string& stringValue) override; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; - void OnActivityTimerDone(Entity* self, const std::string& name) override; - void OnActivityTimerUpdate(Entity* self, const std::string& name, float_t timeRemaining, float_t elapsedTime) override; - void OnRequestActivityExit(Entity* self, LWOOBJID player, bool canceled) override; - void OnActivityNotify(Entity* self, GameMessages::ActivityNotify& notify) override; - void OnShootingGalleryFire(Entity& self, GameMessages::ShootingGalleryFire& fire) override; - void SuperChargeTimerFunc(Entity* self); - void SpawnWaveTimerFunc(Entity* self); - void EndWaveTimerFunc(Entity* self); - void GameOverTimerFunc(Entity* self); - void DoSpawnTimerFunc(Entity* self, const std::string& name); - void EndGameBufferTimerFunc(Entity* self); -private: - static std::vector> GetWaves(); - static SGConstants GetConstants(); - void ResetVars(Entity* self); - void StartGame(Entity* self); - void DoGameStartup(Entity* self); - void SpawnNewModel(Entity* self); - void TimerToggle(Entity* self, bool start = false); - void SpawnObject(Entity* self, const SGEnemy& toSpawn, bool spawnNow = false); - void StartChargedCannon(Entity* self, uint32_t optionalTime = 0); - void ToggleSuperCharge(Entity* self, bool enable); - void RecordPlayerScore(Entity* self); - void PlaySceneAnimation(Entity* self, const std::u16string& animationName, bool onCannon, bool onPlayer, float_t priority); - static void RemovePlayer(LWOOBJID playerID); - void PauseChargeCannon(Entity* self); - void StopGame(Entity* self, bool cancel = false); - void RegisterHit(Entity* self, Entity* target, const std::string& timerName); - // sg_cannon.lua (checkSpawn): a target that respawns gets its next spawn, while its wave runs - void CheckSpawn(Entity* self, Entity* target, const std::string& timerName); - // SG_TARGET.lua (onArrived at the last waypoint): the cannon spawns the next one, and the target is gone a moment later - void UpdateStreak(Entity* self); - float_t GetCurrentBonus(Entity* self); - - LOT m_CannonLot = 1864; - std::u16string PlayerIDVariable = u"PlayerID"; - std::u16string HideScoreBoardVariable = u"HideScoreBoard"; - std::u16string ReSetSuperChargeVariable = u"ReSetSuperCharge"; - std::u16string ShowLoadingUI = u"showLoadingUI"; - std::u16string SpawnNumberVariable = u"SpawnNum"; - std::u16string CurrentSpawnNumberVariable = u"CurSpawnNum"; - std::u16string ThisWaveVariable = u"ThisWave"; - std::u16string GameScoreVariable = u"GameScore"; - std::u16string GameTimeVariable = u"GameTime"; - std::u16string GameStartedVariable = u"GameStarted"; - std::u16string ShotsFiredVariable = u"ShotsFired"; - std::u16string MaxStreakVariable = u"MaxStreak"; - std::u16string MissesVariable = u"Misses"; - std::u16string CurrentStreakVariable = u"CurrentStreak"; - std::u16string CurrentSuperChargedTimeVariable = u"CurrentSuperChargedTime"; - std::u16string StreakBonusVariable = u"StreakBonus"; - std::u16string LastSuperTotalVariable = u"LastSuperTotal"; - std::u16string CurrentRewardVariable = u"CurrentReward"; - std::u16string RewardsVariable = u"Rewards"; - std::u16string TotalScoreVariable = u"TotalScore"; - std::u16string InitVariable = u"Init"; - std::u16string ImpactSkillVariale = u"ImpactSkill"; - std::u16string PlayerScoresVariable = u"PlayerScores"; - std::u16string InitialVelocityVariable = u"InitialVelocity"; - std::u16string ValidActorsVariable = u"ValidActors"; - std::u16string ValidEffectsVariable = u"ValidEffects"; - std::u16string SuperChargeActiveVariable = u"SuperChargeActive"; - std::u16string MatrixVariable = u"Matrix"; - std::u16string TimeLimitVariable = u"game_timelimit"; - std::u16string AudioStartIntroVariable = u"Audio_Start_Intro"; - std::u16string ClearVariable = u"Clear"; - std::u16string FirstTimeDoneVariable = u"FirstTimeDone"; - std::u16string RewardAddedVariable = u"rewardAdded"; - std::u16string SuperChargePausedVariable = u"Super_Charge_Paused"; - std::u16string WaveStatusVariable = u"WaveStatus"; - std::u16string CountVariable = u"count"; - std::u16string StopVariable = u"Stop"; - std::u16string ActiveSpawnsVariable = u"ActiveSpawns"; - std::u16string SpawnedObjects = u"SpawnedObjects"; - std::u16string WaveNumVariable = u"wave.waveNum"; - std::u16string WaveStrVariable = u"wave.waveStr"; - std::u16string ChargeCountingVariable = u"charge_counting"; - std::u16string SuperChargeBarVariable = u"SuperChargeBar"; - std::u16string NumberOfChargesVariable = u"NumberOfCharges"; - std::u16string CannonBallSkillIDVariable = u"cbskill"; - std::u16string HideSuperChargeVariable = u"HideSuper"; - std::u16string AudioFinalWaveDoneVariable = u"Audio_Final_Wave_Done"; - std::u16string ModelPercentVariable = u"modelPercent"; - - std::string SpawnWaveTimer = "SpawnWave"; - std::string EndWaveTimer = "EndWave"; - std::string GameOverTimer = "GameOver"; - std::string DoSpawnTimer = "DoSpawn"; - std::string EndGameBufferTimer = "endGameBuffer"; - std::string SuperChargeTimer = "SuperChargeTimer"; - - std::string ModelToBuildEvent = "modelToBuild"; - - std::regex DoSpawnRegex = std::regex("\\d*"); - SGConstants constants{}; - std::vector> m_Waves{}; + const ShootingGallery::Constants& GetConstants() const override; + ShootingGallery::SpawnTable TargetSettings() const override; }; diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SgTarget.cpp b/dScripts/ai/MINIGAME/SG_GF/SERVER/SgTarget.cpp index 9f6510f12..ae3b4d31e 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SgTarget.cpp +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SgTarget.cpp @@ -7,7 +7,7 @@ #include "GeneralUtils.h" #include "MovementAIComponent.h" #include "RenderComponent.h" -#include "SGCannon.h" +#include "ShootingGalleryTypes.h" #include "Zone.h" #include "dZoneManager.h" #include "eKillType.h" @@ -18,7 +18,7 @@ void SgTarget::OnStartup(Entity* self) { int32_t SgTarget::GetActivityPoints(Entity* self) { if (!self->HasVar(u"SpawnData")) return 0; - const int32_t points = self->GetVar(u"SpawnData").score; + const int32_t points = self->GetVar(u"SpawnData").sdScore; // SetActivityUserData{userID = zone control's GetActivityUser, typeIndex 5, value = points} on the target: only an // activity takes it, and the zone control without one has no user const auto* const zoneControl = Game::entityManager->GetZoneControlEntity(); @@ -66,10 +66,10 @@ void SgTarget::NotifyParentToRespawn(Entity* self) { return; } // 2 s for a moving platform, so the clients' platforms get to the end of the path first - const auto& spawnData = self->GetVar(u"SpawnData"); - if (!spawnData.despawnOnLastWaypoint) return; + const auto& spawnData = self->GetVar(u"SpawnData"); + if (!spawnData.sdDespawnTime) return; self->CancelTimer("Despawn"); - self->AddTimer("Despawn", spawnData.isMovingPlatform ? 2.0f : 1.0f); + self->AddTimer("Despawn", spawnData.sdMovingPlat ? 2.0f : 1.0f); } // ChangeSpeed: a speed of 1 to 4 every 5 s (the script's startup never starts this timer); Despawn: dies silently @@ -87,9 +87,9 @@ void SgTarget::OnTimerDone(Entity* self, std::string timerName) { // With its spawn data's chance, a new speed between its least and most (whole numbers, as Lua's math.random) void SgTarget::ChangeSpeed(Entity* self) { if (!self->HasVar(u"SpawnData")) return; - const auto& spawnData = self->GetVar(u"SpawnData"); - if (!spawnData.changeSpeedAtWaypoint || GeneralUtils::GenerateRandomNumber(0.0f, 1.0f) > spawnData.speedChangeChance) return; - SetPathingSpeed(self, static_cast(GeneralUtils::GenerateRandomNumber(static_cast(spawnData.minSpeed), static_cast(spawnData.maxSpeed)))); + const auto& spawnData = self->GetVar(u"SpawnData"); + if (!spawnData.sdChangeSpeed || GeneralUtils::GenerateRandomNumber(0.0f, 1.0f) > spawnData.sdSpeedChance) return; + SetPathingSpeed(self, static_cast(GeneralUtils::GenerateRandomNumber(static_cast(spawnData.sdMinSpeed), static_cast(spawnData.sdMaxSpeed)))); } // SetPathingSpeed: only an object following waypoints takes it (a moving platform has no handler for it) diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SgTarget.h b/dScripts/ai/MINIGAME/SG_GF/SERVER/SgTarget.h index 727d76b2b..3f9d8bac7 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SgTarget.h +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SgTarget.h @@ -14,7 +14,7 @@ public: void OnWaypointReached(Entity* self, uint32_t waypointIndex) override; void OnTimerDone(Entity* self, std::string timerName) override; - // The points a hit gives (the script's GetActivityPoints: its spawn data's score; the spawn data has no time score). + // The points a hit gives (the script's GetActivityPoints: its spawn data's score). // Also writes them as user data 5 of the zone control's activity user on the target's own activity, if it has one. static int32_t GetActivityPoints(Entity* self); // The animation a waypoint's first action names when that action is PlayAim, else empty diff --git a/dScripts/ai/MINIGAME/SG_GF/ZoneSGServer.cpp b/dScripts/ai/MINIGAME/SG_GF/ZoneSGServer.cpp index b1de87c92..f7b4b655a 100644 --- a/dScripts/ai/MINIGAME/SG_GF/ZoneSGServer.cpp +++ b/dScripts/ai/MINIGAME/SG_GF/ZoneSGServer.cpp @@ -1,26 +1,7 @@ #include "ZoneSGServer.h" -#include "EntityManager.h" -void ZoneSGServer::OnStartup(Entity* self) { - const auto cannons = Game::entityManager->GetEntitiesByLOT(1864); - for (const auto& cannon : cannons) - self->SetVar(CannonIDVariable, cannon->GetObjectID()); -} - -void ZoneSGServer::OnActivityStateChangeRequest(Entity* self, const LWOOBJID senderID, const int32_t value1, - const int32_t value2, const std::u16string& stringValue) { - - auto* cannon = Game::entityManager->GetEntity(self->GetVar(CannonIDVariable)); - if (cannon != nullptr) { - cannon->OnActivityStateChangeRequest(senderID, value1, value2, stringValue); - } -} - -void ZoneSGServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { - - auto* cannon = Game::entityManager->GetEntity(self->GetVar(CannonIDVariable)); - if (cannon != nullptr) { - cannon->OnFireEventServerSide(sender, args, param1, param2, param3); - } +#include "GfShootingGalleryData.h" + +const ShootingGallery::Constants& ZoneSGServer::GetConstants() const { + return GfShootingGalleryData::GetConstants(); } diff --git a/dScripts/ai/MINIGAME/SG_GF/ZoneSGServer.h b/dScripts/ai/MINIGAME/SG_GF/ZoneSGServer.h index eaa7c909e..78340d3b0 100644 --- a/dScripts/ai/MINIGAME/SG_GF/ZoneSGServer.h +++ b/dScripts/ai/MINIGAME/SG_GF/ZoneSGServer.h @@ -1,13 +1,11 @@ #pragma once -#include "CppScripts.h" +#include "../ShootingGallery/ShootingGalleryZone.h" -class ZoneSGServer : public CppScripts::Script { +/** + * Gnarled Forest's shooting gallery zone (L_ZONE_SG_SERVER.lua, zone 1302): the shared zone script with GF's + * constants. Its own copy of the targets (targetSettings) is not ported: nothing reads it, the cannon has its own. + */ +class ZoneSGServer : public ShootingGalleryZone { public: - void OnStartup(Entity* self) override; - void OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int32_t value1, - int32_t value2, const std::u16string& stringValue) override; - void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; -private: - std::u16string CannonIDVariable = u"CannonID"; + const ShootingGallery::Constants& GetConstants() const override; }; diff --git a/dScripts/ai/MINIGAME/ShootingGallery/CMakeLists.txt b/dScripts/ai/MINIGAME/ShootingGallery/CMakeLists.txt index ae2eacf4e..f6b154eff 100644 --- a/dScripts/ai/MINIGAME/ShootingGallery/CMakeLists.txt +++ b/dScripts/ai/MINIGAME/ShootingGallery/CMakeLists.txt @@ -1,3 +1,5 @@ set(DSCRIPTS_SOURCES_AI_MINIGAME_SHOOTING_GALLERY + "ShootingGalleryCannon.cpp" "ShootingGalleryLogic.cpp" + "ShootingGalleryZone.cpp" PARENT_SCOPE) diff --git a/dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryCannon.cpp b/dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryCannon.cpp new file mode 100644 index 000000000..735bd0e2c --- /dev/null +++ b/dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryCannon.cpp @@ -0,0 +1,1138 @@ +#include "ShootingGalleryCannon.h" + +#include "ShootingGalleryLogic.h" +#include "SgTarget.h" + +#include "ActivityMessages.h" +#include "BuildingMessages.h" +#include "Character.h" +#include "CharacterComponent.h" +#include "DestroyableComponent.h" +#include "EffectsMessages.h" +#include "Entity.h" +#include "EntityManager.h" +#include "GameMessages.h" +#include "GeneralUtils.h" +#include "InventoryComponent.h" +#include "Item.h" +#include "Loot.h" +#include "MissionComponent.h" +#include "MovementAIComponent.h" +#include "MovingPlatformComponent.h" +#include "PlayerManager.h" +#include "PossessorComponent.h" +#include "RenderComponent.h" +#include "ShootingGalleryComponent.h" +#include "SimplePhysicsComponent.h" +#include "SkillComponent.h" +#include "Zone.h" +#include "dZoneManager.h" +#include "eGameActivity.h" +#include "eKillType.h" +#include "eMissionTaskType.h" + +#include + +namespace { + // for Animations + const std::vector VALID_ACTORS = { 3109, 3110, 3111, 3112, 3125, 3126 }; + const std::vector VALID_EFFECTS = { 3122 }; + const std::vector STREAK_BONUS = { 1, 2, 5, 10 }; + + const std::string SuperChargeTimer = "Super_Charge_Timer"; + const std::string SpawnWaveTimer = "SpawnWave"; + const std::string EndWaveTimer = "EndWave"; + const std::string GameOverTimer = "GameOver"; + const std::string DoSpawnTimer = "DoSpawn"; + const std::string EndGameBufferTimer = "endGameBuffer"; + + // math.random() + float Random01() { + return GeneralUtils::GenerateRandomNumber(0.0f, 1.0f); + } + + // math.random(m, n) + int32_t RandomRange(const int32_t m, const int32_t n) { + return GeneralUtils::GenerateRandomNumber(m, n); + } +}; + +ShootingGalleryCannon::State& ShootingGalleryCannon::GetState(const Entity* self) { + return m_States[self->GetObjectID()]; +} + +Entity* ShootingGalleryCannon::GetActivityUser(const Entity* self) const { + const auto* const shootingGallery = self->GetComponent(); + if (shootingGallery == nullptr) return nullptr; + return Game::entityManager->GetEntity(shootingGallery->GetCurrentPlayerID()); +} + +Entity* ShootingGalleryCannon::GetActivityPlayer(Entity* self) { + return Game::entityManager->GetEntity(GetState(self).activityPlayer); +} + +// SetShootingGalleryParams: the cannon's shooting gallery component takes them and sends them to the clients +void ShootingGalleryCannon::SetShootingGalleryParams(Entity* self, const float cooldown, const float timeLimit) { + auto* const shootingGallery = self->GetComponent(); + if (shootingGallery == nullptr) return; + const auto& g_const = GetConstants(); + auto params = shootingGallery->GetDynamicParams(); + if (g_const.CANNON_BARREL_OFFSET) params.cameraBarrelOffset = *g_const.CANNON_BARREL_OFFSET; + params.cannonVelocity = g_const.CANNON_VELOCITY; + params.cannonRefireRate = cooldown; + params.cannonMinDistance = g_const.CANNON_MIN_DISTANCE; + params.cannonTimeout = timeLimit; + params.cannonFOV = g_const.CANNON_FOV; + shootingGallery->SetDynamicParams(params); + Game::entityManager->SerializeEntity(self); +} + +// RequestActivitySummaryLeaderboardData{target = self, queryType = 1, gameID = activityID} on the activity user +void ShootingGalleryCannon::RequestActivitySummaryLeaderboardData(Entity* self) { + const auto* const user = GetActivityUser(self); + if (user == nullptr) return; + GetLeaderboardData(self, user->GetObjectID(), GetConstants().ActivityID, 10); +} + +// ActivityPause{rerouteID = player, bPause} +void ShootingGalleryCannon::ActivityPause(Entity* self, Entity* player, const bool bPause) { + if (player == nullptr) return; + GameMessages::ActivityPause activityPause; + activityPause.target = self->GetObjectID(); + activityPause.bPause = bPause; + activityPause.Send(player->GetSystemAddress()); +} + +// ActivityStop{rerouteID = player, bExit, bUserCanceled}: a game played to its end gets the activity's rewards, rated +// by onDoCalculateActivityRating, and its missions +void ShootingGalleryCannon::ActivityStop(Entity* self, Entity* player, const bool bExit, const bool bUserCanceled) { + if (!bUserCanceled) { + const auto& state = GetState(self); + if (auto* const missionComponent = player->GetComponent()) { + missionComponent->Progress(eMissionTaskType::PERFORM_ACTIVITY, state.Mym_totalScore, self->GetObjectID(), "performact_score"); + missionComponent->Progress(eMissionTaskType::PERFORM_ACTIVITY, state.m_maxStreak, self->GetObjectID(), "performact_streak"); + missionComponent->Progress(eMissionTaskType::ACTIVITY, GetConstants().CANNON_TEMPLATEID, 0, "", state.Mym_totalScore); + } + Loot::GiveActivityLoot(player, self->GetObjectID(), GetGameID(self), static_cast(CalculateActivityRating(self, player->GetObjectID()))); + } + + GameMessages::ActivityStop activityStop; + activityStop.target = self->GetObjectID(); + activityStop.bExit = bExit; + activityStop.bUserCancel = bUserCanceled; + activityStop.Send(player->GetSystemAddress()); +} + +// -------------------------------------------------------------- +// onStartup +// -------------------------------------------------------------- +void ShootingGalleryCannon::OnStartup(Entity* self) { + auto& state = GetState(self); + // set game state + state.spawns = TargetSettings(); + ResetVars(self); + state.GameStarted = false; + state.m_totalScore = 0; + + // send an object loaded message to the ZoneControl object + auto* const zoneControl = Game::entityManager->GetZoneControlEntity(); + if (zoneControl != nullptr) { + GameMessages::ObjectLoaded objectLoaded; + objectLoaded.objectID = self->GetObjectID(); + objectLoaded.lot = self->GetLOT(); + objectLoaded.Send(zoneControl->GetObjectID()); + } + + // StartLuaNotify: the zone script passes its ActivityStateChangeRequest, MessageBoxRespond and ObjectLoaded on + // (ShootingGalleryZone) + + // Constants + const auto& g_const = GetConstants(); + state.FIRST_WAVE_START_TIME = g_const.FIRST_WAVE_START_TIME; + state.ImpactSkillID = g_const.IMPACT_SKILLID; + + auto* const shootingGallery = self->GetComponent(); + if (shootingGallery != nullptr) { + // The camera, which the script does not set + shootingGallery->SetStaticParams({ + NiPoint3(-327.8609924316406f, 256.8999938964844f, 1.6482199430465698f), + NiPoint3(-181.4320068359375f, 212.39999389648438f, 2.5182199478149414f) + }); + } + SetShootingGalleryParams(self, g_const.CANNON_REFIRE_RATE, g_const.CANNON_TIMEOUT); + + state.TIME_LIMIT = g_const.waveTimeLimits.empty() ? 0.0f : g_const.waveTimeLimits.front(); + state.Super_Charge_Active = false; + state.Matrix = 1; + state.bInit = true; + + if (auto* const simplePhysics = self->GetComponent()) simplePhysics->SetPhysicsMotionState(5); + Game::entityManager->SerializeEntity(self); +} + +// resetVars +void ShootingGalleryCannon::ResetVars(Entity* self) { + auto& state = GetState(self); + state.SpawnNum = 0; + state.CurSpawnNum = 0; + state.ThisWave = 0; + state.GameStarted = false; + state.m_shotsFired = 0; + state.m_maxStreak = 0; + state.m_misses = 0; + state.m_curStreak = 0; + state.Current_Super_Charged_Time = 0.0f; + + state.StreakBonus = 0; + state.LastSuperTotal.reset(); + state.currentReward = LOT_NULL; + state.rewards = { LOT_NULL }; + state.Mym_totalScore = 0; + + if (state.bInit) ToggleSuperCharge(self, false); + + state.ImpactSkillID = GetConstants().IMPACT_SKILLID; + + // reset scores + state.PLAYER_SCORE.assign(GetConstants().NUM_WAVES(), 0); + + ActivityTimerStopAllTimers(self); +} + +// The first onChildLoaded (firing the loaded projectile) is replaced by the second one, the target spawning; the +// projectile's skill and velocity come from the cannon's skill. + +// -------------------------------------------------------------- +// PlaySceneAnimation: play animations on all actors in the scene, and others +// -------------------------------------------------------------- +void ShootingGalleryCannon::PlaySceneAnimation(Entity* self, const std::string& anim, const bool bPlayCannon, const bool bPlayPlayer, const bool bMustPlay) { + const float priority = bMustPlay ? 1.07f : 0.5f; + + for (auto* const friendObject : Game::entityManager->GetEntitiesInGroup("cannongroup")) { + RenderComponent::PlayAnimation(friendObject, anim, priority); + } + + // play on cannon + if (bPlayCannon) RenderComponent::PlayAnimation(self, anim, priority); + + // play on player + if (bPlayPlayer) { + auto* const player = GetActivityPlayer(self); + if (player != nullptr) RenderComponent::PlayAnimation(player, anim, priority); + } +} + +// PlaySceneEffect: play effects on all effects in the scene +void ShootingGalleryCannon::PlaySceneEffect(Entity* self, const std::u16string& effectName) { + for (const auto effectID : GetState(self).EFFECTS) { + GameMessages::PlayFXEffect(effectID, -1, effectName, "").Send(UNASSIGNED_SYSTEM_ADDRESS); + } +} + +// -------------------------------------------------------------- +// onShootingGalleryFire: called when the client wants to fire +// -------------------------------------------------------------- +void ShootingGalleryCannon::OnShootingGalleryFire(Entity& self, GameMessages::ShootingGalleryFire& fire) { + auto& state = GetState(&self); + // CalculateFiringParameters{targetPos, bUseHighArc = false}: the server has no solver for it, so the firing + // velocity counts as found (all three of its axes not 0) + state.m_shotsFired++; + + if (auto* const player = GetActivityUser(&self)) { + // PlayFXEffect with ignoreID = player: every client but the player's + GameMessages::PlayFXEffect(self.GetObjectID(), -1, u"onfire", "").BroadcastExcept(player->GetSystemAddress()); + GameMessages::PlayFXEffect(self.GetObjectID(), -1, u"onfire2", "").BroadcastExcept(player->GetSystemAddress()); + GameMessages::PlayFXEffect(player->GetObjectID(), -1, u"SG-fire", "").BroadcastExcept(player->GetSystemAddress()); + } + // Tell the zone control we just fired (its script has no handler) + + // play fire animation on actors + PlaySceneAnimation(&self, "fire", false, false); + PlaySceneEffect(&self, u"fire"); +} + +// onGetFaction (the cannon's faction is the user's) is not ported: the cannon's own faction is what its skill hits with + +// toggleSuperCharge +void ShootingGalleryCannon::ToggleSuperCharge(Entity* self, const bool enable) { + auto& state = GetState(self); + const auto& g_const = GetConstants(); + uint32_t iSkillID = g_const.CANNON_SKILL; + float iCooldown = g_const.CANNON_REFIRE_RATE; + bool bSetChargedState = false; + + // GetInventoryItemInSlot{slot = 0 / 1} + Item* meItem1 = nullptr; + Item* meItem2 = nullptr; + auto* const inventory = self->GetComponent(); + if (inventory != nullptr) { + for (auto* const item : inventory->GetInventory(eInventoryType::ITEMS)->GetItems() | std::views::values) { + if (item->GetSlot() == 0) meItem1 = item; + else if (item->GetSlot() == 1) meItem2 = item; + } + } + + if (enable && state.Super_Charge_Active) { + return; + } else if (enable && !state.Super_Charge_Active) { + if (inventory != nullptr && meItem1 != nullptr) inventory->EquipItem(meItem1); + if (inventory != nullptr && meItem2 != nullptr) inventory->EquipItem(meItem2); + + iSkillID = g_const.CANNON_SUPERCHARGE_SKILL; + iCooldown = 400.0f; + bSetChargedState = true; + } else { + if (inventory != nullptr && meItem1 != nullptr) inventory->UnEquipItem(meItem1); + if (inventory != nullptr && meItem2 != nullptr) inventory->UnEquipItem(meItem2); + + state.NumberOfCharges = 0; + } + + SetShootingGalleryParams(self, iCooldown, -1.0f); + + self->SetNetworkVar(u"cbskill", iSkillID); + state.Super_Charge_Active = bSetChargedState; +} + +// TimerToggle +void ShootingGalleryCannon::TimerToggle(Entity* self, const bool bStart) { + auto& state = GetState(self); + if (bStart) { + self->SetNetworkVar(u"count", static_cast(state.TIME_LIMIT)); + state.Started = true; + } else { + // Stop Timer on Client + self->SetNetworkVar(u"Stop", true); + } +} + +// pauseChargeCannon +void ShootingGalleryCannon::PauseChargeCannon(Entity* self) { + auto& state = GetState(self); + float superChargeTime = std::ceil(ActivityTimerGetRemainingTime(self, SuperChargeTimer)); + + if (superChargeTime < 1 && superChargeTime > 0) superChargeTime = 1; + + state.Super_Charge_Paused = true; + state.Current_Super_Charged_Time = superChargeTime; + + self->SetNetworkVar(u"charge_counting", std::ceil(superChargeTime)); + ActivityTimerStop(self, SuperChargeTimer); +} + +// StartChargedCannon: a time of 0 is a time (Lua's 0 is true), only none uses ChargedTime +void ShootingGalleryCannon::StartChargedCannon(Entity* self, const std::optional optionalTime) { + auto& state = GetState(self); + const float iTime = optionalTime.value_or(GetConstants().ChargedTime); + + state.Super_Charge_Paused = false; + ToggleSuperCharge(self, true); + ActivityTimerStart(self, SuperChargeTimer, 1, iTime); + + if (!state.WaveStatus) PauseChargeCannon(self); +} + +// updateStreak +void ShootingGalleryCannon::UpdateStreak(Entity* self) { + auto& state = GetState(self); + const auto streakBonus = ShootingGallery::Logic::GetCurrentBonus(state.m_curStreak); + const auto curStreak = state.m_curStreak; + + self->SetNetworkVar(u"cStreak", curStreak); + // Update the marks + switch (ShootingGallery::Logic::GetStreakMark(curStreak)) { + case ShootingGallery::Logic::StreakMark::MARK1: + self->SetNetworkVar(u"Mark1", true); + break; + case ShootingGallery::Logic::StreakMark::MARK2: + self->SetNetworkVar(u"Mark2", true); + break; + case ShootingGallery::Logic::StreakMark::MARK3: + state.StreakBonus = streakBonus; + self->SetNetworkVar(u"ShowStreak", streakBonus + 1); + self->SetNetworkVar(u"Mark3", true); + break; + case ShootingGallery::Logic::StreakMark::UNMARK_ALL: + state.StreakBonus = streakBonus; + self->SetNetworkVar(u"UnMarkAll", true); + break; + case ShootingGallery::Logic::StreakMark::NONE: + break; + } +} + +// -------------------------------------------------------------- +// onActivityTimerUpdate +// -------------------------------------------------------------- +void ShootingGalleryCannon::OnActivityTimerUpdate(Entity* self, const std::string& name, const float_t timeRemaining, const float_t elapsedTime) { + if (name == SuperChargeTimer && !GetState(self).Super_Charge_Paused) { + self->SetNetworkVar(u"charge_counting", timeRemaining); + } +} + +// -------------------------------------------------------------- +// onActivityTimerDone +// -------------------------------------------------------------- +void ShootingGalleryCannon::OnActivityTimerDone(Entity* self, const std::string& name) { + auto& state = GetState(self); + const auto& g_const = GetConstants(); + + if (name == SuperChargeTimer && !state.Super_Charge_Paused) { + if (state.WaveStatus || state.Current_Super_Charged_Time < 1) { + self->SetNetworkVar(u"charge_counting", 999.0f); + self->SetNetworkVar(u"SuperChargeBar", 0.0f); + ToggleSuperCharge(self, false); + } + } else if (name.starts_with(SpawnWaveTimer)) { + if (state.GameStarted) { + const auto waveNum = state.ThisWave; + auto* const player = GetActivityPlayer(self); + + // store this wave number + state.WaveStatus = true; + state.ThisWaveVar = waveNum; + + if (waveNum != 1 && state.Super_Charge_Paused) { + StartChargedCannon(self, state.Current_Super_Charged_Time); + state.Current_Super_Charged_Time = 0.0f; + } + + TimerToggle(self, true); + + // setup spawns for wave + if (waveNum >= 1 && waveNum <= state.spawns.size()) { + auto& waveSpawns = state.spawns[waveNum - 1]; + for (uint32_t k = 0; k < waveSpawns.size(); k++) SpawnObject(k, waveSpawns[k], self, true); + } + + // there are no more waves left so stop game after this wave + if (waveNum >= g_const.NUM_WAVES()) { + ActivityTimerStart(self, GameOverTimer, state.TIME_LIMIT, state.TIME_LIMIT); + } else { + // setup next wave + ActivityTimerStart(self, EndWaveTimer + std::to_string(waveNum), state.TIME_LIMIT, state.TIME_LIMIT); + } + + if (player != nullptr) { + GameMessages::StartActivityTime startActivityTime; + startActivityTime.target = self->GetObjectID(); + startActivityTime.startTime = state.TIME_LIMIT; + startActivityTime.Send(player->GetSystemAddress()); + ActivityPause(self, player, false); + } + } + } else if (name.starts_with(EndWaveTimer)) { // called when a wave ends, contains the number of the next wave + if (state.GameStarted) { + state.WaveStatus = false; + + // get rid of current spawns + TimerToggle(self); + + // record the score + RecordPlayerWaveScore(self); + + // get the wave number from the rest of the string, and store the next wave number + const auto waveNum = ShootingGallery::Logic::GetTimerNumber(name, EndWaveTimer).value_or(0) + 1; + state.ThisWave = waveNum; + + // play wave animation on actors, cannon, and player + PlaySceneAnimation(self, "wave" + std::to_string(state.ThisWave), true, true, true); + // display wave number to player + DisplayWaveNumberToPlayer(self, waveNum); + + // there are no more waves left so stop game after this wave + if (waveNum > g_const.NUM_WAVES()) { + // Game Over + ActivityTimerStart(self, GameOverTimer, 0.1f, 0.1f); + } else { + // setup next wave + ActivityTimerStart(self, SpawnWaveTimer + std::to_string(waveNum), g_const.IN_BETWEEN_WAVE_PAUSE, g_const.IN_BETWEEN_WAVE_PAUSE); + } + + ActivityPause(self, GetActivityPlayer(self), true); + + if (state.Super_Charge_Active && !state.Super_Charge_Paused) PauseChargeCannon(self); + } + } else if (name == GameOverTimer) { + // Send buffer timer here + auto* const player = GetActivityPlayer(self); + // The "cannonball" group: the cannon balls still in the air + const auto* const skill = self->GetComponent(); + const auto cannonballs = skill != nullptr ? skill->GetManagedProjectileCount() : 0; + + ActivityPause(self, player, true); + + if (cannonballs >= 1) { + ActivityTimerStart(self, EndGameBufferTimer, 1, static_cast(cannonballs)); + } else { + RecordPlayerWaveScore(self); + StopGame(self, false); + } + + TimerToggle(self); + } else if (name.starts_with(DoSpawnTimer)) { + if (state.GameStarted) { + // get the spawn number from the rest of the string + const auto spawnNum = ShootingGallery::Logic::GetTimerNumber(name, DoSpawnTimer); + if (spawnNum) DoSpawn(self, *spawnNum); + } + } else if (name == EndGameBufferTimer) { + RecordPlayerWaveScore(self); + StopGame(self, false); + } +} + +// onActivityTimerDone's DoSpawn: load the spawn data's target at the first waypoint of its path +void ShootingGalleryCannon::DoSpawn(Entity* self, const uint32_t spawnNum) { + auto& state = GetState(self); + const auto itr = state.SPAWN_DATA.find(spawnNum); + if (itr == state.SPAWN_DATA.end()) return; + const auto spawnData = itr->second; + const auto templateID = spawnData.sdTemplate; + // get the position of the first waypoint (the Lua errors on a spawn without a path, which spawns nothing) + if (!spawnData.sdPath) return; + const auto* const path = Game::zoneManager->GetZone()->GetPath(*spawnData.sdPath); + if (path == nullptr || path->pathWaypoints.empty()) return; + + EntityInfo info{}; + info.lot = templateID; + info.spawnerID = self->GetObjectID(); + info.pos = path->pathWaypoints.front().position; + info.settings.Insert(u"streakmod", GetConstants().STREAK_MOD); + info.settings.Insert>(u"streakbonus", STREAK_BONUS); + info.settings.Insert(u"wave", state.ThisWave); + info.settings.Insert(u"custom_script_server", "scripts/ai/ACT/SG_TARGET.lua"); + info.settings.Insert(u"custom_script_client", "scripts/client/ai/SG_TARGET_CLIENT.lua"); + + // load the object in the world + auto* const child = Game::entityManager->CreateEntity(info, nullptr, self); + // onChildLoaded, before the clients get it so they get it on its path (live's targets came with their path) + OnChildLoaded(self, child); + if (auto* const simplePhysics = child->GetComponent()) simplePhysics->SetPhysicsMotionState(4); + Game::entityManager->ConstructEntity(child); +} + +// -------------------------------------------------------------- +// onActivityNotify +// -------------------------------------------------------------- +void ShootingGalleryCannon::OnActivityNotify(Entity* self, GameMessages::ActivityNotify& notify) { + auto& state = GetState(self); + const auto tKills = state.CannonBallKills; + const auto& g_const = GetConstants(); + + const auto itr = notify.notification.values.find(u"shot_done"); + if (itr == notify.notification.values.end() || itr->second->GetValueType() != LDF_TYPE_S32) return; + // Don't count any of this if we're firing our super charged cannon ball + const LOT shotDone = static_cast*>(itr->second.get())->GetValue(); + + if (tKills.empty() && shotDone != g_const.CANNON_SUPER_CHARGE) { + state.m_curStreak = 0; + // This account for real misses + state.m_misses++; + self->SetNetworkVar(u"HideStreak", true); + self->SetNetworkVar(u"UnMarkAll", true); + } else if (!tKills.empty()) { + // registerHit for all of the kills since last shot + for (const auto killID : tKills) { + // The Lua errors on a target that is gone + auto* const target = Game::entityManager->GetEntity(killID); + if (target != nullptr) RegisterHit(self, target, shotDone); + } + + if (tKills.size() > 1) self->SetNetworkVar(u"mHit", true); + } + + if (shotDone != g_const.CANNON_SUPER_CHARGE) { + if (state.friendly_hit) state.m_curStreak = 0; + + UpdateStreak(self); + } + + state.friendly_hit = false; + state.CannonBallKills.clear(); +} + +// registerHit +void ShootingGalleryCannon::RegisterHit(Entity* self, Entity* target, const LOT shotType) { + auto& state = GetState(self); + const auto& g_const = GetConstants(); + int32_t points = SgTarget::GetActivityPoints(target); + + // Only apply bonus to positive things and don't do streak etc for negative + if (points >= 0) { + points = ShootingGallery::Logic::ApplyStreakBonus(points, state.m_curStreak); + + if (shotType != g_const.CANNON_SUPER_CHARGE) { + state.m_curStreak++; + + if (state.m_curStreak > state.m_maxStreak) state.m_maxStreak = state.m_curStreak; + } + } else { + if (shotType != g_const.CANNON_SUPER_CHARGE) { + state.m_curStreak = 0; + // This accounts for friendlies + state.m_misses++; + state.friendly_hit = true; + } + + self->SetNetworkVar(u"hitFriend", true); + } + + auto* const user = GetActivityUser(self); + if (user != nullptr) { + GameMessages::NotifyClientShootingGalleryScore galleryScore; + galleryScore.target = self->GetObjectID(); + galleryScore.score = points; + galleryScore.targetID = target->GetObjectID(); + galleryScore.targetPos = target->GetPosition(); + galleryScore.Send(user->GetSystemAddress()); + } + + state.m_totalScore += points; + + self->SetNetworkVar(u"updateScore", state.m_totalScore); + + const int32_t lastSuperTotal = state.LastSuperTotal.value_or(0); + const int32_t scScore = state.m_totalScore - lastSuperTotal; + + if (shotType != g_const.CANNON_SUPER_CHARGE && scScore >= g_const.ChargedPoints && points >= 0) { + StartChargedCannon(self); + self->SetNetworkVar(u"SuperChargeBar", 100.0f); + state.LastSuperTotal = state.m_totalScore; + } + + float rewardF = 0.0f; + + if (state.Matrix <= 5 && state.Matrix <= g_const.Score_Reward.size()) { + rewardF = ShootingGallery::Logic::GetRewardPercent(state.m_totalScore, g_const.Score_Reward[state.Matrix - 1]); + self->SetNetworkVar(u"modelPercent", rewardF); + } + + if (rewardF > 0 && rewardF < 200 && state.Matrix <= 5) { + const auto obj = Game::entityManager->GetEntitiesInGroup(g_const.Reward_Model_GrpName); + + // check to make sure obj[1] is not nil + if (!obj.empty()) { + GameMessages::SpawnModelBricks spawnBricks; + spawnBricks.target = obj.front()->GetObjectID(); + spawnBricks.amount = rewardF / 100.0f; + spawnBricks.position = target->GetPosition(); + spawnBricks.Send(UNASSIGNED_SYSTEM_ADDRESS); + + if (rewardF >= 100) { + SpawnNewModel(self); + state.Matrix++; + } + } + } + + self->SetNetworkVar(u"beatHighScore", GeneralUtils::to_u16string(state.m_totalScore)); + + CheckSpawn(self, target); +} + +// onUpdateMissionTask: the cannon ball's kills, forwarded to the cannon; kept for the shot's end (onActivityNotify) +void ShootingGalleryCannon::UpdateMissionTaskKill(Entity* self, Entity* target) { + GetState(self).CannonBallKills.push_back(target->GetObjectID()); + + auto* const user = GetActivityUser(self); + if (user == nullptr) return; + if (auto* const missionComponent = user->GetComponent()) { + missionComponent->Progress(eMissionTaskType::SMASH, target->GetLOT(), self->GetObjectID()); + } +} + +// -------------------------------------------------------------- +// RequestActivityEnter, then onRequestActivityEnter: put the player in the cannon, does not start the cannon +// -------------------------------------------------------------- +void ShootingGalleryCannon::RequestActivityEnter(Entity* self, Entity* player) { + // The activity takes the player: the client enters the cannon + GameMessages::ActivityEnter activityEnter; + activityEnter.target = self->GetObjectID(); + activityEnter.Send(player->GetSystemAddress()); + + if (auto* const shootingGallery = self->GetComponent()) { + shootingGallery->SetCurrentPlayerID(player->GetObjectID()); + Game::entityManager->SerializeEntity(self); + } + + if (auto* const characterComponent = player->GetComponent()) { + characterComponent->SetCurrentActivity(eGameActivity::SHOOTING_GALLERY); + if (auto* const possessor = player->GetComponent()) { + possessor->SetPossessable(self->GetObjectID()); + possessor->SetPossessableType(ePossessionType::NO_POSSESSION); + } + Game::entityManager->SerializeEntity(player); + } + + // onRequestActivityEnter + GetState(self).activityPlayer = player->GetObjectID(); + self->SetNetworkVar(u"HideScoreBoard", true); + self->SetNetworkVar(u"ReSetSuperCharge", true); + self->SetNetworkVar(u"showLoadingUI", true); + + // Preloading reload animations: cannonballs, plunger, and pirate + const auto preload = [self](const Entity* object) { + GameMessages::PreloadAnimation preloadAnimation; + preloadAnimation.target = object->GetObjectID(); + preloadAnimation.animationID = u"wave1"; + preloadAnimation.respondObjID = self->GetObjectID(); + preloadAnimation.Send(UNASSIGNED_SYSTEM_ADDRESS); + }; + for (const auto* const sceneActor : Game::entityManager->GetEntitiesInGroup("cannongroup")) preload(sceneActor); + preload(player); + preload(self); +} + +// spawnNewModel +void ShootingGalleryCannon::SpawnNewModel(Entity* self) { + auto& state = GetState(self); + const auto& g_const = GetConstants(); + + if (state.currentReward != LOT_NULL) { + if (!state.rewards.empty() && state.rewards.front() != LOT_NULL) { + state.rewards.push_back(state.currentReward); + } else { + state.rewards = { state.currentReward }; + } + + self->SetNetworkVar(u"rewardAdded", state.currentReward); + } + + auto* const player = GetActivityPlayer(self); + // Score_LootMatrix_ (none past the fifth) + const uint32_t lootMatrix = state.Matrix >= 1 && state.Matrix <= g_const.Score_LootMatrix.size() ? g_const.Score_LootMatrix[state.Matrix - 1] : 0; + for (auto* const rewardObj : Game::entityManager->GetEntitiesInGroup(g_const.Reward_Model_GrpName)) { + if (player == nullptr || lootMatrix == 0) continue; + const auto items = Loot::RollLootMatrix(player, lootMatrix); + + for (const auto& [lot, count] : items) { + GameMessages::SetModelToBuild modelToBuild; + modelToBuild.target = rewardObj->GetObjectID(); + modelToBuild.modelLot = lot; + modelToBuild.Send(UNASSIGNED_SYSTEM_ADDRESS); + state.currentReward = lot; + } + } +} + +// -------------------------------------------------------------- +// startGame: try to start the game +// -------------------------------------------------------------- +void ShootingGalleryCannon::StartGame(Entity* self) { + auto& state = GetState(self); + // clear score + self->SetNetworkVar(u"game_timelimit", static_cast(state.TIME_LIMIT)); + self->SetNetworkVar(u"Audio_Start_Intro", true); + + state.currentReward = LOT_NULL; + + for (auto* const rewardObj : Game::entityManager->GetEntitiesInGroup(GetConstants().Reward_Model_GrpName)) { + GameMessages::SetModelToBuild modelToBuild; + modelToBuild.target = rewardObj->GetObjectID(); + modelToBuild.modelLot = LOT_NULL; + modelToBuild.Send(UNASSIGNED_SYSTEM_ADDRESS); + } + + // get the player + auto* const player = GetActivityPlayer(self); + + if (player != nullptr) { + // Tell the client to get the initial data for showing the top score + RequestActivitySummaryLeaderboardData(self); + + // put the player in if we have to, otherwise start + const auto* const user = GetActivityUser(self); + if (user != nullptr && user->GetObjectID() == player->GetObjectID()) { + GameMessages::ActivityStart activityStart; + activityStart.target = self->GetObjectID(); + activityStart.Send(player->GetSystemAddress()); + } + + self->SetNetworkVar(u"Clear", true); + + DoGameStartup(self); + + if (!state.firstTimeDone) { + // remove the activity cost from the player as they load into the map + TakeActivityCost(self, player->GetObjectID()); + } + + state.firstTimeDone = true; + } + + SpawnNewModel(self); +} + +// -------------------------------------------------------------- +// stopGame: try to stop the game +// -------------------------------------------------------------- +void ShootingGalleryCannon::StopGame(Entity* self, const bool bCanceling) { + auto& state = GetState(self); + self->SetNetworkVar(u"ReSetSuperCharge", true); + self->SetNetworkVar(u"HideSuper", true); + + // get the player + auto* const player = GetActivityPlayer(self); + + if (player == nullptr) return; + + ToggleSuperCharge(self, false); + + // if we have both stop it if we need to, but dont exit + if (!bCanceling) { + // Now retrieve everything from the cannon. We have the score here so we do the rest here too + const auto streak = state.m_maxStreak; + const auto misses = state.m_misses; + const auto fired = state.m_shotsFired; + + // SetActivityUserData 0 / 1 / 2 and UpdateActivityLeaderboard: the leaderboard stores them + const float percentage = ShootingGallery::Logic::GetAccuracy(fired, misses); + SaveScore(self, player->GetObjectID(), static_cast(state.m_totalScore), static_cast(streak), percentage); + + state.Mym_totalScore = state.m_totalScore; + state.m_totalScore = 0; + + state.GameStarted = false; + + ShowSummaryDialog(self, fired, fired - misses, streak); + AwardModels(state.rewards, player); + } + + ActivityStop(self, player, false, bCanceling); + DoGameShutdown(self); + ResetVars(self); +} + +// awardModels +void ShootingGalleryCannon::AwardModels(const std::vector& rewards, Entity* player) { + auto* const inventory = player->GetComponent(); + if (inventory == nullptr) return; + + for (const auto reward : rewards) { + if (reward != LOT_NULL) inventory->AddItem(reward, 1, eLootSourceType::ACTIVITY, eInventoryType::MODELS); + } +} + +// DisplayWaveNumberToPlayer: the wave table {waveNum, waveStr} as wave.waveNum / wave.waveStr +void ShootingGalleryCannon::DisplayWaveNumberToPlayer(Entity* self, const uint32_t waveNum) { + if (GetActivityPlayer(self) == nullptr) return; + self->SetNetworkVar(u"wave.waveNum", waveNum); + self->SetNetworkVar(u"wave.waveStr", static_cast(GetState(self).TIME_LIMIT)); +} + +// showSummaryDialog +void ShootingGalleryCannon::ShowSummaryDialog(Entity* self, const int32_t shots, const int32_t kills, const int32_t streak) { + auto& state = GetState(self); + if (GetActivityPlayer(self) == nullptr) return; + + // The Lua also builds the activity reward's text (GetActivityReward) and sends none of it + const auto rscore = ShootingGallery::Logic::GetRewardsString(state.Mym_totalScore, state.PLAYER_SCORE, shots, kills, streak); + + // Send the activity ID down to the client + self->SetNetworkVar(u"UI_Rewards", GeneralUtils::ASCIIToUTF16(rscore)); + self->SetNetworkVar(u"Audio_Final_Wave_Done", true); + + RequestActivitySummaryLeaderboardData(self); +} + +// RecordPlayerWaveScore +void ShootingGalleryCannon::RecordPlayerWaveScore(Entity* self) { + auto& state = GetState(self); + ShootingGallery::Logic::RecordPlayerWaveScore(state.PLAYER_SCORE, state.m_totalScore, state.ThisWave); +} + +// onDoCalculateActivityRating +uint32_t ShootingGalleryCannon::CalculateActivityRating(Entity* self, const LWOOBJID playerID) { + // also return the score as the result for the activity + return static_cast(std::max(GetState(self).Mym_totalScore, 0)); +} + +// checkSpawn +void ShootingGalleryCannon::CheckSpawn(Entity* self, Entity* target) { + auto& state = GetState(self); + const auto waveNum = state.ThisWave; + if (!state.GameStarted || waveNum == 0) return; + if (!target->HasVar(u"SpawnData")) return; + const auto& spawnData = target->GetVar(u"SpawnData"); + + // spawn the right object + if (spawnData.sdRespawn && target->GetVar(u"wave") == state.ThisWave && waveNum <= state.spawns.size()) { + auto& waveSpawns = state.spawns[waveNum - 1]; + if (spawnData.sdnum >= waveSpawns.size()) return; + waveSpawns[spawnData.sdnum].sdLastPath = spawnData.sdPath; + SpawnObject(spawnData.sdnum, waveSpawns[spawnData.sdnum], self, false); + } +} + +// RemovePlayerFromZone +void ShootingGalleryCannon::RemovePlayerFromZone(Entity* player) { + if (player == nullptr) return; + + // TransferToLastNonInstance{bUseLastPosition = true} + auto* const character = player->GetCharacter(); + auto* const characterComponent = player->GetComponent(); + if (character != nullptr && characterComponent != nullptr) characterComponent->SendToZone(character->GetLastNonInstanceZoneID()); +} + +// -------------------------------------------------------------- +// onRequestActivityExit: User is exiting via cancel +// -------------------------------------------------------------- +void ShootingGalleryCannon::OnRequestActivityExit(Entity* self, const LWOOBJID player, const bool canceled) { + if (canceled) { + StopGame(self, canceled); + RemovePlayerFromZone(Game::entityManager->GetEntity(player)); + } +} + +// -------------------------------------------------------------- +// DoGameStartup: handle all the game startup data +// -------------------------------------------------------------- +void ShootingGalleryCannon::DoGameStartup(Entity* self) { + auto& state = GetState(self); + // set game state and vars + ResetVars(self); + state.GameStarted = true; + self->SetNetworkVar(u"Clear", true); + + // start the first wave + state.ThisWave = 1; + + if (state.FIRST_WAVE_START_TIME < 1) state.FIRST_WAVE_START_TIME = 1; + + ActivityTimerStart(self, SpawnWaveTimer + "1", state.FIRST_WAVE_START_TIME, state.FIRST_WAVE_START_TIME); +} + +// -------------------------------------------------------------- +// onChildLoaded: called when a Child is loaded +// -------------------------------------------------------------- +void ShootingGalleryCannon::OnChildLoaded(Entity* self, Entity* child) { + // look through spawn data to find the most recent data that matches the template + auto* const spawnData = GetLatestSpawnDataByTemplate(self, child->GetLOT()); + if (spawnData == nullptr) return; + auto& state = GetState(self); + + const auto curSpawnNum = ++state.CurSpawnNum; + + // store spawn for use later + state.spawnObject[curSpawnNum] = child->GetObjectID(); + // store who the parent is + child->SetVar(u"My_Parent_ID", self->GetObjectID()); + // store the spawn data in the child + child->SetVar(u"SpawnData", *spawnData); + + // The cannon ball's kills (onUpdateMissionTask); a silent death is none + const auto selfID = self->GetObjectID(); + const auto childID = child->GetObjectID(); + child->AddDieCallback([this, selfID, childID]() { + auto* const cannon = Game::entityManager->GetEntity(selfID); + auto* const target = Game::entityManager->GetEntity(childID); + if (cannon != nullptr && target != nullptr && !SgTarget::DiedSilently(target)) UpdateMissionTaskKill(cannon, target); + }); + + const auto* const path = spawnData->sdPath ? Game::zoneManager->GetZone()->GetPath(*spawnData->sdPath) : nullptr; + if (path == nullptr || path->pathWaypoints.empty()) return; + + if (spawnData->sdMovingPlat) { + // SetPathingSpeed: a moving platform has no handler for it. SetCurrentPath{pathName, startPoint = 0} + if (auto* const movingPlatform = child->GetComponent()) movingPlatform->SetCurrentPath(path->pathName, 0); + } else { + // assign child's waypoint + child->SetVar(u"attached_path", path->pathName); + child->SetVar(u"attached_path_start", 0); + + child->SetPosition(path->pathWaypoints.front().position); + // start child on path + auto* movementAI = child->GetComponent(); + if (movementAI == nullptr) movementAI = child->AddComponent(-1, MovementAIInfo{}); + movementAI->SetHaltDistance(0.0f); + movementAI->SetPath(path->pathWaypoints); + movementAI->SetMaxSpeed(spawnData->sdSpeed); + movementAI->SetCurrentSpeed(spawnData->sdSpeed); + } +} + +// IsValidActor: return if template is a valid actor +bool ShootingGalleryCannon::IsValidActor(const LOT templateID) const { + return std::ranges::find(VALID_ACTORS, templateID) != VALID_ACTORS.end(); +} + +// IsValidEffect: return if template is a valid effect +bool ShootingGalleryCannon::IsValidEffect(const LOT templateID) const { + return std::ranges::find(VALID_EFFECTS, templateID) != VALID_EFFECTS.end(); +} + +// DoGameShutdown: handle all the game shutdown data +void ShootingGalleryCannon::DoGameShutdown(Entity* self) { + GetState(self).GameStarted = false; + + // cancel all timers + ActivityTimerStopAllTimers(self); + + // despawn all spawns + DestroyAllSpawns(self); +} + +// GetRandomPath +std::optional ShootingGalleryCannon::GetRandomPath(Entity* self, const ShootingGallery::Spawn& spawn, const std::optional& lastPath) { + auto& state = GetState(self); + const auto newPath = ShootingGallery::Logic::GetRandomPath(spawn.path, lastPath, state.lastRandomPath, RandomRange); + state.lastRandomPath = newPath; + return newPath; +} + +// SpawnObject: spawn an object for the game +void ShootingGalleryCannon::SpawnObject(const uint32_t num, ShootingGallery::Spawn& spawn, Entity* self, const bool bSpawnNow) { + auto& state = GetState(self); + // get the current spawn number + const auto spawnNum = ++state.SpawnNum; + const auto newPath = GetRandomPath(self, spawn, spawn.sdLastPath); + + // The spawn table keeps this for the rest of the cannon's life + if (!newPath) spawn.bRespawn = false; + + // save the spawn data for the object when it is loaded + ShootingGallery::SpawnData spawnData; + spawnData.sdTemplate = spawn.id; + spawnData.sdRespawn = spawn.bRespawn; + spawnData.sdSpeed = spawn.speed; + spawnData.sdScore = spawn.score; + spawnData.sdPath = newPath; + spawnData.sdnum = num; + spawnData.sdChangeSpeed = spawn.bChangeSpeed; + spawnData.sdSpeedChance = spawn.speedChangeChance; + spawnData.sdMinSpeed = spawn.minSpeed; + spawnData.sdMaxSpeed = spawn.maxSpeed; + spawnData.sdMovingPlat = spawn.bMovingPlatform; + spawnData.sdDespawnTime = spawn.despawnTime; + spawnData.sdTimeScore = spawn.timeScore; + spawnData.bSpawned = false; + + // store the data + state.SPAWN_DATA[spawnNum] = spawnData; + + // set the timer to spawn the object + const auto spawnTime = ShootingGallery::Logic::GetSpawnTime(spawn, bSpawnNow, Random01()); + if (spawnTime) ActivityTimerStart(self, DoSpawnTimer + std::to_string(spawnNum), *spawnTime, *spawnTime); +} + +// DestroyAllSpawns +void ShootingGalleryCannon::DestroyAllSpawns(Entity* self) { + auto& state = GetState(self); + + for (uint32_t spawn = 1; spawn <= state.CurSpawnNum; spawn++) { + const auto itr = state.spawnObject.find(spawn); + if (itr == state.spawnObject.end()) continue; + auto* const spawnObject = Game::entityManager->GetEntity(itr->second); + if (spawnObject == nullptr) continue; + const auto* const destroyable = spawnObject->GetComponent(); + if (destroyable != nullptr && destroyable->GetIsDead()) continue; + + // Die{killerID = spawnObject, killType = "SILENT"} + spawnObject->SetVar(u"SilentDeath", true); + spawnObject->Smash(spawnObject->GetObjectID(), eKillType::SILENT); + } + + // reset vars + state.SpawnNum = 0; + state.CurSpawnNum = 0; + state.spawnObject.clear(); +} + +// GetLatestSpawnDataByTemplate: the newest spawn data not spawned yet that matches the template, or nullptr +ShootingGallery::SpawnData* ShootingGalleryCannon::GetLatestSpawnDataByTemplate(Entity* self, const LOT templateID) { + auto& state = GetState(self); + + for (auto spawnNum = state.SpawnNum; spawnNum > 0; spawnNum--) { + const auto itr = state.SPAWN_DATA.find(spawnNum); + if (itr == state.SPAWN_DATA.end()) continue; + // check spawn flag and template + if (!itr->second.bSpawned && templateID == itr->second.sdTemplate) { + // set spawned flag + itr->second.bSpawned = true; + return &itr->second; + } + } + + return nullptr; +} + +// -------------------------------------------------------------- +// notifyMessageBoxRespond: sent from a player when responding from a messagebox +// -------------------------------------------------------------- +void ShootingGalleryCannon::NotifyMessageBoxRespond(Entity* self, Entity* sender, const int32_t iButton, const std::u16string& identifier) { + // make sure this is the right player + auto* const player = GetActivityPlayer(self); + if (player == nullptr || sender == nullptr || player->GetObjectID() != sender->GetObjectID()) return; + auto* const zoneControl = Game::entityManager->GetZoneControlEntity(); + + if (identifier == u"Scoreboardinfo") { + // show the summary message box + GameMessages::DisplayMessageBox messageBox; + messageBox.target = player->GetObjectID(); + messageBox.bShow = true; + messageBox.imageID = 2; + messageBox.callbackClient = zoneControl != nullptr ? zoneControl->GetObjectID() : LWOOBJID_EMPTY; + messageBox.text = u"Retry?"; + messageBox.identifier = u"Shooting_Gallery_Retry"; + messageBox.Send(player->GetSystemAddress()); + } else { + const bool retry = identifier == u"Shooting_Gallery_Retry" || identifier == u"RePlay"; + // User wants to retry or is closing the big help to start the game (any button 0 is that too) + if ((iButton == 1 && retry) || identifier == u"SG1" || iButton == 0) { + self->SetNetworkVar(u"Clear", true); + StartGame(self); + } else if (iButton == 0 && retry) { // User wants to quit (never reached: button 0 started the game above) + self->RequestActivityExit(self, player->GetObjectID(), false); + RemovePlayerFromZone(player); + } else if (iButton == 1 && identifier == u"Shooting_Gallery_Exit") { + RemovePlayerFromZone(player); + self->RequestActivityExit(self, player->GetObjectID(), true); + } + } +} + +// notifyObjectLoaded +void ShootingGalleryCannon::NotifyObjectLoaded(Entity* self, const LWOOBJID objectID, const LOT templateID) { + auto& state = GetState(self); + if (IsValidActor(templateID)) { + // store the actor + state.ACTORS.push_back(objectID); + } else if (IsValidEffect(templateID)) { // check for effects + state.EFFECTS.push_back(objectID); + } +} + +// onNotifyObject +void ShootingGalleryCannon::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) { + if (name == "FinishedPath" && sender != nullptr) OnTargetFinishedPath(self, sender); +} + +void ShootingGalleryCannon::OnTargetFinishedPath(Entity* self, Entity* target) { + CheckSpawn(self, target); +} + +// notifyActivityStateChangeRequest +void ShootingGalleryCannon::NotifyActivityStateChangeRequest(Entity* self, const int32_t iNumValue1) { + if (iNumValue1 == 1000) { // retry + StartGame(self); + } else if (iNumValue1 == 7777) { // query + RequestActivitySummaryLeaderboardData(self); + } else if (iNumValue1 == 2000) { // exit + auto* const player = GetActivityPlayer(self); + if (player == nullptr) return; + auto* const zoneControl = Game::entityManager->GetZoneControlEntity(); + + // show the summary message box + GameMessages::DisplayMessageBox messageBox; + messageBox.target = player->GetObjectID(); + messageBox.bShow = true; + messageBox.imageID = 1; + messageBox.callbackClient = zoneControl != nullptr ? zoneControl->GetObjectID() : LWOOBJID_EMPTY; + messageBox.text = u"Exit?"; + messageBox.identifier = u"Shooting_Gallery_Exit"; + messageBox.Send(player->GetSystemAddress()); + } else if (iNumValue1 == 1200) { // play + StartGame(self); + } +} diff --git a/dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryCannon.h b/dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryCannon.h new file mode 100644 index 000000000..a503fab89 --- /dev/null +++ b/dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryCannon.h @@ -0,0 +1,144 @@ +#pragma once + +#include "GameMessages.h" +#include "ActivityManager.h" +#include "ShootingGalleryTypes.h" + +#include +#include + +/** + * A shooting gallery cannon: SG_CANNON.lua, line for line. A gallery gives it its zone's constants and its + * targetSettings, and may change what a target at the end of its path does; the rest (waves, spawning, scoring, + * streaks, the super charge, reward models, the end of the game) is shared. Each function names the Lua function it + * comes from. + * + * The Lua's notifications from the zone control (ActivityStateChangeRequest, MessageBoxRespond, ObjectLoaded) come in + * through the Notify* functions, which the gallery's zone script (ShootingGalleryZone) calls. + */ +class ShootingGalleryCannon : public ActivityManager { +public: + // The gallery's zone CONSTANTS + virtual const ShootingGallery::Constants& GetConstants() const = 0; + // targetSettings: the spawn table + virtual ShootingGallery::SpawnTable TargetSettings() const = 0; + + void OnStartup(Entity* self) override; + void OnShootingGalleryFire(Entity& self, GameMessages::ShootingGalleryFire& fire) override; + void OnActivityTimerUpdate(Entity* self, const std::string& name, float_t timeRemaining, float_t elapsedTime) override; + void OnActivityTimerDone(Entity* self, const std::string& name) override; + void OnActivityNotify(Entity* self, GameMessages::ActivityNotify& notify) override; + void OnRequestActivityExit(Entity* self, LWOOBJID player, bool canceled) override; + void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; + + // RequestActivityEnter{bStart = false, userID} (the zone's enterCannon): the activity takes the player, then + // onRequestActivityEnter + void RequestActivityEnter(Entity* self, Entity* player); + // notifyActivityStateChangeRequest (from the zone control) + void NotifyActivityStateChangeRequest(Entity* self, int32_t iNumValue1); + // notifyMessageBoxRespond (from the zone control) + void NotifyMessageBoxRespond(Entity* self, Entity* sender, int32_t iButton, const std::u16string& identifier); + // notifyObjectLoaded (from the zone control) + void NotifyObjectLoaded(Entity* self, LWOOBJID objectID, LOT templateID); + + // onDoCalculateActivityRating: the last game's score + uint32_t CalculateActivityRating(Entity* self, LWOOBJID playerID) override; + + // The cannon's script state: the Lua's script globals (spawns, SPAWN_DATA, LOCALS, PLAYER_SCORE, EFFECTS, + // m_totalScore) and its SetVar vars + struct State { + ShootingGallery::SpawnTable spawns{}; + std::map SPAWN_DATA{}; + std::vector PLAYER_SCORE{}; + std::vector EFFECTS{}; + std::vector ACTORS{}; + int32_t m_totalScore = 0; + // g_const.FIRST_WAVE_START_TIME, which DoGameStartup raises to 1 + float FIRST_WAVE_START_TIME = 0.0f; + + // LOCALS + uint32_t SpawnNum = 0; + uint32_t CurSpawnNum = 0; + uint32_t ThisWave = 0; + bool GameStarted = false; + LWOOBJID activityPlayer = LWOOBJID_EMPTY; + std::map spawnObject{}; + + // self:SetVar + float TIME_LIMIT = 0.0f; + uint32_t ImpactSkillID = 0; + int32_t m_shotsFired = 0; + int32_t m_maxStreak = 0; + int32_t m_misses = 0; + int32_t m_curStreak = 0; + float Current_Super_Charged_Time = 0.0f; + int32_t StreakBonus = 0; + std::optional LastSuperTotal{}; + LOT currentReward = LOT_NULL; + std::vector rewards{ LOT_NULL }; + int32_t Mym_totalScore = 0; + bool Super_Charge_Active = false; + bool Super_Charge_Paused = false; + uint32_t Matrix = 1; + bool bInit = false; + bool WaveStatus = false; + uint32_t ThisWaveVar = 0; + bool Started = false; + bool firstTimeDone = false; + std::vector CannonBallKills{}; + bool friendly_hit = false; + std::optional lastRandomPath{}; + int32_t NumberOfCharges = 0; + }; + State& GetState(const Entity* self); + +protected: + // onNotifyObject: FinishedPath from a target at the end of its path + virtual void OnTargetFinishedPath(Entity* self, Entity* target); + + // checkSpawn: a target that respawns has its next one spawned, while its wave runs + void CheckSpawn(Entity* self, Entity* target); + + // The player in the activity (getActivityUser), or nullptr + Entity* GetActivityUser(const Entity* self) const; + // getObjectByName("activityPlayer") + Entity* GetActivityPlayer(Entity* self); + +private: + void ResetVars(Entity* self); + void PlaySceneAnimation(Entity* self, const std::string& anim, bool bPlayCannon, bool bPlayPlayer, bool bMustPlay = false); + void PlaySceneEffect(Entity* self, const std::u16string& effectName); + void ToggleSuperCharge(Entity* self, bool enable); + void TimerToggle(Entity* self, bool bStart = false); + void PauseChargeCannon(Entity* self); + void StartChargedCannon(Entity* self, std::optional optionalTime = std::nullopt); + void UpdateStreak(Entity* self); + void RegisterHit(Entity* self, Entity* target, LOT shotType); + void UpdateMissionTaskKill(Entity* self, Entity* target); + void SpawnNewModel(Entity* self); + void StartGame(Entity* self); + void StopGame(Entity* self, bool bCanceling); + void AwardModels(const std::vector& rewards, Entity* player); + void DisplayWaveNumberToPlayer(Entity* self, uint32_t waveNum); + void ShowSummaryDialog(Entity* self, int32_t shots, int32_t kills, int32_t streak); + void RecordPlayerWaveScore(Entity* self); + static void RemovePlayerFromZone(Entity* player); + void DoGameStartup(Entity* self); + void OnChildLoaded(Entity* self, Entity* child); + bool IsValidActor(LOT templateID) const; + bool IsValidEffect(LOT templateID) const; + void DoGameShutdown(Entity* self); + std::optional GetRandomPath(Entity* self, const ShootingGallery::Spawn& spawn, const std::optional& lastPath); + void SpawnObject(uint32_t num, ShootingGallery::Spawn& spawn, Entity* self, bool bSpawnNow); + void DestroyAllSpawns(Entity* self); + ShootingGallery::SpawnData* GetLatestSpawnDataByTemplate(Entity* self, LOT templateID); + void DoSpawn(Entity* self, uint32_t spawnNum); + + // The engine side of a few of the Lua's messages + void SetShootingGalleryParams(Entity* self, float cooldown, float timeLimit); + void RequestActivitySummaryLeaderboardData(Entity* self); + void ActivityStop(Entity* self, Entity* player, bool bExit, bool bUserCanceled); + void ActivityPause(Entity* self, Entity* player, bool bPause); + + std::map m_States{}; +}; diff --git a/dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryZone.cpp b/dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryZone.cpp new file mode 100644 index 000000000..6c61dd5d5 --- /dev/null +++ b/dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryZone.cpp @@ -0,0 +1,97 @@ +#include "ShootingGalleryZone.h" + +#include "ShootingGalleryCannon.h" + +#include "CombatMessages.h" +#include "Entity.h" +#include "EntityManager.h" +#include "GameMessages.h" +#include "eStateChangeType.h" + +void ShootingGalleryZone::OnStartup(Entity* self) { + // onObjectLoaded: ObjectLoaded is a message objects send the zone control + self->RegisterMsg(MessageType::Game::OBJECT_LOADED, [this, self](GameMessages::GameMsg& msg) { return OnObjectLoaded(self, msg); }); + // SetVar("CONSTANTS") and SetVar("timelimit"): the cannon takes the same constants (GetConstants) +} + +Entity* ShootingGalleryZone::GetCannon(Entity* self) { + return Game::entityManager->GetEntity(GetState(self).cannonObject); +} + +ShootingGalleryCannon* ShootingGalleryZone::GetCannonScript(Entity* self) { + auto* const cannon = GetCannon(self); + return cannon != nullptr ? dynamic_cast(cannon->GetScript()) : nullptr; +} + +// -------------------------------------------------------------- +// enterCannon: put the player in the cannon, does not start the cannon +// -------------------------------------------------------------- +void ShootingGalleryZone::EnterCannon(Entity* self) { + auto& state = GetState(self); + if (state.bLoaded) return; + + // get the cannon and the player + auto* const cannon = GetCannon(self); + auto* const player = Game::entityManager->GetEntity(state.activityPlayer); + + if (cannon == nullptr || player == nullptr) return; + + // if we have both start it + FreezePlayer(player, true); + state.bLoaded = true; + if (auto* const cannonScript = GetCannonScript(self)) cannonScript->RequestActivityEnter(cannon, player); +} + +// freezePlayer +void ShootingGalleryZone::FreezePlayer(Entity* player, const bool bFreeze) { + GameMessages::SetStunned stun; + stun.target = player->GetObjectID(); + stun.StateChangeType = bFreeze ? eStateChangeType::PUSH : eStateChangeType::POP; + stun.bCantMove = true; + stun.bCantAttack = true; + stun.bCantInteract = true; + stun.Send(player->GetSystemAddress()); +} + +// -------------------------------------------------------------- +// mainPlayerLoaded: called when Player Loads into Zone +// -------------------------------------------------------------- +void ShootingGalleryZone::OnPlayerLoaded(Entity* self, Entity* player) { + // CancelMission{missionID = 30}: there is no mission 30 + GetState(self).activityPlayer = player->GetObjectID(); +} + +// onObjectLoaded, then the cannon's notifyObjectLoaded +bool ShootingGalleryZone::OnObjectLoaded(Entity* self, GameMessages::GameMsg& msg) { + const auto& objectLoaded = static_cast(msg); + MainObjectLoaded(self, objectLoaded.objectID, objectLoaded.lot); + auto* const cannon = GetCannon(self); + if (auto* const cannonScript = GetCannonScript(self)) cannonScript->NotifyObjectLoaded(cannon, objectLoaded.objectID, objectLoaded.lot); + return true; +} + +void ShootingGalleryZone::MainObjectLoaded(Entity* self, const LWOOBJID objectID, const LOT templateID) { + // Cannon Object Loaded + if (templateID == GetConstants().CANNON_TEMPLATEID) { + // store the cannon object for use later + GetState(self).cannonObject = objectID; + // try to put the player in the cannon + EnterCannon(self); + } +} + +// onActivityStateChangeRequest, then the cannon's notifyActivityStateChangeRequest +void ShootingGalleryZone::OnActivityStateChangeRequest(Entity* self, const LWOOBJID senderID, const int32_t value1, const int32_t value2, const std::u16string& stringValue) { + if (stringValue == u"clientready") { + // put the player in the cannon + EnterCannon(self); + } + auto* const cannon = GetCannon(self); + if (auto* const cannonScript = GetCannonScript(self)) cannonScript->NotifyActivityStateChangeRequest(cannon, value1); +} + +// The cannon's notifyMessageBoxRespond +void ShootingGalleryZone::OnMessageBoxResponse(Entity* self, Entity* sender, const int32_t button, const std::u16string& identifier, const std::u16string& userData) { + auto* const cannon = GetCannon(self); + if (auto* const cannonScript = GetCannonScript(self)) cannonScript->NotifyMessageBoxRespond(cannon, sender, button, identifier); +} diff --git a/dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryZone.h b/dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryZone.h new file mode 100644 index 000000000..1586e034f --- /dev/null +++ b/dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryZone.h @@ -0,0 +1,46 @@ +#pragma once + +#include "CppScripts.h" +#include "ShootingGalleryTypes.h" + +#include + +class ShootingGalleryCannon; + +/** + * A shooting gallery's zone control: L_GF_SG.lua (every gallery's zone script includes it). It puts the player in + * the cannon once both are loaded, and passes on to the cannon what the cannon asked to be told + * (SendLuaNotificationRequest: ActivityStateChangeRequest, MessageBoxRespond, ObjectLoaded). + */ +class ShootingGalleryZone : public CppScripts::Script { +public: + // The gallery's zone CONSTANTS + virtual const ShootingGallery::Constants& GetConstants() const = 0; + + void OnStartup(Entity* self) override; + void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int32_t value1, int32_t value2, const std::u16string& stringValue) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; + + struct State { + LWOOBJID cannonObject = LWOOBJID_EMPTY; + LWOOBJID activityPlayer = LWOOBJID_EMPTY; + bool bLoaded = false; + }; + State& GetState(const Entity* self) { return m_States[self->GetObjectID()]; } + +protected: + // The stored cannon and its script, or nullptr + Entity* GetCannon(Entity* self); + ShootingGalleryCannon* GetCannonScript(Entity* self); + + // mainObjectLoaded: sent from an object after loading into zone + virtual void MainObjectLoaded(Entity* self, LWOOBJID objectID, LOT templateID); + +private: + void EnterCannon(Entity* self); + static void FreezePlayer(Entity* player, bool bFreeze); + bool OnObjectLoaded(Entity* self, GameMessages::GameMsg& msg); + + std::map m_States{}; +}; diff --git a/tests/dGameTests/dComponentsTests/MovingPlatformComponentTests.cpp b/tests/dGameTests/dComponentsTests/MovingPlatformComponentTests.cpp index 4a07fb191..f17f33422 100644 --- a/tests/dGameTests/dComponentsTests/MovingPlatformComponentTests.cpp +++ b/tests/dGameTests/dComponentsTests/MovingPlatformComponentTests.cpp @@ -16,7 +16,7 @@ #include "MovementMessages.h" #include "MovingPlatformComponent.h" #include "02_server/Map/General/SimpleOnceOnlyMoverSpinnerEvent.h" -#include "ai/MINIGAME/SG_GF/SERVER/SGCannon.h" +#include "ai/MINIGAME/ShootingGallery/ShootingGalleryTypes.h" #include "ai/MINIGAME/SG_GF/SERVER/SgTarget.h" #include "ScriptComponent.h" #include "ScriptedActivityComponent.h" @@ -1241,14 +1241,14 @@ TEST_F(MovingPlatformComponentTest, ShootingGalleryTargetAtTheEndOfItsPath) { path.pathWaypoints = { first, second }; const_cast(Game::zoneManager->GetZone())->AddPath(path); - SGEnemy spawnData{}; - spawnData.score = 1500; - spawnData.isMovingPlatform = true; - spawnData.despawnOnLastWaypoint = true; + ShootingGallery::SpawnData spawnData{}; + spawnData.sdScore = 1500; + spawnData.sdMovingPlat = true; + spawnData.sdDespawnTime = true; info.settings.Insert(u"attached_path", "TestTargetPath"); Entity entity(288300744895900134, info); info.settings.values.clear(); - entity.SetVar(u"SpawnData", spawnData); + entity.SetVar(u"SpawnData", spawnData); SgTarget script; EXPECT_EQ(SgTarget::GetActivityPoints(&entity), 1500); @@ -1285,7 +1285,7 @@ TEST_F(MovingPlatformComponentTest, ShootingGalleryTargetPlayAimAction) { info.settings.Insert(u"attached_path", "TestAimPath"); Entity entity(288300744895900140, info); info.settings.values.clear(); - entity.SetVar(u"SpawnData", SGEnemy{}); + entity.SetVar(u"SpawnData", ShootingGallery::SpawnData{}); SgTarget script; script.OnWaypointReached(&entity, 0); entity.Update(0.0f); @@ -1310,9 +1310,9 @@ TEST_F(MovingPlatformComponentTest, ShootingGalleryTargetChangeSpeedTimer) { // control's activity user (none here: no zone control) TEST_F(MovingPlatformComponentTest, ShootingGalleryTargetWritesItsTimeScore) { Entity entity(288300744895900142, info); - SGEnemy spawnData{}; - spawnData.score = 500; - entity.SetVar(u"SpawnData", spawnData); + ShootingGallery::SpawnData spawnData{}; + spawnData.sdScore = 500; + entity.SetVar(u"SpawnData", spawnData); auto* const activity = entity.AddComponent(-1); EXPECT_EQ(SgTarget::GetActivityPoints(&entity), 500); EXPECT_FLOAT_EQ(activity->GetActivityValue(LWOOBJID_EMPTY, 5), 500.0f);