Merge exp/platforms-6: moving platforms round 6

Mover turns with a stopped rotator, Departed script hook, arrivals at
waypoints in one place as the client, GF shooting gallery target script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Aaron Kimbrell
2026-11-27 17:47:21 -06:00
12 changed files with 509 additions and 88 deletions

View File

@@ -167,6 +167,12 @@ namespace {
}
}
// The client's platform takes away both of its object's velocities
void MovingPlatformComponent::ResetVelocities(PlatformSubComponent& platform) {
platform.mVelocity = NiPoint3Constant::ZERO;
m_AngularVelocity = NiPoint3Constant::ZERO;
}
// The level config: the path, a simple mover's settings, and where and whether each platform starts
void MovingPlatformComponent::LoadConfigData() {
const auto pathName = GeneralUtils::UTF16ToWTF8(m_PathName);
@@ -416,7 +422,7 @@ void MovingPlatformComponent::PlatformGotoWaypoint(PlatformSubComponent& platfor
platform.mShouldStopAtDesiredWaypoint = false;
if (stopAtWaypoint) {
StopTravelling(platform);
platform.mVelocity = NiPoint3Constant::ZERO;
ResetVelocities(platform);
}
FireArrivalHooks(index, true, index == waypoints.size() - 1);
return;
@@ -515,20 +521,21 @@ void MovingPlatformComponent::PlatformStop(PlatformSubComponent& platform) {
return;
}
StopTravelling(platform);
platform.mVelocity = NiPoint3Constant::ZERO;
ResetVelocities(platform);
SerializePlatform(platform);
return;
}
if (platform.GetType() == eMoverSubComponentType::rotater) {
// No longer spinning
StopTravelling(platform);
m_AngularVelocity = NiPoint3Constant::ZERO;
Game::entityManager->SerializeEntity(m_Parent);
return;
}
if (platform.mPath == nullptr) return;
// Stopped where it is (the client stops on the stopped bit, 4)
StopTravelling(platform);
platform.mVelocity = NiPoint3Constant::ZERO;
ResetVelocities(platform);
platform.mDesiredWaypointIndex = -1;
platform.mShouldStopAtDesiredWaypoint = false;
Game::entityManager->SerializeEntity(m_Parent);
@@ -595,7 +602,7 @@ void MovingPlatformComponent::PlatformSetWaitingTime(PlatformSubComponent& platf
// Only at an end of the path, or stopped, does the object lose its velocities here. Waiting at a waypoint in between
// it keeps them: live's platforms went on as they came for the wait (the GF shooting gallery subs 2 units past each
// waypoint, the FV dragons 5.33; a dragon met 2.2 s into a 5 s wait was 88 past its waypoint).
if ((platform.mState & (ReachedFinalDestination | Stopped)) != 0) platform.mVelocity = NiPoint3Constant::ZERO;
if ((platform.mState & (ReachedFinalDestination | Stopped)) != 0) ResetVelocities(platform);
}
// The velocity towards the next waypoint at the speed for where the platform is; setting off drops the two "reached"
@@ -611,6 +618,9 @@ void MovingPlatformComponent::PlatformUpdateVelocities(PlatformSubComponent& pla
if (platform.mTimeBased) speed = platform.mCurrentSpeed > 0.0f ? distance / platform.mCurrentSpeed : 0.0f;
else speed = platform.mCurrentSpeed + (platform.mNextSpeed - platform.mCurrentSpeed) * platform.mPercentBetweenPoints;
platform.mVelocity = direction * speed;
// The object turns at its angular velocity only where it has a rotator on a path; else it is turned between the
// two waypoints' rotations as it goes (MoveObject)
if (platform.GetType() != eMoverSubComponentType::rotater && HasRotatorOnPath()) PlatformSetAngularVelocity(platform);
platform.mState &= MovementMask;
}
@@ -631,9 +641,6 @@ void MovingPlatformComponent::PlatformResumeTravelling(PlatformSubComponent& pla
// run once turns it round. It stops there if it was sent there to stop or turned at the end of a path run once; else
// it travels on, after the waypoint's wait. False when a script told of it put the platform on another path.
bool MovingPlatformComponent::PlatformArrivedAtWaypoint(PlatformSubComponent& platform) {
// A platform with nowhere to go (one waypoint, or at the end of a path run once) is not arriving
if (platform.mCurrentWaypointIndex == platform.mNextWaypointIndex) return true;
const auto& waypoints = platform.mPath->pathWaypoints;
const auto& next = waypoints[platform.mNextWaypointIndex].position;
bool closeEnough{};
@@ -648,6 +655,12 @@ bool MovingPlatformComponent::PlatformArrivedAtWaypoint(PlatformSubComponent& pl
}
if (!closeEnough) return true;
// What the clients were last sent, to know whether an arrival while waiting changes it
const auto sentState = platform.mState;
const auto sentCurrent = platform.mCurrentWaypointIndex;
const auto sentNext = platform.mNextWaypointIndex;
const bool sentReverse = platform.mInReverse;
const auto arrived = platform.mNextWaypointIndex;
const bool atLastWaypoint = arrived == static_cast<uint32_t>(waypoints.size() - 1);
bool atDesiredWaypoint = false;
@@ -670,13 +683,19 @@ bool MovingPlatformComponent::PlatformArrivedAtWaypoint(PlatformSubComponent& pl
}
if (stopAtDesiredWaypoint || turnedAtEnd) {
StopTravelling(platform);
platform.mVelocity = NiPoint3Constant::ZERO;
ResetVelocities(platform);
} else {
StartTravelling(platform);
}
PlatformProcessStateChange(platform, arrived);
MoveObject(platform, true);
if (!PlatformHandleWaypointArrived(platform, arrived, atDesiredWaypoint, atLastWaypoint)) return false;
// Live serialized a platform that waits at the waypoint it arrived at (it leaves again), not one that stopped there.
// A platform kept at one waypoint by its path (a path of one waypoint) arrives every frame of its wait without
// anything to send.
const bool unchanged = (sentState & Waiting) != 0 && platform.mState == sentState && platform.mCurrentWaypointIndex == sentCurrent
&& platform.mNextWaypointIndex == sentNext && platform.mInReverse == sentReverse;
if ((platform.mState & Stopped) == 0 && !unchanged) SerializePlatform(platform);
// A simple mover sent elsewhere on its way (it cannot turn between its ends) sets off from where it stopped
if (IsSimpleMover(platform) && (platform.mState & Stopped) != 0 && platform.mDesiredWaypointIndex >= 0
@@ -697,8 +716,6 @@ bool MovingPlatformComponent::PlatformHandleWaypointArrived(PlatformSubComponent
StartWaiting(platform);
PlatformSetWaitingTime(platform, platform.mWaitTime, 0.0f);
}
// Live serialized a platform that waits at the waypoint it arrived at (it leaves again), not one that stopped there
if ((platform.mState & Stopped) == 0) SerializePlatform(platform);
return true;
}
@@ -782,51 +799,114 @@ NiPoint3 CalcRotatorAngularVelocity(const float rotX, const float rotY, const fl
q[k] = (m[k][i] + m[i][k]) * root;
}
// The velocity that turns from one rotation to another in a time: the rotation from the first to the
// second (the rotation itself, or its inverse in reverse), normalized; without an axis there is no velocity; else
// the axis (the other way for a negative w) times twice the arc cosine of |w| over the time
if (reverse) {
q[0] = -q[0];
q[1] = -q[1];
q[2] = -q[2];
}
const float length = std::sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]);
if (length <= 0.0f || rate == 0.0f) return NiPoint3Constant::ZERO;
for (auto& part : q) part /= length;
const float axisLength = std::sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2]);
// From no rotation to it (from it to none in reverse) in half the rate
const NiQuaternion rotation(q[3], q[0], q[1], q[2]);
if (rate == 0.0f) return NiPoint3Constant::ZERO;
const float time = rate * 0.5f;
return reverse ? CalcAngularVelocity(rotation, QuatUtils::IDENTITY, time) : CalcAngularVelocity(QuatUtils::IDENTITY, rotation, time);
}
// The rotation from the first to the second (the second times the inverse of the first), normalized; without an axis
// there is no velocity; else the axis (the other way for a negative w) times twice the arc cosine of |w| over the time
NiPoint3 CalcAngularVelocity(const NiQuaternion& from, const NiQuaternion& to, const float time) {
if (!(time > 0.0f)) return NiPoint3Constant::ZERO;
auto diff = to * glm::inverse(from);
const float length = std::sqrt(diff.x * diff.x + diff.y * diff.y + diff.z * diff.z + diff.w * diff.w);
if (!(length > 0.0f)) return NiPoint3Constant::ZERO;
diff = NiQuaternion(diff.w / length, diff.x / length, diff.y / length, diff.z / length);
const float axisLength = std::sqrt(diff.x * diff.x + diff.y * diff.y + diff.z * diff.z);
if (!(axisLength > std::numeric_limits<float>::epsilon())) return NiPoint3Constant::ZERO;
const float angle = 2.0f * std::acos(std::min(std::abs(q[3]), 1.0f));
const float scale = (q[3] < 0.0f ? -1.0f : 1.0f) / axisLength * angle * (1.0f / (rate * 0.5f));
return NiPoint3(q[0] * scale, q[1] * scale, q[2] * scale);
const float angle = 2.0f * std::acos(std::min(std::abs(diff.w), 1.0f));
const float scale = (diff.w < 0.0f ? -1.0f : 1.0f) / axisLength * angle * (1.0f / time);
return NiPoint3(diff.x * scale, diff.y * scale, diff.z * scale);
}
// Even acceleration from one speed to the other over the way; the time at that acceleration, or the way over the
// speed without one
float CalcPlatformTravelTime(const NiPoint3& start, const NiPoint3& end, const float startSpeed, const float endSpeed) {
constexpr float minDistance = 0.00001f;
const float distance = Vector3::Distance(start, end);
if (distance < minDistance) return 0.0f;
float acceleration = 0.0f;
if (startSpeed != endSpeed) acceleration = static_cast<float>((endSpeed * endSpeed - startSpeed * startSpeed) / (distance * 2.0));
if (acceleration != 0.0f) {
const double root = std::sqrt(startSpeed * startSpeed + acceleration * 2.0 * distance);
return static_cast<float>(-startSpeed + root) / acceleration;
}
return startSpeed == 0.0f ? 0.0f : distance / startSpeed;
}
// A rotator's wait never ends and it never arrives; it has no linear velocity. The client's physics turn the object at
// the rotator's angular velocity; the server turns its object here, without a serialization of its physics, as a
// mover's.
// its angular velocity, which a rotator that has not stopped puts back to its own whenever it differs (so a mover on
// the same object only turns it while the rotator is stopped). The server turns its object in TurnObject, without a
// serialization of its physics, as a mover's.
void MovingPlatformComponent::RunRotator(RotatorSubComponent& rotator, const float deltaTime) {
if (rotator.mPath == nullptr) return;
// It turns the object where the object is: a mover on the same object may have moved it
auto position = m_Parent->GetPosition();
auto rotation = m_Parent->GetRotation();
bool moved = false;
if (!rotator.mPlaced) {
// The object is put at its waypoint when the rotator is set up on its path
rotator.mPlaced = true;
position = rotator.mPosition;
rotation = rotator.mPath->pathWaypoints[rotator.mCurrentWaypointIndex].rotation;
moved = true;
SetObjectTransform(rotator.mPosition, rotator.mPath->pathWaypoints[rotator.mCurrentWaypointIndex].rotation);
}
if (rotator.mActive && (rotator.mState & Travelling) != 0) {
const auto velocity = rotator.GetAngularVelocity();
const float speed = velocity.Length();
if (speed > 0.0f && std::isfinite(speed)) {
const glm::vec3 axis(velocity.x / speed, velocity.y / speed, velocity.z / speed);
rotation = glm::normalize(glm::angleAxis(speed * deltaTime, axis) * rotation);
moved = true;
// An open quick build's platforms do not turn it
if (!rotator.mActive) m_AngularVelocity = NiPoint3Constant::ZERO;
else if (rotator.mState != 0 && (rotator.mState & Stopped) == 0) m_AngularVelocity = rotator.GetAngularVelocity();
}
bool MovingPlatformComponent::HasRotatorOnPath() const {
const auto* const rotator = GetSubComponent(eMoverSubComponentType::rotater);
return rotator != nullptr && rotator->mPath != nullptr;
}
void MovingPlatformComponent::TurnObject(const float deltaTime) {
const float speed = m_AngularVelocity.Length();
if (!(speed > 0.0f) || !std::isfinite(speed)) return;
const glm::vec3 axis(m_AngularVelocity.x / speed, m_AngularVelocity.y / speed, m_AngularVelocity.z / speed);
SetObjectTransform(m_Parent->GetPosition(), glm::normalize(glm::angleAxis(speed * deltaTime, axis) * m_Parent->GetRotation()));
}
// The client's mover sets off (and, between waypoints of different speeds, goes on) turned towards the next
// waypoint's rotation: at a waypoint from that waypoint's rotation; between two from the rotation for how far it is
// (or its own, when that is within 8 degrees of it, then timed from where it is at the speed for there), at the
// angular velocity that gets it there with the next waypoint. With both waypoints in one rotation it is put in it and
// does not turn.
void MovingPlatformComponent::PlatformSetAngularVelocity(PlatformSubComponent& platform) {
constexpr float closeAngle = 0.13962634f;
constexpr float minStretchSquared = 0.00001f;
const auto& waypoints = platform.mPath->pathWaypoints;
const auto& currentRotation = waypoints[platform.mCurrentWaypointIndex].rotation;
const auto& nextRotation = waypoints[platform.mNextWaypointIndex].rotation;
if (currentRotation == nextRotation) {
SetObjectTransform(platform.mPosition, currentRotation);
m_AngularVelocity = NiPoint3Constant::ZERO;
return;
}
bool closeToRotation = false;
auto rotation = currentRotation;
if ((platform.mState & ReachedDesiredWaypoint) == 0) {
rotation = glm::slerp(currentRotation, nextRotation, platform.mPercentBetweenPoints);
const auto current = m_Parent->GetRotation();
const float dot = std::abs(glm::dot(rotation, current));
if (std::acos(std::min(dot, 1.0f)) < closeAngle) {
closeToRotation = true;
rotation = current;
}
}
if (moved) SetObjectTransform(position, rotation);
if (!closeToRotation) SetObjectTransform(platform.mPosition, rotation);
float time = platform.mTimeBased ? platform.mCurrentSpeed - platform.mMoveTimeElapsed : 0.0f;
if (!platform.mTimeBased) {
auto start = waypoints[platform.mCurrentWaypointIndex].position;
auto startSpeed = platform.mCurrentSpeed;
if (closeToRotation) {
start = platform.mPosition;
startSpeed = platform.mCurrentSpeed + (platform.mNextSpeed - platform.mCurrentSpeed) * platform.mPercentBetweenPoints;
}
const auto& end = waypoints[platform.mNextWaypointIndex].position;
if ((start - end).SquaredLength() > minStretchSquared) time = CalcPlatformTravelTime(start, end, startSpeed, platform.mNextSpeed);
}
if (time > 0.0f) m_AngularVelocity = CalcAngularVelocity(rotation, nextRotation, time);
}
// A platform on its path. The client's is moved by its physics, at the velocity the platform gives its object; the
@@ -835,7 +915,7 @@ bool MovingPlatformComponent::RunPlatform(PlatformSubComponent& platform, const
if (platform.mPath == nullptr) return true;
if (!platform.mActive) {
// An open quick build's platform loses its velocities
platform.mVelocity = NiPoint3Constant::ZERO;
ResetVelocities(platform);
return true;
}
if (platform.mState == 0) return true;
@@ -869,15 +949,18 @@ bool MovingPlatformComponent::RunPlatform(PlatformSubComponent& platform, const
}
if (doneWaiting) {
StartTravelling(platform);
} else if (!stopped && (travelling || platform.mSegmentLength > 0.0f)) {
} else if (!stopped) {
// A platform that has not stopped looks whether it arrived, also while it waits. Live's FV dragons, going on as
// they came through the 5 s wait at their waypoint 4, were at waypoint 5 (waiting there, then going on in the
// direction they came to 4 in) without ever having left 4. Where two waypoints are in one place the client
// arrives every frame of the wait; here only a travelling one arrives there.
// direction they came to 4 in) without ever having left 4. Where the next waypoint is in the same place (two
// waypoints in one place, a path of one waypoint) it is there at once: it arrives in the first frame of the
// wait, and on a path that keeps it there, every frame, as the client's.
if (!PlatformArrivedAtWaypoint(platform)) return false;
}
if ((platform.mState & Travelling) != 0 && (doneWaiting || platform.mCurrentSpeed != platform.mNextSpeed)) {
// The client's platform sends Departed as it leaves a waypoint it waited at
if (doneWaiting && !FireDeparted(platform.mCurrentWaypointIndex)) return false;
PlatformUpdateVelocities(platform);
// Live serialized a platform leaving its waypoint, where it then was: as far past the waypoint as the wait took it
if (doneWaiting) SerializePlatform(platform);
@@ -898,6 +981,7 @@ void MovingPlatformComponent::Run(const float deltaTime) {
// A script told of an arrival may have put the platforms on another path
if (generation != m_SetupGeneration) return;
}
if (HasRotatorOnPath()) TurnObject(deltaTime);
}
// What live answered a client's request with: the state of the platform (a mover's, a simple mover's on its own path,
@@ -954,7 +1038,7 @@ void MovingPlatformComponent::PlatformWarpToWaypoint(PlatformSubComponent& platf
PlatformProcessStateChange(platform, static_cast<uint32_t>(index));
const bool atEnd = index == 0 || index == waypoints.size() - 1;
platform.mState = Stopped | ReachedDesiredWaypoint | (atEnd ? ReachedFinalDestination : 0);
platform.mVelocity = NiPoint3Constant::ZERO;
ResetVelocities(platform);
m_Parent->SetPosition(waypoints[index].position);
m_Parent->SetRotation(waypoints[index].rotation);
@@ -999,6 +1083,12 @@ void MovingPlatformComponent::FireArrivalHooks(const uint32_t index, const bool
}
}
bool MovingPlatformComponent::FireDeparted(const uint32_t index) {
const auto generation = m_SetupGeneration;
m_Parent->GetScript()->OnDeparted(m_Parent, index);
return generation == m_SetupGeneration;
}
void MovingPlatformComponent::AddPlatformAtLastWaypointCallback(const std::function<void()>& callback) {
m_AtLastWaypointCallbacks.push_back(callback);
}

View File

@@ -144,6 +144,19 @@ public:
*/
NiPoint3 CalcRotatorAngularVelocity(float rotX, float rotY, float rotZ, float rate, bool reverse);
/**
* The angular velocity that turns from one rotation to another in a time, as the client's physics work it out: the
* rotation from the first to the second, normalized, by the shortest way (at most half a turn). None without an axis
* (the same rotation, or whole turns) or without time.
*/
NiPoint3 CalcAngularVelocity(const NiQuaternion& from, const NiQuaternion& to, float time);
/**
* The time to go from start to end, speeding up or slowing down evenly from startSpeed to endSpeed, as the client
* works it out (none for a way under 0.00001 or without speed)
*/
float CalcPlatformTravelTime(const NiPoint3& start, const NiPoint3& end, float startSpeed, float endSpeed);
/**
* A rotator (6), as the client's: on its path it does not move, it turns at its angular velocity while travelling
* (rotX/rotY/rotZ in half turns, at rate), and never waits or arrives; it sends the data a mover sends.
@@ -395,6 +408,22 @@ private:
void RunRotator(RotatorSubComponent& rotator, float deltaTime);
// Whether the platforms of a quick build run yet
void UpdateActive();
// Whether the object has a rotator on a path: then the object turns at its angular velocity
bool HasRotatorOnPath() const;
// A mover's turn towards its next waypoint's rotation, as the client's mover gives it when it sets off: put in the
// rotation for where it is (the waypoint's at a waypoint, else between the two unless it is within 8 degrees of
// that), and the angular velocity that gets it to the next waypoint's rotation as it gets there
void PlatformSetAngularVelocity(PlatformSubComponent& platform);
// Turns the object by its angular velocity
void TurnObject(float deltaTime);
// Takes away the object's linear and angular velocities
void ResetVelocities(PlatformSubComponent& platform);
// Tells the scripts the platform leaves a waypoint after waiting there; false when one put it on another path
bool FireDeparted(uint32_t index);
// The object's angular velocity (world), only used while it has a rotator on a path: the mover's turn towards the
// next waypoint's rotation, or the rotator's, which puts its own back whenever it is turning
NiPoint3 m_AngularVelocity{};
public:
void Run(float deltaTime) override;
@@ -405,6 +434,9 @@ public:
// Whether the platform has a mover on a path
bool IsMover() const;
// The object's angular velocity while it has a rotator on a path
const NiPoint3& GetAngularVelocity() const { return m_AngularVelocity; }
// Whether the platform follows a path (its attached_path); a simple mover without one has no waypoints
bool HasPath() const { return m_Path != nullptr; }

View File

@@ -40,7 +40,7 @@ void ScriptComponent::LoadDataFromTemplate() {
m_ClientScriptName = row.client_script_name;
}
// custom_script_server replaces a missing server script; a client script (the row's or custom_script_client, or
// custom_script_server replaces a missing (or empty) server script; a client script (the row's or custom_script_client, or
// any object's without a server script) makes it a client script component
void ScriptComponent::LoadConfigData() {
if (!m_FromObject) return;
@@ -50,7 +50,9 @@ void ScriptComponent::LoadConfigData() {
const auto customScriptServer = m_Parent->GetVarAsString(u"custom_script_server");
if (!m_Parent->GetVarAsString(u"custom_script_client").empty()) client = true;
if (!customScriptServer.empty() && m_ScriptName.empty()) m_ScriptName = customScriptServer;
// The client's script component takes a custom script over its row's; here it replaces the row's only where that is
// the empty script (the GF shooting gallery targets: the cannon gives them SG_TARGET.lua)
if (!customScriptServer.empty() && (m_ScriptName.empty() || m_ScriptName == "scripts\\empty.lua")) m_ScriptName = customScriptServer;
m_Client = client && m_ScriptName.empty();
SetScript(m_ScriptName);

View File

@@ -58,6 +58,11 @@ public:
*/
void SetScript(const std::string& scriptName);
/**
* Sets the script itself (it is not owned: scripts are shared singletons)
*/
void SetScript(CppScripts::Script* const script) { m_Script = script; }
bool OnGetObjectReportInfo(GameMessages::GetObjectReportInfo& reportInfo);
// Registers a message from a script to be listened for on the parent object

View File

@@ -129,6 +129,7 @@
// SG Scripts
#include "SGCannon.h"
#include "SgTarget.h"
#include "ZoneSGServer.h"
// FV Scripts
@@ -529,6 +530,8 @@ namespace {
//SG
{"scripts\\ai\\MINIGAME\\SG_GF\\SERVER\\SG_CANNON.lua", []() {return new SGCannon();}},
// The cannon gives its targets this one, with forward slashes
{"scripts/ai/ACT/SG_TARGET.lua", []() {return new SgTarget();}},
{"scripts\\ai\\MINIGAME\\SG_GF\\L_ZONE_SG_SERVER.lua", []() {return new ZoneSGServer();}},
//PR

View File

@@ -307,6 +307,14 @@ namespace CppScripts {
*/
virtual void OnPlatformAtLastWaypoint(Entity* self) {};
/**
* Invoked when a moving platform leaves a waypoint after waiting there (the Departed message, path type
* "movingPlatform"), with the waypoint it leaves.
*
* Equivalent to 'function onDeparted(self, msg)'
*/
virtual void OnDeparted(Entity* self, uint32_t waypointIndex) {};
/**
* Invoked when a player fired a skill event on self.
*

View File

@@ -1,3 +1,4 @@
set(DSCRIPTS_SOURCES_AI_MINIGAME_SG_GF_SERVER
"SGCannon.cpp"
"SgTarget.cpp"
PARENT_SCOPE)

View File

@@ -1,4 +1,5 @@
#include "SGCannon.h"
#include "SgTarget.h"
#include "EntityManager.h"
#include "GameMessages.h"
#include "EffectsMessages.h"
@@ -287,7 +288,7 @@ void SGCannon::DoSpawnTimerFunc(Entity* self, const std::string& name) {
info.pos = path->pathWaypoints[0].position;
info.settings.Insert<SGEnemy>(u"SpawnData", toSpawn);
info.settings.Insert<std::string>(u"custom_script_server", "scripts/ai/ACT/SG_TARGET.lua"); // never loaded (the targets have a script row): TargetFinishedPath does its part
info.settings.Insert<std::string>(u"custom_script_server", "scripts/ai/ACT/SG_TARGET.lua");
info.settings.Insert<std::string>(u"custom_script_client", "scripts/client/ai/SG_TARGET_CLIENT.lua");
info.settings.Insert<std::string>(u"attached_path", path->pathName);
info.settings.Insert<uint32_t>(u"attached_path_start", 0);
@@ -295,6 +296,10 @@ void SGCannon::DoSpawnTimerFunc(Entity* self, const std::string& name) {
info.settings.Insert<uint32_t>(u"wave", self->GetVar<uint32_t>(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<LWOOBJID>(u"My_Parent_ID", self->GetObjectID());
enemy->SetVar<std::string>(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
@@ -323,26 +328,11 @@ void SGCannon::DoSpawnTimerFunc(Entity* self, const std::string& name) {
}
// 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 (SG_TARGET.lua), which is no hit.
const auto silentDeath = std::make_shared<bool>(false);
enemy->AddDieCallback([this, self, enemy, name, silentDeath]() {
if (!*silentDeath) RegisterHit(self, enemy, name);
// 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);
});
// SG_TARGET.lua (onArrived): the Arrived message says whether the waypoint is the path's last one, for a moving
// platform as for an object following waypoints (the script reads isLastPoint, which the client's PushToLua
// sets from the path and the waypoint)
const auto lastWaypoint = static_cast<uint32_t>(path->pathWaypoints.size() - 1);
if (movingPlatform) {
movingPlatform->AddPlatformAtLastWaypointCallback([this, self, enemy, name, silentDeath]() {
TargetFinishedPath(self, enemy, name, silentDeath);
});
} else if (movementAI) {
movementAI->AddWaypointReachedCallback([this, self, enemy, name, silentDeath, lastWaypoint](const uint32_t waypoint) {
if (waypoint == lastWaypoint) TargetFinishedPath(self, enemy, name, silentDeath);
});
}
// Save the enemy
if (enemy != nullptr) {
const_cast<std::vector<LWOOBJID>&>(self->GetVar<std::vector<LWOOBJID>>(SpawnedObjects)).push_back(enemy->GetObjectID());
@@ -712,24 +702,9 @@ void SGCannon::CheckSpawn(Entity* self, Entity* target, const std::string& timer
}
}
// SG_TARGET.lua: at the last waypoint of its path a target notifies the cannon (FinishedPath: sg_cannon.lua spawns the
// next one as after a hit, without a score) and, when it is to despawn there, dies silently 1 s later, a moving
// platform after 2 s (so the clients' platforms get to the end of the path first).
void SGCannon::TargetFinishedPath(Entity* self, Entity* target, const std::string& timerName, const std::shared_ptr<bool>& silentDeath) {
// Once: a platform sent on would tell again
if (target->GetVar<bool>(u"FinishedPath")) return;
target->SetVar<bool>(u"FinishedPath", true);
CheckSpawn(self, target, timerName);
const auto& spawnInfo = target->GetVar<SGEnemy>(u"SpawnData");
if (!spawnInfo.despawnOnLastWaypoint) return;
target->AddCallbackTimer(spawnInfo.isMovingPlatform ? 2.0f : 1.0f, [target, silentDeath]() {
// Hit in the meantime
if (target->GetIsDead()) return;
*silentDeath = true;
target->Smash(target->GetObjectID(), eKillType::SILENT);
});
// 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<std::string>(u"SpawnTimerName"));
}
void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& timerName) {
@@ -742,7 +717,7 @@ void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& time
CheckSpawn(self, target, timerName);
int32_t score = spawnInfo.score;
int32_t score = SgTarget::GetActivityPoints(target);
if (score > 0) {
score += score * GetCurrentBonus(self);

View File

@@ -59,6 +59,7 @@ class SGCannon : public ActivityManager {
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;
@@ -93,7 +94,6 @@ private:
// 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 TargetFinishedPath(Entity* self, Entity* target, const std::string& timerName, const std::shared_ptr<bool>& silentDeath);
void UpdateStreak(Entity* self);
float_t GetCurrentBonus(Entity* self);

View File

@@ -0,0 +1,75 @@
#include "SgTarget.h"
#include "DestroyableComponent.h"
#include "Entity.h"
#include "EntityManager.h"
#include "GeneralUtils.h"
#include "MovementAIComponent.h"
#include "SGCannon.h"
#include "Zone.h"
#include "dZoneManager.h"
#include "eKillType.h"
void SgTarget::OnStartup(Entity* self) {
if (auto* const destroyable = self->GetComponent<DestroyableComponent>()) destroyable->SetExplodeFactor(2.5f);
}
int32_t SgTarget::GetActivityPoints(Entity* self) {
return self->HasVar(u"SpawnData") ? self->GetVar<SGEnemy>(u"SpawnData").score : 0;
}
bool SgTarget::DiedSilently(Entity* self) {
return self->GetVar<bool>(u"SilentDeath");
}
// The Arrived message's isLastPoint: whether the waypoint is the last of the path it arrived on (the one it was put
// on: its attached_path)
void SgTarget::OnWaypointReached(Entity* self, const uint32_t waypointIndex) {
const auto* const path = Game::zoneManager->GetZone()->GetPath(self->GetVarAsString(u"attached_path"));
if (path != nullptr && !path->pathWaypoints.empty() && waypointIndex == path->pathWaypoints.size() - 1) {
NotifyParentToRespawn(self);
return;
}
ChangeSpeed(self);
// The script also plays the animation a waypoint's PlayAim action names; no path in the game has one. Then it
// continues its waypoints, which the movement does by itself.
}
// The cannon spawns the next one (as after a hit, without a score); then the target despawns
void SgTarget::NotifyParentToRespawn(Entity* self) {
auto* const parent = Game::entityManager->GetEntity(self->GetVar<LWOOBJID>(u"My_Parent_ID"));
if (parent != nullptr) parent->GetScript()->OnNotifyObject(parent, self, "FinishedPath");
if (!self->HasVar(u"SpawnData")) {
self->CancelAllTimers();
self->SetVar<bool>(u"SilentDeath", true);
self->Smash(self->GetObjectID(), eKillType::SILENT);
return;
}
// 2 s for a moving platform, so the clients' platforms get to the end of the path first
const auto& spawnData = self->GetVar<SGEnemy>(u"SpawnData");
if (!spawnData.despawnOnLastWaypoint) return;
self->CancelTimer("Despawn");
self->AddTimer("Despawn", spawnData.isMovingPlatform ? 2.0f : 1.0f);
}
void SgTarget::OnTimerDone(Entity* self, std::string timerName) {
if (timerName != "Despawn") return;
self->CancelAllTimers();
self->SetVar<bool>(u"SilentDeath", true);
self->Smash(self->GetObjectID(), eKillType::SILENT);
}
// With its spawn data's chance, a new speed between its least and most (whole numbers, as Lua's math.random). The
// script sets it with SetPathingSpeed, which only an object following waypoints takes (a moving platform has no
// handler for it).
void SgTarget::ChangeSpeed(Entity* self) {
if (!self->HasVar(u"SpawnData")) return;
const auto& spawnData = self->GetVar<SGEnemy>(u"SpawnData");
if (!spawnData.changeSpeedAtWaypoint || GeneralUtils::GenerateRandomNumber<float>(0.0f, 1.0f) > spawnData.speedChangeChance) return;
const auto newSpeed = static_cast<float>(GeneralUtils::GenerateRandomNumber<int32_t>(static_cast<int32_t>(spawnData.minSpeed), static_cast<int32_t>(spawnData.maxSpeed)));
if (auto* const movementAI = self->GetComponent<MovementAIComponent>()) {
movementAI->SetMaxSpeed(newSpeed);
movementAI->SetCurrentSpeed(newSpeed);
}
}

View File

@@ -0,0 +1,22 @@
#pragma once
#include "CppScripts.h"
/**
* A GF shooting gallery target (SG_TARGET.lua, set by the cannon as the target's custom_script_server): its explode
* factor, its score, and what it does at the waypoints of its path. At the last one it tells the cannon
* (FinishedPath, the cannon spawns the next one) and dies silently a moment later; at the others it may change speed.
*/
class SgTarget : public CppScripts::Script {
public:
void OnStartup(Entity* self) override;
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)
static int32_t GetActivityPoints(Entity* self);
// Whether it died silently at the end of its path (that is no hit)
static bool DiedSilently(Entity* self);
private:
void NotifyParentToRespawn(Entity* self);
void ChangeSpeed(Entity* self);
};

View File

@@ -5,6 +5,8 @@
#include <bit>
#include <glm/gtc/quaternion.hpp>
#include "BitStream.h"
#include "CDClientDatabase.h"
#include "Entity.h"
@@ -14,6 +16,9 @@
#include "MovementMessages.h"
#include "MovingPlatformComponent.h"
#include "02_server/Map/General/SimpleOnceOnlyMoverSpinnerEvent.h"
#include "ai/MINIGAME/SG_GF/SERVER/SGCannon.h"
#include "ai/MINIGAME/SG_GF/SERVER/SgTarget.h"
#include "ScriptComponent.h"
#include "SimplePhysicsComponent.h"
#include "Zone.h"
#include "dZoneManager.h"
@@ -29,6 +34,15 @@ namespace {
return bits;
}
// Counts the platform messages its object's script is told of
class PlatformMessages : public CppScripts::Script {
public:
void OnWaypointReached(Entity* self, const uint32_t waypointIndex) override { arrived.push_back(waypointIndex); }
void OnDeparted(Entity* self, const uint32_t waypointIndex) override { departed.push_back(waypointIndex); }
std::vector<uint32_t> arrived;
std::vector<uint32_t> departed;
};
std::string HexBits(const std::string& hex, const uint32_t count) {
std::string bits;
for (size_t i = 0; i + 1 < hex.size(); i += 2) {
@@ -995,3 +1009,197 @@ TEST_F(MovingPlatformComponentTest, FireTransRockGoesBackDownAfterItsHold) {
EXPECT_EQ(mover->mState, 28u);
EXPECT_EQ(mover->mCurrentWaypointIndex, 0u);
}
// An object with a mover and a rotator: while the rotator is stopped, the mover turns the object as the client's does.
// Setting off from a waypoint it is put in that waypoint's rotation and gets the angular velocity that brings it to the
// next waypoint's rotation as it gets there (here a quarter turn about y over the 2 s of the way); at the end it is put
// in the waypoint's rotation and stops turning. A rotator that turns again wins over the mover.
TEST_F(MovingPlatformComponentTest, MoverTurnsItsObjectWhileItsRotatorIsStopped) {
Path path;
path.pathType = PathType::MovingPlatform;
path.pathName = "TestMoverTurnPath";
path.pathBehavior = PathBehavior::Once;
PathWaypoint first;
first.position = NiPoint3(0.0f, 0.0f, 0.0f);
first.speed = 5.0f;
PathWaypoint second = first;
second.position = NiPoint3(10.0f, 0.0f, 0.0f);
second.rotation = glm::angleAxis(3.14159265f / 2.0f, glm::vec3(0.0f, 1.0f, 0.0f));
path.pathWaypoints = { first, second };
const_cast<Zone*>(Game::zoneManager->GetZone())->AddPath(path);
info.pos = NiPoint3(0.0f, 0.0f, 0.0f);
info.rot = QuatUtils::IDENTITY;
info.settings.Insert<bool>(u"platformIsMover", true);
info.settings.Insert<bool>(u"platformIsRotater", true);
info.settings.Insert<float>(u"rotY", 0.5f);
info.settings.Insert<float>(u"rate", 2.0f);
Entity entity(288300744895900130, info);
info.settings.values.clear();
entity.AddComponent<SimplePhysicsComponent>(-1);
auto* const platform = entity.AddComponent<MovingPlatformComponent>(-1, "TestMoverTurnPath");
auto* const mover = platform->GetSubComponent(eMoverSubComponentType::mover);
auto* const rotator = platform->GetSubComponent(eMoverSubComponentType::rotater);
ASSERT_NE(rotator, nullptr);
// The rotator stopped at its waypoint, as one never started
rotator->mState = 12;
platform->Run(0.11f);
EXPECT_EQ(mover->mState, 2u);
EXPECT_NEAR(platform->GetAngularVelocity().y, 3.14159265f / 4.0f, 0.0001f);
platform->Run(0.89f);
EXPECT_NEAR(entity.GetPosition().x, 4.45f, 0.001f);
EXPECT_NEAR(entity.GetRotation().w, std::cos(3.14159265f / 8.0f), 0.001f);
EXPECT_NEAR(entity.GetRotation().y, std::sin(3.14159265f / 8.0f), 0.001f);
platform->Run(1.2f);
EXPECT_EQ(mover->mState, 28u);
EXPECT_EQ(entity.GetRotation(), second.rotation);
EXPECT_EQ(platform->GetAngularVelocity(), NiPoint3Constant::ZERO);
platform->Run(1.0f);
EXPECT_EQ(entity.GetRotation(), second.rotation);
// The rotator sent turning again: its angular velocity, not the mover's
platform->StartPathing();
platform->Run(0.5f);
EXPECT_NEAR(platform->GetAngularVelocity().y, -3.14159265f / 2.0f, 0.0001f);
}
// The client's angular velocity between two rotations: the shortest way, over the time; none without a turn or a time.
// Its travel time speeds up or slows down evenly between the two speeds.
TEST_F(MovingPlatformComponentTest, AngularVelocityAndTravelTimeAsTheClient) {
const auto quarter = glm::angleAxis(3.14159265f / 2.0f, glm::vec3(0.0f, 0.0f, 1.0f));
const auto velocity = CalcAngularVelocity(QuatUtils::IDENTITY, quarter, 2.0f);
EXPECT_NEAR(velocity.z, 3.14159265f / 4.0f, 0.0001f);
EXPECT_NEAR(CalcAngularVelocity(quarter, QuatUtils::IDENTITY, 2.0f).z, -3.14159265f / 4.0f, 0.0001f);
EXPECT_EQ(CalcAngularVelocity(quarter, quarter, 2.0f), NiPoint3Constant::ZERO);
EXPECT_EQ(CalcAngularVelocity(QuatUtils::IDENTITY, quarter, 0.0f), NiPoint3Constant::ZERO);
EXPECT_FLOAT_EQ(CalcPlatformTravelTime(NiPoint3(0.0f, 0.0f, 0.0f), NiPoint3(10.0f, 0.0f, 0.0f), 5.0f, 5.0f), 2.0f);
// From 0 to 10 over 10: the average speed 5
EXPECT_NEAR(CalcPlatformTravelTime(NiPoint3(0.0f, 0.0f, 0.0f), NiPoint3(10.0f, 0.0f, 0.0f), 0.0f, 10.0f), 2.0f, 0.0001f);
EXPECT_EQ(CalcPlatformTravelTime(NiPoint3(0.0f, 0.0f, 0.0f), NiPoint3(0.0f, 0.0f, 0.0f), 5.0f, 5.0f), 0.0f);
}
// The client's platform sends Departed as it leaves a waypoint it waited at (with that waypoint), not when it stops
TEST_F(MovingPlatformComponentTest, MoverDepartsAfterItsWait) {
Path path;
path.pathType = PathType::MovingPlatform;
path.pathName = "TestDepartedPath";
path.pathBehavior = PathBehavior::Once;
PathWaypoint first;
first.position = NiPoint3(0.0f, 0.0f, 0.0f);
first.speed = 10.0f;
PathWaypoint second = first;
second.position = NiPoint3(10.0f, 0.0f, 0.0f);
second.movingPlatform.wait = 1.0f;
PathWaypoint third = first;
third.position = NiPoint3(20.0f, 0.0f, 0.0f);
path.pathWaypoints = { first, second, third };
const_cast<Zone*>(Game::zoneManager->GetZone())->AddPath(path);
Entity entity(288300744895900131, info);
PlatformMessages messages;
entity.AddComponent<ScriptComponent>(-1, "", false)->SetScript(&messages);
auto* const platform = entity.AddComponent<MovingPlatformComponent>(-1, "TestDepartedPath");
platform->Run(0.05f);
EXPECT_TRUE(messages.departed.empty());
platform->Run(0.06f);
EXPECT_EQ(messages.departed, std::vector<uint32_t>{ 0 });
platform->Run(1.0f);
EXPECT_EQ(messages.arrived, std::vector<uint32_t>{ 1 });
platform->Run(0.5f);
EXPECT_EQ(messages.departed, std::vector<uint32_t>{ 0 });
platform->Run(0.51f);
EXPECT_EQ(messages.departed, (std::vector<uint32_t>{ 0, 1 }));
platform->Run(1.0f);
platform->Run(1.0f);
EXPECT_EQ(messages.arrived, (std::vector<uint32_t>{ 1, 2 }));
EXPECT_EQ(messages.departed.size(), 2u);
}
// Where the next waypoint is in the same place the client's platform is there at once: waiting at waypoint 0 it
// arrives at waypoint 1 in the first frame, and waits there. On a path of one waypoint it arrives every frame.
TEST_F(MovingPlatformComponentTest, WaypointsInOnePlaceArriveAtOnce) {
Path path;
path.pathType = PathType::MovingPlatform;
path.pathName = "TestSamePlacePath";
path.pathBehavior = PathBehavior::Once;
PathWaypoint first;
first.position = NiPoint3(0.0f, 0.0f, 0.0f);
first.speed = 10.0f;
PathWaypoint second = first;
second.movingPlatform.wait = 2.0f;
PathWaypoint third = first;
third.position = NiPoint3(10.0f, 0.0f, 0.0f);
path.pathWaypoints = { first, second, third };
const_cast<Zone*>(Game::zoneManager->GetZone())->AddPath(path);
Entity entity(288300744895900132, info);
PlatformMessages messages;
entity.AddComponent<ScriptComponent>(-1, "", false)->SetScript(&messages);
auto* const platform = entity.AddComponent<MovingPlatformComponent>(-1, "TestSamePlacePath");
auto* const mover = platform->GetMoverSubComponent();
EXPECT_EQ(mover->mState, 9u);
platform->Run(0.05f);
EXPECT_EQ(messages.arrived, std::vector<uint32_t>{ 1 });
EXPECT_EQ(mover->mState, 9u);
EXPECT_EQ(mover->mCurrentWaypointIndex, 1u);
EXPECT_TRUE(messages.departed.empty());
platform->Run(1.0f);
EXPECT_EQ(mover->mState, 9u);
platform->Run(1.0f);
EXPECT_EQ(messages.departed, std::vector<uint32_t>{ 1 });
Path single;
single.pathType = PathType::MovingPlatform;
single.pathName = "TestOneWaypointPath";
single.pathBehavior = PathBehavior::Loop;
single.pathWaypoints = { first };
const_cast<Zone*>(Game::zoneManager->GetZone())->AddPath(single);
Entity alone(288300744895900133, info);
PlatformMessages aloneMessages;
alone.AddComponent<ScriptComponent>(-1, "", false)->SetScript(&aloneMessages);
auto* const alonePlatform = alone.AddComponent<MovingPlatformComponent>(-1, "TestOneWaypointPath");
alonePlatform->Run(0.05f);
alonePlatform->Run(0.05f);
alonePlatform->Run(0.05f);
EXPECT_EQ(aloneMessages.arrived, (std::vector<uint32_t>{ 0, 0, 0 }));
EXPECT_TRUE(aloneMessages.departed.empty());
}
// SG_TARGET.lua: a target scores its spawn data's score; at the last waypoint of its path it despawns a moment later
// (1 s, 2 s on a moving platform) when its spawn data says so, silently (no hit); at the others it does not
TEST_F(MovingPlatformComponentTest, ShootingGalleryTargetAtTheEndOfItsPath) {
Path path;
path.pathType = PathType::MovingPlatform;
path.pathName = "TestTargetPath";
path.pathBehavior = PathBehavior::Once;
PathWaypoint first;
first.speed = 10.0f;
PathWaypoint second = first;
second.position = NiPoint3(10.0f, 0.0f, 0.0f);
path.pathWaypoints = { first, second };
const_cast<Zone*>(Game::zoneManager->GetZone())->AddPath(path);
SGEnemy spawnData{};
spawnData.score = 1500;
spawnData.isMovingPlatform = true;
spawnData.despawnOnLastWaypoint = true;
info.settings.Insert<std::string>(u"attached_path", "TestTargetPath");
Entity entity(288300744895900134, info);
info.settings.values.clear();
entity.SetVar<SGEnemy>(u"SpawnData", spawnData);
SgTarget script;
EXPECT_EQ(SgTarget::GetActivityPoints(&entity), 1500);
script.OnWaypointReached(&entity, 0);
entity.Update(0.0f);
EXPECT_FALSE(entity.HasTimer("Despawn"));
script.OnWaypointReached(&entity, 1);
entity.Update(0.0f);
EXPECT_TRUE(entity.HasTimer("Despawn"));
EXPECT_FALSE(SgTarget::DiedSilently(&entity));
}