--- a/rts/Game/Game.cpp +++ b/rts/Game/Game.cpp @@ -1141,6 +1141,12 @@ int CGame::KeyPressed(int keyCode, int scanCode, bool isRepeat) { gameInputReceiver.KeyPressed(keyCode, scanCode, isRepeat); + return 0; +} + +int CGame::NativeKeyPressed(int keyCode, int scanCode, bool isRepeat) +{ + gameInputReceiver.KeyPressed(keyCode, scanCode, isRepeat, true); return 0; } --- a/rts/Game/Game.h +++ b/rts/Game/Game.h @@ -124,6 +124,7 @@ /// Called when a key is released by the user int KeyPressed(int keyCode, int scanCode, bool isRepeat) override; + int NativeKeyPressed(int keyCode, int scanCode, bool isRepeat) override; /// Called when the key is pressed by the user (can be called several times due to key repeat) int KeyReleased(int keyCode, int scanCode) override; --- a/rts/Game/GameController.h +++ b/rts/Game/GameController.h @@ -18,6 +18,7 @@ virtual bool Draw() { return true; } virtual bool Update() { return true; } virtual int KeyPressed(int keyCode, int scanCode, bool isRepeat) { return 0; } + virtual int NativeKeyPressed(int keyCode, int scanCode, bool isRepeat) { return KeyPressed(keyCode, scanCode, isRepeat); } virtual int KeyMapChanged() { return 0; } virtual int KeyReleased(int keyCode, int scanCode) { return 0; } virtual int TextInput(const std::string& utf8Text) { return 0; } --- a/rts/Game/GameInputReceiver.cpp +++ b/rts/Game/GameInputReceiver.cpp @@ -7,6 +7,7 @@ #include "Game/GlobalUnsynced.h" #include "Game/Players/PlayerHandler.h" #include "Game/UI/KeyBindings.h" +#include "Game/UI/GuiHandler.h" #include "Game/UI/KeyCodes.h" #include "Game/UI/KeySet.h" #include "Game/UI/ScanCodes.h" @@ -24,7 +25,7 @@ CGameInputReceiver::~CGameInputReceiver() = default; -bool CGameInputReceiver::KeyPressed(int keyCode, int scanCode, bool isRepeat) +bool CGameInputReceiver::KeyPressed(int keyCode, int scanCode, bool isRepeat, bool fromPlayerInput) { if (!game->IsGameOver() && !isRepeat) playerHandler.Player(gu->myPlayerNum)->currentStats.keyPresses++; @@ -49,7 +50,7 @@ // try the input receivers for (CInputReceiver* recv: CInputReceiver::GetReceivers()) { - if (recv != nullptr && recv->KeyPressed(keyCode, scanCode, isRepeat)) + if (recv != nullptr && (recv == guihandler ? guihandler->KeyPressed(keyCode, scanCode, isRepeat, fromPlayerInput) : recv->KeyPressed(keyCode, scanCode, isRepeat))) return false; } --- a/rts/Game/GameInputReceiver.h +++ b/rts/Game/GameInputReceiver.h @@ -13,7 +13,8 @@ CGameInputReceiver(); ~CGameInputReceiver(); - bool KeyPressed(int keyCode, int scanCode, bool isRepeat) override; + bool KeyPressed(int keyCode, int scanCode, bool isRepeat) override { return KeyPressed(keyCode, scanCode, isRepeat, false); } + bool KeyPressed(int keyCode, int scanCode, bool isRepeat, bool fromPlayerInput); bool KeyReleased(int keyCode, int scanCode) override; bool MousePress(int x, int y, int button) override; --- a/rts/Game/SelectedUnitsAI.cpp +++ b/rts/Game/SelectedUnitsAI.cpp @@ -85,7 +85,7 @@ return true; } -bool CSelectedUnitsHandlerAI::GiveCommandNet(Command& c, int playerNum) +bool CSelectedUnitsHandlerAI::GiveCommandNet(Command& c, int playerNum, bool fromPlayerNetwork) { RECOIL_DETAILED_TRACY_ZONE; assert(playerHandler.IsValidPlayer(playerNum)); @@ -102,7 +102,7 @@ assert(numSelectedUnits > 0); if ((cmdID == CMD_ATTACK) && ((c.GetNumParams() == 6) || ((c.GetNumParams() == 4) && (c.GetParam(3) > 0.001f)))) - return (SelectAttackNet(c, playerNum)); + return (SelectAttackNet(c, playerNum, fromPlayerNetwork)); if (numSelectedUnits == 1) { // a single unit selected @@ -119,7 +119,7 @@ if (MayRequireSetMaxSpeedCommand(c)) SetUnitWantedMaxSpeedNet(unit); - unit->commandAI->GiveCommand(c, playerNum, true, false); + unit->commandAI->GiveCommand(c, playerNum, true, false, fromPlayerNetwork); if (cmdID == CMD_WAIT && playerNum == gu->myPlayerNum) waitCommandsAI.AcknowledgeCommand(c); @@ -165,7 +165,7 @@ ret = true; } - MakeFormationFrontOrder(&c, playerNum); + MakeFormationFrontOrder(&c, playerNum, fromPlayerNetwork); return ret; } @@ -204,7 +204,7 @@ // push back some extra params so it confer with a front move c.PushPos(pos + (sideDir * length)); - MakeFormationFrontOrder(&c, playerNum); + MakeFormationFrontOrder(&c, playerNum, fromPlayerNetwork); return ret; } @@ -238,7 +238,7 @@ SetUnitWantedMaxSpeedNet(unit); } - unit->commandAI->GiveCommand(uc, playerNum, ret = true, false); + unit->commandAI->GiveCommand(uc, playerNum, ret = true, false, fromPlayerNetwork); } return ret; @@ -256,7 +256,7 @@ if (MayRequireSetMaxSpeedCommand(c)) SetUnitWantedMaxSpeedNet(unit); - unit->commandAI->GiveCommand(c, playerNum, ret = true, false); + unit->commandAI->GiveCommand(c, playerNum, ret = true, false, fromPlayerNetwork); } if (cmdID != CMD_WAIT) @@ -322,7 +322,7 @@ } -void CSelectedUnitsHandlerAI::MakeFormationFrontOrder(Command* c, int playerNum) +void CSelectedUnitsHandlerAI::MakeFormationFrontOrder(Command* c, int playerNum, bool fromPlayerNetwork) { RECOIL_DETAILED_TRACY_ZONE; // called when releasing the mouse; accompanies GuiHandler::DrawFormationFrontOrder @@ -342,7 +342,7 @@ if (unit == nullptr) continue; - unit->commandAI->GiveCommand(*c, playerNum, false, false); + unit->commandAI->GiveCommand(*c, playerNum, false, false, fromPlayerNetwork); } return; @@ -479,7 +479,7 @@ CUnit* unit = unitHandler.GetUnit(mixedUnitIDs[i]); CCommandAI* cai = unit->commandAI; - cai->GiveCommand(allFrontMoveCommands[i].second, playerNum, false, false); + cai->GiveCommand(allFrontMoveCommands[i].second, playerNum, false, false, fromPlayerNetwork); } } @@ -557,7 +557,7 @@ } -bool CSelectedUnitsHandlerAI::SelectAttackNet(const Command& cmd, int playerNum) +bool CSelectedUnitsHandlerAI::SelectAttackNet(const Command& cmd, int playerNum, bool fromPlayerNetwork) { RECOIL_DETAILED_TRACY_ZONE; bool ret = false; @@ -611,7 +611,7 @@ if (!commandAI->WillCancelQueued(attackCmd)) continue; - commandAI->GiveCommand(attackCmd, playerNum, ret = true, false); + commandAI->GiveCommand(attackCmd, playerNum, ret = true, false, fromPlayerNetwork); } } @@ -665,7 +665,7 @@ if (queueingCmd && commandAI->WillCancelQueued(attackCmd)) continue; - commandAI->GiveCommand(attackCmd, playerNum, ret = true, false); + commandAI->GiveCommand(attackCmd, playerNum, ret = true, false, fromPlayerNetwork); SetUnitWantedMaxSpeedNet(unit); // following commands are always queued --- a/rts/Game/SelectedUnitsAI.h +++ b/rts/Game/SelectedUnitsAI.h @@ -14,11 +14,11 @@ /// handles giving commands to the currently selected group of units. class CSelectedUnitsHandlerAI { public: - bool GiveCommandNet(Command& c, int playerNum); + bool GiveCommandNet(Command& c, int playerNum, bool fromPlayerNetwork = false); private: void CalculateGroupData(int playerNum, bool queueing); - void MakeFormationFrontOrder(Command* c, int playerNum); + void MakeFormationFrontOrder(Command* c, int playerNum, bool fromPlayerNetwork = false); void CreateUnitOrder(std::vector< std::pair >& out, int playerNum); float3 MoveToPos(float3 nextCornerPos, float3 dir, const CUnit* unit, Command* command, std::vector >* frontcmds, bool* newline); @@ -26,7 +26,7 @@ void SetUnitWantedMaxSpeedNet(CUnit* unit); void SetUnitGroupWantedMaxSpeedNet(CUnit* unit); - bool SelectAttackNet(const Command& cmd, int playerNum); + bool SelectAttackNet(const Command& cmd, int playerNum, bool fromPlayerNetwork = false); void SelectCircleUnits(const float3& pos, float radius, int playerNum, std::vector& units); void SelectRectangleUnits(const float3& pos0, const float3& pos1, int playerNum, std::vector& units); --- a/rts/Game/SelectedUnitsHandler.cpp +++ b/rts/Game/SelectedUnitsHandler.cpp @@ -155,7 +155,7 @@ } -void CSelectedUnitsHandler::GiveCommand(const Command& c, bool fromUser) +void CSelectedUnitsHandler::GiveCommand(const Command& c, bool fromUser, bool fromPlayerInput) { RECOIL_DETAILED_TRACY_ZONE; if (gu->spectating && gs->godMode == 0) @@ -256,7 +256,7 @@ return; } - SendCommand(c); + SendCommand(c, fromPlayerInput); if (!selectedUnits.empty()) { const CUnit* u = unitHandler.GetUnit(*selectedUnits.begin()); @@ -744,7 +744,7 @@ } // handles NETMSG_COMMAND's -void CSelectedUnitsHandler::NetOrder(Command& c, int playerId) +void CSelectedUnitsHandler::NetOrder(Command& c, int playerId, bool fromPlayerNetwork) { RECOIL_DETAILED_TRACY_ZONE; assert(unsigned(playerId) < netSelected.size()); @@ -752,7 +752,7 @@ if (netSelected[playerId].empty()) return; - selectedUnitsAI.GiveCommandNet(c, playerId); + selectedUnitsAI.GiveCommandNet(c, playerId, fromPlayerNetwork); eoh->PlayerCommandGiven(netSelected[playerId], c, playerId); } @@ -763,7 +763,7 @@ } // handles NETMSG_AICOMMAND{S}'s sent by AICallback / LuaUnsyncedCtrl (!) -void CSelectedUnitsHandler::AINetOrder(int unitID, int aiTeamID, int playerID, const Command& c) +void CSelectedUnitsHandler::AINetOrder(int unitID, int aiTeamID, int playerID, const Command& c, bool fromPlayerNetwork) { RECOIL_DETAILED_TRACY_ZONE; CUnit* unit = unitHandler.GetUnit(unitID); @@ -788,7 +788,7 @@ // always pulled from net, synced command by definition // (fromSynced determines whether CMD_UNLOAD_UNITS uses // synced or unsynced randomized position sampling, etc) - unit->commandAI->GiveCommand(c, playerID, true, false); + unit->commandAI->GiveCommand(c, playerID, true, false, fromPlayerNetwork && aiTeamID == MAX_TEAMS); } @@ -1029,11 +1029,11 @@ -void CSelectedUnitsHandler::SendCommand(const Command& c) +void CSelectedUnitsHandler::SendCommand(const Command& c, bool fromPlayerInput) { RECOIL_DETAILED_TRACY_ZONE; SendSelect(); - clientNet->Send(CBaseNetProtocol::Get().SendCommand(gu->myPlayerNum, c.GetID(), c.GetTimeOut(), c.GetOpts(), c.GetNumParams(), c.GetParams())); + clientNet->Send(CBaseNetProtocol::Get().SendCommand(gu->myPlayerNum, c.GetID(), c.GetTimeOut(), c.GetOpts(), c.GetNumParams(), c.GetParams(), fromPlayerInput)); } void CSelectedUnitsHandler::SendSelect() @@ -1053,7 +1053,7 @@ // despite the NETMSG_AICOMMANDS packet-id, this only services LuaUnsyncedCtrl -void CSelectedUnitsHandler::SendCommandsToUnits(const std::vector& unitIDs, const std::vector& commands, bool pairwise) +void CSelectedUnitsHandler::SendCommandsToUnits(const std::vector& unitIDs, const std::vector& commands, bool pairwise, bool fromPlayerNetwork) { // do not waste bandwidth (units can be selected // by any spectator, but not given orders without @@ -1125,7 +1125,8 @@ << static_cast(MAX_AIS) // << static_cast(MAX_TEAMS) - << static_cast(pairwise) + // bit0 retains pairwise; bit1 records admitted WebBAR player origin. + << static_cast((pairwise ? 1u : 0u) | (fromPlayerNetwork ? 2u : 0u)) << static_cast(refCmdID) << static_cast(refCmdOpts) << static_cast(refCmdSize); --- a/rts/Game/SelectedUnitsHandler.h +++ b/rts/Game/SelectedUnitsHandler.h @@ -23,10 +23,10 @@ void Init(unsigned numPlayers); void SelectGroup(int num); void SetGroup(CGroup* group, bool fromFactory= false, bool autoSelect = false); - void AINetOrder(int unitID, int aiTeamID, int playerID, const Command& c); + void AINetOrder(int unitID, int aiTeamID, int playerID, const Command& c, bool fromPlayerNetwork = false); int GetDefaultCmd(const CUnit* unit, const CFeature* feature); - void NetOrder(Command& c, int playerId); + void NetOrder(Command& c, int playerId, bool fromPlayerNetwork = false); void NetSelect(std::vector& s, int playerId); void ClearNetSelect(int playerId); void DependentDied(CObject* o); @@ -37,7 +37,7 @@ int commandPage; }; AvailableCommandsStruct GetAvailableCommands(); - void GiveCommand(const Command& c, bool fromUser = true); + void GiveCommand(const Command& c, bool fromUser = true, bool fromPlayerInput = false); void AddUnit(CUnit* unit); void RemoveUnit(CUnit* unit); void ClearSelected(); @@ -53,9 +53,9 @@ void DrawCommands(); std::string GetTooltip(); void SetCommandPage(int page); - void SendCommand(const Command& c); + void SendCommand(const Command& c, bool fromPlayerInput = false); void SendSelect(); - void SendCommandsToUnits(const std::vector& unitIDs, const std::vector& commands, bool pairwise = false); + void SendCommandsToUnits(const std::vector& unitIDs, const std::vector& commands, bool pairwise = false, bool fromPlayerNetwork = false); bool CommandsChanged() const { return possibleCommandsChanged; } bool IsUnitSelected(const CUnit* unit) const; --- a/rts/Game/UI/GuiHandler.cpp +++ b/rts/Game/UI/GuiHandler.cpp @@ -965,20 +965,20 @@ } -void CGuiHandler::GiveCommand(const Command& cmd, bool fromUser) +void CGuiHandler::GiveCommand(const Command& cmd, bool fromUser, bool fromPlayerInput) { RECOIL_DETAILED_TRACY_ZONE; - commandsToGive.emplace_back(cmd, fromUser); + commandsToGive.push_back({cmd, fromUser, fromPlayerInput}); } void CGuiHandler::GiveCommandsNow() { RECOIL_DETAILED_TRACY_ZONE; - for (const auto& [cmd, fromUser] : commandsToGive) { + for (const auto& [cmd, fromUser, fromPlayerInput] : commandsToGive) { if (eventHandler.CommandNotify(cmd)) continue; - selectedUnitsHandler.GiveCommand(cmd, fromUser); + selectedUnitsHandler.GiveCommand(cmd, fromUser, fromPlayerInput); if (!gatherMode) continue; @@ -1250,7 +1250,7 @@ } -void CGuiHandler::MouseRelease(int x, int y, int button, const float3& cameraPos, const float3& mouseDir) +void CGuiHandler::MouseRelease(int x, int y, int button, const float3& cameraPos, const float3& mouseDir, bool fromPlayerInput) { RECOIL_DETAILED_TRACY_ZONE; if (button != SDL_BUTTON_LEFT && button != SDL_BUTTON_RIGHT && button != -SDL_BUTTON_RIGHT && button != -SDL_BUTTON_LEFT) @@ -1292,13 +1292,13 @@ } if (size_t(iconCmd) < commands.size()) { - SetActiveCommand(iconCmd, button == SDL_BUTTON_RIGHT); + SetActiveCommand(iconCmd, button == SDL_BUTTON_RIGHT, fromPlayerInput); return; } // not over a button, try to execute a command // note: this executes GiveCommand for build-icon clicks if !preview - const Command c = GetCommand(x, y, button, false, cameraPos, mouseDir); + const Command c = GetCommand(x, y, button, false, cameraPos, mouseDir, fromPlayerInput); if (c.GetID() == CMD_FAILED) { // failed indicates we should not finish the current command @@ -1308,7 +1308,7 @@ // stop indicates that no good command could be found if (c.GetID() != CMD_STOP) { - GiveCommand(c); + GiveCommand(c, true, fromPlayerInput); lastKeySet.Reset(); } @@ -1317,7 +1317,7 @@ } -bool CGuiHandler::SetActiveCommand(int cmdIndex, bool rightMouseButton) +bool CGuiHandler::SetActiveCommand(int cmdIndex, bool rightMouseButton, bool fromPlayerInput) { RECOIL_DETAILED_TRACY_ZONE; if (cmdIndex >= (int)commands.size()) @@ -1347,7 +1347,7 @@ if (invertQueueKey && ((cd.id < 0) || (cd.id == CMD_STOCKPILE))) c.SetOpts(c.GetOpts() ^ SHIFT_KEY); } - GiveCommand(c); + GiveCommand(c, true, fromPlayerInput); break; } case CMDTYPE_ICON_MODE: { @@ -1361,7 +1361,7 @@ SNPRINTF(t, sizeof(t), "%d", newMode); cd.params[0] = t; - GiveCommand(Command(cd.id, CreateOptions(rightMouseButton), newMode)); + GiveCommand(Command(cd.id, CreateOptions(rightMouseButton), newMode), true, fromPlayerInput); forceLayoutUpdate = true; break; } @@ -1858,7 +1858,7 @@ } -bool CGuiHandler::KeyPressed(int keyCode, int scanCode, bool isRepeat) +bool CGuiHandler::KeyPressed(int keyCode, int scanCode, bool isRepeat, bool fromPlayerInput) { RECOIL_DETAILED_TRACY_ZONE; if (keyCode == SDLK_ESCAPE && (activeMousePress || inCommand >= 0)) { @@ -1890,7 +1890,7 @@ for (int ali = 0; ali < (int)al.size(); ++ali) { const int actionIndex = (ali + tmpActionOffset) % (int)al.size(); //???? const Action& action = al[actionIndex]; - if (SetActiveCommand(action, ks, actionIndex)) { + if (SetActiveCommand(action, ks, actionIndex, fromPlayerInput)) { return true; } } @@ -1900,7 +1900,7 @@ bool CGuiHandler::SetActiveCommand(const Action& action, - const CKeySet& ks, int actionIndex) + const CKeySet& ks, int actionIndex, bool fromPlayerInput) { RECOIL_DETAILED_TRACY_ZONE; if (ProcessLocalActions(action)) { @@ -1965,7 +1965,7 @@ else if (action.extra.find("queued") != std::string::npos) { c.SetOpts(c.GetOpts() | SHIFT_KEY); } - GiveCommand(c); + GiveCommand(c, true, fromPlayerInput); break; } case CMDTYPE_ICON_MODE: { @@ -1985,7 +1985,7 @@ SNPRINTF(t, sizeof(t), "%d", newMode); cmdDesc.params[0] = t; - GiveCommand(Command(cmdDesc.id, 0, newMode)); + GiveCommand(Command(cmdDesc.id, 0, newMode), true, fromPlayerInput); forceLayoutUpdate = true; break; } @@ -2008,7 +2008,7 @@ if (action.extra.find("queued") != std::string::npos) c.SetOpts(SHIFT_KEY); - GiveCommand(c); + GiveCommand(c, true, fromPlayerInput); break; } else { @@ -2168,7 +2168,7 @@ return true; } -Command CGuiHandler::GetCommand(int mouseX, int mouseY, int buttonHint, bool preview, const float3& cameraPos, const float3& mouseDir) +Command CGuiHandler::GetCommand(int mouseX, int mouseY, int buttonHint, bool preview, const float3& cameraPos, const float3& mouseDir, bool fromPlayerInput) { RECOIL_DETAILED_TRACY_ZONE; const Command defaultRet(CMD_FAILED); @@ -2266,7 +2266,7 @@ // only issue if more than one entry, i.e. user created some // kind of line/area queue (caller handles the last command) for (auto beg = buildInfos.cbegin(), end = --buildInfos.cend(); beg != end; ++beg) { - GiveCommand(beg->CreateCommand(CreateOptions(button))); + GiveCommand(beg->CreateCommand(CreateOptions(button)), true, fromPlayerInput); } } --- a/rts/Game/UI/GuiHandler.h +++ b/rts/Game/UI/GuiHandler.h @@ -35,7 +35,8 @@ void DrawCentroidCursor(); bool AboveGui(int x, int y); - bool KeyPressed(int keyCode, int scanCode, bool isRepeat); + bool KeyPressed(int keyCode, int scanCode, bool isRepeat) override { return KeyPressed(keyCode, scanCode, isRepeat, false); } + bool KeyPressed(int keyCode, int scanCode, bool isRepeat, bool fromPlayerInput); bool KeyReleased(int keyCode, int scanCode); bool MousePress(int x, int y, int button); void MouseRelease(int x, int y, int button) @@ -45,7 +46,7 @@ // where camera and mouse are still undefined. MouseRelease(x, y, button, camera->GetPos(), mouse->dir); } - void MouseRelease(int x, int y, int button, const float3& cameraPos, const float3& mouseDir); + void MouseRelease(int x, int y, int button, const float3& cameraPos, const float3& mouseDir, bool fromPlayerInput = false); bool IsAbove(int x, int y); std::string GetTooltip(int x, int y); std::string GetBuildTooltip() const; @@ -58,7 +59,7 @@ // where camera and mouse are still undefined. return GetCommand(mouseX, mouseY, buttonHint, preview, camera->GetPos(), mouse->dir); } - Command GetCommand(int mouseX, int mouseY, int buttonHint, bool preview, const float3& cameraPos, const float3& mouseDir); + Command GetCommand(int mouseX, int mouseY, int buttonHint, bool preview, const float3& cameraPos, const float3& mouseDir, bool fromPlayerInput = false); /// startInfo.def has to be endInfo.def size_t GetBuildPositions(const BuildInfo& startInfo, const BuildInfo& endInfo, const float3& cameraPos, const float3& mouseDir); @@ -96,9 +97,9 @@ } int GetDefaultCommand(int x, int y, const float3& cameraPos, const float3& mouseDir) const; - bool SetActiveCommand(int cmdIndex, bool rightMouseButton); + bool SetActiveCommand(int cmdIndex, bool rightMouseButton, bool fromPlayerInput = false); bool SetActiveCommand(int cmdIndex, int button, bool leftMouseButton, bool rightMouseButton, bool alt, bool ctrl, bool meta, bool shift); - bool SetActiveCommand(const Action& action, const CKeySet& ks, int actionIndex); + bool SetActiveCommand(const Action& action, const CKeySet& ks, int actionIndex, bool fromPlayerInput = false); void CancelActiveCommand(); void SetDrawSelectionInfo(bool dsi) { drawSelectionInfo = dsi; } @@ -110,7 +111,7 @@ void LayoutIcons(bool useSelectionPage); private: - void GiveCommand(const Command& cmd, bool fromUser = true); + void GiveCommand(const Command& cmd, bool fromUser = true, bool fromPlayerInput = false); void GiveCommandsNow(); bool LayoutCustomIcons(bool useSelectionPage); void ResizeIconArray(size_t size); @@ -259,7 +260,8 @@ std::vector icons; std::vector layoutCommands; - std::vector< std::pair > commandsToGive; + struct QueuedCommand { Command command; bool fromUser; bool fromPlayerInput; }; + std::vector commandsToGive; // DrawMapStuff caches std::vector buildInfos; --- a/rts/Game/UI/MiniMap.cpp +++ b/rts/Game/UI/MiniMap.cpp @@ -811,7 +811,7 @@ } -void CMiniMap::MouseRelease(int x, int y, int button) +void CMiniMap::MouseRelease(int x, int y, int button, bool fromPlayerInput) { RECOIL_DETAILED_TRACY_ZONE; // if Press is not handled, should never get Release @@ -826,7 +826,7 @@ } if (proxyMode) { - ProxyMouseRelease(x, y, button); + ProxyMouseRelease(x, y, button, fromPlayerInput); proxyMode = false; return; } @@ -934,7 +934,7 @@ } -void CMiniMap::ProxyMouseRelease(int x, int y, int button) +void CMiniMap::ProxyMouseRelease(int x, int y, int button, bool fromPlayerInput) { RECOIL_DETAILED_TRACY_ZONE; float3 mapPos = GetMapPosition(x, y); @@ -949,7 +949,7 @@ } } - guihandler->MouseRelease(x, y, -button, mapPos, -UpVector); + guihandler->MouseRelease(x, y, -button, mapPos, -UpVector, fromPlayerInput); } --- a/rts/Game/UI/MiniMap.h +++ b/rts/Game/UI/MiniMap.h @@ -27,7 +27,8 @@ bool MousePress(int x, int y, int button) override; void MouseMove(int x, int y, int dx, int dy, int button) override; - void MouseRelease(int x, int y, int button) override; + void MouseRelease(int x, int y, int button) override { MouseRelease(x, y, button, false); } + void MouseRelease(int x, int y, int button, bool fromPlayerInput); void MouseWheel(bool up, float delta); void MoveView(int x, int y) { MoveView(GetMapPosition(x, y)); } bool IsAbove(int x, int y) override; @@ -100,7 +101,7 @@ void SelectUnits(int x, int y); void ProxyMousePress(int x, int y, int button); - void ProxyMouseRelease(int x, int y, int button); + void ProxyMouseRelease(int x, int y, int button, bool fromPlayerInput = false); void MoveView(const float3& mapPos); bool RenderCachedTexture(bool useGeom); --- a/rts/Game/UI/MouseHandler.cpp +++ b/rts/Game/UI/MouseHandler.cpp @@ -522,7 +522,7 @@ } -void CMouseHandler::MouseRelease(int x, int y, int button) +void CMouseHandler::MouseRelease(int x, int y, int button, bool fromPlayerInput) { RECOIL_DETAILED_TRACY_ZONE; const CUnit *_lastClicked = lastClicked; @@ -565,7 +565,11 @@ } if (activeReceiver != nullptr) { - activeReceiver->MouseRelease(x, y, button); + // Pass provenance only to the native GUI/minimap receiver. Lua callbacks + // retain the ordinary API and cannot inherit this call-local value. + if (activeReceiver == guihandler) guihandler->MouseRelease(x, y, button, camera->GetPos(), dir, fromPlayerInput); + else if (activeReceiver == minimap) minimap->MouseRelease(x, y, button, fromPlayerInput); + else activeReceiver->MouseRelease(x, y, button); if (!buttons[SDL_BUTTON_LEFT].pressed && !buttons[SDL_BUTTON_MIDDLE].pressed && !buttons[SDL_BUTTON_RIGHT].pressed) activeReceiver = nullptr; --- a/rts/Game/UI/MouseHandler.h +++ b/rts/Game/UI/MouseHandler.h @@ -48,7 +48,7 @@ void DrawSelectionBox() const; /// draw mousebox (selection box) void DrawCursor(); - void MouseRelease(int x, int y, int button); + void MouseRelease(int x, int y, int button, bool fromPlayerInput = false); void MousePress(int x, int y, int button); void MouseMove(int x, int y, int dx, int dy); void MouseWheel(float delta); --- a/rts/Lua/LuaInterCall.cpp +++ b/rts/Lua/LuaInterCall.cpp @@ -9,6 +9,9 @@ #include "LuaGaia.h" #include "LuaRules.h" #include "LuaUI.h" +#ifdef __EMSCRIPTEN__ +#include "WebbarLuaUI.h" +#endif enum { @@ -63,6 +66,14 @@ CLuaHandle* lh = GetLuaHandle(L, addrIndex); const char* funcName = luaL_checkstring(L, nameIndex); +#ifdef __EMSCRIPTEN__ + const int* target = static_cast(lua_touserdata(L, addrIndex)); + if (lh == nullptr && target != nullptr && *target == LUA_UI && !CLuaHandle::GetHandleSynced(L) && WebbarLuaUiCall(funcName)) { + CaptureWebbarLuaUiCall(L, funcName); + return 0; + } +#endif + if (lh == nullptr) return 0; @@ -87,6 +98,14 @@ const int addrIndex = lua_upvalueindex(1); const CLuaHandle* lh = GetLuaHandle(L, addrIndex); +#ifdef __EMSCRIPTEN__ + const int* target = static_cast(lua_touserdata(L, addrIndex)); + if (lh == nullptr && target != nullptr && *target == LUA_UI && !CLuaHandle::GetHandleSynced(L) && lua_gettop(L) > 1 && lua_israwstring(L, 2) && WebbarLuaUiCall(lua_tostring(L, 2))) { + lua_pushboolean(L, true); + return 1; + } +#endif + if (lh == nullptr) return 0; --- a/rts/Net/NetCommands.cpp +++ b/rts/Net/NetCommands.cpp @@ -3,6 +3,10 @@ #include #include "Game/Game.h" +#include "Sim/Units/WebbarAutomation.h" +#ifdef __EMSCRIPTEN__ +#include "Game/WebbarUiEvents.h" +#endif #include "GameServer.h" #include "ExternalAI/EngineOutHandler.h" @@ -696,6 +700,11 @@ pckt >> cmdTimeOut; pckt >> cmdOptions; pckt >> numParams; + const bool fromPlayerNetwork = (numParams & 0x80000000u) != 0; + numParams &= 0x7fffffffu; + // Before reading any parameter, bind the count to actual packet bytes. + if (dataLength < 17 || packetSize != dataLength || ((dataLength - 17) % 4) != 0 || numParams != uint32_t((dataLength - 17) / 4)) + throw netcode::UnpackPacketException("Invalid command count/length"); Command c(cmdID, cmdOptions); c.SetTimeOut(cmdTimeOut); @@ -705,7 +714,7 @@ c.PushParam(param); } - selectedUnitsHandler.NetOrder(c, playerNum); + selectedUnitsHandler.NetOrder(c, playerNum, fromPlayerNetwork); AddTraffic(playerNum, packetCode, dataLength); } catch (const netcode::UnpackPacketException& ex) { LOG_L(L_ERROR, "[Game::%s][NETMSG_COMMAND] exception \"%s\"", __func__, ex.what()); @@ -827,6 +836,10 @@ pckt >> aiInstID; pckt >> pairwise; + if ((pairwise & ~3u) != 0) + throw netcode::UnpackPacketException("Invalid pairwise/player origin flags"); + const bool fromPlayerNetwork = (pairwise & 2u) != 0; + pairwise &= 1u; pckt >> sameCmdID; pckt >> sameCmdOpt; pckt >> sameCmdParamSize; @@ -876,12 +889,12 @@ // apply the "AI" commands (which actually originate from LuaUnsyncedCtrl) if (pairwise) { for (int16_t x = 0; x < std::min(unitCount, commandCount); ++x) { - selectedUnitsHandler.AINetOrder(unitIDs[x], aiInstID, playerID, commands[x]); + selectedUnitsHandler.AINetOrder(unitIDs[x], aiInstID, playerID, commands[x], fromPlayerNetwork); } } else { for (int16_t c = 0; c < commandCount; c++) { for (int16_t u = 0; u < unitCount; u++) { - selectedUnitsHandler.AINetOrder(unitIDs[u], aiInstID, playerID, commands[c]); + selectedUnitsHandler.AINetOrder(unitIDs[u], aiInstID, playerID, commands[c], fromPlayerNetwork); } } } @@ -1030,7 +1043,8 @@ unpack >> mode; unpack >> data; - CLuaHandle::HandleLuaMsg(playerNum, script, mode, data); + if (!WebbarAutomation::Receive(playerNum, script, mode, data)) + CLuaHandle::HandleLuaMsg(playerNum, script, mode, data); AddTraffic(playerNum, packetCode, dataLength); } catch (const netcode::UnpackPacketException& ex) { LOG_L(L_ERROR, "[Game::%s][NETMSG_LUAMSG] exception \"%s\"", __func__, ex.what()); @@ -1201,6 +1215,9 @@ case TEAMMSG_RESIGN: { if (!playing) break; +#ifdef __EMSCRIPTEN__ + if (!player->spectator) WebbarUiEvents::Emit({0, 0, 4, 0xffffffffu, 0, uint32_t(player->team), playerNum, 0, uint32_t(gu->spectating), player->name.substr(0, 256)}); +#endif player->StartSpectating(); --- a/rts/Net/Protocol/BaseNetProtocol.cpp +++ b/rts/Net/Protocol/BaseNetProtocol.cpp @@ -8,6 +8,7 @@ #include "System/Net/PackPacket.h" #include "System/Net/ProtocolDef.h" #include +#include using netcode::PackPacket; typedef std::shared_ptr PacketType; @@ -121,14 +122,18 @@ int32_t timeout, uint8_t options, uint32_t numParams, - const float* params + const float* params, + bool fromPlayerInput ) { + // A u16 packet length bounds the count independently of its origin bit. + if (numParams > (65535u - 17u) / 4u || (numParams != 0 && params == nullptr)) + throw std::invalid_argument("Invalid command parameter count"); const uint32_t payloadSize = sizeof(playerNum) + sizeof(commandID) + sizeof(timeout) + sizeof(options) + sizeof(numParams) + (numParams * sizeof(float)); const uint32_t headerSize = sizeof(uint8_t) + sizeof(uint16_t); const uint32_t packetSize = headerSize + payloadSize; PackPacket* packet = new PackPacket(packetSize, NETMSG_COMMAND); - *packet << static_cast(packetSize) << playerNum << commandID << timeout << options << numParams; + *packet << static_cast(packetSize) << playerNum << commandID << timeout << options << (numParams | (fromPlayerInput ? 0x80000000u : 0u)); for (uint32_t i = 0; i < numParams; i++) { *packet << params[i]; --- a/rts/Net/Protocol/BaseNetProtocol.h +++ b/rts/Net/Protocol/BaseNetProtocol.h @@ -54,7 +54,7 @@ PacketType SendSelect(uint8_t playerNum, const std::vector& selectedUnitIDs); PacketType SendPause(uint8_t playerNum, uint8_t bPaused); - PacketType SendCommand(uint8_t playerNum, int32_t commandID, int32_t timeout, uint8_t options, uint32_t numParams, const float* params); + PacketType SendCommand(uint8_t playerNum, int32_t commandID, int32_t timeout, uint8_t options, uint32_t numParams, const float* params, bool fromPlayerInput = false); PacketType SendAICommand(uint8_t playerNum, uint8_t aiInstID, uint8_t aiTeamID, int16_t unitID, int32_t commandID, int32_t aiCommandID, int32_t timeout, uint8_t options, uint32_t numParams, const float* params); PacketType SendAIShare(uint8_t playerNum, uint8_t aiID, uint8_t sourceTeam, uint8_t destTeam, float metal, float energy, const std::vector& unitIDs); --- a/rts/Sim/CMakeLists.txt +++ b/rts/Sim/CMakeLists.txt @@ -127,6 +127,7 @@ "${CMAKE_CURRENT_SOURCE_DIR}/Units/Scripts/UnitScriptEngine.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/Units/Scripts/UnitScriptFactory.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/Units/Unit.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Units/WebbarAutomation.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/Units/UnitDef.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/Units/UnitDefHandler.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/Units/UnitHandler.cpp" --- a/rts/Sim/Units/CommandAI/CommandAI.cpp +++ b/rts/Sim/Units/CommandAI/CommandAI.cpp @@ -2,12 +2,15 @@ #include "CommandAI.h" +#include "Sim/Units/WebbarAutomation.h" #include "BuilderCAI.h" #include "FactoryCAI.h" #include "ExternalAI/EngineOutHandler.h" #include "ExternalAI/SkirmishAIHandler.h" #include "Game/GlobalUnsynced.h" +#include "Game/Players/Player.h" +#include "Game/Players/PlayerHandler.h" #include "Game/SelectedUnitsHandler.h" #include "Game/WaitCommandsAI.h" #include "Map/Ground.h" @@ -818,12 +821,21 @@ RECOIL_DETAILED_TRACY_ZONE; GiveCommand(c, teamHandler.Team(owner->team)->leader, fromSynced, false); } -void CCommandAI::GiveCommand(const Command& c, int playerNum, bool fromSynced, bool fromLua) +void CCommandAI::GiveCommand(const Command& c, int playerNum, bool fromSynced, bool fromLua, bool fromPlayerNetwork, bool* playerActionAccepted) { RECOIL_DETAILED_TRACY_ZONE; if (!eventHandler.AllowCommand(owner, c, playerNum, fromSynced, fromLua)) return; + // Network commands are synced execution, but an explicitly recorded player + // origin must retire manual leases. Lua/AI/internal dispatch keeps the old + // flags and cannot inherit this call-local origin through nested commands. + const bool admittedPlayer = fromPlayerNetwork && !fromLua && playerHandler.IsValidPlayer(playerNum) && playerHandler.Player(playerNum)->CanControlTeam(owner->team); + // Only authenticated closed manual actions may bypass their own DispatchScope. + // The call-local argument defaults false on every generic/Lua/network route. + const bool admittedPlayerAction = playerActionAccepted != nullptr && !*playerActionAccepted && !fromLua && playerHandler.IsValidPlayer(playerNum) && playerHandler.Player(playerNum)->CanControlTeam(owner->team); + if (admittedPlayer || admittedPlayerAction) WebbarAutomation::CommandGiven(owner, c, false, admittedPlayerAction); + if (admittedPlayerAction) *playerActionAccepted = true; eventHandler.UnitCommand(owner, c, playerNum, fromSynced, fromLua); GiveCommandReal(c, fromSynced); // send to the sub-classes } @@ -1107,6 +1119,7 @@ if (owner->GetGroup() == nullptr) eoh->UnitIdle(*owner); + WebbarAutomation::Idle(owner); eventHandler.UnitIdle(owner); } else { SlowUpdate(); @@ -1201,7 +1214,8 @@ SetOrderTarget(nullptr); const Command& cmd = queue->front(); eoh->CommandFinished(*owner, cmd); - eventHandler.UnitCmdDone(owner, cmd); + WebbarAutomation::CommandDone(owner, cmd); + eventHandler.UnitCmdDone(owner, cmd); ClearTargetLock(cmd); } @@ -1687,6 +1701,7 @@ SetOrderTarget(nullptr); eoh->CommandFinished(*owner, cmd); + WebbarAutomation::CommandDone(owner, cmd); eventHandler.UnitCmdDone(owner, cmd); ClearTargetLock(cmd); @@ -1694,6 +1709,7 @@ if (owner->GetGroup() == nullptr) eoh->UnitIdle(*owner); + WebbarAutomation::Idle(owner); eventHandler.UnitIdle(owner); } --- a/rts/Sim/Units/CommandAI/CommandAI.h +++ b/rts/Sim/Units/CommandAI/CommandAI.h @@ -41,7 +41,7 @@ // these both feed into GiveCommandReal() void GiveCommand(const Command& c, bool fromSynced = true ); // sim - void GiveCommand(const Command& c, int playerNum, bool fromSynced , bool fromLua); // net,Lua + void GiveCommand(const Command& c, int playerNum, bool fromSynced , bool fromLua, bool fromPlayerNetwork = false, bool* playerActionAccepted = nullptr); // net,Lua void ClearTargetLock(const Command& fc); void WeaponFired(CWeapon* weapon, const bool searchForNewTarget, bool raiseEvent = true); --- a/rts/Sim/Units/Unit.cpp +++ b/rts/Sim/Units/Unit.cpp @@ -9,6 +9,7 @@ #include "Game/WebbarLossCauses.h" #endif #include "UnitHandler.h" +#include "WebbarAutomation.h" #include "UnitDefHandler.h" #include "UnitLoader.h" #include "UnitMemPool.h" @@ -108,6 +109,7 @@ CUnit::~CUnit() { + WebbarAutomation::Destroyed(id); #ifdef __EMSCRIPTEN__ webbarCloakEvents::Forget(id); webbarWorkAudio::Forget(id); @@ -398,8 +400,10 @@ const bool preBeingBuilt = beingBuilt; // these must precede UnitFinished from FinishedBuilding + WebbarAutomation::BeginBirth(this); eventHandler.UnitCreated(this, builder); eoh->UnitCreated(*this, builder); + WebbarAutomation::FinishBirth(this); // skip past the gradual build-progression if (!preBeingBuilt && !beingBuilt) @@ -426,6 +430,8 @@ if (!beingBuilt && !postInit) return; + // Also covers Lua UnitCreated -> FinishedBuilding before PostInit returns. + WebbarAutomation::FinishBirth(this); beingBuilt = false; buildProgress = 1.0f; mass = unitDef->mass; @@ -839,6 +845,7 @@ transportee->SetStunned(transportee->paralyzeDamage > (modInfo.paralyzeOnMaxHealth? transportee->maxHealth: transportee->health)); transportee->SetVelocityAndSpeed(speed * (0.5f + 0.5f * gsRNG.NextFloat())); + WebbarAutomation::Unloaded(transportee); eventHandler.UnitUnloaded(transportee, this); } } @@ -1616,6 +1623,7 @@ if (!teamHandler.AlliedTeams(oldteam, newteam)) ChangeTeamReset(); + WebbarAutomation::Transferred(this, oldteam); return true; } @@ -2665,6 +2673,7 @@ unit->CalculateTerrainType(); unit->UpdateTerrainType(); + WebbarAutomation::Loaded(unit); eventHandler.UnitLoaded(unit, this); commandAI->BuggerOff(pos, -1.0f); return true; @@ -2712,6 +2721,7 @@ unit->CalculateTerrainType(); unit->UpdateTerrainType(); + WebbarAutomation::Unloaded(unit); eventHandler.UnitUnloaded(unit, this); return true; } --- a/rts/Sim/Units/UnitHandler.cpp +++ b/rts/Sim/Units/UnitHandler.cpp @@ -40,6 +40,7 @@ CR_BIND(CUnitHandler, ) CR_REG_METADATA(CUnitHandler, ( CR_MEMBER(idPool), + CR_MEMBER(webbarAutomation), CR_MEMBER(units), CR_MEMBER(unitsByDefs), @@ -133,6 +134,8 @@ void CUnitHandler::Kill() { + webbarAutomation = {}; + WebbarAutomation::ClearReports(); RECOIL_DETAILED_TRACY_ZONE; for (CUnit* u: activeUnits) { // ~CUnit dereferences featureHandler which is destroyed already --- a/rts/Sim/Units/UnitHandler.h +++ b/rts/Sim/Units/UnitHandler.h @@ -3,6 +3,7 @@ #ifndef UNITHANDLER_H #define UNITHANDLER_H +#include "WebbarAutomation.h" #include #include @@ -21,6 +22,8 @@ public: CUnitHandler(): idPool(MAX_UNITS) {} + WebbarAutomationState webbarAutomation; + void Init(); void Kill(); --- a/rts/Sim/Units/UnitTypes/Factory.cpp +++ b/rts/Sim/Units/UnitTypes/Factory.cpp @@ -2,6 +2,7 @@ #include "Factory.h" +#include "Sim/Units/WebbarAutomation.h" #if defined(__EMSCRIPTEN__) #include "Game/WebbarNano.h" #include "Game/WebbarWorkAudio.h" @@ -286,6 +287,7 @@ CFactoryCAI* factoryCAI = static_cast(commandAI); factoryCAI->FactoryFinishBuild(finishedBuildCommand); + WebbarAutomation::FactoryProduced(buildee, this); eventHandler.UnitFromFactory(buildee, this, !buildeeIdle); StopBuild(); } --- a/rts/System/Input/MouseInput.cpp +++ b/rts/System/Input/MouseInput.cpp @@ -84,7 +84,7 @@ mousepos = int2(event.button.x, event.button.y); if (mouse != nullptr && !mouse->IsButtonEmulated(event.button.button)) - mouse->MouseRelease(mousepos.x, mousepos.y, event.button.button); + mouse->MouseRelease(mousepos.x, mousepos.y, event.button.button, true); } break; case SDL_MOUSEWHEEL: { --- a/rts/System/SpringApp.cpp +++ b/rts/System/SpringApp.cpp @@ -1283,7 +1283,7 @@ // state is already down, so the real press is not a new edge // (the emulated store is keyed by raw SDL2 keycode, like keyVec) if (!KeyInput::IsKeyEmulated(event.key.keysym.sym)) - activeController->KeyPressed(keyCode, scanCode, event.key.repeat); + activeController->NativeKeyPressed(keyCode, scanCode, event.key.repeat); } } break; --- /dev/null +++ b/rts/Game/WebbarAutomationBrowser.h @@ -0,0 +1,84 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +#include "Lua/LuaHandle.h" +#include "Sim/Units/WebbarAutomation.h" +#include "Sim/Units/WebbarAutomationProtocol.h" + +// Polling only serializes an ordinary recorded native message. Admission and +// all policy/state changes happen later in common native/WASM NETMSG_LUAMSG. +static void PollWebbarCreationPreferences() +{ + if (gu->spectating || webbarReplay::Enabled()) return; + std::array bytes{}; + const int size = MAIN_THREAD_EM_ASM_INT({ return Module['webbarPollCreationPreferences'] ? Module['webbarPollCreationPreferences']($0, $1) : 0; }, bytes.data(), bytes.size()); + if (size <= 0 || size > int(bytes.size())) return; + std::vector packet(bytes.begin(), bytes.begin() + size); + WebbarAutomationProtocol::Policy policy; + if (!WebbarAutomationProtocol::Decode(packet, policy) || policy.team != uint32_t(gu->myTeam)) return; + clientNet->Send(CBaseNetProtocol::Get().SendLuaMsg(gu->myPlayerNum, LUA_HANDLE_ORDER_RULES, 0, packet)); +} + +static void PollWebbarAutomationActions() +{ + if (gu->spectating || webbarReplay::Enabled()) return; + std::array bytes{}; + const int size = MAIN_THREAD_EM_ASM_INT({ return Module['webbarPollAutomationActions'] ? Module['webbarPollAutomationActions']($0, $1) : 0; }, bytes.data(), bytes.size()); + if (size <= 0 || size > int(bytes.size())) return; + std::vector packet(bytes.begin(), bytes.begin() + size); + WebbarAutomationProtocol::ActionRequest request; + if (!WebbarAutomationProtocol::DecodeAction(packet, request) || request.team != uint32_t(gu->myTeam)) return; + clientNet->Send(CBaseNetProtocol::Get().SendLuaMsg(gu->myPlayerNum, LUA_HANDLE_ORDER_RULES, 0, packet)); +} + +static void PublishWebbarAutomationReports() +{ + const bool quiet = WebbarUiEvents::reset || WebbarUiEvents::CatchingUp() || webbarReplay::Enabled() || gu->spectating; + std::vector packet{0x31524157, uint32_t(gs->frameNum), uint32_t(gu->myTeam), 0, quiet ? 0 : WebbarAutomation::DroppedReports(), 0}; + if (!quiet) for (const auto& report: WebbarAutomation::Reports()) { + if (report.player != gu->myPlayerNum) continue; + packet.insert(packet.end(), {report.kind, report.request, report.team, report.revision, report.unit, report.epoch, report.event, report.action, report.status, report.frame}); + ++packet[3]; + } + if (packet[3] != 0 || packet[4] != 0) { + MAIN_THREAD_EM_ASM({ if (Module['webbarAutomationReports']) Module['webbarAutomationReports'](HEAPU8.slice($0, $0 + $1).buffer); }, packet.data(), packet.size() * 4); + } + WebbarAutomation::ClearReports(); +} + +static void PublishWebbarCreationState() +{ + // Full authoritative policy replacement accompanies every full snapshot, + // including quiet restore and view changes. Rows contain no foreign policy. + const auto& policies = unitHandler.webbarAutomation.policies; + const auto found = policies.find(gu->myTeam); + const bool admitted = !gu->spectating || webbarReplay::Enabled(); + std::vector packet{0x31504357, uint32_t(gs->frameNum), uint32_t(gu->myTeam), admitted && found != policies.end() ? found->second.revision : 0, 0, uint32_t(webbarStateRefresh)}; + if (admitted && found != policies.end()) for (const auto& row: found->second.rows) { + packet.insert(packet.end(), {row.definition, row.events, row.action}); ++packet[4]; + } + MAIN_THREAD_EM_ASM({ if (Module['webbarCreationState']) Module['webbarCreationState'](HEAPU8.slice($0, $0 + $1).buffer); }, packet.data(), packet.size() * 4); +} + +// Existing admitted target monitors only. Validity is exactly the original +// Lua visibility query, not a guessed death event. Four stored-position corners +// are checked natively; hidden target coordinates are never queried or exported. +static void PublishWebbarBomberTargets() +{ + if (!webbarStateRefresh && gs->frameNum % 7 != 1) return; + std::string json = "{\"version\":1,\"frame\":" + std::to_string(gs->frameNum) + ",\"team\":" + std::to_string(gu->myTeam) + ",\"complete\":true,\"targets\":["; + bool first = true; + if (!gu->spectating || webbarReplay::Enabled()) for (const auto& observation: WebbarAutomation::ObserveBomberTargets(gu->myTeam)) { + if (!first) json += ','; first = false; + const auto& target = observation.target; + json += "{\"id\":" + std::to_string(target.id) + ",\"epoch\":" + std::to_string(target.epoch) + ",\"x\":"; WebbarJsonNumber(json, target.x); + json += ",\"y\":"; WebbarJsonNumber(json, target.y); json += ",\"z\":"; WebbarJsonNumber(json, target.z); + json += ",\"valid\":" + std::string(observation.valid ? "true" : "false") + ",\"cornersInLos\":["; + for (int i = 0; i < 4; ++i) { if (i) json += ','; json += observation.corners[i] ? "true" : "false"; } + json += "],\"bombers\":["; + for (size_t i = 0; i < target.bombers.size(); ++i) { if (i) json += ','; json += "{\"id\":" + std::to_string(target.bombers[i].id) + ",\"epoch\":" + std::to_string(target.bombers[i].epoch) + '}'; } + json += "]}"; + } + json += "]}"; + MAIN_THREAD_EM_ASM({ if (Module['webbarBomberTargets']) Module['webbarBomberTargets']($0, $1, UTF8ToString($2)); }, gs->frameNum, gu->myTeam, json.c_str()); +} --- a/rts/Game/WebbarBrowser.h +++ b/rts/Game/WebbarBrowser.h @@ -105,6 +105,12 @@ #include "WebbarQueueActions.h" #include "WebbarQuotaOwnership.h" #include "WebbarLegion.h" +#include "WebbarHudReports.h" +#include "Sim/Units/WebbarAutomation.h" +#include "WebbarOwnedQueues.h" +#include "WebbarOrderEvents.h" +#include "WebbarAutomationBrowser.h" +#include "WebbarWidgetQueries.h" static void PublishWebbarPlayState() { @@ -116,7 +122,7 @@ // EB4 (M5) bits: 22 pose mailbox (only used when the page asks for it) | 23 removals by cause. // EB1 bits: 17 solo result from BAR game_end | 18 PvE GameRulesParams | 19 RaptorEvent/ScavEvent | // 20 display-only PvE catalog | 21 own/allied experience, self-destruct and damage reports. - MAIN_THREAD_EM_ASM({ if (Module['webbarProtocol']) Module['webbarProtocol'](9, 1375731711 /* bit 30: complete queue actions, original factory modifiers and owned factory provenance | bit 28: Legion carrier spawn switch and owned reactive armor (WRA1) | bit 24: read-only replay playback, controls and perspectives | bit 23: unit removals by cause (WLC1) | bit 22: pose mailbox (WEBBAR_POSE_MAILBOX, WebbarPoses.h) | bits 17-21: EB1 (above) | bit 16: match recovery stream export + resume | restore | shields | cloak | resurrection | native work effects | area resurrection | manual launch | capture | smart trajectory | energy conversion | geothermal | selectability | build restrictions | queue edit | game speed | engine memory */); }); + MAIN_THREAD_EM_ASM({ if (Module['webbarProtocol']) Module['webbarProtocol'](9, 2147483647 /* bits 25: authorized HUD reports, 26: native UI events, 27: original awards, 29: typed creation-state admission and exact queues | bit 30: complete queue actions, original factory modifiers and owned factory provenance | bit 28: Legion carrier spawn switch and owned reactive armor (WRA1) | bit 24: read-only replay playback, controls and perspectives | bit 23: unit removals by cause (WLC1) | bit 22: pose mailbox (WEBBAR_POSE_MAILBOX, WebbarPoses.h) | bits 17-21: EB1 (above) | bit 16: match recovery stream export + resume | restore | shields | cloak | resurrection | native work effects | area resurrection | manual launch | capture | smart trajectory | energy conversion | geothermal | selectability | build restrictions | queue edit | game speed | engine memory */); }); PublishWebbarEngineMemory(); MAIN_THREAD_EM_ASM({ if (Module['webbarIdentity']) Module['webbarIdentity']($0, $1, $2, $3); @@ -214,12 +220,16 @@ { SCOPED_TIMER("Webbar::Publish::State::Reports"); if (webbarStateRefresh || gs->frameNum % 30 == 0) { PublishWebbarUnitExperience(); PublishWebbarRules(webbarStateRefresh); } PublishWebbarUnitDamage(); PublishWebbarPveEvents(); - PublishWebbarQuotaOwnership(); } + PublishWebbarQuotaOwnership(WebbarWidgetQueries::WeaponIdentityNeeded()); } PublishWebbarReactiveArmor(); + PublishWebbarCreationState(); + PublishWebbarHudReports(); + PublishWebbarOwnedQueues(); if (gs->frameNum % 300 == 0) PublishWebbarEngineMemory(); if (webbarStateRefresh || (gs->frameNum > 0 && gs->frameNum % (TeamStatistics::statsPeriod * GAME_SPEED) == 0)) PublishWebbarTeamStats(false, nullptr); { SCOPED_TIMER("Webbar::Publish::State::WorkAudio"); webbarWorkAudio::Publish(); } { SCOPED_TIMER("Webbar::Publish::World"); PublishWebbarWorld(); } + WebbarWidgetQueries::Publish(); { SCOPED_TIMER("Webbar::Publish::State::Resurrection"); PublishWebbarResurrection(); } } @@ -256,6 +266,7 @@ if (Module['webbarState']) Module['webbarState']($0, $1); }, lastPaused, gs->frameNum); } + if (!catchingUp) WebbarWidgetQueries::Poll(); if (!gs->paused) webbarPausedCommandsChanged = false; else if (!catchingUp && WebbarCarrierModesChanged()) webbarPausedCommandsChanged = true; if (gs->paused && !catchingUp && webbarPausedCommandsChanged) { @@ -268,6 +279,8 @@ } WebbarPoseMailbox::Refresh(&WebbarUnits); + if (!catchingUp) { PollWebbarCreationPreferences(); PollWebbarAutomationActions(); } + // Pinned BAR modules/customcommands.lua; its synced gadget reissues native MANUALFIRE. constexpr int BAR_MANUAL_LAUNCH = 32102; struct BrowserOrder { @@ -284,6 +297,10 @@ }, &order); if (!available) break; + // Separate one-shot host metadata; the legacy 288-byte order is unchanged. + const bool fromPlayerNetwork = MAIN_THREAD_EM_ASM_INT({ + return Module['webbarCommandOrigin'] && Module['webbarCommandOrigin']($0 >>> 0) === 1 ? 1 : 0; + }, order.request) != 0; int status = 0; float3 buildPos(order.x, 0.0f, order.z); @@ -305,7 +322,7 @@ if (WebbarSelectable(unit) && std::find(ids.begin(), ids.end(), unit->id) == ids.end()) ids.push_back(unit->id); } - Command command(order.kind, uint8_t(order.options & SHIFT_KEY)); + Command command(order.kind, uint8_t(order.options & (SHIFT_KEY | (order.kind == CMD_FIGHT ? META_KEY : 0)))); const auto description = [](int id, int kind) -> const SCommandDescription* { for (const auto* desc: unitHandler.GetUnit(id)->commandAI->GetPossibleCommands()) if (desc->id == kind && !desc->disabled && !desc->hidden) return desc; @@ -321,14 +338,14 @@ const uint32_t insertion = (order.options >> 16) & 3; const bool frontKind = order.kind == CMD_MOVE || order.kind == CMD_FIGHT || order.kind == CMD_PATROL || order.kind == CMD_ATTACK || order.kind == CMD_GUARD || order.kind == CMD_LOAD_UNITS || order.kind == CMD_UNLOAD_UNITS || order.kind == CMD_REPAIR || order.kind == CMD_CAPTURE || order.kind == CMD_RECLAIM || order.kind == CMD_RESURRECT || order.kind == CMD_MANUALFIRE || order.kind == BAR_MANUAL_LAUNCH || order.kind == CMD_RESTORE || order.kind == 1002 || order.kind == 1004 || order.kind == 1006 || order.kind == 1007 || order.kind == 1008; const bool nearestKind = frontKind && order.kind != CMD_PATROL && order.kind != CMD_CAPTURE && order.kind != CMD_LOAD_UNITS && order.kind != CMD_UNLOAD_UNITS && order.kind != CMD_RESTORE && order.kind != BAR_MANUAL_LAUNCH; - const uint32_t allowedOptions = order.kind == 1003 ? uint32_t(SHIFT_KEY | CONTROL_KEY | RIGHT_MOUSE_KEY | ALT_KEY) : uint32_t(SHIFT_KEY) | ((order.kind == 1001 || order.kind == 1002) ? 0x300u : 0u) | (order.kind == 1006 ? uint32_t(ALT_KEY) : 0u) | (frontKind ? 0x30000u : 0u); + const uint32_t allowedOptions = order.kind == 1003 ? uint32_t(SHIFT_KEY | CONTROL_KEY | RIGHT_MOUSE_KEY | ALT_KEY) : uint32_t(SHIFT_KEY) | (order.kind == CMD_FIGHT ? uint32_t(META_KEY) : 0u) | ((order.kind == 1001 || order.kind == 1002) ? 0x300u : 0u) | (order.kind == 1006 ? uint32_t(ALT_KEY) : 0u) | (frontKind ? 0x30000u : 0u); if ((order.options & ~allowedOptions) != 0 || insertion == 3 || (insertion == 1 && !frontKind) || (insertion == 2 && !nearestKind)) { status = 6; } else if (ids.empty()) { status = 2; } else if (order.kind == 1014 || order.kind == 1015) { if (order.options != 0) status = 6; - else for (int id: ids) WebbarRemoveQueueEnd(unitHandler.GetUnit(id), order.kind == 1015); + else for (int id: ids) WebbarRemoveQueueEnd(unitHandler.GetUnit(id), order.kind == 1015, fromPlayerNetwork); } else if (order.kind == 1016) { if (ids.size() != 1 || order.options != 0) status = 6; else { @@ -345,8 +362,11 @@ } else { command.PushPos(float3(order.x, CGround::GetHeightReal(order.x, order.z), order.z)); } - } else if (order.kind == CMD_FIRE_STATE || order.kind == CMD_MOVE_STATE || order.kind == CMD_REPEAT || order.kind == CMD_ONOFF || order.kind == 37382 /* BAR CMD_WANT_CLOAK */ || order.kind == CMD_TRAJECTORY || order.kind == 37384 /* BAR SMART_TOGGLE */ || order.kind == CMD_AUTOREPAIRLEVEL || order.kind == CMD_IDLEMODE || order.kind == 31200 /* BAR CARRIER_SPAWN_ONOFF */) { - requireCapability(order.kind); + } else if (order.kind == CMD_FIRE_STATE || order.kind == CMD_MOVE_STATE || order.kind == CMD_REPEAT || order.kind == CMD_ONOFF || order.kind == 37382 /* BAR CMD_WANT_CLOAK */ || order.kind == CMD_TRAJECTORY || order.kind == 37384 /* BAR SMART_TOGGLE */ || order.kind == CMD_AUTOREPAIRLEVEL || order.kind == CMD_IDLEMODE || order.kind == 31200 /* BAR CARRIER_SPAWN_ONOFF */ || order.kind == 13921 /* BAR FACTORY_GUARD */) { + const bool creationDefault = (order.kind == CMD_FIRE_STATE && order.target == 0) || (order.kind == CMD_MOVE_STATE && order.target <= 1) || (order.kind == CMD_IDLEMODE && order.target == 0) || (order.kind == 13921 && order.target == 1); + std::erase_if(ids, [&](int id) { return (!creationDefault && unitHandler.GetUnit(id)->beingBuilt) || description(id, order.kind) == nullptr; }); + if (ids.empty()) status = 8; + if (order.kind == 13921 && order.target != 1) status = 6; if (order.kind == 31200 && (order.target > 1 || order.options != 0)) status = 6; for (int id: ids) { const auto* desc = description(id, order.kind); @@ -484,7 +504,7 @@ for (unsigned int p = 0; p < moving->GetNumParams(); ++p) insert.PushParam(moving->GetParam(p)); Command remove(CMD_REMOVE, queueOpt); remove.PushParam(float(order.target)); - selectedUnitsHandler.SendCommandsToUnits(ids, {insert, remove}, false); + selectedUnitsHandler.SendCommandsToUnits(ids, {insert, remove}, false, fromPlayerNetwork); } } else { const UnitDef* def = unitDefHandler->GetUnitDefByID(order.target); @@ -496,7 +516,7 @@ insert.PushParam(float(anchor)); insert.PushParam(float(-def->id)); insert.PushParam(0.0f); - selectedUnitsHandler.SendCommandsToUnits(ids, {insert}, false); + selectedUnitsHandler.SendCommandsToUnits(ids, {insert}, false, fromPlayerNetwork); } } } @@ -540,8 +560,8 @@ if (order.kind == CMD_PATROL || order.kind == CMD_MANUALFIRE || order.kind == BAR_MANUAL_LAUNCH) requireCapability(order.kind); if (status == 0 && order.kind != 1001 && order.kind != 1011 && order.kind != 1012 && order.kind != 1014 && order.kind != 1015 && order.kind != 1016) { if (insertion != 0) { - for (int id: ids) WebbarInsertCommand(unitHandler.GetUnit(id), command, insertion == 2); - } else selectedUnitsHandler.SendCommandsToUnits(ids, {command}, false); + for (int id: ids) WebbarInsertCommand(unitHandler.GetUnit(id), command, insertion == 2, fromPlayerNetwork); + } else selectedUnitsHandler.SendCommandsToUnits(ids, {command}, false, fromPlayerNetwork); } } MAIN_THREAD_EM_ASM({ @@ -649,6 +669,10 @@ // first packet after a skipped stretch). One-time definitions and full-state channels are kept. static void DiscardWebbarPresentationQueues() { + WebbarWidgetQueries::Clear(); + WebbarUiEvents::Discard(); + WebbarAutomation::ClearReports(); + GetWebbarOrderEvents().Clear(); WebbarNano::pending.clear(); WebbarNano::dropped = 0; webbarWorkAudio::pending.clear(); webbarWorkAudio::dropped = 0; webbarFireAudio::pending.clear(); webbarFireAudio::dropped = 0; @@ -669,7 +693,7 @@ if (!webbarRepublish) webbarFrameChecksum = CSyncChecker::GetChecksum(); // Register before replay/resume can suppress presentation. The same event // history, including ownership transfers, must reconstruct quota identities. - if (std::getenv("WEBBAR_PLAYABLE") != nullptr) GetWebbarQuotaOwnership(); + if (std::getenv("WEBBAR_PLAYABLE") != nullptr) { GetWebbarQuotaOwnership(); GetWebbarHudEvents(); GetWebbarOrderEvents(); } if (webbarReplay::Enabled()) { ApplyWebbarReplayView(); const int seek = webbarReplay::seek.load(); @@ -691,8 +715,12 @@ static const bool browser = std::getenv("WEBBAR_BROWSER") != nullptr; static const bool playableBrowser = browser && std::getenv("WEBBAR_PLAYABLE") != nullptr; if (playableBrowser && gs->frameNum >= 0) { SCOPED_TIMER("Webbar::Publish::Effects"); GetWebbarEffects().Publish(); } + if (playableBrowser) { PublishWebbarAutomationReports(); PublishWebbarBomberTargets(); PublishWebbarOrderEvents(); } + // A recorded automation policy adds exact10-frame ferry observations. Old + // streams without that registry keep the original publication cadence. + const bool automationTick = playableBrowser && unitHandler.webbarAutomation.active && gs->frameNum % 10 == 0; // Forced publications keep snapshot, poses and low-frequency state at one frame. - if ((!output && !browser) || (gs->frameNum % 3 != 0 && !webbarStateRefresh && !(webbarReplay::Enabled() && (gs->frameNum == webbarReplay::total.load() || gs->frameNum == webbarReplay::seek.load())))) + if ((!output && !browser) || (gs->frameNum % 3 != 0 && !automationTick && !webbarStateRefresh && !(webbarReplay::Enabled() && (gs->frameNum == webbarReplay::total.load() || gs->frameNum == webbarReplay::seek.load())))) return; SCOPED_TIMER("Webbar::Publish::Frame3"); --- /dev/null +++ b/rts/Game/WebbarHudReports.h @@ -0,0 +1,208 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +#include "WebbarUiEvents.h" + +static uint32_t WebbarHudLifetime(const CUnit* unit) +{ + const auto& entries = GetWebbarQuotaOwnership().entries; + const auto known = entries.find(unit->id); + return known != entries.end() && known->second.team == unit->team ? known->second.lifetime : 0; +} + + +// Same-frame, complete own/allied reports. Public team identity and death status +// are separate from private economy and unit data. No hidden-event ID gaps. +class WebbarHudEvents final: public CEventClient +{ +public: + WebbarHudEvents(): CEventClient("Webbar HUD events", -99995, false) { eventHandler.AddClient(this); } + bool WantsEvent(const std::string& name) override { return name == "UnitMoveFailed" || name == "TeamDied" || name == "PlayerChanged" || name == "TeamChanged"; } + int GetReadAllyTeam() const override { return AllAccessTeam; } + void UnitMoveFailed(const CUnit* unit) override { + if (unit == nullptr || unit->isDead || unit->team != gu->myTeam || gu->spectating || WebbarUiEvents::CatchingUp() || webbarReplay::Enabled()) return; + WebbarUiEvents::Emit({0, 0, 1, uint32_t(unit->id), WebbarHudLifetime(unit), uint32_t(unit->team), 0xffffffffu, 0, 0, {}}); + } + void TeamDied(int team) override { + if (!teamHandler.IsValidTeam(team) || team == teamHandler.GaiaTeamID()) return; + WebbarUiEvents::Emit({0, 0, 2, 0xffffffffu, 0, uint32_t(team), 0xffffffffu, 0, uint32_t(gu->spectating), {}}); + statusDirty = true; + } + void PlayerChanged(int) override { statusDirty = true; } + void TeamChanged(int) override { statusDirty = true; } + bool statusDirty = true; +}; +static WebbarHudEvents& GetWebbarHudEvents() { static WebbarHudEvents events; return events; } + +// Events are sent BEFORE the same-frame public-status replacement. An initial, +// recovery or perspective reset silently seeds status and discards old events. +static void PublishWebbarNativeUiEvents() +{ + using namespace WebbarUiEvents; + if (reset || CatchingUp() || webbarReplay::Enabled()) { pending.clear(); dropped = 0; return; } + if (pending.empty() && dropped == 0) return; + std::string json = "["; + for (const auto& event: pending) { + if (event.kind == 1) { + const CUnit* unit = unitHandler.GetUnit(event.unit); + const auto lifetime = GetWebbarQuotaOwnership().entries.find(event.unit); + if (unit == nullptr || unit->isDead || unit->team != gu->myTeam || unit->team != int(event.team) || lifetime == GetWebbarQuotaOwnership().entries.end() || lifetime->second.team != int(event.team) || lifetime->second.lifetime != event.lifetime) continue; + } + if (json.size() > 1) json += ','; + json += "[" + std::to_string(event.token) + ',' + std::to_string(event.frame) + ',' + std::to_string(event.kind) + ',' + std::to_string(event.unit) + ',' + std::to_string(event.lifetime) + ',' + std::to_string(event.team) + ',' + std::to_string(event.player) + ',' + std::to_string(event.force) + ',' + std::to_string(event.quiet) + ','; + WebbarJsonString(json, event.name); json += ']'; + } + json += ']'; + MAIN_THREAD_EM_ASM({ if (Module['webbarNativeUiEvents']) Module['webbarNativeUiEvents']($0, UTF8ToString($1), $2); }, gs->frameNum, json.c_str(), dropped); + pending.clear(); dropped = 0; +} + +// WUS1: {magic, frame, count, overflow, viewedTeam, flags}, then 28-byte +// {unit, definition, lifetime, team, repeat, i32 fireState, relation}. flags: refresh=1, +// fullView=2, complete=4; relation: own=1, allied=2, other-full-view=4. +// Overflow clears the entire report; a partial army is never labeled complete. +static void PublishWebbarUnitSettings(bool reset) +{ + struct Record { uint32_t unit, definition, lifetime, team, repeat; int32_t fireState; uint32_t relation; }; + static_assert(sizeof(Record) == 28); + std::vector records; + uint32_t overflow = 0; + for (const CUnit* unit: unitHandler.GetActiveUnits()) { + const bool ally = teamHandler.Ally(gu->myAllyTeam, unit->allyteam); + if (unit->isDead || (!gu->spectatingFullView && !ally)) continue; + if (records.size() >= 8192) { ++overflow; continue; } + const uint32_t lifetime = WebbarHudLifetime(unit); + if (lifetime == 0) { ++overflow; continue; } + records.push_back({uint32_t(unit->id), uint32_t(unit->unitDef->id), lifetime, uint32_t(unit->team), uint32_t(unit->commandAI->repeatOrders), unit->fireState, unit->team == gu->myTeam ? 1u : ally ? 2u : 4u}); + } + if (overflow != 0) { overflow += records.size(); records.clear(); } + const uint32_t header[] = {0x31535557, uint32_t(gs->frameNum), uint32_t(records.size()), overflow, uint32_t(gu->myTeam), uint32_t(reset) | (uint32_t(gu->spectatingFullView) << 1) | (uint32_t(overflow == 0) << 2)}; + std::vector packet(sizeof(header) + records.size() * sizeof(Record)); + std::memcpy(packet.data(), header, sizeof(header)); + if (!records.empty()) std::memcpy(packet.data() + sizeof(header), records.data(), records.size() * sizeof(Record)); + MAIN_THREAD_EM_ASM({ if (Module['webbarUnitSettings']) Module['webbarUnitSettings'](HEAPU8.slice($0, $0 + $1).buffer); }, packet.data(), packet.size()); +} + +static void PublishWebbarTeamReports(bool reset) +{ + std::array commanders = {}; + for (const CUnit* unit: unitHandler.GetActiveUnits()) { + if (unit->isDead || (!gu->spectatingFullView && !teamHandler.Ally(gu->myAllyTeam, unit->allyteam))) continue; + const auto& params = unit->unitDef->customParams; + if ((params.contains("iscommander") && params.find("iscommander")->second != "0") || (params.contains("isscavcommander") && params.find("isscavcommander")->second != "0")) commanders[unit->team] = true; + } + std::string json = "{\"version\":1,\"frame\":" + std::to_string(gs->frameNum) + ",\"team\":" + std::to_string(gu->myTeam) + ",\"allyTeam\":" + std::to_string(gu->myAllyTeam) + ",\"fullView\":" + (gu->spectatingFullView ? "true" : "false") + ",\"reset\":" + (reset ? "true" : "false") + ",\"teamOrder\":["; + bool first = true; + // Exactly Spring.GetTeamList(myAllyTeam): ascending native IDs, same ally ID. + for (int t = 0; t < teamHandler.ActiveTeams(); ++t) { + if (teamHandler.AllyTeam(t) != gu->myAllyTeam) continue; + if (!first) json += ','; first = false; json += std::to_string(t); + } + json += "],\"teams\":["; first = true; + for (int t = 0; t < teamHandler.ActiveTeams(); ++t) { + if (!gu->spectatingFullView && !teamHandler.AlliedTeams(t, gu->myTeam)) continue; + const CTeam* team = teamHandler.Team(t); + if (!first) json += ','; first = false; + json += "{\"id\":" + std::to_string(t) + ",\"allyTeam\":" + std::to_string(teamHandler.AllyTeam(t)) + ",\"dead\":" + (team->isDead ? "true" : "false") + ",\"unitCount\":" + std::to_string(team->GetNumUnits()) + ",\"hasCommander\":" + (commanders[t] ? "true" : "false"); + for (int resource = 0; resource < 2; ++resource) { + json += resource == 0 ? ",\"metal\":{" : ",\"energy\":{"; + const float values[] = {team->res[resource], team->resStorage[resource], team->resPrevPull[resource], team->resPrevIncome[resource], team->resPrevExpense[resource], team->resShare[resource], team->resPrevSent[resource], team->resPrevReceived[resource], team->resPrevExcess[resource]}; + const char* names[] = {"current", "storage", "pull", "income", "expense", "share", "sent", "received", "excess"}; + for (int i = 0; i < 9; ++i) { if (i != 0) json += ','; WebbarJsonString(json, names[i]); json += ':'; WebbarJsonNumber(json, values[i]); } + json += '}'; + } + json += '}'; + } + json += "]}"; + MAIN_THREAD_EM_ASM({ if (Module['webbarTeamReports']) Module['webbarTeamReports'](UTF8ToString($0)); }, json.c_str()); +} + +// Original death_messages.lua uses GetAIInfo(team)'s FOURTH return, then the +// public ainame_TEAM GameRulesParam. This is not the team controller name or +// SkirmishAIData::name. The pinned ai_namer writes strings during GameID. +static void AppendWebbarAiDeathName(std::string& json, int team) +{ + const auto& ais = skirmishAIHandler.GetSkirmishAIsInTeam(team); + if (ais.empty()) { json += "null"; return; } + const auto* ai = skirmishAIHandler.GetSkirmishAI(ais.front()); + if (ai == nullptr) { json += "null"; return; } + std::string name = skirmishAIHandler.IsLocalSkirmishAI(ais.front()) ? ai->shortName : "UNKNOWN"; + const auto& params = CSplitLuaHandle::GetGameParams(); + const auto override = params.find("ainame_" + std::to_string(team)); + if (override != params.end()) { + if (const auto* value = std::get_if(&override->second.value)) name = *value; + else { + // Lua false means no override. Unexpected truthy non-string values + // are not generated by the pinned game: do not invent a label. + const auto* boolean = std::get_if(&override->second.value); + if (boolean == nullptr || *boolean) { json += "null"; return; } + } + } + WebbarJsonString(json, name.substr(0, 256)); +} + +static void PublishWebbarPublicStatus(bool reset) +{ + std::string json = "{\"version\":1,\"frame\":" + std::to_string(gs->frameNum) + ",\"reset\":" + (reset ? "true" : "false") + ",\"teams\":["; + for (int t = 0; t < teamHandler.ActiveTeams(); ++t) { + const CTeam* team = teamHandler.Team(t); + if (t != 0) json += ','; + json += "{\"id\":" + std::to_string(t) + ",\"allyTeam\":" + std::to_string(teamHandler.AllyTeam(t)) + ",\"dead\":" + (team->isDead ? "true" : "false") + ",\"gaia\":" + (t == teamHandler.GaiaTeamID() ? "true" : "false") + ",\"leader\":" + std::to_string(team->leader) + ",\"name\":"; + WebbarJsonString(json, std::string(team->GetControllerName()).substr(0, 256)); + json += ",\"aiDeathName\":"; AppendWebbarAiDeathName(json, t); json += '}'; + } + json += "],\"players\":["; + for (int p = 0; p < playerHandler.ActivePlayers(); ++p) { + const CPlayer* player = playerHandler.Player(p); + if (p != 0) json += ','; + json += "{\"id\":" + std::to_string(p) + ",\"team\":" + std::to_string(player->team) + ",\"active\":" + (player->active ? "true" : "false") + ",\"spectator\":" + (player->spectator ? "true" : "false") + ",\"name\":"; + WebbarJsonString(json, player->name.substr(0, 256)); json += '}'; + } + json += "],\"ais\":["; + bool first = true; + for (const auto& [id, ai]: skirmishAIHandler.GetAllSkirmishAIs()) { + if (ai == nullptr) continue; + if (!first) json += ','; first = false; + json += "{\"id\":" + std::to_string(id) + ",\"team\":" + std::to_string(ai->team) + ",\"isLuaAI\":" + (ai->isLuaAI ? "true" : "false") + ",\"name\":"; + WebbarJsonString(json, ai->name.substr(0, 256)); json += ",\"shortName\":"; WebbarJsonString(json, ai->shortName.substr(0, 128)); json += '}'; + } + json += "]}"; + MAIN_THREAD_EM_ASM({ if (Module['webbarPublicStatus']) Module['webbarPublicStatus'](UTF8ToString($0)); }, json.c_str()); +} + +static void PublishWebbarAwards(bool force) +{ + using namespace WebbarUiEvents; + static uint32_t sent = 0; + if (awardsFrame < 0 || (!force && sent == awardsVersion)) return; + sent = awardsVersion; + std::string json = "{"; + for (size_t i = 0; i < awardNames.size(); ++i) { + if (i != 0) json += ','; + WebbarJsonString(json, awardNames[i]); json += ":["; + for (size_t j = 0; j < awards[i].size(); ++j) { + if (j != 0) json += ','; + json += "{\"teamID\":" + std::to_string(awards[i][j].team) + ",\"score\":"; + char number[32]; std::snprintf(number, sizeof(number), "%.17g", awards[i][j].score); json += number; json += '}'; + } + json += ']'; + } + json += '}'; + MAIN_THREAD_EM_ASM({ if (Module['webbarAwards']) Module['webbarAwards']($0, UTF8ToString($1)); }, awardsFrame, json.c_str()); +} + +static void PublishWebbarHudReports() +{ + const bool silentReset = WebbarUiEvents::reset || WebbarUiEvents::CatchingUp(); + // This runs before public replacement; pause refresh alone is not a quiet + // reset and must not erase a real TeamDied from this same frame. + PublishWebbarNativeUiEvents(); + PublishWebbarUnitSettings(webbarStateRefresh || silentReset); + PublishWebbarTeamReports(webbarStateRefresh || silentReset); + if (webbarStateRefresh || silentReset || GetWebbarHudEvents().statusDirty || gs->frameNum % 30 == 0) { + PublishWebbarPublicStatus(silentReset); + GetWebbarHudEvents().statusDirty = false; + } + PublishWebbarAwards(webbarStateRefresh || silentReset); + WebbarUiEvents::reset = false; +} --- /dev/null +++ b/rts/Game/WebbarOrderEvents.h @@ -0,0 +1,171 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +// Original native callins, captured at the callin (not inferred from snapshots). +// Presentation history only; no callback applies defaults or mutates simulation. +class WebbarOrderEvents final: public CEventClient +{ +public: + struct Order { int id, timeout; uint32_t tag, options; std::vector params; }; + struct Event { + bool incomingTaken = false, incomingTakenAborted = false; + // Internal allocation identity; never serialized or dereferenced later. + const CUnit* allocation = nullptr; + bool deferredLifetime = false, deferredAborted = false; + uint32_t bindingToken = 0; + uint32_t receivedLifetime = 0; + uint32_t token, frame, kind, unit, definition, lifetime, team, other = 0xffffffffu, otherLifetime = 0; + bool userOrders = false, complete = true, beingBuilt = false, fromSynced = false, fromLua = false; + float health = 0, maxHealth = 0; + int oldTeam = -1, newTeam = -1, player = -1; + float3 position; + bool hasProductionDestination = false; + float productionDestination[3] = {}; + std::vector commands; + uint32_t total = 0, automationEpoch = 0, otherAutomationEpoch = 0, captureHandle = 0, idleGuardHandle = 0, nanoIdleHandle = 0, nanoRemoveHandle = 0, nanoRemoveTag = 0, productionHandle = 0; + }; + WebbarOrderEvents(): CEventClient("Webbar order events", -99994, false) { eventHandler.AddClient(this); } + bool WantsEvent(const std::string& name) override { + return name == "UnitIdle" || name == "UnitCommand" || name == "UnitCreated" || name == "UnitGiven" || name == "UnitTaken" || name == "UnitFromFactory" || name == "UnitCmdDone" || name == "UnitLoaded" || name == "UnitUnloaded"; + } + int GetReadAllyTeam() const override { return AllAccessTeam; } + void UnitIdle(const CUnit* unit) override { Emit(9, unit); } + void UnitCreated(const CUnit* unit, const CUnit* builder) override { BindDeferred(unit, 0); Emit(1, unit, builder); } + void UnitGiven(const CUnit* unit, int oldTeam, int newTeam) override { ResolveIncomingTaken(unit, oldTeam, newTeam); Emit(2, unit, nullptr, nullptr, false, oldTeam, newTeam); } + void UnitTaken(const CUnit* unit, int oldTeam, int newTeam) override { Emit(3, unit, nullptr, nullptr, false, oldTeam, newTeam); AbortBirthDeferred(unit); CaptureIncomingTaken(unit, oldTeam, newTeam); } + void UnitFromFactory(const CUnit* unit, const CUnit* factory, bool userOrders) override { Emit(4, unit, factory, nullptr, userOrders); } + void UnitCommand(const CUnit* unit, const Command& command, int playerNum, bool fromSynced, bool fromLua) override { Emit(8, unit, nullptr, &command, false, -1, -1, playerNum, fromSynced, fromLua); } + void UnitCmdDone(const CUnit* unit, const Command& command) override { Emit(5, unit, nullptr, &command); } + void UnitLoaded(const CUnit* unit, const CUnit* transport) override { Emit(6, unit, transport); } + void UnitUnloaded(const CUnit* unit, const CUnit* transport) override { Emit(7, unit, transport); } + // Original Taken data is captured before ownership changes. The incoming + // form has no old-owner private facts or speculative new ownership token. + void CaptureIncomingTaken(const CUnit* unit, int oldTeam, int newTeam) { + if (!WebbarUiEvents::Enabled() || gu->spectating || webbarReplay::Enabled() || WebbarUiEvents::CatchingUp() || unit == nullptr || unit->isDead || gs->frameNum < 0 || oldTeam == newTeam || oldTeam != unit->team || newTeam != gu->myTeam) return; + if (pending.size() >= 512) { ++dropped; return; } + if (++sequence == 0) ++sequence; + Event event{}; + event.allocation = unit; event.incomingTaken = true; event.token = sequence; event.frame = uint32_t(gs->frameNum); event.kind = 3; + event.unit = uint32_t(unit->id); event.definition = uint32_t(unit->unitDef->id); event.oldTeam = oldTeam; event.newTeam = newTeam; + pending.push_back(std::move(event)); + } + void ResolveIncomingTaken(const CUnit* unit, int oldTeam, int newTeam) { + if (unit == nullptr || unit->isDead || newTeam != gu->myTeam || unit->team != newTeam || gs->frameNum < 0) return; + // WQO's -99996 Given observer has now assigned the actual new lifetime. + // LIFO matching preserves nested same-frame transfers. Never synthesize + // Taken from Given alone or use the not-yet-reset automation epoch. + const uint32_t lifetime = WebbarHudLifetime(unit); + if (lifetime == 0 || lifetime == 0xffffffffu) return; + for (auto i = pending.rbegin(); i != pending.rend(); ++i) { + if (!i->incomingTaken || i->incomingTakenAborted || i->receivedLifetime != 0 || i->allocation != unit || i->unit != uint32_t(unit->id) || i->definition != uint32_t(unit->unitDef->id) || i->frame != uint32_t(gs->frameNum) || i->oldTeam != oldTeam || i->newTeam != newTeam) continue; + i->receivedLifetime = lifetime; + BindDeferred(unit, i->token); + return; + } + } + void BindDeferred(const CUnit* unit, uint32_t bindingToken) { + if (unit == nullptr || unit->isDead || gs->frameNum < 0) return; + const uint32_t lifetime = WebbarHudLifetime(unit); + if (lifetime == 0 || lifetime == 0xffffffffu) return; + for (auto& event: pending) { + if (!event.deferredLifetime || event.deferredAborted || event.lifetime != 0 || event.bindingToken != bindingToken || event.allocation != unit || event.frame != uint32_t(gs->frameNum) || event.unit != uint32_t(unit->id) || event.definition != uint32_t(unit->unitDef->id) || event.team != uint32_t(unit->team)) continue; + // Only actual ownership is bound. Frame, sequence, epoch (including + // zero), commands, queue and private facts remain the callin snapshot. + event.lifetime = lifetime; + } + } + void AbortBirthDeferred(const CUnit* unit) { + // Birth facts cannot cross an ownership change before actual Created. + for (auto& event: pending) if (event.deferredLifetime && event.lifetime == 0 && event.bindingToken == 0 && event.allocation == unit) event.deferredAborted = true; + } + void AbortIncomingTaken(const CUnit* unit) { + // Never bind a dead allocation's callbacks to a later recycled ID/address. + for (auto& event: pending) { + if (event.allocation != unit) continue; + if (event.incomingTaken && event.receivedLifetime == 0) event.incomingTakenAborted = true; + if (event.deferredLifetime && event.lifetime == 0) event.deferredAborted = true; + } + } + void Emit(uint32_t kind, const CUnit* unit, const CUnit* other = nullptr, const Command* done = nullptr, bool userOrders = false, int oldTeam = -1, int newTeam = -1, int player = -1, bool fromSynced = false, bool fromLua = false) { + if (!WebbarUiEvents::Enabled() || gu->spectating || webbarReplay::Enabled() || WebbarUiEvents::CatchingUp() || unit == nullptr || (unit->isDead && kind != 10) || gs->frameNum < 0) return; + const bool alliedFactory = (kind == 4 && teamHandler.AlliedTeams(unit->team, gu->myTeam)) || (kind == 10 && teamHandler.AllyTeam(unit->team) == teamHandler.AllyTeam(gu->myTeam)); + if (unit->team != gu->myTeam && !alliedFactory) return; + const uint32_t lifetime = WebbarHudLifetime(unit); + if (pending.size() >= 512 || (lifetime == 0 && kind == 10)) { ++dropped; return; } + if (++sequence == 0) ++sequence; + Event event{}; + event.allocation = unit; event.deferredLifetime = lifetime == 0; + if (event.deferredLifetime) { + // A transfer gap is associated with its actual preceding Taken, not + // mistaken for birth or rebound to a nested same-frame transfer. + for (auto i = pending.rbegin(); i != pending.rend(); ++i) { + if (i->incomingTaken && !i->incomingTakenAborted && i->receivedLifetime == 0 && i->allocation == unit && i->frame == uint32_t(gs->frameNum) && i->newTeam == unit->team && i->unit == uint32_t(unit->id) && i->definition == uint32_t(unit->unitDef->id)) { event.bindingToken = i->token; break; } + } + } + event.token = sequence; event.frame = uint32_t(gs->frameNum); event.kind = kind; event.unit = uint32_t(unit->id); event.definition = uint32_t(unit->unitDef->id); event.lifetime = lifetime; event.team = uint32_t(unit->team); event.automationEpoch = WebbarAutomation::Epoch(unit); event.captureHandle = WebbarAutomation::CaptureHandle(unit); event.idleGuardHandle = WebbarAutomation::IdleGuardHandle(unit); event.nanoIdleHandle = WebbarAutomation::NanoIdleHandle(unit); event.nanoRemoveHandle = WebbarAutomation::NanoRemoveHandle(unit); event.nanoRemoveTag = WebbarAutomation::NanoRemoveTag(unit); event.productionHandle = WebbarAutomation::ProductionHandle(unit); event.hasProductionDestination = teamHandler.AllyTeam(unit->team) == teamHandler.AllyTeam(gu->myTeam) && WebbarAutomation::ProductionDestination(unit, event.productionDestination); + event.position = unit->pos; event.userOrders = userOrders; event.beingBuilt = unit->beingBuilt; event.health = unit->health; event.maxHealth = unit->maxHealth; event.oldTeam = oldTeam; event.newTeam = newTeam; event.player = player; event.fromSynced = fromSynced; event.fromLua = fromLua; + if (other != nullptr && teamHandler.AlliedTeams(other->team, gu->myTeam)) { event.other = uint32_t(other->id); event.otherLifetime = WebbarHudLifetime(other); event.otherAutomationEpoch = WebbarAutomation::Epoch(other); } + const auto capture = [&](const Command& command) { + if (event.commands.size() >= 1024 || command.GetNumParams() > 64 || parameterWords + command.GetNumParams() > 131072 || commandRows >= 16384) { event.complete = false; return; } + Order order{command.GetID(), command.GetTimeOut(), command.GetTag(), command.GetOpts(), {}}; + for (uint32_t p = 0; p < command.GetNumParams(); ++p) { const float value = command.GetParam(p); if (!std::isfinite(value)) { event.complete = false; return; } order.params.push_back(value); } + parameterWords += uint32_t(order.params.size()); ++commandRows; event.commands.push_back(std::move(order)); + }; + // CmdDone/UnitCommand store the actual callback command and queue count + // at that callin, not an inferred success or a later queue disappearance. + // Loaded stores its queue *now*, before later transport changes can erase it. + if (done != nullptr) { event.total = uint32_t(unit->commandAI->commandQue.size()); capture(*done); } + if (kind == 6) { event.total = uint32_t(unit->commandAI->commandQue.size()); if (event.total > 1024) event.complete = false; else for (const Command& command: unit->commandAI->commandQue) { capture(command); if (!event.complete) break; } } + if (!event.complete) event.commands.clear(); + pending.push_back(std::move(event)); + } + void Clear() { pending.clear(); dropped = 0; commandRows = 0; parameterWords = 0; } + std::vector pending; + uint32_t sequence = 0, dropped = 0, commandRows = 0, parameterWords = 0; +}; +// Capture removal before WQO retires the lifetime. Other callins stay after +// ownership creation/transfer, so their newly assigned lifetime is authoritative. +class WebbarOrderDeathEvents final: public CEventClient { +public: + explicit WebbarOrderDeathEvents(WebbarOrderEvents& output): CEventClient("Webbar order deaths", -99997, false), output(output) { eventHandler.AddClient(this); } + bool WantsEvent(const std::string& name) override { return name == "UnitDestroyed"; } + int GetReadAllyTeam() const override { return AllAccessTeam; } + void UnitDestroyed(const CUnit* unit, const CUnit*, int) override { output.AbortIncomingTaken(unit); output.Emit(10, unit); } +private: + WebbarOrderEvents& output; +}; +static WebbarOrderEvents& GetWebbarOrderEvents() { static WebbarOrderEvents events; static WebbarOrderDeathEvents deaths(events); return events; } + +static void PublishWebbarOrderEvents() +{ + auto& source = GetWebbarOrderEvents(); + if (WebbarUiEvents::reset || WebbarUiEvents::CatchingUp() || webbarReplay::Enabled() || gu->spectating) { source.Clear(); return; } + if (source.pending.empty() && source.dropped == 0) return; + std::string json = "["; + for (const auto& event: source.pending) { + if (event.deferredLifetime && (event.deferredAborted || event.lifetime == 0)) { ++source.dropped; continue; } + if (event.incomingTaken) { + if (event.newTeam != gu->myTeam) continue; + if (event.incomingTakenAborted || event.receivedLifetime == 0) { ++source.dropped; continue; } + if (json.size() > 1) json += ','; + json += "{\"incomingTaken\":true,\"kind\":3,\"token\":" + std::to_string(event.token) + ",\"frame\":" + std::to_string(event.frame) + ",\"unit\":" + std::to_string(event.unit) + ",\"definition\":" + std::to_string(event.definition) + ",\"oldTeam\":" + std::to_string(event.oldTeam) + ",\"newTeam\":" + std::to_string(event.newTeam) + ",\"receivedLifetime\":" + std::to_string(event.receivedLifetime) + "}"; + continue; + } + if (json.size() > 1) json += ','; + json += "{\"token\":" + std::to_string(event.token) + ",\"frame\":" + std::to_string(event.frame) + ",\"kind\":" + std::to_string(event.kind) + ",\"unit\":" + std::to_string(event.unit) + ",\"definition\":" + std::to_string(event.definition) + ",\"lifetime\":" + std::to_string(event.lifetime) + ",\"team\":" + std::to_string(event.team) + ",\"other\":" + std::to_string(event.other) + ",\"otherLifetime\":" + std::to_string(event.otherLifetime) + ",\"userOrders\":" + (event.userOrders ? "true" : "false") + ",\"complete\":" + (event.complete ? "true" : "false") + ",\"total\":" + std::to_string(event.total) + ",\"position\":["; + WebbarJsonNumber(json, event.position.x); json += ','; WebbarJsonNumber(json, event.position.y); json += ','; WebbarJsonNumber(json, event.position.z); json += "],\"beingBuilt\":" + std::string(event.beingBuilt ? "true" : "false") + ",\"oldTeam\":" + std::to_string(event.oldTeam) + ",\"newTeam\":" + std::to_string(event.newTeam) + ",\"health\":"; WebbarJsonNumber(json, event.health); json += ",\"maxHealth\":"; WebbarJsonNumber(json, event.maxHealth); json += ",\"otherAutomationEpoch\":" + std::to_string(event.otherAutomationEpoch) + ",\"captureHandle\":" + std::to_string(event.captureHandle) + ",\"automationEpoch\":" + std::to_string(event.automationEpoch) + ",\"player\":" + std::to_string(event.player) + ",\"fromSynced\":" + (event.fromSynced ? "true" : "false") + ",\"fromLua\":" + (event.fromLua ? "true" : "false") + ",\"idleGuardHandle\":" + std::to_string(event.idleGuardHandle) + ",\"nanoIdleHandle\":" + std::to_string(event.nanoIdleHandle) + ",\"nanoRemoveHandle\":" + std::to_string(event.nanoRemoveHandle) + ",\"nanoRemoveTag\":" + std::to_string(event.nanoRemoveTag) + ",\"productionHandle\":" + std::to_string(event.productionHandle) + ",\"productionDestination\":"; + if (event.hasProductionDestination) { json += '['; for (int i = 0; i < 3; ++i) { if (i) json += ','; WebbarJsonNumber(json, event.productionDestination[i]); } json += ']'; } else json += "null"; + json += ",\"commands\":["; + for (size_t i = 0; i < event.commands.size(); ++i) { + if (i) json += ','; const auto& command = event.commands[i]; + json += "{\"id\":" + std::to_string(command.id) + ",\"tag\":" + std::to_string(command.tag) + ",\"options\":" + std::to_string(command.options) + ",\"timeout\":" + std::to_string(command.timeout) + ",\"params\":["; + for (size_t p = 0; p < command.params.size(); ++p) { if (p) json += ','; WebbarJsonNumber(json, command.params[p]); } + json += "]}"; + } + json += "]}"; + } + json += ']'; + if (json.size() > 2 * 1024 * 1024) { source.dropped += uint32_t(source.pending.size()); json = "[]"; } + MAIN_THREAD_EM_ASM({ if (Module['webbarOrderEvents']) Module['webbarOrderEvents']($0, $1, UTF8ToString($2), $3); }, gs->frameNum, gu->myTeam, json.c_str(), source.dropped); + source.Clear(); +} --- /dev/null +++ b/rts/Game/WebbarOwnedQueues.h @@ -0,0 +1,113 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include + +// WRQ2 complete owned queues, alongside the small legacy overlay packet. +// Header: magic, frame, team, unitRows, commandRows, parameterWords, dropped, flags. +// Unit row: id, definition, ownershipLifetime, kind(0=unit,1=production,2=rally), +// totalCount, firstCommand, storedCount, complete, automationEpoch, waitLease, waitTag, captureHandle, captureUnloaded. +// Command row: tag, i32 kind, +// options, i32 timeout, firstParameter, parameterCount; then exact f32 parameters. +// A unit row is either complete or empty. Bounds never turn a prefix into a queue. +// Supplement the existing queue publication with only the missing ferry facts. +// Own queues remain in WRQ2. Other queues are restricted to Lua's same-ally-team +// read authority; dynamic alliance alone does not reveal foreign command queues. +static std::string WebbarTransportFacts() +{ + const int ally = teamHandler.AllyTeam(gu->myTeam); + std::string units = "[", definitions = "["; + std::set seenDefinitions; + uint32_t count = 0, commandCount = 0, parameterCount = 0, cargoCount = 0, dropped = 0; + const auto number = [](std::string& json, float value) { WebbarJsonNumber(json, value); }; + if (!gu->spectating || webbarReplay::Enabled()) for (const CUnit* unit: unitHandler.GetActiveUnits()) { + if (unit->isDead || teamHandler.AllyTeam(unit->team) != ally) continue; + const auto* def = unit->unitDef; + const uint32_t lifetime = WebbarHudLifetime(unit), epoch = WebbarAutomation::Epoch(unit); + if (!std::isfinite(def->mass) || !std::isfinite(def->transportMass) || !std::isfinite(def->speed)) { ++dropped; break; } + if (++count > 8192 || lifetime == 0 || unit->transportedUnits.size() > 1024 || cargoCount + unit->transportedUnits.size() > 16384) { ++dropped; break; } + if (seenDefinitions.insert(def->id).second) { + if (definitions.size() > 1) definitions += ','; + definitions += "{\"id\":" + std::to_string(def->id) + ",\"factory\":" + (def->IsFactoryUnit() ? "true" : "false") + ",\"transport\":" + (def->IsTransportUnit() ? "true" : "false") + ",\"canFly\":" + (def->canfly ? "true" : "false") + ",\"cantBeTransported\":" + (def->cantBeTransported ? "true" : "false") + ",\"transportCapacity\":" + std::to_string(def->transportCapacity) + ",\"transportSize\":" + std::to_string(def->transportSize) + ",\"xsize\":" + std::to_string(def->xsize) + ",\"mass\":"; + number(definitions, def->mass); definitions += ",\"transportMass\":"; number(definitions, def->transportMass); definitions += ",\"speed\":"; number(definitions, def->speed); definitions += '}'; + } + if (units.size() > 1) units += ','; + units += "{\"id\":" + std::to_string(unit->id) + ",\"definition\":" + std::to_string(def->id) + ",\"team\":" + std::to_string(unit->team) + ",\"lifetime\":" + std::to_string(lifetime) + ",\"epoch\":" + std::to_string(epoch) + (unit->team == gu->myTeam ? ",\"manualRevision\":" + std::to_string(WebbarAutomation::ManualRevision(unit)) + ",\"waitPurpose\":" + std::to_string(WebbarAutomation::WaitPurpose(unit)) + ",\"idleGuardHandle\":" + std::to_string(WebbarAutomation::IdleGuardHandle(unit)) + ",\"nanoIdleHandle\":" + std::to_string(WebbarAutomation::NanoIdleHandle(unit)) + ",\"nanoRemoveHandle\":" + std::to_string(WebbarAutomation::NanoRemoveHandle(unit)) + ",\"nanoRemoveTag\":" + std::to_string(WebbarAutomation::NanoRemoveTag(unit)) : "") + ",\"productionHandle\":" + std::to_string(WebbarAutomation::ProductionHandle(unit)) + ",\"carried\":["; + bool firstCargo = true; + for (const auto& item: unit->transportedUnits) { + const CUnit* cargo = item.unit; + if (cargo == nullptr || cargo->isDead || teamHandler.AllyTeam(cargo->team) != ally || WebbarHudLifetime(cargo) == 0) { ++dropped; break; } + if (!firstCargo) units += ','; firstCargo = false; ++cargoCount; + units += "{\"id\":" + std::to_string(cargo->id) + ",\"definition\":" + std::to_string(cargo->unitDef->id) + ",\"team\":" + std::to_string(cargo->team) + ",\"lifetime\":" + std::to_string(WebbarHudLifetime(cargo)) + ",\"epoch\":" + std::to_string(WebbarAutomation::Epoch(cargo)) + '}'; + } + units += ']'; + float destination[3] = {}; uint32_t ferryCargo = 0, ferryEpoch = 0, ferryFactory = 0, ferryFactoryEpoch = 0, ferryPhase = 0; bool cargoValid = false; + units += ",\"productionDestination\":"; + if (WebbarAutomation::ProductionDestination(unit, destination)) { units += '['; for (int i = 0; i < 3; ++i) { if (i) units += ','; number(units, destination[i]); } units += ']'; } else units += "null"; + if (unit->team == gu->myTeam) { + units += ",\"ferry\":"; + if (WebbarAutomation::FerryDestination(unit, &ferryCargo, &ferryEpoch, destination, &ferryFactory, &ferryFactoryEpoch, &ferryPhase, &cargoValid)) { + units += "{\"cargo\":" + std::to_string(ferryCargo) + ",\"epoch\":" + std::to_string(ferryEpoch) + ",\"factory\":" + std::to_string(ferryFactory) + ",\"factoryEpoch\":" + std::to_string(ferryFactoryEpoch) + ",\"phase\":" + std::to_string(ferryPhase) + ",\"cargoValid\":" + (cargoValid ? "true" : "false") + ",\"destination\":["; + for (int i = 0; i < 3; ++i) { if (i) units += ','; number(units, destination[i]); } units += "]}"; + } else units += "null"; + } + if (def->IsTransportUnit()) { + units += ",\"groundPosition\":["; number(units, unit->pos.x); units += ','; number(units, CGround::GetHeightReal(unit->pos.x, unit->pos.z, false)); units += ','; number(units, unit->pos.z); units += ']'; + } + if (unit->team != gu->myTeam) { + const auto& queue = def->IsFactoryUnit() ? static_cast(unit->commandAI)->newUnitCommands : unit->commandAI->commandQue; + if (queue.size() > 1024 || commandCount + queue.size() > 16384) { ++dropped; break; } + units += ",\"queue\":["; + bool firstCommand = true; + for (const Command& command: queue) { + if (command.GetNumParams() > 64 || parameterCount + command.GetNumParams() > 131072) { ++dropped; break; } + if (!firstCommand) units += ','; firstCommand = false; ++commandCount; + units += "{\"id\":" + std::to_string(command.GetID()) + ",\"tag\":" + std::to_string(command.GetTag()) + ",\"options\":" + std::to_string(command.GetOpts()) + ",\"timeout\":" + std::to_string(command.GetTimeOut()) + ",\"params\":["; + for (uint32_t p = 0; p < command.GetNumParams(); ++p) { if (!std::isfinite(command.GetParam(p))) { ++dropped; break; } if (p) units += ','; number(units, command.GetParam(p)); ++parameterCount; } + units += "]}"; + } + units += ']'; + } + units += '}'; + if (dropped != 0 || units.size() + definitions.size() > 2 * 1024 * 1024 - 1024) { ++dropped; break; } + } + units += ']'; definitions += ']'; + return "{\"version\":1,\"frame\":" + std::to_string(gs->frameNum) + ",\"team\":" + std::to_string(gu->myTeam) + ",\"complete\":" + (dropped == 0 ? "true" : "false") + ",\"dropped\":" + std::to_string(dropped) + ",\"footprintScale\":" + std::to_string(SPRING_FOOTPRINT_SCALE) + ",\"units\":" + (dropped == 0 ? units : "[]") + ",\"definitions\":" + (dropped == 0 ? definitions : "[]") + '}'; +} + +static void PublishWebbarOwnedQueues() +{ + if (!webbarStateRefresh && gs->frameNum % 15 != 0 && !(unitHandler.webbarAutomation.active && gs->frameNum % 10 == 0)) return; + std::vector units, commands; + std::vector parameters; + uint32_t dropped = 0; + const auto add = [&](const CUnit* unit, uint32_t kind, const CCommandQueue& queue) { + if (units.size() / 13 >= 8192) { ++dropped; return; } + const uint32_t lifetime = WebbarHudLifetime(unit); + const size_t start = commands.size(), parameterStart = parameters.size(); + bool complete = lifetime != 0 && queue.size() <= 1024 && start / 6 + queue.size() <= 16384; + if (complete) for (const Command& command: queue) { + if (command.GetNumParams() > 64 || parameters.size() + command.GetNumParams() > 131072) { complete = false; break; } + for (uint32_t p = 0; p < command.GetNumParams(); ++p) { + if (!std::isfinite(command.GetParam(p))) { complete = false; break; } + } + if (!complete) break; + commands.insert(commands.end(), {command.GetTag(), uint32_t(command.GetID()), uint32_t(command.GetOpts()), uint32_t(command.GetTimeOut()), uint32_t(parameters.size()), command.GetNumParams()}); + for (uint32_t p = 0; p < command.GetNumParams(); ++p) parameters.push_back(command.GetParam(p)); + } + if (!complete) { commands.resize(start); parameters.resize(parameterStart); ++dropped; } + units.insert(units.end(), {uint32_t(unit->id), uint32_t(unit->unitDef->id), lifetime, kind, uint32_t(queue.size()), uint32_t(start / 6), complete ? uint32_t(queue.size()) : 0, uint32_t(complete), WebbarAutomation::Epoch(unit), WebbarAutomation::WaitLease(unit), WebbarAutomation::WaitTag(unit), WebbarAutomation::CaptureHandle(unit), uint32_t(WebbarAutomation::CaptureUnloaded(unit))}); + }; + if (!gu->spectating || webbarReplay::Enabled()) for (const CUnit* unit: unitHandler.GetActiveUnits()) { + if (unit->isDead || unit->team != gu->myTeam) continue; + const bool factory = unit->unitDef->IsFactoryUnit(); + add(unit, factory ? 1 : 0, unit->commandAI->commandQue); + if (factory) add(unit, 2, static_cast(unit->commandAI)->newUnitCommands); + } + const uint32_t header[] = {0x32515257, uint32_t(gs->frameNum), uint32_t(gu->myTeam), uint32_t(units.size()/13), uint32_t(commands.size()/6), uint32_t(parameters.size()), dropped, uint32_t(webbarStateRefresh) | (dropped == 0 ? 4u : 0u)}; + std::vector packet(sizeof(header) + 4 * (units.size() + commands.size() + parameters.size())); + uint8_t* cursor = packet.data(); + const auto append = [&](const void* data, size_t size) { if (size) std::memcpy(cursor, data, size); cursor += size; }; + append(header, sizeof(header)); append(units.data(), units.size()*4); append(commands.data(), commands.size()*4); append(parameters.data(), parameters.size()*4); + const std::string facts = WebbarTransportFacts(); + MAIN_THREAD_EM_ASM({ if (Module['webbarOwnedQueues']) Module['webbarOwnedQueues'](HEAPU8.slice($0, $0 + $1).buffer, UTF8ToString($2)); }, packet.data(), packet.size(), facts.c_str()); +} --- a/rts/Game/WebbarQueueActions.h +++ b/rts/Game/WebbarQueueActions.h @@ -9,7 +9,7 @@ return unit->unitDef->IsFactoryUnit() ? static_cast(unit->commandAI)->newUnitCommands : unit->commandAI->commandQue; } -static void WebbarRemoveQueueEnd(const CUnit* unit, bool last) +static void WebbarRemoveQueueEnd(const CUnit* unit, bool last, bool fromPlayerNetwork = false) { const auto& queue = WebbarUnitCommandQueue(unit); if (queue.empty()) return; @@ -27,19 +27,19 @@ // The widget replaces the temporary patrol FIGHT with MOVE before // rebuilding its remaining route. Snapshot before sending any orders. std::vector route(queue.begin(), queue.end()); - selectedUnitsHandler.SendCommandsToUnits({unit->id}, {Command(CMD_STOP)}, false); + selectedUnitsHandler.SendCommandsToUnits({unit->id}, {Command(CMD_STOP)}, false, fromPlayerNetwork); Command move(CMD_MOVE); for (unsigned int p = 0; p < route[0].GetNumParams(); ++p) move.PushParam(route[0].GetParam(p)); - selectedUnitsHandler.SendCommandsToUnits({unit->id}, {move}, false); + selectedUnitsHandler.SendCommandsToUnits({unit->id}, {move}, false, fromPlayerNetwork); for (size_t i = 1; i < route.size(); ++i) { route[i].SetOpts(SHIFT_KEY); - selectedUnitsHandler.SendCommandsToUnits({unit->id}, {route[i]}, false); + selectedUnitsHandler.SendCommandsToUnits({unit->id}, {route[i]}, false, fromPlayerNetwork); } return; } remove.PushParam(float(current.GetTag())); - selectedUnitsHandler.SendCommandsToUnits({unit->id}, {remove}, false); - if (queue.size() == 1) selectedUnitsHandler.SendCommandsToUnits({unit->id}, {Command(CMD_STOP)}, false); + selectedUnitsHandler.SendCommandsToUnits({unit->id}, {remove}, false, fromPlayerNetwork); + if (queue.size() == 1) selectedUnitsHandler.SendCommandsToUnits({unit->id}, {Command(CMD_STOP)}, false, fromPlayerNetwork); } static bool WebbarCommandPosition(const Command& command, float3& position) @@ -62,7 +62,7 @@ return true; } -static void WebbarInsertCommand(const CUnit* unit, const Command& command, bool nearest) +static void WebbarInsertCommand(const CUnit* unit, const Command& command, bool nearest, bool fromPlayerNetwork = false) { int index = 0; if (nearest) { @@ -86,14 +86,14 @@ // both the intermediate and final leg. Native duplicate handling stays. if (distance(previous, target) < best) { Command append(command); append.SetOpts(command.GetOpts() | SHIFT_KEY); - selectedUnitsHandler.SendCommandsToUnits({unit->id}, {append}, false); + selectedUnitsHandler.SendCommandsToUnits({unit->id}, {append}, false, fromPlayerNetwork); return; } } Command insert(CMD_INSERT, ALT_KEY); insert.PushParam(float(index)); insert.PushParam(float(command.GetID())); insert.PushParam(float(command.GetOpts())); for (unsigned int p = 0; p < command.GetNumParams(); ++p) insert.PushParam(command.GetParam(p)); - selectedUnitsHandler.SendCommandsToUnits({unit->id}, {insert}, false); + selectedUnitsHandler.SendCommandsToUnits({unit->id}, {insert}, false, fromPlayerNetwork); } // unit_factory_quota.lua: manual Alt orders and WAIT precede quotas; quotas --- a/rts/Game/WebbarQuotaOwnership.h +++ b/rts/Game/WebbarQuotaOwnership.h @@ -45,9 +45,11 @@ }; static WebbarQuotaOwnership& GetWebbarQuotaOwnership() { static WebbarQuotaOwnership observer; return observer; } -static void PublishWebbarQuotaOwnership() +static void PublishWebbarQuotaOwnership(bool widgetQueryRefresh = false) { - if (!webbarStateRefresh && gs->frameNum % 15 != 0) return; + // Pending weapon queries add identity only at an existing snapshot, never a + // new snapshot tick or an extra full queue/world publication. + if (!widgetQueryRefresh && !webbarStateRefresh && gs->frameNum % 15 != 0 && !(unitHandler.webbarAutomation.active && gs->frameNum % 10 == 0)) return; const auto& entries = GetWebbarQuotaOwnership().entries; std::vector packet = {0x314f5157, uint32_t(gs->frameNum), uint32_t(gu->myTeam), 0, 0, 0}; for (const CUnit* unit: unitHandler.GetActiveUnits()) { --- /dev/null +++ b/rts/Game/WebbarUiEvents.h @@ -0,0 +1,53 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +#include +#include +#include +#include +#include +#include +#include "Game/GlobalUnsynced.h" +#include "Sim/Misc/GlobalSynced.h" +#include "Sim/Misc/GlobalConstants.h" +#include "Net/WebbarReplay.h" +#include "Net/WebbarResume.h" + +// Unsynced presentation only. This storage is never read by game simulation. +namespace WebbarUiEvents { +struct Event { + uint32_t token, frame, kind, unit, lifetime, team, player, force, quiet; + std::string name; +}; +inline std::vector pending; +inline uint32_t sequence = 0, dropped = 0; +inline bool reset = true; +struct Award { int team; double score; }; +inline constexpr std::array awardNames = {"ecoKill", "fightKill", "efficiency", "eco", "sleep", "damageReceived", "goldenCow", "traitor"}; +inline std::array, 8> awards; +inline int awardsFrame = -1; +inline uint32_t awardsVersion = 0; + +inline bool Enabled() +{ + static const bool enabled = std::getenv("WEBBAR_PLAYABLE") != nullptr && std::getenv("WEBBAR_BROWSER") != nullptr; + return enabled; +} +inline bool CatchingUp() +{ + const int target = webbarResumeTarget.load(); + return (target >= 0 && gs->frameNum <= target) || (webbarReplay::Enabled() && webbarReplay::seek.load() >= gs->frameNum); +} +inline void Discard() +{ + pending.clear(); dropped = 0; reset = true; +} +inline void Emit(Event event) +{ + if (!Enabled() || gs->frameNum < 0 || (gu->spectating && event.kind != 2) || CatchingUp() || webbarReplay::Enabled()) return; + if (pending.size() >= 512) { ++dropped; return; } + if (++sequence == 0) ++sequence; + event.token = sequence; event.frame = gs->frameNum; + pending.emplace_back(std::move(event)); +} +} --- a/rts/Game/WebbarWeapons.h +++ b/rts/Game/WebbarWeapons.h @@ -2,9 +2,23 @@ #pragma once #include "Sim/Projectiles/WeaponProjectiles/WeaponProjectile.h" #include "Sim/Weapons/PlasmaRepulser.h" +#include "Sim/Features/Feature.h" +#include "Sim/Units/Unit.h" #include "Game/WebbarEffectQueue.h" #include +// Same discriminator as Spring.GetProjectileTarget, read only after the existing +// projectile admission. Do not publish its target ID or look up another object. +static uint32_t WebbarProjectileTargetKind(const CWeaponProjectile* projectile) +{ + const CWorldObject* target = projectile->GetTargetObject(); + if (target == nullptr) return uint32_t('g'); + if (dynamic_cast(target) != nullptr) return uint32_t('u'); + if (dynamic_cast(target) != nullptr) return uint32_t('f'); + if (dynamic_cast(target) != nullptr) return uint32_t('p'); + return 0; +} + // Read-only presentation. Definitions are sent once, after leaving synced code. // ProjectileCreated fires in the BASE constructor: use WeaponDef/start/target, // never derived members or virtual calls on a partially constructed projectile. @@ -20,8 +34,9 @@ float dx, dy, dz, damage, groundHeight; uint32_t impactFlags; }; - // WBW2: owner team after definition (0xffffffff without one); the shot is already visible. - struct Shot { uint32_t id, definition, team; float x,y,z,vx,vy,vz,ex,ey,ez,ttl; }; + // WPN3: existing WPN2 fields, then original Lua target kind (g/u/f/p or 0). + // The projectile is already admitted; target IDs are never exported here. + struct Shot { uint32_t id, definition, team; float x,y,z,vx,vy,vz,ex,ey,ez,ttl; uint32_t targetKind; }; // WBC1 naval CEG record (wakes, bow splashes, Lua splashes, torpedo trails). struct Ceg { uint32_t id, frame, generator, owner, flags, pad; float pos[3], dir[3], damage, radius, gfxMod, pad2; }; WebbarEffects(): CEventClient("Webbar browser effects", -100000, false) { eventHandler.AddClient(this); } @@ -113,7 +128,7 @@ if (shots.size()>=4096) {++omitted;continue;} const float3& pos=d->IsHitScanWeapon()?w->GetStartPos():p->pos; const auto& end=w->GetTargetPos(); - shots.push_back({uint32_t(p->id),definition,p->GetTeamID()>=0?uint32_t(p->GetTeamID()):0xffffffff,pos.x,pos.y,pos.z,p->speed.x,p->speed.y,p->speed.z,end.x,end.y,end.z,float(w->GetTimeToLive())}); + shots.push_back({uint32_t(p->id),definition,p->GetTeamID()>=0?uint32_t(p->GetTeamID()):0xffffffff,pos.x,pos.y,pos.z,p->speed.x,p->speed.y,p->speed.z,end.x,end.y,end.z,float(w->GetTimeToLive()),WebbarProjectileTargetKind(w)}); } for (const auto* d: pending) { const auto& v=d->visuals; @@ -126,7 +141,7 @@ },d->id,d->name.c_str(),d->type.c_str(),v.impactExpGenTag.c_str(),v.ptrailExpGenTag.c_str(),v.modelName.c_str(),values,(d->customParams.contains("beam_thickness_orig")||d->customParams.contains("plasma_size_orig"))); } pending.clear(); - static_assert(sizeof(Record)==88 && sizeof(Shot)==52); + static_assert(sizeof(Record)==88 && sizeof(Shot)==56); if (!records.empty() || dropped) { const uint32_t header[]={0x33454257,uint32_t(gs->frameNum),uint32_t(records.size()),dropped}; std::vector packet(sizeof(header)+records.size()*sizeof(Record)); @@ -134,7 +149,7 @@ MAIN_THREAD_EM_ASM({if(Module['webbarEffects'])Module['webbarEffects'](HEAPU8.slice($0,$0+$1).buffer);},packet.data(),packet.size()); records.clear();dropped=0; } - const uint32_t header[]={0x32574257,uint32_t(gs->frameNum),uint32_t(shots.size()),omitted}; + const uint32_t header[]={0x33574257,uint32_t(gs->frameNum),uint32_t(shots.size()),omitted}; std::vector packet(sizeof(header)+shots.size()*sizeof(Shot)); std::memcpy(packet.data(),header,sizeof(header));std::memcpy(packet.data()+sizeof(header),shots.data(),shots.size()*sizeof(Shot)); MAIN_THREAD_EM_ASM({if(Module['webbarWeapons'])Module['webbarWeapons'](HEAPU8.slice($0,$0+$1).buffer);},packet.data(),packet.size()); --- /dev/null +++ b/rts/Game/WebbarWidgetQueries.h @@ -0,0 +1,146 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +#include "Sim/Misc/QuadField.h" +#include "Sim/Weapons/Weapon.h" +#include "Map/MapInfo.h" +#include +#include +#include +#include +#include + +// Gesture-scoped native reads only. No Lua message, command, network packet, +// preference or synced policy is created here. Private live-team authority is +// deliberately narrower than spectator/full-view LuaUI. +namespace WebbarWidgetQueries { +constexpr uint32_t REQUEST_MAGIC = 0x31595157; // WQY1 +constexpr uint32_t RESULT_MAGIC = 0x315a5157; // WQZ1 +constexpr uint32_t MAX_ROWS = 64, MAX_FEATURES = 100000, MAX_AGE = 30; +struct Header { uint32_t magic, request, generation, kind, team, frame, count, reserved; }; +struct Row { uint32_t id, lifetime, weapon; float x, y, z; }; +static_assert(sizeof(Header) == 32 && sizeof(Row) == 24); +struct Request { Header header{}; std::array rows{}; bool pending = false; }; +static Request pending; + +static void Clear() { pending = {}; } +static bool Live() { return !gu->spectating && !webbarReplay::Enabled() && !WebbarUiEvents::CatchingUp() && teamHandler.IsValidTeam(gu->myTeam) && teamHandler.IsValidAllyTeam(gu->myAllyTeam); } +static uint32_t Word(float value) { uint32_t result; std::memcpy(&result, &value, 4); return result; } +static bool Position(float x, float z) { return std::isfinite(x) && std::isfinite(z) && std::fabs(x) <= 1048576.0f && std::fabs(z) <= 1048576.0f; } +static bool Fresh(uint32_t frame) { return gs->frameNum >= 0 && frame <= uint32_t(gs->frameNum) && uint32_t(gs->frameNum) - frame <= MAX_AGE; } +static bool WeaponIdentityNeeded() +{ + return pending.pending && pending.header.kind == 1 && Live() && pending.header.team == uint32_t(gu->myTeam) && Fresh(pending.header.frame) && (webbarStateRefresh || gs->frameNum % 3 == 0); +} +static float MapGravity() { return -mapInfo->map.gravity * GAME_SPEED * GAME_SPEED; } + +static void Reply(const Header& request, uint32_t status, uint32_t count = 0, uint32_t dropped = 0, const std::vector& data = {}) +{ + // status0=complete,1=malformed,2=authority/identity,3=stale,4=overflow. + // Feature response data begins with origin facts, then count ordered rows. + // Word11 is kind-specific: exact Lua Game.gravity f32 bits for weapons, + // exact Game.maxUnits u32 for cylinders. Failed replies leave it zero. + const uint32_t nativeConstant = status != 0 ? 0u : (request.kind == 1 ? Word(MapGravity()) : uint32_t(unitHandler.MaxUnits())); + std::vector packet{RESULT_MAGIC, request.request, request.generation, request.kind, uint32_t(gu->myTeam), request.frame, uint32_t(gs->frameNum), status, count, dropped, status == 0 ? 4u : 0u, nativeConstant}; + packet.insert(packet.end(), data.begin(), data.end()); + MAIN_THREAD_EM_ASM({ if (Module['webbarWidgetQueryResult']) Module['webbarWidgetQueryResult'](HEAPU8.slice($0, $0 + $1).buffer); }, packet.data(), packet.size() * 4); +} + +static void Poll() +{ + if (!Live()) { Clear(); return; } + if (pending.pending) return; // one batch, host keeps only bounded pending gesture requests + std::array bytes{}; + const int size = MAIN_THREAD_EM_ASM_INT({ return Module['webbarPollWidgetQueries'] ? Module['webbarPollWidgetQueries']($0, $1) : 0; }, bytes.data(), bytes.size()); + if (size <= 0 || size > int(bytes.size()) || size < int(sizeof(Header))) return; + Request request; + std::memcpy(&request.header, bytes.data(), sizeof(Header)); + const Header& header = request.header; + if (header.magic != REQUEST_MAGIC || header.request == 0 || header.request == 0xffffffffu || header.generation == 0 || header.generation == 0xffffffffu) return; + if (header.reserved != 0 || header.kind < 1 || header.kind > 2 || header.count == 0 || header.count > MAX_ROWS || (header.kind == 2 && header.count != 1) || size != int(sizeof(Header) + header.count * sizeof(Row))) { Reply(header, 1); return; } + if (header.team != uint32_t(gu->myTeam)) { Reply(header, 2); return; } + if (!Fresh(header.frame)) { Reply(header, 3); return; } + std::memcpy(request.rows.data(), bytes.data() + sizeof(Header), header.count * sizeof(Row)); + for (uint32_t i = 0; i < header.count; ++i) { + const Row& row = request.rows[i]; + if (header.kind == 1) { + if (row.id > 65535 || row.lifetime == 0 || row.lifetime == 0xffffffffu || row.weapon == 0 || row.weapon > 64 || !Position(row.x, row.z) || !std::isfinite(row.y) || std::fabs(row.y) > 1048576.0f) { Reply(header, 1); return; } + } else { + // Cylinder rows encode originID,0,0,centerX,centerZ,radius. + const float maximumRadius = std::hypot(float(mapDims.mapx * SQUARE_SIZE), float(mapDims.mapy * SQUARE_SIZE)); + if (row.id > 0x7ffffffeu || row.lifetime != 0 || row.weapon != 0 || !Position(row.x, row.y) || !std::isfinite(row.z) || row.z < 0 || row.z > maximumRadius) { Reply(header, 1); return; } + } + } + request.pending = true; pending = request; + // A paused gesture gets the existing read-only full publication path; this + // never unpauses, advances a frame, or sends a gameplay order. + if (gs->paused) webbarPausedCommandsChanged = true; +} + +static bool FeatureVisible(const CFeature* feature) +{ + // Exact LuaUtils::IsFeatureVisible for this admitted live ally-team view. + return feature != nullptr && feature->IsInLosForAllyTeam(gu->myAllyTeam); +} +static bool FeatureFacts(std::vector& words, const CFeature* feature) +{ + const float values[] = {feature->pos.x, feature->pos.y, feature->pos.z, feature->resources.metal, feature->resources.energy}; + for (float value: values) if (!std::isfinite(value)) return false; + words.push_back(uint32_t(feature->id)); + for (float value: values) words.push_back(Word(value)); + return true; +} + +static void Publish() +{ + if (!pending.pending) return; + if (!Live()) { Clear(); return; } + // Weapon hints use existing3-frame snapshots plus only an owned-identity + // refresh. Cylinder actions retain the full15-frame queue/world boundary. + // Both replies precede their same-frame snapshot; neither adds a sim tick. + if (!webbarStateRefresh && gs->frameNum % (pending.header.kind == 1 ? 3 : 15) != 0) return; + const Request request = pending; Clear(); + const Header& header = request.header; + if (header.team != uint32_t(gu->myTeam)) { Reply(header, 2); return; } + if (!Fresh(header.frame)) { Reply(header, 3); return; } + std::vector words; + if (header.kind == 1) { + if (mapInfo == nullptr || !std::isfinite(MapGravity())) { Reply(header, 1); return; } + for (uint32_t i = 0; i < header.count; ++i) { + const Row& row = request.rows[i]; + const CUnit* unit = unitHandler.GetUnit(row.id); + uint32_t status = 0, inRange = 0, highTrajectory = 0; + if (!WebbarSelectable(unit) || WebbarHudLifetime(unit) != row.lifetime) status = 2; + else if (row.weapon > unit->weapons.size() || unit->weapons[row.weapon - 1] == nullptr) status = 1; + else { + const float3 position(row.x, row.y, row.z); + // Same position-target branch and one-based weapon index as + // LuaSyncedRead::GetUnitWeaponTestRange; do not approximate distance. + inRange = unit->weapons[row.weapon - 1]->TestRange(position, SWeaponTarget(nullptr, position, true)); + highTrajectory = unit->useHighTrajectory; + } + // 36-byte row: request identity, status, true result/state, exact target. + words.insert(words.end(), {row.id, row.lifetime, row.weapon, status, inRange, highTrajectory, Word(row.x), Word(row.y), Word(row.z)}); + } + Reply(header, 0, header.count, 0, words); + return; + } + const Row& row = request.rows[0]; + const CFeature* origin = featureHandler.GetFeature(row.id); + if (!FeatureVisible(origin)) { Reply(header, 2); return; } + if (!FeatureFacts(words, origin)) { Reply(header, 1); return; } + QuadFieldQuery query; + quadField.GetFeaturesExact(query, float3(row.x, 0, row.y), row.z, false); + uint32_t count = 0, dropped = 0; + for (const CFeature* feature: *query.features) { + if (!FeatureVisible(feature)) continue; + if (count >= MAX_FEATURES) { ++dropped; continue; } + if (!FeatureFacts(words, feature)) { Reply(header, 1); return; } + ++count; + } + if (dropped != 0) { Reply(header, 4, 0, dropped); return; } + // Preserve native QuadField order and its actual feature-radius edge test. + // No renderability/reclaimable filter, sorting, or resource reconstruction. + Reply(header, 0, count, 0, words); +} +} // namespace WebbarWidgetQueries --- a/rts/Game/WebbarWorld.h +++ b/rts/Game/WebbarWorld.h @@ -28,26 +28,28 @@ std::memcpy(vision.data() + sizeof(visionHeader) + grid * grid, contacts.data(), contacts.size() * sizeof(float3)); MAIN_THREAD_EM_ASM({ if (Module['webbarVision']) Module['webbarVision'](HEAPU8.slice($0, $0 + $1).buffer); }, vision.data(), vision.size()); - struct FeatureRecord { uint32_t id, def; float metal, reclaim; float matrix[16]; }; - static_assert(sizeof(FeatureRecord) == 80); + struct FeatureRecord { uint32_t id, def; float metal, energy, reclaim; float matrix[16]; }; + static_assert(sizeof(FeatureRecord) == 84); std::vector features; + uint32_t featuresDropped = 0; static std::vector featureDefs; for (const int id: featureHandler.GetActiveFeatureIDs()) { const CFeature* feature = featureHandler.GetFeature(id); // Geovents have their own stream; undrawn features have no model. Non-reclaimable // scenery is drawn but carries reclaim = -1 (schema 1) so it is never a reclaim target. if (feature->def->geoThermal || feature->def->drawType == DRAWTYPE_NONE || (!gu->spectatingFullView && !losHandler->InLos(feature->pos, gu->myAllyTeam))) continue; + if (features.size() >= 100000) { ++featuresDropped; continue; } if (std::find(featureDefs.begin(), featureDefs.end(), feature->def->id) == featureDefs.end()) { featureDefs.push_back(feature->def->id); MAIN_THREAD_EM_ASM({ if (Module['webbarFeatureDef']) Module['webbarFeatureDef']($0, UTF8ToString($1)); }, feature->def->id, feature->def->modelName.c_str()); } const bool reclaimable = feature->def->reclaimable; - FeatureRecord record = {uint32_t(id), uint32_t(feature->def->id), reclaimable ? feature->resources.metal : 0.0f, reclaimable ? feature->reclaimLeft : -1.0f, {}}; + FeatureRecord record = {uint32_t(id), uint32_t(feature->def->id), reclaimable ? feature->resources.metal : 0.0f, reclaimable ? feature->resources.energy : 0.0f, reclaimable ? feature->reclaimLeft : -1.0f, {}}; const CMatrix44f matrix = feature->GetTransformMatrix(true); std::memcpy(record.matrix, matrix.m, sizeof(record.matrix)); features.push_back(record); } - const uint32_t featureHeader[] = {0x31464257, uint32_t(gs->frameNum), uint32_t(features.size()), 1}; + const uint32_t featureHeader[] = {0x32464257, uint32_t(gs->frameNum), uint32_t(features.size()), featuresDropped, uint32_t(gu->myTeam), uint32_t(webbarStateRefresh) | (uint32_t(gu->spectatingFullView) << 1) | (featuresDropped == 0 ? 4u : 0u)}; std::vector featurePacket(sizeof(featureHeader) + features.size() * sizeof(FeatureRecord)); std::memcpy(featurePacket.data(), featureHeader, sizeof(featureHeader)); std::memcpy(featurePacket.data() + sizeof(featureHeader), features.data(), features.size() * sizeof(FeatureRecord)); --- /dev/null +++ b/rts/Lua/WebbarLuaUI.h @@ -0,0 +1,61 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +#include +#include +#include "Game/WebbarUiEvents.h" +#include "Sim/Misc/TeamHandler.h" + +// The original unsynced BAR broadcaster already performs its recipient check. +// Expose exactly these two absent-LuaUI calls, never a general LuaUI substitute. +static bool WebbarLuaUiCall(const char* name) +{ + return WebbarUiEvents::Enabled() && (std::strcmp(name, "NotificationEvent") == 0 || std::strcmp(name, "GadgetReceiveAwards") == 0); +} + +static void CaptureWebbarLuaUiCall(lua_State* L, const char* name) +{ + using namespace WebbarUiEvents; + if (std::strcmp(name, "NotificationEvent") == 0) { + if (gu->spectating || webbarReplay::Enabled() || CatchingUp() || gs->frameNum < 60 || !lua_israwstring(L, 1)) return; + size_t length = 0; + const char* message = lua_tolstring(L, 1, &length); + if (length == 0 || length > 192) return; + std::istringstream input(std::string(message, length)); + std::string event, recipient, force, extra; + if (!(input >> event >> recipient) || event.size() > 128 || event.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/_") != std::string::npos) return; + input >> force; + if ((!force.empty() && force != "y") || (input >> extra)) return; + char* end = nullptr; + const long player = std::strtol(recipient.c_str(), &end, 10); + if (end == recipient.c_str() || *end != '\0' || player < 0 || player >= MAX_PLAYERS) return; + // Mirror snd_notifications.lua's final widget admission too. Spectators, + // playback and recovery remain silent even for the original forced calls. + if (force.empty() && player != gu->myPlayerNum) return; + Emit({0, 0, 3, 0xffffffffu, 0, 0xffffffffu, uint32_t(player), uint32_t(!force.empty()), 0, std::move(event)}); + return; + } + if (std::strcmp(name, "GadgetReceiveAwards") != 0 || !lua_istable(L, 1)) return; + const int top = lua_gettop(L); + std::array, 8> captured; + bool valid = true; + for (size_t i = 0; i < awardNames.size() && valid; ++i) { + lua_getfield(L, 1, awardNames[i]); + if (!lua_istable(L, -1)) { valid = false; break; } + const size_t count = lua_objlen(L, -1); + if (count != 3 && !(i == 6 && count == 4)) { valid = false; break; } + for (size_t j = 1; j <= count; ++j) { + lua_rawgeti(L, -1, j); + if (!lua_istable(L, -1)) { valid = false; break; } + lua_getfield(L, -1, "teamID"); lua_getfield(L, -2, "score"); + const double team = lua_tonumber(L, -2), score = lua_tonumber(L, -1); + if (!lua_isnumber(L, -2) || !lua_isnumber(L, -1) || !std::isfinite(team) || team != std::floor(team) || team < -1 || team >= teamHandler.ActiveTeams() || !std::isfinite(score)) { valid = false; break; } + captured[i].push_back({int(team), score}); + lua_pop(L, 3); + } + if (valid) lua_pop(L, 1); + } + lua_settop(L, top); + if (!valid) return; + awards = std::move(captured); awardsFrame = gs->frameNum; ++awardsVersion; +} --- /dev/null +++ b/rts/Sim/Units/WebbarAutomation.cpp @@ -0,0 +1,833 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#include "WebbarAutomation.h" +#include "WebbarAutomationProtocol.h" +#include "Unit.h" +#include "UnitDef.h" +#include "UnitDefHandler.h" +#include "UnitHandler.h" +#include "CommandAI/CommandAI.h" +#include "CommandAI/Command.h" +#include "CommandAI/CommandDescription.h" +#include "Game/GameSetup.h" +#include "Game/Players/Player.h" +#include "Game/Players/PlayerHandler.h" +#include "Lua/LuaHandle.h" +#include "Map/ReadMap.h" +#include "Sim/Misc/GlobalSynced.h" +#include "Sim/Misc/TeamHandler.h" +#include "Sim/Misc/LosHandler.h" +#include "Sim/Misc/QuadField.h" +#include "Sim/Weapons/WeaponDef.h" +#include "System/Sync/SyncChecker.h" +#include "System/creg/STL_Map.h" +#include +#include +#include +#include +#include +#include +#include + +CR_BIND(WebbarCreationRow, ) +CR_REG_METADATA(WebbarCreationRow, (CR_MEMBER(definition), CR_MEMBER(events), CR_MEMBER(action))) +CR_BIND(WebbarCreationPolicy, ) +CR_REG_METADATA(WebbarCreationPolicy, (CR_MEMBER(revision), CR_MEMBER(player), CR_MEMBER(rows))) +CR_BIND(WebbarAutomationUnit, ) +CR_REG_METADATA(WebbarAutomationUnit, (CR_MEMBER(team), CR_MEMBER(epoch), CR_MEMBER(birthPending), CR_MEMBER(idleGuardSequence), CR_MEMBER(idleGuardHandle), CR_MEMBER(idleGuardTarget), CR_MEMBER(idleGuardTargetEpoch), CR_MEMBER(idleGuardRevision), CR_MEMBER(productionSequence), CR_MEMBER(productionHandle), CR_MEMBER(productionFactory), CR_MEMBER(productionFactoryEpoch), CR_MEMBER(productionRevision), CR_MEMBER(productionHasDestination), CR_MEMBER(productionX), CR_MEMBER(productionY), CR_MEMBER(productionZ), CR_MEMBER(productionMoveTags), CR_MEMBER(ferryFactory), CR_MEMBER(ferryFactoryEpoch), CR_MEMBER(ferryPhase), CR_MEMBER(ferryCargo), CR_MEMBER(ferryCargoEpoch), CR_MEMBER(ferryRevision), CR_MEMBER(ferryX), CR_MEMBER(ferryY), CR_MEMBER(ferryZ), CR_MEMBER(nanoSequence), CR_MEMBER(nanoIdleHandle), CR_MEMBER(nanoRemoveHandle), CR_MEMBER(nanoRemoveTag), CR_MEMBER(nanoRevision), CR_MEMBER(waitSequence), CR_MEMBER(waitLease), CR_MEMBER(waitTag), CR_MEMBER(waitPurpose), CR_MEMBER(captureSequence), CR_MEMBER(captureHandle), CR_MEMBER(manualRevision), CR_MEMBER(unloadRevision), CR_MEMBER(captureUnloaded), CR_MEMBER(unloadX), CR_MEMBER(unloadY), CR_MEMBER(unloadZ), CR_MEMBER(captured))) +CR_BIND(WebbarCapturedOrder, ) +CR_REG_METADATA(WebbarCapturedOrder, (CR_MEMBER(id), CR_MEMBER(options), CR_MEMBER(parameters))) +CR_BIND(WebbarAutomationState, ) +CR_REG_METADATA(WebbarAutomationState, (CR_MEMBER(active), CR_MEMBER(policies), CR_MEMBER(units), CR_MEMBER(nextEpoch), CR_MEMBER(capturedCommands), CR_MEMBER(capturedParameters), CR_MEMBER(productionTagCount), CR_MEMBER(bomberTargets))) +CR_BIND(WebbarBomberUnit, ) +CR_REG_METADATA(WebbarBomberUnit, (CR_MEMBER(id), CR_MEMBER(epoch))) +CR_BIND(WebbarBomberTarget, ) +CR_REG_METADATA(WebbarBomberTarget, (CR_MEMBER(id), CR_MEMBER(epoch), CR_MEMBER(x), CR_MEMBER(y), CR_MEMBER(z), CR_MEMBER(bombers))) + +namespace WebbarAutomation { +using namespace WebbarAutomationProtocol; +static std::vector reports; +static uint32_t droppedReports = 0; +static uint32_t dispatchDepth = 0; +struct DispatchScope { DispatchScope() { ++dispatchDepth; } ~DispatchScope() { --dispatchDepth; } }; +const std::vector& Reports() { return reports; } +uint32_t DroppedReports() { return droppedReports; } +void ClearReports() { reports.clear(); droppedReports = 0; } +static void ReportResult(Report report) +{ + if (reports.size() >= 512) { ++droppedReports; return; } + report.frame = uint32_t(gs->frameNum); + reports.push_back(report); +} + +static void Sync(uint32_t value) +{ +#ifdef SYNCCHECK + CSyncChecker::Sync(value); +#else + (void)value; +#endif +} + +static bool Controller(int player, int team) +{ + if (!playerHandler.IsValidPlayer(player) || !teamHandler.IsValidTeam(team)) return false; + const CPlayer* owner = playerHandler.Player(player); + return owner->active && !owner->spectator && owner->CanControlTeam(team); +} + +static bool Supported(uint32_t action) { return AllowedEvents(action) != 0; } + +static bool ExperimentalFirestate() +{ + // BAR common/springoverrides.lua: the bool is tonumber(raw) == 1, + // with default false. Match the pinned float Lua number parser. + const auto& options = gameSetup->GetModOptionsCont(); + const auto option = options.find("experimental_defend_firestate"); + if (option == options.end()) return false; + const char* text = option->second.c_str(); char* end = nullptr; + float value = float(std::strtod(text, &end)); + if (end == text) return false; + if (*end == 'x' || *end == 'X') value = float(std::strtoul(text, &end, 16)); + while (std::isspace(static_cast(*end))) ++end; + return *end == '\0' && value == 1.0f; +} + +static bool Eligible(const UnitDef* def, uint32_t action) +{ + if (def == nullptr) return false; + const auto truth = [&](const char* key) { return def->customParams.contains(key); }; + switch (action) { + case 1: { + for (const auto& weapon: def->weapons) if (weapon.def != nullptr && weapon.def->type == "AircraftBomb") return true; + return false; + } + case 2: return def->IsFactoryUnit() && !truth("airfactory"); + case 3: return truth("fighter") || truth("drone") || truth("flyingcarrier"); + case 4: + if (!def->IsFactoryUnit()) return false; + for (const auto& [slot, name]: def->buildOptions) { + const UnitDef* child = unitDefHandler->GetUnitDefByName(name); + if (child != nullptr && child->IsBuilderUnit() && child->canAssist) return true; + } + return false; + case 5: return def->IsBuilderUnit() && !def->canmove && !def->IsFactoryUnit(); + default: return false; + } +} + +static void ClearCapture(WebbarAutomationUnit& identity) +{ + auto& state = unitHandler.webbarAutomation; + state.capturedCommands -= uint32_t(identity.captured.size()); + for (const auto& order: identity.captured) state.capturedParameters -= uint32_t(order.parameters.size()); + identity.captured.clear(); identity.captureHandle = 0; identity.captureUnloaded = false; +} + +static void ClearProduction(WebbarAutomationUnit& identity) +{ + unitHandler.webbarAutomation.productionTagCount -= uint32_t(identity.productionMoveTags.size()); + identity.productionMoveTags.clear(); identity.productionHandle = 0; identity.productionHasDestination = false; +} + +static uint32_t Assign(CUnit* unit, bool birth) +{ + auto& state = unitHandler.webbarAutomation; + const auto previous = state.units.find(unit->id); + if (previous != state.units.end()) { ClearCapture(previous->second); ClearProduction(previous->second); } + auto& next = state.nextEpoch[unit->team]; + if (++next == 0 || next == 0xffffffffu) next = 1; + state.units[unit->id] = {unit->team, next, birth}; + Sync(uint32_t(unit->id)); Sync(uint32_t(unit->team)); Sync(next); Sync(uint32_t(birth)); + return next; +} + +uint32_t Epoch(const CUnit* unit) +{ + const auto& state = unitHandler.webbarAutomation; + if (!state.active || unit == nullptr) return 0; + const auto found = state.units.find(unit->id); + return found != state.units.end() && found->second.team == unit->team ? found->second.epoch : 0; +} + +// Missing or disabled descriptors fail closed. GiveCommand remains the native +// AllowCommand -> UnitCommand -> command-AI path, including original gadgets. +static bool Send(CUnit* unit, int player, int id, float value) +{ + const auto& descriptions = unit->commandAI->GetPossibleCommands(); + const auto desc = std::find_if(descriptions.begin(), descriptions.end(), [&](const auto* d) { return d->id == id && !d->disabled && !d->hidden; }); + if (desc == descriptions.end() || (*desc)->type != CMDTYPE_ICON_MODE || (*desc)->params.size() < 2 || value < 0 || value >= (*desc)->params.size() - 1) return false; + const DispatchScope dispatch; + unit->commandAI->GiveCommand(Command(id, 0, value), player, false, false); + return true; +} + +static bool BomberHoldFire(CUnit* unit, int player) +{ + if (!ExperimentalFirestate()) return Send(unit, player, CMD_FIRE_STATE, 0); + // The original handler creates this typed rules param in UnitCreated. + // USER_FIRESTATE31300 has no descriptor: AllowCommand consumes [0,0], + // writes user_firestate, and issues native FIRE_STATE0 itself. Never fall + // back to45 when that original handler is absent or rejects the request. + const auto param = unit->modParams.find("user_firestate"); + if (param == unit->modParams.end()) return false; + const float* before = std::get_if(¶m->second.value); + if (before == nullptr || !std::isfinite(*before) || *before < 0 || *before > 4) return false; + Command command(31300, 0); command.PushParam(0); command.PushParam(0); + const DispatchScope dispatch; + unit->commandAI->GiveCommand(command, player, false, false); + const auto after = unit->modParams.find("user_firestate"); + const float* value = after == unit->modParams.end() ? nullptr : std::get_if(&after->second.value); + return value != nullptr && *value == 0 && unit->fireState == 0; +} + +static bool BomberHoldPosition(CUnit* unit, int player) +{ + // BAR removes the bomber move-state descriptor, but its original widget + // still sends this supported native state command. Do not widen Send. + if (!Eligible(unit->unitDef, 1) || (!unit->unitDef->canmove && !unit->unitDef->builder)) return false; + const DispatchScope dispatch; + unit->commandAI->GiveCommand(Command(CMD_MOVE_STATE, 0, 0.0f), player, false, false); + return unit->moveState == 0; +} + +static void Apply(CUnit* unit, uint32_t event, const std::vector* only = nullptr) +{ + auto& state = unitHandler.webbarAutomation; + const auto policy = state.policies.find(unit->team); + if (unit->isDead || policy == state.policies.end() || !Controller(policy->second.player, unit->team)) return; + const int player = policy->second.player; + for (const auto& row: only != nullptr ? *only : policy->second.rows) { + if ((row.events & event) == 0 || !Eligible(unit->unitDef, row.action)) continue; + bool submitted = false; + switch (row.action) { + case 1: { const bool fire = BomberHoldFire(unit, player); const bool move = BomberHoldPosition(unit, player); submitted = fire && move; break; } + case 2: submitted = Send(unit, player, CMD_MOVE_STATE, 0); break; + case 3: submitted = Send(unit, player, CMD_IDLEMODE, 0); break; + case 4: submitted = Send(unit, player, 13921, 1); break; + case 5: { + const bool move = Send(unit, player, CMD_MOVE_STATE, 1); + const auto& descriptions = unit->commandAI->GetPossibleCommands(); + if (std::none_of(descriptions.begin(), descriptions.end(), [](const auto* d) { return d->id == CMD_FIGHT && !d->disabled && !d->hidden; })) break; + Command fight(CMD_FIGHT, META_KEY); + fight.PushParam(unit->pos.x + (unit->pos.x > mapDims.mapx * SQUARE_SIZE / 2 ? -50 : 50)); + fight.PushParam(unit->pos.y); + fight.PushParam(unit->pos.z + (unit->pos.z > mapDims.mapy * SQUARE_SIZE / 2 ? -50 : 50)); + const DispatchScope dispatch; + unit->commandAI->GiveCommand(fight, player, false, false); + submitted = move; + break; + } + } + ReportResult({2, 0, uint32_t(unit->team), policy->second.revision, uint32_t(unit->id), Epoch(unit), event, row.action, submitted ? 0u : 5u, 0, player}); + } +} + +static bool HasCommand(const CUnit* unit, int command) +{ + const auto& descriptions = unit->commandAI->GetPossibleCommands(); + return std::any_of(descriptions.begin(), descriptions.end(), [&](const auto* d) { return d->id == command && !d->disabled; }); +} + +// Match Lua's local-team visibility/type/decoy authority. Radar-only typed +// contacts retain Lua position error; no hidden definition or exact position leaks. +static const UnitDef* ReadDefinition(int ally, const CUnit* unit) +{ + if (unit == nullptr || unit->isDead) return nullptr; + if (teamHandler.AllyTeam(unit->team) == ally) return unit->unitDef; + const auto los = unit->losStatus[ally]; + if ((los & (LOS_INLOS | LOS_INRADAR)) == 0 || ((los & LOS_INLOS) == 0 && (los & (LOS_PREVLOS | LOS_CONTRADAR)) != (LOS_PREVLOS | LOS_CONTRADAR))) return nullptr; + return unit->unitDef->decoyDef != nullptr ? unit->unitDef->decoyDef : unit->unitDef; +} +static float3 ReadPosition(int ally, const CUnit* unit) +{ + return unit->pos + (teamHandler.AllyTeam(unit->team) == ally ? float3(0, 0, 0) : unit->GetLuaErrorVector(ally, false)); +} +static uint32_t Next(uint32_t& sequence) +{ + if (++sequence == 0 || sequence == 0xffffffffu) sequence = 1; + return sequence; +} +static CUnit* IdleGuardTarget(CUnit* unit, const Command& command) +{ + const int ally = teamHandler.AllyTeam(unit->team); + if (command.GetID() == CMD_REPAIR) { + if (command.GetNumParams() < 1 || !std::isfinite(command.GetParam(0))) return nullptr; + CUnit* target = unitHandler.GetUnit(uint32_t(command.GetParam(0))); + const UnitDef* def = ReadDefinition(ally, target); + return def != nullptr && def->IsFactoryUnit() ? target : nullptr; + } + if (command.GetID() >= 0 || command.GetNumParams() < 3) return nullptr; + const UnitDef* built = unitDefHandler->GetUnitDefByID(-command.GetID()); + if (built == nullptr || !built->IsFactoryUnit()) return nullptr; + for (uint32_t i = 0; i < 3; ++i) if (!std::isfinite(command.GetParam(i))) return nullptr; + const float3 center(command.GetParam(0), command.GetParam(1), command.GetParam(2)); + const float error = losHandler->GetAllyTeamRadarErrorSize(ally); + QuadFieldQuery query; + quadField.GetUnitsExact(query, float3(center.x - 50 - error, 0, center.z - 50 - error), float3(center.x + 50 + error, 0, center.z + 50 + error)); + if (query.units->size() > 8192) return nullptr; + // Native quad-field order, mid-position, radar error and exact 3D sphere + // are the original GetUnitsInSphere default-AllUnits path. Never sort it. + for (CUnit* target: *query.units) { + const UnitDef* def = ReadDefinition(ally, target); + if (def == nullptr || def->id != -command.GetID()) continue; + if ((target->midPos + target->GetLuaErrorVector(ally, false)).SqDistance(center) <= 2500) return target; + } + return nullptr; +} +void FactoryProduced(CUnit* unit, const CUnit* factory) +{ + if (Epoch(unit) == 0 || Epoch(factory) == 0) return; + auto& state = unitHandler.webbarAutomation; + auto& identity = state.units.at(unit->id); + ClearProduction(identity); + identity.productionHandle = Next(identity.productionSequence); identity.productionFactory = uint32_t(factory->id); identity.productionFactoryEpoch = Epoch(factory); identity.productionRevision = identity.manualRevision; + const auto& route = unit->commandAI->commandQue; + if (route.size() >= 2 && route.size() <= 1024 && (route[1].GetID() == CMD_MOVE || route[1].GetID() < 0) && route[1].GetNumParams() >= 3) { + const float x = route[1].GetParam(0), y = route[1].GetParam(1), z = route[1].GetParam(2); + if (std::isfinite(x) && std::isfinite(y) && std::isfinite(z)) { + std::vector tags; + for (const Command& command: route) { if (command.GetID() != CMD_MOVE || command.GetNumParams() < 3) break; if (command.GetParam(0) == x && command.GetParam(1) == y && command.GetParam(2) == z) break; tags.push_back(command.GetTag()); } + if (state.productionTagCount + tags.size() <= 16384) { identity.productionHasDestination = true; identity.productionX = x; identity.productionY = y; identity.productionZ = z; state.productionTagCount += uint32_t(tags.size()); identity.productionMoveTags = std::move(tags); } + } + } + Sync(uint32_t(unit->id)); Sync(identity.productionHandle); Sync(identity.productionFactory); Sync(identity.productionFactoryEpoch); Sync(uint32_t(identity.productionHasDestination)); + if (identity.productionHasDestination) for (float value: {identity.productionX, identity.productionY, identity.productionZ}) { uint32_t bits; std::memcpy(&bits, &value, 4); Sync(bits); } + for (uint32_t tag: identity.productionMoveTags) Sync(tag); +} +uint32_t ManualRevision(const CUnit* unit) { return Epoch(unit) == 0 ? 0 : unitHandler.webbarAutomation.units.at(unit->id).manualRevision; } +uint32_t ProductionHandle(const CUnit* unit) { return Epoch(unit) == 0 ? 0 : unitHandler.webbarAutomation.units.at(unit->id).productionHandle; } +bool ProductionDestination(const CUnit* unit, float* xyz) +{ + if (Epoch(unit) == 0) return false; + const auto& identity = unitHandler.webbarAutomation.units.at(unit->id); + if (!identity.productionHasDestination || identity.productionHandle == 0) return false; + xyz[0] = identity.productionX; xyz[1] = identity.productionY; xyz[2] = identity.productionZ; return true; +} +bool FerryDestination(const CUnit* unit, uint32_t* cargo, uint32_t* epoch, float* xyz, uint32_t* factory, uint32_t* factoryEpoch, uint32_t* phase, bool* cargoValid) +{ + if (Epoch(unit) == 0) return false; + const auto& identity = unitHandler.webbarAutomation.units.at(unit->id); + const CUnit* producer = unitHandler.GetUnit(identity.ferryFactory); + if (identity.ferryFactory == 0xffffffffu || identity.ferryRevision != identity.manualRevision || producer == nullptr || producer->isDead || Epoch(producer) != identity.ferryFactoryEpoch || teamHandler.AllyTeam(producer->team) != teamHandler.AllyTeam(unit->team)) return false; + *factory = identity.ferryFactory; *factoryEpoch = identity.ferryFactoryEpoch; *phase = identity.ferryPhase; + const CUnit* target = unitHandler.GetUnit(identity.ferryCargo); const int ally = teamHandler.AllyTeam(unit->team); + *cargoValid = target != nullptr && Epoch(target) == identity.ferryCargoEpoch && (teamHandler.AllyTeam(target->team) == ally || (target->losStatus[ally] & (LOS_INLOS | LOS_INRADAR)) != 0) && !target->isDead; + *cargo = identity.ferryCargo; *epoch = identity.ferryCargoEpoch; xyz[0] = identity.ferryX; xyz[1] = identity.ferryY; xyz[2] = identity.ferryZ; return true; +} +// The pinned ferry widget's metadata test deliberately differs from the native +// execution test (count vs footprint capacity, base mass, no terrain). Preserve it +// for choosing a candidate; native GiveCommand still owns actual load admission. +static bool FerryCanTransport(const CUnit* transport, const CUnit* cargo) +{ + const UnitDef* td = transport->unitDef; const UnitDef* cd = cargo->unitDef; + if (!td->IsTransportUnit() || cd->xsize > td->transportSize * SPRING_FOOTPRINT_SCALE || td->transportCapacity <= int(transport->transportedUnits.size()) || cd->cantBeTransported) return false; + float mass = 0; + for (const auto& item: transport->transportedUnits) mass += item.unit->unitDef->mass; + mass += cd->mass; + return mass <= td->transportMass; +} +static float FerryDistance(const float3& a, const float3& b) +{ + // Pinned Lua uses float numbers and math.diag accumulates z,y,x. Keep + // every subtraction/product/addition rounded before strict time limits. + const float x = a.x - b.x, y = a.y - b.y, z = a.z - b.z; + float squared = 0; squared += z * z; squared += y * y; squared += x * x; + return math::sqrt(squared); +} +static bool FerryTimeEligible(const float3& transport, const float3& cargo, const float3& destination, float transportSpeed, float cargoSpeed) +{ + const float pickup = FerryDistance(transport, cargo) / transportSpeed; + const float flight = FerryDistance(cargo, destination) / transportSpeed; + const float walk = FerryDistance(cargo, destination) / cargoSpeed; + const float total = pickup + flight; + return walk > 10 && pickup < 3 && total < walk; +} +void CommandDone(CUnit* unit, const Command& command) +{ + if (Epoch(unit) == 0) return; + auto& identity = unitHandler.webbarAutomation.units.at(unit->id); + identity.idleGuardHandle = 0; + const UnitDef* def = unit->unitDef; + if (def->IsBuilderUnit() && def->canAssist && def->canmove && !def->IsFactoryUnit() && unit->commandAI->commandQue.empty()) { + CUnit* target = IdleGuardTarget(unit, command); + if (target != nullptr && Epoch(target) != 0) { + identity.idleGuardHandle = Next(identity.idleGuardSequence); identity.idleGuardTarget = uint32_t(target->id); identity.idleGuardTargetEpoch = Epoch(target); identity.idleGuardRevision = identity.manualRevision; + } + } + Sync(uint32_t(unit->id)); Sync(identity.idleGuardHandle); Sync(identity.idleGuardTarget); Sync(identity.idleGuardTargetEpoch); +} +void Idle(CUnit* unit) +{ + if (Epoch(unit) == 0 || !Eligible(unit->unitDef, 5)) return; + auto& identity = unitHandler.webbarAutomation.units.at(unit->id); + identity.nanoIdleHandle = Next(identity.nanoSequence); identity.nanoRevision = identity.manualRevision; + Sync(uint32_t(unit->id)); Sync(identity.nanoIdleHandle); +} +uint32_t IdleGuardHandle(const CUnit* unit) { return Epoch(unit) == 0 ? 0 : unitHandler.webbarAutomation.units.at(unit->id).idleGuardHandle; } +uint32_t NanoIdleHandle(const CUnit* unit) { return Epoch(unit) == 0 ? 0 : unitHandler.webbarAutomation.units.at(unit->id).nanoIdleHandle; } +uint32_t NanoRemoveHandle(const CUnit* unit) { return Epoch(unit) == 0 ? 0 : unitHandler.webbarAutomation.units.at(unit->id).nanoRemoveHandle; } +uint32_t NanoRemoveTag(const CUnit* unit) { return Epoch(unit) == 0 ? 0 : unitHandler.webbarAutomation.units.at(unit->id).nanoRemoveTag; } + +static bool Bomber(const UnitDef* definition) +{ + return (definition->weapons[0].def != nullptr && definition->weapons[0].def->type == "AircraftBomb") || definition->name.find("armlance") != std::string::npos || definition->name.find("cortitan") != std::string::npos || definition->name.find("legatorpbomber") != std::string::npos; +} + +static BomberObservation Observe(int team, const WebbarBomberTarget& target) +{ + BomberObservation observation; observation.target = target; + const int ally = teamHandler.AllyTeam(team); + const CUnit* unit = unitHandler.GetUnit(target.id); + // Exact Lua ValidUnitID visibility, with the recorded identity preventing ID + // reuse from adopting a different target. No hidden coordinates are read. + observation.valid = unit != nullptr && Epoch(unit) == target.epoch && (teamHandler.AllyTeam(unit->team) == ally || (unit->losStatus[ally] & (LOS_INLOS | LOS_INRADAR)) != 0); + const int dx[] = {-75, -75, 75, 75}, dz[] = {75, -75, -75, 75}; + for (int i = 0; i < 4; ++i) observation.corners[i] = losHandler->InLos(float3(target.x + dx[i], target.y, target.z + dz[i]), ally); + return observation; +} + +std::vector ObserveBomberTargets(int team) +{ + std::vector observations; + const auto& targets = unitHandler.webbarAutomation.bomberTargets; + const auto found = targets.find(team); + if (found == targets.end()) return observations; + for (const auto& [id, target]: found->second) observations.push_back(Observe(team, target)); + return observations; +} + +static bool ConvertBomberOrder(int player, const ActionRequest& request) +{ + auto& state = unitHandler.webbarAutomation; + const auto& first = request.rows.front(); + CUnit* target = unitHandler.GetUnit(first.target); + const int ally = teamHandler.AllyTeam(request.team); + const UnitDef* targetDefinition = ReadDefinition(ally, target); + uint32_t status = 0; + std::vector selection, bombers; + if (!state.active || target == nullptr || target->isDead || Epoch(target) == 0 || targetDefinition == nullptr || (!targetDefinition->IsBuildingUnit() && targetDefinition->name.find("nanotc") == std::string::npos)) status = 4; + for (const auto& row: request.rows) { + CUnit* unit = unitHandler.GetUnit(row.unit); + if (row.target != first.target || row.argument != first.argument || unit == nullptr || unit->isDead || unit->team != int(request.team) || Epoch(unit) != row.epoch) { status = 4; break; } + selection.push_back(unit); + if (Bomber(unit->unitDef)) bombers.push_back(unit); + } + if (bombers.empty()) status = 5; + if (status == 0) { + auto& targets = state.bomberTargets[request.team]; + const auto known = targets.find(target->id); + const bool same = known != targets.end() && known->second.epoch == Epoch(target); + size_t total = same ? known->second.bombers.size() : 0; + for (const CUnit* unit: bombers) if (!same || std::none_of(known->second.bombers.begin(), known->second.bombers.end(), [&](const auto& old) { return old.id == uint32_t(unit->id) && old.epoch == Epoch(unit); })) ++total; + if ((known == targets.end() && targets.size() >= 512) || total > 64) status = 5; + else { + if (known == targets.end() || known->second.epoch != Epoch(target)) { + const float3 position = ReadPosition(ally, target); + WebbarBomberTarget monitor; monitor.id = uint32_t(target->id); monitor.epoch = Epoch(target); monitor.x = position.x; monitor.y = position.y; monitor.z = position.z; + targets[target->id] = monitor; + } + auto& monitor = targets.at(target->id); + for (const CUnit* unit: bombers) if (std::none_of(monitor.bombers.begin(), monitor.bombers.end(), [&](const auto& b) { return b.id == uint32_t(unit->id) && b.epoch == Epoch(unit); })) monitor.bombers.push_back({uint32_t(unit->id), Epoch(unit)}); + Sync(request.team); Sync(monitor.id); Sync(monitor.epoch); + for (float value: {monitor.x, monitor.y, monitor.z}) { uint32_t bits; std::memcpy(&bits, &value, sizeof(bits)); Sync(bits); } + for (const auto& unit: monitor.bombers) { Sync(unit.id); Sync(unit.epoch); } + const DispatchScope dispatch; + const float3 position = ReadPosition(ally, target); + // The pinned widget calls group GiveOrder once per selected bomber. + // Preserve the literal repeated SHIFT orders for the selected group. + std::array manualActionAccepted{}; + for (size_t repeat = 0; repeat < bombers.size(); ++repeat) for (size_t selected = 0; selected < selection.size(); ++selected) { + CUnit* unit = selection[selected]; + Command command(CMD_ATTACK, uint8_t(first.argument)); command.PushParam(position.x); command.PushParam(position.y); command.PushParam(position.z); + // WAC7 is the authenticated manual interception, including its mixed + // selection and original repeated group orders. Retire only after AllowCommand. + unit->commandAI->GiveCommand(command, player, false, false, false, &manualActionAccepted[selected]); + } + } + } + for (const auto& row: request.rows) ReportResult({3, request.request, request.team, 0, row.unit, row.epoch, 0, request.action, status, 0, player}); + return true; +} + +static bool ReceiveAction(int player, const std::vector& bytes) +{ + ActionRequest request; + if (!DecodeAction(bytes, request) || !Controller(player, request.team)) { + ReportResult({3, bytes.size() >= 12 ? Word(bytes, 8) : 0, bytes.size() >= 16 ? Word(bytes, 12) : 0xffffffffu, 0, 0xffffffffu, 0, 0, bytes.size() >= 20 ? Word(bytes, 16) : 0, request.request == 0 ? 1u : 2u, 0, player}); + return true; + } + if (request.action == 7) return ConvertBomberOrder(player, request); + auto& state = unitHandler.webbarAutomation; + for (const auto& row: request.rows) { + uint32_t status = 0, lease = 0, tag = 0; + CUnit* unit = unitHandler.GetUnit(row.unit); + const auto known = state.units.find(row.unit); + if (!state.active || unit == nullptr || unit->isDead || unit->team != int(request.team) || known == state.units.end() || known->second.team != unit->team || known->second.epoch != row.epoch) status = 4; + else { + auto& identity = known->second; + auto& queue = unit->commandAI->commandQue; + const DispatchScope dispatch; + switch (request.action) { + case 1: + // Cancel only: a stale request must never start self destruction. + if (unit->selfDCountdown == 0) break; + if (!HasCommand(unit, CMD_SELFD)) { status = 5; break; } + unit->commandAI->GiveCommand(Command(CMD_SELFD), player, false, false); + if (unit->selfDCountdown != 0) status = 6; + break; + case 2: { + // Check the live state so a queued request cannot undo a newer + // user's Fire At Will. Keep the original two front inserts. + if (unit->fireState != 0) { status = 4; break; } + if (!HasCommand(unit, CMD_STOP) || !HasCommand(unit, 34924)) { status = 5; break; } + for (int command: {CMD_STOP, 34924}) { + Command insert(CMD_INSERT, ALT_KEY); + insert.PushParam(0); insert.PushParam(float(command)); insert.PushParam(0); + unit->commandAI->GiveCommand(insert, player, false, false); + } + break; + } + case 3: + if (identity.waitLease != 0 && WaitLease(unit) == 0) { identity.waitLease = identity.waitTag = identity.waitPurpose = 0; Sync(row.unit); Sync(0); Sync(0); Sync(0); } + if (identity.waitLease != 0 || (!queue.empty() && queue.front().GetID() == CMD_WAIT) || (row.expectedTag == 0xffffffffu ? !queue.empty() : queue.empty() || queue.front().GetTag() != row.expectedTag || uint32_t(queue.front().GetID()) != row.argument)) { status = 4; break; } + if (!HasCommand(unit, CMD_WAIT)) { status = 5; break; } + unit->commandAI->GiveCommand(Command(CMD_WAIT, uint8_t(row.flags)), player, false, false); + if (queue.empty() || queue.front().GetID() != CMD_WAIT) { status = 6; break; } + if (++identity.waitSequence == 0 || identity.waitSequence == 0xffffffffu) identity.waitSequence = 1; + lease = identity.waitLease = identity.waitSequence; tag = identity.waitTag = queue.front().GetTag(); + identity.waitPurpose = row.flags == ALT_KEY ? 2u : 1u; + Sync(row.unit); Sync(lease); Sync(tag); Sync(identity.waitPurpose); + break; + case 4: + if (identity.waitPurpose != (row.flags == ALT_KEY ? 2u : 1u) || identity.waitLease != row.lease || identity.waitTag != row.expectedTag || queue.empty() || queue.front().GetID() != CMD_WAIT || queue.front().GetTag() != row.expectedTag) { status = 4; break; } + unit->commandAI->GiveCommand(Command(CMD_WAIT, uint8_t(row.flags)), player, false, false); + if (!queue.empty() && queue.front().GetID() == CMD_WAIT && queue.front().GetTag() == row.expectedTag) { status = 6; break; } + identity.waitLease = identity.waitTag = identity.waitPurpose = 0; Sync(row.unit); Sync(0); Sync(0); Sync(0); + break; + case 5: { + if (identity.captureHandle != row.lease || !identity.captureUnloaded || identity.manualRevision != identity.unloadRevision || unit->GetTransporter() != nullptr) { status = 4; break; } + std::vector orders; + for (size_t i = 0; i < identity.captured.size(); ++i) { + const auto& order = identity.captured[i]; + if (order.parameters.size() < 3) continue; + if (i == 0) { + const double dx = double(identity.unloadX) - order.parameters[0], dy = double(identity.unloadY) - order.parameters[1], dz = double(identity.unloadZ) - order.parameters[2]; + if (std::sqrt(dx * dx + dy * dy + dz * dz) > 500.0) continue; + } + orders.push_back(order); + } + // A one-shot native handle cannot restore twice or after a new + // load/manual command. Only the captured original commands enter. + ClearCapture(identity); Sync(row.unit); Sync(0); Sync(state.capturedCommands); Sync(state.capturedParameters); + for (const auto& order: orders) { + Command command(order.id, uint8_t(order.options)); + for (float value: order.parameters) command.PushParam(value); + unit->commandAI->GiveCommand(command, player, false, false); + } + break; + } + case 6: { + const CUnit* child = unitHandler.GetUnit(row.target); + const CUnit* factory = unitHandler.GetUnit(row.argument); + if (!unit->unitDef->IsBuilderUnit() || !unit->unitDef->canAssist || child == nullptr || child->isDead || factory == nullptr || factory->isDead || !factory->unitDef->IsFactoryUnit() || !teamHandler.AlliedTeams(unit->team, child->team) || !teamHandler.AlliedTeams(unit->team, factory->team) || Epoch(child) != row.targetEpoch || Epoch(factory) != row.lease || child->health >= child->maxHealth || queue.size() < 2 || queue[0].GetID() != CMD_REPAIR || queue[0].GetTag() != row.expectedTag || queue[0].GetNumParams() != 1 || queue[0].GetParam(0) != float(child->id) || queue[1].GetID() != CMD_GUARD || queue[1].GetNumParams() != 1 || queue[1].GetParam(0) != float(factory->id)) { status = 4; break; } + // Preserve the original ALT removal by command ID: every repair + // command is removed only under the source's exact front pair. + unit->commandAI->GiveCommand(Command(CMD_REMOVE, ALT_KEY, float(CMD_REPAIR)), player, false, false); + break; + } + case 9: { + CUnit* target = unitHandler.GetUnit(identity.idleGuardTarget); + if (identity.idleGuardHandle != row.lease || identity.manualRevision != identity.idleGuardRevision || !queue.empty() || target == nullptr || Epoch(target) != identity.idleGuardTargetEpoch || ReadDefinition(teamHandler.AllyTeam(unit->team), target) == nullptr) { status = 4; break; } + if (!HasCommand(unit, CMD_GUARD)) { status = 5; break; } + identity.idleGuardHandle = 0; Sync(row.unit); Sync(0); + unit->commandAI->GiveCommand(Command(CMD_GUARD, SHIFT_KEY, float(target->id)), player, false, false); + break; + } + case 10: { + const auto policy = state.policies.find(unit->team); + if (!Eligible(unit->unitDef, 5) || identity.nanoIdleHandle != row.lease || identity.manualRevision != identity.nanoRevision || !queue.empty() || policy == state.policies.end() || std::none_of(policy->second.rows.begin(), policy->second.rows.end(), [](const auto& r) { return r.action == 5; })) { status = 4; break; } + if (!HasCommand(unit, CMD_FIGHT)) { status = 5; break; } + identity.nanoIdleHandle = 0; Sync(row.unit); Sync(0); + Command command(CMD_FIGHT, META_KEY); command.PushParam(unit->pos.x + (unit->pos.x > mapDims.mapx * SQUARE_SIZE * 0.5f ? -50 : 50)); command.PushParam(unit->pos.y); command.PushParam(unit->pos.z + (unit->pos.z > mapDims.mapy * SQUARE_SIZE * 0.5f ? -50 : 50)); + unit->commandAI->GiveCommand(command, player, false, false); break; + } + case 11: { + if (!Eligible(unit->unitDef, 5) || identity.nanoRemoveHandle != row.lease || identity.nanoRemoveTag != row.expectedTag || identity.nanoRevision != identity.manualRevision || std::none_of(queue.begin(), queue.end(), [&](const Command& c) { return c.GetID() == CMD_FIGHT && c.GetTag() == row.expectedTag; })) { status = 4; break; } + identity.nanoRemoveHandle = 0; Sync(row.unit); Sync(0); + unit->commandAI->GiveCommand(Command(CMD_REMOVE, 0, float(row.expectedTag)), player, false, false); break; + } + case 12: { + CUnit* cargo = unitHandler.GetUnit(row.target); CUnit* factory = unitHandler.GetUnit(row.expectedTag); + const int ally = teamHandler.AllyTeam(unit->team); + if (identity.manualRevision != row.flags || identity.ferryPhase != 0 || identity.ferryFactory != row.expectedTag || identity.ferryFactoryEpoch != row.lease || queue.empty() || queue.front().GetID() != CMD_GUARD || queue.front().GetNumParams() != 1 || queue.front().GetParam(0) != float(row.expectedTag) || cargo == nullptr || cargo->isDead || factory == nullptr || factory->isDead || Epoch(cargo) != row.targetEpoch || Epoch(factory) != row.lease || !factory->unitDef->IsFactoryUnit() || teamHandler.AllyTeam(cargo->team) != ally || teamHandler.AllyTeam(factory->team) != ally || !FerryCanTransport(unit, cargo)) { status = 4; break; } + auto& produced = state.units.at(cargo->id); + if (produced.productionHandle != row.argument || produced.productionFactory != uint32_t(factory->id) || produced.productionFactoryEpoch != row.lease || produced.productionRevision != produced.manualRevision || !produced.productionHasDestination) { status = 4; break; } + const float3 destination(produced.productionX, produced.productionY, produced.productionZ); + if (!std::isfinite(destination.x) || !std::isfinite(destination.y) || !std::isfinite(destination.z) || !FerryTimeEligible(unit->pos, cargo->pos, destination, unit->unitDef->speed, cargo->unitDef->speed)) { status = 4; break; } + if (!HasCommand(unit, CMD_MOVE) || !HasCommand(unit, CMD_GUARD)) { status = 5; break; } + Command remove(CMD_REMOVE); + for (uint32_t tag: produced.productionMoveTags) remove.PushParam(float(tag)); + identity.ferryFactory = uint32_t(factory->id); identity.ferryFactoryEpoch = row.lease; identity.ferryPhase = 1; identity.ferryCargo = row.target; identity.ferryCargoEpoch = row.targetEpoch; identity.ferryRevision = identity.manualRevision; identity.ferryX = destination.x; identity.ferryY = destination.y; identity.ferryZ = destination.z; + ClearProduction(produced); Sync(row.target); Sync(0); Sync(state.productionTagCount); Sync(row.unit); Sync(row.target); Sync(row.targetEpoch); + Command approach(CMD_MOVE, RIGHT_MOUSE_KEY); approach.PushParam(cargo->pos.x); approach.PushParam(cargo->pos.y); approach.PushParam(cargo->pos.z); unit->commandAI->GiveCommand(approach, player, false, false); + unit->commandAI->GiveCommand(Command(CMD_GUARD, SHIFT_KEY, float(factory->id)), player, false, false); + // Original GiveOrderToUnit cannot mutate an allied AI's queue. + if (Controller(player, cargo->team) && remove.GetNumParams() != 0) cargo->commandAI->GiveCommand(remove, player, false, false); + break; + } + case 13: { + const CUnit* cargo = unitHandler.GetUnit(row.target); + float x = FloatWord(row.expectedTag), y = FloatWord(row.lease), z = FloatWord(row.argument); + if (identity.ferryCargo == row.target && identity.ferryCargoEpoch == row.targetEpoch && identity.ferryRevision == identity.manualRevision) { x = identity.ferryX; y = identity.ferryY; z = identity.ferryZ; } + if (identity.manualRevision != row.flags || !unit->unitDef->IsTransportUnit() || cargo == nullptr || cargo->isDead || Epoch(cargo) != row.targetEpoch || cargo->GetTransporter() != unit || teamHandler.AllyTeam(cargo->team) != teamHandler.AllyTeam(unit->team) || unit->transportedUnits.empty() || unit->transportedUnits.front().unit != cargo || x < 0 || x > mapDims.mapx * SQUARE_SIZE || z < 0 || z > mapDims.mapy * SQUARE_SIZE || std::abs(y) > 100000) { status = 4; break; } + // 81 is the original single-unit native operation. Some transport + // UIs list only area-unload80; descriptor80 also authorizes81. + if (!HasCommand(unit, CMD_UNLOAD_UNIT) && !HasCommand(unit, CMD_UNLOAD_UNITS)) { status = 5; break; } + if (identity.ferryFactory != 0xffffffffu) { identity.ferryPhase = 3; Sync(row.unit); Sync(3); } + Command unload(CMD_UNLOAD_UNIT, RIGHT_MOUSE_KEY); unload.PushParam(x); unload.PushParam(y); unload.PushParam(z); unit->commandAI->GiveCommand(unload, player, false, false); break; + } + case 14: case 15: { + CUnit* target = unitHandler.GetUnit(row.target); + if (!unit->unitDef->IsTransportUnit() || target == nullptr || target->isDead || Epoch(target) != row.targetEpoch || teamHandler.AllyTeam(target->team) != teamHandler.AllyTeam(unit->team) || (row.expectedTag == 0xffffffffu ? !queue.empty() : queue.empty() || queue.front().GetTag() != row.expectedTag)) { status = 4; break; } + const int command = request.action == 14 ? CMD_LOAD_UNITS : CMD_GUARD; + if (!HasCommand(unit, command)) { status = 5; break; } + if (request.action == 14 && (!unit->CanTransport(target) || target->commandAI->commandQue.empty() || target->commandAI->commandQue.front().GetID() != CMD_WAIT)) { status = 4; break; } + if (request.action == 15 && !target->unitDef->IsFactoryUnit()) { status = 4; break; } + if (request.action == 14 && identity.ferryCargo == row.target && identity.ferryCargoEpoch == row.targetEpoch) { identity.ferryPhase = 2; Sync(row.unit); Sync(2); } + if (request.action == 15 && row.argument == SHIFT_KEY && identity.ferryFactory == row.target && identity.ferryFactoryEpoch == row.targetEpoch) { + uint32_t cargo, epoch, factory, factoryEpoch, phase; float xyz[3]; bool cargoValid; + if (FerryDestination(unit, &cargo, &epoch, xyz, &factory, &factoryEpoch, &phase, &cargoValid) && (!cargoValid || (phase == 3 && unit->transportedUnits.empty()))) { identity.ferryPhase = 4; Sync(row.unit); Sync(4); } + } + bool manualActionAccepted = false; + unit->commandAI->GiveCommand(Command(command, request.action == 14 ? RIGHT_MOUSE_KEY : uint8_t(row.argument), float(target->id)), player, false, false, false, request.action == 15 && row.argument == 0 ? &manualActionAccepted : nullptr); break; + } + case 16: case 17: { + const CUnit* factory = unitHandler.GetUnit(row.target); + if (!unit->unitDef->IsTransportUnit() || factory == nullptr || factory->isDead || !factory->unitDef->IsFactoryUnit() || Epoch(factory) != row.targetEpoch || teamHandler.AllyTeam(factory->team) != teamHandler.AllyTeam(unit->team) || (row.expectedTag == 0xffffffffu ? !queue.empty() : queue.empty() || queue.front().GetTag() != row.expectedTag)) { status = 4; break; } + const bool frontGuard = !queue.empty() && queue.front().GetID() == CMD_GUARD && queue.front().GetNumParams() == 1 && queue.front().GetParam(0) == float(factory->id); + const bool settling = request.action == 16 && identity.ferryPhase == 4 && identity.ferryFactory == row.target && identity.ferryFactoryEpoch == row.targetEpoch; + if (!frontGuard && !settling) { status = 4; break; } + const CUnit* cargo = request.action == 17 && !unit->transportedUnits.empty() ? unit->transportedUnits.front().unit : nullptr; + const float x = request.action == 17 ? FloatWord(row.lease) : 0, y = request.action == 17 ? FloatWord(row.flags) : 0, z = request.action == 17 ? FloatWord(row.argument) : 0; + if (cargo != nullptr && (cargo->isDead || Epoch(cargo) == 0 || teamHandler.AllyTeam(cargo->team) != teamHandler.AllyTeam(unit->team) || x < 0 || x > mapDims.mapx * SQUARE_SIZE || z < 0 || z > mapDims.mapy * SQUARE_SIZE || std::abs(y) > 100000)) { status = 4; break; } + identity.ferryFactory = row.target; identity.ferryFactoryEpoch = row.targetEpoch; identity.ferryRevision = identity.manualRevision; identity.ferryPhase = cargo != nullptr ? 2 : 0; identity.ferryCargo = cargo != nullptr ? uint32_t(cargo->id) : 0xffffffffu; identity.ferryCargoEpoch = cargo != nullptr ? Epoch(cargo) : 0; identity.ferryX = x; identity.ferryY = y; identity.ferryZ = z; + Sync(row.unit); Sync(row.target); Sync(row.targetEpoch); Sync(identity.ferryPhase); Sync(identity.ferryCargo); Sync(identity.ferryCargoEpoch); if (cargo != nullptr) { Sync(row.lease); Sync(row.flags); Sync(row.argument); } + break; + } + case 8: { + auto teamTargets = state.bomberTargets.find(request.team); + if (teamTargets == state.bomberTargets.end()) { status = 4; break; } + auto target = teamTargets->second.find(row.target); + if (target == teamTargets->second.end() || target->second.epoch != row.targetEpoch || std::none_of(target->second.bombers.begin(), target->second.bombers.end(), [&](const auto& b) { return b.id == row.unit && b.epoch == row.epoch; })) { status = 4; break; } + const auto observation = Observe(request.team, target->second); + if (observation.valid || !std::all_of(std::begin(observation.corners), std::end(observation.corners), [](bool visible) { return visible; })) { status = 4; break; } + // Native capture of the original first100 commands; no client + // supplied command body. The source predicate is literally X-only. + std::vector>> captured; + for (const auto& bomber: target->second.bombers) { + CUnit* current = unitHandler.GetUnit(bomber.id); + if (current == nullptr || current->isDead || current->team != int(request.team) || Epoch(current) != bomber.epoch) continue; + std::vector orders; + for (const Command& command: current->commandAI->commandQue) { + if (orders.size() == 100) break; + if (command.GetNumParams() > 64) { status = 5; break; } + for (uint32_t i = 0; i < command.GetNumParams(); ++i) if (!std::isfinite(command.GetParam(i))) { status = 5; break; } + if (status != 0) break; + orders.push_back(command); + } + if (status != 0) break; + captured.emplace_back(current, std::move(orders)); + } + if (status != 0) break; + for (auto& [current, orders]: captured) { + current->commandAI->GiveCommand(Command(CMD_STOP), player, false, false); + for (const Command& prior: orders) { + if (prior.GetID() == CMD_ATTACK && prior.GetNumParams() != 0 && prior.GetParam(0) == target->second.x) continue; + Command command(prior.GetID(), SHIFT_KEY); + for (uint32_t i = 0; i < prior.GetNumParams(); ++i) command.PushParam(prior.GetParam(i)); + current->commandAI->GiveCommand(command, player, false, false); + } + } + teamTargets->second.erase(target); Sync(request.team); Sync(row.target); Sync(0); + break; + } + } + } + ReportResult({3, request.request, request.team, lease, row.unit, row.epoch, tag, request.action, status, 0, player}); + } + return true; +} + +bool Receive(int player, uint16_t script, uint8_t mode, const std::vector& bytes) +{ + if (script != LUA_HANDLE_ORDER_RULES || mode != 0) return false; + if (bytes.size() >= 4 && Word(bytes, 0) == ActionMagic) return ReceiveAction(player, bytes); + if (!Recognized(bytes)) return false; + Policy decoded; + const auto reject = [&](uint32_t status) { + ReportResult({1, bytes.size() >= 12 ? Word(bytes, 8) : 0, bytes.size() >= 16 ? Word(bytes, 12) : 0xffffffffu, bytes.size() >= 20 ? Word(bytes, 16) : 0, 0xffffffffu, 0, 0, 0, status, 0, player}); + return true; + }; + // Recognized malformed or unauthorized packets are consumed, never exposed + // to unrelated LuaRules handlers or allowed to partially replace a policy. + if (!Decode(bytes, decoded)) return reject(1); + if (!Controller(player, decoded.team)) return reject(2); + auto& state = unitHandler.webbarAutomation; + const auto old = state.policies.find(decoded.team); + if (old != state.policies.end() && decoded.revision <= old->second.revision) return reject(3); + WebbarCreationPolicy replacement; replacement.revision = decoded.revision; replacement.player = player; + for (const Row& row: decoded.rows) { + if (!Supported(row.action)) return reject(4); + replacement.rows.push_back({row.definition, row.events, row.action}); + } + std::sort(replacement.rows.begin(), replacement.rows.end(), [](const auto& a, const auto& b) { return std::tie(a.definition, a.action) < std::tie(b.definition, b.action); }); + std::vector initialize; + for (const auto& row: replacement.rows) { + if ((row.events & Initialize) == 0) continue; + if (old == state.policies.end() || std::none_of(old->second.rows.begin(), old->second.rows.end(), [&](const auto& prior) { return prior.definition == row.definition && prior.action == row.action; })) initialize.push_back(row); + } + if (!state.active) { + state.active = true; Sync(1); + std::vector units(unitHandler.GetActiveUnits()); + std::sort(units.begin(), units.end(), [](const CUnit* a, const CUnit* b) { return a->id < b->id; }); + for (CUnit* unit: units) if (!unit->isDead) Assign(unit, false); + } + state.policies[decoded.team] = std::move(replacement); + Sync(uint32_t(player)); Sync(decoded.team); Sync(decoded.revision); Sync(uint32_t(decoded.rows.size())); + for (const auto& row: state.policies.at(decoded.team).rows) { Sync(row.definition); Sync(row.events); Sync(row.action); } + ReportResult({1, decoded.request, decoded.team, decoded.revision, 0xffffffffu, 0, 0, 0, 0, 0, player}); + // Widget activation applies Initialize only to the original fighter/nano + // groups, using current native ownership. An unrelated edit never reapplies. + if (!initialize.empty()) { + std::vector units(unitHandler.GetUnitsByTeam(decoded.team)); + std::sort(units.begin(), units.end(), [](const CUnit* a, const CUnit* b) { return a->id < b->id; }); + for (CUnit* unit: units) Apply(unit, Initialize, &initialize); + } + return true; +} + +void BeginBirth(CUnit* unit) +{ + if (!unitHandler.webbarAutomation.active) return; + Assign(unit, true); +} +void FinishBirth(CUnit* unit) +{ + auto& state = unitHandler.webbarAutomation; + if (!state.active) return; + const auto found = state.units.find(unit->id); + if (found == state.units.end() || found->second.team != unit->team || !found->second.birthPending) return; + // Clear before dispatch because gadget commands can cause nested callbacks. + found->second.birthPending = false; Sync(uint32_t(unit->id)); Sync(0); + Apply(unit, Created); +} +void Transferred(CUnit* unit, int oldTeam) +{ + if (!unitHandler.webbarAutomation.active || oldTeam == unit->team) return; + Assign(unit, false); + // Original unsynced Given/Taken orders land after ChangeTeamReset. Do not + // dispatch from the earlier callback where old ownership/reset can erase them. + Apply(unit, Taken); Apply(unit, Given); +} +void Destroyed(int id) +{ + auto& state = unitHandler.webbarAutomation; + if (!state.active) return; + const auto found = state.units.find(id); + if (found == state.units.end()) return; + ClearCapture(found->second); ClearProduction(found->second); state.units.erase(found); + Sync(uint32_t(id)); Sync(0xffffffffu); +} +void CommandGiven(CUnit* unit, const Command& command, bool fromSynced, bool forceManual) +{ + auto& state = unitHandler.webbarAutomation; + if (!state.active || (!forceManual && dispatchDepth != 0) || fromSynced) return; + // State changes do not replace a queued WAIT. Preserve the lease so a + // harmless fire/move-state toggle cannot strand an automation WAIT. + if (unit->commandAI->nonQueingCommands.contains(command.GetID())) return; + const auto known = state.units.find(unit->id); + if (known == state.units.end() || known->second.team != unit->team) return; + ++known->second.manualRevision; Sync(uint32_t(unit->id)); Sync(known->second.manualRevision); + ClearProduction(known->second); + if ((command.GetOpts() & SHIFT_KEY) == 0) { known->second.ferryFactory = known->second.ferryCargo = 0xffffffffu; known->second.ferryPhase = 0; } + else if (known->second.ferryFactory != 0xffffffffu) known->second.ferryRevision = known->second.manualRevision; + known->second.idleGuardHandle = known->second.nanoIdleHandle = known->second.nanoRemoveHandle = 0; + if (Eligible(unit->unitDef, 5) && (command.GetOpts() & SHIFT_KEY) != 0 && command.GetID() != CMD_FIGHT) { + const auto& queue = unit->commandAI->commandQue; + if (!queue.empty() && queue.back().GetID() == CMD_FIGHT) { + known->second.nanoRemoveHandle = Next(known->second.nanoSequence); known->second.nanoRemoveTag = queue.back().GetTag(); known->second.nanoRevision = known->second.manualRevision; + } + } + Sync(known->second.nanoRemoveHandle); Sync(known->second.nanoRemoveTag); + if (known->second.captureUnloaded) { ClearCapture(known->second); Sync(0); Sync(state.capturedCommands); Sync(state.capturedParameters); } + if (known->second.waitLease == 0 || (command.GetOpts() & SHIFT_KEY) != 0) return; + // A manual WAIT toggle/replacement can never inherit our automation lease. + known->second.waitLease = known->second.waitTag = known->second.waitPurpose = 0; + Sync(uint32_t(unit->id)); Sync(0); Sync(0); Sync(0); +} + +uint32_t CaptureHandle(const CUnit* unit) +{ + if (Epoch(unit) == 0) return 0; + return unitHandler.webbarAutomation.units.at(unit->id).captureHandle; +} +bool CaptureUnloaded(const CUnit* unit) +{ + return CaptureHandle(unit) != 0 && unitHandler.webbarAutomation.units.at(unit->id).captureUnloaded; +} +uint32_t WaitLease(const CUnit* unit) +{ + if (Epoch(unit) == 0) return 0; + const auto& identity = unitHandler.webbarAutomation.units.at(unit->id); + if (identity.waitLease == 0) return 0; + const auto& queue = unit->commandAI->commandQue; + return std::any_of(queue.begin(), queue.end(), [&](const Command& command) { return command.GetID() == CMD_WAIT && command.GetTag() == identity.waitTag; }) ? identity.waitLease : 0; +} +uint32_t WaitTag(const CUnit* unit) +{ + return WaitLease(unit) != 0 ? unitHandler.webbarAutomation.units.at(unit->id).waitTag : 0; +} +uint32_t WaitPurpose(const CUnit* unit) +{ + return WaitLease(unit) != 0 ? unitHandler.webbarAutomation.units.at(unit->id).waitPurpose : 0; +} +void Loaded(CUnit* unit) +{ + auto& state = unitHandler.webbarAutomation; + if (!state.active || Epoch(unit) == 0 || !state.policies.contains(unit->team)) return; + auto& identity = state.units.at(unit->id); + ClearCapture(identity); Sync(uint32_t(unit->id)); Sync(0); + const auto& queue = unit->commandAI->commandQue; + if (queue.size() > 1024 || state.capturedCommands + queue.size() > 16384) return; + std::vector captured; + uint32_t parameterWords = 0; + for (const Command& command: queue) { + if (command.GetNumParams() > 64 || state.capturedParameters + parameterWords + command.GetNumParams() > 131072) return; + WebbarCapturedOrder order{command.GetID(), int(command.GetOpts()), {}}; + for (uint32_t i = 0; i < command.GetNumParams(); ++i) { + const float value = command.GetParam(i); + if (!std::isfinite(value)) return; + order.parameters.push_back(value); + } + parameterWords += uint32_t(order.parameters.size()); captured.push_back(std::move(order)); + } + if (++identity.captureSequence == 0 || identity.captureSequence == 0xffffffffu) identity.captureSequence = 1; + identity.captureHandle = identity.captureSequence; + identity.captured = std::move(captured); + state.capturedCommands += uint32_t(identity.captured.size()); state.capturedParameters += parameterWords; + Sync(identity.captureHandle); Sync(state.capturedCommands); Sync(state.capturedParameters); + for (const auto& order: identity.captured) { + Sync(uint32_t(order.id)); Sync(uint32_t(order.options)); Sync(uint32_t(order.parameters.size())); + for (float value: order.parameters) { uint32_t bits; std::memcpy(&bits, &value, sizeof(bits)); Sync(bits); } + } +} +void Unloaded(CUnit* unit) +{ + if (CaptureHandle(unit) == 0) return; + auto& identity = unitHandler.webbarAutomation.units.at(unit->id); + identity.captureUnloaded = true; identity.unloadRevision = identity.manualRevision; + identity.unloadX = unit->pos.x; identity.unloadY = unit->pos.y; identity.unloadZ = unit->pos.z; + Sync(uint32_t(unit->id)); Sync(identity.captureHandle); Sync(identity.unloadRevision); + for (float value: {identity.unloadX, identity.unloadY, identity.unloadZ}) { uint32_t bits; std::memcpy(&bits, &value, sizeof(bits)); Sync(bits); } +} +} --- /dev/null +++ b/rts/Sim/Units/WebbarAutomation.h @@ -0,0 +1,102 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +#include +#include +#include +#include "System/creg/creg_cond.h" + +class CUnit; +struct Command; + +struct WebbarCreationRow { + CR_DECLARE_STRUCT(WebbarCreationRow) + uint32_t definition = 0, events = 0, action = 0; +}; +struct WebbarCreationPolicy { + CR_DECLARE_STRUCT(WebbarCreationPolicy) + uint32_t revision = 0; + int player = -1; + std::vector rows; +}; +struct WebbarCapturedOrder { + CR_DECLARE_STRUCT(WebbarCapturedOrder) + int id = 0, options = 0; + std::vector parameters; +}; +struct WebbarAutomationUnit { + CR_DECLARE_STRUCT(WebbarAutomationUnit) + int team = -1; + uint32_t epoch = 0; + bool birthPending = false; + uint32_t idleGuardSequence = 0, idleGuardHandle = 0, idleGuardTarget = 0xffffffffu, idleGuardTargetEpoch = 0, idleGuardRevision = 0; + uint32_t productionSequence = 0, productionHandle = 0, productionFactory = 0xffffffffu, productionFactoryEpoch = 0, productionRevision = 0; + bool productionHasDestination = false; + float productionX = 0, productionY = 0, productionZ = 0; + std::vector productionMoveTags; + uint32_t ferryFactory = 0xffffffffu, ferryFactoryEpoch = 0, ferryPhase = 0; + uint32_t ferryCargo = 0xffffffffu, ferryCargoEpoch = 0, ferryRevision = 0; + float ferryX = 0, ferryY = 0, ferryZ = 0; + uint32_t nanoSequence = 0, nanoIdleHandle = 0, nanoRemoveHandle = 0, nanoRemoveTag = 0, nanoRevision = 0; + uint32_t waitSequence = 0, waitLease = 0, waitTag = 0, waitPurpose = 0; // 0 unknown, 1 DGun, 2 ferry + uint32_t captureSequence = 0, captureHandle = 0, manualRevision = 0, unloadRevision = 0; + bool captureUnloaded = false; + float unloadX = 0, unloadY = 0, unloadZ = 0; + std::vector captured; +}; +struct WebbarBomberUnit { + CR_DECLARE_STRUCT(WebbarBomberUnit) + uint32_t id = 0, epoch = 0; +}; +struct WebbarBomberTarget { + CR_DECLARE_STRUCT(WebbarBomberTarget) + uint32_t id = 0, epoch = 0; + float x = 0, y = 0, z = 0; + std::vector bombers; +}; +// Serialized with UnitHandler and reconstructed from ordinary recorded packets. +// With no WBD1 packet, active stays false and every hook returns immediately. +struct WebbarAutomationState { + CR_DECLARE_STRUCT(WebbarAutomationState) + bool active = false; + std::map policies; + std::map units; + std::map nextEpoch; + uint32_t capturedCommands = 0, capturedParameters = 0, productionTagCount = 0; + std::map> bomberTargets; +}; + +namespace WebbarAutomation { + struct Report { uint32_t kind, request, team, revision, unit, epoch, event, action, status, frame; int player; }; + // Bounded presentation-only acknowledgements; never read by simulation. + const std::vector& Reports(); + uint32_t DroppedReports(); + void ClearReports(); + bool Receive(int player, uint16_t script, uint8_t mode, const std::vector& bytes); + void BeginBirth(CUnit* unit); + void FinishBirth(CUnit* unit); + void Transferred(CUnit* unit, int oldTeam); + void Destroyed(int id); + void CommandGiven(CUnit* unit, const Command& command, bool fromSynced, bool forceManual = false); + void FactoryProduced(CUnit* unit, const CUnit* factory); + uint32_t ProductionHandle(const CUnit* unit); + uint32_t ManualRevision(const CUnit* unit); + bool ProductionDestination(const CUnit* unit, float* xyz); + bool FerryDestination(const CUnit* unit, uint32_t* cargo, uint32_t* epoch, float* xyz, uint32_t* factory, uint32_t* factoryEpoch, uint32_t* phase, bool* cargoValid); + void CommandDone(CUnit* unit, const Command& command); + void Idle(CUnit* unit); + uint32_t IdleGuardHandle(const CUnit* unit); + uint32_t NanoIdleHandle(const CUnit* unit); + uint32_t NanoRemoveHandle(const CUnit* unit); + uint32_t NanoRemoveTag(const CUnit* unit); + void Loaded(CUnit* unit); + void Unloaded(CUnit* unit); + uint32_t CaptureHandle(const CUnit* unit); + bool CaptureUnloaded(const CUnit* unit); + uint32_t WaitLease(const CUnit* unit); + uint32_t WaitTag(const CUnit* unit); + uint32_t WaitPurpose(const CUnit* unit); + struct BomberObservation { WebbarBomberTarget target; bool valid = false; bool corners[4] = {}; }; + std::vector ObserveBomberTargets(int team); + uint32_t Epoch(const CUnit* unit); +} --- /dev/null +++ b/rts/Sim/Units/WebbarAutomationProtocol.h @@ -0,0 +1,89 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +#include +#include +#include +#include +#include +#include + +// Closed replay-recorded wire format. No native pointers, padding or arbitrary +// command strings enter this decoder. Other Lua packets keep their old path. +namespace WebbarAutomationProtocol { +constexpr uint32_t Magic = 0x31444257; +constexpr uint32_t ActionMagic = 0x31434157; +constexpr uint32_t Created = 1, Given = 2, Taken = 4, Initialize = 8; +struct Row { uint32_t definition = 0, events = 0, action = 0; }; +struct Policy { uint32_t request = 0, team = 0, revision = 0; std::vector rows; }; +inline uint32_t Word(const std::vector& bytes, size_t offset) +{ + return uint32_t(bytes[offset]) | (uint32_t(bytes[offset + 1]) << 8) | (uint32_t(bytes[offset + 2]) << 16) | (uint32_t(bytes[offset + 3]) << 24); +} +inline bool Recognized(const std::vector& bytes) { return bytes.size() >= 4 && Word(bytes, 0) == Magic; } +inline uint32_t AllowedEvents(uint32_t action) +{ + switch (action) { + case 1: case 2: case 4: return Created; + case 3: return Created | Given | Taken | Initialize; + case 5: return Created | Given | Initialize; + default: return 0; + } +} +inline bool Decode(const std::vector& bytes, Policy& output) +{ + if (bytes.size() < 24 || bytes.size() > 4096 || !Recognized(bytes) || Word(bytes, 4) != 1) return false; + const uint32_t count = Word(bytes, 20); + if (count > 5 || bytes.size() != 24 + size_t(count) * 12) return false; + Policy policy{Word(bytes, 8), Word(bytes, 12), Word(bytes, 16), {}}; + if (policy.request == 0 || policy.revision == 0 || policy.team >= 255) return false; + std::set actions; + for (uint32_t i = 0; i < count; ++i) { + Row row{Word(bytes, 24 + i * 12), Word(bytes, 28 + i * 12), Word(bytes, 32 + i * 12)}; + if (row.definition != 0 || AllowedEvents(row.action) == 0 || row.events != AllowedEvents(row.action) || !actions.insert(row.action).second) return false; + policy.rows.push_back(row); + } + output = std::move(policy); + return true; +} + +inline float FloatWord(uint32_t word) { float value; std::memcpy(&value, &word, 4); return value; } +struct ActionRow { uint32_t unit, epoch, target, targetEpoch, expectedTag, lease, argument, flags; }; +struct ActionRequest { uint32_t request = 0, team = 0, action = 0; std::vector rows; }; +inline bool DecodeAction(const std::vector& bytes, ActionRequest& output) +{ + if (bytes.size() < 24 || bytes.size() > 4096 || Word(bytes, 0) != ActionMagic || Word(bytes, 4) != 1) return false; + const uint32_t count = Word(bytes, 20); + if (count == 0 || count > 64 || bytes.size() != 24 + size_t(count) * 32) return false; + ActionRequest request{Word(bytes, 8), Word(bytes, 12), Word(bytes, 16), {}}; + if (request.request == 0 || request.team >= 255 || request.action < 1 || request.action > 17) return false; + std::set units; + for (uint32_t i = 0; i < count; ++i) { + const size_t at = 24 + i * 32; + ActionRow row{Word(bytes, at), Word(bytes, at + 4), Word(bytes, at + 8), Word(bytes, at + 12), Word(bytes, at + 16), Word(bytes, at + 20), Word(bytes, at + 24), Word(bytes, at + 28)}; + if (row.unit > 65535 || row.epoch == 0 || row.epoch == 0xffffffffu || (row.flags != 0 && request.action != 12 && request.action != 13 && request.action != 17 && !((request.action == 3 || request.action == 4) && row.flags == 128)) || !units.insert(row.unit).second) return false; + if (request.action <= 5 && (row.target != 0xffffffffu || row.targetEpoch != 0)) return false; + if (request.action <= 2 && (row.expectedTag != 0xffffffffu || row.lease != 0 || row.argument != 0)) return false; + if (request.action == 3 && row.lease != 0) return false; + if (request.action == 3 && row.expectedTag == 0xffffffffu && row.argument != 0) return false; + if (request.action == 4 && (row.lease == 0 || row.expectedTag == 0xffffffffu || row.argument != 5)) return false; + if (request.action == 5 && (row.lease == 0 || row.expectedTag != 0xffffffffu || row.argument != 0)) return false; + if (request.action == 6 && (row.target > 65535 || row.targetEpoch == 0 || row.targetEpoch == 0xffffffffu || row.expectedTag == 0xffffffffu || row.lease == 0 || row.lease == 0xffffffffu || row.argument > 65535)) return false; + if (request.action == 7 && (row.target > 65535 || row.targetEpoch != 0 || row.expectedTag != 0xffffffffu || row.lease != 0 || (row.argument & ~244u) != 0)) return false; + if (request.action == 8 && (row.target > 65535 || row.targetEpoch == 0 || row.targetEpoch == 0xffffffffu || row.expectedTag != 0xffffffffu || row.lease != 0 || row.argument != 0)) return false; + if (request.action >= 9 && request.action <= 11 && (row.target != 0xffffffffu || row.targetEpoch != 0 || row.lease == 0 || row.argument != 0)) return false; + if ((request.action == 9 || request.action == 10) && row.expectedTag != 0xffffffffu) return false; + if (request.action == 11 && row.expectedTag == 0xffffffffu) return false; + if (request.action >= 12 && (row.target > 65535 || row.targetEpoch == 0 || row.targetEpoch == 0xffffffffu)) return false; + if (request.action == 12 && (row.expectedTag > 65535 || row.lease == 0 || row.lease == 0xffffffffu || row.argument == 0 || row.argument == 0xffffffffu)) return false; + if (request.action == 13 && (!std::isfinite(FloatWord(row.expectedTag)) || !std::isfinite(FloatWord(row.lease)) || !std::isfinite(FloatWord(row.argument)))) return false; + if (request.action == 14 && (row.lease != 0 || row.argument != 0)) return false; + if (request.action == 15 && (row.lease != 0 || (row.argument != 0 && row.argument != 32))) return false; + if (request.action == 16 && (row.lease != 0 || row.argument != 0)) return false; + if (request.action == 17 && (!std::isfinite(FloatWord(row.lease)) || !std::isfinite(FloatWord(row.argument)) || !std::isfinite(FloatWord(row.flags)))) return false; + request.rows.push_back(row); + } + output = std::move(request); + return true; +} +}