--- a/rts/Game/WebbarBrowser.h +++ b/rts/Game/WebbarBrowser.h @@ -102,6 +102,8 @@ #include "WebbarTerrain.h" #include "WebbarTerrainFixture.h" #include "WebbarPoses.h" +#include "WebbarQueueActions.h" +#include "WebbarQuotaOwnership.h" static void PublishWebbarPlayState() { @@ -113,7 +115,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, 33554431 /* 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, 1107296255 /* bit 30: complete queue actions, original factory modifiers and owned factory provenance | 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); @@ -208,7 +210,8 @@ { SCOPED_TIMER("Webbar::Publish::State::Modifiers"); if (webbarStateRefresh || gs->frameNum % 15 == 0) PublishWebbarUnitModifiers(); } { SCOPED_TIMER("Webbar::Publish::State::Reports"); if (webbarStateRefresh || gs->frameNum % 30 == 0) { PublishWebbarUnitExperience(); PublishWebbarRules(webbarStateRefresh); } PublishWebbarUnitDamage(); - PublishWebbarPveEvents(); } + PublishWebbarPveEvents(); + PublishWebbarQuotaOwnership(); } 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(); } @@ -310,8 +313,27 @@ const auto validPosition = [&] { return std::isfinite(order.x) && std::isfinite(order.z) && order.x >= 0 && order.z >= 0 && order.x < mapDims.mapx * SQUARE_SIZE && order.z < mapDims.mapy * SQUARE_SIZE; }; - if (ids.empty()) { + 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); + 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 if (order.kind == 1016) { + if (ids.size() != 1 || order.options != 0) status = 6; + else { + const CUnit* unit = unitHandler.GetUnit(ids[0]); + const UnitDef* def = unitDefHandler->GetUnitDefByID(order.target); + const bool option = unit->unitDef->IsFactoryUnit() && def != nullptr && std::any_of(unit->unitDef->buildOptions.begin(), unit->unitDef->buildOptions.end(), [&](const auto& item) { return item.second == def->name; }); + if (!option || !WebbarSupports(def) || unit->beingBuilt) status = 8; + else if (WebbarBuildRestriction(def->id) != nullptr) status = 9; + else if (!WebbarQuotaTrain(unit, def->id)) status = 8; + } } else if (order.kind == CMD_MOVE || order.kind == CMD_FIGHT || order.kind == CMD_PATROL) { if (!std::isfinite(order.x) || !std::isfinite(order.z) || order.x < 0 || order.z < 0 || order.x >= mapDims.mapx * SQUARE_SIZE || order.z >= mapDims.mapy * SQUARE_SIZE) { status = 3; @@ -374,7 +396,7 @@ } if (!validPosition() || !std::isfinite(order.radius) || order.radius <= 0.0f || order.radius > 2000.0f) status = 3; else { - command = Command(kind, uint8_t(order.options & SHIFT_KEY)); + command = Command(kind, uint8_t(order.options & (SHIFT_KEY | (kind == CMD_REPAIR ? ALT_KEY : 0)))); command.PushPos(float3(order.x, CGround::GetHeightReal(order.x, order.z), order.z)); command.PushParam(order.radius); } @@ -397,7 +419,7 @@ std::erase_if(ids, [&](int id) { const auto* def = unitHandler.GetUnit(id)->unitDef; return !def->IsBuilderUnit() || (order.kind == CMD_REPAIR ? !def->canRepair : !def->canReclaim); }); const CUnit* target = unitHandler.GetUnit(order.target); if (ids.empty()) status = 8; - else if (target == nullptr || target->team != gu->myTeam || target->isDead) status = 4; + else if (target == nullptr || target->isDead || (order.kind == CMD_REPAIR ? target->team != gu->myTeam : (!teamHandler.Ally(gu->myAllyTeam, target->allyteam) && !WebbarVisible(target)))) status = 4; else command.PushParam(float(order.target)); } else if (order.kind == CMD_CAPTURE) { requireCapability(CMD_CAPTURE); @@ -483,12 +505,16 @@ for (const auto& option: unit->unitDef->buildOptions) if (option.second == def->name) return false; return true; }); - if (WebbarBuildRestriction(def->id) != nullptr) { + if (WebbarBuildRestriction(def->id) != nullptr && !(order.kind == 1003 && (order.options & RIGHT_MOUSE_KEY))) { status = 9; } else if (ids.empty()) { status = 8; } else if (order.kind == 1003) { - command = Command(-def->id); // one unit per click; SHIFT means five to a native factory + // Original FactoryCAI: SHIFT x5, CTRL x20, RIGHT removes; + // ALT chooses front and preserves the current unit when repeat is on. + constexpr uint32_t factoryOptions = SHIFT_KEY | CONTROL_KEY | RIGHT_MOUSE_KEY | ALT_KEY; + if ((order.options & ~factoryOptions) != 0) status = 6; + command = Command(-def->id, uint8_t(order.options & factoryOptions)); } else if (!def->IsImmobileUnit() || !std::isfinite(order.x) || !std::isfinite(order.z) || order.x < 0 || order.z < 0 || order.x >= mapDims.mapx * SQUARE_SIZE || order.z >= mapDims.mapy * SQUARE_SIZE) { status = 3; } else { @@ -506,8 +532,11 @@ status = 5; } 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) - selectedUnitsHandler.SendCommandsToUnits(ids, {command}, false); + 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); + } } MAIN_THREAD_EM_ASM({ if (Module['webbarCommandResult']) Module['webbarCommandResult']($0, $1, $2, $3, $4, $5, $6); @@ -632,6 +661,9 @@ // NetCommands adds sync assertions after this per-frame observer returns. // Preserve the original frame checksum for later unsynced UI refreshes. 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 (webbarReplay::Enabled()) { ApplyWebbarReplayView(); const int seek = webbarReplay::seek.load(); --- /dev/null +++ b/rts/Game/WebbarQueueActions.h @@ -0,0 +1,112 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +// Pinned BAR cmd_commandq_manager.lua / cmd_commandinsert.lua. These are +// unsynced player-order adapters; only the ordinary native command path writes +// simulation state. Read complete owned queues, never the bounded WBQ export. +static const CCommandQueue& WebbarUnitCommandQueue(const CUnit* unit) +{ + return unit->unitDef->IsFactoryUnit() ? static_cast(unit->commandAI)->newUnitCommands : unit->commandAI->commandQue; +} + +static void WebbarRemoveQueueEnd(const CUnit* unit, bool last) +{ + const auto& queue = WebbarUnitCommandQueue(unit); + if (queue.empty()) return; + const size_t index = last ? queue.size() - 1 : 0; + const Command& current = queue[index]; + const int kind = current.GetID(); + Command remove(CMD_REMOVE); + if ((kind == CMD_REPAIR || kind == CMD_RECLAIM) && current.GetNumParams() > 1 && index + 1 < queue.size()) { + remove.PushParam(float(queue[index + 1].GetTag())); + } else if (kind == CMD_REPAIR && index + 1 < queue.size() && queue[index + 1].GetID() == CMD_GUARD) { + remove.PushParam(float(queue[index + 1].GetTag())); + } else if (kind == CMD_GUARD && index > 0 && queue[index - 1].GetID() == CMD_REPAIR) { + remove.PushParam(float(queue[index - 1].GetTag())); + } else if (kind == CMD_FIGHT && index == 0 && queue.size() > 1 && queue[1].GetID() == CMD_PATROL) { + // 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); + 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); + for (size_t i = 1; i < route.size(); ++i) { + route[i].SetOpts(SHIFT_KEY); + selectedUnitsHandler.SendCommandsToUnits({unit->id}, {route[i]}, false); + } + return; + } + remove.PushParam(float(current.GetTag())); + selectedUnitsHandler.SendCommandsToUnits({unit->id}, {remove}, false); + if (queue.size() == 1) selectedUnitsHandler.SendCommandsToUnits({unit->id}, {Command(CMD_STOP)}, false); +} + +static bool WebbarCommandPosition(const Command& command, float3& position) +{ + const int kind = command.GetID(); + if (!(kind < 0 || kind == CMD_MOVE || kind == CMD_REPAIR || kind == CMD_RECLAIM || kind == CMD_RESURRECT || kind == CMD_MANUALFIRE || kind == CMD_GUARD || kind == CMD_FIGHT || kind == CMD_ATTACK)) return false; + if (command.GetNumParams() >= 3) { position = command.GetPos(0); return true; } + if (command.GetNumParams() == 0) return false; + const int target = int(command.GetParam(0)); + if (target < 0) return false; + if (target < unitHandler.MaxUnits()) { + const CUnit* unit = unitHandler.GetUnit(target); + if (unit == nullptr || unit->isDead || !WebbarVisible(unit)) return false; + position = unit->pos; + } else { + const CFeature* feature = featureHandler.GetFeature(target - unitHandler.MaxUnits()); + if (feature == nullptr || feature->deleteMe || !losHandler->InLos(feature->pos, gu->myAllyTeam)) return false; + position = feature->pos; + } + return true; +} + +static void WebbarInsertCommand(const CUnit* unit, const Command& command, bool nearest) +{ + int index = 0; + if (nearest) { + float3 target; + if (!WebbarCommandPosition(command, target)) return; + const auto& queue = WebbarUnitCommandQueue(unit); + float3 previous = unit->pos; + double best = 1000000.0; + const auto distance = [](const float3& a, const float3& b) { + const double x = double(a.x) - b.x, y = double(a.y) - b.y, z = double(a.z) - b.z; + return std::sqrt(x*x + y*y + z*z); + }; + for (size_t i = 0; i < std::min(100, queue.size()); ++i) { + float3 next; + if (!WebbarCommandPosition(queue[i], next)) continue; + const double extra = distance(previous, target) + distance(target, next) - distance(previous, next); + if (extra < best) { best = extra; index = int(i); } + previous = next; + } + // Correct the pinned widget's apparent z*y typo: use 3D distance in + // 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); + 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); +} + +// unit_factory_quota.lua: manual Alt orders and WAIT precede quotas; quotas +// precede ordinary production without wasting a substantially built unit. +static bool WebbarQuotaTrain(const CUnit* unit, int definition) +{ + const auto& queue = unit->commandAI->commandQue; + for (size_t i = 0; i < std::min(2, queue.size()); ++i) + if ((queue[i].GetOpts() & ALT_KEY) || queue[i].GetID() == CMD_WAIT) return false; + const CUnit* building = static_cast(unit)->curBuild; + const bool replace = building == nullptr || (building->buildProgress < 0.075f && building->buildProgress * building->unitDef->cost.metal < 500.0f); + Command insert(CMD_INSERT, ALT_KEY | CONTROL_KEY); + insert.PushParam(replace ? 0.0f : 1.0f); insert.PushParam(float(-definition)); insert.PushParam(float(ALT_KEY | INTERNAL_ORDER)); + selectedUnitsHandler.SendCommandsToUnits({unit->id}, {insert}, false); + return true; +} --- /dev/null +++ b/rts/Game/WebbarQuotaOwnership.h @@ -0,0 +1,68 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +// Original unit_factory_quota.lua tracks actual UnitCreated(builderID), removal +// and ownership changes. Event-derived per-team tokens are reconstructed even +// while presentation is suppressed during resume. No global creation counter +// or other team's records are exposed in WQO1. +class WebbarQuotaOwnership final: public CEventClient +{ +public: + struct Entry { int team; uint32_t lifetime, producer = 0xffffffffu, producerLifetime = 0; }; + std::unordered_map entries; + std::unordered_map next; + WebbarQuotaOwnership(): CEventClient("Webbar quota ownership", -99996, false) { + eventHandler.AddClient(this); + std::vector initial; + for (const CUnit* unit: unitHandler.GetActiveUnits()) if (!unit->isDead) initial.push_back(unit); + std::sort(initial.begin(), initial.end(), [](const CUnit* a, const CUnit* b) { return a->id < b->id; }); + for (const CUnit* unit: initial) UnitCreated(unit, nullptr); + } + bool WantsEvent(const std::string& name) override { return name == "UnitCreated" || name == "UnitDestroyed" || name == "UnitGiven" || name == "UnitCommand" || name == "UnitCmdDone"; } + int GetReadAllyTeam() const override { return AllAccessTeam; } + void UnitCreated(const CUnit* unit, const CUnit* builder) override { + uint32_t& token = next[unit->team]; if (++token == 0 || token == 0xffffffffu) token = 1; + Entry entry{unit->team, token}; + if (builder != nullptr && builder->unitDef->IsFactoryUnit() && builder->team == unit->team) { + const auto producer = entries.find(builder->id); + if (producer != entries.end() && producer->second.team == unit->team) { + entry.producer = uint32_t(builder->id); entry.producerLifetime = producer->second.lifetime; + } + } + entries.insert_or_assign(unit->id, entry); + if (gs->paused) webbarPausedCommandsChanged = true; + } + void UnitDestroyed(const CUnit* unit, const CUnit*, int) override { entries.erase(unit->id); if (gs->paused) webbarPausedCommandsChanged = true; } + void UnitCommand(const CUnit* unit, const Command&, int, bool, bool) override { + if (gs->paused && unit->team == gu->myTeam) webbarPausedCommandsChanged = true; + } + void UnitCmdDone(const CUnit* unit, const Command&) override { + if (gs->paused && unit->team == gu->myTeam) webbarPausedCommandsChanged = true; + } + void UnitGiven(const CUnit* unit, int oldTeam, int newTeam) override { + if (oldTeam != newTeam) UnitCreated(unit, nullptr); + } +}; +static WebbarQuotaOwnership& GetWebbarQuotaOwnership() { static WebbarQuotaOwnership observer; return observer; } + +static void PublishWebbarQuotaOwnership() +{ + if (!webbarStateRefresh && gs->frameNum % 15 != 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()) { + if (unit->isDead || unit->team != gu->myTeam) continue; + if (packet[3] >= 8192) { ++packet[4]; continue; } + const auto known = entries.find(unit->id); + if (known == entries.end() || known->second.team != gu->myTeam) { ++packet[4]; continue; } + const auto& entry = known->second; + uint32_t producer = 0xffffffffu, lifetime = 0; + const auto parent = entries.find(int(entry.producer)); + if (parent != entries.end() && parent->second.team == gu->myTeam && parent->second.lifetime == entry.producerLifetime) { + producer = entry.producer; lifetime = entry.producerLifetime; + } + packet.insert(packet.end(), {uint32_t(unit->id), uint32_t(unit->unitDef->id), entry.lifetime, producer, lifetime}); + ++packet[3]; + } + MAIN_THREAD_EM_ASM({ if (Module['webbarQuotaOwnership']) Module['webbarQuotaOwnership'](HEAPU8.slice($0, $0 + $1).buffer); }, packet.data(), packet.size() * 4); +}