Files
DarkflameServer/dGame/dPropertyBehaviors/ControlBehaviors.cpp
Aaron Kimbrell dae1925d1a refactor: effects, audio, animation and UI text game messages as structs
Converts PlayAnimation, PlayNDAudioEmitter, PlayEmbeddedEffectOnAllClientsNearObject,
PlayFXEffect, StopFXEffect, BroadcastTextToChatbox, Play2DAmbientSound,
Stop2DAmbientSound, UIMessageServerToSingleClient, UIMessageServerToAllClients,
StartCelebrationEffect, DisplayMessageBox, DisplayChatBubble, ChangeIdleFlags,
SetNameBillboardState, ShowBillboardInteractIcon, PlayCinematic, EndCinematic,
SlashCommandTextFeedback, PlayEmote and SetEmoteLockState (21 old Send
functions, 23 with overloads) and the received MessageBoxRespond,
ChoiceBoxRespond, CinematicUpdate and PlayEmote to NetGameMsgs in
EffectsMessages.{h,cpp}. The high traffic messages get a constructor for their
required fields. UI messages own their AMF arguments. Every caller is switched,
the received messages are registered in GameMessageHandler's map, and the old
functions and switch cases are deleted. Handlers are copied verbatim.

No wire change and no change in recipients: functions that always broadcast
whatever address they were given are sent with Send(UNASSIGNED_SYSTEM_ADDRESS),
functions that only did SEND_PACKET use SendToClient. Quirks are kept and
documented on the structs (PlayAnimation's UTF-8 sized name, the always written
null terminator in BroadcastTextToChatbox, StartCelebrationEffect always
writing celebrationID, SetNameBillboardState having no payload).

Verified byte for byte against a frozen verbatim copy of the old functions over
an input grid, to one client and broadcast; received messages compared with the
old handlers' read sequences and every truncated payload rejected; hand
computed golden bytes; round trips; a deliberate width mutation made the tests
fail. The byte-equality helper gains a Broadcast mode for functions that
ignored their address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 22:30:51 -05:00

318 lines
13 KiB
C++

#include "ControlBehaviors.h"
#include "Amf3.h"
#include "Entity.h"
#include "Game.h"
#include "GameMessages.h"
#include "EffectsMessages.h"
#include "ModelComponent.h"
#include "ObjectIDManager.h"
#include "Logger.h"
#include "BehaviorStates.h"
#include "AssetManager.h"
#include "BlockDefinition.h"
#include "User.h"
#include "tinyxml2.h"
#include "CDClientDatabase.h"
#include "CharacterComponent.h"
// Message includes
#include "Action.h"
#include "AddActionMessage.h"
#include "AddStripMessage.h"
#include "AddMessage.h"
#include "MigrateActionsMessage.h"
#include "MoveToInventoryMessage.h"
#include "MergeStripsMessage.h"
#include "RearrangeStripMessage.h"
#include "RemoveActionsMessage.h"
#include "RemoveStripMessage.h"
#include "RenameMessage.h"
#include "SplitStripMessage.h"
#include "UpdateActionMessage.h"
#include "UpdateStripUiMessage.h"
#include "eObjectBits.h"
void ControlBehaviors::RequestUpdatedID(ControlBehaviorContext& context) {
BehaviorMessageBase msgBase{ context.arguments };
const auto oldBehaviorID = msgBase.GetBehaviorId();
if (!context) {
LOG("Model to update behavior ID for is null. Cannot update ID.");
return;
}
LWOOBJID persistentIdBig = ObjectIDManager::GetPersistentID();
// This updates the behavior ID of the behavior should this be a new behavior
AMFArrayValue args;
args.Insert("behaviorID", std::to_string(persistentIdBig));
args.Insert("objectID", std::to_string(context.modelComponent->GetParent()->GetObjectID()));
GameMessages::UIMessageServerToSingleClient uiMessage;
uiMessage.target = context.modelOwner->GetObjectID();
uiMessage.strMessageName = "UpdateBehaviorID";
uiMessage.args = std::move(args);
uiMessage.SendToClient(context.modelOwner->GetSystemAddress());
context.modelComponent->UpdatePendingBehaviorId(persistentIdBig, oldBehaviorID);
ControlBehaviors::Instance().SendBehaviorListToClient(context);
}
void ControlBehaviors::SendBehaviorListToClient(const ControlBehaviorContext& context) {
if (!context) return;
AMFArrayValue behaviorsToSerialize;
context.modelComponent->SendBehaviorListToClient(behaviorsToSerialize);
GameMessages::UIMessageServerToSingleClient uiMessage;
uiMessage.target = context.modelOwner->GetObjectID();
uiMessage.strMessageName = "UpdateBehaviorList";
uiMessage.args = std::move(behaviorsToSerialize);
uiMessage.SendToClient(context.modelOwner->GetSystemAddress());
}
// TODO This is also supposed to serialize the state of the behaviors in progress but those aren't implemented yet
void ControlBehaviors::SendBehaviorBlocksToClient(ControlBehaviorContext& context) {
if (!context) return;
BehaviorMessageBase behaviorMsg{ context.arguments };
context.modelComponent->VerifyBehaviors();
AMFArrayValue behavior;
context.modelComponent->SendBehaviorBlocksToClient(behaviorMsg.GetBehaviorId(), behavior);
GameMessages::UIMessageServerToSingleClient uiMessage;
uiMessage.target = context.modelOwner->GetObjectID();
uiMessage.strMessageName = "UpdateBehaviorBlocks";
uiMessage.args = std::move(behavior);
uiMessage.SendToClient(context.modelOwner->GetSystemAddress());
}
void ControlBehaviors::UpdateAction(const AMFArrayValue& arguments) {
UpdateActionMessage updateActionMessage{ arguments };
auto blockDefinition = GetBlockInfo(updateActionMessage.GetAction().GetType());
if (!blockDefinition) {
LOG("Received undefined block type %s. Ignoring.", updateActionMessage.GetAction().GetType().data());
return;
}
if (updateActionMessage.GetAction().GetValueParameterString().size() > 0) {
if (updateActionMessage.GetAction().GetValueParameterString().size() < blockDefinition->GetMinimumValue() ||
updateActionMessage.GetAction().GetValueParameterString().size() > blockDefinition->GetMaximumValue()) {
LOG("Updated block %s is out of range. Ignoring update", updateActionMessage.GetAction().GetType().data());
return;
}
} else {
if (updateActionMessage.GetAction().GetValueParameterDouble() < blockDefinition->GetMinimumValue() ||
updateActionMessage.GetAction().GetValueParameterDouble() > blockDefinition->GetMaximumValue()) {
LOG("Updated block %s is out of range. Ignoring update", updateActionMessage.GetAction().GetType().data());
return;
}
}
}
void ControlBehaviors::ProcessCommand(Entity* const modelEntity, const AMFArrayValue& arguments, const std::string_view command, Entity* const modelOwner) {
if (!isInitialized || !modelEntity || !modelOwner) return;
auto* const modelComponent = modelEntity->GetComponent<ModelComponent>();
if (!modelComponent) return;
ControlBehaviorContext context{ arguments, modelComponent, modelOwner };
bool needsNewBehaviorID = false;
if (command == "sendBehaviorListToClient") {
SendBehaviorListToClient(context);
} else if (command == "sendBehaviorBlocksToClient") {
SendBehaviorBlocksToClient(context);
} else if (command == "modelTypeChanged") {
const auto* const modelType = arguments.Get<double>("ModelType");
if (!modelType) return;
modelEntity->SetVar<int>(u"modelType", modelType->GetValue());
} else if (command == "toggleExecutionUpdates") {
// TODO
} else if (command == "addStrip") {
needsNewBehaviorID = context.modelComponent->HandleControlBehaviorsMsg<AddStripMessage>(context.arguments);
} else if (command == "removeStrip") {
needsNewBehaviorID = context.modelComponent->HandleControlBehaviorsMsg<RemoveStripMessage>(arguments);
} else if (command == "mergeStrips") {
needsNewBehaviorID = context.modelComponent->HandleControlBehaviorsMsg<MergeStripsMessage>(arguments);
} else if (command == "splitStrip") {
needsNewBehaviorID = context.modelComponent->HandleControlBehaviorsMsg<SplitStripMessage>(arguments);
} else if (command == "updateStripUI") {
needsNewBehaviorID = context.modelComponent->HandleControlBehaviorsMsg<UpdateStripUiMessage>(arguments);
} else if (command == "addAction") {
needsNewBehaviorID = context.modelComponent->HandleControlBehaviorsMsg<AddActionMessage>(arguments);
} else if (command == "migrateActions") {
needsNewBehaviorID = context.modelComponent->HandleControlBehaviorsMsg<MigrateActionsMessage>(arguments);
} else if (command == "rearrangeStrip") {
needsNewBehaviorID = context.modelComponent->HandleControlBehaviorsMsg<RearrangeStripMessage>(arguments);
} else if (command == "removeActions") {
needsNewBehaviorID = context.modelComponent->HandleControlBehaviorsMsg<RemoveActionsMessage>(arguments);
} else if (command == "updateAction") {
needsNewBehaviorID = context.modelComponent->HandleControlBehaviorsMsg<UpdateActionMessage>(arguments);
} else if (command == "rename") {
needsNewBehaviorID = context.modelComponent->HandleControlBehaviorsMsg<RenameMessage>(arguments);
// Send the list back to the client so the name is updated.
SendBehaviorListToClient(context);
} else if (command == "add") {
AddMessage msg{ context.arguments, context.modelOwner->GetObjectID() };
context.modelComponent->AddBehavior(msg);
SendBehaviorListToClient(context);
} else if (command == "moveToInventory" || command == "remove") {
// both moveToInventory and remove use the same args
const bool isRemove = command != "remove";
MoveToInventoryMessage msg{ arguments, modelOwner->GetObjectID() };
context.modelComponent->RemoveBehavior(msg, isRemove);
auto* characterComponent = modelOwner->GetComponent<CharacterComponent>();
if (!characterComponent) return;
if (!isRemove) {
AMFArrayValue args;
args.Insert("BehaviorID", std::to_string(msg.GetBehaviorId()));
GameMessages::UIMessageServerToSingleClient uiMessage;
uiMessage.target = modelOwner->GetObjectID();
uiMessage.strMessageName = "BehaviorRemoved";
uiMessage.args = std::move(args);
uiMessage.SendToClient(characterComponent->GetSystemAddress());
}
SendBehaviorListToClient(context);
} else {
LOG("Unknown behavior command (%s)", command.data());
}
// If we need a new behaviorID, request it and progress the mission for adding a behavior.
// "add" takes care of this in the ModelComponent directly so we do not need to do it here for that command.
if (needsNewBehaviorID) {
RequestUpdatedID(context);
context.modelComponent->ProgressAddBehaviorMission(*context.modelOwner);
}
}
ControlBehaviors::ControlBehaviors() {
auto blocksBuffer = Game::assetManager->GetFile("ui\\ingame\\blocksdef.xml");
if (!blocksBuffer) {
LOG("Failed to open blocksdef.xml, property behaviors will be disabled for this zone! "
"(This is a necessary file for cheat detection and ensuring we do not send unexpected values to the client)");
return;
}
tinyxml2::XMLDocument m_Doc;
std::string read;
std::string buffer;
bool commentBlockStart = false;
while (std::getline(blocksBuffer, read)) {
// tinyxml2 should handle comment blocks but the client has one that fails the processing.
// This preprocessing just removes all comments from the read file out of an abundance of caution.
if (read.find("<!--") != std::string::npos) {
commentBlockStart = true;
}
if (read.find("-->") != std::string::npos) {
commentBlockStart = false;
continue;
}
if (!commentBlockStart) buffer += read;
}
auto ret = m_Doc.Parse(buffer.c_str());
if (ret == tinyxml2::XML_SUCCESS) {
LOG_DEBUG("Successfully parsed the blocksdef file!");
} else {
LOG("Failed to parse BlocksDef xmlData due to error %i!", ret);
return;
}
auto* blockLibrary = m_Doc.FirstChildElement();
if (!blockLibrary) {
LOG("No Block Library child element found.");
return;
}
// Now parse the blocksdef for the cheat detection server side.
// The client does these checks, but a bad actor can bypass the client checks
auto* blockSections = blockLibrary->FirstChildElement();
while (blockSections) {
auto* block = blockSections->FirstChildElement();
std::string blockName{};
while (block) {
blockName = block->Name();
auto& blockDefinition = blockTypes[blockName];
std::string name{};
std::string typeName{};
auto* argument = block->FirstChildElement("Argument");
if (argument) {
auto* defaultDefinition = argument->FirstChildElement("DefaultValue");
if (defaultDefinition) blockDefinition.SetDefaultValue(defaultDefinition->GetText());
auto* typeDefinition = argument->FirstChildElement("Type");
if (typeDefinition) typeName = typeDefinition->GetText();
auto* nameDefinition = argument->FirstChildElement("Name");
if (nameDefinition) name = nameDefinition->GetText();
// Now we parse the blocksdef file for the relevant information
if (typeName == "String") {
blockDefinition.SetMaximumValue(50); // The client has a hardcoded limit of 50 characters in a string field
} else if (typeName == "Float" || typeName == "Integer") {
auto* maximumDefinition = argument->FirstChildElement("Maximum");
if (maximumDefinition) blockDefinition.SetMaximumValue(std::stof(maximumDefinition->GetText()));
auto* minimumDefinition = argument->FirstChildElement("Minimum");
if (minimumDefinition) blockDefinition.SetMinimumValue(std::stof(minimumDefinition->GetText()));
} else if (typeName == "Enumeration") {
auto* values = argument->FirstChildElement("Values");
if (values) {
auto* value = values->FirstChildElement("Value");
while (value) {
if (value->GetText() == blockDefinition.GetDefaultValue()) blockDefinition.SetDefaultValue(std::to_string(blockDefinition.GetMaximumValue()));
blockDefinition.SetMaximumValue(blockDefinition.GetMaximumValue() + 1);
value = value->NextSiblingElement("Value");
}
blockDefinition.SetMaximumValue(blockDefinition.GetMaximumValue() - 1); // Maximum value is 0 indexed
} else {
values = argument->FirstChildElement("EnumerationSource");
if (!values) {
LOG("Failed to parse EnumerationSource from block (%s)", blockName.c_str());
continue;
}
auto* serviceNameNode = values->FirstChildElement("ServiceName");
if (!serviceNameNode) {
LOG("Failed to parse ServiceName from block (%s)", blockName.c_str());
continue;
}
std::string serviceName = serviceNameNode->GetText();
if (serviceName == "GetBehaviorSoundList") {
auto res = CDClientDatabase::ExecuteQuery("SELECT MAX(id) as countSounds FROM UGBehaviorSounds;");
blockDefinition.SetMaximumValue(res.getIntField("countSounds"));
blockDefinition.SetDefaultValue("0");
} else {
LOG("Unsupported Enumeration ServiceType (%s)", serviceName.c_str());
continue;
}
}
} else {
LOG("Unsupported block value type (%s)!", typeName.c_str());
continue;
}
}
block = block->NextSiblingElement();
}
blockSections = blockSections->NextSiblingElement();
}
isInitialized = true;
LOG_DEBUG("Created all base block classes");
for (auto& [name, block] : blockTypes) {
LOG_DEBUG("block name is %s default %s min %f max %f", name.data(), block.GetDefaultValue().data(), block.GetMinimumValue(), block.GetMaximumValue());
}
}
std::optional<BlockDefinition> ControlBehaviors::GetBlockInfo(const std::string_view blockName) {
auto blockDefinition = blockTypes.find(blockName);
return blockDefinition != blockTypes.end() ? std::optional(blockDefinition->second) : std::nullopt;
}